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": " fields.username =\n name : 'username'\n itemClass : LoginInputView\n ", "end": 8294, "score": 0.9965208768844604, "start": 8286, "tag": "USERNAME", "value": "username" }, { "context": " inputOptions :\n name ...
client/landing/site.landing/coffee/login/AppView.coffee
lionheart1022/koding
0
$ = require 'jquery' kd = require 'kd' utils = require './../core/utils' JView = require './../core/jview' CustomLinkView = require './../core/customlinkview' LoginInputView = require './logininputview' LoginInlineForm = require './loginform' RegisterInlineForm = require './registerform' RedeemInlineForm = require './redeemform' RecoverInlineForm = require './recoverform' ResetInlineForm = require './resetform' ResendEmailConfirmationLinkInlineForm = require './resendmailconfirmationform' { getGroupNameFromLocation } = utils module.exports = class LoginView extends JView ENTER = 13 USERNAME_VALID = no pendingSignupRequest = no constructor: (options = {}, data) -> options.cssClass = 'login-screen login' options.attributes = testpath : 'login-container' super options, data @logo = new kd.CustomHTMLView tagName : 'a' cssClass : 'koding-logo' partial : '<img src=/a/images/logos/header_logo.svg class="main-header-logo">' attributes : { href : '/' } @backToLoginLink = new CustomLinkView title : 'Sign In' href : '/Login' click : -> @goToRecoverLink = new CustomLinkView cssClass : 'forgot-link' title : 'Forgot your password?' testPath : 'landing-recover-password' href : '/Recover' @formHeader = new kd.CustomHTMLView tagName : 'h4' cssClass : 'form-header' click : (event) -> return unless $(event.target).is 'a.register' @loginForm = new LoginInlineForm cssClass : 'login-form' testPath : 'login-form' callback : @bound 'doLogin' @registerForm = new RegisterInlineForm cssClass : 'login-form' testPath : 'register-form' callback : @bound 'showExtraInformation' @redeemForm = new RedeemInlineForm cssClass : 'login-form' callback : @bound 'doRedeem' @recoverForm = new RecoverInlineForm cssClass : 'login-form' callback : @bound 'doRecover' @resendForm = new ResendEmailConfirmationLinkInlineForm cssClass : 'login-form' callback : @bound 'resendEmailConfirmationToken' @resetForm = new ResetInlineForm cssClass : 'login-form' callback : @bound 'doReset' @headBanner = new kd.CustomHTMLView domId : 'invite-recovery-notification-bar' cssClass : 'invite-recovery-notification-bar hidden' partial : '...' { oauthController } = kd.singletons @githubIcon = new kd.CustomHTMLView tagName : 'span' cssClass : 'gh icon' click : -> oauthController.redirectToOauth { provider: 'github' } @gplusIcon = new kd.CustomHTMLView tagName : 'span' cssClass : 'go icon' click : -> oauthController.redirectToOauth { provider: 'google' } @facebookIcon = new kd.CustomHTMLView tagName : 'span' cssClass : 'fb icon' click : -> oauthController.redirectToOauth { provider: 'facebook' } @twitterIcon = new kd.CustomHTMLView tagName : 'span' cssClass : 'tw icon' click : -> oauthController.redirectToOauth { provider: 'twitter' } kd.singletons.router.on 'RouteInfoHandled', => @signupModal?.destroy() @signupModal = null viewAppended: -> @setTemplate @pistachio() @template.update() query = kd.utils.parseQuery document.location.search.replace '?', '' if query.warning suffix = if query.type is 'comment' then 'post a comment' else 'like an activity' message = "You need to be logged in to #{suffix}" kd.getSingleton('mainView').createGlobalNotification title : message type : 'yellow' content : '' closeTimer : 4000 container : this pistachio: -> # {{> @loginOptions}} # {{> @registerOptions}} """ <div class='tint'></div> {{> @logo }} <div class="flex-wrapper"> <div class="form-area"> {{> @formHeader}} <div class="login-form-holder lf"> {{> @loginForm}} </div> <div class="login-form-holder rf"> {{> @registerForm}} </div> <div class="login-form-holder rdf"> {{> @redeemForm}} </div> <div class="login-form-holder rcf"> {{> @recoverForm}} </div> <div class="login-form-holder rsf"> {{> @resetForm}} </div> <div class="login-form-holder resend-confirmation-form"> {{> @resendForm}} </div> </div> <div class="inline-footer"> <div class="oauth-container"> <span class='text'></span> {{> @githubIcon}} {{> @gplusIcon}} {{> @facebookIcon}} {{> @twitterIcon}} </div> </div> <div class="login-footer">{{> @goToRecoverLink}}</div> </div> <footer> <a href="https://www.koding.com/legal/teams-user-policy" target="_blank">Acceptable user policy</a><a href="https://www.koding.com/legal/teams-copyright" target="_blank">Copyright/DMCA guidelines</a><a href="https://www.koding.com/legal/teams-terms-of-service" target="_blank">Terms of service</a><a href="https://www.koding.com/legal/teams-privacy" target="_blank">Privacy policy</a> </footer> """ doReset: ({ recoveryToken, password }) -> $.ajax url : '/Reset' data : { recoveryToken, password, _csrf : Cookies.get '_csrf' } type : 'POST' error : (xhr) => { responseText } = xhr @resetForm.button.hideLoader() new kd.NotificationView { title : responseText } success : ({ username }) => @resetForm.button.hideLoader() @resetForm.reset() @headBanner.hide() new kd.NotificationView title: 'Password changed, you can login now' kd.singletons.router.handleRoute '/Login' doRecover: ({ email }) -> $.ajax url : '/Recover' data : { email, _csrf : Cookies.get '_csrf' } type : 'POST' error : (xhr) => { responseText } = xhr new kd.NotificationView { title : responseText } @loginForm.button.hideLoader() success : => @recoverForm.reset() { entryPoint } = kd.config kd.getSingleton('router').handleRoute '/Login', { entryPoint } new kd.NotificationView title : 'Check your email' content : "We've sent you a password recovery code." duration : 4500 resendEmailConfirmationToken: (formData) -> kd.remote.api.JPasswordRecovery.recoverPassword formData['username-or-email'], (err) => @resendForm.button.hideLoader() if err new kd.NotificationView title : "An error occurred: #{err.message}" else @resendForm.reset() { entryPoint } = kd.config kd.getSingleton('router').handleRoute '/Login', { entryPoint } new kd.NotificationView title : 'Check your email' content : "We've sent you a confirmation mail." duration : 4500 showExtraInformation : (formData, form) -> form ?= @registerForm { mainView } = kd.singletons mainView.setClass 'blur' { email, password } = formData gravatar = form.gravatars[formData.email] unless gravatar form.once 'gravatarInfoFetched', => @showExtraInformation formData, form return { preferredUsername, requestHash } = gravatar givenName = gravatar.name?.givenName familyName = gravatar.name?.familyName fields = {} size = 80 src = utils.getGravatarUrl size, requestHash fields.photo = itemClass : kd.CustomHTMLView tagName : 'img' attributes : { src } fields.email = itemClass : kd.CustomHTMLView partial : email fields.username = name : 'username' itemClass : LoginInputView label : 'Pick a username' inputOptions : name : 'username' defaultValue : preferredUsername forceCase : 'lowercase' placeholder : 'username' attributes : testpath : 'register-form-username' focus : -> @parent.icon.unsetTooltip() validate : container : this rules : required : yes rangeLength : [4, 25] regExp : /^[a-z\d]+([-][a-z\d]+)*$/i usernameCheck: (input, event) => @usernameCheck input, event finalCheck : (input, event) => @usernameCheck input, event, 0 messages : required : 'Please enter a username.' regExp : 'For username only lowercase letters and numbers are allowed!' rangeLength : 'Username should be between 4 and 25 characters!' events : required : 'blur' rangeLength : 'blur' regExp : 'keyup' usernameCheck: 'keyup' finalCheck : 'blur' nextElement : suffix : itemClass : kd.CustomHTMLView cssClass : 'suffix' partial : '.koding.io' if givenName fields.firstName = defaultValue : givenName label : 'First Name' if familyName fields.lastName = defaultValue : familyName label : 'Last Name' fields.recaptcha = itemClass : kd.CustomHTMLView domId : 'recaptcha' USERNAME_VALID = no pendingSignupRequest = no @signupModal = new kd.ModalViewWithForms cssClass : 'extra-info password' # recaptcha has fixed with of 304, hence this value width : 363 height : 'auto' overlay : yes tabs : forms : extraInformation : callback : @bound 'checkBeforeRegister' fields : fields buttons : continue : title : 'LET\'S GO' style : 'solid green medium' type : 'submit' @signupModal.setOption 'userData', formData usernameView = @signupModal.modalTabs.forms.extraInformation.inputs.username usernameView.setOption 'stickyTooltip', yes unless gravatar.dummy @signupModal.addSubView new kd.CustomHTMLView partial : 'Profile info fetched from Gravatar.' cssClass : 'description' @signupModal.once 'KDObjectWillBeDestroyed', => kd.utils.killWait usernameCheckTimer usernameCheckTimer = null mainView.unsetClass 'blur' form.button.hideLoader() form.email.icon.unsetTooltip() form.password.icon.unsetTooltip() usernameView.icon.unsetTooltip() @signupModal = null @signupModal.once 'viewAppended', => if @recaptchaEnabled() utils.loadRecaptchaScript -> grecaptcha?.render 'recaptcha', { sitekey : kd.config.recaptcha.key } @signupModal.addSubView new kd.CustomHTMLView partial : """<div class='hint accept-tos'>By creating an account, you accept Koding's <a href="/Legal/Terms" target="_blank"> Terms of Service</a> and <a href="/Legal/Privacy" target="_blank">Privacy Policy.</a></div>""" kd.utils.defer -> usernameView.input.setFocus() usernameCheckTimer = null usernameCheck: (input, event, delay = 800) -> return if event?.which is 9 return if input.getValue().length < 4 kd.utils.killWait usernameCheckTimer usernameCheckTimer = null input.setValidationResult 'usernameCheck', null username = input.getValue() return unless input.valid usernameCheckTimer = kd.utils.wait delay, => return unless @signupModal? utils.usernameCheck username, success : => usernameCheckTimer = null return unless @signupModal? input.setValidationResult 'usernameCheck', null USERNAME_VALID = yes @checkBeforeRegister() if pendingSignupRequest error : ({ responseJSON }) => usernameCheckTimer = null pendingSignupRequest = no return unless @signupModal? unless responseJSON return new kd.NotificationView title: 'Something went wrong' { forbidden, kodingUser } = responseJSON USERNAME_VALID = no message = switch when forbidden "Sorry, \"#{username}\" is forbidden to use!" when kodingUser "Sorry, \"#{username}\" is already taken!" else "Sorry, there is a problem with \"#{username}\"!" input.setValidationResult 'usernameCheck', message changeButtonState: (button, state) -> if state button.setClass 'green' button.unsetClass 'red' button.enable() else button.setClass 'red' button.unsetClass 'green' button.disable() recaptchaEnabled: -> return kd.config.recaptcha.enabled and utils.getLastUsedProvider() isnt 'github' checkBeforeRegister: -> return unless @signupModal? { username, firstName, lastName } = @signupModal.modalTabs.forms.extraInformation.inputs if @recaptchaEnabled and grecaptcha?.getResponse() is '' return new kd.NotificationView { title : "Please tell us that you're not a robot!" } pendingSignupRequest = no if USERNAME_VALID and username.input.valid formData = @signupModal.getOption 'userData' formData.recaptcha = grecaptcha?.getResponse() formData.username = username.input.getValue() formData.passwordConfirm = formData.password formData.firstName = firstName?.getValue() formData.lastName = lastName?.getValue() @signupModal.destroy() @doRegister formData, @registerForm else if usernameCheckTimer? pendingSignupRequest = yes doRegister: (formData, form) -> formData.agree = 'on' formData._csrf = Cookies.get '_csrf' unless formData.referrer { mainController } = kd.singletons referrer = utils.getReferrer() or mainController._referrer formData.referrer = referrer if referrer form or= @registerForm form.notificationsDisabled = yes form.notification?.destroy() { username, redirectTo } = formData redirectTo ?= '' query = '' if redirectTo is 'Pricing' { planInterval, planTitle } = formData query = kd.utils.stringifyQuery { planTitle, planInterval } query = "?#{query}" $.ajax url : '/Register' data : formData type : 'POST' xhrFields : { withCredentials : yes } success : -> utils.removeLastUsedProvider() expiration = new Date Date.now() + (60 * 60 * 1000) # an hour document.cookie = "newRegister=true;expires=#{expiration.toUTCString()}" return location.replace "/#{redirectTo}#{query}" error : (xhr) => { responseText } = xhr @showError form, responseText showError: (form, message) -> form.button.hideLoader() form.notificationsDisabled = no form.emit 'SubmitFailed', message if /duplicate key error/.test message form.emit 'EmailError' else if /^Errors were encountered during validation/.test message if /email/.test message form.emit 'EmailError' else form.emit 'UsernameError' else new kd.NotificationView { title: message } doLogin: (formData) -> { mainController } = kd.singletons mainController.on 'LoginFailed', => @loginForm.button.hideLoader() @$('.flex-wrapper').removeClass 'shake' kd.utils.defer => @$('.flex-wrapper').addClass 'animate shake' mainController.on 'TwoFactorEnabled', => @loginForm.button.hideLoader() @loginForm.tfcode.show() @loginForm.tfcode.setFocus() formData.redirectTo = utils.getLoginRedirectPath('/Login') ? 'IDE' mainController.login formData doRedeem: -> new kd.NotificationView { title: 'This feature is disabled.' } hide: (callback) -> @$('.flex-wrapper').removeClass 'expanded' @emit 'LoginViewHidden' @setClass 'hidden' callback?() show: (callback) -> @unsetClass 'hidden' @emit 'LoginViewShown' callback?() setCustomDataToForm: (type, data) -> formName = "#{type}Form" @[formName].addCustomData data setCustomData: (data) -> @setCustomDataToForm 'login', data @setCustomDataToForm 'register', data getRegisterLink: (data = {}) -> queryString = kd.utils.stringifyQuery data queryString = "?#{queryString}" if queryString.length > 0 link = "/Register#{queryString}" animateToForm: (name) -> @unsetClass 'register recover login reset home resendEmail' @emit 'LoginViewAnimated', name @setClass name @$('.flex-wrapper').removeClass 'three one' @formHeader.hide() @goToRecoverLink.show() switch name when 'register' @registerForm.email.input.setFocus() @$('.login-footer').hide() when 'redeem' @$('.flex-wrapper').addClass 'one' @redeemForm.inviteCode.input.setFocus() @$('.inline-footer').hide() @$('.login-footer').hide() when 'login' @loginForm.username.input.setFocus() if @$('.inline-footer').is ':hidden' then @$('.inline-footer').show() if @$('.login-footer').is ':hidden' then @$('.login-footer').show() when 'recover' @$('.flex-wrapper').addClass 'one' @goToRecoverLink.hide() @recoverForm.usernameOrEmail.input.setFocus() @$('.inline-footer').hide() @$('.login-footer').hide() when 'resendEmail' @$('.flex-wrapper').addClass 'one' @resendForm.usernameOrEmail.input.setFocus() @$('.inline-footer').hide() @$('.login-footer').hide() when 'reset' @formHeader.show() @formHeader.updatePartial 'Set your new password below' @goToRecoverLink.hide() @$('.inline-footer').hide() @$('.login-footer').hide() getRouteWithEntryPoint: (route) -> { entryPoint } = kd.config if entryPoint and entryPoint.slug isnt kd.defaultSlug return "/#{entryPoint.slug}/#{route}" else return "/#{route}" showError = (err) -> if err.code and err.code is 403 { name, nickname } = err.data kd.getSingleton('appManager').tell 'Account', 'displayConfirmEmailModal', name, nickname else if err.message.length > 50 new kd.ModalView title : 'Something is wrong!' width : 500 overlay : yes cssClass : 'new-kdmodal' content : "<div class='modalformline'>" + err.message + '</div>' else new kd.NotificationView title : err.message duration: 1000
86941
$ = require 'jquery' kd = require 'kd' utils = require './../core/utils' JView = require './../core/jview' CustomLinkView = require './../core/customlinkview' LoginInputView = require './logininputview' LoginInlineForm = require './loginform' RegisterInlineForm = require './registerform' RedeemInlineForm = require './redeemform' RecoverInlineForm = require './recoverform' ResetInlineForm = require './resetform' ResendEmailConfirmationLinkInlineForm = require './resendmailconfirmationform' { getGroupNameFromLocation } = utils module.exports = class LoginView extends JView ENTER = 13 USERNAME_VALID = no pendingSignupRequest = no constructor: (options = {}, data) -> options.cssClass = 'login-screen login' options.attributes = testpath : 'login-container' super options, data @logo = new kd.CustomHTMLView tagName : 'a' cssClass : 'koding-logo' partial : '<img src=/a/images/logos/header_logo.svg class="main-header-logo">' attributes : { href : '/' } @backToLoginLink = new CustomLinkView title : 'Sign In' href : '/Login' click : -> @goToRecoverLink = new CustomLinkView cssClass : 'forgot-link' title : 'Forgot your password?' testPath : 'landing-recover-password' href : '/Recover' @formHeader = new kd.CustomHTMLView tagName : 'h4' cssClass : 'form-header' click : (event) -> return unless $(event.target).is 'a.register' @loginForm = new LoginInlineForm cssClass : 'login-form' testPath : 'login-form' callback : @bound 'doLogin' @registerForm = new RegisterInlineForm cssClass : 'login-form' testPath : 'register-form' callback : @bound 'showExtraInformation' @redeemForm = new RedeemInlineForm cssClass : 'login-form' callback : @bound 'doRedeem' @recoverForm = new RecoverInlineForm cssClass : 'login-form' callback : @bound 'doRecover' @resendForm = new ResendEmailConfirmationLinkInlineForm cssClass : 'login-form' callback : @bound 'resendEmailConfirmationToken' @resetForm = new ResetInlineForm cssClass : 'login-form' callback : @bound 'doReset' @headBanner = new kd.CustomHTMLView domId : 'invite-recovery-notification-bar' cssClass : 'invite-recovery-notification-bar hidden' partial : '...' { oauthController } = kd.singletons @githubIcon = new kd.CustomHTMLView tagName : 'span' cssClass : 'gh icon' click : -> oauthController.redirectToOauth { provider: 'github' } @gplusIcon = new kd.CustomHTMLView tagName : 'span' cssClass : 'go icon' click : -> oauthController.redirectToOauth { provider: 'google' } @facebookIcon = new kd.CustomHTMLView tagName : 'span' cssClass : 'fb icon' click : -> oauthController.redirectToOauth { provider: 'facebook' } @twitterIcon = new kd.CustomHTMLView tagName : 'span' cssClass : 'tw icon' click : -> oauthController.redirectToOauth { provider: 'twitter' } kd.singletons.router.on 'RouteInfoHandled', => @signupModal?.destroy() @signupModal = null viewAppended: -> @setTemplate @pistachio() @template.update() query = kd.utils.parseQuery document.location.search.replace '?', '' if query.warning suffix = if query.type is 'comment' then 'post a comment' else 'like an activity' message = "You need to be logged in to #{suffix}" kd.getSingleton('mainView').createGlobalNotification title : message type : 'yellow' content : '' closeTimer : 4000 container : this pistachio: -> # {{> @loginOptions}} # {{> @registerOptions}} """ <div class='tint'></div> {{> @logo }} <div class="flex-wrapper"> <div class="form-area"> {{> @formHeader}} <div class="login-form-holder lf"> {{> @loginForm}} </div> <div class="login-form-holder rf"> {{> @registerForm}} </div> <div class="login-form-holder rdf"> {{> @redeemForm}} </div> <div class="login-form-holder rcf"> {{> @recoverForm}} </div> <div class="login-form-holder rsf"> {{> @resetForm}} </div> <div class="login-form-holder resend-confirmation-form"> {{> @resendForm}} </div> </div> <div class="inline-footer"> <div class="oauth-container"> <span class='text'></span> {{> @githubIcon}} {{> @gplusIcon}} {{> @facebookIcon}} {{> @twitterIcon}} </div> </div> <div class="login-footer">{{> @goToRecoverLink}}</div> </div> <footer> <a href="https://www.koding.com/legal/teams-user-policy" target="_blank">Acceptable user policy</a><a href="https://www.koding.com/legal/teams-copyright" target="_blank">Copyright/DMCA guidelines</a><a href="https://www.koding.com/legal/teams-terms-of-service" target="_blank">Terms of service</a><a href="https://www.koding.com/legal/teams-privacy" target="_blank">Privacy policy</a> </footer> """ doReset: ({ recoveryToken, password }) -> $.ajax url : '/Reset' data : { recoveryToken, password, _csrf : Cookies.get '_csrf' } type : 'POST' error : (xhr) => { responseText } = xhr @resetForm.button.hideLoader() new kd.NotificationView { title : responseText } success : ({ username }) => @resetForm.button.hideLoader() @resetForm.reset() @headBanner.hide() new kd.NotificationView title: 'Password changed, you can login now' kd.singletons.router.handleRoute '/Login' doRecover: ({ email }) -> $.ajax url : '/Recover' data : { email, _csrf : Cookies.get '_csrf' } type : 'POST' error : (xhr) => { responseText } = xhr new kd.NotificationView { title : responseText } @loginForm.button.hideLoader() success : => @recoverForm.reset() { entryPoint } = kd.config kd.getSingleton('router').handleRoute '/Login', { entryPoint } new kd.NotificationView title : 'Check your email' content : "We've sent you a password recovery code." duration : 4500 resendEmailConfirmationToken: (formData) -> kd.remote.api.JPasswordRecovery.recoverPassword formData['username-or-email'], (err) => @resendForm.button.hideLoader() if err new kd.NotificationView title : "An error occurred: #{err.message}" else @resendForm.reset() { entryPoint } = kd.config kd.getSingleton('router').handleRoute '/Login', { entryPoint } new kd.NotificationView title : 'Check your email' content : "We've sent you a confirmation mail." duration : 4500 showExtraInformation : (formData, form) -> form ?= @registerForm { mainView } = kd.singletons mainView.setClass 'blur' { email, password } = formData gravatar = form.gravatars[formData.email] unless gravatar form.once 'gravatarInfoFetched', => @showExtraInformation formData, form return { preferredUsername, requestHash } = gravatar givenName = gravatar.name?.givenName familyName = gravatar.name?.familyName fields = {} size = 80 src = utils.getGravatarUrl size, requestHash fields.photo = itemClass : kd.CustomHTMLView tagName : 'img' attributes : { src } fields.email = itemClass : kd.CustomHTMLView partial : email fields.username = name : 'username' itemClass : LoginInputView label : 'Pick a username' inputOptions : name : 'username' defaultValue : preferredUsername forceCase : 'lowercase' placeholder : 'username' attributes : testpath : 'register-form-username' focus : -> @parent.icon.unsetTooltip() validate : container : this rules : required : yes rangeLength : [4, 25] regExp : /^[a-z\d]+([-][a-z\d]+)*$/i usernameCheck: (input, event) => @usernameCheck input, event finalCheck : (input, event) => @usernameCheck input, event, 0 messages : required : 'Please enter a username.' regExp : 'For username only lowercase letters and numbers are allowed!' rangeLength : 'Username should be between 4 and 25 characters!' events : required : 'blur' rangeLength : 'blur' regExp : 'keyup' usernameCheck: 'keyup' finalCheck : 'blur' nextElement : suffix : itemClass : kd.CustomHTMLView cssClass : 'suffix' partial : '.koding.io' if givenName fields.firstName = defaultValue : givenName label : 'First Name' if familyName fields.lastName = defaultValue : familyName label : 'Last Name' fields.recaptcha = itemClass : kd.CustomHTMLView domId : 'recaptcha' USERNAME_VALID = no pendingSignupRequest = no @signupModal = new kd.ModalViewWithForms cssClass : 'extra-info password' # recaptcha has fixed with of 304, hence this value width : 363 height : 'auto' overlay : yes tabs : forms : extraInformation : callback : @bound 'checkBeforeRegister' fields : fields buttons : continue : title : 'LET\'S GO' style : 'solid green medium' type : 'submit' @signupModal.setOption 'userData', formData usernameView = @signupModal.modalTabs.forms.extraInformation.inputs.username usernameView.setOption 'stickyTooltip', yes unless gravatar.dummy @signupModal.addSubView new kd.CustomHTMLView partial : 'Profile info fetched from Gravatar.' cssClass : 'description' @signupModal.once 'KDObjectWillBeDestroyed', => kd.utils.killWait usernameCheckTimer usernameCheckTimer = null mainView.unsetClass 'blur' form.button.hideLoader() form.email.icon.unsetTooltip() form.password.icon.unsetTooltip() usernameView.icon.unsetTooltip() @signupModal = null @signupModal.once 'viewAppended', => if @recaptchaEnabled() utils.loadRecaptchaScript -> grecaptcha?.render 'recaptcha', { sitekey : kd.config.recaptcha.key } @signupModal.addSubView new kd.CustomHTMLView partial : """<div class='hint accept-tos'>By creating an account, you accept Koding's <a href="/Legal/Terms" target="_blank"> Terms of Service</a> and <a href="/Legal/Privacy" target="_blank">Privacy Policy.</a></div>""" kd.utils.defer -> usernameView.input.setFocus() usernameCheckTimer = null usernameCheck: (input, event, delay = 800) -> return if event?.which is 9 return if input.getValue().length < 4 kd.utils.killWait usernameCheckTimer usernameCheckTimer = null input.setValidationResult 'usernameCheck', null username = input.getValue() return unless input.valid usernameCheckTimer = kd.utils.wait delay, => return unless @signupModal? utils.usernameCheck username, success : => usernameCheckTimer = null return unless @signupModal? input.setValidationResult 'usernameCheck', null USERNAME_VALID = yes @checkBeforeRegister() if pendingSignupRequest error : ({ responseJSON }) => usernameCheckTimer = null pendingSignupRequest = no return unless @signupModal? unless responseJSON return new kd.NotificationView title: 'Something went wrong' { forbidden, kodingUser } = responseJSON USERNAME_VALID = no message = switch when forbidden "Sorry, \"#{username}\" is forbidden to use!" when kodingUser "Sorry, \"#{username}\" is already taken!" else "Sorry, there is a problem with \"#{username}\"!" input.setValidationResult 'usernameCheck', message changeButtonState: (button, state) -> if state button.setClass 'green' button.unsetClass 'red' button.enable() else button.setClass 'red' button.unsetClass 'green' button.disable() recaptchaEnabled: -> return kd.config.recaptcha.enabled and utils.getLastUsedProvider() isnt 'github' checkBeforeRegister: -> return unless @signupModal? { username, firstName, lastName } = @signupModal.modalTabs.forms.extraInformation.inputs if @recaptchaEnabled and grecaptcha?.getResponse() is '' return new kd.NotificationView { title : "Please tell us that you're not a robot!" } pendingSignupRequest = no if USERNAME_VALID and username.input.valid formData = @signupModal.getOption 'userData' formData.recaptcha = grecaptcha?.getResponse() formData.username = username.input.getValue() formData.passwordConfirm = <PASSWORD> formData.firstName = firstName?.getValue() formData.lastName = lastName?.getValue() @signupModal.destroy() @doRegister formData, @registerForm else if usernameCheckTimer? pendingSignupRequest = yes doRegister: (formData, form) -> formData.agree = 'on' formData._csrf = Cookies.get '_csrf' unless formData.referrer { mainController } = kd.singletons referrer = utils.getReferrer() or mainController._referrer formData.referrer = referrer if referrer form or= @registerForm form.notificationsDisabled = yes form.notification?.destroy() { username, redirectTo } = formData redirectTo ?= '' query = '' if redirectTo is 'Pricing' { planInterval, planTitle } = formData query = kd.utils.stringifyQuery { planTitle, planInterval } query = "?#{query}" $.ajax url : '/Register' data : formData type : 'POST' xhrFields : { withCredentials : yes } success : -> utils.removeLastUsedProvider() expiration = new Date Date.now() + (60 * 60 * 1000) # an hour document.cookie = "newRegister=true;expires=#{expiration.toUTCString()}" return location.replace "/#{redirectTo}#{query}" error : (xhr) => { responseText } = xhr @showError form, responseText showError: (form, message) -> form.button.hideLoader() form.notificationsDisabled = no form.emit 'SubmitFailed', message if /duplicate key error/.test message form.emit 'EmailError' else if /^Errors were encountered during validation/.test message if /email/.test message form.emit 'EmailError' else form.emit 'UsernameError' else new kd.NotificationView { title: message } doLogin: (formData) -> { mainController } = kd.singletons mainController.on 'LoginFailed', => @loginForm.button.hideLoader() @$('.flex-wrapper').removeClass 'shake' kd.utils.defer => @$('.flex-wrapper').addClass 'animate shake' mainController.on 'TwoFactorEnabled', => @loginForm.button.hideLoader() @loginForm.tfcode.show() @loginForm.tfcode.setFocus() formData.redirectTo = utils.getLoginRedirectPath('/Login') ? 'IDE' mainController.login formData doRedeem: -> new kd.NotificationView { title: 'This feature is disabled.' } hide: (callback) -> @$('.flex-wrapper').removeClass 'expanded' @emit 'LoginViewHidden' @setClass 'hidden' callback?() show: (callback) -> @unsetClass 'hidden' @emit 'LoginViewShown' callback?() setCustomDataToForm: (type, data) -> formName = "#{type}Form" @[formName].addCustomData data setCustomData: (data) -> @setCustomDataToForm 'login', data @setCustomDataToForm 'register', data getRegisterLink: (data = {}) -> queryString = kd.utils.stringifyQuery data queryString = "?#{queryString}" if queryString.length > 0 link = "/Register#{queryString}" animateToForm: (name) -> @unsetClass 'register recover login reset home resendEmail' @emit 'LoginViewAnimated', name @setClass name @$('.flex-wrapper').removeClass 'three one' @formHeader.hide() @goToRecoverLink.show() switch name when 'register' @registerForm.email.input.setFocus() @$('.login-footer').hide() when 'redeem' @$('.flex-wrapper').addClass 'one' @redeemForm.inviteCode.input.setFocus() @$('.inline-footer').hide() @$('.login-footer').hide() when 'login' @loginForm.username.input.setFocus() if @$('.inline-footer').is ':hidden' then @$('.inline-footer').show() if @$('.login-footer').is ':hidden' then @$('.login-footer').show() when 'recover' @$('.flex-wrapper').addClass 'one' @goToRecoverLink.hide() @recoverForm.usernameOrEmail.input.setFocus() @$('.inline-footer').hide() @$('.login-footer').hide() when 'resendEmail' @$('.flex-wrapper').addClass 'one' @resendForm.usernameOrEmail.input.setFocus() @$('.inline-footer').hide() @$('.login-footer').hide() when 'reset' @formHeader.show() @formHeader.updatePartial 'Set your new password below' @goToRecoverLink.hide() @$('.inline-footer').hide() @$('.login-footer').hide() getRouteWithEntryPoint: (route) -> { entryPoint } = kd.config if entryPoint and entryPoint.slug isnt kd.defaultSlug return "/#{entryPoint.slug}/#{route}" else return "/#{route}" showError = (err) -> if err.code and err.code is 403 { name, nickname } = err.data kd.getSingleton('appManager').tell 'Account', 'displayConfirmEmailModal', name, nickname else if err.message.length > 50 new kd.ModalView title : 'Something is wrong!' width : 500 overlay : yes cssClass : 'new-kdmodal' content : "<div class='modalformline'>" + err.message + '</div>' else new kd.NotificationView title : err.message duration: 1000
true
$ = require 'jquery' kd = require 'kd' utils = require './../core/utils' JView = require './../core/jview' CustomLinkView = require './../core/customlinkview' LoginInputView = require './logininputview' LoginInlineForm = require './loginform' RegisterInlineForm = require './registerform' RedeemInlineForm = require './redeemform' RecoverInlineForm = require './recoverform' ResetInlineForm = require './resetform' ResendEmailConfirmationLinkInlineForm = require './resendmailconfirmationform' { getGroupNameFromLocation } = utils module.exports = class LoginView extends JView ENTER = 13 USERNAME_VALID = no pendingSignupRequest = no constructor: (options = {}, data) -> options.cssClass = 'login-screen login' options.attributes = testpath : 'login-container' super options, data @logo = new kd.CustomHTMLView tagName : 'a' cssClass : 'koding-logo' partial : '<img src=/a/images/logos/header_logo.svg class="main-header-logo">' attributes : { href : '/' } @backToLoginLink = new CustomLinkView title : 'Sign In' href : '/Login' click : -> @goToRecoverLink = new CustomLinkView cssClass : 'forgot-link' title : 'Forgot your password?' testPath : 'landing-recover-password' href : '/Recover' @formHeader = new kd.CustomHTMLView tagName : 'h4' cssClass : 'form-header' click : (event) -> return unless $(event.target).is 'a.register' @loginForm = new LoginInlineForm cssClass : 'login-form' testPath : 'login-form' callback : @bound 'doLogin' @registerForm = new RegisterInlineForm cssClass : 'login-form' testPath : 'register-form' callback : @bound 'showExtraInformation' @redeemForm = new RedeemInlineForm cssClass : 'login-form' callback : @bound 'doRedeem' @recoverForm = new RecoverInlineForm cssClass : 'login-form' callback : @bound 'doRecover' @resendForm = new ResendEmailConfirmationLinkInlineForm cssClass : 'login-form' callback : @bound 'resendEmailConfirmationToken' @resetForm = new ResetInlineForm cssClass : 'login-form' callback : @bound 'doReset' @headBanner = new kd.CustomHTMLView domId : 'invite-recovery-notification-bar' cssClass : 'invite-recovery-notification-bar hidden' partial : '...' { oauthController } = kd.singletons @githubIcon = new kd.CustomHTMLView tagName : 'span' cssClass : 'gh icon' click : -> oauthController.redirectToOauth { provider: 'github' } @gplusIcon = new kd.CustomHTMLView tagName : 'span' cssClass : 'go icon' click : -> oauthController.redirectToOauth { provider: 'google' } @facebookIcon = new kd.CustomHTMLView tagName : 'span' cssClass : 'fb icon' click : -> oauthController.redirectToOauth { provider: 'facebook' } @twitterIcon = new kd.CustomHTMLView tagName : 'span' cssClass : 'tw icon' click : -> oauthController.redirectToOauth { provider: 'twitter' } kd.singletons.router.on 'RouteInfoHandled', => @signupModal?.destroy() @signupModal = null viewAppended: -> @setTemplate @pistachio() @template.update() query = kd.utils.parseQuery document.location.search.replace '?', '' if query.warning suffix = if query.type is 'comment' then 'post a comment' else 'like an activity' message = "You need to be logged in to #{suffix}" kd.getSingleton('mainView').createGlobalNotification title : message type : 'yellow' content : '' closeTimer : 4000 container : this pistachio: -> # {{> @loginOptions}} # {{> @registerOptions}} """ <div class='tint'></div> {{> @logo }} <div class="flex-wrapper"> <div class="form-area"> {{> @formHeader}} <div class="login-form-holder lf"> {{> @loginForm}} </div> <div class="login-form-holder rf"> {{> @registerForm}} </div> <div class="login-form-holder rdf"> {{> @redeemForm}} </div> <div class="login-form-holder rcf"> {{> @recoverForm}} </div> <div class="login-form-holder rsf"> {{> @resetForm}} </div> <div class="login-form-holder resend-confirmation-form"> {{> @resendForm}} </div> </div> <div class="inline-footer"> <div class="oauth-container"> <span class='text'></span> {{> @githubIcon}} {{> @gplusIcon}} {{> @facebookIcon}} {{> @twitterIcon}} </div> </div> <div class="login-footer">{{> @goToRecoverLink}}</div> </div> <footer> <a href="https://www.koding.com/legal/teams-user-policy" target="_blank">Acceptable user policy</a><a href="https://www.koding.com/legal/teams-copyright" target="_blank">Copyright/DMCA guidelines</a><a href="https://www.koding.com/legal/teams-terms-of-service" target="_blank">Terms of service</a><a href="https://www.koding.com/legal/teams-privacy" target="_blank">Privacy policy</a> </footer> """ doReset: ({ recoveryToken, password }) -> $.ajax url : '/Reset' data : { recoveryToken, password, _csrf : Cookies.get '_csrf' } type : 'POST' error : (xhr) => { responseText } = xhr @resetForm.button.hideLoader() new kd.NotificationView { title : responseText } success : ({ username }) => @resetForm.button.hideLoader() @resetForm.reset() @headBanner.hide() new kd.NotificationView title: 'Password changed, you can login now' kd.singletons.router.handleRoute '/Login' doRecover: ({ email }) -> $.ajax url : '/Recover' data : { email, _csrf : Cookies.get '_csrf' } type : 'POST' error : (xhr) => { responseText } = xhr new kd.NotificationView { title : responseText } @loginForm.button.hideLoader() success : => @recoverForm.reset() { entryPoint } = kd.config kd.getSingleton('router').handleRoute '/Login', { entryPoint } new kd.NotificationView title : 'Check your email' content : "We've sent you a password recovery code." duration : 4500 resendEmailConfirmationToken: (formData) -> kd.remote.api.JPasswordRecovery.recoverPassword formData['username-or-email'], (err) => @resendForm.button.hideLoader() if err new kd.NotificationView title : "An error occurred: #{err.message}" else @resendForm.reset() { entryPoint } = kd.config kd.getSingleton('router').handleRoute '/Login', { entryPoint } new kd.NotificationView title : 'Check your email' content : "We've sent you a confirmation mail." duration : 4500 showExtraInformation : (formData, form) -> form ?= @registerForm { mainView } = kd.singletons mainView.setClass 'blur' { email, password } = formData gravatar = form.gravatars[formData.email] unless gravatar form.once 'gravatarInfoFetched', => @showExtraInformation formData, form return { preferredUsername, requestHash } = gravatar givenName = gravatar.name?.givenName familyName = gravatar.name?.familyName fields = {} size = 80 src = utils.getGravatarUrl size, requestHash fields.photo = itemClass : kd.CustomHTMLView tagName : 'img' attributes : { src } fields.email = itemClass : kd.CustomHTMLView partial : email fields.username = name : 'username' itemClass : LoginInputView label : 'Pick a username' inputOptions : name : 'username' defaultValue : preferredUsername forceCase : 'lowercase' placeholder : 'username' attributes : testpath : 'register-form-username' focus : -> @parent.icon.unsetTooltip() validate : container : this rules : required : yes rangeLength : [4, 25] regExp : /^[a-z\d]+([-][a-z\d]+)*$/i usernameCheck: (input, event) => @usernameCheck input, event finalCheck : (input, event) => @usernameCheck input, event, 0 messages : required : 'Please enter a username.' regExp : 'For username only lowercase letters and numbers are allowed!' rangeLength : 'Username should be between 4 and 25 characters!' events : required : 'blur' rangeLength : 'blur' regExp : 'keyup' usernameCheck: 'keyup' finalCheck : 'blur' nextElement : suffix : itemClass : kd.CustomHTMLView cssClass : 'suffix' partial : '.koding.io' if givenName fields.firstName = defaultValue : givenName label : 'First Name' if familyName fields.lastName = defaultValue : familyName label : 'Last Name' fields.recaptcha = itemClass : kd.CustomHTMLView domId : 'recaptcha' USERNAME_VALID = no pendingSignupRequest = no @signupModal = new kd.ModalViewWithForms cssClass : 'extra-info password' # recaptcha has fixed with of 304, hence this value width : 363 height : 'auto' overlay : yes tabs : forms : extraInformation : callback : @bound 'checkBeforeRegister' fields : fields buttons : continue : title : 'LET\'S GO' style : 'solid green medium' type : 'submit' @signupModal.setOption 'userData', formData usernameView = @signupModal.modalTabs.forms.extraInformation.inputs.username usernameView.setOption 'stickyTooltip', yes unless gravatar.dummy @signupModal.addSubView new kd.CustomHTMLView partial : 'Profile info fetched from Gravatar.' cssClass : 'description' @signupModal.once 'KDObjectWillBeDestroyed', => kd.utils.killWait usernameCheckTimer usernameCheckTimer = null mainView.unsetClass 'blur' form.button.hideLoader() form.email.icon.unsetTooltip() form.password.icon.unsetTooltip() usernameView.icon.unsetTooltip() @signupModal = null @signupModal.once 'viewAppended', => if @recaptchaEnabled() utils.loadRecaptchaScript -> grecaptcha?.render 'recaptcha', { sitekey : kd.config.recaptcha.key } @signupModal.addSubView new kd.CustomHTMLView partial : """<div class='hint accept-tos'>By creating an account, you accept Koding's <a href="/Legal/Terms" target="_blank"> Terms of Service</a> and <a href="/Legal/Privacy" target="_blank">Privacy Policy.</a></div>""" kd.utils.defer -> usernameView.input.setFocus() usernameCheckTimer = null usernameCheck: (input, event, delay = 800) -> return if event?.which is 9 return if input.getValue().length < 4 kd.utils.killWait usernameCheckTimer usernameCheckTimer = null input.setValidationResult 'usernameCheck', null username = input.getValue() return unless input.valid usernameCheckTimer = kd.utils.wait delay, => return unless @signupModal? utils.usernameCheck username, success : => usernameCheckTimer = null return unless @signupModal? input.setValidationResult 'usernameCheck', null USERNAME_VALID = yes @checkBeforeRegister() if pendingSignupRequest error : ({ responseJSON }) => usernameCheckTimer = null pendingSignupRequest = no return unless @signupModal? unless responseJSON return new kd.NotificationView title: 'Something went wrong' { forbidden, kodingUser } = responseJSON USERNAME_VALID = no message = switch when forbidden "Sorry, \"#{username}\" is forbidden to use!" when kodingUser "Sorry, \"#{username}\" is already taken!" else "Sorry, there is a problem with \"#{username}\"!" input.setValidationResult 'usernameCheck', message changeButtonState: (button, state) -> if state button.setClass 'green' button.unsetClass 'red' button.enable() else button.setClass 'red' button.unsetClass 'green' button.disable() recaptchaEnabled: -> return kd.config.recaptcha.enabled and utils.getLastUsedProvider() isnt 'github' checkBeforeRegister: -> return unless @signupModal? { username, firstName, lastName } = @signupModal.modalTabs.forms.extraInformation.inputs if @recaptchaEnabled and grecaptcha?.getResponse() is '' return new kd.NotificationView { title : "Please tell us that you're not a robot!" } pendingSignupRequest = no if USERNAME_VALID and username.input.valid formData = @signupModal.getOption 'userData' formData.recaptcha = grecaptcha?.getResponse() formData.username = username.input.getValue() formData.passwordConfirm = PI:PASSWORD:<PASSWORD>END_PI formData.firstName = firstName?.getValue() formData.lastName = lastName?.getValue() @signupModal.destroy() @doRegister formData, @registerForm else if usernameCheckTimer? pendingSignupRequest = yes doRegister: (formData, form) -> formData.agree = 'on' formData._csrf = Cookies.get '_csrf' unless formData.referrer { mainController } = kd.singletons referrer = utils.getReferrer() or mainController._referrer formData.referrer = referrer if referrer form or= @registerForm form.notificationsDisabled = yes form.notification?.destroy() { username, redirectTo } = formData redirectTo ?= '' query = '' if redirectTo is 'Pricing' { planInterval, planTitle } = formData query = kd.utils.stringifyQuery { planTitle, planInterval } query = "?#{query}" $.ajax url : '/Register' data : formData type : 'POST' xhrFields : { withCredentials : yes } success : -> utils.removeLastUsedProvider() expiration = new Date Date.now() + (60 * 60 * 1000) # an hour document.cookie = "newRegister=true;expires=#{expiration.toUTCString()}" return location.replace "/#{redirectTo}#{query}" error : (xhr) => { responseText } = xhr @showError form, responseText showError: (form, message) -> form.button.hideLoader() form.notificationsDisabled = no form.emit 'SubmitFailed', message if /duplicate key error/.test message form.emit 'EmailError' else if /^Errors were encountered during validation/.test message if /email/.test message form.emit 'EmailError' else form.emit 'UsernameError' else new kd.NotificationView { title: message } doLogin: (formData) -> { mainController } = kd.singletons mainController.on 'LoginFailed', => @loginForm.button.hideLoader() @$('.flex-wrapper').removeClass 'shake' kd.utils.defer => @$('.flex-wrapper').addClass 'animate shake' mainController.on 'TwoFactorEnabled', => @loginForm.button.hideLoader() @loginForm.tfcode.show() @loginForm.tfcode.setFocus() formData.redirectTo = utils.getLoginRedirectPath('/Login') ? 'IDE' mainController.login formData doRedeem: -> new kd.NotificationView { title: 'This feature is disabled.' } hide: (callback) -> @$('.flex-wrapper').removeClass 'expanded' @emit 'LoginViewHidden' @setClass 'hidden' callback?() show: (callback) -> @unsetClass 'hidden' @emit 'LoginViewShown' callback?() setCustomDataToForm: (type, data) -> formName = "#{type}Form" @[formName].addCustomData data setCustomData: (data) -> @setCustomDataToForm 'login', data @setCustomDataToForm 'register', data getRegisterLink: (data = {}) -> queryString = kd.utils.stringifyQuery data queryString = "?#{queryString}" if queryString.length > 0 link = "/Register#{queryString}" animateToForm: (name) -> @unsetClass 'register recover login reset home resendEmail' @emit 'LoginViewAnimated', name @setClass name @$('.flex-wrapper').removeClass 'three one' @formHeader.hide() @goToRecoverLink.show() switch name when 'register' @registerForm.email.input.setFocus() @$('.login-footer').hide() when 'redeem' @$('.flex-wrapper').addClass 'one' @redeemForm.inviteCode.input.setFocus() @$('.inline-footer').hide() @$('.login-footer').hide() when 'login' @loginForm.username.input.setFocus() if @$('.inline-footer').is ':hidden' then @$('.inline-footer').show() if @$('.login-footer').is ':hidden' then @$('.login-footer').show() when 'recover' @$('.flex-wrapper').addClass 'one' @goToRecoverLink.hide() @recoverForm.usernameOrEmail.input.setFocus() @$('.inline-footer').hide() @$('.login-footer').hide() when 'resendEmail' @$('.flex-wrapper').addClass 'one' @resendForm.usernameOrEmail.input.setFocus() @$('.inline-footer').hide() @$('.login-footer').hide() when 'reset' @formHeader.show() @formHeader.updatePartial 'Set your new password below' @goToRecoverLink.hide() @$('.inline-footer').hide() @$('.login-footer').hide() getRouteWithEntryPoint: (route) -> { entryPoint } = kd.config if entryPoint and entryPoint.slug isnt kd.defaultSlug return "/#{entryPoint.slug}/#{route}" else return "/#{route}" showError = (err) -> if err.code and err.code is 403 { name, nickname } = err.data kd.getSingleton('appManager').tell 'Account', 'displayConfirmEmailModal', name, nickname else if err.message.length > 50 new kd.ModalView title : 'Something is wrong!' width : 500 overlay : yes cssClass : 'new-kdmodal' content : "<div class='modalformline'>" + err.message + '</div>' else new kd.NotificationView title : err.message duration: 1000
[ { "context": "in =\n brand: 'Cerbatán POS'\n name: 'Lisa Doe'\n\n $scope.admin =\n layout: 'wide'\n ", "end": 202, "score": 0.9998782277107239, "start": 194, "tag": "NAME", "value": "Lisa Doe" } ]
app/assets/js/app/controllers.coffee
cerbatan/CerbatanPOS
0
define ['jquery', './module'], ($, app) -> AppCtrl = ($scope, $rootScope, $route, $document) -> $window = $(window) $scope.main = brand: 'Cerbatán POS' name: 'Lisa Doe' $scope.admin = layout: 'wide' menu: 'vertical' fixedHeader: true fixedSidebar: true $scope.$watch 'admin', (newVal, oldVal) -> if newVal.menu == 'horizontal' and oldVal.menu == 'vertical' $rootScope.$broadcast 'nav:reset' return if newVal.fixedHeader == false and newVal.fixedSidebar == true if oldVal.fixedHeader == false and oldVal.fixedSidebar == false $scope.admin.fixedHeader = true $scope.admin.fixedSidebar = true if oldVal.fixedHeader == true and oldVal.fixedSidebar == true $scope.admin.fixedHeader = false $scope.admin.fixedSidebar = false return if newVal.fixedSidebar == true $scope.admin.fixedHeader = true if newVal.fixedHeader == false $scope.admin.fixedSidebar = false return , true $scope.color = primary: '#1BB7A0' success: '#94B758' info: '#56BDF1' infoAlt: '#7F6EC7' warning: '#F3C536' danger: '#FA7B58' $rootScope.$on '$routeChangeSuccess', (event, currentRoute, previousRoute) -> $document.scrollTo 0, 0 AppCtrl .$inject = ['$scope', '$rootScope', '$route', '$document'] app.controller 'AppCtrl', AppCtrl HeaderCtrl = -> app.controller 'HeaderCtrl', HeaderCtrl NavCtrl = ($scope, taskStorage, filterFilter) -> tasks = $scope.tasks = taskStorage.get() $scope.taskRemainingCount = filterFilter(tasks, completed: false).length $scope.$on 'taskRemaining:changed', (event, count) -> $scope.taskRemainingCount = count NavCtrl .$inject = ['$scope', 'taskStorage', 'filterFilter'] app.controller 'NavCtrl', NavCtrl DashboardCtrl = -> app.controller 'DashboardCtrl', DashboardCtrl
39992
define ['jquery', './module'], ($, app) -> AppCtrl = ($scope, $rootScope, $route, $document) -> $window = $(window) $scope.main = brand: 'Cerbatán POS' name: '<NAME>' $scope.admin = layout: 'wide' menu: 'vertical' fixedHeader: true fixedSidebar: true $scope.$watch 'admin', (newVal, oldVal) -> if newVal.menu == 'horizontal' and oldVal.menu == 'vertical' $rootScope.$broadcast 'nav:reset' return if newVal.fixedHeader == false and newVal.fixedSidebar == true if oldVal.fixedHeader == false and oldVal.fixedSidebar == false $scope.admin.fixedHeader = true $scope.admin.fixedSidebar = true if oldVal.fixedHeader == true and oldVal.fixedSidebar == true $scope.admin.fixedHeader = false $scope.admin.fixedSidebar = false return if newVal.fixedSidebar == true $scope.admin.fixedHeader = true if newVal.fixedHeader == false $scope.admin.fixedSidebar = false return , true $scope.color = primary: '#1BB7A0' success: '#94B758' info: '#56BDF1' infoAlt: '#7F6EC7' warning: '#F3C536' danger: '#FA7B58' $rootScope.$on '$routeChangeSuccess', (event, currentRoute, previousRoute) -> $document.scrollTo 0, 0 AppCtrl .$inject = ['$scope', '$rootScope', '$route', '$document'] app.controller 'AppCtrl', AppCtrl HeaderCtrl = -> app.controller 'HeaderCtrl', HeaderCtrl NavCtrl = ($scope, taskStorage, filterFilter) -> tasks = $scope.tasks = taskStorage.get() $scope.taskRemainingCount = filterFilter(tasks, completed: false).length $scope.$on 'taskRemaining:changed', (event, count) -> $scope.taskRemainingCount = count NavCtrl .$inject = ['$scope', 'taskStorage', 'filterFilter'] app.controller 'NavCtrl', NavCtrl DashboardCtrl = -> app.controller 'DashboardCtrl', DashboardCtrl
true
define ['jquery', './module'], ($, app) -> AppCtrl = ($scope, $rootScope, $route, $document) -> $window = $(window) $scope.main = brand: 'Cerbatán POS' name: 'PI:NAME:<NAME>END_PI' $scope.admin = layout: 'wide' menu: 'vertical' fixedHeader: true fixedSidebar: true $scope.$watch 'admin', (newVal, oldVal) -> if newVal.menu == 'horizontal' and oldVal.menu == 'vertical' $rootScope.$broadcast 'nav:reset' return if newVal.fixedHeader == false and newVal.fixedSidebar == true if oldVal.fixedHeader == false and oldVal.fixedSidebar == false $scope.admin.fixedHeader = true $scope.admin.fixedSidebar = true if oldVal.fixedHeader == true and oldVal.fixedSidebar == true $scope.admin.fixedHeader = false $scope.admin.fixedSidebar = false return if newVal.fixedSidebar == true $scope.admin.fixedHeader = true if newVal.fixedHeader == false $scope.admin.fixedSidebar = false return , true $scope.color = primary: '#1BB7A0' success: '#94B758' info: '#56BDF1' infoAlt: '#7F6EC7' warning: '#F3C536' danger: '#FA7B58' $rootScope.$on '$routeChangeSuccess', (event, currentRoute, previousRoute) -> $document.scrollTo 0, 0 AppCtrl .$inject = ['$scope', '$rootScope', '$route', '$document'] app.controller 'AppCtrl', AppCtrl HeaderCtrl = -> app.controller 'HeaderCtrl', HeaderCtrl NavCtrl = ($scope, taskStorage, filterFilter) -> tasks = $scope.tasks = taskStorage.get() $scope.taskRemainingCount = filterFilter(tasks, completed: false).length $scope.$on 'taskRemaining:changed', (event, count) -> $scope.taskRemainingCount = count NavCtrl .$inject = ['$scope', 'taskStorage', 'filterFilter'] app.controller 'NavCtrl', NavCtrl DashboardCtrl = -> app.controller 'DashboardCtrl', DashboardCtrl
[ { "context": "o a hyperlink pasted into slack...\n#\n# Author:\n# John Vernon\n\n#Environment Variables\ncwURL = process.env.HUBOT", "end": 643, "score": 0.9998230338096619, "start": 632, "tag": "NAME", "value": "John Vernon" } ]
src/connectwise-slack.coffee
webteks/hubot-cwslack
0
# Description: # Identifies ConnectWise ticket numbers in chat, verifies they are real, and provides a web link to the ticket # # Dependencies: # Slack Adapter # # Configuration: # HUBOT_CW_URL - The URL of the ConnectWise Server # HUBOT_CW_COMPANYID - The Company ID of the ConnectWise Instance # HUBOT_CW_APIPUBLIC - The REST API Public Key # HUBOT_CW_APISECRECT - The REST API Private Key # # Commands: # 5-6 digit number in chat {}\b\d{5-6}\b}/ig - Provides a Hyperlink to the ticket if the number is a valid ticket number. # # Notes: # Currently will respond to a hyperlink pasted into slack... # # Author: # John Vernon #Environment Variables cwURL = process.env.HUBOT_CW_URL cwCompanyID = process.env.HUBOT_CW_COMPANYID cwPublic = process.env.HUBOT_CW_APIPUBLIC cwSecret = process.env.HUBOT_CW_APISECRECT cwAPIURL = process.env.HUBOT_CW_API_URL #check for config Errors configError = -> unless cwURL? return "Connectwise Helper: Undefined HUBOT_CW_URL" unless cwCompanyID? return "Connectwise Helper: Undefined HUBOT_CW_COMPANYID" unless cwPublic? return "Connectwise Helper: Undefined HUBOT_CW_APIPUBLIC" unless cwSecret? return "Connectwise Helper: Undefined HUBOT_CW_APISECRECT" unless cwAPIURL? return "Connectwise Helper: Undefined HUBOT_CW_API_URL" #Ticket Watchers DAL class CWTWatchers constructor: (@robot) -> @robot.brain.data.cwtwatchers = {} add: (cwTicket, userName) -> if @robot.brain.data.cwtwatchers[cwTicket] is undefined @robot.logger.debug "cwTicket collection is undefined" @robot.brain.data.cwtwatchers[cwTicket] = [] for watcher in @robot.brain.data.cwtwatchers[cwTicket] if watcher.toLowerCase() is userName.toLowerCase() @robot.logger.debug "Found #{watcher} already watching #{cwTicket}" return @robot.brain.data.cwtwatchers[cwTicket].push userName @robot.logger.debug "#{userName} is now watching #{cwTicket}" remove: (cwTicket, userName) -> watchers = @robot.brain.data.cwtwatchers[cwTicket] or [] @robot.brain.data.cwtwatchers[cwTicket] = (user for user in watchers when user.toLowerCase() isnt userName.toLowerCase()) @robot.logger.debug "Removed #{userName} from watching #{cwTicket}" removeAll: (cwTicket) -> delete @robot.brain.data.cwtwatchers[cwTicket] watchers: (cwTicket) -> return @robot.brain.data.cwtwatchers[cwTicket] or [] #Check for other listeners that we need to ignore for the ticket watch ticketHeardExclusions = (heardString) -> if heardString.match(/watch ticket \b(\d{3,6})\b/i)? return true if heardString.match(/ignore ticket \b(\d{3,6})\b/i)? return true if heardString.match(/who is watching \b(\d{3,6})\b/i)? return true #Dedupe and array removeDuplicates = (ar) -> if ar.length == 0 return [] res = {} res[ar[key]] = ar[key] for key in [0..ar.length-1] value for key, value of res #create an auth string for ConnectWise REST API auth = 'Basic ' + new Buffer(cwCompanyID + '+' + cwPublic + ':' + cwSecret).toString('base64'); ###Begin Listeners### module.exports = (robot) -> CWTicketWatchers = new CWTWatchers robot #Listen for ticket numbers mentioned in chat robot.hear /\b(\d{3,6})\b/i, (msg) -> unless not configError()? msg.send "#{configError()}" return robot.logger.debug "CWTicket passed environment check" #check to ensure that the message is not in another match robot.logger.debug "HeardString = #{msg.message.text}" if ticketHeardExclusions(msg.message.text)? robot.logger.debug "Excluded string match found" return #Create an array of match strings foundValues = removeDuplicates(msg.message.text.match(/\b(\d{3,6})\b/ig)) for cwticket in foundValues #check ConnectWise to see if ticket exists robot.http("https://#{cwAPIURL}/v4_6_release/apis/3.0/service/tickets/#{cwticket}") .headers(Authorization: auth, Accept: 'application/json') .get() (err, res, body) -> data = JSON.parse(body) if res.statusCode == 200 robot.logger.debug "Ticket Link: #{data.id}!" robot.emit 'slack.attachment', message: msg.message content: title: "Ticket Link: #{data.id}!" title_link: "https://#{cwURL}/v4_6_release/services/system_io/Service/fv_sr100_request.rails?service_recid=#{data.id}&companyName=#{cwCompanyID}" color: "#0A53A1" fallback: "Ticket Link: #{data.id}!" #listen for ticket watch requests robot.hear /watch ticket \b(\d{3,6})\b/i, (msg) -> unless not configError()? msg.send "#{configError()}" return robot.http("https://#{cwAPIURL}/v4_6_release/apis/3.0/service/tickets/#{msg.match[1]}") .headers(Authorization: auth, Accept: 'application/json') .get() (err, res, body) -> data = JSON.parse(body) if res.statusCode == 200 #add to watch list CWTicketWatchers.add data.id,msg.message.user.name #notify user of addition robot.logger.debug "Ticket watch set for #{data.id}" robot.emit 'slack.attachment', message: msg.message channel: msg.envelope.user.name content: title: "Ticket watch success" color: "good" fallback: "Watch set for ticket: #{data.id}" text: "Watch set for ticket: #{data.id}" else robot.logger.debug "Ticket #{msg.match[1]} not in CW" robot.emit 'slack.attachment', message: msg.message channel: msg.envelope.user.name content: title: "Ticket watch failure" color: "danger" fallback: "Ticket watch failure" text: "Invalid ticket for watch: #{msg.match[1]}.\nPlease verify that this is the correct ticket number." #get a list of listeners for a given ticket robot.hear /who is watching \b(\d{3,6})\b/i, (msg) -> cwTicket = msg.match[1] ticketWatchers = CWTicketWatchers.watchers(cwTicket) if ticketWatchers.length > 0 robot.logger.debug "#{ticketWatchers.toString()} are watching #{cwTicket}" robot.emit 'slack.attachment', message: msg.message channel: msg.envelope.user.name content: title: "Users watching ticket #{cwTicket}" text: "#{ticketWatchers.toString()} are watching #{cwTicket}" fallback: "#{ticketWatchers.toString()} are watching #{cwTicket}" color: "#439FE0" else robot.logger.debug "Can't find anyone watching #{cwTicket}" msg.send "I don't recall anyone watching #{cwTicket}" #listen for ticket ignore requests robot.hear /ignore ticket \b(\d{3,6})\b/i, (msg) -> unless not configError()? msg.send "#{configError()}" return cwticket = msg.match[1] CWTicketWatchers.remove cwticket, msg.message.user.name robot.logger.debug "Ticket #{cwticket} ignored" robot.emit 'slack.attachment', message: msg.message channel: msg.envelope.user.name content: title: "Ignoring Ticket" color: "good" fallback: "Now ignoring: #{cwticket}" text: "You are no longer watching ticket: #{cwticket}" #clear all followers for a ticket robot.hear /clear all watchers for ticket \b(\d{3,6})\b/i, (msg) -> unless not configError()? msg.send "#{configError()}" return cwticket = msg.match[1] CWTicketWatchers.removeAll cwticket robot.logger.debug "Removed all watchers for ticket #{cwticket}" robot.emit 'slack.attachment', message: msg.message channel: msg.envelope.user.name content: title: "Clear Watchers" color: "info" fallback: "All watchers cleared for ticket #{cwticket}" text: "All watchers cleared for ticket #{cwticket}" #Listen for callbacks with watched tickets robot.router.post '/hubot/cwticket', (req, res) -> if req.query.id? watchers = CWTicketWatchers.watchers req.query.id if watchers.length == 0 return for user in watchers robot.send {room: "#{user}"}, "#{req.query.id} was updated" res.end()
37345
# Description: # Identifies ConnectWise ticket numbers in chat, verifies they are real, and provides a web link to the ticket # # Dependencies: # Slack Adapter # # Configuration: # HUBOT_CW_URL - The URL of the ConnectWise Server # HUBOT_CW_COMPANYID - The Company ID of the ConnectWise Instance # HUBOT_CW_APIPUBLIC - The REST API Public Key # HUBOT_CW_APISECRECT - The REST API Private Key # # Commands: # 5-6 digit number in chat {}\b\d{5-6}\b}/ig - Provides a Hyperlink to the ticket if the number is a valid ticket number. # # Notes: # Currently will respond to a hyperlink pasted into slack... # # Author: # <NAME> #Environment Variables cwURL = process.env.HUBOT_CW_URL cwCompanyID = process.env.HUBOT_CW_COMPANYID cwPublic = process.env.HUBOT_CW_APIPUBLIC cwSecret = process.env.HUBOT_CW_APISECRECT cwAPIURL = process.env.HUBOT_CW_API_URL #check for config Errors configError = -> unless cwURL? return "Connectwise Helper: Undefined HUBOT_CW_URL" unless cwCompanyID? return "Connectwise Helper: Undefined HUBOT_CW_COMPANYID" unless cwPublic? return "Connectwise Helper: Undefined HUBOT_CW_APIPUBLIC" unless cwSecret? return "Connectwise Helper: Undefined HUBOT_CW_APISECRECT" unless cwAPIURL? return "Connectwise Helper: Undefined HUBOT_CW_API_URL" #Ticket Watchers DAL class CWTWatchers constructor: (@robot) -> @robot.brain.data.cwtwatchers = {} add: (cwTicket, userName) -> if @robot.brain.data.cwtwatchers[cwTicket] is undefined @robot.logger.debug "cwTicket collection is undefined" @robot.brain.data.cwtwatchers[cwTicket] = [] for watcher in @robot.brain.data.cwtwatchers[cwTicket] if watcher.toLowerCase() is userName.toLowerCase() @robot.logger.debug "Found #{watcher} already watching #{cwTicket}" return @robot.brain.data.cwtwatchers[cwTicket].push userName @robot.logger.debug "#{userName} is now watching #{cwTicket}" remove: (cwTicket, userName) -> watchers = @robot.brain.data.cwtwatchers[cwTicket] or [] @robot.brain.data.cwtwatchers[cwTicket] = (user for user in watchers when user.toLowerCase() isnt userName.toLowerCase()) @robot.logger.debug "Removed #{userName} from watching #{cwTicket}" removeAll: (cwTicket) -> delete @robot.brain.data.cwtwatchers[cwTicket] watchers: (cwTicket) -> return @robot.brain.data.cwtwatchers[cwTicket] or [] #Check for other listeners that we need to ignore for the ticket watch ticketHeardExclusions = (heardString) -> if heardString.match(/watch ticket \b(\d{3,6})\b/i)? return true if heardString.match(/ignore ticket \b(\d{3,6})\b/i)? return true if heardString.match(/who is watching \b(\d{3,6})\b/i)? return true #Dedupe and array removeDuplicates = (ar) -> if ar.length == 0 return [] res = {} res[ar[key]] = ar[key] for key in [0..ar.length-1] value for key, value of res #create an auth string for ConnectWise REST API auth = 'Basic ' + new Buffer(cwCompanyID + '+' + cwPublic + ':' + cwSecret).toString('base64'); ###Begin Listeners### module.exports = (robot) -> CWTicketWatchers = new CWTWatchers robot #Listen for ticket numbers mentioned in chat robot.hear /\b(\d{3,6})\b/i, (msg) -> unless not configError()? msg.send "#{configError()}" return robot.logger.debug "CWTicket passed environment check" #check to ensure that the message is not in another match robot.logger.debug "HeardString = #{msg.message.text}" if ticketHeardExclusions(msg.message.text)? robot.logger.debug "Excluded string match found" return #Create an array of match strings foundValues = removeDuplicates(msg.message.text.match(/\b(\d{3,6})\b/ig)) for cwticket in foundValues #check ConnectWise to see if ticket exists robot.http("https://#{cwAPIURL}/v4_6_release/apis/3.0/service/tickets/#{cwticket}") .headers(Authorization: auth, Accept: 'application/json') .get() (err, res, body) -> data = JSON.parse(body) if res.statusCode == 200 robot.logger.debug "Ticket Link: #{data.id}!" robot.emit 'slack.attachment', message: msg.message content: title: "Ticket Link: #{data.id}!" title_link: "https://#{cwURL}/v4_6_release/services/system_io/Service/fv_sr100_request.rails?service_recid=#{data.id}&companyName=#{cwCompanyID}" color: "#0A53A1" fallback: "Ticket Link: #{data.id}!" #listen for ticket watch requests robot.hear /watch ticket \b(\d{3,6})\b/i, (msg) -> unless not configError()? msg.send "#{configError()}" return robot.http("https://#{cwAPIURL}/v4_6_release/apis/3.0/service/tickets/#{msg.match[1]}") .headers(Authorization: auth, Accept: 'application/json') .get() (err, res, body) -> data = JSON.parse(body) if res.statusCode == 200 #add to watch list CWTicketWatchers.add data.id,msg.message.user.name #notify user of addition robot.logger.debug "Ticket watch set for #{data.id}" robot.emit 'slack.attachment', message: msg.message channel: msg.envelope.user.name content: title: "Ticket watch success" color: "good" fallback: "Watch set for ticket: #{data.id}" text: "Watch set for ticket: #{data.id}" else robot.logger.debug "Ticket #{msg.match[1]} not in CW" robot.emit 'slack.attachment', message: msg.message channel: msg.envelope.user.name content: title: "Ticket watch failure" color: "danger" fallback: "Ticket watch failure" text: "Invalid ticket for watch: #{msg.match[1]}.\nPlease verify that this is the correct ticket number." #get a list of listeners for a given ticket robot.hear /who is watching \b(\d{3,6})\b/i, (msg) -> cwTicket = msg.match[1] ticketWatchers = CWTicketWatchers.watchers(cwTicket) if ticketWatchers.length > 0 robot.logger.debug "#{ticketWatchers.toString()} are watching #{cwTicket}" robot.emit 'slack.attachment', message: msg.message channel: msg.envelope.user.name content: title: "Users watching ticket #{cwTicket}" text: "#{ticketWatchers.toString()} are watching #{cwTicket}" fallback: "#{ticketWatchers.toString()} are watching #{cwTicket}" color: "#439FE0" else robot.logger.debug "Can't find anyone watching #{cwTicket}" msg.send "I don't recall anyone watching #{cwTicket}" #listen for ticket ignore requests robot.hear /ignore ticket \b(\d{3,6})\b/i, (msg) -> unless not configError()? msg.send "#{configError()}" return cwticket = msg.match[1] CWTicketWatchers.remove cwticket, msg.message.user.name robot.logger.debug "Ticket #{cwticket} ignored" robot.emit 'slack.attachment', message: msg.message channel: msg.envelope.user.name content: title: "Ignoring Ticket" color: "good" fallback: "Now ignoring: #{cwticket}" text: "You are no longer watching ticket: #{cwticket}" #clear all followers for a ticket robot.hear /clear all watchers for ticket \b(\d{3,6})\b/i, (msg) -> unless not configError()? msg.send "#{configError()}" return cwticket = msg.match[1] CWTicketWatchers.removeAll cwticket robot.logger.debug "Removed all watchers for ticket #{cwticket}" robot.emit 'slack.attachment', message: msg.message channel: msg.envelope.user.name content: title: "Clear Watchers" color: "info" fallback: "All watchers cleared for ticket #{cwticket}" text: "All watchers cleared for ticket #{cwticket}" #Listen for callbacks with watched tickets robot.router.post '/hubot/cwticket', (req, res) -> if req.query.id? watchers = CWTicketWatchers.watchers req.query.id if watchers.length == 0 return for user in watchers robot.send {room: "#{user}"}, "#{req.query.id} was updated" res.end()
true
# Description: # Identifies ConnectWise ticket numbers in chat, verifies they are real, and provides a web link to the ticket # # Dependencies: # Slack Adapter # # Configuration: # HUBOT_CW_URL - The URL of the ConnectWise Server # HUBOT_CW_COMPANYID - The Company ID of the ConnectWise Instance # HUBOT_CW_APIPUBLIC - The REST API Public Key # HUBOT_CW_APISECRECT - The REST API Private Key # # Commands: # 5-6 digit number in chat {}\b\d{5-6}\b}/ig - Provides a Hyperlink to the ticket if the number is a valid ticket number. # # Notes: # Currently will respond to a hyperlink pasted into slack... # # Author: # PI:NAME:<NAME>END_PI #Environment Variables cwURL = process.env.HUBOT_CW_URL cwCompanyID = process.env.HUBOT_CW_COMPANYID cwPublic = process.env.HUBOT_CW_APIPUBLIC cwSecret = process.env.HUBOT_CW_APISECRECT cwAPIURL = process.env.HUBOT_CW_API_URL #check for config Errors configError = -> unless cwURL? return "Connectwise Helper: Undefined HUBOT_CW_URL" unless cwCompanyID? return "Connectwise Helper: Undefined HUBOT_CW_COMPANYID" unless cwPublic? return "Connectwise Helper: Undefined HUBOT_CW_APIPUBLIC" unless cwSecret? return "Connectwise Helper: Undefined HUBOT_CW_APISECRECT" unless cwAPIURL? return "Connectwise Helper: Undefined HUBOT_CW_API_URL" #Ticket Watchers DAL class CWTWatchers constructor: (@robot) -> @robot.brain.data.cwtwatchers = {} add: (cwTicket, userName) -> if @robot.brain.data.cwtwatchers[cwTicket] is undefined @robot.logger.debug "cwTicket collection is undefined" @robot.brain.data.cwtwatchers[cwTicket] = [] for watcher in @robot.brain.data.cwtwatchers[cwTicket] if watcher.toLowerCase() is userName.toLowerCase() @robot.logger.debug "Found #{watcher} already watching #{cwTicket}" return @robot.brain.data.cwtwatchers[cwTicket].push userName @robot.logger.debug "#{userName} is now watching #{cwTicket}" remove: (cwTicket, userName) -> watchers = @robot.brain.data.cwtwatchers[cwTicket] or [] @robot.brain.data.cwtwatchers[cwTicket] = (user for user in watchers when user.toLowerCase() isnt userName.toLowerCase()) @robot.logger.debug "Removed #{userName} from watching #{cwTicket}" removeAll: (cwTicket) -> delete @robot.brain.data.cwtwatchers[cwTicket] watchers: (cwTicket) -> return @robot.brain.data.cwtwatchers[cwTicket] or [] #Check for other listeners that we need to ignore for the ticket watch ticketHeardExclusions = (heardString) -> if heardString.match(/watch ticket \b(\d{3,6})\b/i)? return true if heardString.match(/ignore ticket \b(\d{3,6})\b/i)? return true if heardString.match(/who is watching \b(\d{3,6})\b/i)? return true #Dedupe and array removeDuplicates = (ar) -> if ar.length == 0 return [] res = {} res[ar[key]] = ar[key] for key in [0..ar.length-1] value for key, value of res #create an auth string for ConnectWise REST API auth = 'Basic ' + new Buffer(cwCompanyID + '+' + cwPublic + ':' + cwSecret).toString('base64'); ###Begin Listeners### module.exports = (robot) -> CWTicketWatchers = new CWTWatchers robot #Listen for ticket numbers mentioned in chat robot.hear /\b(\d{3,6})\b/i, (msg) -> unless not configError()? msg.send "#{configError()}" return robot.logger.debug "CWTicket passed environment check" #check to ensure that the message is not in another match robot.logger.debug "HeardString = #{msg.message.text}" if ticketHeardExclusions(msg.message.text)? robot.logger.debug "Excluded string match found" return #Create an array of match strings foundValues = removeDuplicates(msg.message.text.match(/\b(\d{3,6})\b/ig)) for cwticket in foundValues #check ConnectWise to see if ticket exists robot.http("https://#{cwAPIURL}/v4_6_release/apis/3.0/service/tickets/#{cwticket}") .headers(Authorization: auth, Accept: 'application/json') .get() (err, res, body) -> data = JSON.parse(body) if res.statusCode == 200 robot.logger.debug "Ticket Link: #{data.id}!" robot.emit 'slack.attachment', message: msg.message content: title: "Ticket Link: #{data.id}!" title_link: "https://#{cwURL}/v4_6_release/services/system_io/Service/fv_sr100_request.rails?service_recid=#{data.id}&companyName=#{cwCompanyID}" color: "#0A53A1" fallback: "Ticket Link: #{data.id}!" #listen for ticket watch requests robot.hear /watch ticket \b(\d{3,6})\b/i, (msg) -> unless not configError()? msg.send "#{configError()}" return robot.http("https://#{cwAPIURL}/v4_6_release/apis/3.0/service/tickets/#{msg.match[1]}") .headers(Authorization: auth, Accept: 'application/json') .get() (err, res, body) -> data = JSON.parse(body) if res.statusCode == 200 #add to watch list CWTicketWatchers.add data.id,msg.message.user.name #notify user of addition robot.logger.debug "Ticket watch set for #{data.id}" robot.emit 'slack.attachment', message: msg.message channel: msg.envelope.user.name content: title: "Ticket watch success" color: "good" fallback: "Watch set for ticket: #{data.id}" text: "Watch set for ticket: #{data.id}" else robot.logger.debug "Ticket #{msg.match[1]} not in CW" robot.emit 'slack.attachment', message: msg.message channel: msg.envelope.user.name content: title: "Ticket watch failure" color: "danger" fallback: "Ticket watch failure" text: "Invalid ticket for watch: #{msg.match[1]}.\nPlease verify that this is the correct ticket number." #get a list of listeners for a given ticket robot.hear /who is watching \b(\d{3,6})\b/i, (msg) -> cwTicket = msg.match[1] ticketWatchers = CWTicketWatchers.watchers(cwTicket) if ticketWatchers.length > 0 robot.logger.debug "#{ticketWatchers.toString()} are watching #{cwTicket}" robot.emit 'slack.attachment', message: msg.message channel: msg.envelope.user.name content: title: "Users watching ticket #{cwTicket}" text: "#{ticketWatchers.toString()} are watching #{cwTicket}" fallback: "#{ticketWatchers.toString()} are watching #{cwTicket}" color: "#439FE0" else robot.logger.debug "Can't find anyone watching #{cwTicket}" msg.send "I don't recall anyone watching #{cwTicket}" #listen for ticket ignore requests robot.hear /ignore ticket \b(\d{3,6})\b/i, (msg) -> unless not configError()? msg.send "#{configError()}" return cwticket = msg.match[1] CWTicketWatchers.remove cwticket, msg.message.user.name robot.logger.debug "Ticket #{cwticket} ignored" robot.emit 'slack.attachment', message: msg.message channel: msg.envelope.user.name content: title: "Ignoring Ticket" color: "good" fallback: "Now ignoring: #{cwticket}" text: "You are no longer watching ticket: #{cwticket}" #clear all followers for a ticket robot.hear /clear all watchers for ticket \b(\d{3,6})\b/i, (msg) -> unless not configError()? msg.send "#{configError()}" return cwticket = msg.match[1] CWTicketWatchers.removeAll cwticket robot.logger.debug "Removed all watchers for ticket #{cwticket}" robot.emit 'slack.attachment', message: msg.message channel: msg.envelope.user.name content: title: "Clear Watchers" color: "info" fallback: "All watchers cleared for ticket #{cwticket}" text: "All watchers cleared for ticket #{cwticket}" #Listen for callbacks with watched tickets robot.router.post '/hubot/cwticket', (req, res) -> if req.query.id? watchers = CWTicketWatchers.watchers req.query.id if watchers.length == 0 return for user in watchers robot.send {room: "#{user}"}, "#{req.query.id} was updated" res.end()
[ { "context": "mfabrik GmbH\n * MIT Licence\n * https://github.com/programmfabrik/coffeescript-ui, http://www.coffeescript-ui.org\n#", "end": 166, "score": 0.9716353416442871, "start": 152, "tag": "USERNAME", "value": "programmfabrik" }, { "context": "t != true\n\t\t\t@append(@_right,...
src/elements/Button/Button.coffee
programmfabrik/coffeescript-ui
10
### * coffeescript-ui - Coffeescript User Interface System (CUI) * Copyright (c) 2013 - 2016 Programmfabrik GmbH * MIT Licence * https://github.com/programmfabrik/coffeescript-ui, http://www.coffeescript-ui.org ### # Base class for all Buttons. Yeahhhh # #TODO document this in class... # role: ui-role # disabled: true, false # # #Button.DOM: the actual button object #Button.disable: disable button #Button.enable: enable button CUI.Template.loadTemplateText(require('./Button.html')); CUI.Template.loadTemplateText(require('./Button_ng.html')); class CUI.Button extends CUI.DOMElement @defaults: confirm_ok: "Ok" confirm_icon: "question" confirm_cancel: "Cancel" confirm_title: "Confirmation" disabled_css_class: "cui-disabled" loading_css_class: "cui-loading" active_css_class: "cui-active" arrow_down: "fa-angle-down" arrow_right: "fa-angle-right" # Construct a new CUI.Button, legacy # # @param [Object] options for button creation # @option options [String] size controls the size of the button. # "mini", small button. # "normal", medium size button. # "big", big sized button. # "bigger", bigger sized button. # @option options [String] appearance controls the style or appearance of the button. # "flat", button has no border and inherits its background color from its parent div. # "normal", standard button with border and its own background color. # "link", standard button without border and a underlined text. # "important", emphasized button , to show the user that the button is important. constructor: (opts) -> super(opts) if @_tooltip if @_tooltip.text or @_tooltip.content @__tooltipOpts = @_tooltip @__has_left = true @__has_right = true @__has_center = true tname = @getTemplateName() # getTemplateName, also sets has_left / has_right @__box = new CUI.Template name: tname map: left: if @__has_left then ".cui-button-left" else undefined center: if @__has_center then ".cui-button-center" else undefined visual: if CUI.__ng__ then ".cui-button-visual" else undefined right: if @__has_right then ".cui-button-right" else undefined @registerTemplate(@__box) @__active = null @__disabled = false @__loading = false @__hidden = false @__txt = null @addClass("cui-button-button") if CUI.util.isString(@__tooltipOpts?.text) @setAria("label", @__tooltipOpts?.text) @__hasAriaLabel = true else @__hasAriaLabel = false CUI.dom.setAttribute(@DOM, "tabindex", @_tabindex) if @_appearance == "flat" and not @_attr?.title CUI.dom.setAttribute(@DOM, "title", @_text) if not @_attr?.role CUI.dom.setAttribute(@DOM, "role", @_role) if not @_left or @_left == true if @_icon CUI.util.assert(CUI.util.isUndef(@_icon_left), "new #{@__cls}", "opts.icon conflicts with opts.icon_left", opts: @opts) icon_left = @_icon else icon_left = @_icon_left if icon_left CUI.util.assert(not @_icon_active and not @_icon_inactive, "new CUI.Button", "opts.icon_active or opts.icon_inactive cannot be set together with opts.icon or opts.icon_left", opts: @opts) @setIcon(icon_left) else @append(@_left, "left") if not @_right if @_icon_right @setIconRight(@_icon_right) else if @_menu and @_icon_right != false @addClass("cui-button--has-caret") if @_menu_parent @setIconRight(CUI.defaults.class.Button.defaults.arrow_right) else @setIconRight(CUI.defaults.class.Button.defaults.arrow_down) else if @_right != true @append(@_right, "right") @setSize(@_size) if @_appearance @addClass("cui-button-appearance-"+@_appearance) if @_primary @addClass("cui-button--primary") if @_secondary and not @_primary @addClass("cui-button--secondary") if @_class @addClass(@_class) if @_center @append(@_center, "center") else if @_text @setText(@_text) if @_disabled and (@_disabled == true or @_disabled.call(@, @)) @disable() if @_loading and (@_loading == true or @_loading.call(@, @)) @setLoading(true) if @_hidden and (@_hidden == true or @_hidden.call(@, @)) @hide() if @_active == true @activate(initial_activate: true) else if @_active == false or @_switch #switch default is active=false TODO initial_activate: true == bug!? @deactivate(initial_activate: true) else @__setState() @__radio_allow_null = @_radio_allow_null if @_radio CUI.util.assert(CUI.util.isUndef(@_switch), "new CUI.Button", "opts.switch conflicts with opts.radio.", opts: @opts) if @_radio == true @__radio = "radio--"+@getUniqueId() else @__radio = @_radio else if not CUI.util.isNull(@_switch) @__radio = "switch--"+@getUniqueId() @__radio_allow_null = true if @__radio CUI.util.assert(not @_attr?.radio, "new CUI.Button", "opts.radio conflicts with opts.attr.radio", opts: @opts) CUI.dom.setAttribute(@DOM, "radio", @__radio) @setGroup(@_group) if @_menu @__menu_opts = {} itemList_opts = {} # rescue options for menu and separate them # from itemlist for k, v of @_menu switch k when "onShow", "onHide" continue when "class", "backdrop", "onPosition", "placement", "placements", "pointer" @__menu_opts[k] = v else itemList_opts[k] = v if not CUI.util.isEmpty(@_class) if @__menu_opts.class @__menu_opts.class += " "+@_class else @__menu_opts.class = @_class if @_menu.itemList @__menu_opts.itemList = @_menu.itemList else @__menu_opts.itemList = itemList_opts @__menu_opts.element = @ if not @__menu_opts.hasOwnProperty("use_element_width_as_min_width") if not @_menu_parent @__menu_opts.use_element_width_as_min_width = true @__menu_opts.onHide = => @_menu.onHide?() @__menu_opts.onShow = => @_menu.onShow?() if not @__menu_opts.hasOwnProperty("backdrop") @__menu_opts.backdrop = policy: "click-thru" if not @__menu_opts.backdrop.hasOwnProperty("blur") and @_menu_parent?.getOpt("backdrop")?.blur if @_menu_on_hover @__menu_opts.backdrop = policy: "click-thru" blur: true else @__menu_opts.backdrop.blur = true if @_menu_parent @__menu_opts.parent_menu = @_menu_parent CUI.Events.listen type: "keydown" node: @DOM capture: true call: (ev) => if ev.hasModifierKey() return if ev.keyCode() in [13, 32] #space / return @onClickAction(ev) ev.stop() return if ev.keyCode() == 27 # blur button @DOM.blur() ev.stop() return el = null right = => el = CUI.dom.findNextVisibleElement(@DOM, "[tabindex]") left = => el = CUI.dom.findPreviousVisibleElement(@DOM, "[tabindex]") switch ev.keyCode() when 39 # right cursor right() when 40 # down cursor right() when 37 # left cursor left() when 38 # up cursor left() if el el.focus() ev.stop() return CUI.Events.listen type: CUI.Button.clickTypesPrevent[@_click_type] node: @DOM call: (ev) => ev.preventDefault() # ev.stopPropagation() return CUI.Events.listen type: CUI.Button.clickTypes[@_click_type] node: @DOM call: (ev) => if CUI.globalDrag # ev.stop() return if ev.getButton() != 0 and not ev.getType().startsWith("touch") # ev.stop() return ev.stopPropagation() @onClickAction(ev) return if @_menu_on_hover CUI.Button.menu_timeout = null menu_stop_hide = => if not CUI.Button.menu_timeout return CUI.clearTimeout(CUI.Button.menu_timeout) CUI.Button.menu_timeout = null menu_start_hide = (ev, ms=700) => menu_stop_hide() # we set a timeout, if during the time # the focus enters the menu, we cancel the timeout CUI.Button.menu_timeout = CUI.setTimeout ms: ms call: => @getMenu().hide(ev) if @_menu_on_hover or @__tooltipOpts or @_onMouseenter CUI.Events.listen type: "mouseenter" node: @DOM call: (ev) => if CUI.globalDrag return @_onMouseenter?(ev) if ev.isImmediatePropagationStopped() return if @__tooltipOpts @__initTooltip() @getTooltip().showTimeout().start() if @_menu_on_hover menu = @getMenu() menu_stop_hide() if not @__disabled and menu.hasItems(ev) menu_shown = CUI.dom.data(CUI.dom.find(".cui-button--hover-menu")[0], "element") if menu_shown and menu_shown != menu menu_shown.hide(ev) CUI.dom.addClass(menu.DOM, "cui-button--hover-menu") CUI.Events.ignore instance: @ node: menu CUI.Events.listen type: "mouseenter" node: menu instance: @ only_once: true call: => menu_stop_hide() CUI.Events.listen type: "mouseleave" node: menu instance: @ only_once: true call: => menu_start_hide(ev) menu.show(ev) return CUI.Events.listen type: "mouseleave" node: @DOM call: (ev) => # @__prevent_btn_click = false if CUI.globalDrag return @_onMouseleave?(ev) if @_menu_on_hover menu_start_hide(ev, 100) return setSize: (size) -> remove = [] for cls in @DOM.classList if cls.startsWith("cui-button-size") remove.push(cls) for cls in remove @DOM.classList.remove(cls) if size @DOM.classList.add("cui-button-size-"+size) @ onClickAction: (ev) -> if @__disabled # or ev.button != 0 ev.preventDefault() return @getTooltip()?.hide(ev) if @__radio if @__radio_allow_null @toggle({}, ev) else @activate({}, ev) if @hasMenu() and # not (ev.ctrlKey or ev.shiftKey or ev.altKey or ev.metaKey) and not @_menu_on_hover and @getMenu().hasItems(ev) @getMenu().show(ev) # in some contexts (like FileUploadButton), this # is necessary, so we stop the file upload # to open # ev.preventDefault() return if ev.isImmediatePropagationStopped() return CUI.Events.trigger type: "cui-button-click" node: @ info: event: ev if ev.isImmediatePropagationStopped() or not @_onClick return @_onClick.call(@, ev, @) initOpts: -> super() @addOpts tabindex: default: 0 check: (v) -> CUI.util.isInteger(v) or v == false # legacy, do not use size: check: ["mini","normal","big","bigger"] # legacy, do not use # link: use ButtonHref instead; important: use "primary: true" instead appearance: check: ["link","flat","normal","important","transparent-border"] primary: mandatory: true default: false check: Boolean secondary: check: Boolean onClick: check: Function click_type: default: "click" # "touchend" mandatory: true check: (v) -> !!CUI.Button.clickTypes[v] text: check: String tooltip: check: "PlainObject" disabled: default: false check: (v) -> CUI.util.isBoolean(v) or CUI.util.isFunction(v) loading: default: false check: (v) -> CUI.util.isBoolean(v) or CUI.util.isFunction(v) class: check: String active_css_class: default: CUI.defaults.class.Button.defaults.active_css_class check: String left: check: (v) -> if v == true return true (CUI.util.isElement(v) or v instanceof CUI.Element or CUI.util.isString(v)) and not @_icon and not @_icon_left and not @_icon_active and not @_icon_inactive right: check: (v) -> (v == true or CUI.util.isContent(v)) and not @_icon_right center: check: (v) -> CUI.util.isContent(v) or CUI.util.isString(v) icon: check: (v) -> v instanceof CUI.Icon or CUI.util.isString(v) icon_left: check: (v) -> v instanceof CUI.Icon or CUI.util.isString(v) icon_right: check: (v) -> v instanceof CUI.Icon or CUI.util.isString(v) or v == false icon_active: check: (v) -> v instanceof CUI.Icon or CUI.util.isString(v) icon_inactive: check: (v) -> v instanceof CUI.Icon or CUI.util.isString(v) text_active: check: String text_inactive: check: String value: {} name: check: String hidden: check: (v) -> CUI.util.isBoolean(v) or CUI.util.isFunction(v) menu: check: "PlainObject" menu_on_hover: check: Boolean menu_parent: check: CUI.Menu onActivate: check: Function onDeactivate: check: Function onMouseenter: check: Function onMouseleave: check: Function # if set, this button belongs # to a group of buttons # on click, the active state of # this button will be set and unset # on the others radio: check: (v) -> CUI.util.isString(v) or v == true # whether to allow de-select # on radio buttons radio_allow_null: check: Boolean switch: check: Boolean active: check: Boolean # set to false to skip running onActivate and onDeactivate # callbacks on initial activate/deactivate when the button is # created activate_initial: default: true check: Boolean #group can be used for buttonbars to specify a group css style group: check: String role: default: "button" mandatory: true check: String # return icon for string __getIcon: (icon) -> if not icon null else if icon instanceof CUI.Icon icon else new CUI.Icon(icon: icon) readOpts: -> if @opts.switch CUI.util.assert(CUI.util.isUndef(@opts.radio_allow_null), "new CUI.Button", "opts.switch cannot be used together with opts.radio_allow_null", opts: @opts) super() if @_left CUI.util.assert(@_left == true or not (@_icon_active or @_icon_inactive or @_icon), "new CUI.Button", "opts.left != true cannot be used togeter with opts.icon*", opts: @opts) getCenter: -> return @__box.map.center; __getTemplateName: -> if @_icon or @_icon_left or @_icon_active or @_icon_inactive or @_left @__has_left = true else @__has_left = false if @_icon_right or (@_menu and @_icon_right != false) or @_right @__has_right = true else @__has_right = false if @__has_left and CUI.util.isUndef(@_text) and CUI.util.isUndef(@_center) and CUI.util.isUndef(@_text_active) and CUI.util.isUndef(@_text_inactive) and CUI.__ng__ @__has_center = false if @__has_left and @__has_right return "button" else if @__has_left if @__has_center return "button-left-center" else return "button-left" else if @__has_right return "button-center-right" else return "button-center" getTemplateName: -> if CUI.__ng__ @__getTemplateName() + "-ng" else @__getTemplateName() getValue: -> @_value getElementForLayer: -> return @__box.map.visual getRadioButtons: -> if not @__radio return [] @__getButtons("radio", @__radio) getGroupButtons: -> if not @getGroup() return [] @__getButtons("button-group", @getGroup()) # returns other buttons __getButtons: (key, value) -> parents = CUI.dom.parents(@DOM, ".cui-buttonbar,.cui-form-table,.cui-item-list-body,.cui-layer") if parents.length == 0 # buttons are not grouped by anything, so we # have no other buttons, so we use the top level element parents = CUI.dom.parents(@DOM) if parents.length > 0 docElem = parents[parents.length-1] else return [] (CUI.dom.data(c, "element") for c in CUI.dom.matchSelector(docElem, ".cui-button[#{key}=\"#{value}\"]")) hasMenu: -> !!@__menu_opts hasLeft: -> @__has_left getMenu: -> if not @hasMenu() return if @__menu @__menu else @__menu = new CUI.Menu(@__menu_opts) menuSetActiveIdx: (idx) -> if @__menu @__menu.setActiveIdx(idx) else @__menu_opts.itemList.active_item_idx = idx @ getMenuRootButton: -> if @_menu_parent return @_menu_parent.getButton()?.getMenuRootButton() else if @hasMenu() return @ else null #TODO rename to toggleActiveState toggle: (flags={}, event) -> @setActive(not @__active, flags, event) setActive: (active, flags={}, event) -> if active @activate(flags, event) else @deactivate(flags, event) __callOnGroup: (call, flags, event) -> group = @getGroup() if not group or not event?.hasModifierKey() or flags.ignore_ctrl return flags.ignore_ctrl = true if not event.altKey() started = true else started = false for btn in @getGroupButtons() if btn == @ started = true continue if not started continue btn[call](flags, event) return activate: (flags={}, event) -> # console.error "activate", flags, @getUniqueId(), @__active, @_activate_initial activate = => @addClass(@_active_css_class) @setAria("pressed", true) @__setState() @__callOnGroup("activate", flags, event) return if @_activate_initial == false and flags.initial_activate @__active = true activate() return @ if @__active == true and CUI.util.isEmptyObject(flags) return @ if @__radio _flags = prior_activate: @ initial_activate: flags.initial_activate for btn, idx in @getRadioButtons() if btn == @ or not btn.isActive() continue # don't send the event here, since this happens # code driven btn.deactivate(_flags) @__active = true ret = @_onActivate?(@, flags, event) if CUI.util.isPromise(ret) ret.done(activate).fail => @__active = false return ret activate() @ deactivate: (flags={}, event) -> # console.error "deactivate", flags, @getUniqueId(), @__active, @_activate_initial, @_icon_inactive deactivate = => @removeClass(@_active_css_class) @setAria("pressed", false) @__setState() @__callOnGroup("deactivate", flags, event) return if @_activate_initial == false and flags.initial_activate @__active = false deactivate() return @ if @__active == false and CUI.util.isEmptyObject(flags) return @ @__active = false ret = @_onDeactivate?(@, flags, event) if CUI.util.isPromise(ret) ret.done(deactivate).fail => @__active = true return ret deactivate() @ setIconRight: (icon=null) -> @setIcon(icon, "right") setIcon: (icon=null, _key="left") -> key = "__icon_"+_key if icon == "" @[key] = "" else @[key] = @__getIcon(icon) CUI.util.assert(@[key] == null or @[key] == "" or @[key] instanceof CUI.Icon, "CUI.Button.setIcon", "icon needs to be instance of Icon", icon: icon) if @[key] == null @empty(_key) else if @[key] == "" @replace(CUI.dom.element("SPAN"), _key) else @replace(@[key], _key) @ startSpinner: -> CUI.util.assert(@__has_left, "CUI.Button.startSpinner", "No space for Icon found, make sure the Button was created with opts.left set.", opts: @opts) if @__hasSpinner return @__iconBeforeSpinner = @getIcon() @__hasSpinner = true @setIcon("spinner") @ stopSpinner: -> @setIcon(@__iconBeforeSpinner) @__hasSpinner = false @__iconBeforeSpinner = null @ getIcon: -> @__icon_left getIconRight: -> @__icon_right __setState: -> @__setIconState() @__setTextState() __setIconState: -> if not (@_icon_active or @_icon_inactive) return @ if @isActive() if not @_icon_active @setIcon("") else @setIcon(@_icon_active) else if not @_icon_inactive @setIcon("") else @setIcon(@_icon_inactive) @ __setTextState: -> if not (@_text_active or @_text_inactive) return @ if @isActive() if not CUI.util.isNull(@_text_active) @setText(@_text_active) else if not CUI.util.isNull(@_text_inactive) @setText(@_text_inactive) @ isActive: -> !!@__active isDisabled: -> @__disabled isEnabled: -> not @__disabled setEnabled: (enabled) -> if enabled @enable() else @disable() setLoading: (on_off) -> if on_off CUI.dom.addClass(@DOM, CUI.defaults.class.Button.defaults.loading_css_class) @__loading = true else CUI.dom.removeClass(@DOM, CUI.defaults.class.Button.defaults.loading_css_class) @__loading = false isLoading: -> @__loading disable: -> CUI.dom.addClass(@DOM, CUI.defaults.class.Button.defaults.disabled_css_class) CUI.dom.removeAttribute(@DOM, "tabindex") @__disabled = true @ enable: -> CUI.dom.removeClass(@DOM, CUI.defaults.class.Button.defaults.disabled_css_class) CUI.dom.setAttribute(@DOM, "tabindex", @_tabindex) @__disabled = false @ setText: (@__txt) -> if CUI.util.isEmpty(@__txt) @__txt = '' span = CUI.dom.text(@__txt) if not @__hasAriaLabel span.id = "button-text-"+@getUniqueId() @setAria("labelledby", span.id) @replace(span, "center") setTextMaxChars: (max_chars) -> CUI.dom.setAttribute(@getCenter().firstChild, "data-max-chars", max_chars) getText: -> @__txt getGroup: -> @__group setGroup: (@__group) -> if @__group CUI.dom.setAttribute(@DOM, "button-group", @__group) else CUI.dom.removeAttribute(@DOM, "button-group") __initTooltip: -> if @__tooltip and not @__tooltip.isDestroyed() return @ tt_opts = CUI.util.copyObject(@__tooltipOpts) tt_opts.element ?= @DOM # make sure the tooltip does not register any listeners for k in ["on_hover", "on_click"] CUI.util.assert(not tt_opts.hasOwnProperty(k), "CUI.Button.__initTooltip", "opts.tooltip cannot contain #{k}.", opts: @opts) tt_opts[k] = false @__tooltip = new CUI.Tooltip(tt_opts) @ getTooltip: -> @__tooltip isShown: -> not @isHidden() isHidden: -> @__hidden destroy: -> # console.debug "destroying button", @__uniqueId, @getText() @__menu?.destroy() @__menu = null @__tooltip?.destroy() @__tooltip = null super() show: -> @__hidden = false CUI.dom.removeClass(@DOM, "cui-button-hidden") CUI.dom.showElement(@DOM) CUI.Events.trigger type: "show" node: @DOM hide: -> @__hidden = true CUI.dom.addClass(@DOM, "cui-button-hidden") CUI.dom.hideElement(@DOM) CUI.Events.trigger type: "hide" node: @DOM @clickTypes: click: ['click'] mouseup: ['mouseup'] dblclick: ['dblclick'] @clickTypesPrevent: click: ['dblclick', 'mousedown'] mouseup: ['mouseup', 'mousedown'] dblclick: ['click', 'mousedown'] CUI.Events.registerEvent type: ["show", "hide", "cui-button-click"] bubble: true CUI.defaults.class.Button = CUI.Button
20163
### * coffeescript-ui - Coffeescript User Interface System (CUI) * Copyright (c) 2013 - 2016 Programmfabrik GmbH * MIT Licence * https://github.com/programmfabrik/coffeescript-ui, http://www.coffeescript-ui.org ### # Base class for all Buttons. Yeahhhh # #TODO document this in class... # role: ui-role # disabled: true, false # # #Button.DOM: the actual button object #Button.disable: disable button #Button.enable: enable button CUI.Template.loadTemplateText(require('./Button.html')); CUI.Template.loadTemplateText(require('./Button_ng.html')); class CUI.Button extends CUI.DOMElement @defaults: confirm_ok: "Ok" confirm_icon: "question" confirm_cancel: "Cancel" confirm_title: "Confirmation" disabled_css_class: "cui-disabled" loading_css_class: "cui-loading" active_css_class: "cui-active" arrow_down: "fa-angle-down" arrow_right: "fa-angle-right" # Construct a new CUI.Button, legacy # # @param [Object] options for button creation # @option options [String] size controls the size of the button. # "mini", small button. # "normal", medium size button. # "big", big sized button. # "bigger", bigger sized button. # @option options [String] appearance controls the style or appearance of the button. # "flat", button has no border and inherits its background color from its parent div. # "normal", standard button with border and its own background color. # "link", standard button without border and a underlined text. # "important", emphasized button , to show the user that the button is important. constructor: (opts) -> super(opts) if @_tooltip if @_tooltip.text or @_tooltip.content @__tooltipOpts = @_tooltip @__has_left = true @__has_right = true @__has_center = true tname = @getTemplateName() # getTemplateName, also sets has_left / has_right @__box = new CUI.Template name: tname map: left: if @__has_left then ".cui-button-left" else undefined center: if @__has_center then ".cui-button-center" else undefined visual: if CUI.__ng__ then ".cui-button-visual" else undefined right: if @__has_right then ".cui-button-right" else undefined @registerTemplate(@__box) @__active = null @__disabled = false @__loading = false @__hidden = false @__txt = null @addClass("cui-button-button") if CUI.util.isString(@__tooltipOpts?.text) @setAria("label", @__tooltipOpts?.text) @__hasAriaLabel = true else @__hasAriaLabel = false CUI.dom.setAttribute(@DOM, "tabindex", @_tabindex) if @_appearance == "flat" and not @_attr?.title CUI.dom.setAttribute(@DOM, "title", @_text) if not @_attr?.role CUI.dom.setAttribute(@DOM, "role", @_role) if not @_left or @_left == true if @_icon CUI.util.assert(CUI.util.isUndef(@_icon_left), "new #{@__cls}", "opts.icon conflicts with opts.icon_left", opts: @opts) icon_left = @_icon else icon_left = @_icon_left if icon_left CUI.util.assert(not @_icon_active and not @_icon_inactive, "new CUI.Button", "opts.icon_active or opts.icon_inactive cannot be set together with opts.icon or opts.icon_left", opts: @opts) @setIcon(icon_left) else @append(@_left, "left") if not @_right if @_icon_right @setIconRight(@_icon_right) else if @_menu and @_icon_right != false @addClass("cui-button--has-caret") if @_menu_parent @setIconRight(CUI.defaults.class.Button.defaults.arrow_right) else @setIconRight(CUI.defaults.class.Button.defaults.arrow_down) else if @_right != true @append(@_right, "right") @setSize(@_size) if @_appearance @addClass("cui-button-appearance-"+@_appearance) if @_primary @addClass("cui-button--primary") if @_secondary and not @_primary @addClass("cui-button--secondary") if @_class @addClass(@_class) if @_center @append(@_center, "center") else if @_text @setText(@_text) if @_disabled and (@_disabled == true or @_disabled.call(@, @)) @disable() if @_loading and (@_loading == true or @_loading.call(@, @)) @setLoading(true) if @_hidden and (@_hidden == true or @_hidden.call(@, @)) @hide() if @_active == true @activate(initial_activate: true) else if @_active == false or @_switch #switch default is active=false TODO initial_activate: true == bug!? @deactivate(initial_activate: true) else @__setState() @__radio_allow_null = @_radio_allow_null if @_radio CUI.util.assert(CUI.util.isUndef(@_switch), "new CUI.Button", "opts.switch conflicts with opts.radio.", opts: @opts) if @_radio == true @__radio = "radio--"+@getUniqueId() else @__radio = @_radio else if not CUI.util.isNull(@_switch) @__radio = "switch--"+@getUniqueId() @__radio_allow_null = true if @__radio CUI.util.assert(not @_attr?.radio, "new CUI.Button", "opts.radio conflicts with opts.attr.radio", opts: @opts) CUI.dom.setAttribute(@DOM, "radio", @__radio) @setGroup(@_group) if @_menu @__menu_opts = {} itemList_opts = {} # rescue options for menu and separate them # from itemlist for k, v of @_menu switch k when "onShow", "onHide" continue when "class", "backdrop", "onPosition", "placement", "placements", "pointer" @__menu_opts[k] = v else itemList_opts[k] = v if not CUI.util.isEmpty(@_class) if @__menu_opts.class @__menu_opts.class += " "+@_class else @__menu_opts.class = @_class if @_menu.itemList @__menu_opts.itemList = @_menu.itemList else @__menu_opts.itemList = itemList_opts @__menu_opts.element = @ if not @__menu_opts.hasOwnProperty("use_element_width_as_min_width") if not @_menu_parent @__menu_opts.use_element_width_as_min_width = true @__menu_opts.onHide = => @_menu.onHide?() @__menu_opts.onShow = => @_menu.onShow?() if not @__menu_opts.hasOwnProperty("backdrop") @__menu_opts.backdrop = policy: "click-thru" if not @__menu_opts.backdrop.hasOwnProperty("blur") and @_menu_parent?.getOpt("backdrop")?.blur if @_menu_on_hover @__menu_opts.backdrop = policy: "click-thru" blur: true else @__menu_opts.backdrop.blur = true if @_menu_parent @__menu_opts.parent_menu = @_menu_parent CUI.Events.listen type: "keydown" node: @DOM capture: true call: (ev) => if ev.hasModifierKey() return if ev.keyCode() in [13, 32] #space / return @onClickAction(ev) ev.stop() return if ev.keyCode() == 27 # blur button @DOM.blur() ev.stop() return el = null right = => el = CUI.dom.findNextVisibleElement(@DOM, "[tabindex]") left = => el = CUI.dom.findPreviousVisibleElement(@DOM, "[tabindex]") switch ev.keyCode() when 39 # right cursor right() when 40 # down cursor right() when 37 # left cursor left() when 38 # up cursor left() if el el.focus() ev.stop() return CUI.Events.listen type: CUI.Button.clickTypesPrevent[@_click_type] node: @DOM call: (ev) => ev.preventDefault() # ev.stopPropagation() return CUI.Events.listen type: CUI.Button.clickTypes[@_click_type] node: @DOM call: (ev) => if CUI.globalDrag # ev.stop() return if ev.getButton() != 0 and not ev.getType().startsWith("touch") # ev.stop() return ev.stopPropagation() @onClickAction(ev) return if @_menu_on_hover CUI.Button.menu_timeout = null menu_stop_hide = => if not CUI.Button.menu_timeout return CUI.clearTimeout(CUI.Button.menu_timeout) CUI.Button.menu_timeout = null menu_start_hide = (ev, ms=700) => menu_stop_hide() # we set a timeout, if during the time # the focus enters the menu, we cancel the timeout CUI.Button.menu_timeout = CUI.setTimeout ms: ms call: => @getMenu().hide(ev) if @_menu_on_hover or @__tooltipOpts or @_onMouseenter CUI.Events.listen type: "mouseenter" node: @DOM call: (ev) => if CUI.globalDrag return @_onMouseenter?(ev) if ev.isImmediatePropagationStopped() return if @__tooltipOpts @__initTooltip() @getTooltip().showTimeout().start() if @_menu_on_hover menu = @getMenu() menu_stop_hide() if not @__disabled and menu.hasItems(ev) menu_shown = CUI.dom.data(CUI.dom.find(".cui-button--hover-menu")[0], "element") if menu_shown and menu_shown != menu menu_shown.hide(ev) CUI.dom.addClass(menu.DOM, "cui-button--hover-menu") CUI.Events.ignore instance: @ node: menu CUI.Events.listen type: "mouseenter" node: menu instance: @ only_once: true call: => menu_stop_hide() CUI.Events.listen type: "mouseleave" node: menu instance: @ only_once: true call: => menu_start_hide(ev) menu.show(ev) return CUI.Events.listen type: "mouseleave" node: @DOM call: (ev) => # @__prevent_btn_click = false if CUI.globalDrag return @_onMouseleave?(ev) if @_menu_on_hover menu_start_hide(ev, 100) return setSize: (size) -> remove = [] for cls in @DOM.classList if cls.startsWith("cui-button-size") remove.push(cls) for cls in remove @DOM.classList.remove(cls) if size @DOM.classList.add("cui-button-size-"+size) @ onClickAction: (ev) -> if @__disabled # or ev.button != 0 ev.preventDefault() return @getTooltip()?.hide(ev) if @__radio if @__radio_allow_null @toggle({}, ev) else @activate({}, ev) if @hasMenu() and # not (ev.ctrlKey or ev.shiftKey or ev.altKey or ev.metaKey) and not @_menu_on_hover and @getMenu().hasItems(ev) @getMenu().show(ev) # in some contexts (like FileUploadButton), this # is necessary, so we stop the file upload # to open # ev.preventDefault() return if ev.isImmediatePropagationStopped() return CUI.Events.trigger type: "cui-button-click" node: @ info: event: ev if ev.isImmediatePropagationStopped() or not @_onClick return @_onClick.call(@, ev, @) initOpts: -> super() @addOpts tabindex: default: 0 check: (v) -> CUI.util.isInteger(v) or v == false # legacy, do not use size: check: ["mini","normal","big","bigger"] # legacy, do not use # link: use ButtonHref instead; important: use "primary: true" instead appearance: check: ["link","flat","normal","important","transparent-border"] primary: mandatory: true default: false check: Boolean secondary: check: Boolean onClick: check: Function click_type: default: "click" # "touchend" mandatory: true check: (v) -> !!CUI.Button.clickTypes[v] text: check: String tooltip: check: "PlainObject" disabled: default: false check: (v) -> CUI.util.isBoolean(v) or CUI.util.isFunction(v) loading: default: false check: (v) -> CUI.util.isBoolean(v) or CUI.util.isFunction(v) class: check: String active_css_class: default: CUI.defaults.class.Button.defaults.active_css_class check: String left: check: (v) -> if v == true return true (CUI.util.isElement(v) or v instanceof CUI.Element or CUI.util.isString(v)) and not @_icon and not @_icon_left and not @_icon_active and not @_icon_inactive right: check: (v) -> (v == true or CUI.util.isContent(v)) and not @_icon_right center: check: (v) -> CUI.util.isContent(v) or CUI.util.isString(v) icon: check: (v) -> v instanceof CUI.Icon or CUI.util.isString(v) icon_left: check: (v) -> v instanceof CUI.Icon or CUI.util.isString(v) icon_right: check: (v) -> v instanceof CUI.Icon or CUI.util.isString(v) or v == false icon_active: check: (v) -> v instanceof CUI.Icon or CUI.util.isString(v) icon_inactive: check: (v) -> v instanceof CUI.Icon or CUI.util.isString(v) text_active: check: String text_inactive: check: String value: {} name: check: String hidden: check: (v) -> CUI.util.isBoolean(v) or CUI.util.isFunction(v) menu: check: "PlainObject" menu_on_hover: check: Boolean menu_parent: check: CUI.Menu onActivate: check: Function onDeactivate: check: Function onMouseenter: check: Function onMouseleave: check: Function # if set, this button belongs # to a group of buttons # on click, the active state of # this button will be set and unset # on the others radio: check: (v) -> CUI.util.isString(v) or v == true # whether to allow de-select # on radio buttons radio_allow_null: check: Boolean switch: check: Boolean active: check: Boolean # set to false to skip running onActivate and onDeactivate # callbacks on initial activate/deactivate when the button is # created activate_initial: default: true check: Boolean #group can be used for buttonbars to specify a group css style group: check: String role: default: "button" mandatory: true check: String # return icon for string __getIcon: (icon) -> if not icon null else if icon instanceof CUI.Icon icon else new CUI.Icon(icon: icon) readOpts: -> if @opts.switch CUI.util.assert(CUI.util.isUndef(@opts.radio_allow_null), "new CUI.Button", "opts.switch cannot be used together with opts.radio_allow_null", opts: @opts) super() if @_left CUI.util.assert(@_left == true or not (@_icon_active or @_icon_inactive or @_icon), "new CUI.Button", "opts.left != true cannot be used togeter with opts.icon*", opts: @opts) getCenter: -> return @__box.map.center; __getTemplateName: -> if @_icon or @_icon_left or @_icon_active or @_icon_inactive or @_left @__has_left = true else @__has_left = false if @_icon_right or (@_menu and @_icon_right != false) or @_right @__has_right = true else @__has_right = false if @__has_left and CUI.util.isUndef(@_text) and CUI.util.isUndef(@_center) and CUI.util.isUndef(@_text_active) and CUI.util.isUndef(@_text_inactive) and CUI.__ng__ @__has_center = false if @__has_left and @__has_right return "button" else if @__has_left if @__has_center return "button-left-center" else return "button-left" else if @__has_right return "button-center-right" else return "button-center" getTemplateName: -> if CUI.__ng__ @__getTemplateName() + "-ng" else @__getTemplateName() getValue: -> @_value getElementForLayer: -> return @__box.map.visual getRadioButtons: -> if not @__radio return [] @__getButtons("radio", @__radio) getGroupButtons: -> if not @getGroup() return [] @__getButtons("button-group", @getGroup()) # returns other buttons __getButtons: (key, value) -> parents = CUI.dom.parents(@DOM, ".cui-buttonbar,.cui-form-table,.cui-item-list-body,.cui-layer") if parents.length == 0 # buttons are not grouped by anything, so we # have no other buttons, so we use the top level element parents = CUI.dom.parents(@DOM) if parents.length > 0 docElem = parents[parents.length-1] else return [] (CUI.dom.data(c, "element") for c in CUI.dom.matchSelector(docElem, ".cui-button[#{key}=\"#{value}\"]")) hasMenu: -> !!@__menu_opts hasLeft: -> @__has_left getMenu: -> if not @hasMenu() return if @__menu @__menu else @__menu = new CUI.Menu(@__menu_opts) menuSetActiveIdx: (idx) -> if @__menu @__menu.setActiveIdx(idx) else @__menu_opts.itemList.active_item_idx = idx @ getMenuRootButton: -> if @_menu_parent return @_menu_parent.getButton()?.getMenuRootButton() else if @hasMenu() return @ else null #TODO rename to toggleActiveState toggle: (flags={}, event) -> @setActive(not @__active, flags, event) setActive: (active, flags={}, event) -> if active @activate(flags, event) else @deactivate(flags, event) __callOnGroup: (call, flags, event) -> group = @getGroup() if not group or not event?.hasModifierKey() or flags.ignore_ctrl return flags.ignore_ctrl = true if not event.altKey() started = true else started = false for btn in @getGroupButtons() if btn == @ started = true continue if not started continue btn[call](flags, event) return activate: (flags={}, event) -> # console.error "activate", flags, @getUniqueId(), @__active, @_activate_initial activate = => @addClass(@_active_css_class) @setAria("pressed", true) @__setState() @__callOnGroup("activate", flags, event) return if @_activate_initial == false and flags.initial_activate @__active = true activate() return @ if @__active == true and CUI.util.isEmptyObject(flags) return @ if @__radio _flags = prior_activate: @ initial_activate: flags.initial_activate for btn, idx in @getRadioButtons() if btn == @ or not btn.isActive() continue # don't send the event here, since this happens # code driven btn.deactivate(_flags) @__active = true ret = @_onActivate?(@, flags, event) if CUI.util.isPromise(ret) ret.done(activate).fail => @__active = false return ret activate() @ deactivate: (flags={}, event) -> # console.error "deactivate", flags, @getUniqueId(), @__active, @_activate_initial, @_icon_inactive deactivate = => @removeClass(@_active_css_class) @setAria("pressed", false) @__setState() @__callOnGroup("deactivate", flags, event) return if @_activate_initial == false and flags.initial_activate @__active = false deactivate() return @ if @__active == false and CUI.util.isEmptyObject(flags) return @ @__active = false ret = @_onDeactivate?(@, flags, event) if CUI.util.isPromise(ret) ret.done(deactivate).fail => @__active = true return ret deactivate() @ setIconRight: (icon=null) -> @setIcon(icon, "right") setIcon: (icon=null, _key="left") -> key = <KEY>_key if icon == "" @[key] = "" else @[key] = @__getIcon(icon) CUI.util.assert(@[key] == null or @[key] == "" or @[key] instanceof CUI.Icon, "CUI.Button.setIcon", "icon needs to be instance of Icon", icon: icon) if @[key] == null @empty(_key) else if @[key] == "" @replace(CUI.dom.element("SPAN"), _key) else @replace(@[key], _key) @ startSpinner: -> CUI.util.assert(@__has_left, "CUI.Button.startSpinner", "No space for Icon found, make sure the Button was created with opts.left set.", opts: @opts) if @__hasSpinner return @__iconBeforeSpinner = @getIcon() @__hasSpinner = true @setIcon("spinner") @ stopSpinner: -> @setIcon(@__iconBeforeSpinner) @__hasSpinner = false @__iconBeforeSpinner = null @ getIcon: -> @__icon_left getIconRight: -> @__icon_right __setState: -> @__setIconState() @__setTextState() __setIconState: -> if not (@_icon_active or @_icon_inactive) return @ if @isActive() if not @_icon_active @setIcon("") else @setIcon(@_icon_active) else if not @_icon_inactive @setIcon("") else @setIcon(@_icon_inactive) @ __setTextState: -> if not (@_text_active or @_text_inactive) return @ if @isActive() if not CUI.util.isNull(@_text_active) @setText(@_text_active) else if not CUI.util.isNull(@_text_inactive) @setText(@_text_inactive) @ isActive: -> !!@__active isDisabled: -> @__disabled isEnabled: -> not @__disabled setEnabled: (enabled) -> if enabled @enable() else @disable() setLoading: (on_off) -> if on_off CUI.dom.addClass(@DOM, CUI.defaults.class.Button.defaults.loading_css_class) @__loading = true else CUI.dom.removeClass(@DOM, CUI.defaults.class.Button.defaults.loading_css_class) @__loading = false isLoading: -> @__loading disable: -> CUI.dom.addClass(@DOM, CUI.defaults.class.Button.defaults.disabled_css_class) CUI.dom.removeAttribute(@DOM, "tabindex") @__disabled = true @ enable: -> CUI.dom.removeClass(@DOM, CUI.defaults.class.Button.defaults.disabled_css_class) CUI.dom.setAttribute(@DOM, "tabindex", @_tabindex) @__disabled = false @ setText: (@__txt) -> if CUI.util.isEmpty(@__txt) @__txt = '' span = CUI.dom.text(@__txt) if not @__hasAriaLabel span.id = "button-text-"+@getUniqueId() @setAria("labelledby", span.id) @replace(span, "center") setTextMaxChars: (max_chars) -> CUI.dom.setAttribute(@getCenter().firstChild, "data-max-chars", max_chars) getText: -> @__txt getGroup: -> @__group setGroup: (@__group) -> if @__group CUI.dom.setAttribute(@DOM, "button-group", @__group) else CUI.dom.removeAttribute(@DOM, "button-group") __initTooltip: -> if @__tooltip and not @__tooltip.isDestroyed() return @ tt_opts = CUI.util.copyObject(@__tooltipOpts) tt_opts.element ?= @DOM # make sure the tooltip does not register any listeners for k in ["on_hover", "on_click"] CUI.util.assert(not tt_opts.hasOwnProperty(k), "CUI.Button.__initTooltip", "opts.tooltip cannot contain #{k}.", opts: @opts) tt_opts[k] = false @__tooltip = new CUI.Tooltip(tt_opts) @ getTooltip: -> @__tooltip isShown: -> not @isHidden() isHidden: -> @__hidden destroy: -> # console.debug "destroying button", @__uniqueId, @getText() @__menu?.destroy() @__menu = null @__tooltip?.destroy() @__tooltip = null super() show: -> @__hidden = false CUI.dom.removeClass(@DOM, "cui-button-hidden") CUI.dom.showElement(@DOM) CUI.Events.trigger type: "show" node: @DOM hide: -> @__hidden = true CUI.dom.addClass(@DOM, "cui-button-hidden") CUI.dom.hideElement(@DOM) CUI.Events.trigger type: "hide" node: @DOM @clickTypes: click: ['click'] mouseup: ['mouseup'] dblclick: ['dblclick'] @clickTypesPrevent: click: ['dblclick', 'mousedown'] mouseup: ['mouseup', 'mousedown'] dblclick: ['click', 'mousedown'] CUI.Events.registerEvent type: ["show", "hide", "cui-button-click"] bubble: true CUI.defaults.class.Button = CUI.Button
true
### * coffeescript-ui - Coffeescript User Interface System (CUI) * Copyright (c) 2013 - 2016 Programmfabrik GmbH * MIT Licence * https://github.com/programmfabrik/coffeescript-ui, http://www.coffeescript-ui.org ### # Base class for all Buttons. Yeahhhh # #TODO document this in class... # role: ui-role # disabled: true, false # # #Button.DOM: the actual button object #Button.disable: disable button #Button.enable: enable button CUI.Template.loadTemplateText(require('./Button.html')); CUI.Template.loadTemplateText(require('./Button_ng.html')); class CUI.Button extends CUI.DOMElement @defaults: confirm_ok: "Ok" confirm_icon: "question" confirm_cancel: "Cancel" confirm_title: "Confirmation" disabled_css_class: "cui-disabled" loading_css_class: "cui-loading" active_css_class: "cui-active" arrow_down: "fa-angle-down" arrow_right: "fa-angle-right" # Construct a new CUI.Button, legacy # # @param [Object] options for button creation # @option options [String] size controls the size of the button. # "mini", small button. # "normal", medium size button. # "big", big sized button. # "bigger", bigger sized button. # @option options [String] appearance controls the style or appearance of the button. # "flat", button has no border and inherits its background color from its parent div. # "normal", standard button with border and its own background color. # "link", standard button without border and a underlined text. # "important", emphasized button , to show the user that the button is important. constructor: (opts) -> super(opts) if @_tooltip if @_tooltip.text or @_tooltip.content @__tooltipOpts = @_tooltip @__has_left = true @__has_right = true @__has_center = true tname = @getTemplateName() # getTemplateName, also sets has_left / has_right @__box = new CUI.Template name: tname map: left: if @__has_left then ".cui-button-left" else undefined center: if @__has_center then ".cui-button-center" else undefined visual: if CUI.__ng__ then ".cui-button-visual" else undefined right: if @__has_right then ".cui-button-right" else undefined @registerTemplate(@__box) @__active = null @__disabled = false @__loading = false @__hidden = false @__txt = null @addClass("cui-button-button") if CUI.util.isString(@__tooltipOpts?.text) @setAria("label", @__tooltipOpts?.text) @__hasAriaLabel = true else @__hasAriaLabel = false CUI.dom.setAttribute(@DOM, "tabindex", @_tabindex) if @_appearance == "flat" and not @_attr?.title CUI.dom.setAttribute(@DOM, "title", @_text) if not @_attr?.role CUI.dom.setAttribute(@DOM, "role", @_role) if not @_left or @_left == true if @_icon CUI.util.assert(CUI.util.isUndef(@_icon_left), "new #{@__cls}", "opts.icon conflicts with opts.icon_left", opts: @opts) icon_left = @_icon else icon_left = @_icon_left if icon_left CUI.util.assert(not @_icon_active and not @_icon_inactive, "new CUI.Button", "opts.icon_active or opts.icon_inactive cannot be set together with opts.icon or opts.icon_left", opts: @opts) @setIcon(icon_left) else @append(@_left, "left") if not @_right if @_icon_right @setIconRight(@_icon_right) else if @_menu and @_icon_right != false @addClass("cui-button--has-caret") if @_menu_parent @setIconRight(CUI.defaults.class.Button.defaults.arrow_right) else @setIconRight(CUI.defaults.class.Button.defaults.arrow_down) else if @_right != true @append(@_right, "right") @setSize(@_size) if @_appearance @addClass("cui-button-appearance-"+@_appearance) if @_primary @addClass("cui-button--primary") if @_secondary and not @_primary @addClass("cui-button--secondary") if @_class @addClass(@_class) if @_center @append(@_center, "center") else if @_text @setText(@_text) if @_disabled and (@_disabled == true or @_disabled.call(@, @)) @disable() if @_loading and (@_loading == true or @_loading.call(@, @)) @setLoading(true) if @_hidden and (@_hidden == true or @_hidden.call(@, @)) @hide() if @_active == true @activate(initial_activate: true) else if @_active == false or @_switch #switch default is active=false TODO initial_activate: true == bug!? @deactivate(initial_activate: true) else @__setState() @__radio_allow_null = @_radio_allow_null if @_radio CUI.util.assert(CUI.util.isUndef(@_switch), "new CUI.Button", "opts.switch conflicts with opts.radio.", opts: @opts) if @_radio == true @__radio = "radio--"+@getUniqueId() else @__radio = @_radio else if not CUI.util.isNull(@_switch) @__radio = "switch--"+@getUniqueId() @__radio_allow_null = true if @__radio CUI.util.assert(not @_attr?.radio, "new CUI.Button", "opts.radio conflicts with opts.attr.radio", opts: @opts) CUI.dom.setAttribute(@DOM, "radio", @__radio) @setGroup(@_group) if @_menu @__menu_opts = {} itemList_opts = {} # rescue options for menu and separate them # from itemlist for k, v of @_menu switch k when "onShow", "onHide" continue when "class", "backdrop", "onPosition", "placement", "placements", "pointer" @__menu_opts[k] = v else itemList_opts[k] = v if not CUI.util.isEmpty(@_class) if @__menu_opts.class @__menu_opts.class += " "+@_class else @__menu_opts.class = @_class if @_menu.itemList @__menu_opts.itemList = @_menu.itemList else @__menu_opts.itemList = itemList_opts @__menu_opts.element = @ if not @__menu_opts.hasOwnProperty("use_element_width_as_min_width") if not @_menu_parent @__menu_opts.use_element_width_as_min_width = true @__menu_opts.onHide = => @_menu.onHide?() @__menu_opts.onShow = => @_menu.onShow?() if not @__menu_opts.hasOwnProperty("backdrop") @__menu_opts.backdrop = policy: "click-thru" if not @__menu_opts.backdrop.hasOwnProperty("blur") and @_menu_parent?.getOpt("backdrop")?.blur if @_menu_on_hover @__menu_opts.backdrop = policy: "click-thru" blur: true else @__menu_opts.backdrop.blur = true if @_menu_parent @__menu_opts.parent_menu = @_menu_parent CUI.Events.listen type: "keydown" node: @DOM capture: true call: (ev) => if ev.hasModifierKey() return if ev.keyCode() in [13, 32] #space / return @onClickAction(ev) ev.stop() return if ev.keyCode() == 27 # blur button @DOM.blur() ev.stop() return el = null right = => el = CUI.dom.findNextVisibleElement(@DOM, "[tabindex]") left = => el = CUI.dom.findPreviousVisibleElement(@DOM, "[tabindex]") switch ev.keyCode() when 39 # right cursor right() when 40 # down cursor right() when 37 # left cursor left() when 38 # up cursor left() if el el.focus() ev.stop() return CUI.Events.listen type: CUI.Button.clickTypesPrevent[@_click_type] node: @DOM call: (ev) => ev.preventDefault() # ev.stopPropagation() return CUI.Events.listen type: CUI.Button.clickTypes[@_click_type] node: @DOM call: (ev) => if CUI.globalDrag # ev.stop() return if ev.getButton() != 0 and not ev.getType().startsWith("touch") # ev.stop() return ev.stopPropagation() @onClickAction(ev) return if @_menu_on_hover CUI.Button.menu_timeout = null menu_stop_hide = => if not CUI.Button.menu_timeout return CUI.clearTimeout(CUI.Button.menu_timeout) CUI.Button.menu_timeout = null menu_start_hide = (ev, ms=700) => menu_stop_hide() # we set a timeout, if during the time # the focus enters the menu, we cancel the timeout CUI.Button.menu_timeout = CUI.setTimeout ms: ms call: => @getMenu().hide(ev) if @_menu_on_hover or @__tooltipOpts or @_onMouseenter CUI.Events.listen type: "mouseenter" node: @DOM call: (ev) => if CUI.globalDrag return @_onMouseenter?(ev) if ev.isImmediatePropagationStopped() return if @__tooltipOpts @__initTooltip() @getTooltip().showTimeout().start() if @_menu_on_hover menu = @getMenu() menu_stop_hide() if not @__disabled and menu.hasItems(ev) menu_shown = CUI.dom.data(CUI.dom.find(".cui-button--hover-menu")[0], "element") if menu_shown and menu_shown != menu menu_shown.hide(ev) CUI.dom.addClass(menu.DOM, "cui-button--hover-menu") CUI.Events.ignore instance: @ node: menu CUI.Events.listen type: "mouseenter" node: menu instance: @ only_once: true call: => menu_stop_hide() CUI.Events.listen type: "mouseleave" node: menu instance: @ only_once: true call: => menu_start_hide(ev) menu.show(ev) return CUI.Events.listen type: "mouseleave" node: @DOM call: (ev) => # @__prevent_btn_click = false if CUI.globalDrag return @_onMouseleave?(ev) if @_menu_on_hover menu_start_hide(ev, 100) return setSize: (size) -> remove = [] for cls in @DOM.classList if cls.startsWith("cui-button-size") remove.push(cls) for cls in remove @DOM.classList.remove(cls) if size @DOM.classList.add("cui-button-size-"+size) @ onClickAction: (ev) -> if @__disabled # or ev.button != 0 ev.preventDefault() return @getTooltip()?.hide(ev) if @__radio if @__radio_allow_null @toggle({}, ev) else @activate({}, ev) if @hasMenu() and # not (ev.ctrlKey or ev.shiftKey or ev.altKey or ev.metaKey) and not @_menu_on_hover and @getMenu().hasItems(ev) @getMenu().show(ev) # in some contexts (like FileUploadButton), this # is necessary, so we stop the file upload # to open # ev.preventDefault() return if ev.isImmediatePropagationStopped() return CUI.Events.trigger type: "cui-button-click" node: @ info: event: ev if ev.isImmediatePropagationStopped() or not @_onClick return @_onClick.call(@, ev, @) initOpts: -> super() @addOpts tabindex: default: 0 check: (v) -> CUI.util.isInteger(v) or v == false # legacy, do not use size: check: ["mini","normal","big","bigger"] # legacy, do not use # link: use ButtonHref instead; important: use "primary: true" instead appearance: check: ["link","flat","normal","important","transparent-border"] primary: mandatory: true default: false check: Boolean secondary: check: Boolean onClick: check: Function click_type: default: "click" # "touchend" mandatory: true check: (v) -> !!CUI.Button.clickTypes[v] text: check: String tooltip: check: "PlainObject" disabled: default: false check: (v) -> CUI.util.isBoolean(v) or CUI.util.isFunction(v) loading: default: false check: (v) -> CUI.util.isBoolean(v) or CUI.util.isFunction(v) class: check: String active_css_class: default: CUI.defaults.class.Button.defaults.active_css_class check: String left: check: (v) -> if v == true return true (CUI.util.isElement(v) or v instanceof CUI.Element or CUI.util.isString(v)) and not @_icon and not @_icon_left and not @_icon_active and not @_icon_inactive right: check: (v) -> (v == true or CUI.util.isContent(v)) and not @_icon_right center: check: (v) -> CUI.util.isContent(v) or CUI.util.isString(v) icon: check: (v) -> v instanceof CUI.Icon or CUI.util.isString(v) icon_left: check: (v) -> v instanceof CUI.Icon or CUI.util.isString(v) icon_right: check: (v) -> v instanceof CUI.Icon or CUI.util.isString(v) or v == false icon_active: check: (v) -> v instanceof CUI.Icon or CUI.util.isString(v) icon_inactive: check: (v) -> v instanceof CUI.Icon or CUI.util.isString(v) text_active: check: String text_inactive: check: String value: {} name: check: String hidden: check: (v) -> CUI.util.isBoolean(v) or CUI.util.isFunction(v) menu: check: "PlainObject" menu_on_hover: check: Boolean menu_parent: check: CUI.Menu onActivate: check: Function onDeactivate: check: Function onMouseenter: check: Function onMouseleave: check: Function # if set, this button belongs # to a group of buttons # on click, the active state of # this button will be set and unset # on the others radio: check: (v) -> CUI.util.isString(v) or v == true # whether to allow de-select # on radio buttons radio_allow_null: check: Boolean switch: check: Boolean active: check: Boolean # set to false to skip running onActivate and onDeactivate # callbacks on initial activate/deactivate when the button is # created activate_initial: default: true check: Boolean #group can be used for buttonbars to specify a group css style group: check: String role: default: "button" mandatory: true check: String # return icon for string __getIcon: (icon) -> if not icon null else if icon instanceof CUI.Icon icon else new CUI.Icon(icon: icon) readOpts: -> if @opts.switch CUI.util.assert(CUI.util.isUndef(@opts.radio_allow_null), "new CUI.Button", "opts.switch cannot be used together with opts.radio_allow_null", opts: @opts) super() if @_left CUI.util.assert(@_left == true or not (@_icon_active or @_icon_inactive or @_icon), "new CUI.Button", "opts.left != true cannot be used togeter with opts.icon*", opts: @opts) getCenter: -> return @__box.map.center; __getTemplateName: -> if @_icon or @_icon_left or @_icon_active or @_icon_inactive or @_left @__has_left = true else @__has_left = false if @_icon_right or (@_menu and @_icon_right != false) or @_right @__has_right = true else @__has_right = false if @__has_left and CUI.util.isUndef(@_text) and CUI.util.isUndef(@_center) and CUI.util.isUndef(@_text_active) and CUI.util.isUndef(@_text_inactive) and CUI.__ng__ @__has_center = false if @__has_left and @__has_right return "button" else if @__has_left if @__has_center return "button-left-center" else return "button-left" else if @__has_right return "button-center-right" else return "button-center" getTemplateName: -> if CUI.__ng__ @__getTemplateName() + "-ng" else @__getTemplateName() getValue: -> @_value getElementForLayer: -> return @__box.map.visual getRadioButtons: -> if not @__radio return [] @__getButtons("radio", @__radio) getGroupButtons: -> if not @getGroup() return [] @__getButtons("button-group", @getGroup()) # returns other buttons __getButtons: (key, value) -> parents = CUI.dom.parents(@DOM, ".cui-buttonbar,.cui-form-table,.cui-item-list-body,.cui-layer") if parents.length == 0 # buttons are not grouped by anything, so we # have no other buttons, so we use the top level element parents = CUI.dom.parents(@DOM) if parents.length > 0 docElem = parents[parents.length-1] else return [] (CUI.dom.data(c, "element") for c in CUI.dom.matchSelector(docElem, ".cui-button[#{key}=\"#{value}\"]")) hasMenu: -> !!@__menu_opts hasLeft: -> @__has_left getMenu: -> if not @hasMenu() return if @__menu @__menu else @__menu = new CUI.Menu(@__menu_opts) menuSetActiveIdx: (idx) -> if @__menu @__menu.setActiveIdx(idx) else @__menu_opts.itemList.active_item_idx = idx @ getMenuRootButton: -> if @_menu_parent return @_menu_parent.getButton()?.getMenuRootButton() else if @hasMenu() return @ else null #TODO rename to toggleActiveState toggle: (flags={}, event) -> @setActive(not @__active, flags, event) setActive: (active, flags={}, event) -> if active @activate(flags, event) else @deactivate(flags, event) __callOnGroup: (call, flags, event) -> group = @getGroup() if not group or not event?.hasModifierKey() or flags.ignore_ctrl return flags.ignore_ctrl = true if not event.altKey() started = true else started = false for btn in @getGroupButtons() if btn == @ started = true continue if not started continue btn[call](flags, event) return activate: (flags={}, event) -> # console.error "activate", flags, @getUniqueId(), @__active, @_activate_initial activate = => @addClass(@_active_css_class) @setAria("pressed", true) @__setState() @__callOnGroup("activate", flags, event) return if @_activate_initial == false and flags.initial_activate @__active = true activate() return @ if @__active == true and CUI.util.isEmptyObject(flags) return @ if @__radio _flags = prior_activate: @ initial_activate: flags.initial_activate for btn, idx in @getRadioButtons() if btn == @ or not btn.isActive() continue # don't send the event here, since this happens # code driven btn.deactivate(_flags) @__active = true ret = @_onActivate?(@, flags, event) if CUI.util.isPromise(ret) ret.done(activate).fail => @__active = false return ret activate() @ deactivate: (flags={}, event) -> # console.error "deactivate", flags, @getUniqueId(), @__active, @_activate_initial, @_icon_inactive deactivate = => @removeClass(@_active_css_class) @setAria("pressed", false) @__setState() @__callOnGroup("deactivate", flags, event) return if @_activate_initial == false and flags.initial_activate @__active = false deactivate() return @ if @__active == false and CUI.util.isEmptyObject(flags) return @ @__active = false ret = @_onDeactivate?(@, flags, event) if CUI.util.isPromise(ret) ret.done(deactivate).fail => @__active = true return ret deactivate() @ setIconRight: (icon=null) -> @setIcon(icon, "right") setIcon: (icon=null, _key="left") -> key = PI:KEY:<KEY>END_PI_key if icon == "" @[key] = "" else @[key] = @__getIcon(icon) CUI.util.assert(@[key] == null or @[key] == "" or @[key] instanceof CUI.Icon, "CUI.Button.setIcon", "icon needs to be instance of Icon", icon: icon) if @[key] == null @empty(_key) else if @[key] == "" @replace(CUI.dom.element("SPAN"), _key) else @replace(@[key], _key) @ startSpinner: -> CUI.util.assert(@__has_left, "CUI.Button.startSpinner", "No space for Icon found, make sure the Button was created with opts.left set.", opts: @opts) if @__hasSpinner return @__iconBeforeSpinner = @getIcon() @__hasSpinner = true @setIcon("spinner") @ stopSpinner: -> @setIcon(@__iconBeforeSpinner) @__hasSpinner = false @__iconBeforeSpinner = null @ getIcon: -> @__icon_left getIconRight: -> @__icon_right __setState: -> @__setIconState() @__setTextState() __setIconState: -> if not (@_icon_active or @_icon_inactive) return @ if @isActive() if not @_icon_active @setIcon("") else @setIcon(@_icon_active) else if not @_icon_inactive @setIcon("") else @setIcon(@_icon_inactive) @ __setTextState: -> if not (@_text_active or @_text_inactive) return @ if @isActive() if not CUI.util.isNull(@_text_active) @setText(@_text_active) else if not CUI.util.isNull(@_text_inactive) @setText(@_text_inactive) @ isActive: -> !!@__active isDisabled: -> @__disabled isEnabled: -> not @__disabled setEnabled: (enabled) -> if enabled @enable() else @disable() setLoading: (on_off) -> if on_off CUI.dom.addClass(@DOM, CUI.defaults.class.Button.defaults.loading_css_class) @__loading = true else CUI.dom.removeClass(@DOM, CUI.defaults.class.Button.defaults.loading_css_class) @__loading = false isLoading: -> @__loading disable: -> CUI.dom.addClass(@DOM, CUI.defaults.class.Button.defaults.disabled_css_class) CUI.dom.removeAttribute(@DOM, "tabindex") @__disabled = true @ enable: -> CUI.dom.removeClass(@DOM, CUI.defaults.class.Button.defaults.disabled_css_class) CUI.dom.setAttribute(@DOM, "tabindex", @_tabindex) @__disabled = false @ setText: (@__txt) -> if CUI.util.isEmpty(@__txt) @__txt = '' span = CUI.dom.text(@__txt) if not @__hasAriaLabel span.id = "button-text-"+@getUniqueId() @setAria("labelledby", span.id) @replace(span, "center") setTextMaxChars: (max_chars) -> CUI.dom.setAttribute(@getCenter().firstChild, "data-max-chars", max_chars) getText: -> @__txt getGroup: -> @__group setGroup: (@__group) -> if @__group CUI.dom.setAttribute(@DOM, "button-group", @__group) else CUI.dom.removeAttribute(@DOM, "button-group") __initTooltip: -> if @__tooltip and not @__tooltip.isDestroyed() return @ tt_opts = CUI.util.copyObject(@__tooltipOpts) tt_opts.element ?= @DOM # make sure the tooltip does not register any listeners for k in ["on_hover", "on_click"] CUI.util.assert(not tt_opts.hasOwnProperty(k), "CUI.Button.__initTooltip", "opts.tooltip cannot contain #{k}.", opts: @opts) tt_opts[k] = false @__tooltip = new CUI.Tooltip(tt_opts) @ getTooltip: -> @__tooltip isShown: -> not @isHidden() isHidden: -> @__hidden destroy: -> # console.debug "destroying button", @__uniqueId, @getText() @__menu?.destroy() @__menu = null @__tooltip?.destroy() @__tooltip = null super() show: -> @__hidden = false CUI.dom.removeClass(@DOM, "cui-button-hidden") CUI.dom.showElement(@DOM) CUI.Events.trigger type: "show" node: @DOM hide: -> @__hidden = true CUI.dom.addClass(@DOM, "cui-button-hidden") CUI.dom.hideElement(@DOM) CUI.Events.trigger type: "hide" node: @DOM @clickTypes: click: ['click'] mouseup: ['mouseup'] dblclick: ['dblclick'] @clickTypesPrevent: click: ['dblclick', 'mousedown'] mouseup: ['mouseup', 'mousedown'] dblclick: ['click', 'mousedown'] CUI.Events.registerEvent type: ["show", "hide", "cui-button-click"] bubble: true CUI.defaults.class.Button = CUI.Button
[ { "context": "les.\n\n# CSS colors courtesy MIT-licensed code from Dave Eddy:\n# github.com/bahamas10/css-color-names/blob/mast", "end": 142, "score": 0.9998912215232849, "start": 133, "tag": "NAME", "value": "Dave Eddy" }, { "context": "sy MIT-licensed code from Dave Eddy:\n# github...
bokehjs/src/coffee/common/color.coffee
rothnic/bokeh
1
# Functionality to handle CSS colors # Used by webgl to convert colors to rgba tuples. # CSS colors courtesy MIT-licensed code from Dave Eddy: # github.com/bahamas10/css-color-names/blob/master/css-color-names.json _component2hex = (v) -> h = Number(v).toString(16) h = if h.length == 1 then '0' + h else h color2hex = (color) -> color = color + '' if color.indexOf('#') == 0 return color else if _color_dict[color]? return _color_dict[color] else if color.indexOf('rgb') == 0 rgb = color.match(/\d+/g) hex = (_component2hex(v) for v in rgb).join('') return '#' + hex.slice(0, 8) # can also be rgba else return color color2rgba = (color, alpha=1) -> if not color # NaN, null, '', etc. return [0, 0, 0, 0] # transparent # Convert to hex and then to clean version of 6 or 8 chars hex = color2hex(color) hex = hex.replace(/ |#/g, '') if hex.length <= 4 hex = hex.replace(/(.)/g, '$1$1') # Convert pairs to numbers hex = hex.match(/../g) rgba = (parseInt(i, 16)/255 for i in hex) # Ensure correct length, add alpha if necessary while rgba.length < 3 rgba.push(0) if rgba.length < 4 rgba.push(alpha) return rgba.slice(0, 4) # return 4 elements _color_dict = { # Matlab/MPL style colors "k": '#000000', "w": '#FFFFFF', "r": '#FF0000', "g": '#00FF00', "b": '#0000FF', "y": '#FFFF00', "m": '#FF00FF', "c": '#00FFFF', # CSS colors "aqua": "#00ffff", "aliceblue": "#f0f8ff", "antiquewhite": "#faebd7", "black": "#000000", "blue": "#0000ff", "cyan": "#00ffff", "darkblue": "#00008b", "darkcyan": "#008b8b", "darkgreen": "#006400", "darkturquoise": "#00ced1", "deepskyblue": "#00bfff", "green": "#008000", "lime": "#00ff00", "mediumblue": "#0000cd", "mediumspringgreen": "#00fa9a", "navy": "#000080", "springgreen": "#00ff7f", "teal": "#008080", "midnightblue": "#191970", "dodgerblue": "#1e90ff", "lightseagreen": "#20b2aa", "forestgreen": "#228b22", "seagreen": "#2e8b57", "darkslategray": "#2f4f4f", "darkslategrey": "#2f4f4f", "limegreen": "#32cd32", "mediumseagreen": "#3cb371", "turquoise": "#40e0d0", "royalblue": "#4169e1", "steelblue": "#4682b4", "darkslateblue": "#483d8b", "mediumturquoise": "#48d1cc", "indigo": "#4b0082", "darkolivegreen": "#556b2f", "cadetblue": "#5f9ea0", "cornflowerblue": "#6495ed", "mediumaquamarine": "#66cdaa", "dimgray": "#696969", "dimgrey": "#696969", "slateblue": "#6a5acd", "olivedrab": "#6b8e23", "slategray": "#708090", "slategrey": "#708090", "lightslategray": "#778899", "lightslategrey": "#778899", "mediumslateblue": "#7b68ee", "lawngreen": "#7cfc00", "aquamarine": "#7fffd4", "chartreuse": "#7fff00", "gray": "#808080", "grey": "#808080", "maroon": "#800000", "olive": "#808000", "purple": "#800080", "lightskyblue": "#87cefa", "skyblue": "#87ceeb", "blueviolet": "#8a2be2", "darkmagenta": "#8b008b", "darkred": "#8b0000", "saddlebrown": "#8b4513", "darkseagreen": "#8fbc8f", "lightgreen": "#90ee90", "mediumpurple": "#9370db", "darkviolet": "#9400d3", "palegreen": "#98fb98", "darkorchid": "#9932cc", "yellowgreen": "#9acd32", "sienna": "#a0522d", "brown": "#a52a2a", "darkgray": "#a9a9a9", "darkgrey": "#a9a9a9", "greenyellow": "#adff2f", "lightblue": "#add8e6", "paleturquoise": "#afeeee", "lightsteelblue": "#b0c4de", "powderblue": "#b0e0e6", "firebrick": "#b22222", "darkgoldenrod": "#b8860b", "mediumorchid": "#ba55d3", "rosybrown": "#bc8f8f", "darkkhaki": "#bdb76b", "silver": "#c0c0c0", "mediumvioletred": "#c71585", "indianred": "#cd5c5c", "peru": "#cd853f", "chocolate": "#d2691e", "tan": "#d2b48c", "lightgray": "#d3d3d3", "lightgrey": "#d3d3d3", "thistle": "#d8bfd8", "goldenrod": "#daa520", "orchid": "#da70d6", "palevioletred": "#db7093", "crimson": "#dc143c", "gainsboro": "#dcdcdc", "plum": "#dda0dd", "burlywood": "#deb887", "lightcyan": "#e0ffff", "lavender": "#e6e6fa", "darksalmon": "#e9967a", "palegoldenrod": "#eee8aa", "violet": "#ee82ee", "azure": "#f0ffff", "honeydew": "#f0fff0", "khaki": "#f0e68c", "lightcoral": "#f08080", "sandybrown": "#f4a460", "beige": "#f5f5dc", "mintcream": "#f5fffa", "wheat": "#f5deb3", "whitesmoke": "#f5f5f5", "ghostwhite": "#f8f8ff", "lightgoldenrodyellow": "#fafad2", "linen": "#faf0e6", "salmon": "#fa8072", "oldlace": "#fdf5e6", "bisque": "#ffe4c4", "blanchedalmond": "#ffebcd", "coral": "#ff7f50", "cornsilk": "#fff8dc", "darkorange": "#ff8c00", "deeppink": "#ff1493", "floralwhite": "#fffaf0", "fuchsia": "#ff00ff", "gold": "#ffd700", "hotpink": "#ff69b4", "ivory": "#fffff0", "lavenderblush": "#fff0f5", "lemonchiffon": "#fffacd", "lightpink": "#ffb6c1", "lightsalmon": "#ffa07a", "lightyellow": "#ffffe0", "magenta": "#ff00ff", "mistyrose": "#ffe4e1", "moccasin": "#ffe4b5", "navajowhite": "#ffdead", "orange": "#ffa500", "orangered": "#ff4500", "papayawhip": "#ffefd5", "peachpuff": "#ffdab9", "pink": "#ffc0cb", "red": "#ff0000", "seashell": "#fff5ee", "snow": "#fffafa", "tomato": "#ff6347", "white": "#ffffff", "yellow": "#ffff00", } module.exports = color2hex: color2hex color2rgba: color2rgba
89363
# Functionality to handle CSS colors # Used by webgl to convert colors to rgba tuples. # CSS colors courtesy MIT-licensed code from <NAME>: # github.com/bahamas10/css-color-names/blob/master/css-color-names.json _component2hex = (v) -> h = Number(v).toString(16) h = if h.length == 1 then '0' + h else h color2hex = (color) -> color = color + '' if color.indexOf('#') == 0 return color else if _color_dict[color]? return _color_dict[color] else if color.indexOf('rgb') == 0 rgb = color.match(/\d+/g) hex = (_component2hex(v) for v in rgb).join('') return '#' + hex.slice(0, 8) # can also be rgba else return color color2rgba = (color, alpha=1) -> if not color # NaN, null, '', etc. return [0, 0, 0, 0] # transparent # Convert to hex and then to clean version of 6 or 8 chars hex = color2hex(color) hex = hex.replace(/ |#/g, '') if hex.length <= 4 hex = hex.replace(/(.)/g, '$1$1') # Convert pairs to numbers hex = hex.match(/../g) rgba = (parseInt(i, 16)/255 for i in hex) # Ensure correct length, add alpha if necessary while rgba.length < 3 rgba.push(0) if rgba.length < 4 rgba.push(alpha) return rgba.slice(0, 4) # return 4 elements _color_dict = { # Matlab/MPL style colors "k": '#000000', "w": '#FFFFFF', "r": '#FF0000', "g": '#00FF00', "b": '#0000FF', "y": '#FFFF00', "m": '#FF00FF', "c": '#00FFFF', # CSS colors "aqua": "#00ffff", "aliceblue": "#f0f8ff", "antiquewhite": "#faebd7", "black": "#000000", "blue": "#0000ff", "cyan": "#00ffff", "darkblue": "#00008b", "darkcyan": "#008b8b", "darkgreen": "#006400", "darkturquoise": "#00ced1", "deepskyblue": "#00bfff", "green": "#008000", "lime": "#00ff00", "mediumblue": "#0000cd", "mediumspringgreen": "#00fa9a", "navy": "#000080", "springgreen": "#00ff7f", "teal": "#008080", "midnightblue": "#191970", "dodgerblue": "#1e90ff", "lightseagreen": "#20b2aa", "forestgreen": "#228b22", "seagreen": "#2e8b57", "darkslategray": "#2f4f4f", "darkslategrey": "#2f4f4f", "limegreen": "#32cd32", "mediumseagreen": "#3cb371", "turquoise": "#40e0d0", "royalblue": "#4169e1", "steelblue": "#4682b4", "darkslateblue": "#483d8b", "mediumturquoise": "#48d1cc", "indigo": "#4b0082", "darkolivegreen": "#556b2f", "cadetblue": "#5f9ea0", "cornflowerblue": "#6495ed", "mediumaquamarine": "#66cdaa", "dimgray": "#696969", "dimgrey": "#696969", "slateblue": "#6a5acd", "olivedrab": "#6b8e23", "slategray": "#708090", "slategrey": "#708090", "lightslategray": "#778899", "lightslategrey": "#778899", "mediumslateblue": "#7b68ee", "lawngreen": "#7cfc00", "aquamarine": "#7fffd4", "chartreuse": "#7fff00", "gray": "#808080", "grey": "#808080", "maroon": "#800000", "olive": "#808000", "purple": "#800080", "lightskyblue": "#87cefa", "skyblue": "#87ceeb", "blueviolet": "#8a2be2", "darkmagenta": "#8b008b", "darkred": "#8b0000", "saddlebrown": "#8b4513", "darkseagreen": "#8fbc8f", "lightgreen": "#90ee90", "mediumpurple": "#9370db", "darkviolet": "#9400d3", "palegreen": "#98fb98", "darkorchid": "#9932cc", "yellowgreen": "#9acd32", "sienna": "#a0522d", "brown": "#a52a2a", "darkgray": "#a9a9a9", "darkgrey": "#a9a9a9", "greenyellow": "#adff2f", "lightblue": "#add8e6", "paleturquoise": "#afeeee", "lightsteelblue": "#b0c4de", "powderblue": "#b0e0e6", "firebrick": "#b22222", "darkgoldenrod": "#b8860b", "mediumorchid": "#ba55d3", "rosybrown": "#bc8f8f", "darkkhaki": "#bdb76b", "silver": "#c0c0c0", "mediumvioletred": "#c71585", "indianred": "#cd5c5c", "peru": "#cd853f", "chocolate": "#d2691e", "tan": "#d2b48c", "lightgray": "#d3d3d3", "lightgrey": "#d3d3d3", "thistle": "#d8bfd8", "goldenrod": "#daa520", "orchid": "#da70d6", "palevioletred": "#db7093", "crimson": "#dc143c", "gainsboro": "#dcdcdc", "plum": "#dda0dd", "burlywood": "#deb887", "lightcyan": "#e0ffff", "lavender": "#e6e6fa", "darksalmon": "#e9967a", "palegoldenrod": "#eee8aa", "violet": "#ee82ee", "azure": "#f0ffff", "honeydew": "#f0fff0", "khaki": "#f0e68c", "lightcoral": "#f08080", "sandybrown": "#f4a460", "beige": "#f5f5dc", "mintcream": "#f5fffa", "wheat": "#f5deb3", "whitesmoke": "#f5f5f5", "ghostwhite": "#f8f8ff", "lightgoldenrodyellow": "#fafad2", "linen": "#faf0e6", "salmon": "#fa8072", "oldlace": "#fdf5e6", "bisque": "#ffe4c4", "blanchedalmond": "#ffebcd", "coral": "#ff7f50", "cornsilk": "#fff8dc", "darkorange": "#ff8c00", "deeppink": "#ff1493", "floralwhite": "#fffaf0", "fuchsia": "#ff00ff", "gold": "#ffd700", "hotpink": "#ff69b4", "ivory": "#fffff0", "lavenderblush": "#fff0f5", "lemonchiffon": "#fffacd", "lightpink": "#ffb6c1", "lightsalmon": "#ffa07a", "lightyellow": "#ffffe0", "magenta": "#ff00ff", "mistyrose": "#ffe4e1", "moccasin": "#ffe4b5", "navajowhite": "#ffdead", "orange": "#ffa500", "orangered": "#ff4500", "papayawhip": "#ffefd5", "peachpuff": "#ffdab9", "pink": "#ffc0cb", "red": "#ff0000", "seashell": "#fff5ee", "snow": "#fffafa", "tomato": "#ff6347", "white": "#ffffff", "yellow": "#ffff00", } module.exports = color2hex: color2hex color2rgba: color2rgba
true
# Functionality to handle CSS colors # Used by webgl to convert colors to rgba tuples. # CSS colors courtesy MIT-licensed code from PI:NAME:<NAME>END_PI: # github.com/bahamas10/css-color-names/blob/master/css-color-names.json _component2hex = (v) -> h = Number(v).toString(16) h = if h.length == 1 then '0' + h else h color2hex = (color) -> color = color + '' if color.indexOf('#') == 0 return color else if _color_dict[color]? return _color_dict[color] else if color.indexOf('rgb') == 0 rgb = color.match(/\d+/g) hex = (_component2hex(v) for v in rgb).join('') return '#' + hex.slice(0, 8) # can also be rgba else return color color2rgba = (color, alpha=1) -> if not color # NaN, null, '', etc. return [0, 0, 0, 0] # transparent # Convert to hex and then to clean version of 6 or 8 chars hex = color2hex(color) hex = hex.replace(/ |#/g, '') if hex.length <= 4 hex = hex.replace(/(.)/g, '$1$1') # Convert pairs to numbers hex = hex.match(/../g) rgba = (parseInt(i, 16)/255 for i in hex) # Ensure correct length, add alpha if necessary while rgba.length < 3 rgba.push(0) if rgba.length < 4 rgba.push(alpha) return rgba.slice(0, 4) # return 4 elements _color_dict = { # Matlab/MPL style colors "k": '#000000', "w": '#FFFFFF', "r": '#FF0000', "g": '#00FF00', "b": '#0000FF', "y": '#FFFF00', "m": '#FF00FF', "c": '#00FFFF', # CSS colors "aqua": "#00ffff", "aliceblue": "#f0f8ff", "antiquewhite": "#faebd7", "black": "#000000", "blue": "#0000ff", "cyan": "#00ffff", "darkblue": "#00008b", "darkcyan": "#008b8b", "darkgreen": "#006400", "darkturquoise": "#00ced1", "deepskyblue": "#00bfff", "green": "#008000", "lime": "#00ff00", "mediumblue": "#0000cd", "mediumspringgreen": "#00fa9a", "navy": "#000080", "springgreen": "#00ff7f", "teal": "#008080", "midnightblue": "#191970", "dodgerblue": "#1e90ff", "lightseagreen": "#20b2aa", "forestgreen": "#228b22", "seagreen": "#2e8b57", "darkslategray": "#2f4f4f", "darkslategrey": "#2f4f4f", "limegreen": "#32cd32", "mediumseagreen": "#3cb371", "turquoise": "#40e0d0", "royalblue": "#4169e1", "steelblue": "#4682b4", "darkslateblue": "#483d8b", "mediumturquoise": "#48d1cc", "indigo": "#4b0082", "darkolivegreen": "#556b2f", "cadetblue": "#5f9ea0", "cornflowerblue": "#6495ed", "mediumaquamarine": "#66cdaa", "dimgray": "#696969", "dimgrey": "#696969", "slateblue": "#6a5acd", "olivedrab": "#6b8e23", "slategray": "#708090", "slategrey": "#708090", "lightslategray": "#778899", "lightslategrey": "#778899", "mediumslateblue": "#7b68ee", "lawngreen": "#7cfc00", "aquamarine": "#7fffd4", "chartreuse": "#7fff00", "gray": "#808080", "grey": "#808080", "maroon": "#800000", "olive": "#808000", "purple": "#800080", "lightskyblue": "#87cefa", "skyblue": "#87ceeb", "blueviolet": "#8a2be2", "darkmagenta": "#8b008b", "darkred": "#8b0000", "saddlebrown": "#8b4513", "darkseagreen": "#8fbc8f", "lightgreen": "#90ee90", "mediumpurple": "#9370db", "darkviolet": "#9400d3", "palegreen": "#98fb98", "darkorchid": "#9932cc", "yellowgreen": "#9acd32", "sienna": "#a0522d", "brown": "#a52a2a", "darkgray": "#a9a9a9", "darkgrey": "#a9a9a9", "greenyellow": "#adff2f", "lightblue": "#add8e6", "paleturquoise": "#afeeee", "lightsteelblue": "#b0c4de", "powderblue": "#b0e0e6", "firebrick": "#b22222", "darkgoldenrod": "#b8860b", "mediumorchid": "#ba55d3", "rosybrown": "#bc8f8f", "darkkhaki": "#bdb76b", "silver": "#c0c0c0", "mediumvioletred": "#c71585", "indianred": "#cd5c5c", "peru": "#cd853f", "chocolate": "#d2691e", "tan": "#d2b48c", "lightgray": "#d3d3d3", "lightgrey": "#d3d3d3", "thistle": "#d8bfd8", "goldenrod": "#daa520", "orchid": "#da70d6", "palevioletred": "#db7093", "crimson": "#dc143c", "gainsboro": "#dcdcdc", "plum": "#dda0dd", "burlywood": "#deb887", "lightcyan": "#e0ffff", "lavender": "#e6e6fa", "darksalmon": "#e9967a", "palegoldenrod": "#eee8aa", "violet": "#ee82ee", "azure": "#f0ffff", "honeydew": "#f0fff0", "khaki": "#f0e68c", "lightcoral": "#f08080", "sandybrown": "#f4a460", "beige": "#f5f5dc", "mintcream": "#f5fffa", "wheat": "#f5deb3", "whitesmoke": "#f5f5f5", "ghostwhite": "#f8f8ff", "lightgoldenrodyellow": "#fafad2", "linen": "#faf0e6", "salmon": "#fa8072", "oldlace": "#fdf5e6", "bisque": "#ffe4c4", "blanchedalmond": "#ffebcd", "coral": "#ff7f50", "cornsilk": "#fff8dc", "darkorange": "#ff8c00", "deeppink": "#ff1493", "floralwhite": "#fffaf0", "fuchsia": "#ff00ff", "gold": "#ffd700", "hotpink": "#ff69b4", "ivory": "#fffff0", "lavenderblush": "#fff0f5", "lemonchiffon": "#fffacd", "lightpink": "#ffb6c1", "lightsalmon": "#ffa07a", "lightyellow": "#ffffe0", "magenta": "#ff00ff", "mistyrose": "#ffe4e1", "moccasin": "#ffe4b5", "navajowhite": "#ffdead", "orange": "#ffa500", "orangered": "#ff4500", "papayawhip": "#ffefd5", "peachpuff": "#ffdab9", "pink": "#ffc0cb", "red": "#ff0000", "seashell": "#fff5ee", "snow": "#fffafa", "tomato": "#ff6347", "white": "#ffffff", "yellow": "#ffff00", } module.exports = color2hex: color2hex color2rgba: color2rgba
[ { "context": " = { name: 'user', type: 'belongsTo', humanName: 'User' }\n\n assert.deepEqual expected, generator.buil", "end": 476, "score": 0.6637489199638367, "start": 472, "tag": "NAME", "value": "User" }, { "context": "', ->\n expected =\n name: 'user'\...
test/cases/generator/server/resourcesTest.coffee
jivagoalves/tower
1
generator = null sourceRoot = null destinationRoot = null cakefileDestination = null describe 'Tower.GeneratorResources', -> beforeEach -> Tower.removeDirectorySync("#{process.cwd()}/test/tmp") generator = new Tower.Generator(silent: true) test '#generateRandom("hex")', -> assert.match generator.generateRandom('hex'), /^\b[0-9a-fA-F]+\b$/ test '#buildRelation', -> expected = { name: 'user', type: 'belongsTo', humanName: 'User' } assert.deepEqual expected, generator.buildRelation('belongsTo', 'User') test '#buildModel("user")', -> expected = name: 'user' namespace: 'App' className: 'User' classNamePlural: 'Users' namespacedClassName: 'App.User' namePlural: 'users' paramName: 'user' paramNamePlural: 'users' humanName: 'User' attributes: [] relations: belongsTo: [] hasOne: [] hasMany: [] namespacedDirectory: '' viewDirectory: '/users' namespaced: '' model = generator.buildModel('user', 'App') for key, value of expected assert.deepEqual value, model[key] test '#buildModel("camelCase")', -> expected = name: 'camelCase' namespace: 'App' className: 'CamelCase' classNamePlural: 'CamelCases' namespacedClassName: 'App.CamelCase' namePlural: 'camelCases' paramName: 'camel-case' paramNamePlural: 'camel-cases' humanName: 'Camel case' attributes: [] relations: belongsTo: [] hasOne: [] hasMany: [] namespacedDirectory: '' viewDirectory: '/camelCases' namespaced: '' model = generator.buildModel('camelCase', 'App') for key, value of expected assert.deepEqual value, model[key] test '#buildController("user")', -> expected = namespace: 'App' className: 'UsersController' directory: '' name: 'usersController' namespaced: false controller = generator.buildController('user') for key, value of expected assert.deepEqual value, controller[key] test '#buildView', -> expected = namespace: 'user' directory: 'users' view = generator.buildView('user') for key, value of expected assert.deepEqual value, view[key] describe '#buildAttribute', -> test 'name: "title"', -> expected = name: 'title' type: 'string' humanName: 'Title' fieldType: 'string' value: 'A title' attribute = generator.buildAttribute('title') for key, value of expected assert.deepEqual value, attribute[key] test 'name: "tags", type: "Array"', -> expected = name: 'tags' type: 'Array' humanName: 'Tags' fieldType: 'string' value: "A tags" attribute = generator.buildAttribute('tags', 'Array') for key, value of expected assert.deepEqual value, attribute[key] test '#buildApp' test '#buildUser'
84768
generator = null sourceRoot = null destinationRoot = null cakefileDestination = null describe 'Tower.GeneratorResources', -> beforeEach -> Tower.removeDirectorySync("#{process.cwd()}/test/tmp") generator = new Tower.Generator(silent: true) test '#generateRandom("hex")', -> assert.match generator.generateRandom('hex'), /^\b[0-9a-fA-F]+\b$/ test '#buildRelation', -> expected = { name: 'user', type: 'belongsTo', humanName: '<NAME>' } assert.deepEqual expected, generator.buildRelation('belongsTo', 'User') test '#buildModel("user")', -> expected = name: '<NAME>' namespace: 'App' className: 'User' classNamePlural: 'Users' namespacedClassName: 'App.User' namePlural: 'users' paramName: 'user' paramNamePlural: 'users' humanName: '<NAME>' attributes: [] relations: belongsTo: [] hasOne: [] hasMany: [] namespacedDirectory: '' viewDirectory: '/users' namespaced: '' model = generator.buildModel('user', 'App') for key, value of expected assert.deepEqual value, model[key] test '#buildModel("camelCase")', -> expected = name: '<NAME>Case' namespace: 'App' className: 'CamelCase' classNamePlural: 'CamelCases' namespacedClassName: 'App.CamelCase' namePlural: 'camelCases' paramName: 'camel-case' paramNamePlural: 'camel-cases' humanName: 'Camel case' attributes: [] relations: belongsTo: [] hasOne: [] hasMany: [] namespacedDirectory: '' viewDirectory: '/camelCases' namespaced: '' model = generator.buildModel('camelCase', 'App') for key, value of expected assert.deepEqual value, model[key] test '#buildController("user")', -> expected = namespace: 'App' className: 'UsersController' directory: '' name: 'usersController' namespaced: false controller = generator.buildController('user') for key, value of expected assert.deepEqual value, controller[key] test '#buildView', -> expected = namespace: 'user' directory: 'users' view = generator.buildView('user') for key, value of expected assert.deepEqual value, view[key] describe '#buildAttribute', -> test 'name: "title"', -> expected = name: 'title' type: 'string' humanName: 'Title' fieldType: 'string' value: 'A title' attribute = generator.buildAttribute('title') for key, value of expected assert.deepEqual value, attribute[key] test 'name: "tags", type: "Array"', -> expected = name: 'tags' type: 'Array' humanName: 'Tags' fieldType: 'string' value: "A tags" attribute = generator.buildAttribute('tags', 'Array') for key, value of expected assert.deepEqual value, attribute[key] test '#buildApp' test '#buildUser'
true
generator = null sourceRoot = null destinationRoot = null cakefileDestination = null describe 'Tower.GeneratorResources', -> beforeEach -> Tower.removeDirectorySync("#{process.cwd()}/test/tmp") generator = new Tower.Generator(silent: true) test '#generateRandom("hex")', -> assert.match generator.generateRandom('hex'), /^\b[0-9a-fA-F]+\b$/ test '#buildRelation', -> expected = { name: 'user', type: 'belongsTo', humanName: 'PI:NAME:<NAME>END_PI' } assert.deepEqual expected, generator.buildRelation('belongsTo', 'User') test '#buildModel("user")', -> expected = name: 'PI:NAME:<NAME>END_PI' namespace: 'App' className: 'User' classNamePlural: 'Users' namespacedClassName: 'App.User' namePlural: 'users' paramName: 'user' paramNamePlural: 'users' humanName: 'PI:NAME:<NAME>END_PI' attributes: [] relations: belongsTo: [] hasOne: [] hasMany: [] namespacedDirectory: '' viewDirectory: '/users' namespaced: '' model = generator.buildModel('user', 'App') for key, value of expected assert.deepEqual value, model[key] test '#buildModel("camelCase")', -> expected = name: 'PI:NAME:<NAME>END_PICase' namespace: 'App' className: 'CamelCase' classNamePlural: 'CamelCases' namespacedClassName: 'App.CamelCase' namePlural: 'camelCases' paramName: 'camel-case' paramNamePlural: 'camel-cases' humanName: 'Camel case' attributes: [] relations: belongsTo: [] hasOne: [] hasMany: [] namespacedDirectory: '' viewDirectory: '/camelCases' namespaced: '' model = generator.buildModel('camelCase', 'App') for key, value of expected assert.deepEqual value, model[key] test '#buildController("user")', -> expected = namespace: 'App' className: 'UsersController' directory: '' name: 'usersController' namespaced: false controller = generator.buildController('user') for key, value of expected assert.deepEqual value, controller[key] test '#buildView', -> expected = namespace: 'user' directory: 'users' view = generator.buildView('user') for key, value of expected assert.deepEqual value, view[key] describe '#buildAttribute', -> test 'name: "title"', -> expected = name: 'title' type: 'string' humanName: 'Title' fieldType: 'string' value: 'A title' attribute = generator.buildAttribute('title') for key, value of expected assert.deepEqual value, attribute[key] test 'name: "tags", type: "Array"', -> expected = name: 'tags' type: 'Array' humanName: 'Tags' fieldType: 'string' value: "A tags" attribute = generator.buildAttribute('tags', 'Array') for key, value of expected assert.deepEqual value, attribute[key] test '#buildApp' test '#buildUser'
[ { "context": "dmin/admin@NODE.DC1.CONSUL'\n kadmin_password: 'admin'\n ssh:\n host: 'localhost'\n username: 'root", "end": 237, "score": 0.9996098875999451, "start": 232, "tag": "PASSWORD", "value": "admin" }, { "context": "dmin'\n ssh:\n host: 'localhost'\n username...
packages/krb5/env/krb5/test.coffee
chibanemourad/node-nikita
0
module.exports = tags: krb5_addprinc: true krb5_delprinc: true krb5_ktadd: true krb5: realm: 'NODE.DC1.CONSUL' kadmin_server: 'krb5' kadmin_principal: 'admin/admin@NODE.DC1.CONSUL' kadmin_password: 'admin' ssh: host: 'localhost' username: 'root'
101655
module.exports = tags: krb5_addprinc: true krb5_delprinc: true krb5_ktadd: true krb5: realm: 'NODE.DC1.CONSUL' kadmin_server: 'krb5' kadmin_principal: 'admin/admin@NODE.DC1.CONSUL' kadmin_password: '<PASSWORD>' ssh: host: 'localhost' username: 'root'
true
module.exports = tags: krb5_addprinc: true krb5_delprinc: true krb5_ktadd: true krb5: realm: 'NODE.DC1.CONSUL' kadmin_server: 'krb5' kadmin_principal: 'admin/admin@NODE.DC1.CONSUL' kadmin_password: 'PI:PASSWORD:<PASSWORD>END_PI' ssh: host: 'localhost' username: 'root'
[ { "context": "d\n localStorage.setItem \"password\", q.password\n closeWindow win\n #", "end": 6050, "score": 0.9990956783294678, "start": 6040, "tag": "PASSWORD", "value": "q.password" }, { "context": "hangeProfile\", {\n ...
client/code/app/util.coffee
Yukimir/jinrou
0
app=require '/app' util=require '/util' exports.showWindow=showWindow=(templatename,tmpl)-> de = document.documentElement bd = document.body sclf = bd.scrollLeft || de.scrollLeft sctp = bd.scrollTop || de.scrollTop x=Math.max 50,sclf+Math.floor(Math.random()*100-200+document.documentElement.clientWidth/2) y=Math.max 50,sctp+Math.floor(Math.random()*100-200+document.documentElement.clientHeight/2) win=$(JT["#{templatename}"](tmpl)).hide().css({left:"#{x}px",top:"#{y}px",}).appendTo("body").fadeIn().draggable() $(".getfocus",win.get(0)).focus() win #編集域を返す exports.blankWindow=(title)-> win=showWindow "util-blank", {title: title} div=document.createElement "div" div.classList.add "window-content" $("form[name='okform']",win).before div win.submit (je)-> je.preventDefault() win.click (je)-> t=je.target while t? if t.name=="ok" closeWindow t break t = t.parentNode $(div) #要素を含むWindowを消す exports.closeWindow=closeWindow= (node)-> w=$(node).closest(".window") w.hide "normal",-> w.remove() w.triggerHandler "close.window" exports.formQuery=(form)-> q={} el=form.elements for e in el if !e.disabled && e.name if (tag=e.tagName.toLowerCase())=="input" if e.type in ["radio","checkbox"] if e.checked q[e.name]=e.value else if e.type!="submit" && e.type!="reset" && e.type!="button" q[e.name]=e.value else if tag in["select","output","textarea"] q[e.name]=e.value q #true,false exports.ask=(title,message,cb)-> win = showWindow "util-ask",{title:title,message:message} win.submit (je)-> je.preventDefault() win.click (je)-> t=je.target while t? if t.name=="yes" cb true closeWindow t break else if t.name=="no" cb false closeWindow t break t = t.parentNode #String / null exports.prompt=(title,message,opt,cb)-> win = showWindow "util-prompt",{title:title,message:message} inp=win.find("input.prompt").get(0) for opv of opt inp[opv]=opt[opv] win.submit (je)-> je.preventDefault() win.click (je)-> t=je.target while t? if t.name=="ok" cb? inp.value closeWindow t break else if t.name=="cancel" cb? null closeWindow t break t = t.parentNode #猝死惩罚 exports.punish=(title,message,cb)-> win = showWindow "util-punish",{title:title,time:message.time} for user in message.userlist a = document.createElement "input" a.type="checkbox" a.name="userList" a.class="punish" a.value=user.userid b = document.createElement "label" $(b).append(a).append(user.name) $("#prePunishUser").append(b).append("<br>") ipt =-> # console.log("punish表单") # console.log(document.punish.userList) user=document.punish.userList; userChecked=[]; if !user[0] a=[] a.push user user=a for pl in user if pl.checked then userChecked.push pl.value # console.log(userChecked) userChecked win.submit (je)-> je.preventDefault() win.click (je)-> t=je.target if t.name=="ok" cb? ipt() closeWindow t else if t.name=="cancel" # cb? null closeWindow t #arr: [{name:"aaa",value:"foo"}, ...] exports.selectprompt=(title,message,arr,cb)-> win = showWindow "util-selectprompt",{title:title,message:message} sel=win.find("select.prompt").get(0) for obj in arr opt=document.createElement "option" opt.textContent=obj.name opt.value=obj.value sel.add opt win.submit (je)-> je.preventDefault() win.click (je)-> t=je.target while t? if t.name=="ok" cb? sel.value closeWindow t break else if t.name=="cancel" cb? null closeWindow t break t = t.parentNode exports.message=(title,message,cb)-> win = showWindow "util-wmessage",{title:title,message:message} win.submit (je)-> je.preventDefault() win.click (je)-> t=je.target while t? if t.name=="ok" cb? true closeWindow t break t = t.parentNode exports.loginWindow=(cb=->app.refresh())-> win = showWindow "util-login" win.click (je)-> t=je.target while t? if t.name=="cancel" closeWindow win break t = t.parentNode $("#loginform").submit (je)-> je.preventDefault() form=je.target app.login form.elements["userid"].value, form.elements["password"].value,(result)-> if result if form.elements["remember_me"].checked # 記憶 localStorage.setItem "userid",form.elements["userid"].value localStorage.setItem "password", form.elements["password"].value cb() closeWindow win else $("#loginerror").text "账号或密码错误。" $("#newentryform").submit (je)-> je.preventDefault() form=je.target q= userid: form.elements["userid"].value password: form.elements["password"].value ss.rpc "user.newentry",q,(result)-> unless result.login $("#newentryerror").text result else localStorage.setItem "userid",q.userid localStorage.setItem "password", q.password closeWindow win # 初期情報を入力してもらう util.blindName {title:"情报输入",message:"请设定用户名"},(obj)-> # 登録する感じの ss.rpc "user.changeProfile", { password:q.password name:obj.name icon:obj.icon },(obj)-> if obj?.error? #错误 util.message "错误",obj.error else util.message "注册","注册成功。" app.setUserid q.userid cb() exports.iconSelectWindow=(def,cb)-> win = showWindow "util-iconselect" form=$("#iconform").get 0 # 头像决定 okicon=(url)-> $("#selecticondisp").attr "src",url def=url # 書き換え okicon def # さいしょ win.click (je)-> t=je.target while t? if t.name=="cancel" closeWindow win cb def # 変わっていない break else if t.name=="urliconbutton" util.prompt "头像","请输入头像图片的URL",null,(url)-> okicon url ? "" break else if t.name=="twittericonbutton" util.prompt "头像","请输入twitterID",null,(id)-> if id # It's 1.0! # okicon "http://api.twitter.com/1/users/profile_image/#{id}" ss.rpc "user.getTwitterIcon",id,(url)-> # 头像を取得 unless url util.message "错误","头像获取失败,请稍后再试。" okicon "" else okicon url else okicon "" break t = t.parentNode $("#iconform").submit (je)-> je.preventDefault() closeWindow win cb def #结果通知 exports.blindName=(opt={},cb)-> win = showWindow "util-blindname",{title:opt.title ? "加入游戏", message:opt.message ? "请输入昵称"} def=null win.click (je)-> t=je.target while t? if t.name=="cancel" closeWindow win cb null # 変わっていない break else if t.name=="iconselectbutton" util.iconSelectWindow null,(url)-> def=url ? null $("#icondisp").attr "src",def break t = t.parentNode $("#nameform").submit (je)-> je.preventDefault() #max bytes of blind name maxLength=20 je.target.elements["name"].value = je.target.elements["name"].value.trim() if je.target.elements["name"].value.trim() == '' util.message "错误","昵称不能仅为空格。" else if je.target.elements["name"].value.replace(/[^\x00-\xFF]/g,'**').length <= maxLength closeWindow win cb {name:je.target.elements["name"].value, icon:def} else byteSub = (str, maxLength) -> str = str.substr(0, str.length - 1) while str.replace(/[^\x00-\xFF]/g, "**").length > maxLength str je.target.elements["name"].value = byteSub(je.target.elements["name"].value, maxLength) util.message "错误","昵称不能超过"+maxLength+"个字节。" # Dateをtime要素に exports.timeFromDate=(date)-> zero2=(num)-> "00#{num}".slice -2 # 0埋め dat="#{date.getFullYear()}-#{zero2(date.getMonth()+1)}-#{zero2(date.getDate())}" tim="#{zero2(date.getHours())}:#{zero2(date.getMinutes())}:#{zero2(date.getSeconds())}" time=document.createElement "time" time.datetime="#{dat}T#{tim}+09:00" time.textContent="#{dat} #{tim}" time
175315
app=require '/app' util=require '/util' exports.showWindow=showWindow=(templatename,tmpl)-> de = document.documentElement bd = document.body sclf = bd.scrollLeft || de.scrollLeft sctp = bd.scrollTop || de.scrollTop x=Math.max 50,sclf+Math.floor(Math.random()*100-200+document.documentElement.clientWidth/2) y=Math.max 50,sctp+Math.floor(Math.random()*100-200+document.documentElement.clientHeight/2) win=$(JT["#{templatename}"](tmpl)).hide().css({left:"#{x}px",top:"#{y}px",}).appendTo("body").fadeIn().draggable() $(".getfocus",win.get(0)).focus() win #編集域を返す exports.blankWindow=(title)-> win=showWindow "util-blank", {title: title} div=document.createElement "div" div.classList.add "window-content" $("form[name='okform']",win).before div win.submit (je)-> je.preventDefault() win.click (je)-> t=je.target while t? if t.name=="ok" closeWindow t break t = t.parentNode $(div) #要素を含むWindowを消す exports.closeWindow=closeWindow= (node)-> w=$(node).closest(".window") w.hide "normal",-> w.remove() w.triggerHandler "close.window" exports.formQuery=(form)-> q={} el=form.elements for e in el if !e.disabled && e.name if (tag=e.tagName.toLowerCase())=="input" if e.type in ["radio","checkbox"] if e.checked q[e.name]=e.value else if e.type!="submit" && e.type!="reset" && e.type!="button" q[e.name]=e.value else if tag in["select","output","textarea"] q[e.name]=e.value q #true,false exports.ask=(title,message,cb)-> win = showWindow "util-ask",{title:title,message:message} win.submit (je)-> je.preventDefault() win.click (je)-> t=je.target while t? if t.name=="yes" cb true closeWindow t break else if t.name=="no" cb false closeWindow t break t = t.parentNode #String / null exports.prompt=(title,message,opt,cb)-> win = showWindow "util-prompt",{title:title,message:message} inp=win.find("input.prompt").get(0) for opv of opt inp[opv]=opt[opv] win.submit (je)-> je.preventDefault() win.click (je)-> t=je.target while t? if t.name=="ok" cb? inp.value closeWindow t break else if t.name=="cancel" cb? null closeWindow t break t = t.parentNode #猝死惩罚 exports.punish=(title,message,cb)-> win = showWindow "util-punish",{title:title,time:message.time} for user in message.userlist a = document.createElement "input" a.type="checkbox" a.name="userList" a.class="punish" a.value=user.userid b = document.createElement "label" $(b).append(a).append(user.name) $("#prePunishUser").append(b).append("<br>") ipt =-> # console.log("punish表单") # console.log(document.punish.userList) user=document.punish.userList; userChecked=[]; if !user[0] a=[] a.push user user=a for pl in user if pl.checked then userChecked.push pl.value # console.log(userChecked) userChecked win.submit (je)-> je.preventDefault() win.click (je)-> t=je.target if t.name=="ok" cb? ipt() closeWindow t else if t.name=="cancel" # cb? null closeWindow t #arr: [{name:"aaa",value:"foo"}, ...] exports.selectprompt=(title,message,arr,cb)-> win = showWindow "util-selectprompt",{title:title,message:message} sel=win.find("select.prompt").get(0) for obj in arr opt=document.createElement "option" opt.textContent=obj.name opt.value=obj.value sel.add opt win.submit (je)-> je.preventDefault() win.click (je)-> t=je.target while t? if t.name=="ok" cb? sel.value closeWindow t break else if t.name=="cancel" cb? null closeWindow t break t = t.parentNode exports.message=(title,message,cb)-> win = showWindow "util-wmessage",{title:title,message:message} win.submit (je)-> je.preventDefault() win.click (je)-> t=je.target while t? if t.name=="ok" cb? true closeWindow t break t = t.parentNode exports.loginWindow=(cb=->app.refresh())-> win = showWindow "util-login" win.click (je)-> t=je.target while t? if t.name=="cancel" closeWindow win break t = t.parentNode $("#loginform").submit (je)-> je.preventDefault() form=je.target app.login form.elements["userid"].value, form.elements["password"].value,(result)-> if result if form.elements["remember_me"].checked # 記憶 localStorage.setItem "userid",form.elements["userid"].value localStorage.setItem "password", form.elements["password"].value cb() closeWindow win else $("#loginerror").text "账号或密码错误。" $("#newentryform").submit (je)-> je.preventDefault() form=je.target q= userid: form.elements["userid"].value password: form.elements["password"].value ss.rpc "user.newentry",q,(result)-> unless result.login $("#newentryerror").text result else localStorage.setItem "userid",q.userid localStorage.setItem "password", <PASSWORD> closeWindow win # 初期情報を入力してもらう util.blindName {title:"情报输入",message:"请设定用户名"},(obj)-> # 登録する感じの ss.rpc "user.changeProfile", { password:<PASSWORD> name:obj.name icon:obj.icon },(obj)-> if obj?.error? #错误 util.message "错误",obj.error else util.message "注册","注册成功。" app.setUserid q.userid cb() exports.iconSelectWindow=(def,cb)-> win = showWindow "util-iconselect" form=$("#iconform").get 0 # 头像决定 okicon=(url)-> $("#selecticondisp").attr "src",url def=url # 書き換え okicon def # さいしょ win.click (je)-> t=je.target while t? if t.name=="cancel" closeWindow win cb def # 変わっていない break else if t.name=="urliconbutton" util.prompt "头像","请输入头像图片的URL",null,(url)-> okicon url ? "" break else if t.name=="twittericonbutton" util.prompt "头像","请输入twitterID",null,(id)-> if id # It's 1.0! # okicon "http://api.twitter.com/1/users/profile_image/#{id}" ss.rpc "user.getTwitterIcon",id,(url)-> # 头像を取得 unless url util.message "错误","头像获取失败,请稍后再试。" okicon "" else okicon url else okicon "" break t = t.parentNode $("#iconform").submit (je)-> je.preventDefault() closeWindow win cb def #结果通知 exports.blindName=(opt={},cb)-> win = showWindow "util-blindname",{title:opt.title ? "加入游戏", message:opt.message ? "请输入昵称"} def=null win.click (je)-> t=je.target while t? if t.name=="cancel" closeWindow win cb null # 変わっていない break else if t.name=="iconselectbutton" util.iconSelectWindow null,(url)-> def=url ? null $("#icondisp").attr "src",def break t = t.parentNode $("#nameform").submit (je)-> je.preventDefault() #max bytes of blind name maxLength=20 je.target.elements["name"].value = je.target.elements["name"].value.trim() if je.target.elements["name"].value.trim() == '' util.message "错误","昵称不能仅为空格。" else if je.target.elements["name"].value.replace(/[^\x00-\xFF]/g,'**').length <= maxLength closeWindow win cb {name:je.target.elements["name"].value, icon:def} else byteSub = (str, maxLength) -> str = str.substr(0, str.length - 1) while str.replace(/[^\x00-\xFF]/g, "**").length > maxLength str je.target.elements["name"].value = byteSub(je.target.elements["name"].value, maxLength) util.message "错误","昵称不能超过"+maxLength+"个字节。" # Dateをtime要素に exports.timeFromDate=(date)-> zero2=(num)-> "00#{num}".slice -2 # 0埋め dat="#{date.getFullYear()}-#{zero2(date.getMonth()+1)}-#{zero2(date.getDate())}" tim="#{zero2(date.getHours())}:#{zero2(date.getMinutes())}:#{zero2(date.getSeconds())}" time=document.createElement "time" time.datetime="#{dat}T#{tim}+09:00" time.textContent="#{dat} #{tim}" time
true
app=require '/app' util=require '/util' exports.showWindow=showWindow=(templatename,tmpl)-> de = document.documentElement bd = document.body sclf = bd.scrollLeft || de.scrollLeft sctp = bd.scrollTop || de.scrollTop x=Math.max 50,sclf+Math.floor(Math.random()*100-200+document.documentElement.clientWidth/2) y=Math.max 50,sctp+Math.floor(Math.random()*100-200+document.documentElement.clientHeight/2) win=$(JT["#{templatename}"](tmpl)).hide().css({left:"#{x}px",top:"#{y}px",}).appendTo("body").fadeIn().draggable() $(".getfocus",win.get(0)).focus() win #編集域を返す exports.blankWindow=(title)-> win=showWindow "util-blank", {title: title} div=document.createElement "div" div.classList.add "window-content" $("form[name='okform']",win).before div win.submit (je)-> je.preventDefault() win.click (je)-> t=je.target while t? if t.name=="ok" closeWindow t break t = t.parentNode $(div) #要素を含むWindowを消す exports.closeWindow=closeWindow= (node)-> w=$(node).closest(".window") w.hide "normal",-> w.remove() w.triggerHandler "close.window" exports.formQuery=(form)-> q={} el=form.elements for e in el if !e.disabled && e.name if (tag=e.tagName.toLowerCase())=="input" if e.type in ["radio","checkbox"] if e.checked q[e.name]=e.value else if e.type!="submit" && e.type!="reset" && e.type!="button" q[e.name]=e.value else if tag in["select","output","textarea"] q[e.name]=e.value q #true,false exports.ask=(title,message,cb)-> win = showWindow "util-ask",{title:title,message:message} win.submit (je)-> je.preventDefault() win.click (je)-> t=je.target while t? if t.name=="yes" cb true closeWindow t break else if t.name=="no" cb false closeWindow t break t = t.parentNode #String / null exports.prompt=(title,message,opt,cb)-> win = showWindow "util-prompt",{title:title,message:message} inp=win.find("input.prompt").get(0) for opv of opt inp[opv]=opt[opv] win.submit (je)-> je.preventDefault() win.click (je)-> t=je.target while t? if t.name=="ok" cb? inp.value closeWindow t break else if t.name=="cancel" cb? null closeWindow t break t = t.parentNode #猝死惩罚 exports.punish=(title,message,cb)-> win = showWindow "util-punish",{title:title,time:message.time} for user in message.userlist a = document.createElement "input" a.type="checkbox" a.name="userList" a.class="punish" a.value=user.userid b = document.createElement "label" $(b).append(a).append(user.name) $("#prePunishUser").append(b).append("<br>") ipt =-> # console.log("punish表单") # console.log(document.punish.userList) user=document.punish.userList; userChecked=[]; if !user[0] a=[] a.push user user=a for pl in user if pl.checked then userChecked.push pl.value # console.log(userChecked) userChecked win.submit (je)-> je.preventDefault() win.click (je)-> t=je.target if t.name=="ok" cb? ipt() closeWindow t else if t.name=="cancel" # cb? null closeWindow t #arr: [{name:"aaa",value:"foo"}, ...] exports.selectprompt=(title,message,arr,cb)-> win = showWindow "util-selectprompt",{title:title,message:message} sel=win.find("select.prompt").get(0) for obj in arr opt=document.createElement "option" opt.textContent=obj.name opt.value=obj.value sel.add opt win.submit (je)-> je.preventDefault() win.click (je)-> t=je.target while t? if t.name=="ok" cb? sel.value closeWindow t break else if t.name=="cancel" cb? null closeWindow t break t = t.parentNode exports.message=(title,message,cb)-> win = showWindow "util-wmessage",{title:title,message:message} win.submit (je)-> je.preventDefault() win.click (je)-> t=je.target while t? if t.name=="ok" cb? true closeWindow t break t = t.parentNode exports.loginWindow=(cb=->app.refresh())-> win = showWindow "util-login" win.click (je)-> t=je.target while t? if t.name=="cancel" closeWindow win break t = t.parentNode $("#loginform").submit (je)-> je.preventDefault() form=je.target app.login form.elements["userid"].value, form.elements["password"].value,(result)-> if result if form.elements["remember_me"].checked # 記憶 localStorage.setItem "userid",form.elements["userid"].value localStorage.setItem "password", form.elements["password"].value cb() closeWindow win else $("#loginerror").text "账号或密码错误。" $("#newentryform").submit (je)-> je.preventDefault() form=je.target q= userid: form.elements["userid"].value password: form.elements["password"].value ss.rpc "user.newentry",q,(result)-> unless result.login $("#newentryerror").text result else localStorage.setItem "userid",q.userid localStorage.setItem "password", PI:PASSWORD:<PASSWORD>END_PI closeWindow win # 初期情報を入力してもらう util.blindName {title:"情报输入",message:"请设定用户名"},(obj)-> # 登録する感じの ss.rpc "user.changeProfile", { password:PI:PASSWORD:<PASSWORD>END_PI name:obj.name icon:obj.icon },(obj)-> if obj?.error? #错误 util.message "错误",obj.error else util.message "注册","注册成功。" app.setUserid q.userid cb() exports.iconSelectWindow=(def,cb)-> win = showWindow "util-iconselect" form=$("#iconform").get 0 # 头像决定 okicon=(url)-> $("#selecticondisp").attr "src",url def=url # 書き換え okicon def # さいしょ win.click (je)-> t=je.target while t? if t.name=="cancel" closeWindow win cb def # 変わっていない break else if t.name=="urliconbutton" util.prompt "头像","请输入头像图片的URL",null,(url)-> okicon url ? "" break else if t.name=="twittericonbutton" util.prompt "头像","请输入twitterID",null,(id)-> if id # It's 1.0! # okicon "http://api.twitter.com/1/users/profile_image/#{id}" ss.rpc "user.getTwitterIcon",id,(url)-> # 头像を取得 unless url util.message "错误","头像获取失败,请稍后再试。" okicon "" else okicon url else okicon "" break t = t.parentNode $("#iconform").submit (je)-> je.preventDefault() closeWindow win cb def #结果通知 exports.blindName=(opt={},cb)-> win = showWindow "util-blindname",{title:opt.title ? "加入游戏", message:opt.message ? "请输入昵称"} def=null win.click (je)-> t=je.target while t? if t.name=="cancel" closeWindow win cb null # 変わっていない break else if t.name=="iconselectbutton" util.iconSelectWindow null,(url)-> def=url ? null $("#icondisp").attr "src",def break t = t.parentNode $("#nameform").submit (je)-> je.preventDefault() #max bytes of blind name maxLength=20 je.target.elements["name"].value = je.target.elements["name"].value.trim() if je.target.elements["name"].value.trim() == '' util.message "错误","昵称不能仅为空格。" else if je.target.elements["name"].value.replace(/[^\x00-\xFF]/g,'**').length <= maxLength closeWindow win cb {name:je.target.elements["name"].value, icon:def} else byteSub = (str, maxLength) -> str = str.substr(0, str.length - 1) while str.replace(/[^\x00-\xFF]/g, "**").length > maxLength str je.target.elements["name"].value = byteSub(je.target.elements["name"].value, maxLength) util.message "错误","昵称不能超过"+maxLength+"个字节。" # Dateをtime要素に exports.timeFromDate=(date)-> zero2=(num)-> "00#{num}".slice -2 # 0埋め dat="#{date.getFullYear()}-#{zero2(date.getMonth()+1)}-#{zero2(date.getDate())}" tim="#{zero2(date.getHours())}:#{zero2(date.getMinutes())}:#{zero2(date.getSeconds())}" time=document.createElement "time" time.datetime="#{dat}T#{tim}+09:00" time.textContent="#{dat} #{tim}" time
[ { "context": "* @package\t\tHome\n * @category\tmodules\n * @author\t\tNazar Mokrynskyi <nazar@mokrynskyi.com>\n * @copyright\tCopyright (c", "end": 71, "score": 0.9998817443847656, "start": 55, "tag": "NAME", "value": "Nazar Mokrynskyi" }, { "context": "* @category\tmodules\n * @aut...
components/modules/Home/includes/js/_map.coffee
nazar-pc/cherrytea.org-old
1
### * @package Home * @category modules * @author Nazar Mokrynskyi <nazar@mokrynskyi.com> * @copyright Copyright (c) 2013-2014, Nazar Mokrynskyi * @license MIT License, see license.txt ### $ -> map_container = $('#map') if !map_container.length return ymaps.ready -> # Map resizing on initialization and window resize do -> map_resize = -> w = $(window).width() $('#map') .css( width : w marginLeft : 500 - w / 2 ) map_resize() $(window).resize(map_resize) window.map = new ymaps.Map 'map', { center : [50.4505, 30.523] zoom : 13 controls : ['geolocationControl', 'fullscreenControl', 'typeSelector', 'zoomControl'] } map.behaviors.disable('scrollZoom') if navigator.geolocation navigator.geolocation.getCurrentPosition( (position) -> map.setCenter([position.coords.latitude, position.coords.longitude]) -> { enableHighAccuracy : true timeout : 30 * 60 * 1000 #Wait for 30 minutes max } ) map.icons_shape = new ymaps.shape.Polygon(new ymaps.geometry.pixel.Polygon([ [ [17-24, 0-58], [30-24, 0-58], [41-24, 7-58], [47-24, 18-58], [47-24, 29-58], [42-24, 38-58], [24-24, 57-58], [8-24, 42-58], [0-24, 30-58], [0-24, 18-58], [6-24, 7-58], [17-24, 0-58] ] ])) map.geoObjects.add( new ymaps.Placemark( [50.487124, 30.596273] { hintContent : 'Благодійний фонд Карітас-Київ' } { iconLayout : 'default#image' iconImageHref : '/components/modules/Home/includes/img/destination.png' iconImageSize : [60, 58] iconImageOffset : [-24, -58] iconImageShape : map.icons_shape balloonLayout : ymaps.templateLayoutFactory.createClass( """<section class="home-page-map-balloon-container centers"> <header><h1>Благодійний фонд Карітас Київ</h1> <a class="uk-close" onclick="map.balloon.close()"></a></header> <article> <address>вулиця Івана Микитенка, 7б</address> <time>Будні: з 9:00 до 18:00<br>Вихідні: з 10:00 до 15:00</time> </article> </section>""" ) } ) ) map.geoObjects.add( new ymaps.Placemark( [50.461404, 30.519216] { hintContent : 'Книжковий магазин Свічадо' } { iconLayout : 'default#image' iconImageHref : '/components/modules/Home/includes/img/destination.png' iconImageSize : [60, 58] iconImageOffset : [-24, -58] iconImageShape : map.icons_shape balloonLayout : ymaps.templateLayoutFactory.createClass( """<section class="home-page-map-balloon-container centers"> <header><h1>Книжковий магазин Свічадо</h1> <a class="uk-close" onclick="map.balloon.close()"></a></header> <article> <address>вулиця Покровська, 6</address> <time>Будні: з 10:00 до 17:00</time> </article> </section>""" ) } ) ) map.geoObjects.add( new ymaps.Placemark( [46.475433,30.719122] { hintContent : 'Благодійний фонд Карітас-Одеса' } { iconLayout : 'default#image' iconImageHref : '/components/modules/Home/includes/img/destination.png' iconImageSize : [60, 58] iconImageOffset : [-24, -58] iconImageShape : map.icons_shape balloonLayout : ymaps.templateLayoutFactory.createClass( """<section class="home-page-map-balloon-container centers"> <header><h1>Карітас Одеса</h1> <a class="uk-close" onclick="map.balloon.close()"></a></header> <article> <address>вул. Південна, 40/1</address> <time>Будні: з 09:00 до 18:00</time> <p style="color:#0097fc">тел./факс: +38 048 712 38 60</p> <p style="color:#0097fc">e-mail: <a href="mailto:caritasodessa@ukr.net">caritasodessa@ukr.net</a></p> </article> </section>""" ) } ) ) filter = $('.cs-home-page-filter') filter.find('input[name=date]') .pickmeup( format : 'd.m.Y' change : (formated) -> filter .find('[name=date]') .val(formated) .pickmeup('hide') .change(); ) filter.find('[name=time]') .next() .find('a') .click -> filter .find('[name=time]') .val($(@).text()) .change() filter.find('.cs-home-page-filter-reservation a').click -> $this = $(@) root = $('.cs-home-page-filter-reservation') root .data('value', $this.data('value')) .find('button') .html($this.html()) find_goods() clusterer = new ymaps.Clusterer() clusterer.createCluster = (center, geoObjects) -> cluster = ymaps.Clusterer.prototype.createCluster.call(this, center, geoObjects) cluster.options.set( icons : [ { href : '/components/modules/Home/includes/img/cluster-46.png' size : [46, 46] offset : [-23, -23] } { href : '/components/modules/Home/includes/img/cluster-58.png' size : [58, 58] offset : [-27, -27] } ] ) cluster map.geoObjects.add(clusterer) find_goods = -> show_goods = $('.cs-home-page-map-goods-switcher .uk-active input').val() if show_goods == 'all' && $('.cs-home-page-filter-reservation').data('value') == 1 show_goods = 'reserved' if show_goods == 'my' $('#map, .cs-home-page-filter').hide() $('.cs-home-page-my-goods-list').html('<p class="uk-margin cs-center"><i class="uk-icon-spin uk-icon-spinner"></i></p>') $('.cs-home-page-my-goods').show() else $('#map, .cs-home-page-filter').show() $('.cs-home-page-my-goods-list').html('') $('.cs-home-page-my-goods').hide() $.ajax( url : 'api/Home/goods' data : date : filter.find('input[name=date]').val() time : filter.find('[name=time]').val() show_goods : show_goods type : 'get' success : (result) -> if result && result.length if show_goods != 'my' placemarks = [] for good in result icon_number = Math.round(Math.random() * 11) if window.driver reservation = if window.driver == parseInt(good.reserved_driver, 10) && good.reserved > (new Date).getTime() / 1000 """<button class="reserved uk-button" data-id="#{good.id}">Зарезервовано</button>""" else """<button class="reservation uk-button" data-id="#{good.id}">Заберу за 24 години</button>""" else reservation = '' delete_button = if window.cs.is_admin || (window.volunteer && good.giver == window.volunteer) """<span class="uk-icon-trash-o cs-home-page-delete-good" data-id="#{good.id}"></span>""" else '' username = if good.profile_link """<a href="#{good.profile_link}" target="_blank">#{good.username}</a>""" else good.username show_details = window.driver || (window.volunteer && good.giver == window.volunteer) placemarks.push( new ymaps.Placemark( [ good.lat good.lng ] { hintContent : if show_details then good.username + ' ' + good.phone else undefined balloonContentHeader : if show_details then delete_button + good.username + ' ' + good.phone else undefined balloonContentBody : if show_details then """<section class="home-page-map-balloon-container"> <article> <address>#{good.address}</address> <time>#{good.date} (#{good.time})</time> <p>#{good.comment}</p> </article> <footer>#{reservation}</footer> </section>""" else undefined } { cursor : if cs.is_user then 'pointer' else 'default' iconLayout : 'default#image' iconImageHref : if good.success != '-1' then '/components/modules/Home/includes/img/finished-icon.png' else '/components/modules/Home/includes/img/map-icons.png' iconImageSize : if good.success != '-1' then [29, 29] else [60, 58] iconImageOffset : if good.success != '-1' then [-8, -29] else [-24, -58] iconImageClipRect : if good.success != '-1' then [0, 0] else [[60 * icon_number, 0], [60 * (icon_number + 1), 58]] iconImageShape : map.icons_shape balloonLayout : if show_details then ymaps.templateLayoutFactory.createClass( """<section class="home-page-map-balloon-container"> <header><h1>#{username} <small>#{good.phone}</small></h1> #{delete_button}<a class="uk-close" onclick="map.balloon.close()"></a></header> <article> <address>#{good.address}</address> <time>#{good.date} (#{good.time})</time> <p>#{good.comment}</p> </article> <footer>#{reservation}</footer> </section>""" ) else undefined } ) ) clusterer.removeAll() if cs.is_guest do -> for placemark, placemark of placemarks map.geoObjects.add(placemark) else clusterer.add(placemarks) else content = '' for good in result show_delete_button = true if good.given == '0' && good.success == '-1' && good.reserved > (new Date).getTime() / 1000 state = 'Зарезервовано водієм' icon_h_offset = 97 else if good.success != '-1' state = 'Доставлено' icon_h_offset = 2 * 97 show_delete_button = false else state = 'Очікує' icon_h_offset = 0 icon_v_offset = Math.round(Math.random() * 5) * 97 confirm = if good.given == '0' && good.success == '-1' then """<button class="cs-home-page-confirm-good uk-button" data-id="#{good.id}"><i class="uk-icon-check"></i> Водій забрав речі</button>""" else '' content += """<aside> <div class="icon" style="background-position: -#{icon_h_offset}px -#{icon_v_offset}px"></div> <h2>#{state}</h2> <span>#{good.phone}</span> <address>#{good.address}</address> <time>#{good.date} (#{good.time})</time> <p>#{good.comment}</p> <p> #{confirm} """ + (if show_delete_button then """ <button class="cs-home-page-delete-good uk-button" data-id="#{good.id}"><i class="uk-icon-times"></i></button>""" else '') + """ </p> </aside>""" $('.cs-home-page-my-goods-list').html(content) else clusterer.removeAll() $('.cs-home-page-my-goods-list').html('<p class="cs-center">Речей не знайдено</p>') return ) find_goods() map_container .on( 'click' '.reservation' -> reservation = $(@) $.ajax( url : 'api/Home/reservation' type : 'post' data : id : reservation.data('id') success : -> reservation .html('Зарезервовано') .removeClass('reservation') .addClass('reserved') alert 'Зарезервовано! Дякуємо та чекаємо вашого приїзду!' find_goods() error : (xhr) -> if xhr.responseText alert(cs.json_decode(xhr.responseText).error_description) else alert(L.auth_connection_error) ) ) .on( 'click' '.reserved' -> reserved = $(@) $.ajax( url : 'api/Home/reservation' type : 'delete' data : id : reserved.data('id') success : -> reserved .html('Заберу за 24 години') .removeClass('reserved') .addClass('reservation') alert 'Резерв скасовано! Дякуємо що попередили!' find_goods() error : (xhr) -> if xhr.responseText alert(cs.json_decode(xhr.responseText).error_description) else alert(L.auth_connection_error) ) ) search_timeout = 0 filter.on( 'keyup change' '[name=date], [name=time], .cs-home-page-map-goods-switcher input' -> clearTimeout(search_timeout) search_timeout = setTimeout(find_goods, 300) ) $('.cs-home-page-map-goods-switcher').on( 'keyup change' 'input' -> clearTimeout(search_timeout) search_timeout = setTimeout(find_goods, 300) ) $(document).on( 'click' '.cs-home-page-delete-good' -> if !confirm('Точно видалити?') return $.ajax( url : 'api/Home/goods/' + $(this).data('id') type : 'delete' success : -> find_goods() ) )
191936
### * @package Home * @category modules * @author <NAME> <<EMAIL>> * @copyright Copyright (c) 2013-2014, <NAME> * @license MIT License, see license.txt ### $ -> map_container = $('#map') if !map_container.length return ymaps.ready -> # Map resizing on initialization and window resize do -> map_resize = -> w = $(window).width() $('#map') .css( width : w marginLeft : 500 - w / 2 ) map_resize() $(window).resize(map_resize) window.map = new ymaps.Map 'map', { center : [50.4505, 30.523] zoom : 13 controls : ['geolocationControl', 'fullscreenControl', 'typeSelector', 'zoomControl'] } map.behaviors.disable('scrollZoom') if navigator.geolocation navigator.geolocation.getCurrentPosition( (position) -> map.setCenter([position.coords.latitude, position.coords.longitude]) -> { enableHighAccuracy : true timeout : 30 * 60 * 1000 #Wait for 30 minutes max } ) map.icons_shape = new ymaps.shape.Polygon(new ymaps.geometry.pixel.Polygon([ [ [17-24, 0-58], [30-24, 0-58], [41-24, 7-58], [47-24, 18-58], [47-24, 29-58], [42-24, 38-58], [24-24, 57-58], [8-24, 42-58], [0-24, 30-58], [0-24, 18-58], [6-24, 7-58], [17-24, 0-58] ] ])) map.geoObjects.add( new ymaps.Placemark( [50.487124, 30.596273] { hintContent : 'Благодійний фонд Карітас-Київ' } { iconLayout : 'default#image' iconImageHref : '/components/modules/Home/includes/img/destination.png' iconImageSize : [60, 58] iconImageOffset : [-24, -58] iconImageShape : map.icons_shape balloonLayout : ymaps.templateLayoutFactory.createClass( """<section class="home-page-map-balloon-container centers"> <header><h1>Благодійний фонд Карітас Київ</h1> <a class="uk-close" onclick="map.balloon.close()"></a></header> <article> <address>вулиця Івана Микитенка, 7б</address> <time>Будні: з 9:00 до 18:00<br>Вихідні: з 10:00 до 15:00</time> </article> </section>""" ) } ) ) map.geoObjects.add( new ymaps.Placemark( [50.461404, 30.519216] { hintContent : 'Книжковий магазин Свічадо' } { iconLayout : 'default#image' iconImageHref : '/components/modules/Home/includes/img/destination.png' iconImageSize : [60, 58] iconImageOffset : [-24, -58] iconImageShape : map.icons_shape balloonLayout : ymaps.templateLayoutFactory.createClass( """<section class="home-page-map-balloon-container centers"> <header><h1>Книжковий магазин Свічадо</h1> <a class="uk-close" onclick="map.balloon.close()"></a></header> <article> <address>вулиця Покровська, 6</address> <time>Будні: з 10:00 до 17:00</time> </article> </section>""" ) } ) ) map.geoObjects.add( new ymaps.Placemark( [46.475433,30.719122] { hintContent : 'Благодійний фонд <NAME>арітас-Одеса' } { iconLayout : 'default#image' iconImageHref : '/components/modules/Home/includes/img/destination.png' iconImageSize : [60, 58] iconImageOffset : [-24, -58] iconImageShape : map.icons_shape balloonLayout : ymaps.templateLayoutFactory.createClass( """<section class="home-page-map-balloon-container centers"> <header><h1>Карітас Одеса</h1> <a class="uk-close" onclick="map.balloon.close()"></a></header> <article> <address>вул. Південна, 40/1</address> <time>Будні: з 09:00 до 18:00</time> <p style="color:#0097fc">тел./факс: +38 048 712 38 60</p> <p style="color:#0097fc">e-mail: <a href="mailto:<EMAIL>"><EMAIL></a></p> </article> </section>""" ) } ) ) filter = $('.cs-home-page-filter') filter.find('input[name=date]') .pickmeup( format : 'd.m.Y' change : (formated) -> filter .find('[name=date]') .val(formated) .pickmeup('hide') .change(); ) filter.find('[name=time]') .next() .find('a') .click -> filter .find('[name=time]') .val($(@).text()) .change() filter.find('.cs-home-page-filter-reservation a').click -> $this = $(@) root = $('.cs-home-page-filter-reservation') root .data('value', $this.data('value')) .find('button') .html($this.html()) find_goods() clusterer = new ymaps.Clusterer() clusterer.createCluster = (center, geoObjects) -> cluster = ymaps.Clusterer.prototype.createCluster.call(this, center, geoObjects) cluster.options.set( icons : [ { href : '/components/modules/Home/includes/img/cluster-46.png' size : [46, 46] offset : [-23, -23] } { href : '/components/modules/Home/includes/img/cluster-58.png' size : [58, 58] offset : [-27, -27] } ] ) cluster map.geoObjects.add(clusterer) find_goods = -> show_goods = $('.cs-home-page-map-goods-switcher .uk-active input').val() if show_goods == 'all' && $('.cs-home-page-filter-reservation').data('value') == 1 show_goods = 'reserved' if show_goods == 'my' $('#map, .cs-home-page-filter').hide() $('.cs-home-page-my-goods-list').html('<p class="uk-margin cs-center"><i class="uk-icon-spin uk-icon-spinner"></i></p>') $('.cs-home-page-my-goods').show() else $('#map, .cs-home-page-filter').show() $('.cs-home-page-my-goods-list').html('') $('.cs-home-page-my-goods').hide() $.ajax( url : 'api/Home/goods' data : date : filter.find('input[name=date]').val() time : filter.find('[name=time]').val() show_goods : show_goods type : 'get' success : (result) -> if result && result.length if show_goods != 'my' placemarks = [] for good in result icon_number = Math.round(Math.random() * 11) if window.driver reservation = if window.driver == parseInt(good.reserved_driver, 10) && good.reserved > (new Date).getTime() / 1000 """<button class="reserved uk-button" data-id="#{good.id}">Зарезервовано</button>""" else """<button class="reservation uk-button" data-id="#{good.id}">Заберу за 24 години</button>""" else reservation = '' delete_button = if window.cs.is_admin || (window.volunteer && good.giver == window.volunteer) """<span class="uk-icon-trash-o cs-home-page-delete-good" data-id="#{good.id}"></span>""" else '' username = if good.profile_link """<a href="#{good.profile_link}" target="_blank">#{good.username}</a>""" else good.username show_details = window.driver || (window.volunteer && good.giver == window.volunteer) placemarks.push( new ymaps.Placemark( [ good.lat good.lng ] { hintContent : if show_details then good.username + ' ' + good.phone else undefined balloonContentHeader : if show_details then delete_button + good.username + ' ' + good.phone else undefined balloonContentBody : if show_details then """<section class="home-page-map-balloon-container"> <article> <address>#{good.address}</address> <time>#{good.date} (#{good.time})</time> <p>#{good.comment}</p> </article> <footer>#{reservation}</footer> </section>""" else undefined } { cursor : if cs.is_user then 'pointer' else 'default' iconLayout : 'default#image' iconImageHref : if good.success != '-1' then '/components/modules/Home/includes/img/finished-icon.png' else '/components/modules/Home/includes/img/map-icons.png' iconImageSize : if good.success != '-1' then [29, 29] else [60, 58] iconImageOffset : if good.success != '-1' then [-8, -29] else [-24, -58] iconImageClipRect : if good.success != '-1' then [0, 0] else [[60 * icon_number, 0], [60 * (icon_number + 1), 58]] iconImageShape : map.icons_shape balloonLayout : if show_details then ymaps.templateLayoutFactory.createClass( """<section class="home-page-map-balloon-container"> <header><h1>#{username} <small>#{good.phone}</small></h1> #{delete_button}<a class="uk-close" onclick="map.balloon.close()"></a></header> <article> <address>#{good.address}</address> <time>#{good.date} (#{good.time})</time> <p>#{good.comment}</p> </article> <footer>#{reservation}</footer> </section>""" ) else undefined } ) ) clusterer.removeAll() if cs.is_guest do -> for placemark, placemark of placemarks map.geoObjects.add(placemark) else clusterer.add(placemarks) else content = '' for good in result show_delete_button = true if good.given == '0' && good.success == '-1' && good.reserved > (new Date).getTime() / 1000 state = 'Зарезервовано водієм' icon_h_offset = 97 else if good.success != '-1' state = 'Доставлено' icon_h_offset = 2 * 97 show_delete_button = false else state = 'Очікує' icon_h_offset = 0 icon_v_offset = Math.round(Math.random() * 5) * 97 confirm = if good.given == '0' && good.success == '-1' then """<button class="cs-home-page-confirm-good uk-button" data-id="#{good.id}"><i class="uk-icon-check"></i> Водій забрав речі</button>""" else '' content += """<aside> <div class="icon" style="background-position: -#{icon_h_offset}px -#{icon_v_offset}px"></div> <h2>#{state}</h2> <span>#{good.phone}</span> <address>#{good.address}</address> <time>#{good.date} (#{good.time})</time> <p>#{good.comment}</p> <p> #{confirm} """ + (if show_delete_button then """ <button class="cs-home-page-delete-good uk-button" data-id="#{good.id}"><i class="uk-icon-times"></i></button>""" else '') + """ </p> </aside>""" $('.cs-home-page-my-goods-list').html(content) else clusterer.removeAll() $('.cs-home-page-my-goods-list').html('<p class="cs-center">Речей не знайдено</p>') return ) find_goods() map_container .on( 'click' '.reservation' -> reservation = $(@) $.ajax( url : 'api/Home/reservation' type : 'post' data : id : reservation.data('id') success : -> reservation .html('Зарезервовано') .removeClass('reservation') .addClass('reserved') alert 'Зарезервовано! Дякуємо та чекаємо вашого приїзду!' find_goods() error : (xhr) -> if xhr.responseText alert(cs.json_decode(xhr.responseText).error_description) else alert(L.auth_connection_error) ) ) .on( 'click' '.reserved' -> reserved = $(@) $.ajax( url : 'api/Home/reservation' type : 'delete' data : id : reserved.data('id') success : -> reserved .html('Заберу за 24 години') .removeClass('reserved') .addClass('reservation') alert 'Резерв скасовано! Дякуємо що попередили!' find_goods() error : (xhr) -> if xhr.responseText alert(cs.json_decode(xhr.responseText).error_description) else alert(L.auth_connection_error) ) ) search_timeout = 0 filter.on( 'keyup change' '[name=date], [name=time], .cs-home-page-map-goods-switcher input' -> clearTimeout(search_timeout) search_timeout = setTimeout(find_goods, 300) ) $('.cs-home-page-map-goods-switcher').on( 'keyup change' 'input' -> clearTimeout(search_timeout) search_timeout = setTimeout(find_goods, 300) ) $(document).on( 'click' '.cs-home-page-delete-good' -> if !confirm('Точно видалити?') return $.ajax( url : 'api/Home/goods/' + $(this).data('id') type : 'delete' success : -> find_goods() ) )
true
### * @package Home * @category modules * @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> * @copyright Copyright (c) 2013-2014, PI:NAME:<NAME>END_PI * @license MIT License, see license.txt ### $ -> map_container = $('#map') if !map_container.length return ymaps.ready -> # Map resizing on initialization and window resize do -> map_resize = -> w = $(window).width() $('#map') .css( width : w marginLeft : 500 - w / 2 ) map_resize() $(window).resize(map_resize) window.map = new ymaps.Map 'map', { center : [50.4505, 30.523] zoom : 13 controls : ['geolocationControl', 'fullscreenControl', 'typeSelector', 'zoomControl'] } map.behaviors.disable('scrollZoom') if navigator.geolocation navigator.geolocation.getCurrentPosition( (position) -> map.setCenter([position.coords.latitude, position.coords.longitude]) -> { enableHighAccuracy : true timeout : 30 * 60 * 1000 #Wait for 30 minutes max } ) map.icons_shape = new ymaps.shape.Polygon(new ymaps.geometry.pixel.Polygon([ [ [17-24, 0-58], [30-24, 0-58], [41-24, 7-58], [47-24, 18-58], [47-24, 29-58], [42-24, 38-58], [24-24, 57-58], [8-24, 42-58], [0-24, 30-58], [0-24, 18-58], [6-24, 7-58], [17-24, 0-58] ] ])) map.geoObjects.add( new ymaps.Placemark( [50.487124, 30.596273] { hintContent : 'Благодійний фонд Карітас-Київ' } { iconLayout : 'default#image' iconImageHref : '/components/modules/Home/includes/img/destination.png' iconImageSize : [60, 58] iconImageOffset : [-24, -58] iconImageShape : map.icons_shape balloonLayout : ymaps.templateLayoutFactory.createClass( """<section class="home-page-map-balloon-container centers"> <header><h1>Благодійний фонд Карітас Київ</h1> <a class="uk-close" onclick="map.balloon.close()"></a></header> <article> <address>вулиця Івана Микитенка, 7б</address> <time>Будні: з 9:00 до 18:00<br>Вихідні: з 10:00 до 15:00</time> </article> </section>""" ) } ) ) map.geoObjects.add( new ymaps.Placemark( [50.461404, 30.519216] { hintContent : 'Книжковий магазин Свічадо' } { iconLayout : 'default#image' iconImageHref : '/components/modules/Home/includes/img/destination.png' iconImageSize : [60, 58] iconImageOffset : [-24, -58] iconImageShape : map.icons_shape balloonLayout : ymaps.templateLayoutFactory.createClass( """<section class="home-page-map-balloon-container centers"> <header><h1>Книжковий магазин Свічадо</h1> <a class="uk-close" onclick="map.balloon.close()"></a></header> <article> <address>вулиця Покровська, 6</address> <time>Будні: з 10:00 до 17:00</time> </article> </section>""" ) } ) ) map.geoObjects.add( new ymaps.Placemark( [46.475433,30.719122] { hintContent : 'Благодійний фонд PI:NAME:<NAME>END_PIарітас-Одеса' } { iconLayout : 'default#image' iconImageHref : '/components/modules/Home/includes/img/destination.png' iconImageSize : [60, 58] iconImageOffset : [-24, -58] iconImageShape : map.icons_shape balloonLayout : ymaps.templateLayoutFactory.createClass( """<section class="home-page-map-balloon-container centers"> <header><h1>Карітас Одеса</h1> <a class="uk-close" onclick="map.balloon.close()"></a></header> <article> <address>вул. Південна, 40/1</address> <time>Будні: з 09:00 до 18:00</time> <p style="color:#0097fc">тел./факс: +38 048 712 38 60</p> <p style="color:#0097fc">e-mail: <a href="mailto:PI:EMAIL:<EMAIL>END_PI">PI:EMAIL:<EMAIL>END_PI</a></p> </article> </section>""" ) } ) ) filter = $('.cs-home-page-filter') filter.find('input[name=date]') .pickmeup( format : 'd.m.Y' change : (formated) -> filter .find('[name=date]') .val(formated) .pickmeup('hide') .change(); ) filter.find('[name=time]') .next() .find('a') .click -> filter .find('[name=time]') .val($(@).text()) .change() filter.find('.cs-home-page-filter-reservation a').click -> $this = $(@) root = $('.cs-home-page-filter-reservation') root .data('value', $this.data('value')) .find('button') .html($this.html()) find_goods() clusterer = new ymaps.Clusterer() clusterer.createCluster = (center, geoObjects) -> cluster = ymaps.Clusterer.prototype.createCluster.call(this, center, geoObjects) cluster.options.set( icons : [ { href : '/components/modules/Home/includes/img/cluster-46.png' size : [46, 46] offset : [-23, -23] } { href : '/components/modules/Home/includes/img/cluster-58.png' size : [58, 58] offset : [-27, -27] } ] ) cluster map.geoObjects.add(clusterer) find_goods = -> show_goods = $('.cs-home-page-map-goods-switcher .uk-active input').val() if show_goods == 'all' && $('.cs-home-page-filter-reservation').data('value') == 1 show_goods = 'reserved' if show_goods == 'my' $('#map, .cs-home-page-filter').hide() $('.cs-home-page-my-goods-list').html('<p class="uk-margin cs-center"><i class="uk-icon-spin uk-icon-spinner"></i></p>') $('.cs-home-page-my-goods').show() else $('#map, .cs-home-page-filter').show() $('.cs-home-page-my-goods-list').html('') $('.cs-home-page-my-goods').hide() $.ajax( url : 'api/Home/goods' data : date : filter.find('input[name=date]').val() time : filter.find('[name=time]').val() show_goods : show_goods type : 'get' success : (result) -> if result && result.length if show_goods != 'my' placemarks = [] for good in result icon_number = Math.round(Math.random() * 11) if window.driver reservation = if window.driver == parseInt(good.reserved_driver, 10) && good.reserved > (new Date).getTime() / 1000 """<button class="reserved uk-button" data-id="#{good.id}">Зарезервовано</button>""" else """<button class="reservation uk-button" data-id="#{good.id}">Заберу за 24 години</button>""" else reservation = '' delete_button = if window.cs.is_admin || (window.volunteer && good.giver == window.volunteer) """<span class="uk-icon-trash-o cs-home-page-delete-good" data-id="#{good.id}"></span>""" else '' username = if good.profile_link """<a href="#{good.profile_link}" target="_blank">#{good.username}</a>""" else good.username show_details = window.driver || (window.volunteer && good.giver == window.volunteer) placemarks.push( new ymaps.Placemark( [ good.lat good.lng ] { hintContent : if show_details then good.username + ' ' + good.phone else undefined balloonContentHeader : if show_details then delete_button + good.username + ' ' + good.phone else undefined balloonContentBody : if show_details then """<section class="home-page-map-balloon-container"> <article> <address>#{good.address}</address> <time>#{good.date} (#{good.time})</time> <p>#{good.comment}</p> </article> <footer>#{reservation}</footer> </section>""" else undefined } { cursor : if cs.is_user then 'pointer' else 'default' iconLayout : 'default#image' iconImageHref : if good.success != '-1' then '/components/modules/Home/includes/img/finished-icon.png' else '/components/modules/Home/includes/img/map-icons.png' iconImageSize : if good.success != '-1' then [29, 29] else [60, 58] iconImageOffset : if good.success != '-1' then [-8, -29] else [-24, -58] iconImageClipRect : if good.success != '-1' then [0, 0] else [[60 * icon_number, 0], [60 * (icon_number + 1), 58]] iconImageShape : map.icons_shape balloonLayout : if show_details then ymaps.templateLayoutFactory.createClass( """<section class="home-page-map-balloon-container"> <header><h1>#{username} <small>#{good.phone}</small></h1> #{delete_button}<a class="uk-close" onclick="map.balloon.close()"></a></header> <article> <address>#{good.address}</address> <time>#{good.date} (#{good.time})</time> <p>#{good.comment}</p> </article> <footer>#{reservation}</footer> </section>""" ) else undefined } ) ) clusterer.removeAll() if cs.is_guest do -> for placemark, placemark of placemarks map.geoObjects.add(placemark) else clusterer.add(placemarks) else content = '' for good in result show_delete_button = true if good.given == '0' && good.success == '-1' && good.reserved > (new Date).getTime() / 1000 state = 'Зарезервовано водієм' icon_h_offset = 97 else if good.success != '-1' state = 'Доставлено' icon_h_offset = 2 * 97 show_delete_button = false else state = 'Очікує' icon_h_offset = 0 icon_v_offset = Math.round(Math.random() * 5) * 97 confirm = if good.given == '0' && good.success == '-1' then """<button class="cs-home-page-confirm-good uk-button" data-id="#{good.id}"><i class="uk-icon-check"></i> Водій забрав речі</button>""" else '' content += """<aside> <div class="icon" style="background-position: -#{icon_h_offset}px -#{icon_v_offset}px"></div> <h2>#{state}</h2> <span>#{good.phone}</span> <address>#{good.address}</address> <time>#{good.date} (#{good.time})</time> <p>#{good.comment}</p> <p> #{confirm} """ + (if show_delete_button then """ <button class="cs-home-page-delete-good uk-button" data-id="#{good.id}"><i class="uk-icon-times"></i></button>""" else '') + """ </p> </aside>""" $('.cs-home-page-my-goods-list').html(content) else clusterer.removeAll() $('.cs-home-page-my-goods-list').html('<p class="cs-center">Речей не знайдено</p>') return ) find_goods() map_container .on( 'click' '.reservation' -> reservation = $(@) $.ajax( url : 'api/Home/reservation' type : 'post' data : id : reservation.data('id') success : -> reservation .html('Зарезервовано') .removeClass('reservation') .addClass('reserved') alert 'Зарезервовано! Дякуємо та чекаємо вашого приїзду!' find_goods() error : (xhr) -> if xhr.responseText alert(cs.json_decode(xhr.responseText).error_description) else alert(L.auth_connection_error) ) ) .on( 'click' '.reserved' -> reserved = $(@) $.ajax( url : 'api/Home/reservation' type : 'delete' data : id : reserved.data('id') success : -> reserved .html('Заберу за 24 години') .removeClass('reserved') .addClass('reservation') alert 'Резерв скасовано! Дякуємо що попередили!' find_goods() error : (xhr) -> if xhr.responseText alert(cs.json_decode(xhr.responseText).error_description) else alert(L.auth_connection_error) ) ) search_timeout = 0 filter.on( 'keyup change' '[name=date], [name=time], .cs-home-page-map-goods-switcher input' -> clearTimeout(search_timeout) search_timeout = setTimeout(find_goods, 300) ) $('.cs-home-page-map-goods-switcher').on( 'keyup change' 'input' -> clearTimeout(search_timeout) search_timeout = setTimeout(find_goods, 300) ) $(document).on( 'click' '.cs-home-page-delete-good' -> if !confirm('Точно видалити?') return $.ajax( url : 'api/Home/goods/' + $(this).data('id') type : 'delete' success : -> find_goods() ) )
[ { "context": "ity value by 1 (to a minimum of \"0\").\"\"\"\n \"Garven Dreis\":\n text: \"\"\"After spending a focus tok", "end": 6336, "score": 0.9969791173934937, "start": 6324, "tag": "NAME", "value": "Garven Dreis" }, { "context": " attacker could target you ins...
coffeescripts/cards-en.coffee
michigun/xwing
0
exportObj = exports ? this exportObj.codeToLanguage ?= {} exportObj.codeToLanguage.en = 'English' exportObj.translations ?= {} # This is here mostly as a template for other languages. exportObj.translations.English = action: "Barrel Roll": "Barrel Roll" "Boost": "Boost" "Evade": "Evade" "Focus": "Focus" "Target Lock": "Target Lock" "Recover": "Recover" "Reinforce": "Reinforce" "Jam": "Jam" "Coordinate": "Coordinate" "Cloak": "Cloak" "SLAM": "SLAM" slot: "Astromech": "Astromech" "Bomb": "Bomb" "Cannon": "Cannon" "Crew": "Crew" "Elite": "Elite" "Missile": "Missile" "System": "System" "Torpedo": "Torpedo" "Turret": "Turret" "Cargo": "Cargo" "Hardpoint": "Hardpoint" "Team": "Team" "Illicit": "Illicit" "Salvaged Astromech": "Salvaged Astromech" sources: # needed? "Core": "Core" "A-Wing Expansion Pack": "A-Wing Expansion Pack" "B-Wing Expansion Pack": "B-Wing Expansion Pack" "X-Wing Expansion Pack": "X-Wing Expansion Pack" "Y-Wing Expansion Pack": "Y-Wing Expansion Pack" "Millennium Falcon Expansion Pack": "Millennium Falcon Expansion Pack" "HWK-290 Expansion Pack": "HWK-290 Expansion Pack" "TIE Fighter Expansion Pack": "TIE Fighter Expansion Pack" "TIE Interceptor Expansion Pack": "TIE Interceptor Expansion Pack" "TIE Bomber Expansion Pack": "TIE Bomber Expansion Pack" "TIE Advanced Expansion Pack": "TIE Advanced Expansion Pack" "Lambda-Class Shuttle Expansion Pack": "Lambda-Class Shuttle Expansion Pack" "Slave I Expansion Pack": "Slave I Expansion Pack" "Imperial Aces Expansion Pack": "Imperial Aces Expansion Pack" "Rebel Transport Expansion Pack": "Rebel Transport Expansion Pack" "Z-95 Headhunter Expansion Pack": "Z-95 Headhunter Expansion Pack" "TIE Defender Expansion Pack": "TIE Defender Expansion Pack" "E-Wing Expansion Pack": "E-Wing Expansion Pack" "TIE Phantom Expansion Pack": "TIE Phantom Expansion Pack" "Tantive IV Expansion Pack": "Tantive IV Expansion Pack" "Rebel Aces Expansion Pack": "Rebel Aces Expansion Pack" "YT-2400 Freighter Expansion Pack": "YT-2400 Freighter Expansion Pack" "VT-49 Decimator Expansion Pack": "VT-49 Decimator Expansion Pack" "StarViper Expansion Pack": "StarViper Expansion Pack" "M3-A Interceptor Expansion Pack": "M3-A Interceptor Expansion Pack" "IG-2000 Expansion Pack": "IG-2000 Expansion Pack" "Most Wanted Expansion Pack": "Most Wanted Expansion Pack" "Imperial Raider Expansion Pack": "Imperial Raider Expansion Pack" "Hound's Tooth Expansion Pack": "Hound's Tooth Expansion Pack" "Kihraxz Fighter Expansion Pack": "Kihraxz Fighter Expansion Pack" "K-Wing Expansion Pack": "K-Wing Expansion Pack" "TIE Punisher Expansion Pack": "TIE Punisher Expansion Pack" ui: shipSelectorPlaceholder: "Select a ship" pilotSelectorPlaceholder: "Select a pilot" upgradePlaceholder: (translator, language, slot) -> "No #{translator language, 'slot', slot} Upgrade" modificationPlaceholder: "No Modification" titlePlaceholder: "No Title" upgradeHeader: (translator, language, slot) -> "#{translator language, 'slot', slot} Upgrade" unreleased: "unreleased" epic: "epic" limited: "limited" byCSSSelector: '.xwing-card-browser .translate.sort-cards-by': 'Sort cards by' '.xwing-card-browser option[value="name"]': 'Name' '.xwing-card-browser option[value="source"]': 'Source' '.xwing-card-browser option[value="type-by-points"]': 'Type (by Points)' '.xwing-card-browser option[value="type-by-name"]': 'Type (by Name)' '.xwing-card-browser .translate.select-a-card': 'Select a card from the list at the left.' # Info well '.info-well .info-ship td.info-header': 'Ship' '.info-well .info-skill td.info-header': 'Skill' '.info-well .info-actions td.info-header': 'Actions' '.info-well .info-upgrades td.info-header': 'Upgrades' '.info-well .info-range td.info-header': 'Range' # Squadron edit buttons '.clear-squad' : 'New Squad' '.save-list' : 'Save' '.save-list-as' : 'Save as…' '.delete-list' : 'Delete' '.backend-list-my-squads' : 'Load squad' '.view-as-text' : '<span class="hidden-phone"><i class="icon-print"></i>&nbsp;Print/View as </span>Text' '.randomize' : 'Random!' '.randomize-options' : 'Randomizer options…' # Print/View modal '.bbcode-list' : 'Copy the BBCode below and paste it into your forum post.<textarea></textarea>' '.vertical-space-checkbox' : """Add space for damage/upgrade cards when printing <input type="checkbox" class="toggle-vertical-space" />""" '.color-print-checkbox' : """Print color <input type="checkbox" class="toggle-color-print" />""" '.print-list' : '<i class="icon-print"></i>&nbsp;Print' # Randomizer options '.do-randomize' : 'Randomize!' # Top tab bar '#empireTab' : 'Galactic Empire' '#rebelTab' : 'Rebel Alliance' '#scumTab' : 'Scum and Villainy' '#browserTab' : 'Card Browser' '#aboutTab' : 'About' singular: 'pilots': 'Pilot' 'modifications': 'Modification' 'titles': 'Title' types: 'Pilot': 'Pilot' 'Modification': 'Modification' 'Title': 'Title' exportObj.cardLoaders ?= {} exportObj.cardLoaders.English = () -> exportObj.cardLanguage = 'English' # Assumes cards-common has been loaded basic_cards = exportObj.basicCardData() exportObj.canonicalizeShipNames basic_cards # English names are loaded by default, so no update is needed exportObj.ships = basic_cards.ships # Names don't need updating, but text needs to be set pilot_translations = "Wedge Antilles": text: """When attacking, reduce the defender's agility value by 1 (to a minimum of "0").""" "Garven Dreis": text: """After spending a focus token, you may place that token on any other friendly ship at Range 1-2 (instead of discarding it).""" "Biggs Darklighter": text: """Other friendly ships at Range 1 cannot be targeted by attacks if the attacker could target you instead.""" "Luke Skywalker": text: """When defending, you may change 1 of your %FOCUS% results to a %EVADE% result.""" '"Dutch" Vander': text: """After acquiring a target lock, choose another friendly ship at Range 1-2. The chosen ship may immediately acquire a target lock.""" "Horton Salm": text: """When attacking at Range 2-3, you may reroll any of your blank results.""" '"Winged Gundark"': text: """When attacking at Range 1, you may change 1 of your %HIT% results to a %CRIT% result.""" '"Night Beast"': text: """After executing a green maneuver, you may perform a free focus action.""" '"Backstabber"': text: """When attacking from outside the defender's firing arc, roll 1 additional attack die.""" '"Dark Curse"': text: """When defending, ships attacking you cannot spend focus tokens or reroll attack dice.""" '"Mauler Mithel"': text: """When attacking at Range 1, roll 1 additional attack die.""" '"Howlrunner"': text: """When another friendly ship at Range 1 is attacking with its primary weapon, it may reroll 1 attack die.""" "Maarek Stele": text: """When your attack deals a faceup Damage card to the defender, instead draw 3 Damage cards, choose 1 to deal, and discard the others.""" "Darth Vader": text: """During your "Perform Action" step, you may perform 2 actions.""" "\"Fel's Wrath\"": text: """When the number of Damage cards assigned to you equals or exceeds your hull value, you are not destroyed until the end of the Combat phase.""" "Turr Phennir": text: """After you perform an attack, you may perform a free boost or barrel roll action.""" "Soontir Fel": text: """When you receive a stress token, you may assign 1 focus token to your ship.""" "Tycho Celchu": text: """You may perform actions even while you have stress tokens.""" "Arvel Crynyd": text: """You may declare an enemy ship inside your firing arc that you are touching as the target of your attack.""" "Chewbacca": text: """When you are dealt a faceup Damage card, immediately flip it facedown (without resolving its ability).""" "Lando Calrissian": text: """After you execute a green maneuver, choose 1 other friendly ship at Range 1. That ship may perform 1 free action shown on its action bar.""" "Han Solo": text: """When attacking, you may reroll all of your dice. If you choose to do so, you must reroll as many of your dice as possible.""" "Kath Scarlet": text: """When attacking, the defender receives 1 stress token if he cancels at least 1 %CRIT% result.""" "Boba Fett": text: """When you reveal a bank maneuver (%BANKLEFT% or %BANKRIGHT%), you may rotate your dial to the other bank maneuver of the same speed.""" "Krassis Trelix": text: """When attacking with a secondary weapon, you may reroll 1 attack die.""" "Ten Numb": text: """When attacking, 1 of your %CRIT% results cannot be canceled by defense dice.""" "Ibtisam": text: """When attacking or defending, if you have at least 1 stress token, you may reroll 1 of your dice.""" "Roark Garnet": text: '''At the start of the Combat phase, choose 1 other friendly ship at Range 1-3. Until the end of the phase, treat that ship's pilot skill value as "12."''' "Kyle Katarn": text: """At the start of the Combat phase, you may assign 1 of your focus tokens to another friendly ship at Range 1-3.""" "Jan Ors": text: """When another friendly ship at Range 1-3 is attacking, if you have no stress tokens, you may receive 1 stress token to allow that ship to roll 1 additional attack die.""" "Captain Jonus": text: """When another friendly ship at Range 1 attacks with a secondary weapon, it may reroll up to 2 attack dice.""" "Major Rhymer": text: """When attacking with a secondary weapon, you may increase or decrease the weapon range by 1 to a limit of Range 1-3.""" "Captain Kagi": text: """When an enemy ship acquires a target lock, it must lock onto your ship if able.""" "Colonel Jendon": text: """At the start of the Combat phase, you may assign 1 of your blue target lock tokens to a friendly ship at Range 1 if it does not have a blue target lock token.""" "Captain Yorr": text: """When another friendly ship at Range 1-2 would receive a stress token, if you have 2 or fewer stress tokens, you may receive that token instead.""" "Lieutenant Lorrir": text: """When performing a barrel roll action, you may receive 1 stress token to use the (%BANKLEFT% 1) or (%BANKRIGHT% 1) template instead of the (%STRAIGHT% 1) template.""" "Tetran Cowall": text: """When you reveal a %UTURN% maneuver, you may treat the speed of that maneuver as "1," "3," or "5".""" "Kir Kanos": text: """When attacking at Range 2-3, you may spend 1 evade token to add 1 %HIT% result to your roll.""" "Carnor Jax": text: """Enemy ships at Range 1 cannot perform focus or evade actions and cannot spend focus or evade tokens.""" "Lieutenant Blount": text: """When attacking, the defender is hit by your attack, even if he does not suffer any damage.""" "Airen Cracken": text: """After you perform an attack, you may choose another friendly ship at Range 1. That ship may perform 1 free action.""" "Colonel Vessery": text: """When attacking, immediately after you roll attack dice, you may acquire a target lock on the defender if it already has a red target lock token.""" "Rexler Brath": text: """After you perform an attack that deals at least 1 Damage card to the defender, you may spend a focus token to flip those cards faceup.""" "Etahn A'baht": text: """When an enemy ship inside your firing arc at Range 1-3 is defending, the attacker may change 1 of its %HIT% results to a %CRIT% result.""" "Corran Horn": text: """At the start of the End phase, you may perform one attack. You cannot attack during the next round.""" '"Echo"': text: """When you decloak, you must use the (%BANKLEFT% 2) or (%BANKRIGHT% 2) template instead of the (%STRAIGHT% 2) template.""" '"Whisper"': text: """After you perform an attack that hits, you may assign 1 focus to your ship.""" "Wes Janson": text: """After you perform an attack, you may remove 1 focus, evade, or blue target lock token from the defender.""" "Jek Porkins": text: """When you receive a stress token, you may remove it and roll 1 attack die. On a %HIT% result, deal 1 facedown Damage card to this ship.""" '"Hobbie" Klivian': text: """When you acquire or spend a target lock, you may remove 1 stress token from your ship.""" "Tarn Mison": text: """When an enemy ship declares you as the target of an attack, you may acquire a target lock on that ship.""" "Jake Farrell": text: """After you perform a focus action or are assigned a focus token, you may perform a free boost or barrel roll action.""" "Gemmer Sojan": text: """While you are at Range 1 of at least 1 enemy ship, increase your agility value by 1.""" "Keyan Farlander": text: """When attacking, you may remove 1 stress token to change all of your %FOCUS% results to %HIT%results.""" "Nera Dantels": text: """You can perform %TORPEDO% secondary weapon attacks against enemy ships outside your firing arc.""" "CR90 Corvette (Fore)": text: """When attacking with your primary weapon, you may spend 1 energy to roll 1 additional attack die.""" # "CR90 Corvette (Crippled Aft)": # text: """You cannot choose or execute (%STRAIGHT% 4), (%BANKLEFT% 2), or (%BANKRIGHT% 2) maneuvers.""" "Dash Rendar": text: """You may ignore obstacles during the Activation phase and when performing actions.""" '"Leebo"': text: """When you are dealt a faceup Damage card, draw 1 additional Damage card, choose 1 to resolve, and discard the other.""" "Eaden Vrill": text: """When performing a primary weapon attack against a stressed ship, roll 1 additional attack die.""" "Rear Admiral Chiraneau": text: """When attacking at Range 1-2, you may change 1 of your %FOCUS% results to a %CRIT% result.""" "Commander Kenkirk": text: """If you have no shields and at least 1 Damage card assigned to you, increase your agility value by 1.""" "Captain Oicunn": text: """After executing a maneuver, each enemy ship you are touching suffers 1 damage.""" "Prince Xizor": text: """When defending, a friendly ship at Range 1 may suffer 1 uncanceled %HIT% or %CRIT% result instead of you.""" "Guri": text: """At the start of the Combat phase, if you are at Range 1 of an enemy ship, you may assign 1 focus token to your ship.""" "Serissu": text: """When another friendly ship at Range 1 is defending, it may reroll 1 defense die.""" "Laetin A'shera": text: """After you defend against an attack, if the attack did not hit, you may assign 1 evade token to your ship.""" "IG-88A": text: """After you perform an attack that destroys the defender, you may recover 1 shield.""" "IG-88B": text: """Once per round, after you perform an attack that does not hit, you may perform an attack with an equipped %CANNON% secondary weapon.""" "IG-88C": text: """After you perform a boost action, you may perform a free evade action.""" "IG-88D": text: """You may execute the (%SLOOPLEFT% 3) or (%SLOOPRIGHT% 3) maneuver using the corresponding (%TURNLEFT% 3) or (%TURNRIGHT% 3) template.""" "Boba Fett (Scum)": text: """When attacking or defending, you may reroll 1 of your dice for each enemy ship at Range 1.""" "Kath Scarlet (Scum)": text: """When attacking a ship inside your auxiliary firing arc, roll 1 additional attack die.""" "Emon Azzameen": text: """When dropping a bomb, you may use the [%TURNLEFT% 3], [%STRAIGHT% 3], or [%TURNRIGHT% 3] template instead of the [%STRAIGHT% 1] template.""" "Kavil": text: """When attacking a ship outside your firing arc, roll 1 additional attack die.""" "Drea Renthal": text: """After you spend a target lock, you may receive 1 stress token to acquire a target lock.""" "Dace Bonearm": text: """When an enemy ship at Range 1-3 receives at least 1 ion token, if you are not stressed, you may receive 1 stress token to cause that ship to suffer 1 damage.""" "Palob Godalhi": text: """At the start of the Combat phase, you may remove 1 focus or evade token from an enemy ship at Range 1-2 and assign it to yourself.""" "Torkil Mux": text: """At the end of the Activation phase, choose 1 enemy ship at Range 1-2. Until the end of the Combat phase, treat that ship's pilot skill value as "0".""" "N'Dru Suhlak": text: """When attacking, if there are no other friendly ships at Range 1-2, roll 1 additional attack die.""" "Kaa'To Leeachos": text: """At the start of the Combat phase, you may remove 1 focus or evade token from another friendly ship at Range 1-2 and assign it to yourself.""" "Commander Alozen": text: """At the start of the Combat phase, you may acquire a target lock on an enemy ship at Range 1.""" "Raider-class Corvette (Fore)": text: """Once per round, after you perform a primary weapon attack, you may spend 2 energy to perform another primary weapon attack.""" "Bossk": text: """When you perform an attack that hits, before dealing damage, you may cancel 1 of your %CRIT% results to add 2 %HIT% results.""" "Talonbane Cobra": text: """When attacking or defending, double the effect of your range combat bonuses.""" "Miranda Doni": text: """Once per round when attacking, you may either spend 1 shield to roll 1 additional attack die <strong>or</strong> roll 1 fewer attack die to recover 1 shield.""" '"Redline"': text: """You may maintain 2 target locks on the same ship. When you acquire a target lock, you may acquire a second lock on that ship.""" '"Deathrain"': text: """When dropping a bomb, you may use the front guides of your ship. After dropping a bomb, you may perform a free barrel roll action.""" "Juno Eclipse": text: """When you reveal your maneuver, you may increase or decrease its speed by 1 (to a minimum of 1).""" "Zertik Strom": text: """Enemy ships at Range 1 cannot add their range combat bonus when attacking.""" "Lieutenant Colzet": text: """At the start of the End phase, you may spend a target lock you have on an enemy ship to flip 1 random facedown Damage card assigned to it faceup.""" "Latts Razzi": text: """When a friendly ship declares an attack, you may spend a target lock you have on the defender to reduce its agility by 1 for that attack.""" "Graz the Hunter": text: """When defending, if the attacker is inside your firing arc, roll 1 additional defense die.""" "Esege Tuketu": text: """When another friendly ship at Range 1-2 is attacking, it may treat your focus tokens as its own.""" "Moralo Eval": text: """You can perform %CANNON% secondary attacks against ships inside your auxiliary firing arc.""" 'Gozanti-class Cruiser': text: """After you execute a maneuver, you may deploy up to 2 attached ships.""" '"Scourge"': text: """When attacking a defender that has 1 or more Damage cards, roll 1 additional attack die.""" "The Inquisitor": text: """When attacking with your primary weapon at Range 2-3, treat the range of the attack as Range 1.""" "Zuckuss": text: """When attacking, you may roll 1 additional attack die. If you do, the defender rolls 1 additional defense die.""" "Dengar": text: """Once per round after defending, if the attacker is inside your firing arc, you may perform an attack against the that ship.""" upgrade_translations = "Ion Cannon Turret": text: """<strong>Attack:</strong> Attack 1 ship (even a ship outside your firing arc).%LINEBREAK%If this attack hits the target ship, the ship suffers 1 damage and receives 1 ion token. Then cancel all dice results.""" "Proton Torpedoes": text: """<strong>Attack (target lock):</strong> Spend your target lock and discard this card to perform this attack.%LINEBREAK%You may change 1 of your %FOCUS% results to a %CRIT% result.""" "R2 Astromech": text: """You may treat all 1- and 2-speed maneuvers as green maneuvers.""" "R2-D2": text: """After executing a green maneuver, you may recover 1 shield (up to your shield value).""" "R2-F2": text: """<strong>Action:</strong> Increase your agility value by 1 until the end of this game round.""" "R5-D8": text: """<strong>Action:</strong> Roll 1 defense die.%LINEBREAK%On a %EVADE% or %FOCUS% result, discard 1 of your facedown Damage cards.""" "R5-K6": text: """After spending your target lock, roll 1 defense die.%LINEBREAK%On a %EVADE% result, immediately acquire a target lock on that same ship. You cannot spend this target lock during this attack.""" "R5 Astromech": text: """During the End phase, you may choose 1 of your faceup Damage cards with the Ship trait and flip it facedown.""" "Determination": text: """When you are dealt a faceup Damage card with the Pilot trait, discard it immediately without resolving its effect.""" "Swarm Tactics": text: """At the start of the Combat phase, you may choose 1 friendly ship at Range 1.%LINEBREAK%Until the end of this phase, treat the chosen ship as if its pilot skill were equal to your pilot skill.""" "Squad Leader": text: """<strong>Action:</strong> Choose 1 ship at Range 1-2 that has a lower pilot skill than you.%LINEBREAK%The chosen ship may immediately perform 1 free action.""" "Expert Handling": text: """<strong>Action:</strong> Perform a free barrel roll action. If you do not have the %BARRELROLL% action icon, receive 1 stress token.%LINEBREAK%You may then remove 1 enemy target lock from your ship.""" "Marksmanship": text: """<strong>Action:</strong> When attacking this round, you may change 1 of your %FOCUS% results to a %CRIT% result and all of your other %FOCUS% results to %HIT% results.""" "Concussion Missiles": text: """<strong>Attack (target lock):</strong> Spend your target lock and discard this card to perform this attack.%LINEBREAK%You may change 1 of your blank results to a %HIT% result.""" "Cluster Missiles": text: """<strong>Attack (target lock):</strong> Spend your target lock and discard this card to perform this attack twice.""" "Daredevil": text: """<strong>Action:</strong> Execute a white (%TURNLEFT% 1) or (%TURNRIGHT% 1) maneuver. Then, receive 1 stress token.%LINEBREAK%Then, if you do not have the %BOOST% action icon, roll 2 attack dice. Suffer any damage (%HIT%) and any critical damage (%CRIT%) rolled.""" "Elusiveness": text: """When defending, you may receive 1 stress token to choose 1 attack die. The attacker must reroll that die.%LINEBREAK%If you have at least 1 stress token, you cannot use this ability.""" "Homing Missiles": text: """<strong>Attack (target lock):</strong> Discard this card to perform this attack.%LINEBREAK%The defender cannot spend evade tokens during this attack.""" "Push the Limit": text: """Once per round, after you perform an action, you may perform 1 free action shown in your action bar.%LINEBREAK%Then receive 1 stress token.""" "Deadeye": text: """You may treat the <strong>Attack (target lock):</strong> header as <strong>Attack (focus):</strong>.%LINEBREAK%When an attack instructs you to spend a target lock, you may spend a focus token instead.""" "Expose": text: """<strong>Action:</strong> Until the end of the round, increase your primary weapon value by 1 and decrease your agility value by 1.""" "Gunner": text: """After you perform an attack that does not hit, you may immediately perform a primary weapon attack. You cannot perform another attack this round.""" "Ion Cannon": text: """<strong>Attack:</strong> Attack 1 ship.%LINEBREAK%If this attack hits, the defender suffers 1 damage and receives 1 ion token. Then cancel all dice results.""" "Heavy Laser Cannon": text: """<strong>Attack:</strong> Attack 1 ship.%LINEBREAK%Immediately after rolling your attack dice, you must change all of your %CRIT% results to %HIT% results.""" "Seismic Charges": text: """When you reveal your maneuver dial, you may discard this card to drop 1 seismic charge token.%LINEBREAK%This token detonates at the end of the Activation phase.%LINEBREAK%<strong>Seismic Charge Token:</strong> When this bomb token detonates, each ship at Range 1 of the token suffers 1 damage. Then discard this token.""" "Mercenary Copilot": text: """When attacking at Range 3, you may change 1 of your %HIT% results to a %CRIT% result.""" "Assault Missiles": text: """<strong>Attack (target lock):</strong> Spend your target lock and discard this card to perform this attack.%LINEBREAK%If this attack hits, each other ship at Range 1 of the defender suffers 1 damage.""" "Veteran Instincts": text: """Increase your pilot skill value by 2.""" "Proximity Mines": text: """<strong>Action:</strong> Discard this card to <strong>drop</strong> 1 proximity mine token.%LINEBREAK%When a ship's base or maneuver template overlaps this token, this token <strong>detonates</strong>.%LINEBREAK%<strong>Proximity Mine Token:</strong> When this bomb token detonates, the ship that moved through or overlapped this token rolls 3 attack dice and suffers all damage (%HIT%) and critical damage (%CRIT%) rolled. Then discard this token.""" "Weapons Engineer": text: """You may maintain 2 target locks (only 1 per enemy ship).%LINEBREAK%When you acquire a target lock, you may lock onto 2 different ships.""" "Draw Their Fire": text: """When a friendly ship at Range 1 is hit by an attack, you may suffer 1 of the uncanceled %CRIT% results instead of the target ship.""" "Luke Skywalker": text: """%REBELONLY%%LINEBREAK%After you perform an attack that does not hit, you may immediately perform a primary weapon attack. You may change 1 %FOCUS% result to a %HIT% result. You cannot perform another attack this round.""" "Nien Nunb": text: """%REBELONLY%%LINEBREAK%You may treat all %STRAIGHT% maneuvers as green maneuvers.""" "Chewbacca": text: """%REBELONLY%%LINEBREAK%When you are dealt a Damage card, you may immediately discard that card and recover 1 shield.%LINEBREAK%Then, discard this Upgrade card.""" "Advanced Proton Torpedoes": text: """<strong>Attack (target lock):</strong> Spend your target lock and discard this card to perform this attack.%LINEBREAK%You may change up to 3 of your blank results to %FOCUS% results.""" "Autoblaster": text: """<strong>Attack:</strong> Attack 1 ship.%LINEBREAK%Your %HIT% results cannot be canceled by defense dice.%LINEBREAK%The defender may cancel %CRIT% results before %HIT% results.""" "Fire-Control System": text: """After you perform an attack, you may acquire a target lock on the defender.""" "Blaster Turret": text: """<strong>Attack (focus):</strong> Spend 1 focus token to perform this attack against 1 ship (even a ship outside your firing arc).""" "Recon Specialist": text: """When you perform a focus action, assign 1 additional focus token to your ship.""" "Saboteur": text: """<strong>Action:</strong> Choose 1 enemy ship at Range 1 and roll 1 attack die. On a %HIT% or %CRIT% result, choose 1 random facedown Damage card assigned to that ship, flip it faceup, and resolve it.""" "Intelligence Agent": text: """At the start of the Activation phase, choose 1 enemy ship at Range 1-2. You may look at that ship's chosen maneuver.""" "Proton Bombs": text: """When you reveal your maneuver dial, you may discard this card to <strong>drop</strong> 1 proton bomb token.%LINEBREAK%This token <strong>detonates</strong> at the end of the Activation phase.%LINEBREAK%<strong>Proton Bomb Token:</strong> When this bomb token detonates, deal 1 <strong>faceup</strong> Damage card to each ship at Range 1 of the token. Then discard this token.""" "Adrenaline Rush": text: """When you reveal a red maneuver, you may discard this card to treat that maneuver as a white maneuver until the end of the Activation phase.""" "Advanced Sensors": text: """Immediately before you reveal your maneuver, you may perform 1 free action.%LINEBREAK%If you use this ability, you must skip your "Perform Action" step during this round.""" "Sensor Jammer": text: """When defending, you may change 1 of the attacker's %HIT% results into a %FOCUS% result.%LINEBREAK%The attacker cannot reroll the die with the changed result.""" "Darth Vader": text: """%IMPERIALONLY%%LINEBREAK%After you perform an attack against an enemy ship, you may suffer 2 damage to cause that ship to suffer 1 critical damage.""" "Rebel Captive": text: """%IMPERIALONLY%%LINEBREAK%Once per round, the first ship that declares you as the target of an attack immediately receives 1 stress token.""" "Flight Instructor": text: """When defending, you may reroll 1 of your %FOCUS% results. If the attacker's pilot skill value is "2" or lower, you may reroll 1 of your blank results instead.""" "Navigator": text: """When you reveal a maneuver, you may rotate your dial to another maneuver with the same bearing.%LINEBREAK%You cannot rotate to a red maneuver if you have any stress tokens.""" "Opportunist": text: """When attacking, if the defender does not have any focus or evade tokens, you may receive 1 stress token to roll 1 additional attack die.%LINEBREAK%You cannot use this ability if you have any stress tokens.""" "Comms Booster": text: """<strong>Energy:</strong> Spend 1 energy to remove all stress tokens from a friendly ship at Range 1-3. Then assign 1 focus token to that ship.""" "Slicer Tools": text: """<strong>Action:</strong> Choose 1 or more ships at Range 1-3 that have a stress token. For each ship chosen, you may spend 1 energy to cause that ship to suffer 1 damage.""" "Shield Projector": text: """When an enemy ship is declaring either a small or large ship as the target of its attack, you may spend 3 energy to force that ship to target you if possible.""" "Ion Pulse Missiles": text: """<strong>Attack (target lock):</strong> Discard this card to perform this attack.%LINEBREAK%If this attack hits, the defender suffers 1 damage and receives 2 ion tokens. Then cancel <strong>all</strong> dice results.""" "Wingman": text: """At the start of the Combat phase, remove 1 stress token from another friendly ship at Range 1.""" "Decoy": text: """At the start of the Combat phase, you may choose 1 friendly ship at Range 1-2. Exchange your pilot skill with that ship's pilot skill until the end of the phase.""" "Outmaneuver": text: """When attacking a ship inside your firing arc, if you are not inside that ship's firing arc, reduce its agility value by 1 (to a minimum of 0).""" "Predator": text: """When attacking, you may reroll 1 attack die. If the defender's pilot skill value is "2" or lower, you may instead reroll up to 2 attack dice.""" "Flechette Torpedoes": text: """<strong>Attack (target lock):</strong> Discard this card and spend your target lock to perform this attack.%LINEBREAK%After you perform this attack, the defender receives 1 stress token if its hull value is "4" or lower.""" "R7 Astromech": text: """Once per round when defending, if you have a target lock on the attacker, you may spend the target lock to choose any or all attack dice. The attacker must reroll the chosen dice.""" "R7-T1": text: """<strong>Action:</strong> Choose an enemy ship at Range 1-2. If you are inside that ship's firing arc, you may acquire a target lock on that ship. Then, you may perform a free boost action.""" "Tactician": text: """After you perform an attack against a ship inside your firing arc at Range 2, that ship receives 1 stress token.""" "R2-D2 (Crew)": text: """%REBELONLY%%LINEBREAK%At the end of the End phase, if you have no shields, you may recover 1 shield and roll 1 attack die. On a %HIT% result, randomly flip 1 of your facedown Damage cards faceup and resolve it.""" "C-3PO": text: """%REBELONLY%%LINEBREAK%Once per round, before you roll 1 or more defense dice, you may guess aloud a number of %EVADE% results. If you roll that many %EVADE% results (before modifying dice), add 1 %EVADE% result.""" "Single Turbolasers": text: """<strong>Attack (Energy):</strong> Spend 2 energy from this card to perform this attack. The defender doubles his agility value against this attack. You may change 1 of your %FOCUS% results to a %HIT% result.""" "Quad Laser Cannons": text: """<strong>Attack (Energy):</strong> Spend 1 energy from this card to perform this attack. If this attack does not hit, you may immediately spend 1 energy from this card to perform this attack again.""" "Tibanna Gas Supplies": text: """<strong>Energy:</strong> You may discard this card to gain 3 energy.""" "Ionization Reactor": text: """<strong>Energy:</strong> Spend 5 energy from this card and discard this card to cause each other ship at Range 1 to suffer 1 damage and receive 1 ion token.""" "Engine Booster": text: """Immediately before you reveal your maneuver dial, you may spend 1 energy to execute a white (%STRAIGHT% 1) maneuver. You cannot use this ability if you would overlap another ship.""" "R3-A2": text: """When you declare the target of your attack, if the defender is inside your firing arc, you may receive 1 stress token to cause the defender to receive 1 stress token.""" "R2-D6": text: """Your upgrade bar gains the %ELITE% upgrade icon.%LINEBREAK%You cannot equip this upgrade if you already have a %ELITE% upgrade icon or if your pilot skill value is "2" or lower.""" "Enhanced Scopes": text: """During the Activation phase, treat your pilot skill value as "0".""" "Chardaan Refit": text: """<span class="card-restriction">A-Wing only.</span>%LINEBREAK%This card has a negative squad point cost.""" "Proton Rockets": text: """<strong>Attack (Focus):</strong> Discard this card to perform this attack.%LINEBREAK%You may roll additional attack dice equal to your agility value, to a maximum of 3 additional dice.""" "Kyle Katarn": text: """%REBELONLY%%LINEBREAK%After you remove a stress token from your ship, you may assign a focus token to your ship.""" "Jan Ors": text: """%REBELONLY%%LINEBREAK%Once per round, when a friendly ship at Range 1-3 performs a focus action or would be assigned a focus token, you may assign it an evade token instead.""" "Toryn Farr": text: """%HUGESHIPONLY% %REBELONLY%%LINEBREAK%<strong>Action:</strong> Spend any amount of energy to choose that many enemy ships at Range 1-2. Remove all focus, evade, and blue target lock tokens from those ships.""" "R4-D6": text: """When you are hit by an attack and there are at least 3 uncanceled %HIT% results, you may choose to cancel those results until there are 2 remaining. For each result canceled this way, receive 1 stress token.""" "R5-P9": text: """At the end of the Combat phase, you may spend 1 of your focus tokens to recover 1 shield (up to your shield value).""" "WED-15 Repair Droid": text: """%HUGESHIPONLY%%LINEBREAK%<strong>Action:</strong> Spend 1 energy to discard 1 of your facedown Damage cards, or spend 3 energy to discard 1 of your faceup Damage cards.""" "Carlist Rieekan": text: """%HUGESHIPONLY% %REBELONLY%%LINEBREAK%At the start of the Activation phase, you may discard this card to treat each friendly ship's pilot skill value as "12" until the end of the phase.""" "Jan Dodonna": text: """%HUGESHIPONLY% %REBELONLY%%LINEBREAK%When another friendly ship at Range 1 is attacking, it may change 1 of its %HIT% results to a %CRIT%.""" "Expanded Cargo Hold": text: """<span class="card-restriction">GR-75 only.</span>%LINEBREAK%Once per round, when you would be dealt a faceup Damage card, you may draw that card from either the fore or aft Damage deck.""" "Backup Shield Generator": text: """At the end of each round, you may spend 1 energy to recover 1 shield (up to your shield value).""" "EM Emitter": text: """When you obstruct an attack, the defender rolls 3 additional defense dice (instead of 1).""" "Frequency Jammer": text: """When you perform a jam action, choose 1 enemy ship that does not have a stress token and is at Range 1 of the jammed ship. The chosen ship receives 1 stress token.""" "Han Solo": text: """%REBELONLY%%LINEBREAK%When attacking, if you have a target lock on the defender, you may spend that target lock to change all of your %FOCUS% results to %HIT% results.""" "Leia Organa": text: """%REBELONLY%%LINEBREAK%At the start of the Activation phase, you may discard this card to allow all friendly ships that reveal a red maneuver to treat that maneuver as a white maneuver until the end of the phase.""" "Targeting Coordinator": text: """<strong>Energy:</strong> You may spend 1 energy to choose 1 friendly ship at Range 1-2. Acquire a target lock, then assign the blue target lock token to the chosen ship.""" "Raymus Antilles": text: """%HUGESHIPONLY% %REBELONLY%%LINEBREAK%At the start of the Activation phase, choose 1 enemy ship at Range 1-3. You may look at that ship's chosen maneuver. If the maneuver is white, assign that ship 1 stress token.""" "Gunnery Team": text: """Once per round, when attacking with a secondary weapon, you may spend 1 energy to change 1 of your blank results to a %HIT% result.""" "Sensor Team": text: """When acquiring a target lock, you may lock onto an enemy ship at Range 1-5 instead of 1-3.""" "Engineering Team": text: """During the Activation phase, when you reveal a %STRAIGHT% maneuver, gain 1 additional energy during the "Gain Energy" step.""" "Lando Calrissian": text: """%REBELONLY%%LINEBREAK%<strong>Action:</strong> Roll 2 defense dice. For each %FOCUS% result, assign 1 focus token to your ship. For each %EVADE% result, assign 1 evade token to your ship.""" "Mara Jade": text: """%IMPERIALONLY%%LINEBREAK%At the end of the Combat phase, each enemy ship at Range 1 that does not have a stress token receives 1 stress token.""" "Fleet Officer": text: """%IMPERIALONLY%%LINEBREAK%<strong>Action:</strong> Choose up to 2 friendly ships at Range 1-2 and assign 1 focus token to each of those ships. Then receive 1 stress token.""" "Lone Wolf": text: """When attacking or defending, if there are no other friendly ships at Range 1-2, you may reroll 1 of your blank results.""" "Stay On Target": text: """When you reveal a maneuver, you may rotate your dial to another maneuver with the same speed.%LINEBREAK%Treat that maneuver as a red maneuver.""" "Dash Rendar": text: """%REBELONLY%%LINEBREAK%You may perform attacks while overlapping an obstacle.%LINEBREAK%Your attacks cannot be obstructed.""" '"Leebo"': text: """%REBELONLY%%LINEBREAK%<strong>Action:</strong> Perform a free boost action. Then receive 1 ion token.""" "Ruthlessness": text: """%IMPERIALONLY%%LINEBREAK%After you perform an attack that hits, you <strong>must</strong> choose 1 other ship at Range 1 of the defender (other than yourself). That ship suffers 1 damage.""" "Intimidation": text: """While you are touching an enemy ship, reduce that ship's agility value by 1.""" "Ysanne Isard": text: """%IMPERIALONLY%%LINEBREAK%At the start of the Combat phase, if you have no shields and at least 1 Damage card assigned to your ship, you may perform a free evade action.""" "Moff Jerjerrod": text: """%IMPERIALONLY%%LINEBREAK%When you are dealt a faceup Damage card, you may discard this Upgrade card or another %CREW% Upgrade card to flip that Damage card facedown (without resolving its effect).""" "Ion Torpedoes": text: """<strong>Attack (target lock):</strong> Spend your target lock and discard this card to perform this attack.%LINEBREAK%If this attack hits, the defender and each ship at Range 1 of it receives 1 ion token.""" "Bodyguard": text: """%SCUMONLY%%LINEBREAK%At the start of the Combat phase, you may spend a focus token to choose a friendly ship at Range 1 with higher pilot skill than you. Increase its agility value by 1 until the end of the round.""" "Calculation": text: """When attacking, you may spend a focus token to change 1 of your %FOCUS% results to a %CRIT% result.""" "Accuracy Corrector": text: """When attacking, during the "Modify Attack Dice" step, you may cancel all of your dice results. Then, you may add 2 %HIT% results to your roll.%LINEBREAK%Your dice cannot be modified again during this attack.""" "Inertial Dampeners": text: """When you reveal your maneuver, you may discard this card to instead perform a white [0%STOP%] maneuver. Then receive 1 stress token.""" "Flechette Cannon": text: """<strong>Attack:</strong> Attack 1 ship.%LINEBREAK%If this attack hits, the defender suffers 1 damage and, if the defender is not stressed, it also receives 1 stress token. Then cancel <strong>all</strong> dice results.""" '"Mangler" Cannon': text: """<strong>Attack:</strong> Attack 1 ship.%LINEBREAK%When attacking, you may change 1 of your %HIT% results to a %CRIT% result.""" "Dead Man's Switch": text: """When you are destroyed, each ship at Range 1 suffers 1 damage.""" "Feedback Array": text: """During the Combat phase, instead of performing any attacks, you may receive 1 ion token and suffer 1 damage to choose 1 enemy ship at Range 1. That ship suffers 1 damage.""" '"Hot Shot" Blaster': text: """<strong>Attack:</strong> Discard this card to attack 1 ship (even a ship outside your firing arc).""" "Greedo": text: """%SCUMONLY%%LINEBREAK%The first time you attack each round and the first time you defend each round, the first Damage card dealt is dealt faceup.""" "Salvaged Astromech": text: """When you are dealt a Damage card with the <strong>Ship</strong> trait, you may immediately discard that card (before resolving its effect).%LINEBREAK%Then, discard this Upgrade card.""" "Bomb Loadout": text: """<span class="card-restriction">Y-Wing only.</span>%LINEBREAK%Your upgrade bar gains the %BOMB% icon.""" '"Genius"': text: """If you are equipped with a bomb that can be dropped when you reveal your maneuver, you may drop the bomb <strong>after</strong> you execute your maneuver instead.""" "Unhinged Astromech": text: """You may treat all 3-speed maneuvers as green maneuvers.""" "R4-B11": text: """When attacking, if you have a target lock on the defender, you may spend the target lock to choose any or all defense dice. The defender must reroll the chosen dice.""" "Autoblaster Turret": text: """<strong>Attack:</strong> Attack 1 ship (even a ship outside your firing arc).%LINEBREAK%Your %HIT% results cannot be canceled by defense dice. The defender may cancel %CRIT% results before %HIT% results.""" "R4 Agromech": text: """When attacking, after you spend a focus token, you may acquire a target lock on the defender.""" "K4 Security Droid": text: """%SCUMONLY%%LINEBREAK%After executing a green maneuver, you may acquire a target lock.""" "Outlaw Tech": text: """%SCUMONLY%%LINEBREAK%After you execute a red maneuver, you may assign 1 focus token to your ship.""" "Advanced Targeting Computer": text: """<span class="card-restriction">TIE Advanced only.</span>%LINEBREAK%When attacking with your primary weapon, if you have a target lock on the defender, you may add 1 %CRIT% result to your roll. If you do, you cannot spend target locks during this attack.""" "Ion Cannon Battery": text: """<strong>Attack (energy):</strong> Spend 2 energy from this card to perform this attack. If this attack hits, the defender suffers 1 critical damage and receives 1 ion token. Then cancel <strong>all</strong> dice results.""" "Extra Munitions": text: """When you equip this card, place 1 ordnance token on each equipped %TORPEDO%, %MISSILE%, and %BOMB% Upgrade card. When you are instructed to discard an Upgrade card, you may discard 1 ordnance token on that card instead.""" "Cluster Mines": text: """<strong>Action:</strong> Discard this card to <strong>drop</strong> 3 cluster mine tokens.<br /><br />When a ship's base or maneuver template overlaps a cluster mine token, that token <strong>detonates</strong>.<br /><br /><strong>Cluster Mines Tokens:</strong> When one of these bomb tokens detonates, the ship that moved through or overlapped this token rolls 2 attack dice and suffers all damage (%HIT%) rolled. Then discard this token.""" "Glitterstim": text: """At the start of the Combat phase, you may discard this card and receive 1 stress token. If you do, until the end of the round, when attacking or defending, you may change all of your %FOCUS% results to %HIT% or %EVADE% results.""" "Grand Moff Tarkin": text: """%HUGESHIPONLY% %IMPERIALONLY%%LINEBREAK%At the start of the Combat phase, you may choose another ship at Range 1-4. Either remove 1 focus token from the chosen ship or assign 1 focus token to that ship.""" "Captain Needa": text: """%HUGESHIPONLY% %IMPERIALONLY%%LINEBREAK%If you overlap an obstacle during the Activation phase, do not suffer 1 faceup damage card. Instead, roll 1 attack die. On a %HIT% or %CRIT% result, suffer 1 damage.""" "Admiral Ozzel": text: """%HUGESHIPONLY% %IMPERIALONLY%%LINEBREAK%<strong>Energy:</strong> You may remove up to 3 shields from your ship. For each shield removed, gain 1 energy.""" "Emperor Palpatine": text: """%IMPERIALONLY%%LINEBREAK%Once per round, you may change a friendly ship's die result to any other die result. That die result cannot be modified again.""" "Bossk": text: """%SCUMONLY%%LINEBREAK%After you perform an attack that does not hit, if you are not stressed, you <strong>must</strong> receive 1 stress token. Then assign 1 focus token to your ship and acquire a target lock on the defender.""" "Lightning Reflexes": text: """%SMALLSHIPONLY%%LINEBREAK%After you execute a white or green maneuver on your dial, you may discard this card to rotate your ship 180&deg;. Then receive 1 stress token <strong>after</strong> the "Check Pilot Stress" step.""" "Twin Laser Turret": text: """<strong>Attack:</strong> Perform this attack <strong>twice</strong> (even against a ship outside your firing arc).<br /><br />Each time this attack hits, the defender suffers 1 damage. Then cancel <strong>all</strong> dice results.""" "Plasma Torpedoes": text: """<strong>Attack (target lock):</strong> Spend your target lock and discard this card to perform this attack.<br /><br />If this attack hits, after dealing damage, remove 1 shield token from the defender.""" "Ion Bombs": text: """When you reveal your maneuver dial, you may discard this card to <strong>drop</strong> 1 ion bomb token.<br /><br />This token <strong>detonates</strong> at the end of the Activation phase.<br /><br /><strong>Ion Bombs Token:</strong> When this bomb token detonates, each ship at Range 1 of the token receives 2 ion tokens. Then discard this token.""" "Conner Net": text: """<strong>Action:</strong> Discard this card to <strong>drop</strong> 1 Conner Net token.<br /><br />When a ship's base or maneuver template overlaps this token, this token <strong>detonates</strong>.<br /><br /><strong>Conner Net Token:</strong> When this bomb token detonates, the ship that moved through or overlapped this token suffers 1 damage, receives 2 ion tokens, and skips its "Perform Action" step. Then discard this token.""" "Bombardier": text: """When dropping a bomb, you may use the (%STRAIGHT% 2) template instead of the (%STRAIGHT% 1) template.""" 'Crack Shot': text: '''When attacking a ship inside your firing arc, you may discard this card to cancel 1 of the defender's %EVADE% results.''' "Advanced Homing Missiles": text: """<strong>Attack (target lock):</strong> Discard this card to perform this attack.%LINEBREAK%If this attack hits, deal 1 faceup Damage card to the defender. Then cancel <strong>all</strong> dice results.""" 'Agent Kallus': text: '''%IMPERIALONLY%%LINEBREAK%At the start of the first round, choose 1 enemy small or large ship. When attacking or defending against that ship, you may change 1 of your %FOCUS% results to a %HIT% or %EVADE% result.''' 'XX-23 S-Thread Tracers': text: """<strong>Attack (focus):</strong> Discard this card to perform this attack. If this attack hits, each friendly ship at Range 1-2 of you may acquire a target lock on the defender. Then cancel <strong>all</strong> dice results.""" "Tractor Beam": text: """<strong>Attack:</strong> Attack 1 ship.%LINEBREAK%If this attack hits, the defender receives 1 tractor beam token. Then cancel <strong>all</strong> dice results.""" "Cloaking Device": text: """%SMALLSHIPONLY%%LINEBREAK%<strong>Action:</strong> Perform a free cloak action.%LINEBREAK%At the end of each round, if you are cloaked, roll 1 attack die. On a %FOCUS% result, discard this card, then decloak or discard your cloak token.""" modification_translations = "Stealth Device": text: """Increase your agility value by 1. If you are hit by an attack, discard this card.""" "Shield Upgrade": text: """Increase your shield value by 1.""" "Engine Upgrade": text: """Your action bar gains the %BOOST% action icon.""" "Anti-Pursuit Lasers": text: """%LARGESHIPONLY%%LINEBREAK%After an enemy ship executes a maneuver that causes it to overlap your ship, roll 1 attack die. On a %HIT% or %CRIT% result, the enemy ship suffers 1 damage.""" "Targeting Computer": text: """Your action bar gains the %TARGETLOCK% action icon.""" "Hull Upgrade": text: """Increase your hull value by 1.""" "Munitions Failsafe": text: """When attacking with a secondary weapon that instructs you to discard it to perform the attack, do not discard it unless the attack hits.""" "Stygium Particle Accelerator": text: """When you either decloak or perform a cloak action, you may perform a free evade action.""" "Advanced Cloaking Device": text: """<span class="card-restriction">TIE Phantom only.</span>%LINEBREAK%After you perform an attack, you may perform a free cloak action.""" "Combat Retrofit": text: """<span class="card-restriction">GR-75 only.</span>%LINEBREAK%Increase your hull value by 2 and your shield value by 1.""" "B-Wing/E2": text: """<span class="card-restriction">B-Wing only.</span>%LINEBREAK%Your upgrade bar gains the %CREW% upgrade icon.""" "Countermeasures": text: """%LARGESHIPONLY%%LINEBREAK%At the start of the Combat phase, you may discard this card to increase your agility value by 1 until the end of the round. Then you may remove 1 enemy target lock from your ship.""" "Experimental Interface": text: """Once per round, after you perform an action, you may perform 1 free action from an equipped Upgrade card with the "<strong>Action:</strong>" header. Then receive 1 stress token.""" "Tactical Jammer": text: """%LARGESHIPONLY%%LINEBREAK%Your ship can obstruct enemy attacks.""" "Autothrusters": text: """When defending, if you are beyond Range 2 or outside the attacker's firing arc, you may change 1 of your blank results to a %EVADE% result. You can equip this card only if you have the %BOOST% action icon.""" "Advanced SLAM": text: """After performing a SLAM action, if you did not overlap an obstacle or another ship, you may perform a free action.""" "Twin Ion Engine Mk. II": text: """You may treat all bank maneuvers (%BANKLEFT% and %BANKRIGHT%) as green maneuvers.""" "Maneuvering Fins": text: """When you reveal a turn maneuver (%TURNLEFT% or %TURNRIGHT%), you may rotate your dial to the corresponding bank maneuver (%BANKLEFT% or %BANKRIGHT%) of the same speed.""" "Ion Projector": text: """%LARGESHIPONLY%%LINEBREAK%After an enemy ship executes a maneuver that causes it to overlap your ship, roll 1 attack die. On a %HIT% or %CRIT% result, the enemy ship receives 1 ion token.""" title_translations = "Slave I": text: """<span class="card-restriction">Firespray-31 only.</span>%LINEBREAK%Your upgrade bar gains the %TORPEDO% upgrade icon.""" "Millennium Falcon": text: """<span class="card-restriction">YT-1300 only.</span>%LINEBREAK%Your action bar gains the %EVADE% action icon.""" "Moldy Crow": text: """<span class="card-restriction">HWK-290 only.</span>%LINEBREAK%During the End phase, do not remove unused focus tokens from your ship.""" "ST-321": text: """<span class="card-restriction"><em>Lambda</em>-class Shuttle only.</span>%LINEBREAK%When acquiring a target lock, you may lock onto any enemy ship in the play area.""" "Royal Guard TIE": text: """<span class="card-restriction">TIE Interceptor only.</span>%LINEBREAK%You may equip up to 2 different Modification upgrades (instead of 1).%LINEBREAK%You cannot equip this card if your pilot skill value is "4" or lower.""" "Dodonna's Pride": text: """<span class="card-restriction">CR90 fore section only.</span>%LINEBREAK%When you perform a coordinate action, you may choose 2 friendly ships (instead of 1). Those ships may each perform 1 free action.""" "A-Wing Test Pilot": text: """<span class="card-restriction">A-Wing only.</span>%LINEBREAK%Your upgrade bar gains 1 %ELITE% upgrade icon.%LINEBREAK%You cannot equip 2 of the same %ELITE% Upgrade cards. You cannot equip this if your pilot skill value is "1" or lower.""" "Tantive IV": text: """<span class="card-restriction">CR90 fore section only.</span>%LINEBREAK%Your fore section upgrade bar gains 1 additional %CREW% and 1 additional %TEAM% upgrade icon.""" "Bright Hope": text: """<span class="card-restriction">GR-75 only.</span>%LINEBREAK%A reinforce action assigned to your fore section adds 2 %EVADE% results (instead of 1).""" "Quantum Storm": text: """<span class="card-restriction">GR-75 only.</span>%LINEBREAK%At the start of the End phase, if you have 1 or fewer energy tokens, gain 1 energy token.""" "Dutyfree": text: """<span class="card-restriction">GR-75 only.</span>%LINEBREAK%When performing a jam action, you may choose an enemy ship at Range 1-3 (instead of at Range 1-2).""" "Jaina's Light": text: """<span class="card-restriction">CR90 fore section only.</span>%LINEBREAK%When defending, once per attack, if you are dealt a faceup Damage card, you may discard it and draw another faceup Damage card.""" "Outrider": text: """<span class="card-restriction">YT-2400 only.</span>%LINEBREAK%While you have a %CANNON% Upgrade card equipped, you <strong>cannot</strong> perform primary weapon attacks and you may perform %CANNON% secondary weapon attacks against ships outside your firing arc.""" "Dauntless": text: """<span class="card-restriction">VT-49 Decimator only.</span>%LINEBREAK%After you execute a maneuver that causes you to overlap another ship, you may perform 1 free action. Then receive 1 stress token.""" "Virago": text: """<span class="card-restriction">StarViper only.</span>%LINEBREAK%Your upgrade bar gains the %SYSTEM% and %ILLICIT% upgrade icons.%LINEBREAK%You cannot equip this card if your pilot skill value is "3" or lower.""" '"Heavy Scyk" Interceptor (Cannon)': text: """<span class="card-restriction">M3-A Interceptor only.</span>%LINEBREAK%Your upgrade bar gains the %CANNON%, %TORPEDO%, or %MISSILE% upgrade icon.""" '"Heavy Scyk" Interceptor (Torpedo)': text: """<span class="card-restriction">M3-A Interceptor only.</span>%LINEBREAK%Your upgrade bar gains the %CANNON%, %TORPEDO%, or %MISSILE% upgrade icon.""" '"Heavy Scyk" Interceptor (Missile)': text: """<span class="card-restriction">M3-A Interceptor only.</span>%LINEBREAK%Your upgrade bar gains the %CANNON%, %TORPEDO%, or %MISSILE% upgrade icon.""" "IG-2000": text: """<span class="card-restriction">Aggressor only.</span>%LINEBREAK%You have the pilot ability of each other friendly ship with the <em>IG-2000</em> Upgrade card (in addition to your own pilot ability).""" "BTL-A4 Y-Wing": text: """<span class="card-restriction">Y-Wing only.</span>%LINEBREAK%You cannot attack ships outside your firing arc. After you perform a primary weapon attack, you may immediately perform an attack with a %TURRET% secondary weapon.""" "Andrasta": text: """Your upgrade bar gains two additional %BOMB% upgrade icons.""" "TIE/x1": text: """<span class="card-restriction">TIE Advanced only.</span>%LINEBREAK%Your upgrade bar gains the %SYSTEM% upgrade icon.%LINEBREAK%If you equip a %SYSTEM% upgrade, its squad point cost is reduced by 4 (to a minimum of 0).""" "Hound's Tooth": text: """<span class="card-restriction">YV-666 only.</span>%LINEBREAK%After you are destroyed, before you are removed from the play area, you may <strong>deploy</strong> the <em>Nashtah Pup</em> ship.%LINEBREAK%It cannot attack this round.""" "Ghost": text: """<span class="card-restriction">VCX-100 only.</span>%LINEBREAK%Equip the <em>Phantom</em> title card to a friendly Attack Shuttle and dock it to this ship.%LINEBREAK%After you execute a maneuver, you may deploy it from your rear guides.""" "Phantom": text: """While you are docked, the <em>Ghost</em> can perform primary weapon attacks from its special firing arc, and, at the end of the Combat phase, it may perform an additional attack with an equipped %TURRET%. If it performs this attack, it cannot attack again this round.""" "TIE/v1": text: """<span class="card-restriction">TIE Advanced Prototype only.</span>%LINEBREAK%After you acquire a target lock, you may perform a free evade action.""" "Mist Hunter": text: """<span class="card-restriction">G-1A starfighter only.</span>%LINEBREAK%Your upgrade bar gains the %BARRELROLL% Upgrade icon.%LINEBREAK%You <strong>must</strong> equip 1 "Tractor Beam" Upgrade card (paying its squad point cost as normal).""" "Punishing One": text: """<span class="card-restriction">JumpMaster 5000 only.</span>%LINEBREAK%Increase your primary weapon value by 1.""" exportObj.setupCardData basic_cards, pilot_translations, upgrade_translations, modification_translations, title_translations
199346
exportObj = exports ? this exportObj.codeToLanguage ?= {} exportObj.codeToLanguage.en = 'English' exportObj.translations ?= {} # This is here mostly as a template for other languages. exportObj.translations.English = action: "Barrel Roll": "Barrel Roll" "Boost": "Boost" "Evade": "Evade" "Focus": "Focus" "Target Lock": "Target Lock" "Recover": "Recover" "Reinforce": "Reinforce" "Jam": "Jam" "Coordinate": "Coordinate" "Cloak": "Cloak" "SLAM": "SLAM" slot: "Astromech": "Astromech" "Bomb": "Bomb" "Cannon": "Cannon" "Crew": "Crew" "Elite": "Elite" "Missile": "Missile" "System": "System" "Torpedo": "Torpedo" "Turret": "Turret" "Cargo": "Cargo" "Hardpoint": "Hardpoint" "Team": "Team" "Illicit": "Illicit" "Salvaged Astromech": "Salvaged Astromech" sources: # needed? "Core": "Core" "A-Wing Expansion Pack": "A-Wing Expansion Pack" "B-Wing Expansion Pack": "B-Wing Expansion Pack" "X-Wing Expansion Pack": "X-Wing Expansion Pack" "Y-Wing Expansion Pack": "Y-Wing Expansion Pack" "Millennium Falcon Expansion Pack": "Millennium Falcon Expansion Pack" "HWK-290 Expansion Pack": "HWK-290 Expansion Pack" "TIE Fighter Expansion Pack": "TIE Fighter Expansion Pack" "TIE Interceptor Expansion Pack": "TIE Interceptor Expansion Pack" "TIE Bomber Expansion Pack": "TIE Bomber Expansion Pack" "TIE Advanced Expansion Pack": "TIE Advanced Expansion Pack" "Lambda-Class Shuttle Expansion Pack": "Lambda-Class Shuttle Expansion Pack" "Slave I Expansion Pack": "Slave I Expansion Pack" "Imperial Aces Expansion Pack": "Imperial Aces Expansion Pack" "Rebel Transport Expansion Pack": "Rebel Transport Expansion Pack" "Z-95 Headhunter Expansion Pack": "Z-95 Headhunter Expansion Pack" "TIE Defender Expansion Pack": "TIE Defender Expansion Pack" "E-Wing Expansion Pack": "E-Wing Expansion Pack" "TIE Phantom Expansion Pack": "TIE Phantom Expansion Pack" "Tantive IV Expansion Pack": "Tantive IV Expansion Pack" "Rebel Aces Expansion Pack": "Rebel Aces Expansion Pack" "YT-2400 Freighter Expansion Pack": "YT-2400 Freighter Expansion Pack" "VT-49 Decimator Expansion Pack": "VT-49 Decimator Expansion Pack" "StarViper Expansion Pack": "StarViper Expansion Pack" "M3-A Interceptor Expansion Pack": "M3-A Interceptor Expansion Pack" "IG-2000 Expansion Pack": "IG-2000 Expansion Pack" "Most Wanted Expansion Pack": "Most Wanted Expansion Pack" "Imperial Raider Expansion Pack": "Imperial Raider Expansion Pack" "Hound's Tooth Expansion Pack": "Hound's Tooth Expansion Pack" "Kihraxz Fighter Expansion Pack": "Kihraxz Fighter Expansion Pack" "K-Wing Expansion Pack": "K-Wing Expansion Pack" "TIE Punisher Expansion Pack": "TIE Punisher Expansion Pack" ui: shipSelectorPlaceholder: "Select a ship" pilotSelectorPlaceholder: "Select a pilot" upgradePlaceholder: (translator, language, slot) -> "No #{translator language, 'slot', slot} Upgrade" modificationPlaceholder: "No Modification" titlePlaceholder: "No Title" upgradeHeader: (translator, language, slot) -> "#{translator language, 'slot', slot} Upgrade" unreleased: "unreleased" epic: "epic" limited: "limited" byCSSSelector: '.xwing-card-browser .translate.sort-cards-by': 'Sort cards by' '.xwing-card-browser option[value="name"]': 'Name' '.xwing-card-browser option[value="source"]': 'Source' '.xwing-card-browser option[value="type-by-points"]': 'Type (by Points)' '.xwing-card-browser option[value="type-by-name"]': 'Type (by Name)' '.xwing-card-browser .translate.select-a-card': 'Select a card from the list at the left.' # Info well '.info-well .info-ship td.info-header': 'Ship' '.info-well .info-skill td.info-header': 'Skill' '.info-well .info-actions td.info-header': 'Actions' '.info-well .info-upgrades td.info-header': 'Upgrades' '.info-well .info-range td.info-header': 'Range' # Squadron edit buttons '.clear-squad' : 'New Squad' '.save-list' : 'Save' '.save-list-as' : 'Save as…' '.delete-list' : 'Delete' '.backend-list-my-squads' : 'Load squad' '.view-as-text' : '<span class="hidden-phone"><i class="icon-print"></i>&nbsp;Print/View as </span>Text' '.randomize' : 'Random!' '.randomize-options' : 'Randomizer options…' # Print/View modal '.bbcode-list' : 'Copy the BBCode below and paste it into your forum post.<textarea></textarea>' '.vertical-space-checkbox' : """Add space for damage/upgrade cards when printing <input type="checkbox" class="toggle-vertical-space" />""" '.color-print-checkbox' : """Print color <input type="checkbox" class="toggle-color-print" />""" '.print-list' : '<i class="icon-print"></i>&nbsp;Print' # Randomizer options '.do-randomize' : 'Randomize!' # Top tab bar '#empireTab' : 'Galactic Empire' '#rebelTab' : 'Rebel Alliance' '#scumTab' : 'Scum and Villainy' '#browserTab' : 'Card Browser' '#aboutTab' : 'About' singular: 'pilots': 'Pilot' 'modifications': 'Modification' 'titles': 'Title' types: 'Pilot': 'Pilot' 'Modification': 'Modification' 'Title': 'Title' exportObj.cardLoaders ?= {} exportObj.cardLoaders.English = () -> exportObj.cardLanguage = 'English' # Assumes cards-common has been loaded basic_cards = exportObj.basicCardData() exportObj.canonicalizeShipNames basic_cards # English names are loaded by default, so no update is needed exportObj.ships = basic_cards.ships # Names don't need updating, but text needs to be set pilot_translations = "Wedge Antilles": text: """When attacking, reduce the defender's agility value by 1 (to a minimum of "0").""" "<NAME>": text: """After spending a focus token, you may place that token on any other friendly ship at Range 1-2 (instead of discarding it).""" "Biggs Darklighter": text: """Other friendly ships at Range 1 cannot be targeted by attacks if the attacker could target you instead.""" "Lu<NAME> Skywalker": text: """When defending, you may change 1 of your %FOCUS% results to a %EVADE% result.""" '"Dutch" Vander': text: """After acquiring a target lock, choose another friendly ship at Range 1-2. The chosen ship may immediately acquire a target lock.""" "<NAME>": text: """When attacking at Range 2-3, you may reroll any of your blank results.""" '"W<NAME>"': text: """When attacking at Range 1, you may change 1 of your %HIT% results to a %CRIT% result.""" '"Night Beast"': text: """After executing a green maneuver, you may perform a free focus action.""" '"Back<NAME>"': text: """When attacking from outside the defender's firing arc, roll 1 additional attack die.""" '"Dark <NAME>"': text: """When defending, ships attacking you cannot spend focus tokens or reroll attack dice.""" '"<NAME>"': text: """When attacking at Range 1, roll 1 additional attack die.""" '"How<NAME>"': text: """When another friendly ship at Range 1 is attacking with its primary weapon, it may reroll 1 attack die.""" "<NAME>": text: """When your attack deals a faceup Damage card to the defender, instead draw 3 Damage cards, choose 1 to deal, and discard the others.""" "<NAME>": text: """During your "Perform Action" step, you may perform 2 actions.""" "\"<NAME>\"": text: """When the number of Damage cards assigned to you equals or exceeds your hull value, you are not destroyed until the end of the Combat phase.""" "<NAME>": text: """After you perform an attack, you may perform a free boost or barrel roll action.""" "<NAME>": text: """When you receive a stress token, you may assign 1 focus token to your ship.""" "<NAME>": text: """You may perform actions even while you have stress tokens.""" "<NAME>": text: """You may declare an enemy ship inside your firing arc that you are touching as the target of your attack.""" "<NAME>": text: """When you are dealt a faceup Damage card, immediately flip it facedown (without resolving its ability).""" "<NAME>": text: """After you execute a green maneuver, choose 1 other friendly ship at Range 1. That ship may perform 1 free action shown on its action bar.""" "<NAME>": text: """When attacking, you may reroll all of your dice. If you choose to do so, you must reroll as many of your dice as possible.""" "<NAME>": text: """When attacking, the defender receives 1 stress token if he cancels at least 1 %CRIT% result.""" "<NAME>": text: """When you reveal a bank maneuver (%BANKLEFT% or %BANKRIGHT%), you may rotate your dial to the other bank maneuver of the same speed.""" "<NAME>": text: """When attacking with a secondary weapon, you may reroll 1 attack die.""" "<NAME>": text: """When attacking, 1 of your %CRIT% results cannot be canceled by defense dice.""" "<NAME>": text: """When attacking or defending, if you have at least 1 stress token, you may reroll 1 of your dice.""" "<NAME>": text: '''At the start of the Combat phase, choose 1 other friendly ship at Range 1-3. Until the end of the phase, treat that ship's pilot skill value as "12."''' "<NAME>": text: """At the start of the Combat phase, you may assign 1 of your focus tokens to another friendly ship at Range 1-3.""" "<NAME>": text: """When another friendly ship at Range 1-3 is attacking, if you have no stress tokens, you may receive 1 stress token to allow that ship to roll 1 additional attack die.""" "<NAME>": text: """When another friendly ship at Range 1 attacks with a secondary weapon, it may reroll up to 2 attack dice.""" "<NAME>": text: """When attacking with a secondary weapon, you may increase or decrease the weapon range by 1 to a limit of Range 1-3.""" "<NAME>": text: """When an enemy ship acquires a target lock, it must lock onto your ship if able.""" "<NAME>": text: """At the start of the Combat phase, you may assign 1 of your blue target lock tokens to a friendly ship at Range 1 if it does not have a blue target lock token.""" "<NAME>": text: """When another friendly ship at Range 1-2 would receive a stress token, if you have 2 or fewer stress tokens, you may receive that token instead.""" "<NAME>": text: """When performing a barrel roll action, you may receive 1 stress token to use the (%BANKLEFT% 1) or (%BANKRIGHT% 1) template instead of the (%STRAIGHT% 1) template.""" "<NAME>": text: """When you reveal a %UTURN% maneuver, you may treat the speed of that maneuver as "1," "3," or "5".""" "<NAME>": text: """When attacking at Range 2-3, you may spend 1 evade token to add 1 %HIT% result to your roll.""" "<NAME>": text: """Enemy ships at Range 1 cannot perform focus or evade actions and cannot spend focus or evade tokens.""" "<NAME>": text: """When attacking, the defender is hit by your attack, even if he does not suffer any damage.""" "<NAME>": text: """After you perform an attack, you may choose another friendly ship at Range 1. That ship may perform 1 free action.""" "<NAME>": text: """When attacking, immediately after you roll attack dice, you may acquire a target lock on the defender if it already has a red target lock token.""" "<NAME>": text: """After you perform an attack that deals at least 1 Damage card to the defender, you may spend a focus token to flip those cards faceup.""" "<NAME>": text: """When an enemy ship inside your firing arc at Range 1-3 is defending, the attacker may change 1 of its %HIT% results to a %CRIT% result.""" "<NAME>": text: """At the start of the End phase, you may perform one attack. You cannot attack during the next round.""" '"<NAME>"': text: """When you decloak, you must use the (%BANKLEFT% 2) or (%BANKRIGHT% 2) template instead of the (%STRAIGHT% 2) template.""" '"<NAME>isper"': text: """After you perform an attack that hits, you may assign 1 focus to your ship.""" "<NAME>": text: """After you perform an attack, you may remove 1 focus, evade, or blue target lock token from the defender.""" "<NAME>": text: """When you receive a stress token, you may remove it and roll 1 attack die. On a %HIT% result, deal 1 facedown Damage card to this ship.""" '"<NAME>" <NAME>': text: """When you acquire or spend a target lock, you may remove 1 stress token from your ship.""" "<NAME>": text: """When an enemy ship declares you as the target of an attack, you may acquire a target lock on that ship.""" "<NAME>": text: """After you perform a focus action or are assigned a focus token, you may perform a free boost or barrel roll action.""" "<NAME>": text: """While you are at Range 1 of at least 1 enemy ship, increase your agility value by 1.""" "<NAME>": text: """When attacking, you may remove 1 stress token to change all of your %FOCUS% results to %HIT%results.""" "<NAME>": text: """You can perform %TORPEDO% secondary weapon attacks against enemy ships outside your firing arc.""" "CR90 Corvette (Fore)": text: """When attacking with your primary weapon, you may spend 1 energy to roll 1 additional attack die.""" # "CR90 Corvette (Crippled Aft)": # text: """You cannot choose or execute (%STRAIGHT% 4), (%BANKLEFT% 2), or (%BANKRIGHT% 2) maneuvers.""" "<NAME>": text: """You may ignore obstacles during the Activation phase and when performing actions.""" '"<NAME>"': text: """When you are dealt a faceup Damage card, draw 1 additional Damage card, choose 1 to resolve, and discard the other.""" "<NAME>": text: """When performing a primary weapon attack against a stressed ship, roll 1 additional attack die.""" "<NAME>": text: """When attacking at Range 1-2, you may change 1 of your %FOCUS% results to a %CRIT% result.""" "<NAME>": text: """If you have no shields and at least 1 Damage card assigned to you, increase your agility value by 1.""" "<NAME>": text: """After executing a maneuver, each enemy ship you are touching suffers 1 damage.""" "<NAME>": text: """When defending, a friendly ship at Range 1 may suffer 1 uncanceled %HIT% or %CRIT% result instead of you.""" "<NAME>": text: """At the start of the Combat phase, if you are at Range 1 of an enemy ship, you may assign 1 focus token to your ship.""" "<NAME>": text: """When another friendly ship at Range 1 is defending, it may reroll 1 defense die.""" "<NAME>": text: """After you defend against an attack, if the attack did not hit, you may assign 1 evade token to your ship.""" "IG-88A": text: """After you perform an attack that destroys the defender, you may recover 1 shield.""" "IG-88B": text: """Once per round, after you perform an attack that does not hit, you may perform an attack with an equipped %CANNON% secondary weapon.""" "IG-88C": text: """After you perform a boost action, you may perform a free evade action.""" "IG-88D": text: """You may execute the (%SLOOPLEFT% 3) or (%SLOOPRIGHT% 3) maneuver using the corresponding (%TURNLEFT% 3) or (%TURNRIGHT% 3) template.""" "<NAME> (Scum)": text: """When attacking or defending, you may reroll 1 of your dice for each enemy ship at Range 1.""" "<NAME> (Scum)": text: """When attacking a ship inside your auxiliary firing arc, roll 1 additional attack die.""" "<NAME>": text: """When dropping a bomb, you may use the [%TURNLEFT% 3], [%STRAIGHT% 3], or [%TURNRIGHT% 3] template instead of the [%STRAIGHT% 1] template.""" "<NAME>": text: """When attacking a ship outside your firing arc, roll 1 additional attack die.""" "<NAME>": text: """After you spend a target lock, you may receive 1 stress token to acquire a target lock.""" "<NAME>": text: """When an enemy ship at Range 1-3 receives at least 1 ion token, if you are not stressed, you may receive 1 stress token to cause that ship to suffer 1 damage.""" "<NAME>": text: """At the start of the Combat phase, you may remove 1 focus or evade token from an enemy ship at Range 1-2 and assign it to yourself.""" "<NAME>": text: """At the end of the Activation phase, choose 1 enemy ship at Range 1-2. Until the end of the Combat phase, treat that ship's pilot skill value as "0".""" "<NAME>": text: """When attacking, if there are no other friendly ships at Range 1-2, roll 1 additional attack die.""" "<NAME>": text: """At the start of the Combat phase, you may remove 1 focus or evade token from another friendly ship at Range 1-2 and assign it to yourself.""" "<NAME>": text: """At the start of the Combat phase, you may acquire a target lock on an enemy ship at Range 1.""" "Raider-class Corvette (Fore)": text: """Once per round, after you perform a primary weapon attack, you may spend 2 energy to perform another primary weapon attack.""" "Boss<NAME>": text: """When you perform an attack that hits, before dealing damage, you may cancel 1 of your %CRIT% results to add 2 %HIT% results.""" "<NAME>": text: """When attacking or defending, double the effect of your range combat bonuses.""" "<NAME>": text: """Once per round when attacking, you may either spend 1 shield to roll 1 additional attack die <strong>or</strong> roll 1 fewer attack die to recover 1 shield.""" '"<NAME>"': text: """You may maintain 2 target locks on the same ship. When you acquire a target lock, you may acquire a second lock on that ship.""" '"<NAME>"': text: """When dropping a bomb, you may use the front guides of your ship. After dropping a bomb, you may perform a free barrel roll action.""" "Juno Eclipse": text: """When you reveal your maneuver, you may increase or decrease its speed by 1 (to a minimum of 1).""" "<NAME>": text: """Enemy ships at Range 1 cannot add their range combat bonus when attacking.""" "<NAME>": text: """At the start of the End phase, you may spend a target lock you have on an enemy ship to flip 1 random facedown Damage card assigned to it faceup.""" "<NAME>": text: """When a friendly ship declares an attack, you may spend a target lock you have on the defender to reduce its agility by 1 for that attack.""" "<NAME>": text: """When defending, if the attacker is inside your firing arc, roll 1 additional defense die.""" "<NAME>": text: """When another friendly ship at Range 1-2 is attacking, it may treat your focus tokens as its own.""" "<NAME>": text: """You can perform %CANNON% secondary attacks against ships inside your auxiliary firing arc.""" '<NAME>anti-class C<NAME>iser': text: """After you execute a maneuver, you may deploy up to 2 attached ships.""" '"<NAME>"': text: """When attacking a defender that has 1 or more Damage cards, roll 1 additional attack die.""" "<NAME> In<NAME>": text: """When attacking with your primary weapon at Range 2-3, treat the range of the attack as Range 1.""" "<NAME>": text: """When attacking, you may roll 1 additional attack die. If you do, the defender rolls 1 additional defense die.""" "Dengar": text: """Once per round after defending, if the attacker is inside your firing arc, you may perform an attack against the that ship.""" upgrade_translations = "Ion Cannon Turret": text: """<strong>Attack:</strong> Attack 1 ship (even a ship outside your firing arc).%LINEBREAK%If this attack hits the target ship, the ship suffers 1 damage and receives 1 ion token. Then cancel all dice results.""" "Pro<NAME>": text: """<strong>Attack (target lock):</strong> Spend your target lock and discard this card to perform this attack.%LINEBREAK%You may change 1 of your %FOCUS% results to a %CRIT% result.""" "R2 Astromech": text: """You may treat all 1- and 2-speed maneuvers as green maneuvers.""" "R2-D2": text: """After executing a green maneuver, you may recover 1 shield (up to your shield value).""" "R2-F2": text: """<strong>Action:</strong> Increase your agility value by 1 until the end of this game round.""" "R5-D8": text: """<strong>Action:</strong> Roll 1 defense die.%LINEBREAK%On a %EVADE% or %FOCUS% result, discard 1 of your facedown Damage cards.""" "R5-K6": text: """After spending your target lock, roll 1 defense die.%LINEBREAK%On a %EVADE% result, immediately acquire a target lock on that same ship. You cannot spend this target lock during this attack.""" "R5 Astromech": text: """During the End phase, you may choose 1 of your faceup Damage cards with the Ship trait and flip it facedown.""" "Determination": text: """When you are dealt a faceup Damage card with the Pilot trait, discard it immediately without resolving its effect.""" "Swarm Tactics": text: """At the start of the Combat phase, you may choose 1 friendly ship at Range 1.%LINEBREAK%Until the end of this phase, treat the chosen ship as if its pilot skill were equal to your pilot skill.""" "Squad Leader": text: """<strong>Action:</strong> Choose 1 ship at Range 1-2 that has a lower pilot skill than you.%LINEBREAK%The chosen ship may immediately perform 1 free action.""" "Expert Handling": text: """<strong>Action:</strong> Perform a free barrel roll action. If you do not have the %BARRELROLL% action icon, receive 1 stress token.%LINEBREAK%You may then remove 1 enemy target lock from your ship.""" "Marksmanship": text: """<strong>Action:</strong> When attacking this round, you may change 1 of your %FOCUS% results to a %CRIT% result and all of your other %FOCUS% results to %HIT% results.""" "Concussion Missiles": text: """<strong>Attack (target lock):</strong> Spend your target lock and discard this card to perform this attack.%LINEBREAK%You may change 1 of your blank results to a %HIT% result.""" "Cluster Missiles": text: """<strong>Attack (target lock):</strong> Spend your target lock and discard this card to perform this attack twice.""" "Daredevil": text: """<strong>Action:</strong> Execute a white (%TURNLEFT% 1) or (%TURNRIGHT% 1) maneuver. Then, receive 1 stress token.%LINEBREAK%Then, if you do not have the %BOOST% action icon, roll 2 attack dice. Suffer any damage (%HIT%) and any critical damage (%CRIT%) rolled.""" "Elusiveness": text: """When defending, you may receive 1 stress token to choose 1 attack die. The attacker must reroll that die.%LINEBREAK%If you have at least 1 stress token, you cannot use this ability.""" "Homing Missiles": text: """<strong>Attack (target lock):</strong> Discard this card to perform this attack.%LINEBREAK%The defender cannot spend evade tokens during this attack.""" "Push the Limit": text: """Once per round, after you perform an action, you may perform 1 free action shown in your action bar.%LINEBREAK%Then receive 1 stress token.""" "Deadeye": text: """You may treat the <strong>Attack (target lock):</strong> header as <strong>Attack (focus):</strong>.%LINEBREAK%When an attack instructs you to spend a target lock, you may spend a focus token instead.""" "Expose": text: """<strong>Action:</strong> Until the end of the round, increase your primary weapon value by 1 and decrease your agility value by 1.""" "Gunner": text: """After you perform an attack that does not hit, you may immediately perform a primary weapon attack. You cannot perform another attack this round.""" "Ion Cannon": text: """<strong>Attack:</strong> Attack 1 ship.%LINEBREAK%If this attack hits, the defender suffers 1 damage and receives 1 ion token. Then cancel all dice results.""" "Heavy Laser Cannon": text: """<strong>Attack:</strong> Attack 1 ship.%LINEBREAK%Immediately after rolling your attack dice, you must change all of your %CRIT% results to %HIT% results.""" "Seismic Charges": text: """When you reveal your maneuver dial, you may discard this card to drop 1 seismic charge token.%LINEBREAK%This token detonates at the end of the Activation phase.%LINEBREAK%<strong>Seismic Charge Token:</strong> When this bomb token detonates, each ship at Range 1 of the token suffers 1 damage. Then discard this token.""" "Mercenary Copilot": text: """When attacking at Range 3, you may change 1 of your %HIT% results to a %CRIT% result.""" "Assault Missiles": text: """<strong>Attack (target lock):</strong> Spend your target lock and discard this card to perform this attack.%LINEBREAK%If this attack hits, each other ship at Range 1 of the defender suffers 1 damage.""" "Veteran Instincts": text: """Increase your pilot skill value by 2.""" "Proximity Mines": text: """<strong>Action:</strong> Discard this card to <strong>drop</strong> 1 proximity mine token.%LINEBREAK%When a ship's base or maneuver template overlaps this token, this token <strong>detonates</strong>.%LINEBREAK%<strong>Proximity Mine Token:</strong> When this bomb token detonates, the ship that moved through or overlapped this token rolls 3 attack dice and suffers all damage (%HIT%) and critical damage (%CRIT%) rolled. Then discard this token.""" "Weapons Engineer": text: """You may maintain 2 target locks (only 1 per enemy ship).%LINEBREAK%When you acquire a target lock, you may lock onto 2 different ships.""" "Draw Their Fire": text: """When a friendly ship at Range 1 is hit by an attack, you may suffer 1 of the uncanceled %CRIT% results instead of the target ship.""" "<NAME>": text: """%REBELONLY%%LINEBREAK%After you perform an attack that does not hit, you may immediately perform a primary weapon attack. You may change 1 %FOCUS% result to a %HIT% result. You cannot perform another attack this round.""" "<NAME>": text: """%REBELONLY%%LINEBREAK%You may treat all %STRAIGHT% maneuvers as green maneuvers.""" "Chewb<NAME>": text: """%REBELONLY%%LINEBREAK%When you are dealt a Damage card, you may immediately discard that card and recover 1 shield.%LINEBREAK%Then, discard this Upgrade card.""" "Advanced Proton Torpedoes": text: """<strong>Attack (target lock):</strong> Spend your target lock and discard this card to perform this attack.%LINEBREAK%You may change up to 3 of your blank results to %FOCUS% results.""" "Autoblaster": text: """<strong>Attack:</strong> Attack 1 ship.%LINEBREAK%Your %HIT% results cannot be canceled by defense dice.%LINEBREAK%The defender may cancel %CRIT% results before %HIT% results.""" "Fire-Control System": text: """After you perform an attack, you may acquire a target lock on the defender.""" "Blaster Turret": text: """<strong>Attack (focus):</strong> Spend 1 focus token to perform this attack against 1 ship (even a ship outside your firing arc).""" "Recon Specialist": text: """When you perform a focus action, assign 1 additional focus token to your ship.""" "Saboteur": text: """<strong>Action:</strong> Choose 1 enemy ship at Range 1 and roll 1 attack die. On a %HIT% or %CRIT% result, choose 1 random facedown Damage card assigned to that ship, flip it faceup, and resolve it.""" "Intelligence Agent": text: """At the start of the Activation phase, choose 1 enemy ship at Range 1-2. You may look at that ship's chosen maneuver.""" "Proton Bombs": text: """When you reveal your maneuver dial, you may discard this card to <strong>drop</strong> 1 proton bomb token.%LINEBREAK%This token <strong>detonates</strong> at the end of the Activation phase.%LINEBREAK%<strong>Proton Bomb Token:</strong> When this bomb token detonates, deal 1 <strong>faceup</strong> Damage card to each ship at Range 1 of the token. Then discard this token.""" "Ad<NAME>aline Rush": text: """When you reveal a red maneuver, you may discard this card to treat that maneuver as a white maneuver until the end of the Activation phase.""" "Advanced Sensors": text: """Immediately before you reveal your maneuver, you may perform 1 free action.%LINEBREAK%If you use this ability, you must skip your "Perform Action" step during this round.""" "Sensor Jammer": text: """When defending, you may change 1 of the attacker's %HIT% results into a %FOCUS% result.%LINEBREAK%The attacker cannot reroll the die with the changed result.""" "Darth Vader": text: """%IMPERIALONLY%%LINEBREAK%After you perform an attack against an enemy ship, you may suffer 2 damage to cause that ship to suffer 1 critical damage.""" "Rebel Captive": text: """%IMPERIALONLY%%LINEBREAK%Once per round, the first ship that declares you as the target of an attack immediately receives 1 stress token.""" "Flight Instructor": text: """When defending, you may reroll 1 of your %FOCUS% results. If the attacker's pilot skill value is "2" or lower, you may reroll 1 of your blank results instead.""" "Navigator": text: """When you reveal a maneuver, you may rotate your dial to another maneuver with the same bearing.%LINEBREAK%You cannot rotate to a red maneuver if you have any stress tokens.""" "Opportunist": text: """When attacking, if the defender does not have any focus or evade tokens, you may receive 1 stress token to roll 1 additional attack die.%LINEBREAK%You cannot use this ability if you have any stress tokens.""" "Comms Booster": text: """<strong>Energy:</strong> Spend 1 energy to remove all stress tokens from a friendly ship at Range 1-3. Then assign 1 focus token to that ship.""" "Slicer Tools": text: """<strong>Action:</strong> Choose 1 or more ships at Range 1-3 that have a stress token. For each ship chosen, you may spend 1 energy to cause that ship to suffer 1 damage.""" "Shield Projector": text: """When an enemy ship is declaring either a small or large ship as the target of its attack, you may spend 3 energy to force that ship to target you if possible.""" "Ion Pulse Missiles": text: """<strong>Attack (target lock):</strong> Discard this card to perform this attack.%LINEBREAK%If this attack hits, the defender suffers 1 damage and receives 2 ion tokens. Then cancel <strong>all</strong> dice results.""" "Wingman": text: """At the start of the Combat phase, remove 1 stress token from another friendly ship at Range 1.""" "Decoy": text: """At the start of the Combat phase, you may choose 1 friendly ship at Range 1-2. Exchange your pilot skill with that ship's pilot skill until the end of the phase.""" "Outmaneuver": text: """When attacking a ship inside your firing arc, if you are not inside that ship's firing arc, reduce its agility value by 1 (to a minimum of 0).""" "Predator": text: """When attacking, you may reroll 1 attack die. If the defender's pilot skill value is "2" or lower, you may instead reroll up to 2 attack dice.""" "<NAME>": text: """<strong>Attack (target lock):</strong> Discard this card and spend your target lock to perform this attack.%LINEBREAK%After you perform this attack, the defender receives 1 stress token if its hull value is "4" or lower.""" "R7 Astromech": text: """Once per round when defending, if you have a target lock on the attacker, you may spend the target lock to choose any or all attack dice. The attacker must reroll the chosen dice.""" "R7-T1": text: """<strong>Action:</strong> Choose an enemy ship at Range 1-2. If you are inside that ship's firing arc, you may acquire a target lock on that ship. Then, you may perform a free boost action.""" "Tactician": text: """After you perform an attack against a ship inside your firing arc at Range 2, that ship receives 1 stress token.""" "R2-D2 (Crew)": text: """%REBELONLY%%LINEBREAK%At the end of the End phase, if you have no shields, you may recover 1 shield and roll 1 attack die. On a %HIT% result, randomly flip 1 of your facedown Damage cards faceup and resolve it.""" "C-3PO": text: """%REBELONLY%%LINEBREAK%Once per round, before you roll 1 or more defense dice, you may guess aloud a number of %EVADE% results. If you roll that many %EVADE% results (before modifying dice), add 1 %EVADE% result.""" "Single Turbolasers": text: """<strong>Attack (Energy):</strong> Spend 2 energy from this card to perform this attack. The defender doubles his agility value against this attack. You may change 1 of your %FOCUS% results to a %HIT% result.""" "Quad Laser Cannons": text: """<strong>Attack (Energy):</strong> Spend 1 energy from this card to perform this attack. If this attack does not hit, you may immediately spend 1 energy from this card to perform this attack again.""" "Tibanna Gas Supplies": text: """<strong>Energy:</strong> You may discard this card to gain 3 energy.""" "Ionization Reactor": text: """<strong>Energy:</strong> Spend 5 energy from this card and discard this card to cause each other ship at Range 1 to suffer 1 damage and receive 1 ion token.""" "Engine Booster": text: """Immediately before you reveal your maneuver dial, you may spend 1 energy to execute a white (%STRAIGHT% 1) maneuver. You cannot use this ability if you would overlap another ship.""" "R3-A2": text: """When you declare the target of your attack, if the defender is inside your firing arc, you may receive 1 stress token to cause the defender to receive 1 stress token.""" "R2-D6": text: """Your upgrade bar gains the %ELITE% upgrade icon.%LINEBREAK%You cannot equip this upgrade if you already have a %ELITE% upgrade icon or if your pilot skill value is "2" or lower.""" "Enhanced Scopes": text: """During the Activation phase, treat your pilot skill value as "0".""" "Chardaan Refit": text: """<span class="card-restriction">A-Wing only.</span>%LINEBREAK%This card has a negative squad point cost.""" "Proton Rockets": text: """<strong>Attack (Focus):</strong> Discard this card to perform this attack.%LINEBREAK%You may roll additional attack dice equal to your agility value, to a maximum of 3 additional dice.""" "<NAME>": text: """%REBELONLY%%LINEBREAK%After you remove a stress token from your ship, you may assign a focus token to your ship.""" "<NAME>": text: """%REBELONLY%%LINEBREAK%Once per round, when a friendly ship at Range 1-3 performs a focus action or would be assigned a focus token, you may assign it an evade token instead.""" "<NAME>": text: """%HUGESHIPONLY% %REBELONLY%%LINEBREAK%<strong>Action:</strong> Spend any amount of energy to choose that many enemy ships at Range 1-2. Remove all focus, evade, and blue target lock tokens from those ships.""" "R4-D6": text: """When you are hit by an attack and there are at least 3 uncanceled %HIT% results, you may choose to cancel those results until there are 2 remaining. For each result canceled this way, receive 1 stress token.""" "R5-P9": text: """At the end of the Combat phase, you may spend 1 of your focus tokens to recover 1 shield (up to your shield value).""" "WED-15 Repair Droid": text: """%HUGESHIPONLY%%LINEBREAK%<strong>Action:</strong> Spend 1 energy to discard 1 of your facedown Damage cards, or spend 3 energy to discard 1 of your faceup Damage cards.""" "<NAME>": text: """%HUGESHIPONLY% %REBELONLY%%LINEBREAK%At the start of the Activation phase, you may discard this card to treat each friendly ship's pilot skill value as "12" until the end of the phase.""" "<NAME>": text: """%HUGESHIPONLY% %REBELONLY%%LINEBREAK%When another friendly ship at Range 1 is attacking, it may change 1 of its %HIT% results to a %CRIT%.""" "Expanded Cargo Hold": text: """<span class="card-restriction">GR-75 only.</span>%LINEBREAK%Once per round, when you would be dealt a faceup Damage card, you may draw that card from either the fore or aft Damage deck.""" "Backup Shield Generator": text: """At the end of each round, you may spend 1 energy to recover 1 shield (up to your shield value).""" "EM Emitter": text: """When you obstruct an attack, the defender rolls 3 additional defense dice (instead of 1).""" "Frequency Jammer": text: """When you perform a jam action, choose 1 enemy ship that does not have a stress token and is at Range 1 of the jammed ship. The chosen ship receives 1 stress token.""" "<NAME>": text: """%REBELONLY%%LINEBREAK%When attacking, if you have a target lock on the defender, you may spend that target lock to change all of your %FOCUS% results to %HIT% results.""" "<NAME>": text: """%REBELONLY%%LINEBREAK%At the start of the Activation phase, you may discard this card to allow all friendly ships that reveal a red maneuver to treat that maneuver as a white maneuver until the end of the phase.""" "Targeting Coordinator": text: """<strong>Energy:</strong> You may spend 1 energy to choose 1 friendly ship at Range 1-2. Acquire a target lock, then assign the blue target lock token to the chosen ship.""" "<NAME>": text: """%HUGESHIPONLY% %REBELONLY%%LINEBREAK%At the start of the Activation phase, choose 1 enemy ship at Range 1-3. You may look at that ship's chosen maneuver. If the maneuver is white, assign that ship 1 stress token.""" "Gunnery Team": text: """Once per round, when attacking with a secondary weapon, you may spend 1 energy to change 1 of your blank results to a %HIT% result.""" "Sensor Team": text: """When acquiring a target lock, you may lock onto an enemy ship at Range 1-5 instead of 1-3.""" "Engineering Team": text: """During the Activation phase, when you reveal a %STRAIGHT% maneuver, gain 1 additional energy during the "Gain Energy" step.""" "<NAME>": text: """%REBELONLY%%LINEBREAK%<strong>Action:</strong> Roll 2 defense dice. For each %FOCUS% result, assign 1 focus token to your ship. For each %EVADE% result, assign 1 evade token to your ship.""" "<NAME>": text: """%IMPERIALONLY%%LINEBREAK%At the end of the Combat phase, each enemy ship at Range 1 that does not have a stress token receives 1 stress token.""" "Fleet Officer": text: """%IMPERIALONLY%%LINEBREAK%<strong>Action:</strong> Choose up to 2 friendly ships at Range 1-2 and assign 1 focus token to each of those ships. Then receive 1 stress token.""" "Lone Wolf": text: """When attacking or defending, if there are no other friendly ships at Range 1-2, you may reroll 1 of your blank results.""" "Stay On Target": text: """When you reveal a maneuver, you may rotate your dial to another maneuver with the same speed.%LINEBREAK%Treat that maneuver as a red maneuver.""" "Dash Rendar": text: """%REBELONLY%%LINEBREAK%You may perform attacks while overlapping an obstacle.%LINEBREAK%Your attacks cannot be obstructed.""" '"Leebo"': text: """%REBELONLY%%LINEBREAK%<strong>Action:</strong> Perform a free boost action. Then receive 1 ion token.""" "Ruthlessness": text: """%IMPERIALONLY%%LINEBREAK%After you perform an attack that hits, you <strong>must</strong> choose 1 other ship at Range 1 of the defender (other than yourself). That ship suffers 1 damage.""" "Intimidation": text: """While you are touching an enemy ship, reduce that ship's agility value by 1.""" "<NAME>": text: """%IMPERIALONLY%%LINEBREAK%At the start of the Combat phase, if you have no shields and at least 1 Damage card assigned to your ship, you may perform a free evade action.""" "<NAME>": text: """%IMPERIALONLY%%LINEBREAK%When you are dealt a faceup Damage card, you may discard this Upgrade card or another %CREW% Upgrade card to flip that Damage card facedown (without resolving its effect).""" "Ion Torpedoes": text: """<strong>Attack (target lock):</strong> Spend your target lock and discard this card to perform this attack.%LINEBREAK%If this attack hits, the defender and each ship at Range 1 of it receives 1 ion token.""" "Bodyguard": text: """%SCUMONLY%%LINEBREAK%At the start of the Combat phase, you may spend a focus token to choose a friendly ship at Range 1 with higher pilot skill than you. Increase its agility value by 1 until the end of the round.""" "Calculation": text: """When attacking, you may spend a focus token to change 1 of your %FOCUS% results to a %CRIT% result.""" "Accuracy Corrector": text: """When attacking, during the "Modify Attack Dice" step, you may cancel all of your dice results. Then, you may add 2 %HIT% results to your roll.%LINEBREAK%Your dice cannot be modified again during this attack.""" "Inertial Dampeners": text: """When you reveal your maneuver, you may discard this card to instead perform a white [0%STOP%] maneuver. Then receive 1 stress token.""" "Flechette Cannon": text: """<strong>Attack:</strong> Attack 1 ship.%LINEBREAK%If this attack hits, the defender suffers 1 damage and, if the defender is not stressed, it also receives 1 stress token. Then cancel <strong>all</strong> dice results.""" '"Mangler" Cannon': text: """<strong>Attack:</strong> Attack 1 ship.%LINEBREAK%When attacking, you may change 1 of your %HIT% results to a %CRIT% result.""" "Dead Man's Switch": text: """When you are destroyed, each ship at Range 1 suffers 1 damage.""" "Feedback Array": text: """During the Combat phase, instead of performing any attacks, you may receive 1 ion token and suffer 1 damage to choose 1 enemy ship at Range 1. That ship suffers 1 damage.""" '"Hot Shot" Blaster': text: """<strong>Attack:</strong> Discard this card to attack 1 ship (even a ship outside your firing arc).""" "Greedo": text: """%SCUMONLY%%LINEBREAK%The first time you attack each round and the first time you defend each round, the first Damage card dealt is dealt faceup.""" "Salvaged Astromech": text: """When you are dealt a Damage card with the <strong>Ship</strong> trait, you may immediately discard that card (before resolving its effect).%LINEBREAK%Then, discard this Upgrade card.""" "Bomb Loadout": text: """<span class="card-restriction">Y-Wing only.</span>%LINEBREAK%Your upgrade bar gains the %BOMB% icon.""" '"Genius"': text: """If you are equipped with a bomb that can be dropped when you reveal your maneuver, you may drop the bomb <strong>after</strong> you execute your maneuver instead.""" "Unhinged Astromech": text: """You may treat all 3-speed maneuvers as green maneuvers.""" "R4-B11": text: """When attacking, if you have a target lock on the defender, you may spend the target lock to choose any or all defense dice. The defender must reroll the chosen dice.""" "Autoblaster Turret": text: """<strong>Attack:</strong> Attack 1 ship (even a ship outside your firing arc).%LINEBREAK%Your %HIT% results cannot be canceled by defense dice. The defender may cancel %CRIT% results before %HIT% results.""" "R4 Agromech": text: """When attacking, after you spend a focus token, you may acquire a target lock on the defender.""" "K4 Security Droid": text: """%SCUMONLY%%LINEBREAK%After executing a green maneuver, you may acquire a target lock.""" "Outlaw Tech": text: """%SCUMONLY%%LINEBREAK%After you execute a red maneuver, you may assign 1 focus token to your ship.""" "Advanced Targeting Computer": text: """<span class="card-restriction">TIE Advanced only.</span>%LINEBREAK%When attacking with your primary weapon, if you have a target lock on the defender, you may add 1 %CRIT% result to your roll. If you do, you cannot spend target locks during this attack.""" "Ion Cannon Battery": text: """<strong>Attack (energy):</strong> Spend 2 energy from this card to perform this attack. If this attack hits, the defender suffers 1 critical damage and receives 1 ion token. Then cancel <strong>all</strong> dice results.""" "Extra Munitions": text: """When you equip this card, place 1 ordnance token on each equipped %TORPEDO%, %MISSILE%, and %BOMB% Upgrade card. When you are instructed to discard an Upgrade card, you may discard 1 ordnance token on that card instead.""" "Cluster Mines": text: """<strong>Action:</strong> Discard this card to <strong>drop</strong> 3 cluster mine tokens.<br /><br />When a ship's base or maneuver template overlaps a cluster mine token, that token <strong>detonates</strong>.<br /><br /><strong>Cluster Mines Tokens:</strong> When one of these bomb tokens detonates, the ship that moved through or overlapped this token rolls 2 attack dice and suffers all damage (%HIT%) rolled. Then discard this token.""" "<NAME>": text: """At the start of the Combat phase, you may discard this card and receive 1 stress token. If you do, until the end of the round, when attacking or defending, you may change all of your %FOCUS% results to %HIT% or %EVADE% results.""" "<NAME>": text: """%HUGESHIPONLY% %IMPERIALONLY%%LINEBREAK%At the start of the Combat phase, you may choose another ship at Range 1-4. Either remove 1 focus token from the chosen ship or assign 1 focus token to that ship.""" "<NAME>": text: """%HUGESHIPONLY% %IMPERIALONLY%%LINEBREAK%If you overlap an obstacle during the Activation phase, do not suffer 1 faceup damage card. Instead, roll 1 attack die. On a %HIT% or %CRIT% result, suffer 1 damage.""" "<NAME>": text: """%HUGESHIPONLY% %IMPERIALONLY%%LINEBREAK%<strong>Energy:</strong> You may remove up to 3 shields from your ship. For each shield removed, gain 1 energy.""" "<NAME>": text: """%IMPERIALONLY%%LINEBREAK%Once per round, you may change a friendly ship's die result to any other die result. That die result cannot be modified again.""" "Bossk": text: """%SCUMONLY%%LINEBREAK%After you perform an attack that does not hit, if you are not stressed, you <strong>must</strong> receive 1 stress token. Then assign 1 focus token to your ship and acquire a target lock on the defender.""" "Lightning Reflexes": text: """%SMALLSHIPONLY%%LINEBREAK%After you execute a white or green maneuver on your dial, you may discard this card to rotate your ship 180&deg;. Then receive 1 stress token <strong>after</strong> the "Check Pilot Stress" step.""" "Twin Laser Turret": text: """<strong>Attack:</strong> Perform this attack <strong>twice</strong> (even against a ship outside your firing arc).<br /><br />Each time this attack hits, the defender suffers 1 damage. Then cancel <strong>all</strong> dice results.""" "Plasma Torpedoes": text: """<strong>Attack (target lock):</strong> Spend your target lock and discard this card to perform this attack.<br /><br />If this attack hits, after dealing damage, remove 1 shield token from the defender.""" "Ion Bombs": text: """When you reveal your maneuver dial, you may discard this card to <strong>drop</strong> 1 ion bomb token.<br /><br />This token <strong>detonates</strong> at the end of the Activation phase.<br /><br /><strong>Ion Bombs Token:</strong> When this bomb token detonates, each ship at Range 1 of the token receives 2 ion tokens. Then discard this token.""" "Conner Net": text: """<strong>Action:</strong> Discard this card to <strong>drop</strong> 1 Conner Net token.<br /><br />When a ship's base or maneuver template overlaps this token, this token <strong>detonates</strong>.<br /><br /><strong>Conner Net Token:</strong> When this bomb token detonates, the ship that moved through or overlapped this token suffers 1 damage, receives 2 ion tokens, and skips its "Perform Action" step. Then discard this token.""" "Bombardier": text: """When dropping a bomb, you may use the (%STRAIGHT% 2) template instead of the (%STRAIGHT% 1) template.""" 'Crack Shot': text: '''When attacking a ship inside your firing arc, you may discard this card to cancel 1 of the defender's %EVADE% results.''' "Advanced Homing Missiles": text: """<strong>Attack (target lock):</strong> Discard this card to perform this attack.%LINEBREAK%If this attack hits, deal 1 faceup Damage card to the defender. Then cancel <strong>all</strong> dice results.""" '<NAME>': text: '''%IMPERIALONLY%%LINEBREAK%At the start of the first round, choose 1 enemy small or large ship. When attacking or defending against that ship, you may change 1 of your %FOCUS% results to a %HIT% or %EVADE% result.''' 'XX-23 S-Thread Tracers': text: """<strong>Attack (focus):</strong> Discard this card to perform this attack. If this attack hits, each friendly ship at Range 1-2 of you may acquire a target lock on the defender. Then cancel <strong>all</strong> dice results.""" "Tractor Beam": text: """<strong>Attack:</strong> Attack 1 ship.%LINEBREAK%If this attack hits, the defender receives 1 tractor beam token. Then cancel <strong>all</strong> dice results.""" "Cloaking Device": text: """%SMALLSHIPONLY%%LINEBREAK%<strong>Action:</strong> Perform a free cloak action.%LINEBREAK%At the end of each round, if you are cloaked, roll 1 attack die. On a %FOCUS% result, discard this card, then decloak or discard your cloak token.""" modification_translations = "Stealth Device": text: """Increase your agility value by 1. If you are hit by an attack, discard this card.""" "Shield Upgrade": text: """Increase your shield value by 1.""" "Engine Upgrade": text: """Your action bar gains the %BOOST% action icon.""" "Anti-Pursuit Lasers": text: """%LARGESHIPONLY%%LINEBREAK%After an enemy ship executes a maneuver that causes it to overlap your ship, roll 1 attack die. On a %HIT% or %CRIT% result, the enemy ship suffers 1 damage.""" "Targeting Computer": text: """Your action bar gains the %TARGETLOCK% action icon.""" "Hull Upgrade": text: """Increase your hull value by 1.""" "Munitions Failsafe": text: """When attacking with a secondary weapon that instructs you to discard it to perform the attack, do not discard it unless the attack hits.""" "Stygium Particle Accelerator": text: """When you either decloak or perform a cloak action, you may perform a free evade action.""" "Advanced Cloaking Device": text: """<span class="card-restriction">TIE Phantom only.</span>%LINEBREAK%After you perform an attack, you may perform a free cloak action.""" "Combat Retrofit": text: """<span class="card-restriction">GR-75 only.</span>%LINEBREAK%Increase your hull value by 2 and your shield value by 1.""" "B-Wing/E2": text: """<span class="card-restriction">B-Wing only.</span>%LINEBREAK%Your upgrade bar gains the %CREW% upgrade icon.""" "Countermeasures": text: """%LARGESHIPONLY%%LINEBREAK%At the start of the Combat phase, you may discard this card to increase your agility value by 1 until the end of the round. Then you may remove 1 enemy target lock from your ship.""" "Experimental Interface": text: """Once per round, after you perform an action, you may perform 1 free action from an equipped Upgrade card with the "<strong>Action:</strong>" header. Then receive 1 stress token.""" "Tactical Jammer": text: """%LARGESHIPONLY%%LINEBREAK%Your ship can obstruct enemy attacks.""" "Autothrusters": text: """When defending, if you are beyond Range 2 or outside the attacker's firing arc, you may change 1 of your blank results to a %EVADE% result. You can equip this card only if you have the %BOOST% action icon.""" "Advanced SLAM": text: """After performing a SLAM action, if you did not overlap an obstacle or another ship, you may perform a free action.""" "Twin Ion Engine Mk. II": text: """You may treat all bank maneuvers (%BANKLEFT% and %BANKRIGHT%) as green maneuvers.""" "Maneuvering Fins": text: """When you reveal a turn maneuver (%TURNLEFT% or %TURNRIGHT%), you may rotate your dial to the corresponding bank maneuver (%BANKLEFT% or %BANKRIGHT%) of the same speed.""" "Ion Projector": text: """%LARGESHIPONLY%%LINEBREAK%After an enemy ship executes a maneuver that causes it to overlap your ship, roll 1 attack die. On a %HIT% or %CRIT% result, the enemy ship receives 1 ion token.""" title_translations = "Slave I": text: """<span class="card-restriction">Firespray-31 only.</span>%LINEBREAK%Your upgrade bar gains the %TORPEDO% upgrade icon.""" "Millennium Falcon": text: """<span class="card-restriction">YT-1300 only.</span>%LINEBREAK%Your action bar gains the %EVADE% action icon.""" "Moldy Crow": text: """<span class="card-restriction">HWK-290 only.</span>%LINEBREAK%During the End phase, do not remove unused focus tokens from your ship.""" "ST-321": text: """<span class="card-restriction"><em>Lambda</em>-class Shuttle only.</span>%LINEBREAK%When acquiring a target lock, you may lock onto any enemy ship in the play area.""" "Royal Guard TIE": text: """<span class="card-restriction">TIE Interceptor only.</span>%LINEBREAK%You may equip up to 2 different Modification upgrades (instead of 1).%LINEBREAK%You cannot equip this card if your pilot skill value is "4" or lower.""" "Dod<NAME>'s Pride": text: """<span class="card-restriction">CR90 fore section only.</span>%LINEBREAK%When you perform a coordinate action, you may choose 2 friendly ships (instead of 1). Those ships may each perform 1 free action.""" "A-Wing Test Pilot": text: """<span class="card-restriction">A-Wing only.</span>%LINEBREAK%Your upgrade bar gains 1 %ELITE% upgrade icon.%LINEBREAK%You cannot equip 2 of the same %ELITE% Upgrade cards. You cannot equip this if your pilot skill value is "1" or lower.""" "Tantive IV": text: """<span class="card-restriction">CR90 fore section only.</span>%LINEBREAK%Your fore section upgrade bar gains 1 additional %CREW% and 1 additional %TEAM% upgrade icon.""" "Bright Hope": text: """<span class="card-restriction">GR-75 only.</span>%LINEBREAK%A reinforce action assigned to your fore section adds 2 %EVADE% results (instead of 1).""" "Quantum Storm": text: """<span class="card-restriction">GR-75 only.</span>%LINEBREAK%At the start of the End phase, if you have 1 or fewer energy tokens, gain 1 energy token.""" "Dutyfree": text: """<span class="card-restriction">GR-75 only.</span>%LINEBREAK%When performing a jam action, you may choose an enemy ship at Range 1-3 (instead of at Range 1-2).""" "Jaina's Light": text: """<span class="card-restriction">CR90 fore section only.</span>%LINEBREAK%When defending, once per attack, if you are dealt a faceup Damage card, you may discard it and draw another faceup Damage card.""" "Outrider": text: """<span class="card-restriction">YT-2400 only.</span>%LINEBREAK%While you have a %CANNON% Upgrade card equipped, you <strong>cannot</strong> perform primary weapon attacks and you may perform %CANNON% secondary weapon attacks against ships outside your firing arc.""" "Dauntless": text: """<span class="card-restriction">VT-49 Decimator only.</span>%LINEBREAK%After you execute a maneuver that causes you to overlap another ship, you may perform 1 free action. Then receive 1 stress token.""" "<NAME>": text: """<span class="card-restriction">StarViper only.</span>%LINEBREAK%Your upgrade bar gains the %SYSTEM% and %ILLICIT% upgrade icons.%LINEBREAK%You cannot equip this card if your pilot skill value is "3" or lower.""" '"Heavy Scyk" Interceptor (Cannon)': text: """<span class="card-restriction">M3-A Interceptor only.</span>%LINEBREAK%Your upgrade bar gains the %CANNON%, %TORPEDO%, or %MISSILE% upgrade icon.""" '"Heavy Scyk" Interceptor (Torpedo)': text: """<span class="card-restriction">M3-A Interceptor only.</span>%LINEBREAK%Your upgrade bar gains the %CANNON%, %TORPEDO%, or %MISSILE% upgrade icon.""" '"Heavy Scyk" Interceptor (Missile)': text: """<span class="card-restriction">M3-A Interceptor only.</span>%LINEBREAK%Your upgrade bar gains the %CANNON%, %TORPEDO%, or %MISSILE% upgrade icon.""" "IG-2000": text: """<span class="card-restriction">Aggressor only.</span>%LINEBREAK%You have the pilot ability of each other friendly ship with the <em>IG-2000</em> Upgrade card (in addition to your own pilot ability).""" "BTL-A4 Y-Wing": text: """<span class="card-restriction">Y-Wing only.</span>%LINEBREAK%You cannot attack ships outside your firing arc. After you perform a primary weapon attack, you may immediately perform an attack with a %TURRET% secondary weapon.""" "Andrasta": text: """Your upgrade bar gains two additional %BOMB% upgrade icons.""" "TIE/x1": text: """<span class="card-restriction">TIE Advanced only.</span>%LINEBREAK%Your upgrade bar gains the %SYSTEM% upgrade icon.%LINEBREAK%If you equip a %SYSTEM% upgrade, its squad point cost is reduced by 4 (to a minimum of 0).""" "<NAME>": text: """<span class="card-restriction">YV-666 only.</span>%LINEBREAK%After you are destroyed, before you are removed from the play area, you may <strong>deploy</strong> the <em>Nashtah Pup</em> ship.%LINEBREAK%It cannot attack this round.""" "Ghost": text: """<span class="card-restriction">VCX-100 only.</span>%LINEBREAK%Equip the <em>Phantom</em> title card to a friendly Attack Shuttle and dock it to this ship.%LINEBREAK%After you execute a maneuver, you may deploy it from your rear guides.""" "Phantom": text: """While you are docked, the <em>Ghost</em> can perform primary weapon attacks from its special firing arc, and, at the end of the Combat phase, it may perform an additional attack with an equipped %TURRET%. If it performs this attack, it cannot attack again this round.""" "TIE/v1": text: """<span class="card-restriction">TIE Advanced Prototype only.</span>%LINEBREAK%After you acquire a target lock, you may perform a free evade action.""" "<NAME>": text: """<span class="card-restriction">G-1A starfighter only.</span>%LINEBREAK%Your upgrade bar gains the %BARRELROLL% Upgrade icon.%LINEBREAK%You <strong>must</strong> equip 1 "Tractor Beam" Upgrade card (paying its squad point cost as normal).""" "<NAME>": text: """<span class="card-restriction">JumpMaster 5000 only.</span>%LINEBREAK%Increase your primary weapon value by 1.""" exportObj.setupCardData basic_cards, pilot_translations, upgrade_translations, modification_translations, title_translations
true
exportObj = exports ? this exportObj.codeToLanguage ?= {} exportObj.codeToLanguage.en = 'English' exportObj.translations ?= {} # This is here mostly as a template for other languages. exportObj.translations.English = action: "Barrel Roll": "Barrel Roll" "Boost": "Boost" "Evade": "Evade" "Focus": "Focus" "Target Lock": "Target Lock" "Recover": "Recover" "Reinforce": "Reinforce" "Jam": "Jam" "Coordinate": "Coordinate" "Cloak": "Cloak" "SLAM": "SLAM" slot: "Astromech": "Astromech" "Bomb": "Bomb" "Cannon": "Cannon" "Crew": "Crew" "Elite": "Elite" "Missile": "Missile" "System": "System" "Torpedo": "Torpedo" "Turret": "Turret" "Cargo": "Cargo" "Hardpoint": "Hardpoint" "Team": "Team" "Illicit": "Illicit" "Salvaged Astromech": "Salvaged Astromech" sources: # needed? "Core": "Core" "A-Wing Expansion Pack": "A-Wing Expansion Pack" "B-Wing Expansion Pack": "B-Wing Expansion Pack" "X-Wing Expansion Pack": "X-Wing Expansion Pack" "Y-Wing Expansion Pack": "Y-Wing Expansion Pack" "Millennium Falcon Expansion Pack": "Millennium Falcon Expansion Pack" "HWK-290 Expansion Pack": "HWK-290 Expansion Pack" "TIE Fighter Expansion Pack": "TIE Fighter Expansion Pack" "TIE Interceptor Expansion Pack": "TIE Interceptor Expansion Pack" "TIE Bomber Expansion Pack": "TIE Bomber Expansion Pack" "TIE Advanced Expansion Pack": "TIE Advanced Expansion Pack" "Lambda-Class Shuttle Expansion Pack": "Lambda-Class Shuttle Expansion Pack" "Slave I Expansion Pack": "Slave I Expansion Pack" "Imperial Aces Expansion Pack": "Imperial Aces Expansion Pack" "Rebel Transport Expansion Pack": "Rebel Transport Expansion Pack" "Z-95 Headhunter Expansion Pack": "Z-95 Headhunter Expansion Pack" "TIE Defender Expansion Pack": "TIE Defender Expansion Pack" "E-Wing Expansion Pack": "E-Wing Expansion Pack" "TIE Phantom Expansion Pack": "TIE Phantom Expansion Pack" "Tantive IV Expansion Pack": "Tantive IV Expansion Pack" "Rebel Aces Expansion Pack": "Rebel Aces Expansion Pack" "YT-2400 Freighter Expansion Pack": "YT-2400 Freighter Expansion Pack" "VT-49 Decimator Expansion Pack": "VT-49 Decimator Expansion Pack" "StarViper Expansion Pack": "StarViper Expansion Pack" "M3-A Interceptor Expansion Pack": "M3-A Interceptor Expansion Pack" "IG-2000 Expansion Pack": "IG-2000 Expansion Pack" "Most Wanted Expansion Pack": "Most Wanted Expansion Pack" "Imperial Raider Expansion Pack": "Imperial Raider Expansion Pack" "Hound's Tooth Expansion Pack": "Hound's Tooth Expansion Pack" "Kihraxz Fighter Expansion Pack": "Kihraxz Fighter Expansion Pack" "K-Wing Expansion Pack": "K-Wing Expansion Pack" "TIE Punisher Expansion Pack": "TIE Punisher Expansion Pack" ui: shipSelectorPlaceholder: "Select a ship" pilotSelectorPlaceholder: "Select a pilot" upgradePlaceholder: (translator, language, slot) -> "No #{translator language, 'slot', slot} Upgrade" modificationPlaceholder: "No Modification" titlePlaceholder: "No Title" upgradeHeader: (translator, language, slot) -> "#{translator language, 'slot', slot} Upgrade" unreleased: "unreleased" epic: "epic" limited: "limited" byCSSSelector: '.xwing-card-browser .translate.sort-cards-by': 'Sort cards by' '.xwing-card-browser option[value="name"]': 'Name' '.xwing-card-browser option[value="source"]': 'Source' '.xwing-card-browser option[value="type-by-points"]': 'Type (by Points)' '.xwing-card-browser option[value="type-by-name"]': 'Type (by Name)' '.xwing-card-browser .translate.select-a-card': 'Select a card from the list at the left.' # Info well '.info-well .info-ship td.info-header': 'Ship' '.info-well .info-skill td.info-header': 'Skill' '.info-well .info-actions td.info-header': 'Actions' '.info-well .info-upgrades td.info-header': 'Upgrades' '.info-well .info-range td.info-header': 'Range' # Squadron edit buttons '.clear-squad' : 'New Squad' '.save-list' : 'Save' '.save-list-as' : 'Save as…' '.delete-list' : 'Delete' '.backend-list-my-squads' : 'Load squad' '.view-as-text' : '<span class="hidden-phone"><i class="icon-print"></i>&nbsp;Print/View as </span>Text' '.randomize' : 'Random!' '.randomize-options' : 'Randomizer options…' # Print/View modal '.bbcode-list' : 'Copy the BBCode below and paste it into your forum post.<textarea></textarea>' '.vertical-space-checkbox' : """Add space for damage/upgrade cards when printing <input type="checkbox" class="toggle-vertical-space" />""" '.color-print-checkbox' : """Print color <input type="checkbox" class="toggle-color-print" />""" '.print-list' : '<i class="icon-print"></i>&nbsp;Print' # Randomizer options '.do-randomize' : 'Randomize!' # Top tab bar '#empireTab' : 'Galactic Empire' '#rebelTab' : 'Rebel Alliance' '#scumTab' : 'Scum and Villainy' '#browserTab' : 'Card Browser' '#aboutTab' : 'About' singular: 'pilots': 'Pilot' 'modifications': 'Modification' 'titles': 'Title' types: 'Pilot': 'Pilot' 'Modification': 'Modification' 'Title': 'Title' exportObj.cardLoaders ?= {} exportObj.cardLoaders.English = () -> exportObj.cardLanguage = 'English' # Assumes cards-common has been loaded basic_cards = exportObj.basicCardData() exportObj.canonicalizeShipNames basic_cards # English names are loaded by default, so no update is needed exportObj.ships = basic_cards.ships # Names don't need updating, but text needs to be set pilot_translations = "Wedge Antilles": text: """When attacking, reduce the defender's agility value by 1 (to a minimum of "0").""" "PI:NAME:<NAME>END_PI": text: """After spending a focus token, you may place that token on any other friendly ship at Range 1-2 (instead of discarding it).""" "Biggs Darklighter": text: """Other friendly ships at Range 1 cannot be targeted by attacks if the attacker could target you instead.""" "LuPI:NAME:<NAME>END_PI Skywalker": text: """When defending, you may change 1 of your %FOCUS% results to a %EVADE% result.""" '"Dutch" Vander': text: """After acquiring a target lock, choose another friendly ship at Range 1-2. The chosen ship may immediately acquire a target lock.""" "PI:NAME:<NAME>END_PI": text: """When attacking at Range 2-3, you may reroll any of your blank results.""" '"WPI:NAME:<NAME>END_PI"': text: """When attacking at Range 1, you may change 1 of your %HIT% results to a %CRIT% result.""" '"Night Beast"': text: """After executing a green maneuver, you may perform a free focus action.""" '"BackPI:NAME:<NAME>END_PI"': text: """When attacking from outside the defender's firing arc, roll 1 additional attack die.""" '"Dark PI:NAME:<NAME>END_PI"': text: """When defending, ships attacking you cannot spend focus tokens or reroll attack dice.""" '"PI:NAME:<NAME>END_PI"': text: """When attacking at Range 1, roll 1 additional attack die.""" '"HowPI:NAME:<NAME>END_PI"': text: """When another friendly ship at Range 1 is attacking with its primary weapon, it may reroll 1 attack die.""" "PI:NAME:<NAME>END_PI": text: """When your attack deals a faceup Damage card to the defender, instead draw 3 Damage cards, choose 1 to deal, and discard the others.""" "PI:NAME:<NAME>END_PI": text: """During your "Perform Action" step, you may perform 2 actions.""" "\"PI:NAME:<NAME>END_PI\"": text: """When the number of Damage cards assigned to you equals or exceeds your hull value, you are not destroyed until the end of the Combat phase.""" "PI:NAME:<NAME>END_PI": text: """After you perform an attack, you may perform a free boost or barrel roll action.""" "PI:NAME:<NAME>END_PI": text: """When you receive a stress token, you may assign 1 focus token to your ship.""" "PI:NAME:<NAME>END_PI": text: """You may perform actions even while you have stress tokens.""" "PI:NAME:<NAME>END_PI": text: """You may declare an enemy ship inside your firing arc that you are touching as the target of your attack.""" "PI:NAME:<NAME>END_PI": text: """When you are dealt a faceup Damage card, immediately flip it facedown (without resolving its ability).""" "PI:NAME:<NAME>END_PI": text: """After you execute a green maneuver, choose 1 other friendly ship at Range 1. That ship may perform 1 free action shown on its action bar.""" "PI:NAME:<NAME>END_PI": text: """When attacking, you may reroll all of your dice. If you choose to do so, you must reroll as many of your dice as possible.""" "PI:NAME:<NAME>END_PI": text: """When attacking, the defender receives 1 stress token if he cancels at least 1 %CRIT% result.""" "PI:NAME:<NAME>END_PI": text: """When you reveal a bank maneuver (%BANKLEFT% or %BANKRIGHT%), you may rotate your dial to the other bank maneuver of the same speed.""" "PI:NAME:<NAME>END_PI": text: """When attacking with a secondary weapon, you may reroll 1 attack die.""" "PI:NAME:<NAME>END_PI": text: """When attacking, 1 of your %CRIT% results cannot be canceled by defense dice.""" "PI:NAME:<NAME>END_PI": text: """When attacking or defending, if you have at least 1 stress token, you may reroll 1 of your dice.""" "PI:NAME:<NAME>END_PI": text: '''At the start of the Combat phase, choose 1 other friendly ship at Range 1-3. Until the end of the phase, treat that ship's pilot skill value as "12."''' "PI:NAME:<NAME>END_PI": text: """At the start of the Combat phase, you may assign 1 of your focus tokens to another friendly ship at Range 1-3.""" "PI:NAME:<NAME>END_PI": text: """When another friendly ship at Range 1-3 is attacking, if you have no stress tokens, you may receive 1 stress token to allow that ship to roll 1 additional attack die.""" "PI:NAME:<NAME>END_PI": text: """When another friendly ship at Range 1 attacks with a secondary weapon, it may reroll up to 2 attack dice.""" "PI:NAME:<NAME>END_PI": text: """When attacking with a secondary weapon, you may increase or decrease the weapon range by 1 to a limit of Range 1-3.""" "PI:NAME:<NAME>END_PI": text: """When an enemy ship acquires a target lock, it must lock onto your ship if able.""" "PI:NAME:<NAME>END_PI": text: """At the start of the Combat phase, you may assign 1 of your blue target lock tokens to a friendly ship at Range 1 if it does not have a blue target lock token.""" "PI:NAME:<NAME>END_PI": text: """When another friendly ship at Range 1-2 would receive a stress token, if you have 2 or fewer stress tokens, you may receive that token instead.""" "PI:NAME:<NAME>END_PI": text: """When performing a barrel roll action, you may receive 1 stress token to use the (%BANKLEFT% 1) or (%BANKRIGHT% 1) template instead of the (%STRAIGHT% 1) template.""" "PI:NAME:<NAME>END_PI": text: """When you reveal a %UTURN% maneuver, you may treat the speed of that maneuver as "1," "3," or "5".""" "PI:NAME:<NAME>END_PI": text: """When attacking at Range 2-3, you may spend 1 evade token to add 1 %HIT% result to your roll.""" "PI:NAME:<NAME>END_PI": text: """Enemy ships at Range 1 cannot perform focus or evade actions and cannot spend focus or evade tokens.""" "PI:NAME:<NAME>END_PI": text: """When attacking, the defender is hit by your attack, even if he does not suffer any damage.""" "PI:NAME:<NAME>END_PI": text: """After you perform an attack, you may choose another friendly ship at Range 1. That ship may perform 1 free action.""" "PI:NAME:<NAME>END_PI": text: """When attacking, immediately after you roll attack dice, you may acquire a target lock on the defender if it already has a red target lock token.""" "PI:NAME:<NAME>END_PI": text: """After you perform an attack that deals at least 1 Damage card to the defender, you may spend a focus token to flip those cards faceup.""" "PI:NAME:<NAME>END_PI": text: """When an enemy ship inside your firing arc at Range 1-3 is defending, the attacker may change 1 of its %HIT% results to a %CRIT% result.""" "PI:NAME:<NAME>END_PI": text: """At the start of the End phase, you may perform one attack. You cannot attack during the next round.""" '"PI:NAME:<NAME>END_PI"': text: """When you decloak, you must use the (%BANKLEFT% 2) or (%BANKRIGHT% 2) template instead of the (%STRAIGHT% 2) template.""" '"PI:NAME:<NAME>END_PIisper"': text: """After you perform an attack that hits, you may assign 1 focus to your ship.""" "PI:NAME:<NAME>END_PI": text: """After you perform an attack, you may remove 1 focus, evade, or blue target lock token from the defender.""" "PI:NAME:<NAME>END_PI": text: """When you receive a stress token, you may remove it and roll 1 attack die. On a %HIT% result, deal 1 facedown Damage card to this ship.""" '"PI:NAME:<NAME>END_PI" PI:NAME:<NAME>END_PI': text: """When you acquire or spend a target lock, you may remove 1 stress token from your ship.""" "PI:NAME:<NAME>END_PI": text: """When an enemy ship declares you as the target of an attack, you may acquire a target lock on that ship.""" "PI:NAME:<NAME>END_PI": text: """After you perform a focus action or are assigned a focus token, you may perform a free boost or barrel roll action.""" "PI:NAME:<NAME>END_PI": text: """While you are at Range 1 of at least 1 enemy ship, increase your agility value by 1.""" "PI:NAME:<NAME>END_PI": text: """When attacking, you may remove 1 stress token to change all of your %FOCUS% results to %HIT%results.""" "PI:NAME:<NAME>END_PI": text: """You can perform %TORPEDO% secondary weapon attacks against enemy ships outside your firing arc.""" "CR90 Corvette (Fore)": text: """When attacking with your primary weapon, you may spend 1 energy to roll 1 additional attack die.""" # "CR90 Corvette (Crippled Aft)": # text: """You cannot choose or execute (%STRAIGHT% 4), (%BANKLEFT% 2), or (%BANKRIGHT% 2) maneuvers.""" "PI:NAME:<NAME>END_PI": text: """You may ignore obstacles during the Activation phase and when performing actions.""" '"PI:NAME:<NAME>END_PI"': text: """When you are dealt a faceup Damage card, draw 1 additional Damage card, choose 1 to resolve, and discard the other.""" "PI:NAME:<NAME>END_PI": text: """When performing a primary weapon attack against a stressed ship, roll 1 additional attack die.""" "PI:NAME:<NAME>END_PI": text: """When attacking at Range 1-2, you may change 1 of your %FOCUS% results to a %CRIT% result.""" "PI:NAME:<NAME>END_PI": text: """If you have no shields and at least 1 Damage card assigned to you, increase your agility value by 1.""" "PI:NAME:<NAME>END_PI": text: """After executing a maneuver, each enemy ship you are touching suffers 1 damage.""" "PI:NAME:<NAME>END_PI": text: """When defending, a friendly ship at Range 1 may suffer 1 uncanceled %HIT% or %CRIT% result instead of you.""" "PI:NAME:<NAME>END_PI": text: """At the start of the Combat phase, if you are at Range 1 of an enemy ship, you may assign 1 focus token to your ship.""" "PI:NAME:<NAME>END_PI": text: """When another friendly ship at Range 1 is defending, it may reroll 1 defense die.""" "PI:NAME:<NAME>END_PI": text: """After you defend against an attack, if the attack did not hit, you may assign 1 evade token to your ship.""" "IG-88A": text: """After you perform an attack that destroys the defender, you may recover 1 shield.""" "IG-88B": text: """Once per round, after you perform an attack that does not hit, you may perform an attack with an equipped %CANNON% secondary weapon.""" "IG-88C": text: """After you perform a boost action, you may perform a free evade action.""" "IG-88D": text: """You may execute the (%SLOOPLEFT% 3) or (%SLOOPRIGHT% 3) maneuver using the corresponding (%TURNLEFT% 3) or (%TURNRIGHT% 3) template.""" "PI:NAME:<NAME>END_PI (Scum)": text: """When attacking or defending, you may reroll 1 of your dice for each enemy ship at Range 1.""" "PI:NAME:<NAME>END_PI (Scum)": text: """When attacking a ship inside your auxiliary firing arc, roll 1 additional attack die.""" "PI:NAME:<NAME>END_PI": text: """When dropping a bomb, you may use the [%TURNLEFT% 3], [%STRAIGHT% 3], or [%TURNRIGHT% 3] template instead of the [%STRAIGHT% 1] template.""" "PI:NAME:<NAME>END_PI": text: """When attacking a ship outside your firing arc, roll 1 additional attack die.""" "PI:NAME:<NAME>END_PI": text: """After you spend a target lock, you may receive 1 stress token to acquire a target lock.""" "PI:NAME:<NAME>END_PI": text: """When an enemy ship at Range 1-3 receives at least 1 ion token, if you are not stressed, you may receive 1 stress token to cause that ship to suffer 1 damage.""" "PI:NAME:<NAME>END_PI": text: """At the start of the Combat phase, you may remove 1 focus or evade token from an enemy ship at Range 1-2 and assign it to yourself.""" "PI:NAME:<NAME>END_PI": text: """At the end of the Activation phase, choose 1 enemy ship at Range 1-2. Until the end of the Combat phase, treat that ship's pilot skill value as "0".""" "PI:NAME:<NAME>END_PI": text: """When attacking, if there are no other friendly ships at Range 1-2, roll 1 additional attack die.""" "PI:NAME:<NAME>END_PI": text: """At the start of the Combat phase, you may remove 1 focus or evade token from another friendly ship at Range 1-2 and assign it to yourself.""" "PI:NAME:<NAME>END_PI": text: """At the start of the Combat phase, you may acquire a target lock on an enemy ship at Range 1.""" "Raider-class Corvette (Fore)": text: """Once per round, after you perform a primary weapon attack, you may spend 2 energy to perform another primary weapon attack.""" "BossPI:NAME:<NAME>END_PI": text: """When you perform an attack that hits, before dealing damage, you may cancel 1 of your %CRIT% results to add 2 %HIT% results.""" "PI:NAME:<NAME>END_PI": text: """When attacking or defending, double the effect of your range combat bonuses.""" "PI:NAME:<NAME>END_PI": text: """Once per round when attacking, you may either spend 1 shield to roll 1 additional attack die <strong>or</strong> roll 1 fewer attack die to recover 1 shield.""" '"PI:NAME:<NAME>END_PI"': text: """You may maintain 2 target locks on the same ship. When you acquire a target lock, you may acquire a second lock on that ship.""" '"PI:NAME:<NAME>END_PI"': text: """When dropping a bomb, you may use the front guides of your ship. After dropping a bomb, you may perform a free barrel roll action.""" "Juno Eclipse": text: """When you reveal your maneuver, you may increase or decrease its speed by 1 (to a minimum of 1).""" "PI:NAME:<NAME>END_PI": text: """Enemy ships at Range 1 cannot add their range combat bonus when attacking.""" "PI:NAME:<NAME>END_PI": text: """At the start of the End phase, you may spend a target lock you have on an enemy ship to flip 1 random facedown Damage card assigned to it faceup.""" "PI:NAME:<NAME>END_PI": text: """When a friendly ship declares an attack, you may spend a target lock you have on the defender to reduce its agility by 1 for that attack.""" "PI:NAME:<NAME>END_PI": text: """When defending, if the attacker is inside your firing arc, roll 1 additional defense die.""" "PI:NAME:<NAME>END_PI": text: """When another friendly ship at Range 1-2 is attacking, it may treat your focus tokens as its own.""" "PI:NAME:<NAME>END_PI": text: """You can perform %CANNON% secondary attacks against ships inside your auxiliary firing arc.""" 'PI:NAME:<NAME>END_PIanti-class CPI:NAME:<NAME>END_PIiser': text: """After you execute a maneuver, you may deploy up to 2 attached ships.""" '"PI:NAME:<NAME>END_PI"': text: """When attacking a defender that has 1 or more Damage cards, roll 1 additional attack die.""" "PI:NAME:<NAME>END_PI InPI:NAME:<NAME>END_PI": text: """When attacking with your primary weapon at Range 2-3, treat the range of the attack as Range 1.""" "PI:NAME:<NAME>END_PI": text: """When attacking, you may roll 1 additional attack die. If you do, the defender rolls 1 additional defense die.""" "Dengar": text: """Once per round after defending, if the attacker is inside your firing arc, you may perform an attack against the that ship.""" upgrade_translations = "Ion Cannon Turret": text: """<strong>Attack:</strong> Attack 1 ship (even a ship outside your firing arc).%LINEBREAK%If this attack hits the target ship, the ship suffers 1 damage and receives 1 ion token. Then cancel all dice results.""" "ProPI:NAME:<NAME>END_PI": text: """<strong>Attack (target lock):</strong> Spend your target lock and discard this card to perform this attack.%LINEBREAK%You may change 1 of your %FOCUS% results to a %CRIT% result.""" "R2 Astromech": text: """You may treat all 1- and 2-speed maneuvers as green maneuvers.""" "R2-D2": text: """After executing a green maneuver, you may recover 1 shield (up to your shield value).""" "R2-F2": text: """<strong>Action:</strong> Increase your agility value by 1 until the end of this game round.""" "R5-D8": text: """<strong>Action:</strong> Roll 1 defense die.%LINEBREAK%On a %EVADE% or %FOCUS% result, discard 1 of your facedown Damage cards.""" "R5-K6": text: """After spending your target lock, roll 1 defense die.%LINEBREAK%On a %EVADE% result, immediately acquire a target lock on that same ship. You cannot spend this target lock during this attack.""" "R5 Astromech": text: """During the End phase, you may choose 1 of your faceup Damage cards with the Ship trait and flip it facedown.""" "Determination": text: """When you are dealt a faceup Damage card with the Pilot trait, discard it immediately without resolving its effect.""" "Swarm Tactics": text: """At the start of the Combat phase, you may choose 1 friendly ship at Range 1.%LINEBREAK%Until the end of this phase, treat the chosen ship as if its pilot skill were equal to your pilot skill.""" "Squad Leader": text: """<strong>Action:</strong> Choose 1 ship at Range 1-2 that has a lower pilot skill than you.%LINEBREAK%The chosen ship may immediately perform 1 free action.""" "Expert Handling": text: """<strong>Action:</strong> Perform a free barrel roll action. If you do not have the %BARRELROLL% action icon, receive 1 stress token.%LINEBREAK%You may then remove 1 enemy target lock from your ship.""" "Marksmanship": text: """<strong>Action:</strong> When attacking this round, you may change 1 of your %FOCUS% results to a %CRIT% result and all of your other %FOCUS% results to %HIT% results.""" "Concussion Missiles": text: """<strong>Attack (target lock):</strong> Spend your target lock and discard this card to perform this attack.%LINEBREAK%You may change 1 of your blank results to a %HIT% result.""" "Cluster Missiles": text: """<strong>Attack (target lock):</strong> Spend your target lock and discard this card to perform this attack twice.""" "Daredevil": text: """<strong>Action:</strong> Execute a white (%TURNLEFT% 1) or (%TURNRIGHT% 1) maneuver. Then, receive 1 stress token.%LINEBREAK%Then, if you do not have the %BOOST% action icon, roll 2 attack dice. Suffer any damage (%HIT%) and any critical damage (%CRIT%) rolled.""" "Elusiveness": text: """When defending, you may receive 1 stress token to choose 1 attack die. The attacker must reroll that die.%LINEBREAK%If you have at least 1 stress token, you cannot use this ability.""" "Homing Missiles": text: """<strong>Attack (target lock):</strong> Discard this card to perform this attack.%LINEBREAK%The defender cannot spend evade tokens during this attack.""" "Push the Limit": text: """Once per round, after you perform an action, you may perform 1 free action shown in your action bar.%LINEBREAK%Then receive 1 stress token.""" "Deadeye": text: """You may treat the <strong>Attack (target lock):</strong> header as <strong>Attack (focus):</strong>.%LINEBREAK%When an attack instructs you to spend a target lock, you may spend a focus token instead.""" "Expose": text: """<strong>Action:</strong> Until the end of the round, increase your primary weapon value by 1 and decrease your agility value by 1.""" "Gunner": text: """After you perform an attack that does not hit, you may immediately perform a primary weapon attack. You cannot perform another attack this round.""" "Ion Cannon": text: """<strong>Attack:</strong> Attack 1 ship.%LINEBREAK%If this attack hits, the defender suffers 1 damage and receives 1 ion token. Then cancel all dice results.""" "Heavy Laser Cannon": text: """<strong>Attack:</strong> Attack 1 ship.%LINEBREAK%Immediately after rolling your attack dice, you must change all of your %CRIT% results to %HIT% results.""" "Seismic Charges": text: """When you reveal your maneuver dial, you may discard this card to drop 1 seismic charge token.%LINEBREAK%This token detonates at the end of the Activation phase.%LINEBREAK%<strong>Seismic Charge Token:</strong> When this bomb token detonates, each ship at Range 1 of the token suffers 1 damage. Then discard this token.""" "Mercenary Copilot": text: """When attacking at Range 3, you may change 1 of your %HIT% results to a %CRIT% result.""" "Assault Missiles": text: """<strong>Attack (target lock):</strong> Spend your target lock and discard this card to perform this attack.%LINEBREAK%If this attack hits, each other ship at Range 1 of the defender suffers 1 damage.""" "Veteran Instincts": text: """Increase your pilot skill value by 2.""" "Proximity Mines": text: """<strong>Action:</strong> Discard this card to <strong>drop</strong> 1 proximity mine token.%LINEBREAK%When a ship's base or maneuver template overlaps this token, this token <strong>detonates</strong>.%LINEBREAK%<strong>Proximity Mine Token:</strong> When this bomb token detonates, the ship that moved through or overlapped this token rolls 3 attack dice and suffers all damage (%HIT%) and critical damage (%CRIT%) rolled. Then discard this token.""" "Weapons Engineer": text: """You may maintain 2 target locks (only 1 per enemy ship).%LINEBREAK%When you acquire a target lock, you may lock onto 2 different ships.""" "Draw Their Fire": text: """When a friendly ship at Range 1 is hit by an attack, you may suffer 1 of the uncanceled %CRIT% results instead of the target ship.""" "PI:NAME:<NAME>END_PI": text: """%REBELONLY%%LINEBREAK%After you perform an attack that does not hit, you may immediately perform a primary weapon attack. You may change 1 %FOCUS% result to a %HIT% result. You cannot perform another attack this round.""" "PI:NAME:<NAME>END_PI": text: """%REBELONLY%%LINEBREAK%You may treat all %STRAIGHT% maneuvers as green maneuvers.""" "ChewbPI:NAME:<NAME>END_PI": text: """%REBELONLY%%LINEBREAK%When you are dealt a Damage card, you may immediately discard that card and recover 1 shield.%LINEBREAK%Then, discard this Upgrade card.""" "Advanced Proton Torpedoes": text: """<strong>Attack (target lock):</strong> Spend your target lock and discard this card to perform this attack.%LINEBREAK%You may change up to 3 of your blank results to %FOCUS% results.""" "Autoblaster": text: """<strong>Attack:</strong> Attack 1 ship.%LINEBREAK%Your %HIT% results cannot be canceled by defense dice.%LINEBREAK%The defender may cancel %CRIT% results before %HIT% results.""" "Fire-Control System": text: """After you perform an attack, you may acquire a target lock on the defender.""" "Blaster Turret": text: """<strong>Attack (focus):</strong> Spend 1 focus token to perform this attack against 1 ship (even a ship outside your firing arc).""" "Recon Specialist": text: """When you perform a focus action, assign 1 additional focus token to your ship.""" "Saboteur": text: """<strong>Action:</strong> Choose 1 enemy ship at Range 1 and roll 1 attack die. On a %HIT% or %CRIT% result, choose 1 random facedown Damage card assigned to that ship, flip it faceup, and resolve it.""" "Intelligence Agent": text: """At the start of the Activation phase, choose 1 enemy ship at Range 1-2. You may look at that ship's chosen maneuver.""" "Proton Bombs": text: """When you reveal your maneuver dial, you may discard this card to <strong>drop</strong> 1 proton bomb token.%LINEBREAK%This token <strong>detonates</strong> at the end of the Activation phase.%LINEBREAK%<strong>Proton Bomb Token:</strong> When this bomb token detonates, deal 1 <strong>faceup</strong> Damage card to each ship at Range 1 of the token. Then discard this token.""" "AdPI:NAME:<NAME>END_PIaline Rush": text: """When you reveal a red maneuver, you may discard this card to treat that maneuver as a white maneuver until the end of the Activation phase.""" "Advanced Sensors": text: """Immediately before you reveal your maneuver, you may perform 1 free action.%LINEBREAK%If you use this ability, you must skip your "Perform Action" step during this round.""" "Sensor Jammer": text: """When defending, you may change 1 of the attacker's %HIT% results into a %FOCUS% result.%LINEBREAK%The attacker cannot reroll the die with the changed result.""" "Darth Vader": text: """%IMPERIALONLY%%LINEBREAK%After you perform an attack against an enemy ship, you may suffer 2 damage to cause that ship to suffer 1 critical damage.""" "Rebel Captive": text: """%IMPERIALONLY%%LINEBREAK%Once per round, the first ship that declares you as the target of an attack immediately receives 1 stress token.""" "Flight Instructor": text: """When defending, you may reroll 1 of your %FOCUS% results. If the attacker's pilot skill value is "2" or lower, you may reroll 1 of your blank results instead.""" "Navigator": text: """When you reveal a maneuver, you may rotate your dial to another maneuver with the same bearing.%LINEBREAK%You cannot rotate to a red maneuver if you have any stress tokens.""" "Opportunist": text: """When attacking, if the defender does not have any focus or evade tokens, you may receive 1 stress token to roll 1 additional attack die.%LINEBREAK%You cannot use this ability if you have any stress tokens.""" "Comms Booster": text: """<strong>Energy:</strong> Spend 1 energy to remove all stress tokens from a friendly ship at Range 1-3. Then assign 1 focus token to that ship.""" "Slicer Tools": text: """<strong>Action:</strong> Choose 1 or more ships at Range 1-3 that have a stress token. For each ship chosen, you may spend 1 energy to cause that ship to suffer 1 damage.""" "Shield Projector": text: """When an enemy ship is declaring either a small or large ship as the target of its attack, you may spend 3 energy to force that ship to target you if possible.""" "Ion Pulse Missiles": text: """<strong>Attack (target lock):</strong> Discard this card to perform this attack.%LINEBREAK%If this attack hits, the defender suffers 1 damage and receives 2 ion tokens. Then cancel <strong>all</strong> dice results.""" "Wingman": text: """At the start of the Combat phase, remove 1 stress token from another friendly ship at Range 1.""" "Decoy": text: """At the start of the Combat phase, you may choose 1 friendly ship at Range 1-2. Exchange your pilot skill with that ship's pilot skill until the end of the phase.""" "Outmaneuver": text: """When attacking a ship inside your firing arc, if you are not inside that ship's firing arc, reduce its agility value by 1 (to a minimum of 0).""" "Predator": text: """When attacking, you may reroll 1 attack die. If the defender's pilot skill value is "2" or lower, you may instead reroll up to 2 attack dice.""" "PI:NAME:<NAME>END_PI": text: """<strong>Attack (target lock):</strong> Discard this card and spend your target lock to perform this attack.%LINEBREAK%After you perform this attack, the defender receives 1 stress token if its hull value is "4" or lower.""" "R7 Astromech": text: """Once per round when defending, if you have a target lock on the attacker, you may spend the target lock to choose any or all attack dice. The attacker must reroll the chosen dice.""" "R7-T1": text: """<strong>Action:</strong> Choose an enemy ship at Range 1-2. If you are inside that ship's firing arc, you may acquire a target lock on that ship. Then, you may perform a free boost action.""" "Tactician": text: """After you perform an attack against a ship inside your firing arc at Range 2, that ship receives 1 stress token.""" "R2-D2 (Crew)": text: """%REBELONLY%%LINEBREAK%At the end of the End phase, if you have no shields, you may recover 1 shield and roll 1 attack die. On a %HIT% result, randomly flip 1 of your facedown Damage cards faceup and resolve it.""" "C-3PO": text: """%REBELONLY%%LINEBREAK%Once per round, before you roll 1 or more defense dice, you may guess aloud a number of %EVADE% results. If you roll that many %EVADE% results (before modifying dice), add 1 %EVADE% result.""" "Single Turbolasers": text: """<strong>Attack (Energy):</strong> Spend 2 energy from this card to perform this attack. The defender doubles his agility value against this attack. You may change 1 of your %FOCUS% results to a %HIT% result.""" "Quad Laser Cannons": text: """<strong>Attack (Energy):</strong> Spend 1 energy from this card to perform this attack. If this attack does not hit, you may immediately spend 1 energy from this card to perform this attack again.""" "Tibanna Gas Supplies": text: """<strong>Energy:</strong> You may discard this card to gain 3 energy.""" "Ionization Reactor": text: """<strong>Energy:</strong> Spend 5 energy from this card and discard this card to cause each other ship at Range 1 to suffer 1 damage and receive 1 ion token.""" "Engine Booster": text: """Immediately before you reveal your maneuver dial, you may spend 1 energy to execute a white (%STRAIGHT% 1) maneuver. You cannot use this ability if you would overlap another ship.""" "R3-A2": text: """When you declare the target of your attack, if the defender is inside your firing arc, you may receive 1 stress token to cause the defender to receive 1 stress token.""" "R2-D6": text: """Your upgrade bar gains the %ELITE% upgrade icon.%LINEBREAK%You cannot equip this upgrade if you already have a %ELITE% upgrade icon or if your pilot skill value is "2" or lower.""" "Enhanced Scopes": text: """During the Activation phase, treat your pilot skill value as "0".""" "Chardaan Refit": text: """<span class="card-restriction">A-Wing only.</span>%LINEBREAK%This card has a negative squad point cost.""" "Proton Rockets": text: """<strong>Attack (Focus):</strong> Discard this card to perform this attack.%LINEBREAK%You may roll additional attack dice equal to your agility value, to a maximum of 3 additional dice.""" "PI:NAME:<NAME>END_PI": text: """%REBELONLY%%LINEBREAK%After you remove a stress token from your ship, you may assign a focus token to your ship.""" "PI:NAME:<NAME>END_PI": text: """%REBELONLY%%LINEBREAK%Once per round, when a friendly ship at Range 1-3 performs a focus action or would be assigned a focus token, you may assign it an evade token instead.""" "PI:NAME:<NAME>END_PI": text: """%HUGESHIPONLY% %REBELONLY%%LINEBREAK%<strong>Action:</strong> Spend any amount of energy to choose that many enemy ships at Range 1-2. Remove all focus, evade, and blue target lock tokens from those ships.""" "R4-D6": text: """When you are hit by an attack and there are at least 3 uncanceled %HIT% results, you may choose to cancel those results until there are 2 remaining. For each result canceled this way, receive 1 stress token.""" "R5-P9": text: """At the end of the Combat phase, you may spend 1 of your focus tokens to recover 1 shield (up to your shield value).""" "WED-15 Repair Droid": text: """%HUGESHIPONLY%%LINEBREAK%<strong>Action:</strong> Spend 1 energy to discard 1 of your facedown Damage cards, or spend 3 energy to discard 1 of your faceup Damage cards.""" "PI:NAME:<NAME>END_PI": text: """%HUGESHIPONLY% %REBELONLY%%LINEBREAK%At the start of the Activation phase, you may discard this card to treat each friendly ship's pilot skill value as "12" until the end of the phase.""" "PI:NAME:<NAME>END_PI": text: """%HUGESHIPONLY% %REBELONLY%%LINEBREAK%When another friendly ship at Range 1 is attacking, it may change 1 of its %HIT% results to a %CRIT%.""" "Expanded Cargo Hold": text: """<span class="card-restriction">GR-75 only.</span>%LINEBREAK%Once per round, when you would be dealt a faceup Damage card, you may draw that card from either the fore or aft Damage deck.""" "Backup Shield Generator": text: """At the end of each round, you may spend 1 energy to recover 1 shield (up to your shield value).""" "EM Emitter": text: """When you obstruct an attack, the defender rolls 3 additional defense dice (instead of 1).""" "Frequency Jammer": text: """When you perform a jam action, choose 1 enemy ship that does not have a stress token and is at Range 1 of the jammed ship. The chosen ship receives 1 stress token.""" "PI:NAME:<NAME>END_PI": text: """%REBELONLY%%LINEBREAK%When attacking, if you have a target lock on the defender, you may spend that target lock to change all of your %FOCUS% results to %HIT% results.""" "PI:NAME:<NAME>END_PI": text: """%REBELONLY%%LINEBREAK%At the start of the Activation phase, you may discard this card to allow all friendly ships that reveal a red maneuver to treat that maneuver as a white maneuver until the end of the phase.""" "Targeting Coordinator": text: """<strong>Energy:</strong> You may spend 1 energy to choose 1 friendly ship at Range 1-2. Acquire a target lock, then assign the blue target lock token to the chosen ship.""" "PI:NAME:<NAME>END_PI": text: """%HUGESHIPONLY% %REBELONLY%%LINEBREAK%At the start of the Activation phase, choose 1 enemy ship at Range 1-3. You may look at that ship's chosen maneuver. If the maneuver is white, assign that ship 1 stress token.""" "Gunnery Team": text: """Once per round, when attacking with a secondary weapon, you may spend 1 energy to change 1 of your blank results to a %HIT% result.""" "Sensor Team": text: """When acquiring a target lock, you may lock onto an enemy ship at Range 1-5 instead of 1-3.""" "Engineering Team": text: """During the Activation phase, when you reveal a %STRAIGHT% maneuver, gain 1 additional energy during the "Gain Energy" step.""" "PI:NAME:<NAME>END_PI": text: """%REBELONLY%%LINEBREAK%<strong>Action:</strong> Roll 2 defense dice. For each %FOCUS% result, assign 1 focus token to your ship. For each %EVADE% result, assign 1 evade token to your ship.""" "PI:NAME:<NAME>END_PI": text: """%IMPERIALONLY%%LINEBREAK%At the end of the Combat phase, each enemy ship at Range 1 that does not have a stress token receives 1 stress token.""" "Fleet Officer": text: """%IMPERIALONLY%%LINEBREAK%<strong>Action:</strong> Choose up to 2 friendly ships at Range 1-2 and assign 1 focus token to each of those ships. Then receive 1 stress token.""" "Lone Wolf": text: """When attacking or defending, if there are no other friendly ships at Range 1-2, you may reroll 1 of your blank results.""" "Stay On Target": text: """When you reveal a maneuver, you may rotate your dial to another maneuver with the same speed.%LINEBREAK%Treat that maneuver as a red maneuver.""" "Dash Rendar": text: """%REBELONLY%%LINEBREAK%You may perform attacks while overlapping an obstacle.%LINEBREAK%Your attacks cannot be obstructed.""" '"Leebo"': text: """%REBELONLY%%LINEBREAK%<strong>Action:</strong> Perform a free boost action. Then receive 1 ion token.""" "Ruthlessness": text: """%IMPERIALONLY%%LINEBREAK%After you perform an attack that hits, you <strong>must</strong> choose 1 other ship at Range 1 of the defender (other than yourself). That ship suffers 1 damage.""" "Intimidation": text: """While you are touching an enemy ship, reduce that ship's agility value by 1.""" "PI:NAME:<NAME>END_PI": text: """%IMPERIALONLY%%LINEBREAK%At the start of the Combat phase, if you have no shields and at least 1 Damage card assigned to your ship, you may perform a free evade action.""" "PI:NAME:<NAME>END_PI": text: """%IMPERIALONLY%%LINEBREAK%When you are dealt a faceup Damage card, you may discard this Upgrade card or another %CREW% Upgrade card to flip that Damage card facedown (without resolving its effect).""" "Ion Torpedoes": text: """<strong>Attack (target lock):</strong> Spend your target lock and discard this card to perform this attack.%LINEBREAK%If this attack hits, the defender and each ship at Range 1 of it receives 1 ion token.""" "Bodyguard": text: """%SCUMONLY%%LINEBREAK%At the start of the Combat phase, you may spend a focus token to choose a friendly ship at Range 1 with higher pilot skill than you. Increase its agility value by 1 until the end of the round.""" "Calculation": text: """When attacking, you may spend a focus token to change 1 of your %FOCUS% results to a %CRIT% result.""" "Accuracy Corrector": text: """When attacking, during the "Modify Attack Dice" step, you may cancel all of your dice results. Then, you may add 2 %HIT% results to your roll.%LINEBREAK%Your dice cannot be modified again during this attack.""" "Inertial Dampeners": text: """When you reveal your maneuver, you may discard this card to instead perform a white [0%STOP%] maneuver. Then receive 1 stress token.""" "Flechette Cannon": text: """<strong>Attack:</strong> Attack 1 ship.%LINEBREAK%If this attack hits, the defender suffers 1 damage and, if the defender is not stressed, it also receives 1 stress token. Then cancel <strong>all</strong> dice results.""" '"Mangler" Cannon': text: """<strong>Attack:</strong> Attack 1 ship.%LINEBREAK%When attacking, you may change 1 of your %HIT% results to a %CRIT% result.""" "Dead Man's Switch": text: """When you are destroyed, each ship at Range 1 suffers 1 damage.""" "Feedback Array": text: """During the Combat phase, instead of performing any attacks, you may receive 1 ion token and suffer 1 damage to choose 1 enemy ship at Range 1. That ship suffers 1 damage.""" '"Hot Shot" Blaster': text: """<strong>Attack:</strong> Discard this card to attack 1 ship (even a ship outside your firing arc).""" "Greedo": text: """%SCUMONLY%%LINEBREAK%The first time you attack each round and the first time you defend each round, the first Damage card dealt is dealt faceup.""" "Salvaged Astromech": text: """When you are dealt a Damage card with the <strong>Ship</strong> trait, you may immediately discard that card (before resolving its effect).%LINEBREAK%Then, discard this Upgrade card.""" "Bomb Loadout": text: """<span class="card-restriction">Y-Wing only.</span>%LINEBREAK%Your upgrade bar gains the %BOMB% icon.""" '"Genius"': text: """If you are equipped with a bomb that can be dropped when you reveal your maneuver, you may drop the bomb <strong>after</strong> you execute your maneuver instead.""" "Unhinged Astromech": text: """You may treat all 3-speed maneuvers as green maneuvers.""" "R4-B11": text: """When attacking, if you have a target lock on the defender, you may spend the target lock to choose any or all defense dice. The defender must reroll the chosen dice.""" "Autoblaster Turret": text: """<strong>Attack:</strong> Attack 1 ship (even a ship outside your firing arc).%LINEBREAK%Your %HIT% results cannot be canceled by defense dice. The defender may cancel %CRIT% results before %HIT% results.""" "R4 Agromech": text: """When attacking, after you spend a focus token, you may acquire a target lock on the defender.""" "K4 Security Droid": text: """%SCUMONLY%%LINEBREAK%After executing a green maneuver, you may acquire a target lock.""" "Outlaw Tech": text: """%SCUMONLY%%LINEBREAK%After you execute a red maneuver, you may assign 1 focus token to your ship.""" "Advanced Targeting Computer": text: """<span class="card-restriction">TIE Advanced only.</span>%LINEBREAK%When attacking with your primary weapon, if you have a target lock on the defender, you may add 1 %CRIT% result to your roll. If you do, you cannot spend target locks during this attack.""" "Ion Cannon Battery": text: """<strong>Attack (energy):</strong> Spend 2 energy from this card to perform this attack. If this attack hits, the defender suffers 1 critical damage and receives 1 ion token. Then cancel <strong>all</strong> dice results.""" "Extra Munitions": text: """When you equip this card, place 1 ordnance token on each equipped %TORPEDO%, %MISSILE%, and %BOMB% Upgrade card. When you are instructed to discard an Upgrade card, you may discard 1 ordnance token on that card instead.""" "Cluster Mines": text: """<strong>Action:</strong> Discard this card to <strong>drop</strong> 3 cluster mine tokens.<br /><br />When a ship's base or maneuver template overlaps a cluster mine token, that token <strong>detonates</strong>.<br /><br /><strong>Cluster Mines Tokens:</strong> When one of these bomb tokens detonates, the ship that moved through or overlapped this token rolls 2 attack dice and suffers all damage (%HIT%) rolled. Then discard this token.""" "PI:NAME:<NAME>END_PI": text: """At the start of the Combat phase, you may discard this card and receive 1 stress token. If you do, until the end of the round, when attacking or defending, you may change all of your %FOCUS% results to %HIT% or %EVADE% results.""" "PI:NAME:<NAME>END_PI": text: """%HUGESHIPONLY% %IMPERIALONLY%%LINEBREAK%At the start of the Combat phase, you may choose another ship at Range 1-4. Either remove 1 focus token from the chosen ship or assign 1 focus token to that ship.""" "PI:NAME:<NAME>END_PI": text: """%HUGESHIPONLY% %IMPERIALONLY%%LINEBREAK%If you overlap an obstacle during the Activation phase, do not suffer 1 faceup damage card. Instead, roll 1 attack die. On a %HIT% or %CRIT% result, suffer 1 damage.""" "PI:NAME:<NAME>END_PI": text: """%HUGESHIPONLY% %IMPERIALONLY%%LINEBREAK%<strong>Energy:</strong> You may remove up to 3 shields from your ship. For each shield removed, gain 1 energy.""" "PI:NAME:<NAME>END_PI": text: """%IMPERIALONLY%%LINEBREAK%Once per round, you may change a friendly ship's die result to any other die result. That die result cannot be modified again.""" "Bossk": text: """%SCUMONLY%%LINEBREAK%After you perform an attack that does not hit, if you are not stressed, you <strong>must</strong> receive 1 stress token. Then assign 1 focus token to your ship and acquire a target lock on the defender.""" "Lightning Reflexes": text: """%SMALLSHIPONLY%%LINEBREAK%After you execute a white or green maneuver on your dial, you may discard this card to rotate your ship 180&deg;. Then receive 1 stress token <strong>after</strong> the "Check Pilot Stress" step.""" "Twin Laser Turret": text: """<strong>Attack:</strong> Perform this attack <strong>twice</strong> (even against a ship outside your firing arc).<br /><br />Each time this attack hits, the defender suffers 1 damage. Then cancel <strong>all</strong> dice results.""" "Plasma Torpedoes": text: """<strong>Attack (target lock):</strong> Spend your target lock and discard this card to perform this attack.<br /><br />If this attack hits, after dealing damage, remove 1 shield token from the defender.""" "Ion Bombs": text: """When you reveal your maneuver dial, you may discard this card to <strong>drop</strong> 1 ion bomb token.<br /><br />This token <strong>detonates</strong> at the end of the Activation phase.<br /><br /><strong>Ion Bombs Token:</strong> When this bomb token detonates, each ship at Range 1 of the token receives 2 ion tokens. Then discard this token.""" "Conner Net": text: """<strong>Action:</strong> Discard this card to <strong>drop</strong> 1 Conner Net token.<br /><br />When a ship's base or maneuver template overlaps this token, this token <strong>detonates</strong>.<br /><br /><strong>Conner Net Token:</strong> When this bomb token detonates, the ship that moved through or overlapped this token suffers 1 damage, receives 2 ion tokens, and skips its "Perform Action" step. Then discard this token.""" "Bombardier": text: """When dropping a bomb, you may use the (%STRAIGHT% 2) template instead of the (%STRAIGHT% 1) template.""" 'Crack Shot': text: '''When attacking a ship inside your firing arc, you may discard this card to cancel 1 of the defender's %EVADE% results.''' "Advanced Homing Missiles": text: """<strong>Attack (target lock):</strong> Discard this card to perform this attack.%LINEBREAK%If this attack hits, deal 1 faceup Damage card to the defender. Then cancel <strong>all</strong> dice results.""" 'PI:NAME:<NAME>END_PI': text: '''%IMPERIALONLY%%LINEBREAK%At the start of the first round, choose 1 enemy small or large ship. When attacking or defending against that ship, you may change 1 of your %FOCUS% results to a %HIT% or %EVADE% result.''' 'XX-23 S-Thread Tracers': text: """<strong>Attack (focus):</strong> Discard this card to perform this attack. If this attack hits, each friendly ship at Range 1-2 of you may acquire a target lock on the defender. Then cancel <strong>all</strong> dice results.""" "Tractor Beam": text: """<strong>Attack:</strong> Attack 1 ship.%LINEBREAK%If this attack hits, the defender receives 1 tractor beam token. Then cancel <strong>all</strong> dice results.""" "Cloaking Device": text: """%SMALLSHIPONLY%%LINEBREAK%<strong>Action:</strong> Perform a free cloak action.%LINEBREAK%At the end of each round, if you are cloaked, roll 1 attack die. On a %FOCUS% result, discard this card, then decloak or discard your cloak token.""" modification_translations = "Stealth Device": text: """Increase your agility value by 1. If you are hit by an attack, discard this card.""" "Shield Upgrade": text: """Increase your shield value by 1.""" "Engine Upgrade": text: """Your action bar gains the %BOOST% action icon.""" "Anti-Pursuit Lasers": text: """%LARGESHIPONLY%%LINEBREAK%After an enemy ship executes a maneuver that causes it to overlap your ship, roll 1 attack die. On a %HIT% or %CRIT% result, the enemy ship suffers 1 damage.""" "Targeting Computer": text: """Your action bar gains the %TARGETLOCK% action icon.""" "Hull Upgrade": text: """Increase your hull value by 1.""" "Munitions Failsafe": text: """When attacking with a secondary weapon that instructs you to discard it to perform the attack, do not discard it unless the attack hits.""" "Stygium Particle Accelerator": text: """When you either decloak or perform a cloak action, you may perform a free evade action.""" "Advanced Cloaking Device": text: """<span class="card-restriction">TIE Phantom only.</span>%LINEBREAK%After you perform an attack, you may perform a free cloak action.""" "Combat Retrofit": text: """<span class="card-restriction">GR-75 only.</span>%LINEBREAK%Increase your hull value by 2 and your shield value by 1.""" "B-Wing/E2": text: """<span class="card-restriction">B-Wing only.</span>%LINEBREAK%Your upgrade bar gains the %CREW% upgrade icon.""" "Countermeasures": text: """%LARGESHIPONLY%%LINEBREAK%At the start of the Combat phase, you may discard this card to increase your agility value by 1 until the end of the round. Then you may remove 1 enemy target lock from your ship.""" "Experimental Interface": text: """Once per round, after you perform an action, you may perform 1 free action from an equipped Upgrade card with the "<strong>Action:</strong>" header. Then receive 1 stress token.""" "Tactical Jammer": text: """%LARGESHIPONLY%%LINEBREAK%Your ship can obstruct enemy attacks.""" "Autothrusters": text: """When defending, if you are beyond Range 2 or outside the attacker's firing arc, you may change 1 of your blank results to a %EVADE% result. You can equip this card only if you have the %BOOST% action icon.""" "Advanced SLAM": text: """After performing a SLAM action, if you did not overlap an obstacle or another ship, you may perform a free action.""" "Twin Ion Engine Mk. II": text: """You may treat all bank maneuvers (%BANKLEFT% and %BANKRIGHT%) as green maneuvers.""" "Maneuvering Fins": text: """When you reveal a turn maneuver (%TURNLEFT% or %TURNRIGHT%), you may rotate your dial to the corresponding bank maneuver (%BANKLEFT% or %BANKRIGHT%) of the same speed.""" "Ion Projector": text: """%LARGESHIPONLY%%LINEBREAK%After an enemy ship executes a maneuver that causes it to overlap your ship, roll 1 attack die. On a %HIT% or %CRIT% result, the enemy ship receives 1 ion token.""" title_translations = "Slave I": text: """<span class="card-restriction">Firespray-31 only.</span>%LINEBREAK%Your upgrade bar gains the %TORPEDO% upgrade icon.""" "Millennium Falcon": text: """<span class="card-restriction">YT-1300 only.</span>%LINEBREAK%Your action bar gains the %EVADE% action icon.""" "Moldy Crow": text: """<span class="card-restriction">HWK-290 only.</span>%LINEBREAK%During the End phase, do not remove unused focus tokens from your ship.""" "ST-321": text: """<span class="card-restriction"><em>Lambda</em>-class Shuttle only.</span>%LINEBREAK%When acquiring a target lock, you may lock onto any enemy ship in the play area.""" "Royal Guard TIE": text: """<span class="card-restriction">TIE Interceptor only.</span>%LINEBREAK%You may equip up to 2 different Modification upgrades (instead of 1).%LINEBREAK%You cannot equip this card if your pilot skill value is "4" or lower.""" "DodPI:NAME:<NAME>END_PI's Pride": text: """<span class="card-restriction">CR90 fore section only.</span>%LINEBREAK%When you perform a coordinate action, you may choose 2 friendly ships (instead of 1). Those ships may each perform 1 free action.""" "A-Wing Test Pilot": text: """<span class="card-restriction">A-Wing only.</span>%LINEBREAK%Your upgrade bar gains 1 %ELITE% upgrade icon.%LINEBREAK%You cannot equip 2 of the same %ELITE% Upgrade cards. You cannot equip this if your pilot skill value is "1" or lower.""" "Tantive IV": text: """<span class="card-restriction">CR90 fore section only.</span>%LINEBREAK%Your fore section upgrade bar gains 1 additional %CREW% and 1 additional %TEAM% upgrade icon.""" "Bright Hope": text: """<span class="card-restriction">GR-75 only.</span>%LINEBREAK%A reinforce action assigned to your fore section adds 2 %EVADE% results (instead of 1).""" "Quantum Storm": text: """<span class="card-restriction">GR-75 only.</span>%LINEBREAK%At the start of the End phase, if you have 1 or fewer energy tokens, gain 1 energy token.""" "Dutyfree": text: """<span class="card-restriction">GR-75 only.</span>%LINEBREAK%When performing a jam action, you may choose an enemy ship at Range 1-3 (instead of at Range 1-2).""" "Jaina's Light": text: """<span class="card-restriction">CR90 fore section only.</span>%LINEBREAK%When defending, once per attack, if you are dealt a faceup Damage card, you may discard it and draw another faceup Damage card.""" "Outrider": text: """<span class="card-restriction">YT-2400 only.</span>%LINEBREAK%While you have a %CANNON% Upgrade card equipped, you <strong>cannot</strong> perform primary weapon attacks and you may perform %CANNON% secondary weapon attacks against ships outside your firing arc.""" "Dauntless": text: """<span class="card-restriction">VT-49 Decimator only.</span>%LINEBREAK%After you execute a maneuver that causes you to overlap another ship, you may perform 1 free action. Then receive 1 stress token.""" "PI:NAME:<NAME>END_PI": text: """<span class="card-restriction">StarViper only.</span>%LINEBREAK%Your upgrade bar gains the %SYSTEM% and %ILLICIT% upgrade icons.%LINEBREAK%You cannot equip this card if your pilot skill value is "3" or lower.""" '"Heavy Scyk" Interceptor (Cannon)': text: """<span class="card-restriction">M3-A Interceptor only.</span>%LINEBREAK%Your upgrade bar gains the %CANNON%, %TORPEDO%, or %MISSILE% upgrade icon.""" '"Heavy Scyk" Interceptor (Torpedo)': text: """<span class="card-restriction">M3-A Interceptor only.</span>%LINEBREAK%Your upgrade bar gains the %CANNON%, %TORPEDO%, or %MISSILE% upgrade icon.""" '"Heavy Scyk" Interceptor (Missile)': text: """<span class="card-restriction">M3-A Interceptor only.</span>%LINEBREAK%Your upgrade bar gains the %CANNON%, %TORPEDO%, or %MISSILE% upgrade icon.""" "IG-2000": text: """<span class="card-restriction">Aggressor only.</span>%LINEBREAK%You have the pilot ability of each other friendly ship with the <em>IG-2000</em> Upgrade card (in addition to your own pilot ability).""" "BTL-A4 Y-Wing": text: """<span class="card-restriction">Y-Wing only.</span>%LINEBREAK%You cannot attack ships outside your firing arc. After you perform a primary weapon attack, you may immediately perform an attack with a %TURRET% secondary weapon.""" "Andrasta": text: """Your upgrade bar gains two additional %BOMB% upgrade icons.""" "TIE/x1": text: """<span class="card-restriction">TIE Advanced only.</span>%LINEBREAK%Your upgrade bar gains the %SYSTEM% upgrade icon.%LINEBREAK%If you equip a %SYSTEM% upgrade, its squad point cost is reduced by 4 (to a minimum of 0).""" "PI:NAME:<NAME>END_PI": text: """<span class="card-restriction">YV-666 only.</span>%LINEBREAK%After you are destroyed, before you are removed from the play area, you may <strong>deploy</strong> the <em>Nashtah Pup</em> ship.%LINEBREAK%It cannot attack this round.""" "Ghost": text: """<span class="card-restriction">VCX-100 only.</span>%LINEBREAK%Equip the <em>Phantom</em> title card to a friendly Attack Shuttle and dock it to this ship.%LINEBREAK%After you execute a maneuver, you may deploy it from your rear guides.""" "Phantom": text: """While you are docked, the <em>Ghost</em> can perform primary weapon attacks from its special firing arc, and, at the end of the Combat phase, it may perform an additional attack with an equipped %TURRET%. If it performs this attack, it cannot attack again this round.""" "TIE/v1": text: """<span class="card-restriction">TIE Advanced Prototype only.</span>%LINEBREAK%After you acquire a target lock, you may perform a free evade action.""" "PI:NAME:<NAME>END_PI": text: """<span class="card-restriction">G-1A starfighter only.</span>%LINEBREAK%Your upgrade bar gains the %BARRELROLL% Upgrade icon.%LINEBREAK%You <strong>must</strong> equip 1 "Tractor Beam" Upgrade card (paying its squad point cost as normal).""" "PI:NAME:<NAME>END_PI": text: """<span class="card-restriction">JumpMaster 5000 only.</span>%LINEBREAK%Increase your primary weapon value by 1.""" exportObj.setupCardData basic_cards, pilot_translations, upgrade_translations, modification_translations, title_translations
[ { "context": "### Copyright (c) 2015 Magnus Leo. All rights reserved. ###\n\ncore = require('../mod", "end": 33, "score": 0.9998645782470703, "start": 23, "tag": "NAME", "value": "Magnus Leo" } ]
src/classes/Actor.coffee
magnusleo/Leo-Engine
1
### Copyright (c) 2015 Magnus Leo. All rights reserved. ### core = require('../modules/core') Sprite = require('./Sprite') module.exports = class Actor constructor: (properties) -> # Actor::constructor # Defaults @posX = 0 @posY = 0 @speedX = 0 @speedY = 0 # User defined properties for key, val of properties @[key] = val core.actors.push this draw: -> # Actor::draw @sprite.draw(@posX, @posY) setSprite: (sprite) -> # Actor::setSprite unless sprite instanceof Sprite throw 'Actor::setSprite - Missing Sprite' @sprite = sprite update: (cycleLength) -> # Actor::update # Animation @sprite.advanceAnimation(cycleLength) # Position @posX += @speedX * cycleLength @posY += @speedY * cycleLength decelerate: (axis, amount) -> # Actor::decelerate if not amount return axis = axis.toUpperCase() unitName = 'speed' + axis curSpeed = @[unitName] if curSpeed > 0 @[unitName] = Math.max(curSpeed - amount, 0) else @[unitName] = Math.min(curSpeed + amount, 0)
67003
### Copyright (c) 2015 <NAME>. All rights reserved. ### core = require('../modules/core') Sprite = require('./Sprite') module.exports = class Actor constructor: (properties) -> # Actor::constructor # Defaults @posX = 0 @posY = 0 @speedX = 0 @speedY = 0 # User defined properties for key, val of properties @[key] = val core.actors.push this draw: -> # Actor::draw @sprite.draw(@posX, @posY) setSprite: (sprite) -> # Actor::setSprite unless sprite instanceof Sprite throw 'Actor::setSprite - Missing Sprite' @sprite = sprite update: (cycleLength) -> # Actor::update # Animation @sprite.advanceAnimation(cycleLength) # Position @posX += @speedX * cycleLength @posY += @speedY * cycleLength decelerate: (axis, amount) -> # Actor::decelerate if not amount return axis = axis.toUpperCase() unitName = 'speed' + axis curSpeed = @[unitName] if curSpeed > 0 @[unitName] = Math.max(curSpeed - amount, 0) else @[unitName] = Math.min(curSpeed + amount, 0)
true
### Copyright (c) 2015 PI:NAME:<NAME>END_PI. All rights reserved. ### core = require('../modules/core') Sprite = require('./Sprite') module.exports = class Actor constructor: (properties) -> # Actor::constructor # Defaults @posX = 0 @posY = 0 @speedX = 0 @speedY = 0 # User defined properties for key, val of properties @[key] = val core.actors.push this draw: -> # Actor::draw @sprite.draw(@posX, @posY) setSprite: (sprite) -> # Actor::setSprite unless sprite instanceof Sprite throw 'Actor::setSprite - Missing Sprite' @sprite = sprite update: (cycleLength) -> # Actor::update # Animation @sprite.advanceAnimation(cycleLength) # Position @posX += @speedX * cycleLength @posY += @speedY * cycleLength decelerate: (axis, amount) -> # Actor::decelerate if not amount return axis = axis.toUpperCase() unitName = 'speed' + axis curSpeed = @[unitName] if curSpeed > 0 @[unitName] = Math.max(curSpeed - amount, 0) else @[unitName] = Math.min(curSpeed + amount, 0)
[ { "context": "\n# grunt-sitemap\n# https://github.com/RayViljoen/grunt-sitemap\n# Copyright (c) 2013 Ray Viljoen\n# ", "end": 48, "score": 0.9994235038757324, "start": 38, "tag": "USERNAME", "value": "RayViljoen" }, { "context": ".com/RayViljoen/grunt-sitemap\n# Copyright (c) 2013 Ra...
src/sitemap.coffee
inlight-media/grunt-sitemap
0
# grunt-sitemap # https://github.com/RayViljoen/grunt-sitemap # Copyright (c) 2013 Ray Viljoen # Licensed under the MIT license. module.exports = (grunt) -> # Node modules path = require 'path' fs = require 'fs' _ = require 'lodash' # Please see the grunt documentation for more information regarding task and # helper creation: https://github.com/cowboy/grunt/blob/master/docs/toc.md # ========================================================================== # TASKS # ========================================================================== grunt.registerMultiTask 'sitemap', 'sitemap description', -> # Homepage from pkg url = @data.homepage or grunt.config.get('pkg.homepage') # Check homepage is set homeErrMess = 'Requires "homepage" parameter. Sitemap was not created.' grunt.fail.warn(homeErrMess, 3) unless url # Add trailing slash to url if not there url += '/' unless url[-1..] is '/' # Site root dir root = path.normalize (@data.siteRoot or '.') # Check a site root was set rootWarnMess = 'No "siteRoot" parameter defined. Using current directory.' grunt.log.subhead rootWarnMess if root is '.' # changereq setting changefreq = @data.changefreq or 'daily' # priority setting # Must be string priority = (@data.priority or 0.5).toString() # File pattern pattern = @data.pattern or '**/*.html' # Glob root files = grunt.file.expand { cwd: root }, pattern # Remove root from path and prepend homepage url files = _.map files, (file) -> # Do not include 404 page return no if file.match /404\.html$/i # Create object with url an mtime fileStat = {} # Get path relative to root, but still containing index paths rawUrlPath = file.replace root, '' # Remove index.html urlPath = rawUrlPath.replace /(index)\.[A-z]+$/, '', 'i' # Join path with homepage url fileStat.url = url + urlPath # Get last modified time mtime = (fs.statSync(path.join(root, file)).mtime).getTime() # Format mtime to ISO (same as +00:00) fileStat.mtime = new Date(mtime).toISOString() # Return fileStat object fileStat # Remove any falsy values (404.html returns false) files = _.compact files # ----------------------- # Build xml # ----------------------- xmlStr = '<?xml version="1.0" encoding="UTF-8"?>\n' xmlStr += '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n' # Create url nodes for file in files xmlStr += '<url>\n' xmlStr += " <loc>#{file.url}</loc>\n" xmlStr += " <lastmod>#{file.mtime}</lastmod>\n" xmlStr += " <changefreq>#{changefreq}</changefreq>\n" xmlStr += " <priority>#{priority}</priority>\n" xmlStr += "</url>\n" # Close xml xmlStr += '</urlset>' # Write sitemap to root sitemapPath = path.join root, 'sitemap.xml' grunt.file.write sitemapPath, xmlStr grunt.log.writeln 'Sitemap created successfully' grunt.log.writeln 'OK' # Return true / false if grunt.task.current.errorCount then no else yes
194526
# grunt-sitemap # https://github.com/RayViljoen/grunt-sitemap # Copyright (c) 2013 <NAME> # Licensed under the MIT license. module.exports = (grunt) -> # Node modules path = require 'path' fs = require 'fs' _ = require 'lodash' # Please see the grunt documentation for more information regarding task and # helper creation: https://github.com/cowboy/grunt/blob/master/docs/toc.md # ========================================================================== # TASKS # ========================================================================== grunt.registerMultiTask 'sitemap', 'sitemap description', -> # Homepage from pkg url = @data.homepage or grunt.config.get('pkg.homepage') # Check homepage is set homeErrMess = 'Requires "homepage" parameter. Sitemap was not created.' grunt.fail.warn(homeErrMess, 3) unless url # Add trailing slash to url if not there url += '/' unless url[-1..] is '/' # Site root dir root = path.normalize (@data.siteRoot or '.') # Check a site root was set rootWarnMess = 'No "siteRoot" parameter defined. Using current directory.' grunt.log.subhead rootWarnMess if root is '.' # changereq setting changefreq = @data.changefreq or 'daily' # priority setting # Must be string priority = (@data.priority or 0.5).toString() # File pattern pattern = @data.pattern or '**/*.html' # Glob root files = grunt.file.expand { cwd: root }, pattern # Remove root from path and prepend homepage url files = _.map files, (file) -> # Do not include 404 page return no if file.match /404\.html$/i # Create object with url an mtime fileStat = {} # Get path relative to root, but still containing index paths rawUrlPath = file.replace root, '' # Remove index.html urlPath = rawUrlPath.replace /(index)\.[A-z]+$/, '', 'i' # Join path with homepage url fileStat.url = url + urlPath # Get last modified time mtime = (fs.statSync(path.join(root, file)).mtime).getTime() # Format mtime to ISO (same as +00:00) fileStat.mtime = new Date(mtime).toISOString() # Return fileStat object fileStat # Remove any falsy values (404.html returns false) files = _.compact files # ----------------------- # Build xml # ----------------------- xmlStr = '<?xml version="1.0" encoding="UTF-8"?>\n' xmlStr += '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n' # Create url nodes for file in files xmlStr += '<url>\n' xmlStr += " <loc>#{file.url}</loc>\n" xmlStr += " <lastmod>#{file.mtime}</lastmod>\n" xmlStr += " <changefreq>#{changefreq}</changefreq>\n" xmlStr += " <priority>#{priority}</priority>\n" xmlStr += "</url>\n" # Close xml xmlStr += '</urlset>' # Write sitemap to root sitemapPath = path.join root, 'sitemap.xml' grunt.file.write sitemapPath, xmlStr grunt.log.writeln 'Sitemap created successfully' grunt.log.writeln 'OK' # Return true / false if grunt.task.current.errorCount then no else yes
true
# grunt-sitemap # https://github.com/RayViljoen/grunt-sitemap # Copyright (c) 2013 PI:NAME:<NAME>END_PI # Licensed under the MIT license. module.exports = (grunt) -> # Node modules path = require 'path' fs = require 'fs' _ = require 'lodash' # Please see the grunt documentation for more information regarding task and # helper creation: https://github.com/cowboy/grunt/blob/master/docs/toc.md # ========================================================================== # TASKS # ========================================================================== grunt.registerMultiTask 'sitemap', 'sitemap description', -> # Homepage from pkg url = @data.homepage or grunt.config.get('pkg.homepage') # Check homepage is set homeErrMess = 'Requires "homepage" parameter. Sitemap was not created.' grunt.fail.warn(homeErrMess, 3) unless url # Add trailing slash to url if not there url += '/' unless url[-1..] is '/' # Site root dir root = path.normalize (@data.siteRoot or '.') # Check a site root was set rootWarnMess = 'No "siteRoot" parameter defined. Using current directory.' grunt.log.subhead rootWarnMess if root is '.' # changereq setting changefreq = @data.changefreq or 'daily' # priority setting # Must be string priority = (@data.priority or 0.5).toString() # File pattern pattern = @data.pattern or '**/*.html' # Glob root files = grunt.file.expand { cwd: root }, pattern # Remove root from path and prepend homepage url files = _.map files, (file) -> # Do not include 404 page return no if file.match /404\.html$/i # Create object with url an mtime fileStat = {} # Get path relative to root, but still containing index paths rawUrlPath = file.replace root, '' # Remove index.html urlPath = rawUrlPath.replace /(index)\.[A-z]+$/, '', 'i' # Join path with homepage url fileStat.url = url + urlPath # Get last modified time mtime = (fs.statSync(path.join(root, file)).mtime).getTime() # Format mtime to ISO (same as +00:00) fileStat.mtime = new Date(mtime).toISOString() # Return fileStat object fileStat # Remove any falsy values (404.html returns false) files = _.compact files # ----------------------- # Build xml # ----------------------- xmlStr = '<?xml version="1.0" encoding="UTF-8"?>\n' xmlStr += '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n' # Create url nodes for file in files xmlStr += '<url>\n' xmlStr += " <loc>#{file.url}</loc>\n" xmlStr += " <lastmod>#{file.mtime}</lastmod>\n" xmlStr += " <changefreq>#{changefreq}</changefreq>\n" xmlStr += " <priority>#{priority}</priority>\n" xmlStr += "</url>\n" # Close xml xmlStr += '</urlset>' # Write sitemap to root sitemapPath = path.join root, 'sitemap.xml' grunt.file.write sitemapPath, xmlStr grunt.log.writeln 'Sitemap created successfully' grunt.log.writeln 'OK' # Return true / false if grunt.task.current.errorCount then no else yes
[ { "context": "# Copyright (C) 2015, Radmon.\n# Use of this source code is governed by the MIT", "end": 28, "score": 0.7916046380996704, "start": 22, "tag": "NAME", "value": "Radmon" }, { "context": "out @timer\n\n $.fn.toast = (option) ->\n key = 'tm.toast'\n this.each ->\n ...
coffee/toast.coffee
radonlab/papery-theme
0
# Copyright (C) 2015, Radmon. # Use of this source code is governed by the MIT license that can be # found in the LICENSE file. module.exports = ($) -> 'use strict' target = '.toast' class Toast @TOAST_DURATION: 5000 @FADING_DURATION: 3000 constructor: (element) -> @element = element @element .on 'mouseenter', => @restore() .on 'mouseleave', => @countdown() show: () -> return if @element.hasClass 'open' @element.addClass 'open' @countdown() dismiss: () -> @element .removeClass 'open' .removeClass 'fading' countdown: () -> window.clearTimeout @timer @timer = window.setTimeout => @decline() , @constructor.TOAST_DURATION decline: () -> @element.addClass 'fading' @timer = window.setTimeout => @dismiss() , @constructor.FADING_DURATION restore: () -> @element.removeClass 'fading' window.clearTimeout @timer $.fn.toast = (option) -> key = 'tm.toast' this.each -> element = $(this) control = element.data key if not control control = new Toast element element.data key, control control[option].call control if typeof option == 'string' FindTarget = (trigger) -> guide = trigger.attr 'data-target' if guide then $(guide) else trigger.next target $(document) .on 'click touch', '[data-trigger="toast"]', (e) -> e.preventDefault() FindTarget $(this) .toast 'show'
120474
# Copyright (C) 2015, <NAME>. # Use of this source code is governed by the MIT license that can be # found in the LICENSE file. module.exports = ($) -> 'use strict' target = '.toast' class Toast @TOAST_DURATION: 5000 @FADING_DURATION: 3000 constructor: (element) -> @element = element @element .on 'mouseenter', => @restore() .on 'mouseleave', => @countdown() show: () -> return if @element.hasClass 'open' @element.addClass 'open' @countdown() dismiss: () -> @element .removeClass 'open' .removeClass 'fading' countdown: () -> window.clearTimeout @timer @timer = window.setTimeout => @decline() , @constructor.TOAST_DURATION decline: () -> @element.addClass 'fading' @timer = window.setTimeout => @dismiss() , @constructor.FADING_DURATION restore: () -> @element.removeClass 'fading' window.clearTimeout @timer $.fn.toast = (option) -> key = '<KEY>' this.each -> element = $(this) control = element.data key if not control control = new Toast element element.data key, control control[option].call control if typeof option == 'string' FindTarget = (trigger) -> guide = trigger.attr 'data-target' if guide then $(guide) else trigger.next target $(document) .on 'click touch', '[data-trigger="toast"]', (e) -> e.preventDefault() FindTarget $(this) .toast 'show'
true
# Copyright (C) 2015, PI:NAME:<NAME>END_PI. # Use of this source code is governed by the MIT license that can be # found in the LICENSE file. module.exports = ($) -> 'use strict' target = '.toast' class Toast @TOAST_DURATION: 5000 @FADING_DURATION: 3000 constructor: (element) -> @element = element @element .on 'mouseenter', => @restore() .on 'mouseleave', => @countdown() show: () -> return if @element.hasClass 'open' @element.addClass 'open' @countdown() dismiss: () -> @element .removeClass 'open' .removeClass 'fading' countdown: () -> window.clearTimeout @timer @timer = window.setTimeout => @decline() , @constructor.TOAST_DURATION decline: () -> @element.addClass 'fading' @timer = window.setTimeout => @dismiss() , @constructor.FADING_DURATION restore: () -> @element.removeClass 'fading' window.clearTimeout @timer $.fn.toast = (option) -> key = 'PI:KEY:<KEY>END_PI' this.each -> element = $(this) control = element.data key if not control control = new Toast element element.data key, control control[option].call control if typeof option == 'string' FindTarget = (trigger) -> guide = trigger.attr 'data-target' if guide then $(guide) else trigger.next target $(document) .on 'click touch', '[data-trigger="toast"]', (e) -> e.preventDefault() FindTarget $(this) .toast 'show'
[ { "context": "#@author alteredq / http://alteredqualia.com/\n\nTHREE = require 'thr", "end": 17, "score": 0.6310222148895264, "start": 9, "tag": "NAME", "value": "alteredq" } ]
src/RenderPass.coffee
caranicas/ThreeJS-EffectComposer
0
#@author alteredq / http://alteredqualia.com/ THREE = require 'threejs' class RenderPass constructor:(scene, camera, overrideMaterial, clearColor, clearAlpha) -> @scene = scene @camera = camera @overrideMaterial = overrideMaterial @clearColor = clearColor @clearAlpha = if clearAlpha? then clearAlpha else 1 @oldClearColor = new THREE.Color() @oldClearAlpha = 1 @enabled = true @clear = true @needsSwap = false render:(renderer, writeBuffer, readBuffer, delta) -> @scene.overrideMaterial = @overrideMaterial if @clearColor @oldClearColor.copy( renderer.getClearColor()) @oldClearAlpha = renderer.getClearAlpha() renderer.setClearColor(@clearColor, @clearAlpha) renderer.render(@scene, @camera, readBuffer, @clear) if @clearColor renderer.setClearColor(@oldClearColor, @oldClearAlpha) @scene.overrideMaterial = null
25555
#@author <NAME> / http://alteredqualia.com/ THREE = require 'threejs' class RenderPass constructor:(scene, camera, overrideMaterial, clearColor, clearAlpha) -> @scene = scene @camera = camera @overrideMaterial = overrideMaterial @clearColor = clearColor @clearAlpha = if clearAlpha? then clearAlpha else 1 @oldClearColor = new THREE.Color() @oldClearAlpha = 1 @enabled = true @clear = true @needsSwap = false render:(renderer, writeBuffer, readBuffer, delta) -> @scene.overrideMaterial = @overrideMaterial if @clearColor @oldClearColor.copy( renderer.getClearColor()) @oldClearAlpha = renderer.getClearAlpha() renderer.setClearColor(@clearColor, @clearAlpha) renderer.render(@scene, @camera, readBuffer, @clear) if @clearColor renderer.setClearColor(@oldClearColor, @oldClearAlpha) @scene.overrideMaterial = null
true
#@author PI:NAME:<NAME>END_PI / http://alteredqualia.com/ THREE = require 'threejs' class RenderPass constructor:(scene, camera, overrideMaterial, clearColor, clearAlpha) -> @scene = scene @camera = camera @overrideMaterial = overrideMaterial @clearColor = clearColor @clearAlpha = if clearAlpha? then clearAlpha else 1 @oldClearColor = new THREE.Color() @oldClearAlpha = 1 @enabled = true @clear = true @needsSwap = false render:(renderer, writeBuffer, readBuffer, delta) -> @scene.overrideMaterial = @overrideMaterial if @clearColor @oldClearColor.copy( renderer.getClearColor()) @oldClearAlpha = renderer.getClearAlpha() renderer.setClearColor(@clearColor, @clearAlpha) renderer.render(@scene, @camera, readBuffer, @clear) if @clearColor renderer.setClearColor(@oldClearColor, @oldClearAlpha) @scene.overrideMaterial = null
[ { "context": "L: 'https://api.mypurecloud.ie'\n deploymentKey: 'caa0323a-7079-4d55-b777-c49db1fe1206'\n orgGuid: '77da0b5f-76dd-40b7-a30c-9f14130bc9e9", "end": 172, "score": 0.9997210502624512, "start": 136, "tag": "KEY", "value": "caa0323a-7079-4d55-b777-c49db1fe1206" } ]
source/javascripts/widgets.js.coffee
mark-siggins-genesys/champagne4you
0
window._genesys = widgets: webchat: transport: type: 'purecloud-v2-sockets' dataURL: 'https://api.mypurecloud.ie' deploymentKey: 'caa0323a-7079-4d55-b777-c49db1fe1206' orgGuid: '77da0b5f-76dd-40b7-a30c-9f14130bc9e9' interactionData: routing: targetType: 'QUEUE' targetAddress: 'SalesHotProspects' priority: 2
42029
window._genesys = widgets: webchat: transport: type: 'purecloud-v2-sockets' dataURL: 'https://api.mypurecloud.ie' deploymentKey: '<KEY>' orgGuid: '77da0b5f-76dd-40b7-a30c-9f14130bc9e9' interactionData: routing: targetType: 'QUEUE' targetAddress: 'SalesHotProspects' priority: 2
true
window._genesys = widgets: webchat: transport: type: 'purecloud-v2-sockets' dataURL: 'https://api.mypurecloud.ie' deploymentKey: 'PI:KEY:<KEY>END_PI' orgGuid: '77da0b5f-76dd-40b7-a30c-9f14130bc9e9' interactionData: routing: targetType: 'QUEUE' targetAddress: 'SalesHotProspects' priority: 2
[ { "context": " @example\n # user = App.User.build(firstName: 'Newton')\n # user.get('dirtyAttributes') #=> {firstNam", "end": 1156, "score": 0.9994208812713623, "start": 1150, "tag": "NAME", "value": "Newton" }, { "context": " # user.get('dirtyAttributes') #=> {firstName: 'Ne...
node_modules/tower/packages/tower-model/shared/dirty.coffee
MagicPower2/Power
1
_ = Tower._ # @mixin Tower.ModelDirty = # Returns a hash in the format `{attribute1Name: [oldValue, newValue]}`, # only for the attributes that have different before/after values. # # @return [Object] changes: Ember.computed(-> attributes = @get('attributes') injectChange = (memo, value, key) => memo[key] = [value, @getAttribute(key)]# [value, attributes[key]] # [old, new] memo _.inject(@get('changedAttributes'), injectChange, {}) ).volatile() # The set of attributes sent to the database. # # When the record is new, it is all the attributes except for the `id` # and any attribute with an `undefined` value (`null` values still go to the database). # When the record is being updated, it only sends the attributes that have changed. # # Some properties are set in before create/save/validate hooks, such as `createdAt` and `updatedAt`. # So when `record.get('dirtyAttributes')` is called from inside the `save` method for example, # as it is in the mongodb store, it is going to include those additional properties. # # @example # user = App.User.build(firstName: 'Newton') # user.get('dirtyAttributes') #=> {firstName: 'Newton'} # # @todo should dirtyAttributes include embedded documents? # or should embedded documents be saved after the the parent model saves? # this is the way mongoid does it (the later) dirtyAttributes: Ember.computed(-> if @get('isNew') @attributesForCreate() else @attributesForUpdate() ).volatile() # A hash of the original attributes values before they were changed (if they were changed at all). # # @example # class App.Post extends Tower.Model # @field 'likeCount', type: 'Integer', default: 0 # @field 'title', type: 'String' # @field 'content', type: 'String' # # post = App.Post.build() # post.get('attributes') #=> {id: undefined, likeCount: 0, title: undefined, content: undefined} # post.get('dirtyAttributes') #=> {likeCount: 0} # # Notice that even though there are 'dirty' attributes, there are no changed attributes, # # because the dirty attribute `likeCount` is a default value. # post.get('changedAttributes') #=> {} # # But you can change that: # post.set('likeCount', 1) # post.get('changedAttributes') #=> {likeCount: [0, 1]} # post.set('likeCount', 0) # post.get('changedAttributes') #=> {} # post.set('title', 'First Post') # post.get('changedAttributes') #=> {title: [undefined, 'First Post']} # # @return [Object] changedAttributes: Ember.computed((key, value) -> {} ).cacheable() # Array of changed attribute names. # # @return [Array] changed: Ember.computed(-> _.keys(@get('changedAttributes')) ).volatile() # Returns true if an attribute has changed, false otherwise. # # @return [Boolean] attributeChanged: (name) -> @get('changedAttributes').hasOwnProperty(name) # Returns an array of `[beforeValue, afterValue]` if an attribute has changed, otherwise it returns `undefined`. attributeChange: (name) -> [@get('changedAttributes')[name], @get('attributes')[name]] if @attributeChanged(name) # Returns the previous attribute value, or `undefined`. attributeWas: (name) -> @get('changedAttributes')[name] # Sets the attribute value back to the default (or `undefined` if no value was set). resetAttribute: (key) -> changedAttributes = @get('changedAttributes') attributes = @get('attributes') if changedAttributes.hasOwnProperty(key) value = changedAttributes[key] else value = @_defaultValue(key) @set(key, value) # Returns a hash of all the attributes to be persisted to the database on create. # # It ignores any attribute with a value of `undefined` (but doesn't ignore `null` values). # # @return [Object] attributesForCreate: -> @_attributesForPersistence(@attributeKeysForCreate()) # Returns a hash of all the attributes to be persisted to the database on update. # # It only includes the attributes that have changed since last save. # # @return [Object] attributesForUpdate: (keys) -> @_attributesForPersistence(@attributeKeysForUpdate(keys)) # This should only get the keys which have been defined, so it doesn't insert null values when # it doesn't need to. attributeKeysForCreate: -> primaryKey = 'id' attributes = @get('attributes') result = [] for key, value of attributes result.push(key) unless (key == primaryKey || typeof value == 'undefined') result # This only returns keys for attributes that have changed. attributeKeysForUpdate: (keys) -> primaryKey = 'id' keys ||= _.keys(@get('changedAttributes')) _.select keys, (key) -> key != primaryKey # @private _updateChangedAttribute: (key, value) -> changedAttributes = @get('changedAttributes') # @todo this is not the current attributes... need to get rid of data.unsavedData attributes = @get('attributes') # @todo, need to account for typecasting better if changedAttributes.hasOwnProperty(key) if _.isEqual(changedAttributes[key], value) delete changedAttributes[key] else old = @_clonedValue(attributes[key]) # @readAttribute(key) changedAttributes[key] = old unless _.isEqual(old, value) # if old != value # @private _attributesForPersistence: (keys) -> result = {} attributes = @get('attributes') for key in keys result[key] = attributes[key] result _clonedValue: (value) -> if _.isArray(value) value.concat() else if _.isDate(value) new Date(value.getTime()) else if typeof value == 'object' _.clone(value) else value _defaultValue: (key) -> return field.defaultValue(@) if field = @_getField(key) _getField: (key) -> @constructor.fields()[key] module.exports = Tower.ModelDirty
82212
_ = Tower._ # @mixin Tower.ModelDirty = # Returns a hash in the format `{attribute1Name: [oldValue, newValue]}`, # only for the attributes that have different before/after values. # # @return [Object] changes: Ember.computed(-> attributes = @get('attributes') injectChange = (memo, value, key) => memo[key] = [value, @getAttribute(key)]# [value, attributes[key]] # [old, new] memo _.inject(@get('changedAttributes'), injectChange, {}) ).volatile() # The set of attributes sent to the database. # # When the record is new, it is all the attributes except for the `id` # and any attribute with an `undefined` value (`null` values still go to the database). # When the record is being updated, it only sends the attributes that have changed. # # Some properties are set in before create/save/validate hooks, such as `createdAt` and `updatedAt`. # So when `record.get('dirtyAttributes')` is called from inside the `save` method for example, # as it is in the mongodb store, it is going to include those additional properties. # # @example # user = App.User.build(firstName: '<NAME>') # user.get('dirtyAttributes') #=> {firstName: '<NAME>'} # # @todo should dirtyAttributes include embedded documents? # or should embedded documents be saved after the the parent model saves? # this is the way mongoid does it (the later) dirtyAttributes: Ember.computed(-> if @get('isNew') @attributesForCreate() else @attributesForUpdate() ).volatile() # A hash of the original attributes values before they were changed (if they were changed at all). # # @example # class App.Post extends Tower.Model # @field 'likeCount', type: 'Integer', default: 0 # @field 'title', type: 'String' # @field 'content', type: 'String' # # post = App.Post.build() # post.get('attributes') #=> {id: undefined, likeCount: 0, title: undefined, content: undefined} # post.get('dirtyAttributes') #=> {likeCount: 0} # # Notice that even though there are 'dirty' attributes, there are no changed attributes, # # because the dirty attribute `likeCount` is a default value. # post.get('changedAttributes') #=> {} # # But you can change that: # post.set('likeCount', 1) # post.get('changedAttributes') #=> {likeCount: [0, 1]} # post.set('likeCount', 0) # post.get('changedAttributes') #=> {} # post.set('title', 'First Post') # post.get('changedAttributes') #=> {title: [undefined, 'First Post']} # # @return [Object] changedAttributes: Ember.computed((key, value) -> {} ).cacheable() # Array of changed attribute names. # # @return [Array] changed: Ember.computed(-> _.keys(@get('changedAttributes')) ).volatile() # Returns true if an attribute has changed, false otherwise. # # @return [Boolean] attributeChanged: (name) -> @get('changedAttributes').hasOwnProperty(name) # Returns an array of `[beforeValue, afterValue]` if an attribute has changed, otherwise it returns `undefined`. attributeChange: (name) -> [@get('changedAttributes')[name], @get('attributes')[name]] if @attributeChanged(name) # Returns the previous attribute value, or `undefined`. attributeWas: (name) -> @get('changedAttributes')[name] # Sets the attribute value back to the default (or `undefined` if no value was set). resetAttribute: (key) -> changedAttributes = @get('changedAttributes') attributes = @get('attributes') if changedAttributes.hasOwnProperty(key) value = changedAttributes[key] else value = @_defaultValue(key) @set(key, value) # Returns a hash of all the attributes to be persisted to the database on create. # # It ignores any attribute with a value of `undefined` (but doesn't ignore `null` values). # # @return [Object] attributesForCreate: -> @_attributesForPersistence(@attributeKeysForCreate()) # Returns a hash of all the attributes to be persisted to the database on update. # # It only includes the attributes that have changed since last save. # # @return [Object] attributesForUpdate: (keys) -> @_attributesForPersistence(@attributeKeysForUpdate(keys)) # This should only get the keys which have been defined, so it doesn't insert null values when # it doesn't need to. attributeKeysForCreate: -> primaryKey = 'id' attributes = @get('attributes') result = [] for key, value of attributes result.push(key) unless (key == primaryKey || typeof value == 'undefined') result # This only returns keys for attributes that have changed. attributeKeysForUpdate: (keys) -> primaryKey = 'id' keys ||= _.keys(@get('changedAttributes')) _.select keys, (key) -> key != primaryKey # @private _updateChangedAttribute: (key, value) -> changedAttributes = @get('changedAttributes') # @todo this is not the current attributes... need to get rid of data.unsavedData attributes = @get('attributes') # @todo, need to account for typecasting better if changedAttributes.hasOwnProperty(key) if _.isEqual(changedAttributes[key], value) delete changedAttributes[key] else old = @_clonedValue(attributes[key]) # @readAttribute(key) changedAttributes[key] = old unless _.isEqual(old, value) # if old != value # @private _attributesForPersistence: (keys) -> result = {} attributes = @get('attributes') for key in keys result[key] = attributes[key] result _clonedValue: (value) -> if _.isArray(value) value.concat() else if _.isDate(value) new Date(value.getTime()) else if typeof value == 'object' _.clone(value) else value _defaultValue: (key) -> return field.defaultValue(@) if field = @_getField(key) _getField: (key) -> @constructor.fields()[key] module.exports = Tower.ModelDirty
true
_ = Tower._ # @mixin Tower.ModelDirty = # Returns a hash in the format `{attribute1Name: [oldValue, newValue]}`, # only for the attributes that have different before/after values. # # @return [Object] changes: Ember.computed(-> attributes = @get('attributes') injectChange = (memo, value, key) => memo[key] = [value, @getAttribute(key)]# [value, attributes[key]] # [old, new] memo _.inject(@get('changedAttributes'), injectChange, {}) ).volatile() # The set of attributes sent to the database. # # When the record is new, it is all the attributes except for the `id` # and any attribute with an `undefined` value (`null` values still go to the database). # When the record is being updated, it only sends the attributes that have changed. # # Some properties are set in before create/save/validate hooks, such as `createdAt` and `updatedAt`. # So when `record.get('dirtyAttributes')` is called from inside the `save` method for example, # as it is in the mongodb store, it is going to include those additional properties. # # @example # user = App.User.build(firstName: 'PI:NAME:<NAME>END_PI') # user.get('dirtyAttributes') #=> {firstName: 'PI:NAME:<NAME>END_PI'} # # @todo should dirtyAttributes include embedded documents? # or should embedded documents be saved after the the parent model saves? # this is the way mongoid does it (the later) dirtyAttributes: Ember.computed(-> if @get('isNew') @attributesForCreate() else @attributesForUpdate() ).volatile() # A hash of the original attributes values before they were changed (if they were changed at all). # # @example # class App.Post extends Tower.Model # @field 'likeCount', type: 'Integer', default: 0 # @field 'title', type: 'String' # @field 'content', type: 'String' # # post = App.Post.build() # post.get('attributes') #=> {id: undefined, likeCount: 0, title: undefined, content: undefined} # post.get('dirtyAttributes') #=> {likeCount: 0} # # Notice that even though there are 'dirty' attributes, there are no changed attributes, # # because the dirty attribute `likeCount` is a default value. # post.get('changedAttributes') #=> {} # # But you can change that: # post.set('likeCount', 1) # post.get('changedAttributes') #=> {likeCount: [0, 1]} # post.set('likeCount', 0) # post.get('changedAttributes') #=> {} # post.set('title', 'First Post') # post.get('changedAttributes') #=> {title: [undefined, 'First Post']} # # @return [Object] changedAttributes: Ember.computed((key, value) -> {} ).cacheable() # Array of changed attribute names. # # @return [Array] changed: Ember.computed(-> _.keys(@get('changedAttributes')) ).volatile() # Returns true if an attribute has changed, false otherwise. # # @return [Boolean] attributeChanged: (name) -> @get('changedAttributes').hasOwnProperty(name) # Returns an array of `[beforeValue, afterValue]` if an attribute has changed, otherwise it returns `undefined`. attributeChange: (name) -> [@get('changedAttributes')[name], @get('attributes')[name]] if @attributeChanged(name) # Returns the previous attribute value, or `undefined`. attributeWas: (name) -> @get('changedAttributes')[name] # Sets the attribute value back to the default (or `undefined` if no value was set). resetAttribute: (key) -> changedAttributes = @get('changedAttributes') attributes = @get('attributes') if changedAttributes.hasOwnProperty(key) value = changedAttributes[key] else value = @_defaultValue(key) @set(key, value) # Returns a hash of all the attributes to be persisted to the database on create. # # It ignores any attribute with a value of `undefined` (but doesn't ignore `null` values). # # @return [Object] attributesForCreate: -> @_attributesForPersistence(@attributeKeysForCreate()) # Returns a hash of all the attributes to be persisted to the database on update. # # It only includes the attributes that have changed since last save. # # @return [Object] attributesForUpdate: (keys) -> @_attributesForPersistence(@attributeKeysForUpdate(keys)) # This should only get the keys which have been defined, so it doesn't insert null values when # it doesn't need to. attributeKeysForCreate: -> primaryKey = 'id' attributes = @get('attributes') result = [] for key, value of attributes result.push(key) unless (key == primaryKey || typeof value == 'undefined') result # This only returns keys for attributes that have changed. attributeKeysForUpdate: (keys) -> primaryKey = 'id' keys ||= _.keys(@get('changedAttributes')) _.select keys, (key) -> key != primaryKey # @private _updateChangedAttribute: (key, value) -> changedAttributes = @get('changedAttributes') # @todo this is not the current attributes... need to get rid of data.unsavedData attributes = @get('attributes') # @todo, need to account for typecasting better if changedAttributes.hasOwnProperty(key) if _.isEqual(changedAttributes[key], value) delete changedAttributes[key] else old = @_clonedValue(attributes[key]) # @readAttribute(key) changedAttributes[key] = old unless _.isEqual(old, value) # if old != value # @private _attributesForPersistence: (keys) -> result = {} attributes = @get('attributes') for key in keys result[key] = attributes[key] result _clonedValue: (value) -> if _.isArray(value) value.concat() else if _.isDate(value) new Date(value.getTime()) else if typeof value == 'object' _.clone(value) else value _defaultValue: (key) -> return field.defaultValue(@) if field = @_getField(key) _getField: (key) -> @constructor.fields()[key] module.exports = Tower.ModelDirty
[ { "context": "-08-12\n -\n - AND\n -\n - OR\n -\n name: chethiya\n age:\n comp: gte\n val: 27\n -\n ", "end": 1045, "score": 0.9996650218963623, "start": 1037, "tag": "NAME", "value": "chethiya" }, { "context": "-\n school: Devi Balika\n\n record...
browser_test.coffee
chethiya/sexprs_logic
0
window.test = -> N = 1000000 cond = o.condition records = o.records test = SExprsLogic.compile cond test2 = SExprsLogic.compileByBind cond #console.log test.toString() #console.log cond[3][2] #college regex #console.log records[2] #college record console.log "Testing compile" d = new Date() res = '' for i in [0...N] res = '' + test records[i%records.length] console.log "Test ans: #{res}, time: #{(new Date() - d) / 1000}sec" console.log "Testing compile by bind" d = new Date() res = '' for i in [0...N] res = '' + test2 records[i%records.length] console.log "Test ans: #{res}, time: #{(new Date() - d) / 1000}sec" console.log "Testing test" d = new Date() res = '' for i in [0...N] res = '' + SExprsLogic.test cond, records[i%records.length] console.log "Test ans: #{res}, time: #{(new Date() - d) / 1000}sec" return yaml = """ condition: - OR - meta.dataset: employee - one.two.three.four.five: 5 - date: comp: is val: 2014-08-12 - - AND - - OR - name: chethiya age: comp: gte val: 27 - name: comp: is val: gangani - address: comp: regex val: '^[0-9]+' - age: comp: lt val: 27 - - OR - school: comp: regex val: '^".*[Cc]ollege"$' - school: Devi Balika records: - name: chethiya age: 27 address: 23A, Ella way, Kurunegala school: Maliyadeva College - name: gangani age: 26 address: homagama school: Devi Balika - name: tharaka age: 33 address: 02342, Oman school: '"Maliyadeva College"' - {} - meta: dataset: 'employee' - one: 1 two: 1 - one: two: three: four: five: 5 - date: 2014-08-12 - date: 2014-08-13 """ o = YAML.parse yaml
65561
window.test = -> N = 1000000 cond = o.condition records = o.records test = SExprsLogic.compile cond test2 = SExprsLogic.compileByBind cond #console.log test.toString() #console.log cond[3][2] #college regex #console.log records[2] #college record console.log "Testing compile" d = new Date() res = '' for i in [0...N] res = '' + test records[i%records.length] console.log "Test ans: #{res}, time: #{(new Date() - d) / 1000}sec" console.log "Testing compile by bind" d = new Date() res = '' for i in [0...N] res = '' + test2 records[i%records.length] console.log "Test ans: #{res}, time: #{(new Date() - d) / 1000}sec" console.log "Testing test" d = new Date() res = '' for i in [0...N] res = '' + SExprsLogic.test cond, records[i%records.length] console.log "Test ans: #{res}, time: #{(new Date() - d) / 1000}sec" return yaml = """ condition: - OR - meta.dataset: employee - one.two.three.four.five: 5 - date: comp: is val: 2014-08-12 - - AND - - OR - name: <NAME> age: comp: gte val: 27 - name: comp: is val: gangani - address: comp: regex val: '^[0-9]+' - age: comp: lt val: 27 - - OR - school: comp: regex val: '^".*[Cc]ollege"$' - school: Devi Balika records: - name: <NAME> age: 27 address: 23A, E<NAME>, Kurunegala school: Maliyadeva College - name: <NAME> age: 26 address: homagama school: Devi Balika - name: <NAME> age: 33 address: 02342, Oman school: '"Maliyadeva College"' - {} - meta: dataset: 'employee' - one: 1 two: 1 - one: two: three: four: five: 5 - date: 2014-08-12 - date: 2014-08-13 """ o = YAML.parse yaml
true
window.test = -> N = 1000000 cond = o.condition records = o.records test = SExprsLogic.compile cond test2 = SExprsLogic.compileByBind cond #console.log test.toString() #console.log cond[3][2] #college regex #console.log records[2] #college record console.log "Testing compile" d = new Date() res = '' for i in [0...N] res = '' + test records[i%records.length] console.log "Test ans: #{res}, time: #{(new Date() - d) / 1000}sec" console.log "Testing compile by bind" d = new Date() res = '' for i in [0...N] res = '' + test2 records[i%records.length] console.log "Test ans: #{res}, time: #{(new Date() - d) / 1000}sec" console.log "Testing test" d = new Date() res = '' for i in [0...N] res = '' + SExprsLogic.test cond, records[i%records.length] console.log "Test ans: #{res}, time: #{(new Date() - d) / 1000}sec" return yaml = """ condition: - OR - meta.dataset: employee - one.two.three.four.five: 5 - date: comp: is val: 2014-08-12 - - AND - - OR - name: PI:NAME:<NAME>END_PI age: comp: gte val: 27 - name: comp: is val: gangani - address: comp: regex val: '^[0-9]+' - age: comp: lt val: 27 - - OR - school: comp: regex val: '^".*[Cc]ollege"$' - school: Devi Balika records: - name: PI:NAME:<NAME>END_PI age: 27 address: 23A, EPI:NAME:<NAME>END_PI, Kurunegala school: Maliyadeva College - name: PI:NAME:<NAME>END_PI age: 26 address: homagama school: Devi Balika - name: PI:NAME:<NAME>END_PI age: 33 address: 02342, Oman school: '"Maliyadeva College"' - {} - meta: dataset: 'employee' - one: 1 two: 1 - one: two: three: four: five: 5 - date: 2014-08-12 - date: 2014-08-13 """ o = YAML.parse yaml
[ { "context": "rection=<top|botton>][&limit=<10>]\n#\n# Author:\n# ajacksified\n\n\n_ = require('underscore')\nclark = require('clar", "end": 1355, "score": 0.9996775388717651, "start": 1344, "tag": "USERNAME", "value": "ajacksified" }, { "context": " # allow for spaces after the t...
src/plusplus.coffee
jcc333/plusplus-hubot
0
# Description: # Give or take away points. Keeps track and even prints out graphs. # # Dependencies: # "underscore": ">= 1.0.0" # "clark": "0.0.6" # # Configuration: # HUBOT_PLUSPLUS_KEYWORD: the keyword that will make hubot give the # score for a name and the reasons. For example you can set this to # "score|karma" so hubot will answer to both keywords. # If not provided will default to 'score'. # # HUBOT_PLUSPLUS_REASON_CONJUNCTIONS: a pipe separated list of conjuntions to # be used when specifying reasons. The default value is # "for|because|cause|cuz|as", so it can be used like: # "foo++ for being awesome" or "foo++ cuz they are awesome". # # Commands: # <name>++ [<reason>] - Increment score for a name (for a reason) # <name>-- [<reason>] - Decrement score for a name (for a reason) # ++<name> [<reason>] - Fast Increment score for a name (for a reason) # --<name> [<reason>] - Fast Decrement score for a name (for a reason) # hubot score <name> - Display the score for a name and some of the reasons # hubot top <amount> - Display the top scoring <amount> # hubot bottom <amount> - Display the bottom scoring <amount> # hubot erase <name> [<reason>] - Remove the score for a name (for a reason) # # URLs: # /hubot/scores[?name=<name>][&direction=<top|botton>][&limit=<10>] # # Author: # ajacksified _ = require('underscore') clark = require('clark') querystring = require('querystring') ScoreKeeper = require('./scorekeeper') module.exports = (robot) -> scoreKeeper = new ScoreKeeper(robot) scoreKeyword = process.env.HUBOT_PLUSPLUS_KEYWORD or 'score' reasonsKeyword = process.env.HUBOT_PLUSPLUS_REASONS or 'raisins' reasonConjunctions = process.env.HUBOT_PLUSPLUS_CONJUNCTIONS or 'for|because|cause|cuz|as' # preincrementing to use in-place assignment for better performance robot.hear /// # from beginning of line ^ # the increment/decrement operator ++ or -- (\+\+|--|—) # the thing being upvoted, which is any number of words and spaces ([\s\w'@.\-:\u3040-\u30FF\uFF01-\uFF60\u4E00-\u9FA0]*) # allow for spaces after the thing being upvoted (@user ++) \s* # optional reason for the plusplus (?:\s+(?:#{reasonConjunctions})\s+(.+))? $ # end of line ///i, (msg) -> # let's get our local vars in place [dummy, operator, name, reason] = msg.match from = msg.message.user.name.toLowerCase() room = msg.message.room # do some sanitizing reason = reason?.trim().toLowerCase() if name if name.charAt(0) == ':' name = (name.replace /(^\s*@)|([,\s]*$)/g, '').trim().toLowerCase() else name = (name.replace /(^\s*@)|([,:\s]*$)/g, '').trim().toLowerCase() # check whether a name was specified. use MRU if not unless name? && name != '' [name, lastReason] = scoreKeeper.last(room) reason = lastReason if !reason? && lastReason? # do the {up, down}vote, and figure out what the new score is [score, reasonScore] = if operator == "++" scoreKeeper.add(name, from, room, reason) else scoreKeeper.subtract(name, from, room, reason) # if we got a score, then display all the things and fire off events! if score? message = if reason? if reasonScore == 1 or reasonScore == -1 if score == 1 or score == -1 "#{name} has #{score} point for #{reason}." else "#{name} has #{score} points, #{reasonScore} of which is for #{reason}." else "#{name} has #{score} points, #{reasonScore} of which are for #{reason}." else if score == 1 "#{name} has #{score} point" else "#{name} has #{score} points" msg.send message robot.emit "plus-one", { name: name direction: operator room: room reason: reason from: from } # sweet regex bro robot.hear /// # from beginning of line ^ # the thing being upvoted, which is any number of words and spaces ([\s\w'@.\-:\u3040-\u30FF\uFF01-\uFF60\u4E00-\u9FA0]*) # allow for spaces after the thing being upvoted (@user ++) \s* # the increment/decrement operator ++ or -- (\+\+|--|—) # optional reason for the plusplus (?:\s+(?:#{reasonConjunctions})\s+(.+))? $ # end of line ///i, (msg) -> # let's get our local vars in place [dummy, name, operator, reason] = msg.match from = msg.message.user.name.toLowerCase() room = msg.message.room # do some sanitizing reason = reason?.trim().toLowerCase() if name if name.charAt(0) == ':' name = (name.replace /(^\s*@)|([,\s]*$)/g, '').trim().toLowerCase() else name = (name.replace /(^\s*@)|([,:\s]*$)/g, '').trim().toLowerCase() # check whether a name was specified. use MRU if not unless name? && name != '' [name, lastReason] = scoreKeeper.last(room) reason = lastReason if !reason? && lastReason? # do the {up, down}vote, and figure out what the new score is [score, reasonScore] = if operator == "++" scoreKeeper.add(name, from, room, reason) else scoreKeeper.subtract(name, from, room, reason) # if we got a score, then display all the things and fire off events! if score? message = if reason? if reasonScore == 1 or reasonScore == -1 if score == 1 or score == -1 "#{name} has #{score} point for #{reason}." else "#{name} has #{score} points, #{reasonScore} of which is for #{reason}." else "#{name} has #{score} points, #{reasonScore} of which are for #{reason}." else if score == 1 "#{name} has #{score} point" else "#{name} has #{score} points" msg.send message robot.emit "plus-one", { name: name direction: operator room: room reason: reason from: from } robot.respond /// (?:erase ) # thing to be erased ([\s\w'@.-:\u3040-\u30FF\uFF01-\uFF60\u4E00-\u9FA0]*) # optionally erase a reason from thing (?:\s+(?:for|because|cause|cuz)\s+(.+))? $ # eol ///i, (msg) -> [__, name, reason] = msg.match from = msg.message.user.name.toLowerCase() user = msg.envelope.user room = msg.message.room reason = reason?.trim().toLowerCase() if name if name.charAt(0) == ':' name = (name.replace /(^\s*@)|([,\s]*$)/g, '').trim().toLowerCase() else name = (name.replace /(^\s*@)|([,:\s]*$)/g, '').trim().toLowerCase() isAdmin = @robot.auth?.hasRole(user, 'plusplus-admin') or @robot.auth?.hasRole(user, 'admin') if not @robot.auth? or isAdmin erased = scoreKeeper.erase(name, from, room, reason) else return msg.reply "Sorry, you don't have authorization to do that." if erased? message = if reason? "Erased the following reason from #{name}: #{reason}" else "Erased points for #{name}" msg.send message # Catch the message asking for the score. robot.respond new RegExp("(?:" + scoreKeyword + ") (for\s)?(.*)", "i"), (msg) -> name = msg.match[2].trim().toLowerCase() if name if name.charAt(0) == ':' name = (name.replace /(^\s*@)|([,\s]*$)/g, '') else name = (name.replace /(^\s*@)|([,:\s]*$)/g, '') console.log(name) score = scoreKeeper.scoreForUser(name) reasons = scoreKeeper.reasonsForUser(name) reasonString = if typeof reasons == 'object' && Object.keys(reasons).length > 0 "#{name} has #{score} points. Here are some #{reasonsKeyword}:" + _.reduce(reasons, (memo, val, key) -> memo += "\n#{key}: #{val} points" , "") else "#{name} has #{score} points." msg.send reasonString robot.respond /(top|bottom) (\d+)/i, (msg) -> amount = parseInt(msg.match[2]) || 10 message = [] tops = scoreKeeper[msg.match[1]](amount) if tops.length > 0 for i in [0..tops.length-1] message.push("#{i+1}. #{tops[i].name} : #{tops[i].score}") else message.push("No scores to keep track of yet!") if(msg.match[1] == "top") graphSize = Math.min(tops.length, Math.min(amount, 20)) message.splice(0, 0, clark(_.first(_.pluck(tops, "score"), graphSize))) msg.send message.join("\n") robot.router.get "/#{robot.name}/normalize-points", (req, res) -> scoreKeeper.normalize((score) -> if score > 0 score = score - Math.ceil(score / 10) else if score < 0 score = score - Math.floor(score / 10) score ) res.end JSON.stringify('done') robot.router.get "/#{robot.name}/scores", (req, res) -> query = querystring.parse(req._parsedUrl.query) if query.name obj = {} obj[query.name] = scoreKeeper.scoreForUser(query.name) res.end JSON.stringify(obj) else direction = query.direction || "top" amount = query.limit || 10 tops = scoreKeeper[direction](amount) res.end JSON.stringify(tops, null, 2)
29569
# Description: # Give or take away points. Keeps track and even prints out graphs. # # Dependencies: # "underscore": ">= 1.0.0" # "clark": "0.0.6" # # Configuration: # HUBOT_PLUSPLUS_KEYWORD: the keyword that will make hubot give the # score for a name and the reasons. For example you can set this to # "score|karma" so hubot will answer to both keywords. # If not provided will default to 'score'. # # HUBOT_PLUSPLUS_REASON_CONJUNCTIONS: a pipe separated list of conjuntions to # be used when specifying reasons. The default value is # "for|because|cause|cuz|as", so it can be used like: # "foo++ for being awesome" or "foo++ cuz they are awesome". # # Commands: # <name>++ [<reason>] - Increment score for a name (for a reason) # <name>-- [<reason>] - Decrement score for a name (for a reason) # ++<name> [<reason>] - Fast Increment score for a name (for a reason) # --<name> [<reason>] - Fast Decrement score for a name (for a reason) # hubot score <name> - Display the score for a name and some of the reasons # hubot top <amount> - Display the top scoring <amount> # hubot bottom <amount> - Display the bottom scoring <amount> # hubot erase <name> [<reason>] - Remove the score for a name (for a reason) # # URLs: # /hubot/scores[?name=<name>][&direction=<top|botton>][&limit=<10>] # # Author: # ajacksified _ = require('underscore') clark = require('clark') querystring = require('querystring') ScoreKeeper = require('./scorekeeper') module.exports = (robot) -> scoreKeeper = new ScoreKeeper(robot) scoreKeyword = process.env.HUBOT_PLUSPLUS_KEYWORD or 'score' reasonsKeyword = process.env.HUBOT_PLUSPLUS_REASONS or 'raisins' reasonConjunctions = process.env.HUBOT_PLUSPLUS_CONJUNCTIONS or 'for|because|cause|cuz|as' # preincrementing to use in-place assignment for better performance robot.hear /// # from beginning of line ^ # the increment/decrement operator ++ or -- (\+\+|--|—) # the thing being upvoted, which is any number of words and spaces ([\s\w'@.\-:\u3040-\u30FF\uFF01-\uFF60\u4E00-\u9FA0]*) # allow for spaces after the thing being upvoted (@user ++) \s* # optional reason for the plusplus (?:\s+(?:#{reasonConjunctions})\s+(.+))? $ # end of line ///i, (msg) -> # let's get our local vars in place [dummy, operator, name, reason] = msg.match from = msg.message.user.name.toLowerCase() room = msg.message.room # do some sanitizing reason = reason?.trim().toLowerCase() if name if name.charAt(0) == ':' name = (name.replace /(^\s*@)|([,\s]*$)/g, '').trim().toLowerCase() else name = (name.replace /(^\s*@)|([,:\s]*$)/g, '').trim().toLowerCase() # check whether a name was specified. use MRU if not unless name? && name != '' [name, lastReason] = scoreKeeper.last(room) reason = lastReason if !reason? && lastReason? # do the {up, down}vote, and figure out what the new score is [score, reasonScore] = if operator == "++" scoreKeeper.add(name, from, room, reason) else scoreKeeper.subtract(name, from, room, reason) # if we got a score, then display all the things and fire off events! if score? message = if reason? if reasonScore == 1 or reasonScore == -1 if score == 1 or score == -1 "#{name} has #{score} point for #{reason}." else "#{name} has #{score} points, #{reasonScore} of which is for #{reason}." else "#{name} has #{score} points, #{reasonScore} of which are for #{reason}." else if score == 1 "#{name} has #{score} point" else "#{name} has #{score} points" msg.send message robot.emit "plus-one", { name: name direction: operator room: room reason: reason from: from } # sweet regex bro robot.hear /// # from beginning of line ^ # the thing being upvoted, which is any number of words and spaces ([\s\w'@.\-:\u3040-\u30FF\uFF01-\uFF60\u4E00-\u9FA0]*) # allow for spaces after the thing being upvoted (@user ++) \s* # the increment/decrement operator ++ or -- (\+\+|--|—) # optional reason for the plusplus (?:\s+(?:#{reasonConjunctions})\s+(.+))? $ # end of line ///i, (msg) -> # let's get our local vars in place [dummy, name, operator, reason] = msg.match from = msg.message.user.name.toLowerCase() room = msg.message.room # do some sanitizing reason = reason?.trim().toLowerCase() if name if name.charAt(0) == ':' name = (name.replace /(^\s*@)|([,\s]*$)/g, '').trim().toLowerCase() else name = (name.replace /(^\s*@)|([,:\s]*$)/g, '').trim().toLowerCase() # check whether a name was specified. use MRU if not unless name? && name != '' [name, lastReason] = scoreKeeper.last(room) reason = lastReason if !reason? && lastReason? # do the {up, down}vote, and figure out what the new score is [score, reasonScore] = if operator == "++" scoreKeeper.add(name, from, room, reason) else scoreKeeper.subtract(name, from, room, reason) # if we got a score, then display all the things and fire off events! if score? message = if reason? if reasonScore == 1 or reasonScore == -1 if score == 1 or score == -1 "#{name} has #{score} point for #{reason}." else "#{name} has #{score} points, #{reasonScore} of which is for #{reason}." else "#{name} has #{score} points, #{reasonScore} of which are for #{reason}." else if score == 1 "#{name} has #{score} point" else "#{name} has #{score} points" msg.send message robot.emit "plus-one", { name: <NAME> direction: operator room: room reason: reason from: from } robot.respond /// (?:erase ) # thing to be erased ([\s\w'@.-:\u3040-\u30FF\uFF01-\uFF60\u4E00-\u9FA0]*) # optionally erase a reason from thing (?:\s+(?:for|because|cause|cuz)\s+(.+))? $ # eol ///i, (msg) -> [__, name, reason] = msg.match from = msg.message.user.name.toLowerCase() user = msg.envelope.user room = msg.message.room reason = reason?.trim().toLowerCase() if name if name.charAt(0) == ':' name = (name.replace /(^\s*@)|([,\s]*$)/g, '').trim().toLowerCase() else name = (name.replace /(^\s*@)|([,:\s]*$)/g, '').trim().toLowerCase() isAdmin = @robot.auth?.hasRole(user, 'plusplus-admin') or @robot.auth?.hasRole(user, 'admin') if not @robot.auth? or isAdmin erased = scoreKeeper.erase(name, from, room, reason) else return msg.reply "Sorry, you don't have authorization to do that." if erased? message = if reason? "Erased the following reason from #{name}: #{reason}" else "Erased points for #{name}" msg.send message # Catch the message asking for the score. robot.respond new RegExp("(?:" + scoreKeyword + ") (for\s)?(.*)", "i"), (msg) -> name = msg.match[2].trim().toLowerCase() if name if name.charAt(0) == ':' name = (name.replace /(^\s*@)|([,\s]*$)/g, '') else name = (name.replace /(^\s*@)|([,:\s]*$)/g, '') console.log(name) score = scoreKeeper.scoreForUser(name) reasons = scoreKeeper.reasonsForUser(name) reasonString = if typeof reasons == 'object' && Object.keys(reasons).length > 0 "#{name} has #{score} points. Here are some #{reasonsKeyword}:" + _.reduce(reasons, (memo, val, key) -> memo += "\n#{key}: #{val} points" , "") else "#{name} has #{score} points." msg.send reasonString robot.respond /(top|bottom) (\d+)/i, (msg) -> amount = parseInt(msg.match[2]) || 10 message = [] tops = scoreKeeper[msg.match[1]](amount) if tops.length > 0 for i in [0..tops.length-1] message.push("#{i+1}. #{tops[i].name} : #{tops[i].score}") else message.push("No scores to keep track of yet!") if(msg.match[1] == "top") graphSize = Math.min(tops.length, Math.min(amount, 20)) message.splice(0, 0, clark(_.first(_.pluck(tops, "score"), graphSize))) msg.send message.join("\n") robot.router.get "/#{robot.name}/normalize-points", (req, res) -> scoreKeeper.normalize((score) -> if score > 0 score = score - Math.ceil(score / 10) else if score < 0 score = score - Math.floor(score / 10) score ) res.end JSON.stringify('done') robot.router.get "/#{robot.name}/scores", (req, res) -> query = querystring.parse(req._parsedUrl.query) if query.name obj = {} obj[query.name] = scoreKeeper.scoreForUser(query.name) res.end JSON.stringify(obj) else direction = query.direction || "top" amount = query.limit || 10 tops = scoreKeeper[direction](amount) res.end JSON.stringify(tops, null, 2)
true
# Description: # Give or take away points. Keeps track and even prints out graphs. # # Dependencies: # "underscore": ">= 1.0.0" # "clark": "0.0.6" # # Configuration: # HUBOT_PLUSPLUS_KEYWORD: the keyword that will make hubot give the # score for a name and the reasons. For example you can set this to # "score|karma" so hubot will answer to both keywords. # If not provided will default to 'score'. # # HUBOT_PLUSPLUS_REASON_CONJUNCTIONS: a pipe separated list of conjuntions to # be used when specifying reasons. The default value is # "for|because|cause|cuz|as", so it can be used like: # "foo++ for being awesome" or "foo++ cuz they are awesome". # # Commands: # <name>++ [<reason>] - Increment score for a name (for a reason) # <name>-- [<reason>] - Decrement score for a name (for a reason) # ++<name> [<reason>] - Fast Increment score for a name (for a reason) # --<name> [<reason>] - Fast Decrement score for a name (for a reason) # hubot score <name> - Display the score for a name and some of the reasons # hubot top <amount> - Display the top scoring <amount> # hubot bottom <amount> - Display the bottom scoring <amount> # hubot erase <name> [<reason>] - Remove the score for a name (for a reason) # # URLs: # /hubot/scores[?name=<name>][&direction=<top|botton>][&limit=<10>] # # Author: # ajacksified _ = require('underscore') clark = require('clark') querystring = require('querystring') ScoreKeeper = require('./scorekeeper') module.exports = (robot) -> scoreKeeper = new ScoreKeeper(robot) scoreKeyword = process.env.HUBOT_PLUSPLUS_KEYWORD or 'score' reasonsKeyword = process.env.HUBOT_PLUSPLUS_REASONS or 'raisins' reasonConjunctions = process.env.HUBOT_PLUSPLUS_CONJUNCTIONS or 'for|because|cause|cuz|as' # preincrementing to use in-place assignment for better performance robot.hear /// # from beginning of line ^ # the increment/decrement operator ++ or -- (\+\+|--|—) # the thing being upvoted, which is any number of words and spaces ([\s\w'@.\-:\u3040-\u30FF\uFF01-\uFF60\u4E00-\u9FA0]*) # allow for spaces after the thing being upvoted (@user ++) \s* # optional reason for the plusplus (?:\s+(?:#{reasonConjunctions})\s+(.+))? $ # end of line ///i, (msg) -> # let's get our local vars in place [dummy, operator, name, reason] = msg.match from = msg.message.user.name.toLowerCase() room = msg.message.room # do some sanitizing reason = reason?.trim().toLowerCase() if name if name.charAt(0) == ':' name = (name.replace /(^\s*@)|([,\s]*$)/g, '').trim().toLowerCase() else name = (name.replace /(^\s*@)|([,:\s]*$)/g, '').trim().toLowerCase() # check whether a name was specified. use MRU if not unless name? && name != '' [name, lastReason] = scoreKeeper.last(room) reason = lastReason if !reason? && lastReason? # do the {up, down}vote, and figure out what the new score is [score, reasonScore] = if operator == "++" scoreKeeper.add(name, from, room, reason) else scoreKeeper.subtract(name, from, room, reason) # if we got a score, then display all the things and fire off events! if score? message = if reason? if reasonScore == 1 or reasonScore == -1 if score == 1 or score == -1 "#{name} has #{score} point for #{reason}." else "#{name} has #{score} points, #{reasonScore} of which is for #{reason}." else "#{name} has #{score} points, #{reasonScore} of which are for #{reason}." else if score == 1 "#{name} has #{score} point" else "#{name} has #{score} points" msg.send message robot.emit "plus-one", { name: name direction: operator room: room reason: reason from: from } # sweet regex bro robot.hear /// # from beginning of line ^ # the thing being upvoted, which is any number of words and spaces ([\s\w'@.\-:\u3040-\u30FF\uFF01-\uFF60\u4E00-\u9FA0]*) # allow for spaces after the thing being upvoted (@user ++) \s* # the increment/decrement operator ++ or -- (\+\+|--|—) # optional reason for the plusplus (?:\s+(?:#{reasonConjunctions})\s+(.+))? $ # end of line ///i, (msg) -> # let's get our local vars in place [dummy, name, operator, reason] = msg.match from = msg.message.user.name.toLowerCase() room = msg.message.room # do some sanitizing reason = reason?.trim().toLowerCase() if name if name.charAt(0) == ':' name = (name.replace /(^\s*@)|([,\s]*$)/g, '').trim().toLowerCase() else name = (name.replace /(^\s*@)|([,:\s]*$)/g, '').trim().toLowerCase() # check whether a name was specified. use MRU if not unless name? && name != '' [name, lastReason] = scoreKeeper.last(room) reason = lastReason if !reason? && lastReason? # do the {up, down}vote, and figure out what the new score is [score, reasonScore] = if operator == "++" scoreKeeper.add(name, from, room, reason) else scoreKeeper.subtract(name, from, room, reason) # if we got a score, then display all the things and fire off events! if score? message = if reason? if reasonScore == 1 or reasonScore == -1 if score == 1 or score == -1 "#{name} has #{score} point for #{reason}." else "#{name} has #{score} points, #{reasonScore} of which is for #{reason}." else "#{name} has #{score} points, #{reasonScore} of which are for #{reason}." else if score == 1 "#{name} has #{score} point" else "#{name} has #{score} points" msg.send message robot.emit "plus-one", { name: PI:NAME:<NAME>END_PI direction: operator room: room reason: reason from: from } robot.respond /// (?:erase ) # thing to be erased ([\s\w'@.-:\u3040-\u30FF\uFF01-\uFF60\u4E00-\u9FA0]*) # optionally erase a reason from thing (?:\s+(?:for|because|cause|cuz)\s+(.+))? $ # eol ///i, (msg) -> [__, name, reason] = msg.match from = msg.message.user.name.toLowerCase() user = msg.envelope.user room = msg.message.room reason = reason?.trim().toLowerCase() if name if name.charAt(0) == ':' name = (name.replace /(^\s*@)|([,\s]*$)/g, '').trim().toLowerCase() else name = (name.replace /(^\s*@)|([,:\s]*$)/g, '').trim().toLowerCase() isAdmin = @robot.auth?.hasRole(user, 'plusplus-admin') or @robot.auth?.hasRole(user, 'admin') if not @robot.auth? or isAdmin erased = scoreKeeper.erase(name, from, room, reason) else return msg.reply "Sorry, you don't have authorization to do that." if erased? message = if reason? "Erased the following reason from #{name}: #{reason}" else "Erased points for #{name}" msg.send message # Catch the message asking for the score. robot.respond new RegExp("(?:" + scoreKeyword + ") (for\s)?(.*)", "i"), (msg) -> name = msg.match[2].trim().toLowerCase() if name if name.charAt(0) == ':' name = (name.replace /(^\s*@)|([,\s]*$)/g, '') else name = (name.replace /(^\s*@)|([,:\s]*$)/g, '') console.log(name) score = scoreKeeper.scoreForUser(name) reasons = scoreKeeper.reasonsForUser(name) reasonString = if typeof reasons == 'object' && Object.keys(reasons).length > 0 "#{name} has #{score} points. Here are some #{reasonsKeyword}:" + _.reduce(reasons, (memo, val, key) -> memo += "\n#{key}: #{val} points" , "") else "#{name} has #{score} points." msg.send reasonString robot.respond /(top|bottom) (\d+)/i, (msg) -> amount = parseInt(msg.match[2]) || 10 message = [] tops = scoreKeeper[msg.match[1]](amount) if tops.length > 0 for i in [0..tops.length-1] message.push("#{i+1}. #{tops[i].name} : #{tops[i].score}") else message.push("No scores to keep track of yet!") if(msg.match[1] == "top") graphSize = Math.min(tops.length, Math.min(amount, 20)) message.splice(0, 0, clark(_.first(_.pluck(tops, "score"), graphSize))) msg.send message.join("\n") robot.router.get "/#{robot.name}/normalize-points", (req, res) -> scoreKeeper.normalize((score) -> if score > 0 score = score - Math.ceil(score / 10) else if score < 0 score = score - Math.floor(score / 10) score ) res.end JSON.stringify('done') robot.router.get "/#{robot.name}/scores", (req, res) -> query = querystring.parse(req._parsedUrl.query) if query.name obj = {} obj[query.name] = scoreKeeper.scoreForUser(query.name) res.end JSON.stringify(obj) else direction = query.direction || "top" amount = query.limit || 10 tops = scoreKeeper[direction](amount) res.end JSON.stringify(tops, null, 2)
[ { "context": "mbers', ->\n expect(@Helper.isEmailAddress \"office.vidatio@vidatio.de\" ).toBeTruthy()\n expect(@Helper.isEmailAdd", "end": 9904, "score": 0.9999105930328369, "start": 9879, "tag": "EMAIL", "value": "office.vidatio@vidatio.de" }, { "context": "BeTruthy()\...
app/components/helper/helper-test.coffee
vidatio/web-app
0
"use strict" describe "Service Helper", -> beforeEach -> @Helper = new window.vidatio.Helper() it 'should recognize wgs84 degree decimal coordinates correctly', -> # with leading sign coordinate = "0" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "-180" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "180" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() # with classification at the front coordinate = "N 0" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "N 90" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "S 0" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "S 90" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "E 0" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "E 180" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "W 0" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "W 180" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() # with classification at the end coordinate = "0 N" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "90 N" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "0 S" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "90 S" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "0 E" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "180 E" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "0 W" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "180 W" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() # with degree symbol coordinate = "0°" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "-180°" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "W 180°" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "180° W" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() # without space between classification and decimal number coordinate = "N0" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "N90" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "0S" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "90S" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "E0" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "E180" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "0W" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "180W" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "181" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeFalsy() coordinate = "-181" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeFalsy() coordinate = "N -90" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeFalsy() coordinate = "N 91" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeFalsy() coordinate = "S -90" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeFalsy() coordinate = "S 91" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeFalsy() coordinate = "E -180" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeFalsy() coordinate = "E 181" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeFalsy() coordinate = "W -180" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeFalsy() coordinate = "W 181" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeFalsy() it 'should recognize wgs84 degree decimal minutes coordinates correctly', -> coordinate = "180 59" expect(@Helper.isCoordinateWGS84DegreeDecimalMinutes(coordinate)).toBeTruthy() coordinate = "E180 59" expect(@Helper.isCoordinateWGS84DegreeDecimalMinutes(coordinate)).toBeTruthy() coordinate = "N 90 0" expect(@Helper.isCoordinateWGS84DegreeDecimalMinutes(coordinate)).toBeTruthy() coordinate = "W 180° 59.999" expect(@Helper.isCoordinateWGS84DegreeDecimalMinutes(coordinate)).toBeTruthy() coordinate = "180° 59.999 W" expect(@Helper.isCoordinateWGS84DegreeDecimalMinutes(coordinate)).toBeTruthy() coordinate = "180" expect(@Helper.isCoordinateWGS84DegreeDecimalMinutes(coordinate)).toBeFalsy() coordinate = "181W 59.999" expect(@Helper.isCoordinateWGS84DegreeDecimalMinutes(coordinate)).toBeFalsy() coordinate = "W 0° 60" expect(@Helper.isCoordinateWGS84DegreeDecimalMinutes(coordinate)).toBeFalsy() coordinate = "S 90° 61" expect(@Helper.isCoordinateWGS84DegreeDecimalMinutes(coordinate)).toBeFalsy() it 'should recognize wgs84 degree decimal minutes seconds coordinates correctly', -> coordinate = "180° 59' 0''" expect(@Helper.isCoordinateWGS84DegreeDecimalMinutesSeconds(coordinate)).toBeTruthy() coordinate = "E180 59 50" expect(@Helper.isCoordinateWGS84DegreeDecimalMinutesSeconds(coordinate)).toBeTruthy() coordinate = "N 90 59 59.999" expect(@Helper.isCoordinateWGS84DegreeDecimalMinutesSeconds(coordinate)).toBeTruthy() coordinate = "180° 1 59.999 W" expect(@Helper.isCoordinateWGS84DegreeDecimalMinutesSeconds(coordinate)).toBeTruthy() coordinate = "180 59" expect(@Helper.isCoordinateWGS84DegreeDecimalMinutesSeconds(coordinate)).toBeFalsy() coordinate = "180 59.1 50" expect(@Helper.isCoordinateWGS84DegreeDecimalMinutesSeconds(coordinate)).toBeFalsy() coordinate = "180° 59.1 50" expect(@Helper.isCoordinateWGS84DegreeDecimalMinutesSeconds(coordinate)).toBeFalsy() coordinate = "S 180° 59 60" expect(@Helper.isCoordinateWGS84DegreeDecimalMinutesSeconds(coordinate)).toBeFalsy() it "should remove null values of a two dimensional array", -> dataset = [ [ null, null, null, null, null ] [ null, "true", "false", null, null ] [ null, "true", "false", null, null ] [ null, null, null, null, null ] ] result = [ [ "true", "false" ] [ "true", "false" ] ] expect(@Helper.trimDataset(dataset).trimmedDataset).toEqual result it "should create a matrix with the initial value", -> dataset = [ [ "true", "true", "true" ] [ "true", "true", "true" ] [ "true", "true", "true" ] ] result = [ [ true, true, true ] [ true, true, true ] [ true, true, true ] ] expect(@Helper.createMatrix dataset, true).toEqual result it "should check if a value is a number", -> expect(@Helper.isNumber 3.14159).toBeTruthy() expect(@Helper.isNumber 180).toBeTruthy() expect(@Helper.isNumber -42).toBeTruthy() expect(@Helper.isNumber "Test").toBeFalsy() expect(@Helper.isNumber undefined).toBeFalsy() expect(@Helper.isNumber null).toBeFalsy() expect(@Helper.isNumber true).toBeFalsy() it "should return a subset of the dataset", -> dataset = [] while dataset.length < 20 dataset.push [ "test" ] expect(@Helper.getSubset(dataset).length).toEqual 20 dataset = [] while dataset.length < 400 dataset.push [ "test" ] expect(@Helper.getSubset(dataset).length).toEqual 40 dataset = [] while dataset.length < 300 dataset.push [ "test" ] expect(@Helper.getSubset(dataset).length).toEqual 30 dataset = [] while dataset.length < 1100 dataset.push [ "test" ] expect(@Helper.getSubset(dataset).length).toEqual 100 it 'should identify phone numbers', -> expect(@Helper.isPhoneNumber "+43 902 128391" ).toBeTruthy() expect(@Helper.isPhoneNumber "+43-231-128391" ).toBeTruthy() expect(@Helper.isPhoneNumber "+43.902.128391" ).toBeTruthy() expect(@Helper.isPhoneNumber "+43-231" ).toBeFalsy() expect(@Helper.isPhoneNumber "+43.128." ).toBeFalsy() expect(@Helper.isPhoneNumber "43 902 128391" ).toBeFalsy() it 'should identify phone numbers', -> expect(@Helper.isEmailAddress "office.vidatio@vidatio.de" ).toBeTruthy() expect(@Helper.isEmailAddress "office@vidat.io" ).toBeTruthy() expect(@Helper.isEmailAddress "office-vidatio@vidat.io" ).toBeTruthy() expect(@Helper.isEmailAddress "@test.de" ).toBeFalsy() expect(@Helper.isEmailAddress "email@test@.de" ).toBeFalsy() expect(@Helper.isEmailAddress "@test.de" ).toBeFalsy() expect(@Helper.isEmailAddress "email@.de" ).toBeFalsy() expect(@Helper.isEmailAddress "+43 549 198012" ).toBeFalsy() it 'should identify urls', -> expect(@Helper.isURL "http://vidatio.mediacube.at" ).toBeTruthy() expect(@Helper.isURL "http://www.vidatio.mediacube.at" ).toBeTruthy() expect(@Helper.isURL "htt://.mediacube.at" ).toBeFalsy() expect(@Helper.isURL "http:vidatio.mediacube.at/delete?q=test&result=test" ).toBeFalsy() it 'should identify dates', -> expect(@Helper.isDate "01.01.2000" ).toBeTruthy() expect(@Helper.isDate "31.12.2000" ).toBeTruthy() expect(@Helper.isDate "12.31.2000" ).toBeTruthy() expect(@Helper.isDate "31.13.2000" ).toBeFalsy() expect(@Helper.isDate "32.12.2000" ).toBeFalsy() expect(@Helper.isDate "13/31/2000" ).toBeFalsy() expect(@Helper.isDate "12-32-2000" ).toBeFalsy() expect(@Helper.isDate "2016-01-13" ).toBeTruthy() expect(@Helper.isDate "2016-12-31" ).toBeTruthy() expect(@Helper.isDate "2016/12/31" ).toBeTruthy() expect(@Helper.isDate "2016/12/31" ).toBeTruthy() expect(@Helper.isDate "2016/00/31" ).toBeFalsy() expect(@Helper.isDate "2016/12/32" ).toBeFalsy() it 'should transform 2 dimensional arrays to arrays of objects for a bar chart and scatter plot', -> dataset = [ [ 123, "Hello World" ] [ 456, "This is a test" ] ] headers = "x": "Apfel" "y": "Banane" xColumn = 1 yColumn = 0 color = "#FF0" expectedResult = [ { "Apfel": "Hello World" "Banane": 123 "name": 123 "color": "#FF0" "id": 0 } { "Apfel": "This is a test" "Banane": 456 "name": 456 "color": "#FF0" "id": 1 } ] actualResult = @Helper.transformToArrayOfObjects(dataset, xColumn, yColumn, "bar", headers, color) expect(actualResult).toEqual(expectedResult) actualResult = @Helper.transformToArrayOfObjects(dataset, xColumn, yColumn, "scatter", headers, color) expect(actualResult).not.toEqual(expectedResult) it 'should transform 2 dimensional arrays to arrays of objects for a line chart', -> dataset = [ [ 123, "2016-02-28" ] [ 456, "2016-02-29" ] ] headers = "x": "Apfel" "y": "Banane" xColumn = 1 yColumn = 0 color = "#FF0" expectedResult = [ { "Apfel": "2016-02-28" "Banane": 123 "name": "Line 1" "color": "#FF0" "id": 0 } { "Apfel": "2016-02-29" "Banane": 456 "name": "Line 1" "color": "#FF0" "id": 1 } ] actualResult = @Helper.transformToArrayOfObjects(dataset, xColumn, yColumn, "line", headers, color) expect(actualResult).toEqual(expectedResult) it 'should create a subset of a 2 dimensional array with x column first and y column second (where each column is an Array)', -> test = [ [ 123, 456 ] [ "Hello World", "This is a test" ] [ new Date("2016-02-28"), new Date("2016-02-29") ] ] xColumn = 2 yColumn = 0 expectedResult = [ [ new Date("2016-02-28"), new Date("2016-02-29")] [ 123, 456 ] ] actualResult = @Helper.subsetWithXColumnFirst(test, xColumn, yColumn) expect(actualResult).toEqual(expectedResult) it 'should check if diagram is possible', -> expect(@Helper.isRowUsable("0", "0", "scatter")).toEqual(true) expect(@Helper.isRowUsable("test", "0", "scatter")).toEqual(false) expect(@Helper.isRowUsable("0", "test", "scatter")).toEqual(false) expect(@Helper.isRowUsable("0", "test", "bar")).toEqual(false) expect(@Helper.isRowUsable("test", "0", "bar")).toEqual(true) expect(@Helper.isRowUsable("01.01.2016", "1", "line")).toEqual(true) expect(@Helper.isRowUsable("1", "01.01.2016", "line")).toEqual(false) expect(@Helper.isRowUsable("1", "test", "parallel")).toEqual(true) expect(@Helper.isRowUsable("test", "test", "parallel")).toEqual(true) expect(@Helper.isRowUsable("test", "1", "parallel")).toEqual(true) it 'should untrim the dataset', -> test = [ [1, 2] [3, 4] ] tableOffset = columns: 1 rows: 1 expectedResult = [ [ null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null ] [ null, 1, 2, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null ] [ null, 3, 4, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null ] ] expect(@Helper.untrimDataset test, tableOffset, 26).toEqual expectedResult it 'should clean an array from unwanted values', -> test = [null, null, 1, 2, null, 3, null] expectedResult = [1, 2, 3] expect(@Helper.cleanArray test).toEqual expectedResult
144112
"use strict" describe "Service Helper", -> beforeEach -> @Helper = new window.vidatio.Helper() it 'should recognize wgs84 degree decimal coordinates correctly', -> # with leading sign coordinate = "0" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "-180" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "180" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() # with classification at the front coordinate = "N 0" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "N 90" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "S 0" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "S 90" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "E 0" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "E 180" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "W 0" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "W 180" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() # with classification at the end coordinate = "0 N" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "90 N" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "0 S" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "90 S" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "0 E" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "180 E" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "0 W" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "180 W" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() # with degree symbol coordinate = "0°" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "-180°" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "W 180°" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "180° W" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() # without space between classification and decimal number coordinate = "N0" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "N90" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "0S" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "90S" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "E0" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "E180" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "0W" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "180W" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "181" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeFalsy() coordinate = "-181" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeFalsy() coordinate = "N -90" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeFalsy() coordinate = "N 91" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeFalsy() coordinate = "S -90" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeFalsy() coordinate = "S 91" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeFalsy() coordinate = "E -180" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeFalsy() coordinate = "E 181" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeFalsy() coordinate = "W -180" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeFalsy() coordinate = "W 181" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeFalsy() it 'should recognize wgs84 degree decimal minutes coordinates correctly', -> coordinate = "180 59" expect(@Helper.isCoordinateWGS84DegreeDecimalMinutes(coordinate)).toBeTruthy() coordinate = "E180 59" expect(@Helper.isCoordinateWGS84DegreeDecimalMinutes(coordinate)).toBeTruthy() coordinate = "N 90 0" expect(@Helper.isCoordinateWGS84DegreeDecimalMinutes(coordinate)).toBeTruthy() coordinate = "W 180° 59.999" expect(@Helper.isCoordinateWGS84DegreeDecimalMinutes(coordinate)).toBeTruthy() coordinate = "180° 59.999 W" expect(@Helper.isCoordinateWGS84DegreeDecimalMinutes(coordinate)).toBeTruthy() coordinate = "180" expect(@Helper.isCoordinateWGS84DegreeDecimalMinutes(coordinate)).toBeFalsy() coordinate = "181W 59.999" expect(@Helper.isCoordinateWGS84DegreeDecimalMinutes(coordinate)).toBeFalsy() coordinate = "W 0° 60" expect(@Helper.isCoordinateWGS84DegreeDecimalMinutes(coordinate)).toBeFalsy() coordinate = "S 90° 61" expect(@Helper.isCoordinateWGS84DegreeDecimalMinutes(coordinate)).toBeFalsy() it 'should recognize wgs84 degree decimal minutes seconds coordinates correctly', -> coordinate = "180° 59' 0''" expect(@Helper.isCoordinateWGS84DegreeDecimalMinutesSeconds(coordinate)).toBeTruthy() coordinate = "E180 59 50" expect(@Helper.isCoordinateWGS84DegreeDecimalMinutesSeconds(coordinate)).toBeTruthy() coordinate = "N 90 59 59.999" expect(@Helper.isCoordinateWGS84DegreeDecimalMinutesSeconds(coordinate)).toBeTruthy() coordinate = "180° 1 59.999 W" expect(@Helper.isCoordinateWGS84DegreeDecimalMinutesSeconds(coordinate)).toBeTruthy() coordinate = "180 59" expect(@Helper.isCoordinateWGS84DegreeDecimalMinutesSeconds(coordinate)).toBeFalsy() coordinate = "180 59.1 50" expect(@Helper.isCoordinateWGS84DegreeDecimalMinutesSeconds(coordinate)).toBeFalsy() coordinate = "180° 59.1 50" expect(@Helper.isCoordinateWGS84DegreeDecimalMinutesSeconds(coordinate)).toBeFalsy() coordinate = "S 180° 59 60" expect(@Helper.isCoordinateWGS84DegreeDecimalMinutesSeconds(coordinate)).toBeFalsy() it "should remove null values of a two dimensional array", -> dataset = [ [ null, null, null, null, null ] [ null, "true", "false", null, null ] [ null, "true", "false", null, null ] [ null, null, null, null, null ] ] result = [ [ "true", "false" ] [ "true", "false" ] ] expect(@Helper.trimDataset(dataset).trimmedDataset).toEqual result it "should create a matrix with the initial value", -> dataset = [ [ "true", "true", "true" ] [ "true", "true", "true" ] [ "true", "true", "true" ] ] result = [ [ true, true, true ] [ true, true, true ] [ true, true, true ] ] expect(@Helper.createMatrix dataset, true).toEqual result it "should check if a value is a number", -> expect(@Helper.isNumber 3.14159).toBeTruthy() expect(@Helper.isNumber 180).toBeTruthy() expect(@Helper.isNumber -42).toBeTruthy() expect(@Helper.isNumber "Test").toBeFalsy() expect(@Helper.isNumber undefined).toBeFalsy() expect(@Helper.isNumber null).toBeFalsy() expect(@Helper.isNumber true).toBeFalsy() it "should return a subset of the dataset", -> dataset = [] while dataset.length < 20 dataset.push [ "test" ] expect(@Helper.getSubset(dataset).length).toEqual 20 dataset = [] while dataset.length < 400 dataset.push [ "test" ] expect(@Helper.getSubset(dataset).length).toEqual 40 dataset = [] while dataset.length < 300 dataset.push [ "test" ] expect(@Helper.getSubset(dataset).length).toEqual 30 dataset = [] while dataset.length < 1100 dataset.push [ "test" ] expect(@Helper.getSubset(dataset).length).toEqual 100 it 'should identify phone numbers', -> expect(@Helper.isPhoneNumber "+43 902 128391" ).toBeTruthy() expect(@Helper.isPhoneNumber "+43-231-128391" ).toBeTruthy() expect(@Helper.isPhoneNumber "+43.902.128391" ).toBeTruthy() expect(@Helper.isPhoneNumber "+43-231" ).toBeFalsy() expect(@Helper.isPhoneNumber "+43.128." ).toBeFalsy() expect(@Helper.isPhoneNumber "43 902 128391" ).toBeFalsy() it 'should identify phone numbers', -> expect(@Helper.isEmailAddress "<EMAIL>" ).toBeTruthy() expect(@Helper.isEmailAddress "<EMAIL>" ).toBeTruthy() expect(@Helper.isEmailAddress "<EMAIL>" ).toBeTruthy() expect(@Helper.isEmailAddress "@test.de" ).toBeFalsy() expect(@Helper.isEmailAddress "<EMAIL>" ).toBeFalsy() expect(@Helper.isEmailAddress "@test.de" ).toBeFalsy() expect(@Helper.isEmailAddress "<EMAIL>" ).toBeFalsy() expect(@Helper.isEmailAddress "+43 549 198012" ).toBeFalsy() it 'should identify urls', -> expect(@Helper.isURL "http://vidatio.mediacube.at" ).toBeTruthy() expect(@Helper.isURL "http://www.vidatio.mediacube.at" ).toBeTruthy() expect(@Helper.isURL "htt://.mediacube.at" ).toBeFalsy() expect(@Helper.isURL "http:vidatio.mediacube.at/delete?q=test&result=test" ).toBeFalsy() it 'should identify dates', -> expect(@Helper.isDate "01.01.2000" ).toBeTruthy() expect(@Helper.isDate "31.12.2000" ).toBeTruthy() expect(@Helper.isDate "12.31.2000" ).toBeTruthy() expect(@Helper.isDate "31.13.2000" ).toBeFalsy() expect(@Helper.isDate "32.12.2000" ).toBeFalsy() expect(@Helper.isDate "13/31/2000" ).toBeFalsy() expect(@Helper.isDate "12-32-2000" ).toBeFalsy() expect(@Helper.isDate "2016-01-13" ).toBeTruthy() expect(@Helper.isDate "2016-12-31" ).toBeTruthy() expect(@Helper.isDate "2016/12/31" ).toBeTruthy() expect(@Helper.isDate "2016/12/31" ).toBeTruthy() expect(@Helper.isDate "2016/00/31" ).toBeFalsy() expect(@Helper.isDate "2016/12/32" ).toBeFalsy() it 'should transform 2 dimensional arrays to arrays of objects for a bar chart and scatter plot', -> dataset = [ [ 123, "Hello World" ] [ 456, "This is a test" ] ] headers = "x": "Apfel" "y": "Banane" xColumn = 1 yColumn = 0 color = "#FF0" expectedResult = [ { "Ap<NAME>": "Hello World" "Ban<NAME>": 123 "name": 123 "color": "#FF0" "id": 0 } { "<NAME>": "This is a test" "Banane": 456 "name": 456 "color": "#FF0" "id": 1 } ] actualResult = @Helper.transformToArrayOfObjects(dataset, xColumn, yColumn, "bar", headers, color) expect(actualResult).toEqual(expectedResult) actualResult = @Helper.transformToArrayOfObjects(dataset, xColumn, yColumn, "scatter", headers, color) expect(actualResult).not.toEqual(expectedResult) it 'should transform 2 dimensional arrays to arrays of objects for a line chart', -> dataset = [ [ 123, "2016-02-28" ] [ 456, "2016-02-29" ] ] headers = "x": "<NAME>" "y": "<NAME>" xColumn = 1 yColumn = 0 color = "#FF0" expectedResult = [ { "Apfel": "2016-02-28" "Ban<NAME>": 123 "name": "Line 1" "color": "#FF0" "id": 0 } { "Apfel": "2016-02-29" "Ban<NAME>": 456 "name": "Line 1" "color": "#FF0" "id": 1 } ] actualResult = @Helper.transformToArrayOfObjects(dataset, xColumn, yColumn, "line", headers, color) expect(actualResult).toEqual(expectedResult) it 'should create a subset of a 2 dimensional array with x column first and y column second (where each column is an Array)', -> test = [ [ 123, 456 ] [ "Hello World", "This is a test" ] [ new Date("2016-02-28"), new Date("2016-02-29") ] ] xColumn = 2 yColumn = 0 expectedResult = [ [ new Date("2016-02-28"), new Date("2016-02-29")] [ 123, 456 ] ] actualResult = @Helper.subsetWithXColumnFirst(test, xColumn, yColumn) expect(actualResult).toEqual(expectedResult) it 'should check if diagram is possible', -> expect(@Helper.isRowUsable("0", "0", "scatter")).toEqual(true) expect(@Helper.isRowUsable("test", "0", "scatter")).toEqual(false) expect(@Helper.isRowUsable("0", "test", "scatter")).toEqual(false) expect(@Helper.isRowUsable("0", "test", "bar")).toEqual(false) expect(@Helper.isRowUsable("test", "0", "bar")).toEqual(true) expect(@Helper.isRowUsable("01.01.2016", "1", "line")).toEqual(true) expect(@Helper.isRowUsable("1", "01.01.2016", "line")).toEqual(false) expect(@Helper.isRowUsable("1", "test", "parallel")).toEqual(true) expect(@Helper.isRowUsable("test", "test", "parallel")).toEqual(true) expect(@Helper.isRowUsable("test", "1", "parallel")).toEqual(true) it 'should untrim the dataset', -> test = [ [1, 2] [3, 4] ] tableOffset = columns: 1 rows: 1 expectedResult = [ [ null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null ] [ null, 1, 2, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null ] [ null, 3, 4, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null ] ] expect(@Helper.untrimDataset test, tableOffset, 26).toEqual expectedResult it 'should clean an array from unwanted values', -> test = [null, null, 1, 2, null, 3, null] expectedResult = [1, 2, 3] expect(@Helper.cleanArray test).toEqual expectedResult
true
"use strict" describe "Service Helper", -> beforeEach -> @Helper = new window.vidatio.Helper() it 'should recognize wgs84 degree decimal coordinates correctly', -> # with leading sign coordinate = "0" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "-180" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "180" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() # with classification at the front coordinate = "N 0" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "N 90" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "S 0" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "S 90" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "E 0" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "E 180" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "W 0" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "W 180" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() # with classification at the end coordinate = "0 N" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "90 N" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "0 S" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "90 S" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "0 E" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "180 E" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "0 W" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "180 W" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() # with degree symbol coordinate = "0°" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "-180°" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "W 180°" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "180° W" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() # without space between classification and decimal number coordinate = "N0" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "N90" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "0S" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "90S" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "E0" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "E180" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "0W" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "180W" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeTruthy() coordinate = "181" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeFalsy() coordinate = "-181" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeFalsy() coordinate = "N -90" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeFalsy() coordinate = "N 91" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeFalsy() coordinate = "S -90" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeFalsy() coordinate = "S 91" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeFalsy() coordinate = "E -180" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeFalsy() coordinate = "E 181" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeFalsy() coordinate = "W -180" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeFalsy() coordinate = "W 181" expect(@Helper.isCoordinateWGS84DegreeDecimal(coordinate)).toBeFalsy() it 'should recognize wgs84 degree decimal minutes coordinates correctly', -> coordinate = "180 59" expect(@Helper.isCoordinateWGS84DegreeDecimalMinutes(coordinate)).toBeTruthy() coordinate = "E180 59" expect(@Helper.isCoordinateWGS84DegreeDecimalMinutes(coordinate)).toBeTruthy() coordinate = "N 90 0" expect(@Helper.isCoordinateWGS84DegreeDecimalMinutes(coordinate)).toBeTruthy() coordinate = "W 180° 59.999" expect(@Helper.isCoordinateWGS84DegreeDecimalMinutes(coordinate)).toBeTruthy() coordinate = "180° 59.999 W" expect(@Helper.isCoordinateWGS84DegreeDecimalMinutes(coordinate)).toBeTruthy() coordinate = "180" expect(@Helper.isCoordinateWGS84DegreeDecimalMinutes(coordinate)).toBeFalsy() coordinate = "181W 59.999" expect(@Helper.isCoordinateWGS84DegreeDecimalMinutes(coordinate)).toBeFalsy() coordinate = "W 0° 60" expect(@Helper.isCoordinateWGS84DegreeDecimalMinutes(coordinate)).toBeFalsy() coordinate = "S 90° 61" expect(@Helper.isCoordinateWGS84DegreeDecimalMinutes(coordinate)).toBeFalsy() it 'should recognize wgs84 degree decimal minutes seconds coordinates correctly', -> coordinate = "180° 59' 0''" expect(@Helper.isCoordinateWGS84DegreeDecimalMinutesSeconds(coordinate)).toBeTruthy() coordinate = "E180 59 50" expect(@Helper.isCoordinateWGS84DegreeDecimalMinutesSeconds(coordinate)).toBeTruthy() coordinate = "N 90 59 59.999" expect(@Helper.isCoordinateWGS84DegreeDecimalMinutesSeconds(coordinate)).toBeTruthy() coordinate = "180° 1 59.999 W" expect(@Helper.isCoordinateWGS84DegreeDecimalMinutesSeconds(coordinate)).toBeTruthy() coordinate = "180 59" expect(@Helper.isCoordinateWGS84DegreeDecimalMinutesSeconds(coordinate)).toBeFalsy() coordinate = "180 59.1 50" expect(@Helper.isCoordinateWGS84DegreeDecimalMinutesSeconds(coordinate)).toBeFalsy() coordinate = "180° 59.1 50" expect(@Helper.isCoordinateWGS84DegreeDecimalMinutesSeconds(coordinate)).toBeFalsy() coordinate = "S 180° 59 60" expect(@Helper.isCoordinateWGS84DegreeDecimalMinutesSeconds(coordinate)).toBeFalsy() it "should remove null values of a two dimensional array", -> dataset = [ [ null, null, null, null, null ] [ null, "true", "false", null, null ] [ null, "true", "false", null, null ] [ null, null, null, null, null ] ] result = [ [ "true", "false" ] [ "true", "false" ] ] expect(@Helper.trimDataset(dataset).trimmedDataset).toEqual result it "should create a matrix with the initial value", -> dataset = [ [ "true", "true", "true" ] [ "true", "true", "true" ] [ "true", "true", "true" ] ] result = [ [ true, true, true ] [ true, true, true ] [ true, true, true ] ] expect(@Helper.createMatrix dataset, true).toEqual result it "should check if a value is a number", -> expect(@Helper.isNumber 3.14159).toBeTruthy() expect(@Helper.isNumber 180).toBeTruthy() expect(@Helper.isNumber -42).toBeTruthy() expect(@Helper.isNumber "Test").toBeFalsy() expect(@Helper.isNumber undefined).toBeFalsy() expect(@Helper.isNumber null).toBeFalsy() expect(@Helper.isNumber true).toBeFalsy() it "should return a subset of the dataset", -> dataset = [] while dataset.length < 20 dataset.push [ "test" ] expect(@Helper.getSubset(dataset).length).toEqual 20 dataset = [] while dataset.length < 400 dataset.push [ "test" ] expect(@Helper.getSubset(dataset).length).toEqual 40 dataset = [] while dataset.length < 300 dataset.push [ "test" ] expect(@Helper.getSubset(dataset).length).toEqual 30 dataset = [] while dataset.length < 1100 dataset.push [ "test" ] expect(@Helper.getSubset(dataset).length).toEqual 100 it 'should identify phone numbers', -> expect(@Helper.isPhoneNumber "+43 902 128391" ).toBeTruthy() expect(@Helper.isPhoneNumber "+43-231-128391" ).toBeTruthy() expect(@Helper.isPhoneNumber "+43.902.128391" ).toBeTruthy() expect(@Helper.isPhoneNumber "+43-231" ).toBeFalsy() expect(@Helper.isPhoneNumber "+43.128." ).toBeFalsy() expect(@Helper.isPhoneNumber "43 902 128391" ).toBeFalsy() it 'should identify phone numbers', -> expect(@Helper.isEmailAddress "PI:EMAIL:<EMAIL>END_PI" ).toBeTruthy() expect(@Helper.isEmailAddress "PI:EMAIL:<EMAIL>END_PI" ).toBeTruthy() expect(@Helper.isEmailAddress "PI:EMAIL:<EMAIL>END_PI" ).toBeTruthy() expect(@Helper.isEmailAddress "@test.de" ).toBeFalsy() expect(@Helper.isEmailAddress "PI:EMAIL:<EMAIL>END_PI" ).toBeFalsy() expect(@Helper.isEmailAddress "@test.de" ).toBeFalsy() expect(@Helper.isEmailAddress "PI:EMAIL:<EMAIL>END_PI" ).toBeFalsy() expect(@Helper.isEmailAddress "+43 549 198012" ).toBeFalsy() it 'should identify urls', -> expect(@Helper.isURL "http://vidatio.mediacube.at" ).toBeTruthy() expect(@Helper.isURL "http://www.vidatio.mediacube.at" ).toBeTruthy() expect(@Helper.isURL "htt://.mediacube.at" ).toBeFalsy() expect(@Helper.isURL "http:vidatio.mediacube.at/delete?q=test&result=test" ).toBeFalsy() it 'should identify dates', -> expect(@Helper.isDate "01.01.2000" ).toBeTruthy() expect(@Helper.isDate "31.12.2000" ).toBeTruthy() expect(@Helper.isDate "12.31.2000" ).toBeTruthy() expect(@Helper.isDate "31.13.2000" ).toBeFalsy() expect(@Helper.isDate "32.12.2000" ).toBeFalsy() expect(@Helper.isDate "13/31/2000" ).toBeFalsy() expect(@Helper.isDate "12-32-2000" ).toBeFalsy() expect(@Helper.isDate "2016-01-13" ).toBeTruthy() expect(@Helper.isDate "2016-12-31" ).toBeTruthy() expect(@Helper.isDate "2016/12/31" ).toBeTruthy() expect(@Helper.isDate "2016/12/31" ).toBeTruthy() expect(@Helper.isDate "2016/00/31" ).toBeFalsy() expect(@Helper.isDate "2016/12/32" ).toBeFalsy() it 'should transform 2 dimensional arrays to arrays of objects for a bar chart and scatter plot', -> dataset = [ [ 123, "Hello World" ] [ 456, "This is a test" ] ] headers = "x": "Apfel" "y": "Banane" xColumn = 1 yColumn = 0 color = "#FF0" expectedResult = [ { "ApPI:NAME:<NAME>END_PI": "Hello World" "BanPI:NAME:<NAME>END_PI": 123 "name": 123 "color": "#FF0" "id": 0 } { "PI:NAME:<NAME>END_PI": "This is a test" "Banane": 456 "name": 456 "color": "#FF0" "id": 1 } ] actualResult = @Helper.transformToArrayOfObjects(dataset, xColumn, yColumn, "bar", headers, color) expect(actualResult).toEqual(expectedResult) actualResult = @Helper.transformToArrayOfObjects(dataset, xColumn, yColumn, "scatter", headers, color) expect(actualResult).not.toEqual(expectedResult) it 'should transform 2 dimensional arrays to arrays of objects for a line chart', -> dataset = [ [ 123, "2016-02-28" ] [ 456, "2016-02-29" ] ] headers = "x": "PI:NAME:<NAME>END_PI" "y": "PI:NAME:<NAME>END_PI" xColumn = 1 yColumn = 0 color = "#FF0" expectedResult = [ { "Apfel": "2016-02-28" "BanPI:NAME:<NAME>END_PI": 123 "name": "Line 1" "color": "#FF0" "id": 0 } { "Apfel": "2016-02-29" "BanPI:NAME:<NAME>END_PI": 456 "name": "Line 1" "color": "#FF0" "id": 1 } ] actualResult = @Helper.transformToArrayOfObjects(dataset, xColumn, yColumn, "line", headers, color) expect(actualResult).toEqual(expectedResult) it 'should create a subset of a 2 dimensional array with x column first and y column second (where each column is an Array)', -> test = [ [ 123, 456 ] [ "Hello World", "This is a test" ] [ new Date("2016-02-28"), new Date("2016-02-29") ] ] xColumn = 2 yColumn = 0 expectedResult = [ [ new Date("2016-02-28"), new Date("2016-02-29")] [ 123, 456 ] ] actualResult = @Helper.subsetWithXColumnFirst(test, xColumn, yColumn) expect(actualResult).toEqual(expectedResult) it 'should check if diagram is possible', -> expect(@Helper.isRowUsable("0", "0", "scatter")).toEqual(true) expect(@Helper.isRowUsable("test", "0", "scatter")).toEqual(false) expect(@Helper.isRowUsable("0", "test", "scatter")).toEqual(false) expect(@Helper.isRowUsable("0", "test", "bar")).toEqual(false) expect(@Helper.isRowUsable("test", "0", "bar")).toEqual(true) expect(@Helper.isRowUsable("01.01.2016", "1", "line")).toEqual(true) expect(@Helper.isRowUsable("1", "01.01.2016", "line")).toEqual(false) expect(@Helper.isRowUsable("1", "test", "parallel")).toEqual(true) expect(@Helper.isRowUsable("test", "test", "parallel")).toEqual(true) expect(@Helper.isRowUsable("test", "1", "parallel")).toEqual(true) it 'should untrim the dataset', -> test = [ [1, 2] [3, 4] ] tableOffset = columns: 1 rows: 1 expectedResult = [ [ null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null ] [ null, 1, 2, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null ] [ null, 3, 4, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null ] ] expect(@Helper.untrimDataset test, tableOffset, 26).toEqual expectedResult it 'should clean an array from unwanted values', -> test = [null, null, 1, 2, null, 3, null] expectedResult = [1, 2, 3] expect(@Helper.cleanArray test).toEqual expectedResult
[ { "context": "ar\":\"2015\",\n \"first_name\":\"Muslim\",\n \"last_name\":\"Nurakhunov", "end": 1419, "score": 0.99961918592453, "start": 1413, "tag": "NAME", "value": "Muslim" }, { "context": "e\":\"Muslim\",\n \"l...
models/shopping_cart/fixture/getpurchasesummary.coffee
signonsridhar/sridhar_hbs
0
define(['can_fixture'], (can)-> can.fixture('POST /bss/order?action=getpurchasesummary',(req, res)-> return { "response":{ "service":"getpurchasesummary", "response_code":100, "execution_time":11391, "timestamp":"2014-04-21T23:48:56+0000", "response_data":{ "line_name":"T-Mobile Line Bundle Monthly (Dev)-V2", "total_line_quantity":0.0, "line_quantity":3.0, "extension_quantity":3.0, "did_quantity":3.0, "device_quantity":3.0, "master_paln_extensioin_quantity":1.0, "master_plan_did_quantity":0.0, "master_plan_device_quantity":2.0, "billing_period":1, "amount_per_unit":"50.00", "tax_amount":"2.67", "total_amount_before_taxes":"150.00", "total_amount_after_taxes":"152.67", "credit_card":{ "creditcardid":"1", "address1":"951 S12 Street", "city":"San Jose", "country":"US", "expiration_month":"5", "expiration_year":"2015", "first_name":"Muslim", "last_name":"Nurakhunov", "number":"XXXX-1111", "zip_code":"95112", "state":"CA", "card_type":"Visa", "primary":true } }, "version":"1.0" } } ) )
2250
define(['can_fixture'], (can)-> can.fixture('POST /bss/order?action=getpurchasesummary',(req, res)-> return { "response":{ "service":"getpurchasesummary", "response_code":100, "execution_time":11391, "timestamp":"2014-04-21T23:48:56+0000", "response_data":{ "line_name":"T-Mobile Line Bundle Monthly (Dev)-V2", "total_line_quantity":0.0, "line_quantity":3.0, "extension_quantity":3.0, "did_quantity":3.0, "device_quantity":3.0, "master_paln_extensioin_quantity":1.0, "master_plan_did_quantity":0.0, "master_plan_device_quantity":2.0, "billing_period":1, "amount_per_unit":"50.00", "tax_amount":"2.67", "total_amount_before_taxes":"150.00", "total_amount_after_taxes":"152.67", "credit_card":{ "creditcardid":"1", "address1":"951 S12 Street", "city":"San Jose", "country":"US", "expiration_month":"5", "expiration_year":"2015", "first_name":"<NAME>", "last_name":"<NAME>", "number":"XXXX-1111", "zip_code":"95112", "state":"CA", "card_type":"Visa", "primary":true } }, "version":"1.0" } } ) )
true
define(['can_fixture'], (can)-> can.fixture('POST /bss/order?action=getpurchasesummary',(req, res)-> return { "response":{ "service":"getpurchasesummary", "response_code":100, "execution_time":11391, "timestamp":"2014-04-21T23:48:56+0000", "response_data":{ "line_name":"T-Mobile Line Bundle Monthly (Dev)-V2", "total_line_quantity":0.0, "line_quantity":3.0, "extension_quantity":3.0, "did_quantity":3.0, "device_quantity":3.0, "master_paln_extensioin_quantity":1.0, "master_plan_did_quantity":0.0, "master_plan_device_quantity":2.0, "billing_period":1, "amount_per_unit":"50.00", "tax_amount":"2.67", "total_amount_before_taxes":"150.00", "total_amount_after_taxes":"152.67", "credit_card":{ "creditcardid":"1", "address1":"951 S12 Street", "city":"San Jose", "country":"US", "expiration_month":"5", "expiration_year":"2015", "first_name":"PI:NAME:<NAME>END_PI", "last_name":"PI:NAME:<NAME>END_PI", "number":"XXXX-1111", "zip_code":"95112", "state":"CA", "card_type":"Visa", "primary":true } }, "version":"1.0" } } ) )
[ { "context": "{Name: n, Value: v} for n, v of config when n != \"username\"\n attributes\n\n register = (attributes, option", "end": 696, "score": 0.9482213258743286, "start": 688, "tag": "USERNAME", "value": "username" }, { "context": "ister = (attributes, options={}) ->\n pa...
src/proxies/frictionless.coffee
pandastrike/panda-sky-identity
0
# Frictionless is a Panda Sky Cognito mixin preset that automates the generation and entry of a password so the end user only deals with multi-factor authentication to get unguessable keys on their device. import {merge} from "fairmont-helpers" import {randomKey} from "key-forge" frictionless = (liftedAWS, env) -> cog = liftedAWS.CognitoIdentityServiceProvider poolID = env.mixinCognitoPoolID clientID = env.mixinCognitoClientID assignAttributes = (config) -> if !config.email && !config.phone_number throw new Error "Must provide email and/or phone_number for registration." attributes = [] attributes.push {Name: n, Value: v} for n, v of config when n != "username" attributes register = (attributes, options={}) -> password = randomKey 16, "base64url" attributes["custom:password"] = password params = Username: attributes.username Password: password ClientId: clientID UserAttributes: assignAttributes attributes params = merge params, options { password, registrationDetails: await cog.signUp params } confirm = (username, code, options={}) -> params = Username: username ConfirmationCode: code ClientId: clientID params = merge params, options await cog.confirmSignUp params startAuthFlow = (flow, data, options={}) -> params = AuthFlow: flow ClientId: clientID AuthParameters: data params = merge params, options await cog.initiateAuth params login = ({username, password, key}, options={}) -> data = USERNAME: username PASSWORD: password data.DEVICE_KEY = key if key await startAuthFlow "USER_PASSWORD_AUTH", data, options refresh = (token, key, options={}) -> data = REFRESH_TOKEN: token DEVICE_KEY: key await startAuthFlow "REFRESH_TOKEN", data, options respond = (challenge, response, options={}) -> params = ChallengeName: challenge.ChallengeName ClientId: clientID ChallengeResponses: response Session: challenge.Session params = merge params, options await cog.respondToAuthChallenge params validateMFA = (challenge, code, options={}) -> response = SMS_MFA_CODE: code USERNAME: challenge.ChallengeParameters.USER_ID_FOR_SRP await respond challenge, response, options refreshLogin = (username, password, options={}) -> login = (username, password, options={}) -> # params = # AuthFlow: USER_SRP_AUTH | REFRESH_TOKEN_AUTH | REFRESH_TOKEN | CUSTOM_AUTH | ADMIN_NO_SRP_AUTH | USER_PASSWORD_AUTH, /* required */ # ClientId: 'STRING_VALUE', /* required */ # AnalyticsMetadata: { # AnalyticsEndpointId: 'STRING_VALUE' # }, # AuthParameters: { # '<StringType>': 'STRING_VALUE', # /* '<StringType>': ... */ # }, # ClientMetadata: { # '<StringType>': 'STRING_VALUE', # /* '<StringType>': ... */ # }, # UserContextData: { # EncodedData: 'STRING_VALUE' # } # await cog.initiateAuth params {register, confirm, login, respond, validateMFA} export default frictionless
128577
# Frictionless is a Panda Sky Cognito mixin preset that automates the generation and entry of a password so the end user only deals with multi-factor authentication to get unguessable keys on their device. import {merge} from "fairmont-helpers" import {randomKey} from "key-forge" frictionless = (liftedAWS, env) -> cog = liftedAWS.CognitoIdentityServiceProvider poolID = env.mixinCognitoPoolID clientID = env.mixinCognitoClientID assignAttributes = (config) -> if !config.email && !config.phone_number throw new Error "Must provide email and/or phone_number for registration." attributes = [] attributes.push {Name: n, Value: v} for n, v of config when n != "username" attributes register = (attributes, options={}) -> password = <PASSWORD> 1<PASSWORD>, "base<PASSWORD>" attributes["custom:password"] = <PASSWORD> params = Username: attributes.username Password: <PASSWORD> ClientId: clientID UserAttributes: assignAttributes attributes params = merge params, options { password, registrationDetails: await cog.signUp params } confirm = (username, code, options={}) -> params = Username: username ConfirmationCode: code ClientId: clientID params = merge params, options await cog.confirmSignUp params startAuthFlow = (flow, data, options={}) -> params = AuthFlow: flow ClientId: clientID AuthParameters: data params = merge params, options await cog.initiateAuth params login = ({username, password, key}, options={}) -> data = USERNAME: username PASSWORD: <PASSWORD> data.DEVICE_KEY = key if key await startAuthFlow "USER_PASSWORD_AUTH", data, options refresh = (token, key, options={}) -> data = REFRESH_TOKEN: token DEVICE_KEY: key await startAuthFlow "REFRESH_TOKEN", data, options respond = (challenge, response, options={}) -> params = ChallengeName: challenge.ChallengeName ClientId: clientID ChallengeResponses: response Session: challenge.Session params = merge params, options await cog.respondToAuthChallenge params validateMFA = (challenge, code, options={}) -> response = SMS_MFA_CODE: code USERNAME: challenge.ChallengeParameters.USER_ID_FOR_SRP await respond challenge, response, options refreshLogin = (username, password, options={}) -> login = (username, password, options={}) -> # params = # AuthFlow: USER_SRP_AUTH | REFRESH_TOKEN_AUTH | REFRESH_TOKEN | CUSTOM_AUTH | ADMIN_NO_SRP_AUTH | USER_PASSWORD_AUTH, /* required */ # ClientId: 'STRING_VALUE', /* required */ # AnalyticsMetadata: { # AnalyticsEndpointId: 'STRING_VALUE' # }, # AuthParameters: { # '<StringType>': 'STRING_VALUE', # /* '<StringType>': ... */ # }, # ClientMetadata: { # '<StringType>': 'STRING_VALUE', # /* '<StringType>': ... */ # }, # UserContextData: { # EncodedData: 'STRING_VALUE' # } # await cog.initiateAuth params {register, confirm, login, respond, validateMFA} export default frictionless
true
# Frictionless is a Panda Sky Cognito mixin preset that automates the generation and entry of a password so the end user only deals with multi-factor authentication to get unguessable keys on their device. import {merge} from "fairmont-helpers" import {randomKey} from "key-forge" frictionless = (liftedAWS, env) -> cog = liftedAWS.CognitoIdentityServiceProvider poolID = env.mixinCognitoPoolID clientID = env.mixinCognitoClientID assignAttributes = (config) -> if !config.email && !config.phone_number throw new Error "Must provide email and/or phone_number for registration." attributes = [] attributes.push {Name: n, Value: v} for n, v of config when n != "username" attributes register = (attributes, options={}) -> password = PI:PASSWORD:<PASSWORD>END_PI 1PI:PASSWORD:<PASSWORD>END_PI, "basePI:PASSWORD:<PASSWORD>END_PI" attributes["custom:password"] = PI:PASSWORD:<PASSWORD>END_PI params = Username: attributes.username Password: PI:PASSWORD:<PASSWORD>END_PI ClientId: clientID UserAttributes: assignAttributes attributes params = merge params, options { password, registrationDetails: await cog.signUp params } confirm = (username, code, options={}) -> params = Username: username ConfirmationCode: code ClientId: clientID params = merge params, options await cog.confirmSignUp params startAuthFlow = (flow, data, options={}) -> params = AuthFlow: flow ClientId: clientID AuthParameters: data params = merge params, options await cog.initiateAuth params login = ({username, password, key}, options={}) -> data = USERNAME: username PASSWORD: PI:PASSWORD:<PASSWORD>END_PI data.DEVICE_KEY = key if key await startAuthFlow "USER_PASSWORD_AUTH", data, options refresh = (token, key, options={}) -> data = REFRESH_TOKEN: token DEVICE_KEY: key await startAuthFlow "REFRESH_TOKEN", data, options respond = (challenge, response, options={}) -> params = ChallengeName: challenge.ChallengeName ClientId: clientID ChallengeResponses: response Session: challenge.Session params = merge params, options await cog.respondToAuthChallenge params validateMFA = (challenge, code, options={}) -> response = SMS_MFA_CODE: code USERNAME: challenge.ChallengeParameters.USER_ID_FOR_SRP await respond challenge, response, options refreshLogin = (username, password, options={}) -> login = (username, password, options={}) -> # params = # AuthFlow: USER_SRP_AUTH | REFRESH_TOKEN_AUTH | REFRESH_TOKEN | CUSTOM_AUTH | ADMIN_NO_SRP_AUTH | USER_PASSWORD_AUTH, /* required */ # ClientId: 'STRING_VALUE', /* required */ # AnalyticsMetadata: { # AnalyticsEndpointId: 'STRING_VALUE' # }, # AuthParameters: { # '<StringType>': 'STRING_VALUE', # /* '<StringType>': ... */ # }, # ClientMetadata: { # '<StringType>': 'STRING_VALUE', # /* '<StringType>': ... */ # }, # UserContextData: { # EncodedData: 'STRING_VALUE' # } # await cog.initiateAuth params {register, confirm, login, respond, validateMFA} export default frictionless
[ { "context": "d = require 'should'\n\nboards = [\n {\n \"name\": \"ToDoNow\",\n \"desc\": \"\",\n \"descData\": null,\n \"clos", "end": 111, "score": 0.7737023830413818, "start": 104, "tag": "NAME", "value": "ToDoNow" }, { "context": "3-08T09:32:52.044Z\",\n \"idTags\...
test/servers/trello.coffee
jianliaoim/talk-services
40
express = require 'express' _ = require 'lodash' should = require 'should' boards = [ { "name": "ToDoNow", "desc": "", "descData": null, "closed": false, "idOrganization": null, "pinned": null, "invitations": null, "shortLink": "GkR7AsMR", "powerUps": [ "calendar" ], "dateLastActivity": "2016-03-08T09:32:52.044Z", "idTags": [], "id": "4f83f6fab28be1c82841b3c0", "invited": false, "starred": false, "url": "https://trello.com/b/GkR7AsMR/todonow", "prefs": { "permissionLevel": "private", "voting": "disabled", "comments": "members", "invitations": "members", "selfJoin": false, "cardCovers": true, "calendarFeedEnabled": false, "background": "green", "backgroundImage": null, "backgroundImageScaled": null, "backgroundTile": false, "backgroundBrightness": "dark", "backgroundColor": "#519839", "canBePublic": true, "canBeOrg": true, "canBePrivate": true, "canInvite": true }, "memberships": [ { "id": "4f83f6fab28be1c82841b3c8", "idMember": "4f0a922ff25c53695a0cb1c2", "memberType": "admin", "unconfirmed": false, "deactivated": false } ], "subscribed": false, "labelNames": { "green": "", "yellow": "", "orange": "", "red": "", "purple": "", "blue": "", "sky": "", "lime": "", "pink": "", "black": "" }, "dateLastView": "2016-03-08T09:37:53.442Z", "shortUrl": "https://trello.com/b/GkR7AsMR" }, { "name": "Welcome Board", "desc": "", "descData": null, "closed": true, "idOrganization": null, "pinned": null, "invitations": null, "shortLink": "OWsaWkrk", "powerUps": [ "voting" ], "dateLastActivity": null, "idTags": [], "id": "4f0a922ff25c53695a0cb1d7", "invited": false, "starred": false, "url": "https://trello.com/b/OWsaWkrk/welcome-board", "prefs": { "permissionLevel": "private", "voting": "members", "comments": "members", "invitations": "members", "selfJoin": true, "cardCovers": true, "calendarFeedEnabled": false, "background": "blue", "backgroundImage": null, "backgroundImageScaled": null, "backgroundTile": false, "backgroundBrightness": "dark", "backgroundColor": "#0079BF", "canBePublic": true, "canBeOrg": true, "canBePrivate": true, "canInvite": true }, "memberships": [ { "id": "4f0a922ff25c53695a0cb1d6", "idMember": "4e6a7fad05d98b02ba00845c", "memberType": "normal", "unconfirmed": false, "deactivated": false }, { "id": "4f0a922ff25c53695a0cb1e1", "idMember": "4f0a922ff25c53695a0cb1c2", "memberType": "admin", "unconfirmed": false, "deactivated": false } ], "subscribed": false, "labelNames": { "green": "", "yellow": "", "orange": "", "red": "", "purple": "", "blue": "", "sky": "", "lime": "", "pink": "", "black": "" }, "dateLastView": "2012-04-10T09:03:00.057Z", "shortUrl": "https://trello.com/b/OWsaWkrk" } ] webhooks = '4f0a922ff25c53695a0cb1d7': "id": "56dfc3818d119dd1563685dc", "description": "New webhook", "idModel": "4f0a922ff25c53695a0cb1d7", "callbackURL": "https://jianliao.com/webhook", "active": true '4f83f6fab28be1c82841b3c0': "id": "56dfc3818d119dd1563685dd", "description": "New new webhook", "idModel": "4f83f6fab28be1c82841b3c0", "callbackURL": "https://jianliao.com/webhook", "active": true app = express() app.get '/members/me/boards', (req, res) -> res.send boards app.post '/webhooks', (req, res) -> should(req.body.idModel).not.empty should(webhooks[req.body.idModel]).not.empty res.send webhooks[req.body.idModel] app.delete '/webhooks/:id', (req, res) -> should(webhooks[req.params.id]).not.empty res.send {} module.exports = app
3329
express = require 'express' _ = require 'lodash' should = require 'should' boards = [ { "name": "<NAME>", "desc": "", "descData": null, "closed": false, "idOrganization": null, "pinned": null, "invitations": null, "shortLink": "GkR7AsMR", "powerUps": [ "calendar" ], "dateLastActivity": "2016-03-08T09:32:52.044Z", "idTags": [], "id": "<KEY>", "invited": false, "starred": false, "url": "https://trello.com/b/GkR7AsMR/todonow", "prefs": { "permissionLevel": "private", "voting": "disabled", "comments": "members", "invitations": "members", "selfJoin": false, "cardCovers": true, "calendarFeedEnabled": false, "background": "green", "backgroundImage": null, "backgroundImageScaled": null, "backgroundTile": false, "backgroundBrightness": "dark", "backgroundColor": "#519839", "canBePublic": true, "canBeOrg": true, "canBePrivate": true, "canInvite": true }, "memberships": [ { "id": "<KEY>", "idMember": "<KEY>", "memberType": "admin", "unconfirmed": false, "deactivated": false } ], "subscribed": false, "labelNames": { "green": "", "yellow": "", "orange": "", "red": "", "purple": "", "blue": "", "sky": "", "lime": "", "pink": "", "black": "" }, "dateLastView": "2016-03-08T09:37:53.442Z", "shortUrl": "https://trello.com/b/GkR7AsMR" }, { "name": "Welcome Board", "desc": "", "descData": null, "closed": true, "idOrganization": null, "pinned": null, "invitations": null, "shortLink": "OWsaWkrk", "powerUps": [ "voting" ], "dateLastActivity": null, "idTags": [], "id": "<KEY>", "invited": false, "starred": false, "url": "https://trello.com/b/OWsaWkrk/welcome-board", "prefs": { "permissionLevel": "private", "voting": "members", "comments": "members", "invitations": "members", "selfJoin": true, "cardCovers": true, "calendarFeedEnabled": false, "background": "blue", "backgroundImage": null, "backgroundImageScaled": null, "backgroundTile": false, "backgroundBrightness": "dark", "backgroundColor": "#0079BF", "canBePublic": true, "canBeOrg": true, "canBePrivate": true, "canInvite": true }, "memberships": [ { "id": "<KEY>", "idMember": "<KEY>", "memberType": "normal", "unconfirmed": false, "deactivated": false }, { "id": "<KEY>", "idMember": "<KEY>", "memberType": "admin", "unconfirmed": false, "deactivated": false } ], "subscribed": false, "labelNames": { "green": "", "yellow": "", "orange": "", "red": "", "purple": "", "blue": "", "sky": "", "lime": "", "pink": "", "black": "" }, "dateLastView": "2012-04-10T09:03:00.057Z", "shortUrl": "https://trello.com/b/OWsaWkrk" } ] webhooks = '<KEY>': "id": "<KEY>", "description": "New webhook", "idModel": "4f0a922ff25c53695a0cb1d7", "callbackURL": "https://jianliao.com/webhook", "active": true '4<KEY>8<KEY>f6<KEY>28<KEY>1c82841b3c0': "id": "<KEY>", "description": "New new webhook", "idModel": "4f83f6fab28be1c82841b3c0", "callbackURL": "https://jianliao.com/webhook", "active": true app = express() app.get '/members/me/boards', (req, res) -> res.send boards app.post '/webhooks', (req, res) -> should(req.body.idModel).not.empty should(webhooks[req.body.idModel]).not.empty res.send webhooks[req.body.idModel] app.delete '/webhooks/:id', (req, res) -> should(webhooks[req.params.id]).not.empty res.send {} module.exports = app
true
express = require 'express' _ = require 'lodash' should = require 'should' boards = [ { "name": "PI:NAME:<NAME>END_PI", "desc": "", "descData": null, "closed": false, "idOrganization": null, "pinned": null, "invitations": null, "shortLink": "GkR7AsMR", "powerUps": [ "calendar" ], "dateLastActivity": "2016-03-08T09:32:52.044Z", "idTags": [], "id": "PI:KEY:<KEY>END_PI", "invited": false, "starred": false, "url": "https://trello.com/b/GkR7AsMR/todonow", "prefs": { "permissionLevel": "private", "voting": "disabled", "comments": "members", "invitations": "members", "selfJoin": false, "cardCovers": true, "calendarFeedEnabled": false, "background": "green", "backgroundImage": null, "backgroundImageScaled": null, "backgroundTile": false, "backgroundBrightness": "dark", "backgroundColor": "#519839", "canBePublic": true, "canBeOrg": true, "canBePrivate": true, "canInvite": true }, "memberships": [ { "id": "PI:KEY:<KEY>END_PI", "idMember": "PI:KEY:<KEY>END_PI", "memberType": "admin", "unconfirmed": false, "deactivated": false } ], "subscribed": false, "labelNames": { "green": "", "yellow": "", "orange": "", "red": "", "purple": "", "blue": "", "sky": "", "lime": "", "pink": "", "black": "" }, "dateLastView": "2016-03-08T09:37:53.442Z", "shortUrl": "https://trello.com/b/GkR7AsMR" }, { "name": "Welcome Board", "desc": "", "descData": null, "closed": true, "idOrganization": null, "pinned": null, "invitations": null, "shortLink": "OWsaWkrk", "powerUps": [ "voting" ], "dateLastActivity": null, "idTags": [], "id": "PI:KEY:<KEY>END_PI", "invited": false, "starred": false, "url": "https://trello.com/b/OWsaWkrk/welcome-board", "prefs": { "permissionLevel": "private", "voting": "members", "comments": "members", "invitations": "members", "selfJoin": true, "cardCovers": true, "calendarFeedEnabled": false, "background": "blue", "backgroundImage": null, "backgroundImageScaled": null, "backgroundTile": false, "backgroundBrightness": "dark", "backgroundColor": "#0079BF", "canBePublic": true, "canBeOrg": true, "canBePrivate": true, "canInvite": true }, "memberships": [ { "id": "PI:KEY:<KEY>END_PI", "idMember": "PI:KEY:<KEY>END_PI", "memberType": "normal", "unconfirmed": false, "deactivated": false }, { "id": "PI:KEY:<KEY>END_PI", "idMember": "PI:KEY:<KEY>END_PI", "memberType": "admin", "unconfirmed": false, "deactivated": false } ], "subscribed": false, "labelNames": { "green": "", "yellow": "", "orange": "", "red": "", "purple": "", "blue": "", "sky": "", "lime": "", "pink": "", "black": "" }, "dateLastView": "2012-04-10T09:03:00.057Z", "shortUrl": "https://trello.com/b/OWsaWkrk" } ] webhooks = 'PI:KEY:<KEY>END_PI': "id": "PI:KEY:<KEY>END_PI", "description": "New webhook", "idModel": "4f0a922ff25c53695a0cb1d7", "callbackURL": "https://jianliao.com/webhook", "active": true '4PI:KEY:<KEY>END_PI8PI:KEY:<KEY>END_PIf6PI:KEY:<KEY>END_PI28PI:KEY:<KEY>END_PI1c82841b3c0': "id": "PI:KEY:<KEY>END_PI", "description": "New new webhook", "idModel": "4f83f6fab28be1c82841b3c0", "callbackURL": "https://jianliao.com/webhook", "active": true app = express() app.get '/members/me/boards', (req, res) -> res.send boards app.post '/webhooks', (req, res) -> should(req.body.idModel).not.empty should(webhooks[req.body.idModel]).not.empty res.send webhooks[req.body.idModel] app.delete '/webhooks/:id', (req, res) -> should(webhooks[req.params.id]).not.empty res.send {} module.exports = app
[ { "context": "#####################################\n# Created by Markus on 23/10/2015.\n##################################", "end": 73, "score": 0.9977468848228455, "start": 67, "tag": "NAME", "value": "Markus" } ]
server/logic/nlp.coffee
MooqitaSFH/worklearn
0
##################################################### # Created by Markus on 23/10/2015. ##################################################### ##################################################### _task_map = "profiles_resume": "n_gram" "organizations_description": "n_gram" "jobs_description": "n_gram" "jobs_title": "n_gram" "challenges_title": "n_gram" "challenges_content": "n_gram" "profiles_city": ["entity", "place"] "profiles_state": ["entity", "place"] "profiles_given_name": ["entity", "person"] "profiles_middle_name": ["entity", "person"] "profiles_family_name": ["entity", "person"] "organizations_name": ["entity", "org"] ##################################################### class @NLPTask constructor: (@payload, @task, @owner_id) -> @priority = 0 @attempts = 0 @locked_by = null @locked_at = null @last_error = null ##################################################### # collection_name: Name of the collection the text to # analyse can be found. # item_id: _id of the object that contains # the text. # field: the field name of the collection ##################################################### ##################################################### @handle_text = (collection, item, field, user) -> if typeof collection != "string" collection = get_collection_name(collection) if typeof item != "string" item = item._id if not item throw new Meteor.Error "Item not found." if user if typeof user != "string" user = user._id key = (collection + "_" + field) task = _task_map[key] if not task return null sub_task = "" if typeof task != "string" sub_task = task[1] task = task[0] meta_data = sub_taks: sub_task collection_name: collection item_id: item field: field owner_id: user ds = new @NLPTask(meta_data, task, user) set_id = NLPTasks.insert(ds) return set_id
49264
##################################################### # Created by <NAME> on 23/10/2015. ##################################################### ##################################################### _task_map = "profiles_resume": "n_gram" "organizations_description": "n_gram" "jobs_description": "n_gram" "jobs_title": "n_gram" "challenges_title": "n_gram" "challenges_content": "n_gram" "profiles_city": ["entity", "place"] "profiles_state": ["entity", "place"] "profiles_given_name": ["entity", "person"] "profiles_middle_name": ["entity", "person"] "profiles_family_name": ["entity", "person"] "organizations_name": ["entity", "org"] ##################################################### class @NLPTask constructor: (@payload, @task, @owner_id) -> @priority = 0 @attempts = 0 @locked_by = null @locked_at = null @last_error = null ##################################################### # collection_name: Name of the collection the text to # analyse can be found. # item_id: _id of the object that contains # the text. # field: the field name of the collection ##################################################### ##################################################### @handle_text = (collection, item, field, user) -> if typeof collection != "string" collection = get_collection_name(collection) if typeof item != "string" item = item._id if not item throw new Meteor.Error "Item not found." if user if typeof user != "string" user = user._id key = (collection + "_" + field) task = _task_map[key] if not task return null sub_task = "" if typeof task != "string" sub_task = task[1] task = task[0] meta_data = sub_taks: sub_task collection_name: collection item_id: item field: field owner_id: user ds = new @NLPTask(meta_data, task, user) set_id = NLPTasks.insert(ds) return set_id
true
##################################################### # Created by PI:NAME:<NAME>END_PI on 23/10/2015. ##################################################### ##################################################### _task_map = "profiles_resume": "n_gram" "organizations_description": "n_gram" "jobs_description": "n_gram" "jobs_title": "n_gram" "challenges_title": "n_gram" "challenges_content": "n_gram" "profiles_city": ["entity", "place"] "profiles_state": ["entity", "place"] "profiles_given_name": ["entity", "person"] "profiles_middle_name": ["entity", "person"] "profiles_family_name": ["entity", "person"] "organizations_name": ["entity", "org"] ##################################################### class @NLPTask constructor: (@payload, @task, @owner_id) -> @priority = 0 @attempts = 0 @locked_by = null @locked_at = null @last_error = null ##################################################### # collection_name: Name of the collection the text to # analyse can be found. # item_id: _id of the object that contains # the text. # field: the field name of the collection ##################################################### ##################################################### @handle_text = (collection, item, field, user) -> if typeof collection != "string" collection = get_collection_name(collection) if typeof item != "string" item = item._id if not item throw new Meteor.Error "Item not found." if user if typeof user != "string" user = user._id key = (collection + "_" + field) task = _task_map[key] if not task return null sub_task = "" if typeof task != "string" sub_task = task[1] task = task[0] meta_data = sub_taks: sub_task collection_name: collection item_id: item field: field owner_id: user ds = new @NLPTask(meta_data, task, user) set_id = NLPTasks.insert(ds) return set_id
[ { "context": "verview Forbid target='_blank' attribute\n# @author Kevin Miller\n###\n'use strict'\n\n# -----------------------------", "end": 76, "score": 0.9987582564353943, "start": 64, "tag": "NAME", "value": "Kevin Miller" } ]
src/tests/rules/jsx-no-target-blank.coffee
helixbass/eslint-plugin-coffee
21
###* # @fileoverview Forbid target='_blank' attribute # @author Kevin Miller ### 'use strict' # ------------------------------------------------------------------------------ # Requirements # ------------------------------------------------------------------------------ rule = require '../../rules/jsx-no-target-blank' {RuleTester} = require 'eslint' path = require 'path' # ------------------------------------------------------------------------------ # Tests # ------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' defaultErrors = [ message: 'Using target="_blank" without rel="noreferrer" is a security risk:' + ' see https://html.spec.whatwg.org/multipage/links.html#link-type-noopener' ] ruleTester.run 'jsx-no-target-blank', rule, valid: [ code: '<a href="foobar"></a>' , code: '<a randomTag></a>' , # , # code: '<a target />' code: '<a href="foobar" target="_blank" rel="noopener noreferrer"></a>' , code: '<a href="foobar" target="_blank" rel="noreferrer"></a>' , code: '<a href="foobar" target="_blank" rel={"noreferrer"}></a>' , code: '<a target="_blank" {...spreadProps} rel="noopener noreferrer"></a>' , code: '<a {...spreadProps} target="_blank" rel="noopener noreferrer" href="http://example.com">s</a>' , code: '<a target="_blank" rel="noopener noreferrer" {...spreadProps}></a>' , code: '<p target="_blank"></p>' , code: '<a href="foobar" target="_BLANK" rel="NOOPENER noreferrer"></a>' , code: '<a target="_blank" rel={relValue}></a>' , code: '<a target={targetValue} rel="noopener noreferrer"></a>' , code: '<a target={targetValue} href="relative/path"></a>' , code: '<a target={targetValue} href="/absolute/path"></a>' , code: '<a target="_blank" href={ dynamicLink }></a>' options: [enforceDynamicLinks: 'never'] ] invalid: [ code: '<a target="_blank" href="http://example.com"></a>' errors: defaultErrors , code: '<a target={if b then "_blank"} href="http://example.com"></a>' errors: defaultErrors , code: '<a target="_blank" rel="" href="http://example.com"></a>' errors: defaultErrors , code: '<a target="_blank" rel="noopenernoreferrer" href="http://example.com"></a>' errors: defaultErrors , code: '<a target="_BLANK" href="http://example.com"></a>' errors: defaultErrors , code: '<a target="_blank" href="//example.com"></a>' errors: defaultErrors , code: '<a target="_blank" href="//example.com" rel={true}></a>' errors: defaultErrors , code: '<a target="_blank" href="//example.com" rel={3}></a>' errors: defaultErrors , code: '<a target="_blank" href="//example.com" rel={null}></a>' errors: defaultErrors , code: '<a target="_blank" href="//example.com" rel></a>' errors: defaultErrors , code: '<a target="_blank" href={ dynamicLink }></a>' errors: defaultErrors , code: '<a target="_blank" href={ dynamicLink }></a>' options: [enforceDynamicLinks: 'always'] errors: defaultErrors ]
97692
###* # @fileoverview Forbid target='_blank' attribute # @author <NAME> ### 'use strict' # ------------------------------------------------------------------------------ # Requirements # ------------------------------------------------------------------------------ rule = require '../../rules/jsx-no-target-blank' {RuleTester} = require 'eslint' path = require 'path' # ------------------------------------------------------------------------------ # Tests # ------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' defaultErrors = [ message: 'Using target="_blank" without rel="noreferrer" is a security risk:' + ' see https://html.spec.whatwg.org/multipage/links.html#link-type-noopener' ] ruleTester.run 'jsx-no-target-blank', rule, valid: [ code: '<a href="foobar"></a>' , code: '<a randomTag></a>' , # , # code: '<a target />' code: '<a href="foobar" target="_blank" rel="noopener noreferrer"></a>' , code: '<a href="foobar" target="_blank" rel="noreferrer"></a>' , code: '<a href="foobar" target="_blank" rel={"noreferrer"}></a>' , code: '<a target="_blank" {...spreadProps} rel="noopener noreferrer"></a>' , code: '<a {...spreadProps} target="_blank" rel="noopener noreferrer" href="http://example.com">s</a>' , code: '<a target="_blank" rel="noopener noreferrer" {...spreadProps}></a>' , code: '<p target="_blank"></p>' , code: '<a href="foobar" target="_BLANK" rel="NOOPENER noreferrer"></a>' , code: '<a target="_blank" rel={relValue}></a>' , code: '<a target={targetValue} rel="noopener noreferrer"></a>' , code: '<a target={targetValue} href="relative/path"></a>' , code: '<a target={targetValue} href="/absolute/path"></a>' , code: '<a target="_blank" href={ dynamicLink }></a>' options: [enforceDynamicLinks: 'never'] ] invalid: [ code: '<a target="_blank" href="http://example.com"></a>' errors: defaultErrors , code: '<a target={if b then "_blank"} href="http://example.com"></a>' errors: defaultErrors , code: '<a target="_blank" rel="" href="http://example.com"></a>' errors: defaultErrors , code: '<a target="_blank" rel="noopenernoreferrer" href="http://example.com"></a>' errors: defaultErrors , code: '<a target="_BLANK" href="http://example.com"></a>' errors: defaultErrors , code: '<a target="_blank" href="//example.com"></a>' errors: defaultErrors , code: '<a target="_blank" href="//example.com" rel={true}></a>' errors: defaultErrors , code: '<a target="_blank" href="//example.com" rel={3}></a>' errors: defaultErrors , code: '<a target="_blank" href="//example.com" rel={null}></a>' errors: defaultErrors , code: '<a target="_blank" href="//example.com" rel></a>' errors: defaultErrors , code: '<a target="_blank" href={ dynamicLink }></a>' errors: defaultErrors , code: '<a target="_blank" href={ dynamicLink }></a>' options: [enforceDynamicLinks: 'always'] errors: defaultErrors ]
true
###* # @fileoverview Forbid target='_blank' attribute # @author PI:NAME:<NAME>END_PI ### 'use strict' # ------------------------------------------------------------------------------ # Requirements # ------------------------------------------------------------------------------ rule = require '../../rules/jsx-no-target-blank' {RuleTester} = require 'eslint' path = require 'path' # ------------------------------------------------------------------------------ # Tests # ------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' defaultErrors = [ message: 'Using target="_blank" without rel="noreferrer" is a security risk:' + ' see https://html.spec.whatwg.org/multipage/links.html#link-type-noopener' ] ruleTester.run 'jsx-no-target-blank', rule, valid: [ code: '<a href="foobar"></a>' , code: '<a randomTag></a>' , # , # code: '<a target />' code: '<a href="foobar" target="_blank" rel="noopener noreferrer"></a>' , code: '<a href="foobar" target="_blank" rel="noreferrer"></a>' , code: '<a href="foobar" target="_blank" rel={"noreferrer"}></a>' , code: '<a target="_blank" {...spreadProps} rel="noopener noreferrer"></a>' , code: '<a {...spreadProps} target="_blank" rel="noopener noreferrer" href="http://example.com">s</a>' , code: '<a target="_blank" rel="noopener noreferrer" {...spreadProps}></a>' , code: '<p target="_blank"></p>' , code: '<a href="foobar" target="_BLANK" rel="NOOPENER noreferrer"></a>' , code: '<a target="_blank" rel={relValue}></a>' , code: '<a target={targetValue} rel="noopener noreferrer"></a>' , code: '<a target={targetValue} href="relative/path"></a>' , code: '<a target={targetValue} href="/absolute/path"></a>' , code: '<a target="_blank" href={ dynamicLink }></a>' options: [enforceDynamicLinks: 'never'] ] invalid: [ code: '<a target="_blank" href="http://example.com"></a>' errors: defaultErrors , code: '<a target={if b then "_blank"} href="http://example.com"></a>' errors: defaultErrors , code: '<a target="_blank" rel="" href="http://example.com"></a>' errors: defaultErrors , code: '<a target="_blank" rel="noopenernoreferrer" href="http://example.com"></a>' errors: defaultErrors , code: '<a target="_BLANK" href="http://example.com"></a>' errors: defaultErrors , code: '<a target="_blank" href="//example.com"></a>' errors: defaultErrors , code: '<a target="_blank" href="//example.com" rel={true}></a>' errors: defaultErrors , code: '<a target="_blank" href="//example.com" rel={3}></a>' errors: defaultErrors , code: '<a target="_blank" href="//example.com" rel={null}></a>' errors: defaultErrors , code: '<a target="_blank" href="//example.com" rel></a>' errors: defaultErrors , code: '<a target="_blank" href={ dynamicLink }></a>' errors: defaultErrors , code: '<a target="_blank" href={ dynamicLink }></a>' options: [enforceDynamicLinks: 'always'] errors: defaultErrors ]
[ { "context": " Xyz: 'xyz'\n Abc: 'abc'\n Name: 'john'\n xml = \"\"\"\n <Data xmlns=\"#{xmlns}\">\n ", "end": 1970, "score": 0.9984635710716248, "start": 1966, "tag": "NAME", "value": "john" }, { "context": "= \"\"\"\n <Data xmlns=\"#{xmlns}\">\n ...
test/unit/xml/builder.spec.coffee
explodingbarrel/aws-sdk-js
1
# Copyright 2011-2012 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). You # may not use this file except in compliance with the License. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompanying this file. This file 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. helpers = require('../../helpers') AWS = helpers.AWS matchXML = helpers.matchXML describe 'AWS.XML.Builder', -> xmlns = 'http://mockservice.com/xmlns' toXML = (rules, params, options) -> options = {} if (!options) options.xmlNamespace = xmlns builder = new AWS.XML.Builder('Data', rules, options) builder.toXML(params) describe 'toXML', -> it 'returns an empty element when there are no params', -> expect(toXML(null, null)).toEqual("<Data xmlns=\"#{xmlns}\"/>") it 'wraps simple structures with location of body', -> rules = {Name:{},State:{}} params = { Name:'abc', State: 'Enabled' } xml = """ <Data xmlns="#{xmlns}"> <Name>abc</Name> <State>Enabled</State> </Data> """ matchXML(toXML(rules, params), xml) it 'orders xml members by the order they appear in the rules', -> rules = {Count:{t:'i'},State:{}} params = { State: 'Disabled', Count: 123 } xml = """ <Data xmlns="#{xmlns}"> <Count>123</Count> <State>Disabled</State> </Data> """ matchXML(toXML(rules, params), xml) it 'can serializes structures into XML', -> rules = Name: {} Details: t: 'o' m: Abc: {} Xyz: {} params = Details: Xyz: 'xyz' Abc: 'abc' Name: 'john' xml = """ <Data xmlns="#{xmlns}"> <Name>john</Name> <Details> <Abc>abc</Abc> <Xyz>xyz</Xyz> </Details> </Data> """ matchXML(toXML(rules, params), xml) it 'serializes empty structures as empty element', -> rules = {Config:{t:'o',m:{Foo:{},Bar:{}}}} params = { Config: {} } xml = """ <Data xmlns="#{xmlns}"> <Config/> </Data> """ matchXML(toXML(rules, params), xml) it 'does not serialize missing members', -> rules = {Config:{t:'o',m:{Foo:{},Bar:{}}}} params = { Config: { Foo: 'abc' } } xml = """ <Data xmlns="#{xmlns}"> <Config> <Foo>abc</Foo> </Config> </Data> """ matchXML(toXML(rules, params), xml) describe 'lists', -> it 'serializes lists (default member names)', -> rules = {Aliases:{t:'a',m:{}}} params = {Aliases:['abc','mno','xyz']} xml = """ <Data xmlns="#{xmlns}"> <Aliases> <member>abc</member> <member>mno</member> <member>xyz</member> </Aliases> </Data> """ matchXML(toXML(rules, params), xml) it 'serializes lists (custom member names)', -> rules = {Aliases:{t:'a',m:{n:'Alias'}}} params = {Aliases:['abc','mno','xyz']} xml = """ <Data xmlns="#{xmlns}"> <Aliases> <Alias>abc</Alias> <Alias>mno</Alias> <Alias>xyz</Alias> </Aliases> </Data> """ matchXML(toXML(rules, params), xml) it 'includes lists elements even if they have no members', -> rules = {Aliases:{t:'a',m:{n:'Alias'}}} params = {Aliases:[]} xml = """ <Data xmlns="#{xmlns}"> <Aliases/> </Data> """ matchXML(toXML(rules, params), xml) it 'serializes lists of structures', -> rules = Points: t: 'a' m: t: 'o' n: 'Point' m: X: {t:'n'} Y: {t:'n'} params = {Points:[{X:1.2,Y:2.1},{X:3.4,Y:4.3}]} xml = """ <Data xmlns="#{xmlns}"> <Points> <Point> <X>1.2</X> <Y>2.1</Y> </Point> <Point> <X>3.4</X> <Y>4.3</Y> </Point> </Points> </Data> """ matchXML(toXML(rules, params), xml) describe 'numbers', -> it 'integers', -> rules = {Count:{t:'i'}} params = { Count: 123.0 } xml = """ <Data xmlns="#{xmlns}"> <Count>123</Count> </Data> """ matchXML(toXML(rules, params), xml) it 'floats', -> rules = {Count:{t:'n'}} params = { Count: 123.123 } xml = """ <Data xmlns="#{xmlns}"> <Count>123.123</Count> </Data> """ matchXML(toXML(rules, params), xml) describe 'timestamps', -> it 'true', -> rules = {Enabled:{t:'b'}} params = { Enabled: true } xml = """ <Data xmlns="#{xmlns}"> <Enabled>true</Enabled> </Data> """ matchXML(toXML(rules, params), xml) it 'false', -> rules = {Enabled:{t:'b'}} params = { Enabled: false } xml = """ <Data xmlns="#{xmlns}"> <Enabled>false</Enabled> </Data> """ matchXML(toXML(rules, params), xml) describe 'timestamps', -> time = new Date() it 'iso8601', -> rules = {Expires:{t:'t'}} params = { Expires: time } xml = """ <Data xmlns="#{xmlns}"> <Expires>#{AWS.util.date.iso8601(time)}</Expires> </Data> """ matchXML(toXML(rules, params, {timestampFormat:'iso8601'}), xml) it 'rfc822', -> rules = {Expires:{t:'t'}} params = { Expires: time } xml = """ <Data xmlns="#{xmlns}"> <Expires>#{AWS.util.date.rfc822(time)}</Expires> </Data> """ matchXML(toXML(rules, params, {timestampFormat:'rfc822'}), xml) it 'unix timestamp', -> rules = {Expires:{t:'t'}} params = { Expires: time } xml = """ <Data xmlns="#{xmlns}"> <Expires>#{AWS.util.date.unixTimestamp(time)}</Expires> </Data> """ matchXML(toXML(rules, params, {timestampFormat:'unixTimestamp'}), xml)
22328
# Copyright 2011-2012 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). You # may not use this file except in compliance with the License. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompanying this file. This file 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. helpers = require('../../helpers') AWS = helpers.AWS matchXML = helpers.matchXML describe 'AWS.XML.Builder', -> xmlns = 'http://mockservice.com/xmlns' toXML = (rules, params, options) -> options = {} if (!options) options.xmlNamespace = xmlns builder = new AWS.XML.Builder('Data', rules, options) builder.toXML(params) describe 'toXML', -> it 'returns an empty element when there are no params', -> expect(toXML(null, null)).toEqual("<Data xmlns=\"#{xmlns}\"/>") it 'wraps simple structures with location of body', -> rules = {Name:{},State:{}} params = { Name:'abc', State: 'Enabled' } xml = """ <Data xmlns="#{xmlns}"> <Name>abc</Name> <State>Enabled</State> </Data> """ matchXML(toXML(rules, params), xml) it 'orders xml members by the order they appear in the rules', -> rules = {Count:{t:'i'},State:{}} params = { State: 'Disabled', Count: 123 } xml = """ <Data xmlns="#{xmlns}"> <Count>123</Count> <State>Disabled</State> </Data> """ matchXML(toXML(rules, params), xml) it 'can serializes structures into XML', -> rules = Name: {} Details: t: 'o' m: Abc: {} Xyz: {} params = Details: Xyz: 'xyz' Abc: 'abc' Name: '<NAME>' xml = """ <Data xmlns="#{xmlns}"> <Name><NAME></Name> <Details> <Abc>abc</Abc> <Xyz>xyz</Xyz> </Details> </Data> """ matchXML(toXML(rules, params), xml) it 'serializes empty structures as empty element', -> rules = {Config:{t:'o',m:{Foo:{},Bar:{}}}} params = { Config: {} } xml = """ <Data xmlns="#{xmlns}"> <Config/> </Data> """ matchXML(toXML(rules, params), xml) it 'does not serialize missing members', -> rules = {Config:{t:'o',m:{Foo:{},Bar:{}}}} params = { Config: { Foo: 'abc' } } xml = """ <Data xmlns="#{xmlns}"> <Config> <Foo>abc</Foo> </Config> </Data> """ matchXML(toXML(rules, params), xml) describe 'lists', -> it 'serializes lists (default member names)', -> rules = {Aliases:{t:'a',m:{}}} params = {Aliases:['abc','mno','xyz']} xml = """ <Data xmlns="#{xmlns}"> <Aliases> <member>abc</member> <member>mno</member> <member>xyz</member> </Aliases> </Data> """ matchXML(toXML(rules, params), xml) it 'serializes lists (custom member names)', -> rules = {Aliases:{t:'a',m:{n:'Alias'}}} params = {Aliases:['abc','mno','xyz']} xml = """ <Data xmlns="#{xmlns}"> <Aliases> <Alias>abc</Alias> <Alias>mno</Alias> <Alias>xyz</Alias> </Aliases> </Data> """ matchXML(toXML(rules, params), xml) it 'includes lists elements even if they have no members', -> rules = {Aliases:{t:'a',m:{n:'Alias'}}} params = {Aliases:[]} xml = """ <Data xmlns="#{xmlns}"> <Aliases/> </Data> """ matchXML(toXML(rules, params), xml) it 'serializes lists of structures', -> rules = Points: t: 'a' m: t: 'o' n: 'Point' m: X: {t:'n'} Y: {t:'n'} params = {Points:[{X:1.2,Y:2.1},{X:3.4,Y:4.3}]} xml = """ <Data xmlns="#{xmlns}"> <Points> <Point> <X>1.2</X> <Y>2.1</Y> </Point> <Point> <X>3.4</X> <Y>4.3</Y> </Point> </Points> </Data> """ matchXML(toXML(rules, params), xml) describe 'numbers', -> it 'integers', -> rules = {Count:{t:'i'}} params = { Count: 123.0 } xml = """ <Data xmlns="#{xmlns}"> <Count>123</Count> </Data> """ matchXML(toXML(rules, params), xml) it 'floats', -> rules = {Count:{t:'n'}} params = { Count: 123.123 } xml = """ <Data xmlns="#{xmlns}"> <Count>123.123</Count> </Data> """ matchXML(toXML(rules, params), xml) describe 'timestamps', -> it 'true', -> rules = {Enabled:{t:'b'}} params = { Enabled: true } xml = """ <Data xmlns="#{xmlns}"> <Enabled>true</Enabled> </Data> """ matchXML(toXML(rules, params), xml) it 'false', -> rules = {Enabled:{t:'b'}} params = { Enabled: false } xml = """ <Data xmlns="#{xmlns}"> <Enabled>false</Enabled> </Data> """ matchXML(toXML(rules, params), xml) describe 'timestamps', -> time = new Date() it 'iso8601', -> rules = {Expires:{t:'t'}} params = { Expires: time } xml = """ <Data xmlns="#{xmlns}"> <Expires>#{AWS.util.date.iso8601(time)}</Expires> </Data> """ matchXML(toXML(rules, params, {timestampFormat:'iso8601'}), xml) it 'rfc822', -> rules = {Expires:{t:'t'}} params = { Expires: time } xml = """ <Data xmlns="#{xmlns}"> <Expires>#{AWS.util.date.rfc822(time)}</Expires> </Data> """ matchXML(toXML(rules, params, {timestampFormat:'rfc822'}), xml) it 'unix timestamp', -> rules = {Expires:{t:'t'}} params = { Expires: time } xml = """ <Data xmlns="#{xmlns}"> <Expires>#{AWS.util.date.unixTimestamp(time)}</Expires> </Data> """ matchXML(toXML(rules, params, {timestampFormat:'unixTimestamp'}), xml)
true
# Copyright 2011-2012 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). You # may not use this file except in compliance with the License. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompanying this file. This file 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. helpers = require('../../helpers') AWS = helpers.AWS matchXML = helpers.matchXML describe 'AWS.XML.Builder', -> xmlns = 'http://mockservice.com/xmlns' toXML = (rules, params, options) -> options = {} if (!options) options.xmlNamespace = xmlns builder = new AWS.XML.Builder('Data', rules, options) builder.toXML(params) describe 'toXML', -> it 'returns an empty element when there are no params', -> expect(toXML(null, null)).toEqual("<Data xmlns=\"#{xmlns}\"/>") it 'wraps simple structures with location of body', -> rules = {Name:{},State:{}} params = { Name:'abc', State: 'Enabled' } xml = """ <Data xmlns="#{xmlns}"> <Name>abc</Name> <State>Enabled</State> </Data> """ matchXML(toXML(rules, params), xml) it 'orders xml members by the order they appear in the rules', -> rules = {Count:{t:'i'},State:{}} params = { State: 'Disabled', Count: 123 } xml = """ <Data xmlns="#{xmlns}"> <Count>123</Count> <State>Disabled</State> </Data> """ matchXML(toXML(rules, params), xml) it 'can serializes structures into XML', -> rules = Name: {} Details: t: 'o' m: Abc: {} Xyz: {} params = Details: Xyz: 'xyz' Abc: 'abc' Name: 'PI:NAME:<NAME>END_PI' xml = """ <Data xmlns="#{xmlns}"> <Name>PI:NAME:<NAME>END_PI</Name> <Details> <Abc>abc</Abc> <Xyz>xyz</Xyz> </Details> </Data> """ matchXML(toXML(rules, params), xml) it 'serializes empty structures as empty element', -> rules = {Config:{t:'o',m:{Foo:{},Bar:{}}}} params = { Config: {} } xml = """ <Data xmlns="#{xmlns}"> <Config/> </Data> """ matchXML(toXML(rules, params), xml) it 'does not serialize missing members', -> rules = {Config:{t:'o',m:{Foo:{},Bar:{}}}} params = { Config: { Foo: 'abc' } } xml = """ <Data xmlns="#{xmlns}"> <Config> <Foo>abc</Foo> </Config> </Data> """ matchXML(toXML(rules, params), xml) describe 'lists', -> it 'serializes lists (default member names)', -> rules = {Aliases:{t:'a',m:{}}} params = {Aliases:['abc','mno','xyz']} xml = """ <Data xmlns="#{xmlns}"> <Aliases> <member>abc</member> <member>mno</member> <member>xyz</member> </Aliases> </Data> """ matchXML(toXML(rules, params), xml) it 'serializes lists (custom member names)', -> rules = {Aliases:{t:'a',m:{n:'Alias'}}} params = {Aliases:['abc','mno','xyz']} xml = """ <Data xmlns="#{xmlns}"> <Aliases> <Alias>abc</Alias> <Alias>mno</Alias> <Alias>xyz</Alias> </Aliases> </Data> """ matchXML(toXML(rules, params), xml) it 'includes lists elements even if they have no members', -> rules = {Aliases:{t:'a',m:{n:'Alias'}}} params = {Aliases:[]} xml = """ <Data xmlns="#{xmlns}"> <Aliases/> </Data> """ matchXML(toXML(rules, params), xml) it 'serializes lists of structures', -> rules = Points: t: 'a' m: t: 'o' n: 'Point' m: X: {t:'n'} Y: {t:'n'} params = {Points:[{X:1.2,Y:2.1},{X:3.4,Y:4.3}]} xml = """ <Data xmlns="#{xmlns}"> <Points> <Point> <X>1.2</X> <Y>2.1</Y> </Point> <Point> <X>3.4</X> <Y>4.3</Y> </Point> </Points> </Data> """ matchXML(toXML(rules, params), xml) describe 'numbers', -> it 'integers', -> rules = {Count:{t:'i'}} params = { Count: 123.0 } xml = """ <Data xmlns="#{xmlns}"> <Count>123</Count> </Data> """ matchXML(toXML(rules, params), xml) it 'floats', -> rules = {Count:{t:'n'}} params = { Count: 123.123 } xml = """ <Data xmlns="#{xmlns}"> <Count>123.123</Count> </Data> """ matchXML(toXML(rules, params), xml) describe 'timestamps', -> it 'true', -> rules = {Enabled:{t:'b'}} params = { Enabled: true } xml = """ <Data xmlns="#{xmlns}"> <Enabled>true</Enabled> </Data> """ matchXML(toXML(rules, params), xml) it 'false', -> rules = {Enabled:{t:'b'}} params = { Enabled: false } xml = """ <Data xmlns="#{xmlns}"> <Enabled>false</Enabled> </Data> """ matchXML(toXML(rules, params), xml) describe 'timestamps', -> time = new Date() it 'iso8601', -> rules = {Expires:{t:'t'}} params = { Expires: time } xml = """ <Data xmlns="#{xmlns}"> <Expires>#{AWS.util.date.iso8601(time)}</Expires> </Data> """ matchXML(toXML(rules, params, {timestampFormat:'iso8601'}), xml) it 'rfc822', -> rules = {Expires:{t:'t'}} params = { Expires: time } xml = """ <Data xmlns="#{xmlns}"> <Expires>#{AWS.util.date.rfc822(time)}</Expires> </Data> """ matchXML(toXML(rules, params, {timestampFormat:'rfc822'}), xml) it 'unix timestamp', -> rules = {Expires:{t:'t'}} params = { Expires: time } xml = """ <Data xmlns="#{xmlns}"> <Expires>#{AWS.util.date.unixTimestamp(time)}</Expires> </Data> """ matchXML(toXML(rules, params, {timestampFormat:'unixTimestamp'}), xml)
[ { "context": "\n\nItemsSlots = () ->\n this.slots = []\n keys = ['z', 'x', 'c', 'v', 'b', 'n'];\n nameItems = ['dagon', 'ethereal', 'eul',\n ", "end": 1027, "score": 0.9798027873039246, "start": 1001, "tag": "KEY", "value": "z', 'x', 'c', 'v', 'b', 'n" } ]
assets/js/src/itemsSlots.coffee
juancjara/dota-game
0
Item = (data) -> data = data or {} this.name = data.name or '' this.srcImg = data.srcImg or '' this.clickNeeded = data.clickNeeded or false this.secondsCd = data.secondsCd or 0 this.onCooldown = false this.countdown = null this.hitTime = data.hitTime or 0 this.duration = data.duration or 0 this.hitDmg = data.hitDamage or 0 this.dmgPerSecond = data.damagePerSecond or 0 this.endDurationDmg = data.endDurationDmg or 0 this.effect = data.effect or '' return Item::finishCd = () -> this.onCooldown = false; return Item::stop = () -> if this.countdown this.countdown.stop() this.onCooldown = false return Item::fun = (click)-> if !this.clickNeeded or (this.clickNeeded and click) dispatcher.unsubscribe 'clickTarget', func dispatcher.execute 'useSkill', this else self = this func = () -> self.fun.bind(self)(true) return dispatcher.subscribe 'clickTarget', func return ItemsSlots = () -> this.slots = [] keys = ['z', 'x', 'c', 'v', 'b', 'n']; nameItems = ['dagon', 'ethereal', 'eul', 'scythe', 'shiva', 'no-item' ]; for i in [0..5] obj = { key: keys[i], item: itemMng.items[nameItems[i]] } this.slots.push obj return ItemsSlots::launch = (index) -> this.slots[index].item.fun() return ItemsSlots::clean = () -> this.slots = []; return if typeof exports isnt 'undefined' exports.ItemsSlots = ItemsSlots exports.Item = Item
89513
Item = (data) -> data = data or {} this.name = data.name or '' this.srcImg = data.srcImg or '' this.clickNeeded = data.clickNeeded or false this.secondsCd = data.secondsCd or 0 this.onCooldown = false this.countdown = null this.hitTime = data.hitTime or 0 this.duration = data.duration or 0 this.hitDmg = data.hitDamage or 0 this.dmgPerSecond = data.damagePerSecond or 0 this.endDurationDmg = data.endDurationDmg or 0 this.effect = data.effect or '' return Item::finishCd = () -> this.onCooldown = false; return Item::stop = () -> if this.countdown this.countdown.stop() this.onCooldown = false return Item::fun = (click)-> if !this.clickNeeded or (this.clickNeeded and click) dispatcher.unsubscribe 'clickTarget', func dispatcher.execute 'useSkill', this else self = this func = () -> self.fun.bind(self)(true) return dispatcher.subscribe 'clickTarget', func return ItemsSlots = () -> this.slots = [] keys = ['<KEY>']; nameItems = ['dagon', 'ethereal', 'eul', 'scythe', 'shiva', 'no-item' ]; for i in [0..5] obj = { key: keys[i], item: itemMng.items[nameItems[i]] } this.slots.push obj return ItemsSlots::launch = (index) -> this.slots[index].item.fun() return ItemsSlots::clean = () -> this.slots = []; return if typeof exports isnt 'undefined' exports.ItemsSlots = ItemsSlots exports.Item = Item
true
Item = (data) -> data = data or {} this.name = data.name or '' this.srcImg = data.srcImg or '' this.clickNeeded = data.clickNeeded or false this.secondsCd = data.secondsCd or 0 this.onCooldown = false this.countdown = null this.hitTime = data.hitTime or 0 this.duration = data.duration or 0 this.hitDmg = data.hitDamage or 0 this.dmgPerSecond = data.damagePerSecond or 0 this.endDurationDmg = data.endDurationDmg or 0 this.effect = data.effect or '' return Item::finishCd = () -> this.onCooldown = false; return Item::stop = () -> if this.countdown this.countdown.stop() this.onCooldown = false return Item::fun = (click)-> if !this.clickNeeded or (this.clickNeeded and click) dispatcher.unsubscribe 'clickTarget', func dispatcher.execute 'useSkill', this else self = this func = () -> self.fun.bind(self)(true) return dispatcher.subscribe 'clickTarget', func return ItemsSlots = () -> this.slots = [] keys = ['PI:KEY:<KEY>END_PI']; nameItems = ['dagon', 'ethereal', 'eul', 'scythe', 'shiva', 'no-item' ]; for i in [0..5] obj = { key: keys[i], item: itemMng.items[nameItems[i]] } this.slots.push obj return ItemsSlots::launch = (index) -> this.slots[index].item.fun() return ItemsSlots::clean = () -> this.slots = []; return if typeof exports isnt 'undefined' exports.ItemsSlots = ItemsSlots exports.Item = Item
[ { "context": "ck on refresh\n # (cf. https://github.com/krispo/angular-nvd3/issues/316).\n # The work-ar", "end": 14416, "score": 0.9996182322502136, "start": 14410, "tag": "USERNAME", "value": "krispo" }, { "context": " # @param key the modeling parameter key, e....
app/javascripts/controllers.coffee
ohsu-qin/qiprofile
0
define ['angular', 'lodash', 'ngsanitize', 'ngnvd3', 'resources', 'modelingChart', 'breast', 'sliceDisplay', 'collection'], (ng, _) -> ctlrs = ng.module( 'qiprofile.controllers', ['ngSanitize', 'nvd3', 'qiprofile.resources', 'qiprofile.modelingchart', 'qiprofile.breast', 'qiprofile.slicedisplay', 'qiprofile.collection'] ) # The local controller helper methods. ctlrs.factory 'ControllerHelper', [ '$location', ($location) -> # Resets the browser URL search parameters to include at most # a non-default project, since all other search parameters are # redundant. cleanBrowserUrl: (project) -> searchParams = {} # TODO - get the default project from a config file. if project != 'QIN' searchParams.project = project $location.search(searchParams) ] ctlrs.controller 'HomeCtrl', [ '$rootScope', '$scope', '$state', ($rootScope, $scope, $state) -> $scope.goHome = () -> project = $rootScope.project or 'QIN' $state.go('quip.home', project: project) ] ctlrs.controller 'HelpCtrl', [ '$rootScope', '$scope', ($rootScope, $scope) -> # Toggles the root scope showHelp flag. # This method and the showHelp flag are defined in the root # scope in order to share them with the partial template # home alert attribute directives. $rootScope.toggleHelp = -> $rootScope.showHelp = !$rootScope.showHelp # Unconditionally hide help when the location changes. $scope.$on '$locationChangeStart', (event, next, current) -> # Set the showHelp flag on the parent scope, since the # flag is shared with the sibling view scope. $rootScope.showHelp = false ] ctlrs.controller 'AccordionGroupCtrl', [ '$scope', ($scope) -> # The accordion group is initially open. $scope.isOpen = true ] ctlrs.controller 'CollectionListCtrl', [ '$rootScope', '$scope', 'project', 'collections', '$window', ($rootScope, $scope, project, collections, $window) -> # Capture the current project. $rootScope.project = project # Place the collections in the scope. $scope.collections = collections $scope.open = (url) -> $window.location.href = url # The help is always open to start with on this landing page. $rootScope.showHelp = true ] ctlrs.controller 'SubjectListCtrl', [ '$rootScope', '$scope', 'project', 'subjects', 'collections', ($rootScope, $scope, project, subjects, collections) -> # Capture the current project. $rootScope.project = project # Place the subjects and collections in the scope. $scope.subjects = subjects $scope.collections = collections ] ctlrs.controller 'CollectionDetailCtrl', [ '$rootScope', '$scope', 'project', 'collection', 'charting', 'Collection', 'ControllerHelper', ($rootScope, $scope, project, collection, charting, Collection, ControllerHelper) -> # Capture the current project. $rootScope.project = project # Place the collection in the scope. $scope.collection = collection # Obtain the valid data series and labels for the current collection # and put them in the scope. These comprise the X/Y axis dropdown # choices. The X axis choices contain all valid data series. The Y axis # choices may only include continuous data types. $scope.choices = Collection.dataSeriesChoices(collection) # Obtain the formatted scatterplot data. data = Collection.chartData(charting, Object.keys $scope.choices.x) # Obtain the chart padding for each data series - continuous data types # only. The padding for categorical data series is configured in the # correlation module chart rendering function. padding = Collection.chartPadding(data, Object.keys $scope.choices.y) # Put a copy of the default charts (X and Y axes) in the scope. # This charts object changes when the user selects a different # axis to chart. $scope.axes = _.clone(Collection.DEFAULT_AXES[collection]) # Check the validity of the default chart axes. # # TODO - Suppress charts where no data exists for a particular data # series throughout the collection. # checkAxes = (axis) -> axis.x in xAxisChoices or throw new Error "Invalid #{ collection } X-axis data series: " + "#{ axis.x }" axis.y in yAxisChoices or throw new Error "Invalid #{ collection } Y-axis data series: " + "#{ axis.y }" xAxisChoices = Object.keys($scope.choices.x) yAxisChoices = Object.keys($scope.choices.y) checkAxes(axis) for axis in $scope.axes # Place the chart configuration object in the scope. $scope.config = data: data padding: padding axes: $scope.axes # If the user changes any X or Y axis selection, then re-render the # charts. The watcher is invoked on initialization and whenever the # user changes the axes. On initialization, then the watcher is called # with new axes value argument identical (===) to the old value # argument. If the user changes the axes, then the watcher is called # with different new and old axes objects. watcher = (newValue, oldValue) -> # If the user changed the axes, then re-render the charts. if newValue != oldValue Collection.renderCharts($scope.config) # Since charts is an object, the objectEquality flag is set to true. # AngularJS then copies the object for later comparison and uses # angular.equals to recursively compare the object properties rather # than a simple === test, which is the default. $scope.$watch('axes', watcher, true) # If the project is the default, then remove it from the URL. ControllerHelper.cleanBrowserUrl($rootScope.project) ] ## The Subject Detail page controllers. ctlrs.controller 'SubjectDetailCtrl', [ '$rootScope', '$scope', 'subject', 'ControllerHelper', ($rootScope, $scope, subject, ControllerHelper) -> # Capture the current project. $rootScope.project = subject.project # Place the subject in scope. $scope.subject = subject # If the project is the default, then remove it from the URL. ControllerHelper.cleanBrowserUrl($rootScope.project) ] ctlrs.controller 'ScanVolumeSelectCtrl', [ '$scope', ($scope) -> # Place the scan protocol id in scope. $scope.protocolId = $scope.scan.protocol ] ctlrs.controller 'RegistrationVolumeSelectCtrl', [ '$scope', ($scope) -> # Place the registration protocol id in scope. $scope.protocolId = $scope.registration.protocol ] ctlrs.controller 'ScanProtocolCtrl', [ '$scope', '$uibModal', 'Resources', ($scope, $uibModal, Resources) -> # Open a modal window to display the scan procedure properties. $scope.open = -> $uibModal.open controller: 'ProtocolModalCtrl' templateUrl: '/partials/scan-protocol.html' size: 'sm' resolve: # Fetch the scan protocol. protocol: -> Resources.ScanProtocol.find(id: $scope.protocolId) ] ctlrs.controller 'RegistrationProtocolCtrl', [ '$scope', '$uibModal', 'Resources', ($scope, $uibModal, Resources) -> # Open a modal window to display the registration properties. $scope.open = -> $uibModal.open controller: 'ProtocolModalCtrl' templateUrl: '/partials/registration-protocol.html' size: 'sm' resolve: # Fetch the registration protocol. protocol: -> Resources.RegistrationProtocol.find(id: $scope.protocolId) ] ctlrs.controller 'ProtocolModalCtrl', [ '$scope', '$uibModalInstance', 'protocol', ($scope, $uibModalInstance, protocol) -> # Place the protocol object in the modal scope. $scope.protocol = protocol $scope.close = -> $uibModalInstance.close() ] ## The Imaging Profile pane controllers. ctlrs.controller 'SubjectModelingCtrl', [ '$scope', ($scope) -> # Place the modelings in scope. # Note: modelings is a subject property that is calculated # on the fly. Since the partials reference the modelings in # ng-switch and ng-repeat models, AngularJS sets up hidden # watches on this variable and redigests the partials whenever # the property value is calculated. If subject.modelings were # used instead of modelings, then AngularJS would enter an # infinite digest cycle. Placing the modelings variable in # scope here avoids this trap by fixing the value for the # course of the AngularJS page formatting. $scope.modelings = $scope.subject.modelings # The format button action. $scope.toggleModelingFormat = -> if $scope.modelingFormat is 'chart' $scope.modelingFormat = 'table' else if $scope.modelingFormat is 'table' $scope.modelingFormat = 'chart' else throw new Error "Modeling format is not recognized:" + " #{ $scope.modelingFormat }" # The modeling format is 'chart' if the subject has # more than one session, 'table' otherwise. if $scope.subject.isMultiSession() $scope.modelingFormat = 'chart' else $scope.modelingFormat = 'table' # The default modeling results index is the first. $scope.modelingIndex = 0 # Place the selected modeling in scope. $scope.$watch 'modelingIndex', (modelingIndex) -> $scope.selModeling = $scope.modelings[modelingIndex] ] ctlrs.controller 'PkModelingHelpCtrl', [ '$scope', '$uibModal', ($scope, $uibModal) -> $scope.open = -> $uibModal.open controller: 'PkModelingHelpModalCtrl' templateUrl: '/partials/pk-modeling-help.html' size: 'med' ] ctlrs.controller 'PkModelingHelpModalCtrl', [ '$scope', '$uibModalInstance', ($scope, $uibModalInstance) -> $scope.close = -> $uibModalInstance.close() ] ctlrs.controller 'ModelingProtocolCtrl', [ '$scope', ($scope) -> # Place the protocol id in scope. $scope.protocolId = $scope.modeling.protocol ] ctlrs.controller 'ModelingInfoCtrl', [ '$scope', '$uibModal', 'Resources', ($scope, $uibModal, Resources) -> # Open a modal window to display the modeling input properties. $scope.open = -> $uibModal.open controller: 'ModelingInfoModalCtrl' templateUrl: '/partials/modeling-info.html' size: 'sm' resolve: # Make modeling injectable in the modal controller. # See the ModelingInfoModalCtrl comment. modeling: -> $scope.modeling # Fetch the modeling protocol. protocol: -> Resources.ModelingProtocol.find(id: $scope.modeling.protocol) ] ctlrs.controller 'ModelingInfoModalCtrl', [ '$scope', '$uibModalInstance', 'modeling', 'protocol', ($scope, $uibModalInstance, modeling, protocol) -> # Since the modal is not contained in the application page, this # modal controller scope does not inherit the application page # scope. Therefore, the application scope modeling variable is # not visible to the modal scope. Hence, it is necessary to # transfer the modeling object as a $uibModal.open function resolve # property into this controller's injection list. # The assignment below then places the modeling object in the # modal scope for use in the modal template partial. $scope.modeling = modeling $scope.protocol = protocol $scope.close = -> $uibModalInstance.close() ] ctlrs.controller 'ModelingSourceProtocolCtrl', [ '$scope', ($scope) -> # The modeling source is either a scan or registration protocol. if $scope.modeling.source.scan? $scope.sourceType = 'scan' $scope.protocolId = $scope.modeling.source.scan else if $scope.modeling.source.registration? $scope.sourceType = 'registration' $scope.protocolId = $scope.modeling.source.registration else throw new Error("The modeling source has neither a scan" + " nor a registration protocol reference") ] ctlrs.controller 'TimelineCtrl', [ '$scope', '$state', '$compile', 'Timeline', ($scope, $state, $compile, Timeline) -> # The chart {options, data} configuration. chartConfig = Timeline.configure($scope.subject) $scope.options = chartConfig.options $scope.data = chartConfig.data # The global configuration. Disable the data watcher since, # once built, the data is not changed. Furthermore, the # data is the modeling parameter objects, which are complex # objects with a circular object graph reference # (paramResult -> parent modelingResult -> child paramResult). $scope.config = deepWatchData: false # The chart decoration callback. $scope.decorate = (scope, element) -> # Note: since the nvd3 directive isolates the scope, # it does not inherit to the parent $scope properties. # Therefore, we must specify $scope.subject rather than # scope.subject. Timeline.decorate(element, $scope.subject, scope, $state) # Note: an angular-nvd3 bug voids element changes made # in this callback on refresh # (cf. https://github.com/krispo/angular-nvd3/issues/316). # The work-around is to surgically intervene in the # defective ngnvd3 code. # TODO - periodically check whether the ngnvd3 bug is # fixed and remove the work-around if possible. #scope.isReady = false if _.isUndefined(scope.isBroken) broken = scope.api.refresh fixed = -> # Note: setting scope.isReady should trigger the watcher # but doesn't. The work-around to this work-around bug is # to force the issue by calling the decorate function # directly in the refresh rather than indirectly via the # watcher. # TODO - remove this work-around to a work-around bug when # the original work-around is fixed. broken() $scope.decorate(scope, element) scope.api.refresh = fixed scope.isBroken = false ] ctlrs.controller 'IntensityChartCtrl', [ '$scope', 'IntensityChart', ($scope, IntensityChart) -> # The chart {options, data} configuration. chartConfig = IntensityChart.configure($scope.scan) $scope.options = chartConfig.options $scope.data = chartConfig.data # The global configuration. See ModelingChartCtrl comment. $scope.config = deepWatchData: false ] ctlrs.controller 'ModelingChartCtrl', [ '$scope', 'ModelingChart', ($scope, ModelingChart) -> # selModeling is set to the modeling object to display. # It is set if and only if there is at least one modeling # object. Thus, the if test guards against there not being # any modeling object to display. if $scope.selModeling? # The chart {options, data} configuration. chartConfig = ModelingChart.configure($scope.selModeling.results, $scope.paramKey) $scope.options = chartConfig.options $scope.data = chartConfig.data # The global configuration. Disable the data watcher since, # once built, the data is not changed. Furthermore, the # data is the modeling parameter objects, which are complex # objects with a circular object graph reference # (paramResult -> parent modelingResult -> child paramResult). $scope.config = deepWatchData: false ] ## The modeling parameter controllers. ## # # TODO - revise to beter fit ngnvd3. These controller's don't do # much. # # Each controller is required to set the following scope variable: # * dataSeriesConfig - the ModelingChart.configureD3 dataSeriesSpec # argument # # Note: The modeling parameter controllers defined below somewhat abuse # Controller-View separation of control, since the controller places # formatting details like the label and color in a scope variable. This # is necessary evil to accomodate d3 charting. A preferable solution is # to specify the color in a style sheet and the data series label in a # transcluded partial. However, that solution appears to go against the # grain of d3. In general, the modeling chart partial/controller pattern # should not be used as an example for building a non-d3 charting # component. ctlrs.controller 'KTransCtrl', [ '$scope', ($scope) -> $scope.paramKey = 'kTrans' ] ctlrs.controller 'VeCtrl', [ '$scope', ($scope) -> $scope.paramKey = 'vE' ] ctlrs.controller 'TauICtrl', [ '$scope', ($scope) -> $scope.paramKey = 'tauI' ] ## The Clinical Profile pane controllers. ## ctlrs.controller 'PathologyCtrl', [ '$scope', ($scope) -> $scope.pathology = $scope.encounter.pathology ] ctlrs.controller 'BreastHormoneReceptorsCtrl', [ '$scope', ($scope) -> $scope.hormoneReceptors = $scope.tumor.hormoneReceptors ] ctlrs.controller 'BreastGeneticExpressionCtrl', [ '$scope', ($scope) -> $scope.geneticExpression = $scope.tumor.geneticExpression ] ctlrs.controller 'BreastGeneAssayCtrl', [ '$scope', 'Breast', ($scope, Breast) -> $scope.assay = $scope.geneticExpression.normalizedAssay $scope.recurrenceScore = Breast.recurrenceScore($scope.assay) ] ctlrs.controller 'TumorExtentCtrl', [ '$scope', ($scope) -> $scope.extent = $scope.tumor.extent ] ctlrs.controller 'ResidualCancerBurdenCtrl', [ '$scope', 'Breast', ($scope, Breast) -> $scope.rcb = Breast.residualCancerBurden($scope.tumor) ] ctlrs.controller 'RecurrenceScoreHelpCtrl', [ '$scope', '$uibModal', ($scope, $uibModal) -> $scope.open = -> $uibModal.open controller: 'RecurrenceScoreHelpModalCtrl' templateUrl: '/partials/recurrence-score-help.html' size: 'med' ] ctlrs.controller 'RecurrenceScoreHelpModalCtrl', [ '$scope', '$uibModalInstance', ($scope, $uibModalInstance) -> $scope.close = -> $uibModalInstance.close() ] ctlrs.controller 'DosageAmountHelpCtrl', [ '$scope', '$uibModal', ($scope, $uibModal) -> $scope.open = -> $uibModal.open controller: 'DosageAmountHelpModalCtrl' templateUrl: '/partials/dosage-amount-help.html' size: 'med' ] ctlrs.controller 'DosageAmountHelpModalCtrl', [ '$scope', '$uibModalInstance', ($scope, $uibModalInstance) -> $scope.close = -> $uibModalInstance.close() ] ctlrs.controller 'TNMCtrl', [ '$scope', ($scope) -> # The parent can either be a pathology evaluation or a # generic evaluation outcome iterator. path = $scope.tumor $scope.tnm = if path then path.tnm else $scope.outcome ] ctlrs.controller 'BreastTNMStageHelpCtrl', [ '$scope', '$uibModal', ($scope, $uibModal) -> $scope.open = -> $uibModal.open controller: 'BreastTNMStageHelpModalCtrl' templateUrl: '/partials/breast-tnm-stage-help.html' size: 'med' ] ctlrs.controller 'BreastTNMStageHelpModalCtrl', [ '$scope', '$uibModalInstance', ($scope, $uibModalInstance) -> $scope.close = -> $uibModalInstance.close() ] ctlrs.controller 'SarcomaTNMStageHelpCtrl', [ '$scope', '$uibModal', ($scope, $uibModal) -> $scope.open = -> $uibModal.open controller: 'SarcomaTNMStageHelpModalCtrl' templateUrl: '/partials/sarcoma-tnm-stage-help.html' size: 'med' ] ctlrs.controller 'SarcomaTNMStageHelpModalCtrl', [ '$scope', '$uibModalInstance', ($scope, $uibModalInstance) -> $scope.close = -> $uibModalInstance.close() ] ctlrs.controller 'GradeCtrl', [ '$scope', ($scope) -> $scope.grade = $scope.tnm.grade ] ctlrs.controller 'HormoneReceptorCtrl', [ '$scope', ($scope) -> # The parent of a generic HormoneReceptor is a generic # evaluation outcome iterator. $scope.receptorStatus = $scope.outcome ] ctlrs.controller 'EstrogenCtrl', [ '$scope', ($scope) -> $scope.receptorStatus = _.find($scope.hormoneReceptors, (hr) -> hr.hormone == 'estrogen') ] ctlrs.controller 'ProgesteroneCtrl', [ '$scope', ($scope) -> $scope.receptorStatus = _.find($scope.hormoneReceptors, (hr) -> hr.hormone == 'progesterone') ] ctlrs.controller 'ChemotherapyCtrl', [ '$scope', ($scope) -> isChemo = (dosage) -> dosage.agent._cls == 'Drug' chemo = $scope.treatment.dosages.filter(isChemo) $scope.chemotherapy = {dosages: chemo} if chemo.length ] ctlrs.controller 'RadiotherapyCtrl', [ '$scope', ($scope) -> isRadio = (dosage) -> dosage.agent._cls == 'Radiation' radio = $scope.treatment.dosages.filter(isRadio) $scope.radiotherapy = {dosages: radio} if radio.length ] ctlrs.controller 'NecrosisPercentCtrl', [ '$scope', ($scope) -> $scope.necrosis_percent = $scope.tumor.necrosis_percent ] ## The Session Detail page controllers. ## ctlrs.controller 'SessionDetailCtrl', [ '$rootScope', '$scope', '$state', 'session', 'ControllerHelper', ($rootScope, $scope, $state, session, ControllerHelper) -> # Capture the current project. $rootScope.project = session.subject.project # Place the session in the scope. $scope.session = session # If the project is the default, then remove it from the URL. ControllerHelper.cleanBrowserUrl($rootScope.project) ] # # TODO - retain on the xtk branch only. # ctlrs.controller 'VolumeDisplayCtrl', [ '$scope', '$state', ($scope, $state) -> # Create the image object on demand. $scope.image = $scope.volume.image # Opens the series image display page. # # @param image the Image object $scope.openImage = () -> # The parent scan or registration image sequence. imageSequence = $scope.volume.imageSequence # The common parameters. params = project: imageSequence.session.subject.project collection: imageSequence.session.subject.collection subject: imageSequence.session.subject.number session: imageSequence.session.number detail: imageSequence.session.detail volume: $scope.volume.number # The target imageSequence route prefix. route = 'quip.collection.subject.session.scan.' # Add to the parameters and route based on the imageSequence type. if imageSequence._cls == 'Scan' params.scan = imageSequence.number else if imageSequence._cls == 'Registration' params.scan = imageSequence.scan.number params.registration = imageSequence.resource route += 'registration.' else throw new TypeError("Unsupported image sequence type:" + " #{ imageSequence._cls }") # Finish off the route. route += 'volume.slice' # Go to the volume page. $state.go(route, params) # # TODO - Legacy controller partially repurposed for slice display. # If volume display is reenabled, then borrow what is needed for # the above controller and delete the rest. # # ctlrs.controller 'VolumeeDisplayCtrl', [ # '$rootScope', '$scope', '$location', '$sce', 'ModelingChart', 'SliceDisplay', # 'ControllerHelper', 'session', 'imageSequence', 'volume', 'slice', # ($rootScope, $scope, $location, $sce, ModelingChart, SliceDisplay, # ControllerHelper, session, imageSequence, volume, slice) -> # # Capture the current project. # $rootScope.project = session.subject.project # # # @param key the modeling parameter key, e.g. 'deltaKTrans' # # @return the modeling parameter heading HTML span element, # # e.g. '<span>&Delta;K<sub>trans</sub></span>' # $scope.parameterHeading = (key) -> # html = "<span>#{ Modeling.properties[key].html }</span>" # $sce.trustAsHtml(html) # # # The session modelings which have an overlay. # $scope.overlayModelings = ( # mdl for mdl in session.modelings when mdl.overlays.length? # ) # # The overlay selection. # $scope.overlayIndex = null # # # The initial saggital slice. # $scope.saggitalView = slice: slice # # # The overlay opacity slider setting and CSS styles. # $scope.overlayConfig = # setting: 1 # style: # "opacity": 1 # "z-index": -1 # # # Watch for a change in the saggital slice control setting. # # When the slice index changes, then update the image and, # # if selected, the overlay. # # # # TODO - address the volume-controls.jade TODO items. # # # $scope.$watch 'saggitalView.slice', (index) -> # SliceDisplay.updateSlice($scope.imageIds[index].dicomImageId) # if $scope.overlayIndex? # Slice.updateOverlay($scope.imageIds[index].overlayIds, # $scope.overlayIndex) # # # Update the URL search parameters. # $location.search('volume', volume) # $location.search('slice', slice) # # # The overlayIndex scope variable is the overlay radio input # # selection value in the format *modeling index*.*overlay index*, # # e.g. the value '0.1' is the second overlay of the first modeling. # # By default, no overlay is selected. When a radio button is # # checked, then the overlayIndex variable is set and the watcher # # below is triggered. # # # # If the overlayIndex scope variable is changed to a non-null value, # # then parse the value and call the image selectOverlay(overlay) # # function on the referenced overlay. # # Otherwise, call the image deselectOverlay() function. # $scope.$watch 'overlayIndex', (index) -> # if index? # # Parse and disaggregate the composite index. # # Note: calling map with parseInt fails with a NaN second value # # since both parseInt can include optional arguments # # (cf. http://stackoverflow.com/questions/262427/javascript-arraymap-and-parseint). # # The work-around is to call map with Number, which takes a # # single string argument. # #[mdlIndex, ovrIndex] = index.split('.').map(Number) # # The selected modeling object. # #modeling = $scope.overlayModelings[mdlIndex] # # The select overlay label map in the selected modeling object. # #overlay = modeling.overlays[ovrIndex] # # Delegate to the image object. # #$scope.volume.selectOverlay(overlay) # # # Move the overlay viewport to the front and update it - # # Cornerstone prototype. # $scope.overlayConfig.style['z-index'] = 1 # slice = $scope.saggitalView.slice # $scope.slice.updateOverlay($scope.imageIds[slice].overlayIds, # index) # else # #$scope.volume.deselectOverlay() # # Move the overlay viewport to the back - Cornerstone prototype. # $scope.overlayConfig.style['z-index'] = -1 # # # # If the project is the default, then remove it from the URL. # ControllerHelper.cleanBrowserUrl($rootScope.project) ] # The Image Slice Display controller. ctlrs.controller 'SliceDisplayCtrl', [ '$rootScope', '$scope', '$location', 'SliceDisplay', 'ControllerHelper', 'timeSeries', 'volume', 'slice', ($rootScope, $scope, $location, SliceDisplay, ControllerHelper, timeSeries, volume, slice) -> # Capture the current project. $rootScope.project = timeSeries.imageSequence.session.subject.project # Place the time series in scope. $scope.timeSeries = timeSeries # Initialize the volume number, if necessary. if not volume? # The default volume is at bolus arrival, if defined, otherwise the # first volume. bolusArvNdx = timeSeries.imageSequence.bolusArrivalIndex volume = if bolusArvNdx? then bolusArvNdx + 1 else 1 # Update the URL search parameter. $location.search('volume', volume) # Place the volume in scope. $scope.volume = volumeNbr: volume # Initialize the slice number, if necessary. if not slice? # The default slice is the point of maximal ROI extent, if defined, # otherwise the first slice. # TODO - calculate the maximal ROI slice in the pipeline and put in # the REST database. maximalROISlice = undefined slice = if maximalROISlice? then maximalROISlice + 1 else 1 # Update the URL search parameter. $location.search('slice', slice) # Place the slice in scope. $scope.slice = sliceNbr: slice # The slice dimensions. $scope.dimensions = [ "Saggital" "Coronal" "Axial" ] # The default slice dimension. $scope.dimension = "Axial" # # TODO - add overlays. The REST data model is: # Modeling { # result { # parameter: parameterResult{name, labelMap: {name, colorTable}}, ...} # } # } # and: # Scan { # rois: [{name, labelMap: {name, colorTable}}, ...] # } # } # with one ROI per tumor. # # The LabelMap objects need to be collected by Scan.extend into a # Scan.overlays virtual property {key, image} object, where: # * *key* is either a modeling parameter name or 'roi' # * *image* is the LabelMap extended by the Image service, which # should be done in Modeling.extend and Scan.extend. # # The composite ROI needs to be created in the pipeline from the # tumor ROIs and placed into a new REST Scan.rois ROI object # {composite, regions}, where: # *composite* is a LabelMap object # *regions* is the current Scan.rois [Region, ...] array. Since # the Scan ROIs do not overlap, the masks can be combined in a # ndarray operation by the pipeline. # # The Slice Display page should have an overlay selection control, # one per modeling parameter and one for the composite ROI. # # A registration image sequence needs to delegate to the parent # scan overlays. This can be done in Registration.extend by adding a # Registration.overlays virtual property. # # Finally, TimeSeries.extend should create a TimeSeries.overlays # virtual property which delegates to the parent overlays. display = -> SliceDisplay.display($scope.timeSeries, $scope.volume.volumeNbr, $scope.slice.sliceNbr) watcher = (newValue, oldValue) -> if newValue != oldValue display() # Display the image the first time and whenever the volume changes # thereafter. $scope.$watch('volume', display, true) # Redisplay the image when the slice changes. $scope.$watch('slice', watcher, true) # # TODO - implement the overlay watcher in conjunction with the # changes described above. # # # Redisplay the overlay when the overlay changes. # $scope.$watch 'overlayIndex', (overlayIndex, previous) -> # # There must first be an overlay. This situation should never # # occur by construction if the UI overlay selection properly # # guards against it. # if not data? # throw new ReferenceError("The time series does not have an overlay") # if overlayIndex != previous # display() # # TODO - borrow whatever is useful from below--but don't copy it as is--then # delete it. # # '$rootScope', '$scope', '$location', '$sce', 'ModelingChart', 'SliceDisplay', # 'ControllerHelper', 'session', 'imageSequence', 'volume', 'slice', # ($rootScope, $scope, $location, $sce, ModelingChart, SliceDisplay, # ControllerHelper, session, imageSequence, volume, slice) -> # # Capture the current project. # $rootScope.project = session.subject.project # # # @param key the modeling parameter key, e.g. 'deltaKTrans' # # @return the modeling parameter heading HTML span element, # # e.g. '<span>&Delta;K<sub>trans</sub></span>' # $scope.parameterHeading = (key) -> # html = "<span>#{ Modeling.properties[key].html }</span>" # $sce.trustAsHtml(html) # # # The session modelings which have an overlay. # $scope.overlayModelings = ( # mdl for mdl in session.modelings when mdl.overlays.length? # ) # # The overlay selection. # $scope.overlayIndex = null # # # The initial saggital slice. # $scope.saggitalView = slice: slice # # # The overlay opacity slider setting and CSS styles. # $scope.overlayConfig = # setting: 1 # style: # "opacity": 1 # "z-index": -1 # # # Watch for a change in the saggital slice control setting. # # When the slice index changes, then update the image and, # # if selected, the overlay. # # # # TODO - address the volume-controls.jade TODO items. # # # $scope.$watch 'saggitalView.slice', (index) -> # SliceDisplay.updateSlice($scope.imageIds[index].dicomImageId) # if $scope.overlayIndex? # Slice.updateOverlay($scope.imageIds[index].overlayIds, # $scope.overlayIndex) # # # # The overlayIndex scope variable is the overlay radio input # # selection value in the format *modeling index*.*overlay index*, # # e.g. the value '0.1' is the second overlay of the first modeling. # # By default, no overlay is selected. When a radio button is # # checked, then the overlayIndex variable is set and the watcher # # below is triggered. # # # # If the overlayIndex scope variable is changed to a non-null value, # # then parse the value and call the image selectOverlay(overlay) # # function on the referenced overlay. # # Otherwise, call the image deselectOverlay() function. # $scope.$watch 'overlayIndex', (index) -> # if index? # # Parse and disaggregate the composite index. # # Note: calling map with parseInt fails with a NaN second value # # since both parseInt can include optional arguments # # (cf. http://stackoverflow.com/questions/262427/javascript-arraymap-and-parseint). # # The work-around is to call map with Number, which takes a # # single string argument. # #[mdlIndex, ovrIndex] = index.split('.').map(Number) # # The selected modeling object. # #modeling = $scope.overlayModelings[mdlIndex] # # The select overlay label map in the selected modeling object. # #overlay = modeling.overlays[ovrIndex] # # Delegate to the image object. # #$scope.volume.selectOverlay(overlay) # # # Move the overlay viewport to the front and update it - # # Cornerstone prototype. # $scope.overlayConfig.style['z-index'] = 1 # slice = $scope.saggitalView.slice # $scope.slice.updateOverlay($scope.imageIds[slice].overlayIds, # index) # else # #$scope.volume.deselectOverlay() # # Move the overlay viewport to the back - Cornerstone prototype. # $scope.overlayConfig.style['z-index'] = -1 # If the project is the default, then remove it from the URL. ControllerHelper.cleanBrowserUrl($rootScope.project) ]
60220
define ['angular', 'lodash', 'ngsanitize', 'ngnvd3', 'resources', 'modelingChart', 'breast', 'sliceDisplay', 'collection'], (ng, _) -> ctlrs = ng.module( 'qiprofile.controllers', ['ngSanitize', 'nvd3', 'qiprofile.resources', 'qiprofile.modelingchart', 'qiprofile.breast', 'qiprofile.slicedisplay', 'qiprofile.collection'] ) # The local controller helper methods. ctlrs.factory 'ControllerHelper', [ '$location', ($location) -> # Resets the browser URL search parameters to include at most # a non-default project, since all other search parameters are # redundant. cleanBrowserUrl: (project) -> searchParams = {} # TODO - get the default project from a config file. if project != 'QIN' searchParams.project = project $location.search(searchParams) ] ctlrs.controller 'HomeCtrl', [ '$rootScope', '$scope', '$state', ($rootScope, $scope, $state) -> $scope.goHome = () -> project = $rootScope.project or 'QIN' $state.go('quip.home', project: project) ] ctlrs.controller 'HelpCtrl', [ '$rootScope', '$scope', ($rootScope, $scope) -> # Toggles the root scope showHelp flag. # This method and the showHelp flag are defined in the root # scope in order to share them with the partial template # home alert attribute directives. $rootScope.toggleHelp = -> $rootScope.showHelp = !$rootScope.showHelp # Unconditionally hide help when the location changes. $scope.$on '$locationChangeStart', (event, next, current) -> # Set the showHelp flag on the parent scope, since the # flag is shared with the sibling view scope. $rootScope.showHelp = false ] ctlrs.controller 'AccordionGroupCtrl', [ '$scope', ($scope) -> # The accordion group is initially open. $scope.isOpen = true ] ctlrs.controller 'CollectionListCtrl', [ '$rootScope', '$scope', 'project', 'collections', '$window', ($rootScope, $scope, project, collections, $window) -> # Capture the current project. $rootScope.project = project # Place the collections in the scope. $scope.collections = collections $scope.open = (url) -> $window.location.href = url # The help is always open to start with on this landing page. $rootScope.showHelp = true ] ctlrs.controller 'SubjectListCtrl', [ '$rootScope', '$scope', 'project', 'subjects', 'collections', ($rootScope, $scope, project, subjects, collections) -> # Capture the current project. $rootScope.project = project # Place the subjects and collections in the scope. $scope.subjects = subjects $scope.collections = collections ] ctlrs.controller 'CollectionDetailCtrl', [ '$rootScope', '$scope', 'project', 'collection', 'charting', 'Collection', 'ControllerHelper', ($rootScope, $scope, project, collection, charting, Collection, ControllerHelper) -> # Capture the current project. $rootScope.project = project # Place the collection in the scope. $scope.collection = collection # Obtain the valid data series and labels for the current collection # and put them in the scope. These comprise the X/Y axis dropdown # choices. The X axis choices contain all valid data series. The Y axis # choices may only include continuous data types. $scope.choices = Collection.dataSeriesChoices(collection) # Obtain the formatted scatterplot data. data = Collection.chartData(charting, Object.keys $scope.choices.x) # Obtain the chart padding for each data series - continuous data types # only. The padding for categorical data series is configured in the # correlation module chart rendering function. padding = Collection.chartPadding(data, Object.keys $scope.choices.y) # Put a copy of the default charts (X and Y axes) in the scope. # This charts object changes when the user selects a different # axis to chart. $scope.axes = _.clone(Collection.DEFAULT_AXES[collection]) # Check the validity of the default chart axes. # # TODO - Suppress charts where no data exists for a particular data # series throughout the collection. # checkAxes = (axis) -> axis.x in xAxisChoices or throw new Error "Invalid #{ collection } X-axis data series: " + "#{ axis.x }" axis.y in yAxisChoices or throw new Error "Invalid #{ collection } Y-axis data series: " + "#{ axis.y }" xAxisChoices = Object.keys($scope.choices.x) yAxisChoices = Object.keys($scope.choices.y) checkAxes(axis) for axis in $scope.axes # Place the chart configuration object in the scope. $scope.config = data: data padding: padding axes: $scope.axes # If the user changes any X or Y axis selection, then re-render the # charts. The watcher is invoked on initialization and whenever the # user changes the axes. On initialization, then the watcher is called # with new axes value argument identical (===) to the old value # argument. If the user changes the axes, then the watcher is called # with different new and old axes objects. watcher = (newValue, oldValue) -> # If the user changed the axes, then re-render the charts. if newValue != oldValue Collection.renderCharts($scope.config) # Since charts is an object, the objectEquality flag is set to true. # AngularJS then copies the object for later comparison and uses # angular.equals to recursively compare the object properties rather # than a simple === test, which is the default. $scope.$watch('axes', watcher, true) # If the project is the default, then remove it from the URL. ControllerHelper.cleanBrowserUrl($rootScope.project) ] ## The Subject Detail page controllers. ctlrs.controller 'SubjectDetailCtrl', [ '$rootScope', '$scope', 'subject', 'ControllerHelper', ($rootScope, $scope, subject, ControllerHelper) -> # Capture the current project. $rootScope.project = subject.project # Place the subject in scope. $scope.subject = subject # If the project is the default, then remove it from the URL. ControllerHelper.cleanBrowserUrl($rootScope.project) ] ctlrs.controller 'ScanVolumeSelectCtrl', [ '$scope', ($scope) -> # Place the scan protocol id in scope. $scope.protocolId = $scope.scan.protocol ] ctlrs.controller 'RegistrationVolumeSelectCtrl', [ '$scope', ($scope) -> # Place the registration protocol id in scope. $scope.protocolId = $scope.registration.protocol ] ctlrs.controller 'ScanProtocolCtrl', [ '$scope', '$uibModal', 'Resources', ($scope, $uibModal, Resources) -> # Open a modal window to display the scan procedure properties. $scope.open = -> $uibModal.open controller: 'ProtocolModalCtrl' templateUrl: '/partials/scan-protocol.html' size: 'sm' resolve: # Fetch the scan protocol. protocol: -> Resources.ScanProtocol.find(id: $scope.protocolId) ] ctlrs.controller 'RegistrationProtocolCtrl', [ '$scope', '$uibModal', 'Resources', ($scope, $uibModal, Resources) -> # Open a modal window to display the registration properties. $scope.open = -> $uibModal.open controller: 'ProtocolModalCtrl' templateUrl: '/partials/registration-protocol.html' size: 'sm' resolve: # Fetch the registration protocol. protocol: -> Resources.RegistrationProtocol.find(id: $scope.protocolId) ] ctlrs.controller 'ProtocolModalCtrl', [ '$scope', '$uibModalInstance', 'protocol', ($scope, $uibModalInstance, protocol) -> # Place the protocol object in the modal scope. $scope.protocol = protocol $scope.close = -> $uibModalInstance.close() ] ## The Imaging Profile pane controllers. ctlrs.controller 'SubjectModelingCtrl', [ '$scope', ($scope) -> # Place the modelings in scope. # Note: modelings is a subject property that is calculated # on the fly. Since the partials reference the modelings in # ng-switch and ng-repeat models, AngularJS sets up hidden # watches on this variable and redigests the partials whenever # the property value is calculated. If subject.modelings were # used instead of modelings, then AngularJS would enter an # infinite digest cycle. Placing the modelings variable in # scope here avoids this trap by fixing the value for the # course of the AngularJS page formatting. $scope.modelings = $scope.subject.modelings # The format button action. $scope.toggleModelingFormat = -> if $scope.modelingFormat is 'chart' $scope.modelingFormat = 'table' else if $scope.modelingFormat is 'table' $scope.modelingFormat = 'chart' else throw new Error "Modeling format is not recognized:" + " #{ $scope.modelingFormat }" # The modeling format is 'chart' if the subject has # more than one session, 'table' otherwise. if $scope.subject.isMultiSession() $scope.modelingFormat = 'chart' else $scope.modelingFormat = 'table' # The default modeling results index is the first. $scope.modelingIndex = 0 # Place the selected modeling in scope. $scope.$watch 'modelingIndex', (modelingIndex) -> $scope.selModeling = $scope.modelings[modelingIndex] ] ctlrs.controller 'PkModelingHelpCtrl', [ '$scope', '$uibModal', ($scope, $uibModal) -> $scope.open = -> $uibModal.open controller: 'PkModelingHelpModalCtrl' templateUrl: '/partials/pk-modeling-help.html' size: 'med' ] ctlrs.controller 'PkModelingHelpModalCtrl', [ '$scope', '$uibModalInstance', ($scope, $uibModalInstance) -> $scope.close = -> $uibModalInstance.close() ] ctlrs.controller 'ModelingProtocolCtrl', [ '$scope', ($scope) -> # Place the protocol id in scope. $scope.protocolId = $scope.modeling.protocol ] ctlrs.controller 'ModelingInfoCtrl', [ '$scope', '$uibModal', 'Resources', ($scope, $uibModal, Resources) -> # Open a modal window to display the modeling input properties. $scope.open = -> $uibModal.open controller: 'ModelingInfoModalCtrl' templateUrl: '/partials/modeling-info.html' size: 'sm' resolve: # Make modeling injectable in the modal controller. # See the ModelingInfoModalCtrl comment. modeling: -> $scope.modeling # Fetch the modeling protocol. protocol: -> Resources.ModelingProtocol.find(id: $scope.modeling.protocol) ] ctlrs.controller 'ModelingInfoModalCtrl', [ '$scope', '$uibModalInstance', 'modeling', 'protocol', ($scope, $uibModalInstance, modeling, protocol) -> # Since the modal is not contained in the application page, this # modal controller scope does not inherit the application page # scope. Therefore, the application scope modeling variable is # not visible to the modal scope. Hence, it is necessary to # transfer the modeling object as a $uibModal.open function resolve # property into this controller's injection list. # The assignment below then places the modeling object in the # modal scope for use in the modal template partial. $scope.modeling = modeling $scope.protocol = protocol $scope.close = -> $uibModalInstance.close() ] ctlrs.controller 'ModelingSourceProtocolCtrl', [ '$scope', ($scope) -> # The modeling source is either a scan or registration protocol. if $scope.modeling.source.scan? $scope.sourceType = 'scan' $scope.protocolId = $scope.modeling.source.scan else if $scope.modeling.source.registration? $scope.sourceType = 'registration' $scope.protocolId = $scope.modeling.source.registration else throw new Error("The modeling source has neither a scan" + " nor a registration protocol reference") ] ctlrs.controller 'TimelineCtrl', [ '$scope', '$state', '$compile', 'Timeline', ($scope, $state, $compile, Timeline) -> # The chart {options, data} configuration. chartConfig = Timeline.configure($scope.subject) $scope.options = chartConfig.options $scope.data = chartConfig.data # The global configuration. Disable the data watcher since, # once built, the data is not changed. Furthermore, the # data is the modeling parameter objects, which are complex # objects with a circular object graph reference # (paramResult -> parent modelingResult -> child paramResult). $scope.config = deepWatchData: false # The chart decoration callback. $scope.decorate = (scope, element) -> # Note: since the nvd3 directive isolates the scope, # it does not inherit to the parent $scope properties. # Therefore, we must specify $scope.subject rather than # scope.subject. Timeline.decorate(element, $scope.subject, scope, $state) # Note: an angular-nvd3 bug voids element changes made # in this callback on refresh # (cf. https://github.com/krispo/angular-nvd3/issues/316). # The work-around is to surgically intervene in the # defective ngnvd3 code. # TODO - periodically check whether the ngnvd3 bug is # fixed and remove the work-around if possible. #scope.isReady = false if _.isUndefined(scope.isBroken) broken = scope.api.refresh fixed = -> # Note: setting scope.isReady should trigger the watcher # but doesn't. The work-around to this work-around bug is # to force the issue by calling the decorate function # directly in the refresh rather than indirectly via the # watcher. # TODO - remove this work-around to a work-around bug when # the original work-around is fixed. broken() $scope.decorate(scope, element) scope.api.refresh = fixed scope.isBroken = false ] ctlrs.controller 'IntensityChartCtrl', [ '$scope', 'IntensityChart', ($scope, IntensityChart) -> # The chart {options, data} configuration. chartConfig = IntensityChart.configure($scope.scan) $scope.options = chartConfig.options $scope.data = chartConfig.data # The global configuration. See ModelingChartCtrl comment. $scope.config = deepWatchData: false ] ctlrs.controller 'ModelingChartCtrl', [ '$scope', 'ModelingChart', ($scope, ModelingChart) -> # selModeling is set to the modeling object to display. # It is set if and only if there is at least one modeling # object. Thus, the if test guards against there not being # any modeling object to display. if $scope.selModeling? # The chart {options, data} configuration. chartConfig = ModelingChart.configure($scope.selModeling.results, $scope.paramKey) $scope.options = chartConfig.options $scope.data = chartConfig.data # The global configuration. Disable the data watcher since, # once built, the data is not changed. Furthermore, the # data is the modeling parameter objects, which are complex # objects with a circular object graph reference # (paramResult -> parent modelingResult -> child paramResult). $scope.config = deepWatchData: false ] ## The modeling parameter controllers. ## # # TODO - revise to beter fit ngnvd3. These controller's don't do # much. # # Each controller is required to set the following scope variable: # * dataSeriesConfig - the ModelingChart.configureD3 dataSeriesSpec # argument # # Note: The modeling parameter controllers defined below somewhat abuse # Controller-View separation of control, since the controller places # formatting details like the label and color in a scope variable. This # is necessary evil to accomodate d3 charting. A preferable solution is # to specify the color in a style sheet and the data series label in a # transcluded partial. However, that solution appears to go against the # grain of d3. In general, the modeling chart partial/controller pattern # should not be used as an example for building a non-d3 charting # component. ctlrs.controller 'KTransCtrl', [ '$scope', ($scope) -> $scope.paramKey = 'kTrans' ] ctlrs.controller 'VeCtrl', [ '$scope', ($scope) -> $scope.paramKey = 'vE' ] ctlrs.controller 'TauICtrl', [ '$scope', ($scope) -> $scope.paramKey = 'tauI' ] ## The Clinical Profile pane controllers. ## ctlrs.controller 'PathologyCtrl', [ '$scope', ($scope) -> $scope.pathology = $scope.encounter.pathology ] ctlrs.controller 'BreastHormoneReceptorsCtrl', [ '$scope', ($scope) -> $scope.hormoneReceptors = $scope.tumor.hormoneReceptors ] ctlrs.controller 'BreastGeneticExpressionCtrl', [ '$scope', ($scope) -> $scope.geneticExpression = $scope.tumor.geneticExpression ] ctlrs.controller 'BreastGeneAssayCtrl', [ '$scope', 'Breast', ($scope, Breast) -> $scope.assay = $scope.geneticExpression.normalizedAssay $scope.recurrenceScore = Breast.recurrenceScore($scope.assay) ] ctlrs.controller 'TumorExtentCtrl', [ '$scope', ($scope) -> $scope.extent = $scope.tumor.extent ] ctlrs.controller 'ResidualCancerBurdenCtrl', [ '$scope', 'Breast', ($scope, Breast) -> $scope.rcb = Breast.residualCancerBurden($scope.tumor) ] ctlrs.controller 'RecurrenceScoreHelpCtrl', [ '$scope', '$uibModal', ($scope, $uibModal) -> $scope.open = -> $uibModal.open controller: 'RecurrenceScoreHelpModalCtrl' templateUrl: '/partials/recurrence-score-help.html' size: 'med' ] ctlrs.controller 'RecurrenceScoreHelpModalCtrl', [ '$scope', '$uibModalInstance', ($scope, $uibModalInstance) -> $scope.close = -> $uibModalInstance.close() ] ctlrs.controller 'DosageAmountHelpCtrl', [ '$scope', '$uibModal', ($scope, $uibModal) -> $scope.open = -> $uibModal.open controller: 'DosageAmountHelpModalCtrl' templateUrl: '/partials/dosage-amount-help.html' size: 'med' ] ctlrs.controller 'DosageAmountHelpModalCtrl', [ '$scope', '$uibModalInstance', ($scope, $uibModalInstance) -> $scope.close = -> $uibModalInstance.close() ] ctlrs.controller 'TNMCtrl', [ '$scope', ($scope) -> # The parent can either be a pathology evaluation or a # generic evaluation outcome iterator. path = $scope.tumor $scope.tnm = if path then path.tnm else $scope.outcome ] ctlrs.controller 'BreastTNMStageHelpCtrl', [ '$scope', '$uibModal', ($scope, $uibModal) -> $scope.open = -> $uibModal.open controller: 'BreastTNMStageHelpModalCtrl' templateUrl: '/partials/breast-tnm-stage-help.html' size: 'med' ] ctlrs.controller 'BreastTNMStageHelpModalCtrl', [ '$scope', '$uibModalInstance', ($scope, $uibModalInstance) -> $scope.close = -> $uibModalInstance.close() ] ctlrs.controller 'SarcomaTNMStageHelpCtrl', [ '$scope', '$uibModal', ($scope, $uibModal) -> $scope.open = -> $uibModal.open controller: 'SarcomaTNMStageHelpModalCtrl' templateUrl: '/partials/sarcoma-tnm-stage-help.html' size: 'med' ] ctlrs.controller 'SarcomaTNMStageHelpModalCtrl', [ '$scope', '$uibModalInstance', ($scope, $uibModalInstance) -> $scope.close = -> $uibModalInstance.close() ] ctlrs.controller 'GradeCtrl', [ '$scope', ($scope) -> $scope.grade = $scope.tnm.grade ] ctlrs.controller 'HormoneReceptorCtrl', [ '$scope', ($scope) -> # The parent of a generic HormoneReceptor is a generic # evaluation outcome iterator. $scope.receptorStatus = $scope.outcome ] ctlrs.controller 'EstrogenCtrl', [ '$scope', ($scope) -> $scope.receptorStatus = _.find($scope.hormoneReceptors, (hr) -> hr.hormone == 'estrogen') ] ctlrs.controller 'ProgesteroneCtrl', [ '$scope', ($scope) -> $scope.receptorStatus = _.find($scope.hormoneReceptors, (hr) -> hr.hormone == 'progesterone') ] ctlrs.controller 'ChemotherapyCtrl', [ '$scope', ($scope) -> isChemo = (dosage) -> dosage.agent._cls == 'Drug' chemo = $scope.treatment.dosages.filter(isChemo) $scope.chemotherapy = {dosages: chemo} if chemo.length ] ctlrs.controller 'RadiotherapyCtrl', [ '$scope', ($scope) -> isRadio = (dosage) -> dosage.agent._cls == 'Radiation' radio = $scope.treatment.dosages.filter(isRadio) $scope.radiotherapy = {dosages: radio} if radio.length ] ctlrs.controller 'NecrosisPercentCtrl', [ '$scope', ($scope) -> $scope.necrosis_percent = $scope.tumor.necrosis_percent ] ## The Session Detail page controllers. ## ctlrs.controller 'SessionDetailCtrl', [ '$rootScope', '$scope', '$state', 'session', 'ControllerHelper', ($rootScope, $scope, $state, session, ControllerHelper) -> # Capture the current project. $rootScope.project = session.subject.project # Place the session in the scope. $scope.session = session # If the project is the default, then remove it from the URL. ControllerHelper.cleanBrowserUrl($rootScope.project) ] # # TODO - retain on the xtk branch only. # ctlrs.controller 'VolumeDisplayCtrl', [ '$scope', '$state', ($scope, $state) -> # Create the image object on demand. $scope.image = $scope.volume.image # Opens the series image display page. # # @param image the Image object $scope.openImage = () -> # The parent scan or registration image sequence. imageSequence = $scope.volume.imageSequence # The common parameters. params = project: imageSequence.session.subject.project collection: imageSequence.session.subject.collection subject: imageSequence.session.subject.number session: imageSequence.session.number detail: imageSequence.session.detail volume: $scope.volume.number # The target imageSequence route prefix. route = 'quip.collection.subject.session.scan.' # Add to the parameters and route based on the imageSequence type. if imageSequence._cls == 'Scan' params.scan = imageSequence.number else if imageSequence._cls == 'Registration' params.scan = imageSequence.scan.number params.registration = imageSequence.resource route += 'registration.' else throw new TypeError("Unsupported image sequence type:" + " #{ imageSequence._cls }") # Finish off the route. route += 'volume.slice' # Go to the volume page. $state.go(route, params) # # TODO - Legacy controller partially repurposed for slice display. # If volume display is reenabled, then borrow what is needed for # the above controller and delete the rest. # # ctlrs.controller 'VolumeeDisplayCtrl', [ # '$rootScope', '$scope', '$location', '$sce', 'ModelingChart', 'SliceDisplay', # 'ControllerHelper', 'session', 'imageSequence', 'volume', 'slice', # ($rootScope, $scope, $location, $sce, ModelingChart, SliceDisplay, # ControllerHelper, session, imageSequence, volume, slice) -> # # Capture the current project. # $rootScope.project = session.subject.project # # # @param key the modeling parameter key, e.g. '<KEY>' # # @return the modeling parameter heading HTML span element, # # e.g. '<span>&Delta;K<sub>trans</sub></span>' # $scope.parameterHeading = (key) -> # html = "<span>#{ Modeling.properties[key].html }</span>" # $sce.trustAsHtml(html) # # # The session modelings which have an overlay. # $scope.overlayModelings = ( # mdl for mdl in session.modelings when mdl.overlays.length? # ) # # The overlay selection. # $scope.overlayIndex = null # # # The initial saggital slice. # $scope.saggitalView = slice: slice # # # The overlay opacity slider setting and CSS styles. # $scope.overlayConfig = # setting: 1 # style: # "opacity": 1 # "z-index": -1 # # # Watch for a change in the saggital slice control setting. # # When the slice index changes, then update the image and, # # if selected, the overlay. # # # # TODO - address the volume-controls.jade TODO items. # # # $scope.$watch 'saggitalView.slice', (index) -> # SliceDisplay.updateSlice($scope.imageIds[index].dicomImageId) # if $scope.overlayIndex? # Slice.updateOverlay($scope.imageIds[index].overlayIds, # $scope.overlayIndex) # # # Update the URL search parameters. # $location.search('volume', volume) # $location.search('slice', slice) # # # The overlayIndex scope variable is the overlay radio input # # selection value in the format *modeling index*.*overlay index*, # # e.g. the value '0.1' is the second overlay of the first modeling. # # By default, no overlay is selected. When a radio button is # # checked, then the overlayIndex variable is set and the watcher # # below is triggered. # # # # If the overlayIndex scope variable is changed to a non-null value, # # then parse the value and call the image selectOverlay(overlay) # # function on the referenced overlay. # # Otherwise, call the image deselectOverlay() function. # $scope.$watch 'overlayIndex', (index) -> # if index? # # Parse and disaggregate the composite index. # # Note: calling map with parseInt fails with a NaN second value # # since both parseInt can include optional arguments # # (cf. http://stackoverflow.com/questions/262427/javascript-arraymap-and-parseint). # # The work-around is to call map with Number, which takes a # # single string argument. # #[mdlIndex, ovrIndex] = index.split('.').map(Number) # # The selected modeling object. # #modeling = $scope.overlayModelings[mdlIndex] # # The select overlay label map in the selected modeling object. # #overlay = modeling.overlays[ovrIndex] # # Delegate to the image object. # #$scope.volume.selectOverlay(overlay) # # # Move the overlay viewport to the front and update it - # # Cornerstone prototype. # $scope.overlayConfig.style['z-index'] = 1 # slice = $scope.saggitalView.slice # $scope.slice.updateOverlay($scope.imageIds[slice].overlayIds, # index) # else # #$scope.volume.deselectOverlay() # # Move the overlay viewport to the back - Cornerstone prototype. # $scope.overlayConfig.style['z-index'] = -1 # # # # If the project is the default, then remove it from the URL. # ControllerHelper.cleanBrowserUrl($rootScope.project) ] # The Image Slice Display controller. ctlrs.controller 'SliceDisplayCtrl', [ '$rootScope', '$scope', '$location', 'SliceDisplay', 'ControllerHelper', 'timeSeries', 'volume', 'slice', ($rootScope, $scope, $location, SliceDisplay, ControllerHelper, timeSeries, volume, slice) -> # Capture the current project. $rootScope.project = timeSeries.imageSequence.session.subject.project # Place the time series in scope. $scope.timeSeries = timeSeries # Initialize the volume number, if necessary. if not volume? # The default volume is at bolus arrival, if defined, otherwise the # first volume. bolusArvNdx = timeSeries.imageSequence.bolusArrivalIndex volume = if bolusArvNdx? then bolusArvNdx + 1 else 1 # Update the URL search parameter. $location.search('volume', volume) # Place the volume in scope. $scope.volume = volumeNbr: volume # Initialize the slice number, if necessary. if not slice? # The default slice is the point of maximal ROI extent, if defined, # otherwise the first slice. # TODO - calculate the maximal ROI slice in the pipeline and put in # the REST database. maximalROISlice = undefined slice = if maximalROISlice? then maximalROISlice + 1 else 1 # Update the URL search parameter. $location.search('slice', slice) # Place the slice in scope. $scope.slice = sliceNbr: slice # The slice dimensions. $scope.dimensions = [ "Saggital" "Coronal" "Axial" ] # The default slice dimension. $scope.dimension = "Axial" # # TODO - add overlays. The REST data model is: # Modeling { # result { # parameter: parameterResult{name, labelMap: {name, colorTable}}, ...} # } # } # and: # Scan { # rois: [{name, labelMap: {name, colorTable}}, ...] # } # } # with one ROI per tumor. # # The LabelMap objects need to be collected by Scan.extend into a # Scan.overlays virtual property {key, image} object, where: # * *key* is either a modeling parameter name or 'roi' # * *image* is the LabelMap extended by the Image service, which # should be done in Modeling.extend and Scan.extend. # # The composite ROI needs to be created in the pipeline from the # tumor ROIs and placed into a new REST Scan.rois ROI object # {composite, regions}, where: # *composite* is a LabelMap object # *regions* is the current Scan.rois [Region, ...] array. Since # the Scan ROIs do not overlap, the masks can be combined in a # ndarray operation by the pipeline. # # The Slice Display page should have an overlay selection control, # one per modeling parameter and one for the composite ROI. # # A registration image sequence needs to delegate to the parent # scan overlays. This can be done in Registration.extend by adding a # Registration.overlays virtual property. # # Finally, TimeSeries.extend should create a TimeSeries.overlays # virtual property which delegates to the parent overlays. display = -> SliceDisplay.display($scope.timeSeries, $scope.volume.volumeNbr, $scope.slice.sliceNbr) watcher = (newValue, oldValue) -> if newValue != oldValue display() # Display the image the first time and whenever the volume changes # thereafter. $scope.$watch('volume', display, true) # Redisplay the image when the slice changes. $scope.$watch('slice', watcher, true) # # TODO - implement the overlay watcher in conjunction with the # changes described above. # # # Redisplay the overlay when the overlay changes. # $scope.$watch 'overlayIndex', (overlayIndex, previous) -> # # There must first be an overlay. This situation should never # # occur by construction if the UI overlay selection properly # # guards against it. # if not data? # throw new ReferenceError("The time series does not have an overlay") # if overlayIndex != previous # display() # # TODO - borrow whatever is useful from below--but don't copy it as is--then # delete it. # # '$rootScope', '$scope', '$location', '$sce', 'ModelingChart', 'SliceDisplay', # 'ControllerHelper', 'session', 'imageSequence', 'volume', 'slice', # ($rootScope, $scope, $location, $sce, ModelingChart, SliceDisplay, # ControllerHelper, session, imageSequence, volume, slice) -> # # Capture the current project. # $rootScope.project = session.subject.project # # # @param key the modeling parameter key, e.g. '<KEY>' # # @return the modeling parameter heading HTML span element, # # e.g. '<span>&Delta;K<sub>trans</sub></span>' # $scope.parameterHeading = (key) -> # html = "<span>#{ Modeling.properties[key].html }</span>" # $sce.trustAsHtml(html) # # # The session modelings which have an overlay. # $scope.overlayModelings = ( # mdl for mdl in session.modelings when mdl.overlays.length? # ) # # The overlay selection. # $scope.overlayIndex = null # # # The initial saggital slice. # $scope.saggitalView = slice: slice # # # The overlay opacity slider setting and CSS styles. # $scope.overlayConfig = # setting: 1 # style: # "opacity": 1 # "z-index": -1 # # # Watch for a change in the saggital slice control setting. # # When the slice index changes, then update the image and, # # if selected, the overlay. # # # # TODO - address the volume-controls.jade TODO items. # # # $scope.$watch 'saggitalView.slice', (index) -> # SliceDisplay.updateSlice($scope.imageIds[index].dicomImageId) # if $scope.overlayIndex? # Slice.updateOverlay($scope.imageIds[index].overlayIds, # $scope.overlayIndex) # # # # The overlayIndex scope variable is the overlay radio input # # selection value in the format *modeling index*.*overlay index*, # # e.g. the value '0.1' is the second overlay of the first modeling. # # By default, no overlay is selected. When a radio button is # # checked, then the overlayIndex variable is set and the watcher # # below is triggered. # # # # If the overlayIndex scope variable is changed to a non-null value, # # then parse the value and call the image selectOverlay(overlay) # # function on the referenced overlay. # # Otherwise, call the image deselectOverlay() function. # $scope.$watch 'overlayIndex', (index) -> # if index? # # Parse and disaggregate the composite index. # # Note: calling map with parseInt fails with a NaN second value # # since both parseInt can include optional arguments # # (cf. http://stackoverflow.com/questions/262427/javascript-arraymap-and-parseint). # # The work-around is to call map with Number, which takes a # # single string argument. # #[mdlIndex, ovrIndex] = index.split('.').map(Number) # # The selected modeling object. # #modeling = $scope.overlayModelings[mdlIndex] # # The select overlay label map in the selected modeling object. # #overlay = modeling.overlays[ovrIndex] # # Delegate to the image object. # #$scope.volume.selectOverlay(overlay) # # # Move the overlay viewport to the front and update it - # # Cornerstone prototype. # $scope.overlayConfig.style['z-index'] = 1 # slice = $scope.saggitalView.slice # $scope.slice.updateOverlay($scope.imageIds[slice].overlayIds, # index) # else # #$scope.volume.deselectOverlay() # # Move the overlay viewport to the back - Cornerstone prototype. # $scope.overlayConfig.style['z-index'] = -1 # If the project is the default, then remove it from the URL. ControllerHelper.cleanBrowserUrl($rootScope.project) ]
true
define ['angular', 'lodash', 'ngsanitize', 'ngnvd3', 'resources', 'modelingChart', 'breast', 'sliceDisplay', 'collection'], (ng, _) -> ctlrs = ng.module( 'qiprofile.controllers', ['ngSanitize', 'nvd3', 'qiprofile.resources', 'qiprofile.modelingchart', 'qiprofile.breast', 'qiprofile.slicedisplay', 'qiprofile.collection'] ) # The local controller helper methods. ctlrs.factory 'ControllerHelper', [ '$location', ($location) -> # Resets the browser URL search parameters to include at most # a non-default project, since all other search parameters are # redundant. cleanBrowserUrl: (project) -> searchParams = {} # TODO - get the default project from a config file. if project != 'QIN' searchParams.project = project $location.search(searchParams) ] ctlrs.controller 'HomeCtrl', [ '$rootScope', '$scope', '$state', ($rootScope, $scope, $state) -> $scope.goHome = () -> project = $rootScope.project or 'QIN' $state.go('quip.home', project: project) ] ctlrs.controller 'HelpCtrl', [ '$rootScope', '$scope', ($rootScope, $scope) -> # Toggles the root scope showHelp flag. # This method and the showHelp flag are defined in the root # scope in order to share them with the partial template # home alert attribute directives. $rootScope.toggleHelp = -> $rootScope.showHelp = !$rootScope.showHelp # Unconditionally hide help when the location changes. $scope.$on '$locationChangeStart', (event, next, current) -> # Set the showHelp flag on the parent scope, since the # flag is shared with the sibling view scope. $rootScope.showHelp = false ] ctlrs.controller 'AccordionGroupCtrl', [ '$scope', ($scope) -> # The accordion group is initially open. $scope.isOpen = true ] ctlrs.controller 'CollectionListCtrl', [ '$rootScope', '$scope', 'project', 'collections', '$window', ($rootScope, $scope, project, collections, $window) -> # Capture the current project. $rootScope.project = project # Place the collections in the scope. $scope.collections = collections $scope.open = (url) -> $window.location.href = url # The help is always open to start with on this landing page. $rootScope.showHelp = true ] ctlrs.controller 'SubjectListCtrl', [ '$rootScope', '$scope', 'project', 'subjects', 'collections', ($rootScope, $scope, project, subjects, collections) -> # Capture the current project. $rootScope.project = project # Place the subjects and collections in the scope. $scope.subjects = subjects $scope.collections = collections ] ctlrs.controller 'CollectionDetailCtrl', [ '$rootScope', '$scope', 'project', 'collection', 'charting', 'Collection', 'ControllerHelper', ($rootScope, $scope, project, collection, charting, Collection, ControllerHelper) -> # Capture the current project. $rootScope.project = project # Place the collection in the scope. $scope.collection = collection # Obtain the valid data series and labels for the current collection # and put them in the scope. These comprise the X/Y axis dropdown # choices. The X axis choices contain all valid data series. The Y axis # choices may only include continuous data types. $scope.choices = Collection.dataSeriesChoices(collection) # Obtain the formatted scatterplot data. data = Collection.chartData(charting, Object.keys $scope.choices.x) # Obtain the chart padding for each data series - continuous data types # only. The padding for categorical data series is configured in the # correlation module chart rendering function. padding = Collection.chartPadding(data, Object.keys $scope.choices.y) # Put a copy of the default charts (X and Y axes) in the scope. # This charts object changes when the user selects a different # axis to chart. $scope.axes = _.clone(Collection.DEFAULT_AXES[collection]) # Check the validity of the default chart axes. # # TODO - Suppress charts where no data exists for a particular data # series throughout the collection. # checkAxes = (axis) -> axis.x in xAxisChoices or throw new Error "Invalid #{ collection } X-axis data series: " + "#{ axis.x }" axis.y in yAxisChoices or throw new Error "Invalid #{ collection } Y-axis data series: " + "#{ axis.y }" xAxisChoices = Object.keys($scope.choices.x) yAxisChoices = Object.keys($scope.choices.y) checkAxes(axis) for axis in $scope.axes # Place the chart configuration object in the scope. $scope.config = data: data padding: padding axes: $scope.axes # If the user changes any X or Y axis selection, then re-render the # charts. The watcher is invoked on initialization and whenever the # user changes the axes. On initialization, then the watcher is called # with new axes value argument identical (===) to the old value # argument. If the user changes the axes, then the watcher is called # with different new and old axes objects. watcher = (newValue, oldValue) -> # If the user changed the axes, then re-render the charts. if newValue != oldValue Collection.renderCharts($scope.config) # Since charts is an object, the objectEquality flag is set to true. # AngularJS then copies the object for later comparison and uses # angular.equals to recursively compare the object properties rather # than a simple === test, which is the default. $scope.$watch('axes', watcher, true) # If the project is the default, then remove it from the URL. ControllerHelper.cleanBrowserUrl($rootScope.project) ] ## The Subject Detail page controllers. ctlrs.controller 'SubjectDetailCtrl', [ '$rootScope', '$scope', 'subject', 'ControllerHelper', ($rootScope, $scope, subject, ControllerHelper) -> # Capture the current project. $rootScope.project = subject.project # Place the subject in scope. $scope.subject = subject # If the project is the default, then remove it from the URL. ControllerHelper.cleanBrowserUrl($rootScope.project) ] ctlrs.controller 'ScanVolumeSelectCtrl', [ '$scope', ($scope) -> # Place the scan protocol id in scope. $scope.protocolId = $scope.scan.protocol ] ctlrs.controller 'RegistrationVolumeSelectCtrl', [ '$scope', ($scope) -> # Place the registration protocol id in scope. $scope.protocolId = $scope.registration.protocol ] ctlrs.controller 'ScanProtocolCtrl', [ '$scope', '$uibModal', 'Resources', ($scope, $uibModal, Resources) -> # Open a modal window to display the scan procedure properties. $scope.open = -> $uibModal.open controller: 'ProtocolModalCtrl' templateUrl: '/partials/scan-protocol.html' size: 'sm' resolve: # Fetch the scan protocol. protocol: -> Resources.ScanProtocol.find(id: $scope.protocolId) ] ctlrs.controller 'RegistrationProtocolCtrl', [ '$scope', '$uibModal', 'Resources', ($scope, $uibModal, Resources) -> # Open a modal window to display the registration properties. $scope.open = -> $uibModal.open controller: 'ProtocolModalCtrl' templateUrl: '/partials/registration-protocol.html' size: 'sm' resolve: # Fetch the registration protocol. protocol: -> Resources.RegistrationProtocol.find(id: $scope.protocolId) ] ctlrs.controller 'ProtocolModalCtrl', [ '$scope', '$uibModalInstance', 'protocol', ($scope, $uibModalInstance, protocol) -> # Place the protocol object in the modal scope. $scope.protocol = protocol $scope.close = -> $uibModalInstance.close() ] ## The Imaging Profile pane controllers. ctlrs.controller 'SubjectModelingCtrl', [ '$scope', ($scope) -> # Place the modelings in scope. # Note: modelings is a subject property that is calculated # on the fly. Since the partials reference the modelings in # ng-switch and ng-repeat models, AngularJS sets up hidden # watches on this variable and redigests the partials whenever # the property value is calculated. If subject.modelings were # used instead of modelings, then AngularJS would enter an # infinite digest cycle. Placing the modelings variable in # scope here avoids this trap by fixing the value for the # course of the AngularJS page formatting. $scope.modelings = $scope.subject.modelings # The format button action. $scope.toggleModelingFormat = -> if $scope.modelingFormat is 'chart' $scope.modelingFormat = 'table' else if $scope.modelingFormat is 'table' $scope.modelingFormat = 'chart' else throw new Error "Modeling format is not recognized:" + " #{ $scope.modelingFormat }" # The modeling format is 'chart' if the subject has # more than one session, 'table' otherwise. if $scope.subject.isMultiSession() $scope.modelingFormat = 'chart' else $scope.modelingFormat = 'table' # The default modeling results index is the first. $scope.modelingIndex = 0 # Place the selected modeling in scope. $scope.$watch 'modelingIndex', (modelingIndex) -> $scope.selModeling = $scope.modelings[modelingIndex] ] ctlrs.controller 'PkModelingHelpCtrl', [ '$scope', '$uibModal', ($scope, $uibModal) -> $scope.open = -> $uibModal.open controller: 'PkModelingHelpModalCtrl' templateUrl: '/partials/pk-modeling-help.html' size: 'med' ] ctlrs.controller 'PkModelingHelpModalCtrl', [ '$scope', '$uibModalInstance', ($scope, $uibModalInstance) -> $scope.close = -> $uibModalInstance.close() ] ctlrs.controller 'ModelingProtocolCtrl', [ '$scope', ($scope) -> # Place the protocol id in scope. $scope.protocolId = $scope.modeling.protocol ] ctlrs.controller 'ModelingInfoCtrl', [ '$scope', '$uibModal', 'Resources', ($scope, $uibModal, Resources) -> # Open a modal window to display the modeling input properties. $scope.open = -> $uibModal.open controller: 'ModelingInfoModalCtrl' templateUrl: '/partials/modeling-info.html' size: 'sm' resolve: # Make modeling injectable in the modal controller. # See the ModelingInfoModalCtrl comment. modeling: -> $scope.modeling # Fetch the modeling protocol. protocol: -> Resources.ModelingProtocol.find(id: $scope.modeling.protocol) ] ctlrs.controller 'ModelingInfoModalCtrl', [ '$scope', '$uibModalInstance', 'modeling', 'protocol', ($scope, $uibModalInstance, modeling, protocol) -> # Since the modal is not contained in the application page, this # modal controller scope does not inherit the application page # scope. Therefore, the application scope modeling variable is # not visible to the modal scope. Hence, it is necessary to # transfer the modeling object as a $uibModal.open function resolve # property into this controller's injection list. # The assignment below then places the modeling object in the # modal scope for use in the modal template partial. $scope.modeling = modeling $scope.protocol = protocol $scope.close = -> $uibModalInstance.close() ] ctlrs.controller 'ModelingSourceProtocolCtrl', [ '$scope', ($scope) -> # The modeling source is either a scan or registration protocol. if $scope.modeling.source.scan? $scope.sourceType = 'scan' $scope.protocolId = $scope.modeling.source.scan else if $scope.modeling.source.registration? $scope.sourceType = 'registration' $scope.protocolId = $scope.modeling.source.registration else throw new Error("The modeling source has neither a scan" + " nor a registration protocol reference") ] ctlrs.controller 'TimelineCtrl', [ '$scope', '$state', '$compile', 'Timeline', ($scope, $state, $compile, Timeline) -> # The chart {options, data} configuration. chartConfig = Timeline.configure($scope.subject) $scope.options = chartConfig.options $scope.data = chartConfig.data # The global configuration. Disable the data watcher since, # once built, the data is not changed. Furthermore, the # data is the modeling parameter objects, which are complex # objects with a circular object graph reference # (paramResult -> parent modelingResult -> child paramResult). $scope.config = deepWatchData: false # The chart decoration callback. $scope.decorate = (scope, element) -> # Note: since the nvd3 directive isolates the scope, # it does not inherit to the parent $scope properties. # Therefore, we must specify $scope.subject rather than # scope.subject. Timeline.decorate(element, $scope.subject, scope, $state) # Note: an angular-nvd3 bug voids element changes made # in this callback on refresh # (cf. https://github.com/krispo/angular-nvd3/issues/316). # The work-around is to surgically intervene in the # defective ngnvd3 code. # TODO - periodically check whether the ngnvd3 bug is # fixed and remove the work-around if possible. #scope.isReady = false if _.isUndefined(scope.isBroken) broken = scope.api.refresh fixed = -> # Note: setting scope.isReady should trigger the watcher # but doesn't. The work-around to this work-around bug is # to force the issue by calling the decorate function # directly in the refresh rather than indirectly via the # watcher. # TODO - remove this work-around to a work-around bug when # the original work-around is fixed. broken() $scope.decorate(scope, element) scope.api.refresh = fixed scope.isBroken = false ] ctlrs.controller 'IntensityChartCtrl', [ '$scope', 'IntensityChart', ($scope, IntensityChart) -> # The chart {options, data} configuration. chartConfig = IntensityChart.configure($scope.scan) $scope.options = chartConfig.options $scope.data = chartConfig.data # The global configuration. See ModelingChartCtrl comment. $scope.config = deepWatchData: false ] ctlrs.controller 'ModelingChartCtrl', [ '$scope', 'ModelingChart', ($scope, ModelingChart) -> # selModeling is set to the modeling object to display. # It is set if and only if there is at least one modeling # object. Thus, the if test guards against there not being # any modeling object to display. if $scope.selModeling? # The chart {options, data} configuration. chartConfig = ModelingChart.configure($scope.selModeling.results, $scope.paramKey) $scope.options = chartConfig.options $scope.data = chartConfig.data # The global configuration. Disable the data watcher since, # once built, the data is not changed. Furthermore, the # data is the modeling parameter objects, which are complex # objects with a circular object graph reference # (paramResult -> parent modelingResult -> child paramResult). $scope.config = deepWatchData: false ] ## The modeling parameter controllers. ## # # TODO - revise to beter fit ngnvd3. These controller's don't do # much. # # Each controller is required to set the following scope variable: # * dataSeriesConfig - the ModelingChart.configureD3 dataSeriesSpec # argument # # Note: The modeling parameter controllers defined below somewhat abuse # Controller-View separation of control, since the controller places # formatting details like the label and color in a scope variable. This # is necessary evil to accomodate d3 charting. A preferable solution is # to specify the color in a style sheet and the data series label in a # transcluded partial. However, that solution appears to go against the # grain of d3. In general, the modeling chart partial/controller pattern # should not be used as an example for building a non-d3 charting # component. ctlrs.controller 'KTransCtrl', [ '$scope', ($scope) -> $scope.paramKey = 'kTrans' ] ctlrs.controller 'VeCtrl', [ '$scope', ($scope) -> $scope.paramKey = 'vE' ] ctlrs.controller 'TauICtrl', [ '$scope', ($scope) -> $scope.paramKey = 'tauI' ] ## The Clinical Profile pane controllers. ## ctlrs.controller 'PathologyCtrl', [ '$scope', ($scope) -> $scope.pathology = $scope.encounter.pathology ] ctlrs.controller 'BreastHormoneReceptorsCtrl', [ '$scope', ($scope) -> $scope.hormoneReceptors = $scope.tumor.hormoneReceptors ] ctlrs.controller 'BreastGeneticExpressionCtrl', [ '$scope', ($scope) -> $scope.geneticExpression = $scope.tumor.geneticExpression ] ctlrs.controller 'BreastGeneAssayCtrl', [ '$scope', 'Breast', ($scope, Breast) -> $scope.assay = $scope.geneticExpression.normalizedAssay $scope.recurrenceScore = Breast.recurrenceScore($scope.assay) ] ctlrs.controller 'TumorExtentCtrl', [ '$scope', ($scope) -> $scope.extent = $scope.tumor.extent ] ctlrs.controller 'ResidualCancerBurdenCtrl', [ '$scope', 'Breast', ($scope, Breast) -> $scope.rcb = Breast.residualCancerBurden($scope.tumor) ] ctlrs.controller 'RecurrenceScoreHelpCtrl', [ '$scope', '$uibModal', ($scope, $uibModal) -> $scope.open = -> $uibModal.open controller: 'RecurrenceScoreHelpModalCtrl' templateUrl: '/partials/recurrence-score-help.html' size: 'med' ] ctlrs.controller 'RecurrenceScoreHelpModalCtrl', [ '$scope', '$uibModalInstance', ($scope, $uibModalInstance) -> $scope.close = -> $uibModalInstance.close() ] ctlrs.controller 'DosageAmountHelpCtrl', [ '$scope', '$uibModal', ($scope, $uibModal) -> $scope.open = -> $uibModal.open controller: 'DosageAmountHelpModalCtrl' templateUrl: '/partials/dosage-amount-help.html' size: 'med' ] ctlrs.controller 'DosageAmountHelpModalCtrl', [ '$scope', '$uibModalInstance', ($scope, $uibModalInstance) -> $scope.close = -> $uibModalInstance.close() ] ctlrs.controller 'TNMCtrl', [ '$scope', ($scope) -> # The parent can either be a pathology evaluation or a # generic evaluation outcome iterator. path = $scope.tumor $scope.tnm = if path then path.tnm else $scope.outcome ] ctlrs.controller 'BreastTNMStageHelpCtrl', [ '$scope', '$uibModal', ($scope, $uibModal) -> $scope.open = -> $uibModal.open controller: 'BreastTNMStageHelpModalCtrl' templateUrl: '/partials/breast-tnm-stage-help.html' size: 'med' ] ctlrs.controller 'BreastTNMStageHelpModalCtrl', [ '$scope', '$uibModalInstance', ($scope, $uibModalInstance) -> $scope.close = -> $uibModalInstance.close() ] ctlrs.controller 'SarcomaTNMStageHelpCtrl', [ '$scope', '$uibModal', ($scope, $uibModal) -> $scope.open = -> $uibModal.open controller: 'SarcomaTNMStageHelpModalCtrl' templateUrl: '/partials/sarcoma-tnm-stage-help.html' size: 'med' ] ctlrs.controller 'SarcomaTNMStageHelpModalCtrl', [ '$scope', '$uibModalInstance', ($scope, $uibModalInstance) -> $scope.close = -> $uibModalInstance.close() ] ctlrs.controller 'GradeCtrl', [ '$scope', ($scope) -> $scope.grade = $scope.tnm.grade ] ctlrs.controller 'HormoneReceptorCtrl', [ '$scope', ($scope) -> # The parent of a generic HormoneReceptor is a generic # evaluation outcome iterator. $scope.receptorStatus = $scope.outcome ] ctlrs.controller 'EstrogenCtrl', [ '$scope', ($scope) -> $scope.receptorStatus = _.find($scope.hormoneReceptors, (hr) -> hr.hormone == 'estrogen') ] ctlrs.controller 'ProgesteroneCtrl', [ '$scope', ($scope) -> $scope.receptorStatus = _.find($scope.hormoneReceptors, (hr) -> hr.hormone == 'progesterone') ] ctlrs.controller 'ChemotherapyCtrl', [ '$scope', ($scope) -> isChemo = (dosage) -> dosage.agent._cls == 'Drug' chemo = $scope.treatment.dosages.filter(isChemo) $scope.chemotherapy = {dosages: chemo} if chemo.length ] ctlrs.controller 'RadiotherapyCtrl', [ '$scope', ($scope) -> isRadio = (dosage) -> dosage.agent._cls == 'Radiation' radio = $scope.treatment.dosages.filter(isRadio) $scope.radiotherapy = {dosages: radio} if radio.length ] ctlrs.controller 'NecrosisPercentCtrl', [ '$scope', ($scope) -> $scope.necrosis_percent = $scope.tumor.necrosis_percent ] ## The Session Detail page controllers. ## ctlrs.controller 'SessionDetailCtrl', [ '$rootScope', '$scope', '$state', 'session', 'ControllerHelper', ($rootScope, $scope, $state, session, ControllerHelper) -> # Capture the current project. $rootScope.project = session.subject.project # Place the session in the scope. $scope.session = session # If the project is the default, then remove it from the URL. ControllerHelper.cleanBrowserUrl($rootScope.project) ] # # TODO - retain on the xtk branch only. # ctlrs.controller 'VolumeDisplayCtrl', [ '$scope', '$state', ($scope, $state) -> # Create the image object on demand. $scope.image = $scope.volume.image # Opens the series image display page. # # @param image the Image object $scope.openImage = () -> # The parent scan or registration image sequence. imageSequence = $scope.volume.imageSequence # The common parameters. params = project: imageSequence.session.subject.project collection: imageSequence.session.subject.collection subject: imageSequence.session.subject.number session: imageSequence.session.number detail: imageSequence.session.detail volume: $scope.volume.number # The target imageSequence route prefix. route = 'quip.collection.subject.session.scan.' # Add to the parameters and route based on the imageSequence type. if imageSequence._cls == 'Scan' params.scan = imageSequence.number else if imageSequence._cls == 'Registration' params.scan = imageSequence.scan.number params.registration = imageSequence.resource route += 'registration.' else throw new TypeError("Unsupported image sequence type:" + " #{ imageSequence._cls }") # Finish off the route. route += 'volume.slice' # Go to the volume page. $state.go(route, params) # # TODO - Legacy controller partially repurposed for slice display. # If volume display is reenabled, then borrow what is needed for # the above controller and delete the rest. # # ctlrs.controller 'VolumeeDisplayCtrl', [ # '$rootScope', '$scope', '$location', '$sce', 'ModelingChart', 'SliceDisplay', # 'ControllerHelper', 'session', 'imageSequence', 'volume', 'slice', # ($rootScope, $scope, $location, $sce, ModelingChart, SliceDisplay, # ControllerHelper, session, imageSequence, volume, slice) -> # # Capture the current project. # $rootScope.project = session.subject.project # # # @param key the modeling parameter key, e.g. 'PI:KEY:<KEY>END_PI' # # @return the modeling parameter heading HTML span element, # # e.g. '<span>&Delta;K<sub>trans</sub></span>' # $scope.parameterHeading = (key) -> # html = "<span>#{ Modeling.properties[key].html }</span>" # $sce.trustAsHtml(html) # # # The session modelings which have an overlay. # $scope.overlayModelings = ( # mdl for mdl in session.modelings when mdl.overlays.length? # ) # # The overlay selection. # $scope.overlayIndex = null # # # The initial saggital slice. # $scope.saggitalView = slice: slice # # # The overlay opacity slider setting and CSS styles. # $scope.overlayConfig = # setting: 1 # style: # "opacity": 1 # "z-index": -1 # # # Watch for a change in the saggital slice control setting. # # When the slice index changes, then update the image and, # # if selected, the overlay. # # # # TODO - address the volume-controls.jade TODO items. # # # $scope.$watch 'saggitalView.slice', (index) -> # SliceDisplay.updateSlice($scope.imageIds[index].dicomImageId) # if $scope.overlayIndex? # Slice.updateOverlay($scope.imageIds[index].overlayIds, # $scope.overlayIndex) # # # Update the URL search parameters. # $location.search('volume', volume) # $location.search('slice', slice) # # # The overlayIndex scope variable is the overlay radio input # # selection value in the format *modeling index*.*overlay index*, # # e.g. the value '0.1' is the second overlay of the first modeling. # # By default, no overlay is selected. When a radio button is # # checked, then the overlayIndex variable is set and the watcher # # below is triggered. # # # # If the overlayIndex scope variable is changed to a non-null value, # # then parse the value and call the image selectOverlay(overlay) # # function on the referenced overlay. # # Otherwise, call the image deselectOverlay() function. # $scope.$watch 'overlayIndex', (index) -> # if index? # # Parse and disaggregate the composite index. # # Note: calling map with parseInt fails with a NaN second value # # since both parseInt can include optional arguments # # (cf. http://stackoverflow.com/questions/262427/javascript-arraymap-and-parseint). # # The work-around is to call map with Number, which takes a # # single string argument. # #[mdlIndex, ovrIndex] = index.split('.').map(Number) # # The selected modeling object. # #modeling = $scope.overlayModelings[mdlIndex] # # The select overlay label map in the selected modeling object. # #overlay = modeling.overlays[ovrIndex] # # Delegate to the image object. # #$scope.volume.selectOverlay(overlay) # # # Move the overlay viewport to the front and update it - # # Cornerstone prototype. # $scope.overlayConfig.style['z-index'] = 1 # slice = $scope.saggitalView.slice # $scope.slice.updateOverlay($scope.imageIds[slice].overlayIds, # index) # else # #$scope.volume.deselectOverlay() # # Move the overlay viewport to the back - Cornerstone prototype. # $scope.overlayConfig.style['z-index'] = -1 # # # # If the project is the default, then remove it from the URL. # ControllerHelper.cleanBrowserUrl($rootScope.project) ] # The Image Slice Display controller. ctlrs.controller 'SliceDisplayCtrl', [ '$rootScope', '$scope', '$location', 'SliceDisplay', 'ControllerHelper', 'timeSeries', 'volume', 'slice', ($rootScope, $scope, $location, SliceDisplay, ControllerHelper, timeSeries, volume, slice) -> # Capture the current project. $rootScope.project = timeSeries.imageSequence.session.subject.project # Place the time series in scope. $scope.timeSeries = timeSeries # Initialize the volume number, if necessary. if not volume? # The default volume is at bolus arrival, if defined, otherwise the # first volume. bolusArvNdx = timeSeries.imageSequence.bolusArrivalIndex volume = if bolusArvNdx? then bolusArvNdx + 1 else 1 # Update the URL search parameter. $location.search('volume', volume) # Place the volume in scope. $scope.volume = volumeNbr: volume # Initialize the slice number, if necessary. if not slice? # The default slice is the point of maximal ROI extent, if defined, # otherwise the first slice. # TODO - calculate the maximal ROI slice in the pipeline and put in # the REST database. maximalROISlice = undefined slice = if maximalROISlice? then maximalROISlice + 1 else 1 # Update the URL search parameter. $location.search('slice', slice) # Place the slice in scope. $scope.slice = sliceNbr: slice # The slice dimensions. $scope.dimensions = [ "Saggital" "Coronal" "Axial" ] # The default slice dimension. $scope.dimension = "Axial" # # TODO - add overlays. The REST data model is: # Modeling { # result { # parameter: parameterResult{name, labelMap: {name, colorTable}}, ...} # } # } # and: # Scan { # rois: [{name, labelMap: {name, colorTable}}, ...] # } # } # with one ROI per tumor. # # The LabelMap objects need to be collected by Scan.extend into a # Scan.overlays virtual property {key, image} object, where: # * *key* is either a modeling parameter name or 'roi' # * *image* is the LabelMap extended by the Image service, which # should be done in Modeling.extend and Scan.extend. # # The composite ROI needs to be created in the pipeline from the # tumor ROIs and placed into a new REST Scan.rois ROI object # {composite, regions}, where: # *composite* is a LabelMap object # *regions* is the current Scan.rois [Region, ...] array. Since # the Scan ROIs do not overlap, the masks can be combined in a # ndarray operation by the pipeline. # # The Slice Display page should have an overlay selection control, # one per modeling parameter and one for the composite ROI. # # A registration image sequence needs to delegate to the parent # scan overlays. This can be done in Registration.extend by adding a # Registration.overlays virtual property. # # Finally, TimeSeries.extend should create a TimeSeries.overlays # virtual property which delegates to the parent overlays. display = -> SliceDisplay.display($scope.timeSeries, $scope.volume.volumeNbr, $scope.slice.sliceNbr) watcher = (newValue, oldValue) -> if newValue != oldValue display() # Display the image the first time and whenever the volume changes # thereafter. $scope.$watch('volume', display, true) # Redisplay the image when the slice changes. $scope.$watch('slice', watcher, true) # # TODO - implement the overlay watcher in conjunction with the # changes described above. # # # Redisplay the overlay when the overlay changes. # $scope.$watch 'overlayIndex', (overlayIndex, previous) -> # # There must first be an overlay. This situation should never # # occur by construction if the UI overlay selection properly # # guards against it. # if not data? # throw new ReferenceError("The time series does not have an overlay") # if overlayIndex != previous # display() # # TODO - borrow whatever is useful from below--but don't copy it as is--then # delete it. # # '$rootScope', '$scope', '$location', '$sce', 'ModelingChart', 'SliceDisplay', # 'ControllerHelper', 'session', 'imageSequence', 'volume', 'slice', # ($rootScope, $scope, $location, $sce, ModelingChart, SliceDisplay, # ControllerHelper, session, imageSequence, volume, slice) -> # # Capture the current project. # $rootScope.project = session.subject.project # # # @param key the modeling parameter key, e.g. 'PI:KEY:<KEY>END_PI' # # @return the modeling parameter heading HTML span element, # # e.g. '<span>&Delta;K<sub>trans</sub></span>' # $scope.parameterHeading = (key) -> # html = "<span>#{ Modeling.properties[key].html }</span>" # $sce.trustAsHtml(html) # # # The session modelings which have an overlay. # $scope.overlayModelings = ( # mdl for mdl in session.modelings when mdl.overlays.length? # ) # # The overlay selection. # $scope.overlayIndex = null # # # The initial saggital slice. # $scope.saggitalView = slice: slice # # # The overlay opacity slider setting and CSS styles. # $scope.overlayConfig = # setting: 1 # style: # "opacity": 1 # "z-index": -1 # # # Watch for a change in the saggital slice control setting. # # When the slice index changes, then update the image and, # # if selected, the overlay. # # # # TODO - address the volume-controls.jade TODO items. # # # $scope.$watch 'saggitalView.slice', (index) -> # SliceDisplay.updateSlice($scope.imageIds[index].dicomImageId) # if $scope.overlayIndex? # Slice.updateOverlay($scope.imageIds[index].overlayIds, # $scope.overlayIndex) # # # # The overlayIndex scope variable is the overlay radio input # # selection value in the format *modeling index*.*overlay index*, # # e.g. the value '0.1' is the second overlay of the first modeling. # # By default, no overlay is selected. When a radio button is # # checked, then the overlayIndex variable is set and the watcher # # below is triggered. # # # # If the overlayIndex scope variable is changed to a non-null value, # # then parse the value and call the image selectOverlay(overlay) # # function on the referenced overlay. # # Otherwise, call the image deselectOverlay() function. # $scope.$watch 'overlayIndex', (index) -> # if index? # # Parse and disaggregate the composite index. # # Note: calling map with parseInt fails with a NaN second value # # since both parseInt can include optional arguments # # (cf. http://stackoverflow.com/questions/262427/javascript-arraymap-and-parseint). # # The work-around is to call map with Number, which takes a # # single string argument. # #[mdlIndex, ovrIndex] = index.split('.').map(Number) # # The selected modeling object. # #modeling = $scope.overlayModelings[mdlIndex] # # The select overlay label map in the selected modeling object. # #overlay = modeling.overlays[ovrIndex] # # Delegate to the image object. # #$scope.volume.selectOverlay(overlay) # # # Move the overlay viewport to the front and update it - # # Cornerstone prototype. # $scope.overlayConfig.style['z-index'] = 1 # slice = $scope.saggitalView.slice # $scope.slice.updateOverlay($scope.imageIds[slice].overlayIds, # index) # else # #$scope.volume.deselectOverlay() # # Move the overlay viewport to the back - Cornerstone prototype. # $scope.overlayConfig.style['z-index'] = -1 # If the project is the default, then remove it from the URL. ControllerHelper.cleanBrowserUrl($rootScope.project) ]
[ { "context": "---\n---\n\n# Ben Scott # 2015-10-02 # CoffeeScript Sketch #\n\n'use strict", "end": 20, "score": 0.9997660517692566, "start": 11, "tag": "NAME", "value": "Ben Scott" } ]
js/lack_of_focus.coffee
evan-erdos/evan-erdos.github.io
1
--- --- # Ben Scott # 2015-10-02 # CoffeeScript Sketch # 'use strict' # just like JavaScript ### `P5.js` Main class This is our instance of the main class in the `P5.js` library. The argument is the link between the library and this code, and the special functions we override in the class definition are callbacks for P5.js events. ### myp = new p5 (p) -> ### Input ### alt = false mouse = [p.mouseX,p.mouseY] lastMouse = [p.pmouseX,p.pmouseY] ### DOM ### [container,canvas] = [null,null] [r_sl,g_sl,b_sl] = [null,null,null] [d_sl,s_sl,rand_sl] = [null,null,null] ### `Events` These functions are automatic callbacks for `P5.js` events: - `p.preload` is called once, immediately before `setup` - `p.setup` is called once, at the beginning of execution - `p.draw` is called as frequently as `p.framerate` - `p.keyPressed` is called on every key input event - `p.mousePressed` is called on mouse down - `p.windowResized` keeps window full - `p.remove` destroys everything in the sketch ### p.setup = -> setupCanvas() setupDOM() p.noStroke() p.frameRate(60) p.draw = -> getInput() drawDOM() p.keyPressed = -> alt = !alt if (p.keyCode is p.ALT) p.getInput = -> mouse = [p.mouseX,p.mouseY] if (p.mouseIsPressed) p.mousePressed() p.mousePressed = -> s = s_sl.value() [x,y] = [16*s,16*s] d = d_sl.value() rgb = p.color( r_sl.value()+p.random(d) g_sl.value()+p.random(d) b_sl.value()+p.random(d),127) rand = rand_sl.value() delta_size = p.random(s/2) if (alt) then p.fill(255) else p.fill(rgb) p.ellipse( mouse[0]+p.random(-rand,rand) mouse[1]+p.random(-rand,rand) x*delta_size,y*delta_size) #p.windowResized = -> p.resizeCanvas(p.windowWidth, p.windowHeight); #p.remove = -> p5 = null ### DOM Functions These functions initialize the DOM objects in the sketch. - `setupCanvas` creates and positions the main canvas - `setupDOM` creates and positions the color sliders - `drawDOM` renders the color sliders on every draw - `getInput` collects input data, processes it, and in the case of `p.mouseIsPressed`, it calls the mouse event callback (otherwise it single-clicks) ### setupCanvas = -> container = document.getElementById("CoffeeSketch") canvas = p.createCanvas(756,512) canvas.parent('CoffeeSketch') canvas.class("entry") canvas.style("max-width", "100%") setupDOM = -> writeDOMText(" Red: ") r_sl = p.createSlider(0,255,100) r_sl.parent('CoffeeSketch') writeDOMText(" Green: ") g_sl = p.createSlider(0,255,0) g_sl.parent('CoffeeSketch') writeDOMText(" Blue: ") b_sl = p.createSlider(0,255,255) b_sl.parent('CoffeeSketch') writeDOMText(" Size: ") s_sl = p.createSlider(1,8,4) s_sl.parent('CoffeeSketch') writeDOMText(" Delta: ") d_sl = p.createSlider(0,64,32) d_sl.parent('CoffeeSketch') writeDOMText(" Random: ") rand_sl = p.createSlider(0,16,4) rand_sl.parent('CoffeeSketch') drawDOM = -> p.fill(0) #p.text("Red",150,16+4) writeDOMText = (s) -> temp = document.createTextNode(s) container.appendChild(temp) getInput = -> mouse = [p.mouseX,p.mouseY] lastMouse = [p.pmouseX,p.pmouseY] p.mousePressed() if (p.mouseIsPressed)
19957
--- --- # <NAME> # 2015-10-02 # CoffeeScript Sketch # 'use strict' # just like JavaScript ### `P5.js` Main class This is our instance of the main class in the `P5.js` library. The argument is the link between the library and this code, and the special functions we override in the class definition are callbacks for P5.js events. ### myp = new p5 (p) -> ### Input ### alt = false mouse = [p.mouseX,p.mouseY] lastMouse = [p.pmouseX,p.pmouseY] ### DOM ### [container,canvas] = [null,null] [r_sl,g_sl,b_sl] = [null,null,null] [d_sl,s_sl,rand_sl] = [null,null,null] ### `Events` These functions are automatic callbacks for `P5.js` events: - `p.preload` is called once, immediately before `setup` - `p.setup` is called once, at the beginning of execution - `p.draw` is called as frequently as `p.framerate` - `p.keyPressed` is called on every key input event - `p.mousePressed` is called on mouse down - `p.windowResized` keeps window full - `p.remove` destroys everything in the sketch ### p.setup = -> setupCanvas() setupDOM() p.noStroke() p.frameRate(60) p.draw = -> getInput() drawDOM() p.keyPressed = -> alt = !alt if (p.keyCode is p.ALT) p.getInput = -> mouse = [p.mouseX,p.mouseY] if (p.mouseIsPressed) p.mousePressed() p.mousePressed = -> s = s_sl.value() [x,y] = [16*s,16*s] d = d_sl.value() rgb = p.color( r_sl.value()+p.random(d) g_sl.value()+p.random(d) b_sl.value()+p.random(d),127) rand = rand_sl.value() delta_size = p.random(s/2) if (alt) then p.fill(255) else p.fill(rgb) p.ellipse( mouse[0]+p.random(-rand,rand) mouse[1]+p.random(-rand,rand) x*delta_size,y*delta_size) #p.windowResized = -> p.resizeCanvas(p.windowWidth, p.windowHeight); #p.remove = -> p5 = null ### DOM Functions These functions initialize the DOM objects in the sketch. - `setupCanvas` creates and positions the main canvas - `setupDOM` creates and positions the color sliders - `drawDOM` renders the color sliders on every draw - `getInput` collects input data, processes it, and in the case of `p.mouseIsPressed`, it calls the mouse event callback (otherwise it single-clicks) ### setupCanvas = -> container = document.getElementById("CoffeeSketch") canvas = p.createCanvas(756,512) canvas.parent('CoffeeSketch') canvas.class("entry") canvas.style("max-width", "100%") setupDOM = -> writeDOMText(" Red: ") r_sl = p.createSlider(0,255,100) r_sl.parent('CoffeeSketch') writeDOMText(" Green: ") g_sl = p.createSlider(0,255,0) g_sl.parent('CoffeeSketch') writeDOMText(" Blue: ") b_sl = p.createSlider(0,255,255) b_sl.parent('CoffeeSketch') writeDOMText(" Size: ") s_sl = p.createSlider(1,8,4) s_sl.parent('CoffeeSketch') writeDOMText(" Delta: ") d_sl = p.createSlider(0,64,32) d_sl.parent('CoffeeSketch') writeDOMText(" Random: ") rand_sl = p.createSlider(0,16,4) rand_sl.parent('CoffeeSketch') drawDOM = -> p.fill(0) #p.text("Red",150,16+4) writeDOMText = (s) -> temp = document.createTextNode(s) container.appendChild(temp) getInput = -> mouse = [p.mouseX,p.mouseY] lastMouse = [p.pmouseX,p.pmouseY] p.mousePressed() if (p.mouseIsPressed)
true
--- --- # PI:NAME:<NAME>END_PI # 2015-10-02 # CoffeeScript Sketch # 'use strict' # just like JavaScript ### `P5.js` Main class This is our instance of the main class in the `P5.js` library. The argument is the link between the library and this code, and the special functions we override in the class definition are callbacks for P5.js events. ### myp = new p5 (p) -> ### Input ### alt = false mouse = [p.mouseX,p.mouseY] lastMouse = [p.pmouseX,p.pmouseY] ### DOM ### [container,canvas] = [null,null] [r_sl,g_sl,b_sl] = [null,null,null] [d_sl,s_sl,rand_sl] = [null,null,null] ### `Events` These functions are automatic callbacks for `P5.js` events: - `p.preload` is called once, immediately before `setup` - `p.setup` is called once, at the beginning of execution - `p.draw` is called as frequently as `p.framerate` - `p.keyPressed` is called on every key input event - `p.mousePressed` is called on mouse down - `p.windowResized` keeps window full - `p.remove` destroys everything in the sketch ### p.setup = -> setupCanvas() setupDOM() p.noStroke() p.frameRate(60) p.draw = -> getInput() drawDOM() p.keyPressed = -> alt = !alt if (p.keyCode is p.ALT) p.getInput = -> mouse = [p.mouseX,p.mouseY] if (p.mouseIsPressed) p.mousePressed() p.mousePressed = -> s = s_sl.value() [x,y] = [16*s,16*s] d = d_sl.value() rgb = p.color( r_sl.value()+p.random(d) g_sl.value()+p.random(d) b_sl.value()+p.random(d),127) rand = rand_sl.value() delta_size = p.random(s/2) if (alt) then p.fill(255) else p.fill(rgb) p.ellipse( mouse[0]+p.random(-rand,rand) mouse[1]+p.random(-rand,rand) x*delta_size,y*delta_size) #p.windowResized = -> p.resizeCanvas(p.windowWidth, p.windowHeight); #p.remove = -> p5 = null ### DOM Functions These functions initialize the DOM objects in the sketch. - `setupCanvas` creates and positions the main canvas - `setupDOM` creates and positions the color sliders - `drawDOM` renders the color sliders on every draw - `getInput` collects input data, processes it, and in the case of `p.mouseIsPressed`, it calls the mouse event callback (otherwise it single-clicks) ### setupCanvas = -> container = document.getElementById("CoffeeSketch") canvas = p.createCanvas(756,512) canvas.parent('CoffeeSketch') canvas.class("entry") canvas.style("max-width", "100%") setupDOM = -> writeDOMText(" Red: ") r_sl = p.createSlider(0,255,100) r_sl.parent('CoffeeSketch') writeDOMText(" Green: ") g_sl = p.createSlider(0,255,0) g_sl.parent('CoffeeSketch') writeDOMText(" Blue: ") b_sl = p.createSlider(0,255,255) b_sl.parent('CoffeeSketch') writeDOMText(" Size: ") s_sl = p.createSlider(1,8,4) s_sl.parent('CoffeeSketch') writeDOMText(" Delta: ") d_sl = p.createSlider(0,64,32) d_sl.parent('CoffeeSketch') writeDOMText(" Random: ") rand_sl = p.createSlider(0,16,4) rand_sl.parent('CoffeeSketch') drawDOM = -> p.fill(0) #p.text("Red",150,16+4) writeDOMText = (s) -> temp = document.createTextNode(s) container.appendChild(temp) getInput = -> mouse = [p.mouseX,p.mouseY] lastMouse = [p.pmouseX,p.pmouseY] p.mousePressed() if (p.mouseIsPressed)
[ { "context": "key: 'liquid'\npatterns: [\n { include: 'text.html.liquid' }\n]\n", "end": 12, "score": 0.5168231725692749, "start": 6, "tag": "KEY", "value": "liquid" } ]
grammars/repositories/inlines/liquid.cson
doc22940/language-markdown
138
key: 'liquid' patterns: [ { include: 'text.html.liquid' } ]
78305
key: '<KEY>' patterns: [ { include: 'text.html.liquid' } ]
true
key: 'PI:KEY:<KEY>END_PI' patterns: [ { include: 'text.html.liquid' } ]
[ { "context": "oginUsers.some (u) =>\n if u.username is username && u.password is password\n user = JS", "end": 690, "score": 0.9859931468963623, "start": 682, "tag": "USERNAME", "value": "username" }, { "context": " if u.username is username && u.passwo...
src/mock/mock.coffee
triaregithubaccess/kardea_Admin_panel
0
import axios from 'axios'; import MockAdapter from 'axios-mock-adapter'; import { LoginUsers, Users } from './data/user'; _Users = Users; export_default = # /** # * mock bootstrap # */ bootstrap: -> mock = new MockAdapter(axios) # // mock success request mock.onGet('/success').reply 200, msg: 'success' # // mock error request mock.onGet('/error').reply 500, msg: 'failure' # // Login mock.onPost('/login').reply (config) => {username, password} = JSON.parse(config.data); new Promise (resolve, reject) => user = null; setTimeout => hasUser = LoginUsers.some (u) => if u.username is username && u.password is password user = JSON.parse(JSON.stringify(u)); user.password = undefined; return true; if hasUser resolve([200, { code: 200, msg: 'success', user }]); else resolve([200, { code: 500, msg: 'Incorrect username or password' }]); , 1000 # //获取用户列表 mock.onGet('/user/list').reply (config) => {name} = config.params; mockUsers = _Users.filter (user) => if name && user.name.indexOf(name) == -1 return false; return true; return new Promise (resolve, reject) => setTimeout => resolve([200, users: mockUsers ]); , 1000 # //获取用户列表(分页) mock.onGet('/user/listpage').reply (config) => console.log("in MOCK -user-listPgae!!---->>"); {page, name} = config.params; mockUsers = _Users.filter (user) => if name && user.name.indexOf(name) == -1 return false; return true; total = mockUsers.length; mockUsers = mockUsers.filter((u, index) => index < 20 * page && index >= 20 * (page - 1)); return new Promise (resolve, reject) => setTimeout => resolve [200, total: total, users: mockUsers ] , 1000 mock.onGet('/user/remove').reply (config) => { id } = config.params; _Users = _Users.filter (u) => u.id isnt id return new Promise (resolve, reject) => setTimeout => resolve [200, code: 200, msg: '删除成功' ] , 500 # //批量删除用户 mock.onGet('/user/batchremove').reply (config) => { ids } = config.params; ids = ids.split(','); _Users = _Users.filter((u) => !ids.includes(u.id)); return new Promise (resolve, reject) => setTimeout => resolve [200, code: 200, msg: '删除成功' ] , 500 # //编辑用户 mock.onGet('/user/edit').reply (config) => { id, name, addr, age, birth, sex } = config.params; _Users.some u => if u.id is id u.name = name; u.addr = addr; u.age = age; u.birth = birth; u.sex = sex; return true; return new Promise (resolve, reject) => setTimeout => resolve [200, code: 200, msg: '编辑成功' ] , 500 # //新增用户 mock.onGet('/user/add').reply (config) => { name, addr, age, birth, sex } = config.params; _Users.push name: name, addr: addr, age: age, birth: birth, sex: sex return new Promise (resolve, reject) => setTimeout => resolve [200, code: 200, msg: '新增成功' ] , 500 `export default export_default;`
187593
import axios from 'axios'; import MockAdapter from 'axios-mock-adapter'; import { LoginUsers, Users } from './data/user'; _Users = Users; export_default = # /** # * mock bootstrap # */ bootstrap: -> mock = new MockAdapter(axios) # // mock success request mock.onGet('/success').reply 200, msg: 'success' # // mock error request mock.onGet('/error').reply 500, msg: 'failure' # // Login mock.onPost('/login').reply (config) => {username, password} = JSON.parse(config.data); new Promise (resolve, reject) => user = null; setTimeout => hasUser = LoginUsers.some (u) => if u.username is username && u.password is <PASSWORD> user = JSON.parse(JSON.stringify(u)); user.password = <PASSWORD>; return true; if hasUser resolve([200, { code: 200, msg: 'success', user }]); else resolve([200, { code: 500, msg: 'Incorrect username or password' }]); , 1000 # //获取用户列表 mock.onGet('/user/list').reply (config) => {name} = config.params; mockUsers = _Users.filter (user) => if name && user.name.indexOf(name) == -1 return false; return true; return new Promise (resolve, reject) => setTimeout => resolve([200, users: mockUsers ]); , 1000 # //获取用户列表(分页) mock.onGet('/user/listpage').reply (config) => console.log("in MOCK -user-listPgae!!---->>"); {page, name} = config.params; mockUsers = _Users.filter (user) => if name && user.name.indexOf(name) == -1 return false; return true; total = mockUsers.length; mockUsers = mockUsers.filter((u, index) => index < 20 * page && index >= 20 * (page - 1)); return new Promise (resolve, reject) => setTimeout => resolve [200, total: total, users: mockUsers ] , 1000 mock.onGet('/user/remove').reply (config) => { id } = config.params; _Users = _Users.filter (u) => u.id isnt id return new Promise (resolve, reject) => setTimeout => resolve [200, code: 200, msg: '删除成功' ] , 500 # //批量删除用户 mock.onGet('/user/batchremove').reply (config) => { ids } = config.params; ids = ids.split(','); _Users = _Users.filter((u) => !ids.includes(u.id)); return new Promise (resolve, reject) => setTimeout => resolve [200, code: 200, msg: '删除成功' ] , 500 # //编辑用户 mock.onGet('/user/edit').reply (config) => { id, name, addr, age, birth, sex } = config.params; _Users.some u => if u.id is id u.name = <NAME>; u.addr = addr; u.age = age; u.birth = birth; u.sex = sex; return true; return new Promise (resolve, reject) => setTimeout => resolve [200, code: 200, msg: '编辑成功' ] , 500 # //新增用户 mock.onGet('/user/add').reply (config) => { name, addr, age, birth, sex } = config.params; _Users.push name: name, addr: addr, age: age, birth: birth, sex: sex return new Promise (resolve, reject) => setTimeout => resolve [200, code: 200, msg: '新增成功' ] , 500 `export default export_default;`
true
import axios from 'axios'; import MockAdapter from 'axios-mock-adapter'; import { LoginUsers, Users } from './data/user'; _Users = Users; export_default = # /** # * mock bootstrap # */ bootstrap: -> mock = new MockAdapter(axios) # // mock success request mock.onGet('/success').reply 200, msg: 'success' # // mock error request mock.onGet('/error').reply 500, msg: 'failure' # // Login mock.onPost('/login').reply (config) => {username, password} = JSON.parse(config.data); new Promise (resolve, reject) => user = null; setTimeout => hasUser = LoginUsers.some (u) => if u.username is username && u.password is PI:PASSWORD:<PASSWORD>END_PI user = JSON.parse(JSON.stringify(u)); user.password = PI:PASSWORD:<PASSWORD>END_PI; return true; if hasUser resolve([200, { code: 200, msg: 'success', user }]); else resolve([200, { code: 500, msg: 'Incorrect username or password' }]); , 1000 # //获取用户列表 mock.onGet('/user/list').reply (config) => {name} = config.params; mockUsers = _Users.filter (user) => if name && user.name.indexOf(name) == -1 return false; return true; return new Promise (resolve, reject) => setTimeout => resolve([200, users: mockUsers ]); , 1000 # //获取用户列表(分页) mock.onGet('/user/listpage').reply (config) => console.log("in MOCK -user-listPgae!!---->>"); {page, name} = config.params; mockUsers = _Users.filter (user) => if name && user.name.indexOf(name) == -1 return false; return true; total = mockUsers.length; mockUsers = mockUsers.filter((u, index) => index < 20 * page && index >= 20 * (page - 1)); return new Promise (resolve, reject) => setTimeout => resolve [200, total: total, users: mockUsers ] , 1000 mock.onGet('/user/remove').reply (config) => { id } = config.params; _Users = _Users.filter (u) => u.id isnt id return new Promise (resolve, reject) => setTimeout => resolve [200, code: 200, msg: '删除成功' ] , 500 # //批量删除用户 mock.onGet('/user/batchremove').reply (config) => { ids } = config.params; ids = ids.split(','); _Users = _Users.filter((u) => !ids.includes(u.id)); return new Promise (resolve, reject) => setTimeout => resolve [200, code: 200, msg: '删除成功' ] , 500 # //编辑用户 mock.onGet('/user/edit').reply (config) => { id, name, addr, age, birth, sex } = config.params; _Users.some u => if u.id is id u.name = PI:NAME:<NAME>END_PI; u.addr = addr; u.age = age; u.birth = birth; u.sex = sex; return true; return new Promise (resolve, reject) => setTimeout => resolve [200, code: 200, msg: '编辑成功' ] , 500 # //新增用户 mock.onGet('/user/add').reply (config) => { name, addr, age, birth, sex } = config.params; _Users.push name: name, addr: addr, age: age, birth: birth, sex: sex return new Promise (resolve, reject) => setTimeout => resolve [200, code: 200, msg: '新增成功' ] , 500 `export default export_default;`
[ { "context": "\n uuid: 'new-uuid'\n token: 'new-token'\n\n callback null, response\n\n setTimeo", "end": 1873, "score": 0.6197465658187866, "start": 1864, "tag": "PASSWORD", "value": "new-token" } ]
test/auto-register-spec.coffee
canfer/meshblu-core-protocol-adapter-socket.io
0
_ = require 'lodash' meshblu = require 'meshblu' Redis = require 'ioredis' RedisNS = require '@octoblu/redis-ns' Server = require '../src/server' UUID = require 'uuid' { JobManagerResponder } = require 'meshblu-core-job-manager' describe 'Auto Register', -> beforeEach -> queueId = UUID.v4() @namespace = 'ns' @redisUri = 'redis://localhost' @requestQueueName = "test:request:queue:#{queueId}" @responseQueueName = "test:response:queue:#{queueId}" beforeEach (done) -> @workerFunc = (@request, callback) => @jobManagerDo @request, callback @jobManager = new JobManagerResponder { @redisUri @namespace @workerFunc maxConnections: 1 queueTimeoutSeconds: 1 jobTimeoutSeconds: 1 jobLogSampleRate: 1 requestQueueName: @requestQueueName responseQueueName: @responseQueueName } @jobManager.start done beforeEach -> @jobManager.do = (@jobManagerDo) => afterEach -> @jobManager.stop() beforeEach (done) -> @sut = new Server { namespace: @namespace port: 0xcafe jobTimeoutSeconds: 10 jobLogRedisUri: @redisUri redisUri: @redisUri cacheRedisUri: @redisUri firehoseRedisUri: @redisUri jobLogQueue: 'jobz' jobLogSampleRate: 0 maxConnections: 10 @requestQueueName @responseQueueName } @sut.run done afterEach -> @sut.stop() describe 'when an unauthenticated client connects', -> @timeout 5000 beforeEach (done) -> doneOnce = _.once done @conn = meshblu.createConnection({server: 'localhost', port: 0xcafe}) @jobManager.do (@request, callback) => response = metadata: responseId: @request.metadata.responseId code: 204 data: uuid: 'new-uuid' token: 'new-token' callback null, response setTimeout doneOnce, 4000 @conn.once 'ready', (@device) => doneOnce() afterEach (done) -> @conn.close done it 'should create a device', -> expect(@device.uuid).to.exist expect(@device.token).to.exist
31946
_ = require 'lodash' meshblu = require 'meshblu' Redis = require 'ioredis' RedisNS = require '@octoblu/redis-ns' Server = require '../src/server' UUID = require 'uuid' { JobManagerResponder } = require 'meshblu-core-job-manager' describe 'Auto Register', -> beforeEach -> queueId = UUID.v4() @namespace = 'ns' @redisUri = 'redis://localhost' @requestQueueName = "test:request:queue:#{queueId}" @responseQueueName = "test:response:queue:#{queueId}" beforeEach (done) -> @workerFunc = (@request, callback) => @jobManagerDo @request, callback @jobManager = new JobManagerResponder { @redisUri @namespace @workerFunc maxConnections: 1 queueTimeoutSeconds: 1 jobTimeoutSeconds: 1 jobLogSampleRate: 1 requestQueueName: @requestQueueName responseQueueName: @responseQueueName } @jobManager.start done beforeEach -> @jobManager.do = (@jobManagerDo) => afterEach -> @jobManager.stop() beforeEach (done) -> @sut = new Server { namespace: @namespace port: 0xcafe jobTimeoutSeconds: 10 jobLogRedisUri: @redisUri redisUri: @redisUri cacheRedisUri: @redisUri firehoseRedisUri: @redisUri jobLogQueue: 'jobz' jobLogSampleRate: 0 maxConnections: 10 @requestQueueName @responseQueueName } @sut.run done afterEach -> @sut.stop() describe 'when an unauthenticated client connects', -> @timeout 5000 beforeEach (done) -> doneOnce = _.once done @conn = meshblu.createConnection({server: 'localhost', port: 0xcafe}) @jobManager.do (@request, callback) => response = metadata: responseId: @request.metadata.responseId code: 204 data: uuid: 'new-uuid' token: '<PASSWORD>' callback null, response setTimeout doneOnce, 4000 @conn.once 'ready', (@device) => doneOnce() afterEach (done) -> @conn.close done it 'should create a device', -> expect(@device.uuid).to.exist expect(@device.token).to.exist
true
_ = require 'lodash' meshblu = require 'meshblu' Redis = require 'ioredis' RedisNS = require '@octoblu/redis-ns' Server = require '../src/server' UUID = require 'uuid' { JobManagerResponder } = require 'meshblu-core-job-manager' describe 'Auto Register', -> beforeEach -> queueId = UUID.v4() @namespace = 'ns' @redisUri = 'redis://localhost' @requestQueueName = "test:request:queue:#{queueId}" @responseQueueName = "test:response:queue:#{queueId}" beforeEach (done) -> @workerFunc = (@request, callback) => @jobManagerDo @request, callback @jobManager = new JobManagerResponder { @redisUri @namespace @workerFunc maxConnections: 1 queueTimeoutSeconds: 1 jobTimeoutSeconds: 1 jobLogSampleRate: 1 requestQueueName: @requestQueueName responseQueueName: @responseQueueName } @jobManager.start done beforeEach -> @jobManager.do = (@jobManagerDo) => afterEach -> @jobManager.stop() beforeEach (done) -> @sut = new Server { namespace: @namespace port: 0xcafe jobTimeoutSeconds: 10 jobLogRedisUri: @redisUri redisUri: @redisUri cacheRedisUri: @redisUri firehoseRedisUri: @redisUri jobLogQueue: 'jobz' jobLogSampleRate: 0 maxConnections: 10 @requestQueueName @responseQueueName } @sut.run done afterEach -> @sut.stop() describe 'when an unauthenticated client connects', -> @timeout 5000 beforeEach (done) -> doneOnce = _.once done @conn = meshblu.createConnection({server: 'localhost', port: 0xcafe}) @jobManager.do (@request, callback) => response = metadata: responseId: @request.metadata.responseId code: 204 data: uuid: 'new-uuid' token: 'PI:PASSWORD:<PASSWORD>END_PI' callback null, response setTimeout doneOnce, 4000 @conn.once 'ready', (@device) => doneOnce() afterEach (done) -> @conn.close done it 'should create a device', -> expect(@device.uuid).to.exist expect(@device.token).to.exist
[ { "context": "0, put: 0, delete: 0\n }\n {\n ###\n Author: ec.huyinghuan@gmail.com\n Date: 2015.07.06\n Describe: 项目中gitlab的", "end": 2646, "score": 0.9999335408210754, "start": 2623, "tag": "EMAIL", "value": "ec.huyinghuan@gmail.com" } ]
src/config/routers/project.coffee
kiteam/kiteam
0
module.exports = [ { path: 'project/:project_id(\\d+)/member' biz: 'project' methods: delete: 'removeMember', put: 'addMember', post: 'addMember', get: 'getMembers' allowGuest: ['get'] }, # { # #查看某个项目下的所有commit # #提交commit,用于git或svn提交commit时,自动获取commit并分析,需要指定project_id # path: 'project/:project_id(\\d+)/git/commit' # biz: 'commit' # methods: post: 'postCommit', get: 0, delete: 0, patch: 0, put: 0 # }, # { # #更改issue的所有者及计划 # path: 'project/:project_id(\\d+)/issue/:issue_id(\\d+)/plan' # biz: 'issue' # suffix: false, # methods: put: 'changeOwnerOrSchedule', get: 0, delete: 0, patch: 0, post: 0 # }, #0 #doing @功能 增加改变owner和计划完成时间的接口 { #获取一个项目的所有素材 path: 'project/:project_id(\\d+)/assets' biz: 'asset' methods: post: '{uploadFile}', delete: 'remove', patch: 0, put: 0 allowGuest: ['get'] }, { #获取一个项目的所有素材 path: 'project/:project_id(\\d+)/webhook' biz: 'webhook' }, { #获取素材的缩略图 path: 'project/:project_id(\\d+)/asset/:asset_id/thumbnail' biz: 'asset' methods: get: '{thumbnail}', delete: 0, patch: 0, put: 0, post: 0 }, { #获取素材的文件 path: 'project/:project_id(\\d+)/asset/:asset_id/read' biz: 'asset' methods: get: '{readAsset}', delete: 0, patch: 0, put: 0, post: 0 }, { ##展开zip的素材 path: 'project/:project_id(\\d+)/assets/:asset_id/unwind' biz: 'asset' suffix: false methods: get: 'unwind', post: 0, delete: 0, patch: 0, put: 0 }, { #issue相关 path: 'project/:project_id(\\d+)/member/invite' biz: 'invite' }, { #获取项目的统计情况 path: 'project/:project_id(\\d+)/stat' biz: 'issue' methods: get: 'statistic', post: 0, delete: 0, patch: 0, put: 0 }, { path: 'project/:project_id(\\d+)/discussion' biz: 'issue' methods: put: 0, post: 0, delete: 0, patch: 0, get: 'getDiscussion' allowGuest: ['get'] } { #项目分类 path: 'project/:project_id/category' biz: 'issue_category' allowGuest: ['get'] }, { #项目版本 path: 'project/:project_id/version' biz: 'version' allowGuest: ['get'] } { #上传文件,用于评论中的附件 path: 'project/:project_id/attachment/(:filename)?' biz: 'attachment' suffix: false, methods: post: '{uploadFile}', get: '{readFile}' }, { #路由地址 path: 'project' allowGuest: ['get'] }, { #收藏项目 path: 'project/:project_id/favorite' biz: 'favorite' suffix: false methods: get: 0, patch: 0, put: 0 } { path: 'project/git-map' biz: 'git_map' data: type: 'project' methods: post: 0, put: 0, delete: 0 } { ### Author: ec.huyinghuan@gmail.com Date: 2015.07.06 Describe: 项目中gitlab的增删查 ### path: 'project/:project_id/gitlab' biz: 'git_map' data: type: 'project' methods: get: 'getAllGitsInProject', put: 'addGitToProject', post: 'createGitForProject', delete: 'delOne' allowGuest: ['get'] } { #fork项目 path: 'project/:project_id/gitlab/:gitlab_id/fork' biz: 'git_map' data: type: 'project' methods: get: 'fork', put: 0, delete: 0 } { #获取项目中所有自己的git仓库地址 path: 'project/:project_id/owned-gits' biz: 'git_map' data: type: 'project' methods: get: 'getProjectOwnedGitsList', post: 0, put: 0, delete: 0 } ]
200504
module.exports = [ { path: 'project/:project_id(\\d+)/member' biz: 'project' methods: delete: 'removeMember', put: 'addMember', post: 'addMember', get: 'getMembers' allowGuest: ['get'] }, # { # #查看某个项目下的所有commit # #提交commit,用于git或svn提交commit时,自动获取commit并分析,需要指定project_id # path: 'project/:project_id(\\d+)/git/commit' # biz: 'commit' # methods: post: 'postCommit', get: 0, delete: 0, patch: 0, put: 0 # }, # { # #更改issue的所有者及计划 # path: 'project/:project_id(\\d+)/issue/:issue_id(\\d+)/plan' # biz: 'issue' # suffix: false, # methods: put: 'changeOwnerOrSchedule', get: 0, delete: 0, patch: 0, post: 0 # }, #0 #doing @功能 增加改变owner和计划完成时间的接口 { #获取一个项目的所有素材 path: 'project/:project_id(\\d+)/assets' biz: 'asset' methods: post: '{uploadFile}', delete: 'remove', patch: 0, put: 0 allowGuest: ['get'] }, { #获取一个项目的所有素材 path: 'project/:project_id(\\d+)/webhook' biz: 'webhook' }, { #获取素材的缩略图 path: 'project/:project_id(\\d+)/asset/:asset_id/thumbnail' biz: 'asset' methods: get: '{thumbnail}', delete: 0, patch: 0, put: 0, post: 0 }, { #获取素材的文件 path: 'project/:project_id(\\d+)/asset/:asset_id/read' biz: 'asset' methods: get: '{readAsset}', delete: 0, patch: 0, put: 0, post: 0 }, { ##展开zip的素材 path: 'project/:project_id(\\d+)/assets/:asset_id/unwind' biz: 'asset' suffix: false methods: get: 'unwind', post: 0, delete: 0, patch: 0, put: 0 }, { #issue相关 path: 'project/:project_id(\\d+)/member/invite' biz: 'invite' }, { #获取项目的统计情况 path: 'project/:project_id(\\d+)/stat' biz: 'issue' methods: get: 'statistic', post: 0, delete: 0, patch: 0, put: 0 }, { path: 'project/:project_id(\\d+)/discussion' biz: 'issue' methods: put: 0, post: 0, delete: 0, patch: 0, get: 'getDiscussion' allowGuest: ['get'] } { #项目分类 path: 'project/:project_id/category' biz: 'issue_category' allowGuest: ['get'] }, { #项目版本 path: 'project/:project_id/version' biz: 'version' allowGuest: ['get'] } { #上传文件,用于评论中的附件 path: 'project/:project_id/attachment/(:filename)?' biz: 'attachment' suffix: false, methods: post: '{uploadFile}', get: '{readFile}' }, { #路由地址 path: 'project' allowGuest: ['get'] }, { #收藏项目 path: 'project/:project_id/favorite' biz: 'favorite' suffix: false methods: get: 0, patch: 0, put: 0 } { path: 'project/git-map' biz: 'git_map' data: type: 'project' methods: post: 0, put: 0, delete: 0 } { ### Author: <EMAIL> Date: 2015.07.06 Describe: 项目中gitlab的增删查 ### path: 'project/:project_id/gitlab' biz: 'git_map' data: type: 'project' methods: get: 'getAllGitsInProject', put: 'addGitToProject', post: 'createGitForProject', delete: 'delOne' allowGuest: ['get'] } { #fork项目 path: 'project/:project_id/gitlab/:gitlab_id/fork' biz: 'git_map' data: type: 'project' methods: get: 'fork', put: 0, delete: 0 } { #获取项目中所有自己的git仓库地址 path: 'project/:project_id/owned-gits' biz: 'git_map' data: type: 'project' methods: get: 'getProjectOwnedGitsList', post: 0, put: 0, delete: 0 } ]
true
module.exports = [ { path: 'project/:project_id(\\d+)/member' biz: 'project' methods: delete: 'removeMember', put: 'addMember', post: 'addMember', get: 'getMembers' allowGuest: ['get'] }, # { # #查看某个项目下的所有commit # #提交commit,用于git或svn提交commit时,自动获取commit并分析,需要指定project_id # path: 'project/:project_id(\\d+)/git/commit' # biz: 'commit' # methods: post: 'postCommit', get: 0, delete: 0, patch: 0, put: 0 # }, # { # #更改issue的所有者及计划 # path: 'project/:project_id(\\d+)/issue/:issue_id(\\d+)/plan' # biz: 'issue' # suffix: false, # methods: put: 'changeOwnerOrSchedule', get: 0, delete: 0, patch: 0, post: 0 # }, #0 #doing @功能 增加改变owner和计划完成时间的接口 { #获取一个项目的所有素材 path: 'project/:project_id(\\d+)/assets' biz: 'asset' methods: post: '{uploadFile}', delete: 'remove', patch: 0, put: 0 allowGuest: ['get'] }, { #获取一个项目的所有素材 path: 'project/:project_id(\\d+)/webhook' biz: 'webhook' }, { #获取素材的缩略图 path: 'project/:project_id(\\d+)/asset/:asset_id/thumbnail' biz: 'asset' methods: get: '{thumbnail}', delete: 0, patch: 0, put: 0, post: 0 }, { #获取素材的文件 path: 'project/:project_id(\\d+)/asset/:asset_id/read' biz: 'asset' methods: get: '{readAsset}', delete: 0, patch: 0, put: 0, post: 0 }, { ##展开zip的素材 path: 'project/:project_id(\\d+)/assets/:asset_id/unwind' biz: 'asset' suffix: false methods: get: 'unwind', post: 0, delete: 0, patch: 0, put: 0 }, { #issue相关 path: 'project/:project_id(\\d+)/member/invite' biz: 'invite' }, { #获取项目的统计情况 path: 'project/:project_id(\\d+)/stat' biz: 'issue' methods: get: 'statistic', post: 0, delete: 0, patch: 0, put: 0 }, { path: 'project/:project_id(\\d+)/discussion' biz: 'issue' methods: put: 0, post: 0, delete: 0, patch: 0, get: 'getDiscussion' allowGuest: ['get'] } { #项目分类 path: 'project/:project_id/category' biz: 'issue_category' allowGuest: ['get'] }, { #项目版本 path: 'project/:project_id/version' biz: 'version' allowGuest: ['get'] } { #上传文件,用于评论中的附件 path: 'project/:project_id/attachment/(:filename)?' biz: 'attachment' suffix: false, methods: post: '{uploadFile}', get: '{readFile}' }, { #路由地址 path: 'project' allowGuest: ['get'] }, { #收藏项目 path: 'project/:project_id/favorite' biz: 'favorite' suffix: false methods: get: 0, patch: 0, put: 0 } { path: 'project/git-map' biz: 'git_map' data: type: 'project' methods: post: 0, put: 0, delete: 0 } { ### Author: PI:EMAIL:<EMAIL>END_PI Date: 2015.07.06 Describe: 项目中gitlab的增删查 ### path: 'project/:project_id/gitlab' biz: 'git_map' data: type: 'project' methods: get: 'getAllGitsInProject', put: 'addGitToProject', post: 'createGitForProject', delete: 'delOne' allowGuest: ['get'] } { #fork项目 path: 'project/:project_id/gitlab/:gitlab_id/fork' biz: 'git_map' data: type: 'project' methods: get: 'fork', put: 0, delete: 0 } { #获取项目中所有自己的git仓库地址 path: 'project/:project_id/owned-gits' biz: 'git_map' data: type: 'project' methods: get: 'getProjectOwnedGitsList', post: 0, put: 0, delete: 0 } ]
[ { "context": " super(options)\n @outKey = options.outKey or 'account_id'\n\n initialize: (options) ->\n super(options)\n ", "end": 413, "score": 0.9852046966552734, "start": 403, "tag": "KEY", "value": "account_id" } ]
app/scripts/views/steps/accountselector-step.coffee
toggl/pipes-ui
12
class pipes.steps.AccountSelectorStep extends pipes.steps.DataPollStep ### An all-in-one account selector step. Polls accounts from the given url, displayes them in a list and stores the selected account's id in @sharedData[@outKey] ### listTemplate: templates['steps/account-selector.html'] url: null constructor: (options = {}) -> super(options) @outKey = options.outKey or 'account_id' initialize: (options) -> super(options) @url = @view.model.collection.integration.accountsUrl() successCallback: (response, step) -> @ajaxEnd() if not response?.accounts?.length? @trigger 'error', this, "Did not receive any accounts" if response.accounts.length > 1 @displayList response.accounts return false # Don't auto-end() else @selectAccount response.accounts[0].id onEnd: -> @getContainer().empty().off '.account-selection' displayList: (accounts) -> @getContainer().html @listTemplate accounts: accounts @getContainer().on 'click.account-selection', '.button.select-account', (e) => $(e.currentTarget).attr 'disabled', true @selectAccount $(e.currentTarget).data('id') selectAccount: (@accountId) -> @sharedData[@outKey] = @accountId @end()
116749
class pipes.steps.AccountSelectorStep extends pipes.steps.DataPollStep ### An all-in-one account selector step. Polls accounts from the given url, displayes them in a list and stores the selected account's id in @sharedData[@outKey] ### listTemplate: templates['steps/account-selector.html'] url: null constructor: (options = {}) -> super(options) @outKey = options.outKey or '<KEY>' initialize: (options) -> super(options) @url = @view.model.collection.integration.accountsUrl() successCallback: (response, step) -> @ajaxEnd() if not response?.accounts?.length? @trigger 'error', this, "Did not receive any accounts" if response.accounts.length > 1 @displayList response.accounts return false # Don't auto-end() else @selectAccount response.accounts[0].id onEnd: -> @getContainer().empty().off '.account-selection' displayList: (accounts) -> @getContainer().html @listTemplate accounts: accounts @getContainer().on 'click.account-selection', '.button.select-account', (e) => $(e.currentTarget).attr 'disabled', true @selectAccount $(e.currentTarget).data('id') selectAccount: (@accountId) -> @sharedData[@outKey] = @accountId @end()
true
class pipes.steps.AccountSelectorStep extends pipes.steps.DataPollStep ### An all-in-one account selector step. Polls accounts from the given url, displayes them in a list and stores the selected account's id in @sharedData[@outKey] ### listTemplate: templates['steps/account-selector.html'] url: null constructor: (options = {}) -> super(options) @outKey = options.outKey or 'PI:KEY:<KEY>END_PI' initialize: (options) -> super(options) @url = @view.model.collection.integration.accountsUrl() successCallback: (response, step) -> @ajaxEnd() if not response?.accounts?.length? @trigger 'error', this, "Did not receive any accounts" if response.accounts.length > 1 @displayList response.accounts return false # Don't auto-end() else @selectAccount response.accounts[0].id onEnd: -> @getContainer().empty().off '.account-selection' displayList: (accounts) -> @getContainer().html @listTemplate accounts: accounts @getContainer().on 'click.account-selection', '.button.select-account', (e) => $(e.currentTarget).attr 'disabled', true @selectAccount $(e.currentTarget).data('id') selectAccount: (@accountId) -> @sharedData[@outKey] = @accountId @end()
[ { "context": "subtotal: 999,\n total: 999,\n customer: 'cus_5Fz9MVWP2bDPGV',\n object: 'invoice',\n attempted: true,", "end": 520, "score": 0.5040715932846069, "start": 502, "tag": "USERNAME", "value": "cus_5Fz9MVWP2bDPGV" }, { "context": "76967,\n status: 'c...
test/server/functional/subscription.spec.coffee
rishiloyola/codecombat
1
config = require '../../../server_config' require '../common' # sample data that comes in through the webhook when you subscribe invoiceChargeSampleEvent = { id: 'evt_155TBeKaReE7xLUdrKM72O5R', created: 1417574898, livemode: false, type: 'invoice.payment_succeeded', data: { object: { date: 1417574897, id: 'in_155TBdKaReE7xLUdv8z8ipWl', period_start: 1417574897, period_end: 1417574897, lines: {}, subtotal: 999, total: 999, customer: 'cus_5Fz9MVWP2bDPGV', object: 'invoice', attempted: true, closed: true, forgiven: false, paid: true, livemode: false, attempt_count: 1, amount_due: 999, currency: 'usd', starting_balance: 0, ending_balance: 0, next_payment_attempt: null, webhooks_delivered_at: null, charge: 'ch_155TBdKaReE7xLUdRU0WcMzR', discount: null, application_fee: null, subscription: 'sub_5Fz99gXrBtreNe', metadata: {}, statement_description: null, description: null, receipt_number: null } }, object: 'event', pending_webhooks: 1, request: 'iar_5Fz9c4BZJyNNsM', api_version: '2014-11-05' } customerSubscriptionDeletedSampleEvent = { id: 'evt_155Tj4KaReE7xLUdpoMx0UaA', created: 1417576970, livemode: false, type: 'customer.subscription.deleted', data: { object: { id: 'sub_5FziOkege03vT7', plan: [Object], object: 'subscription', start: 1417576967, status: 'canceled', customer: 'cus_5Fzi54gMvGG9Px', cancel_at_period_end: true, current_period_start: 1417576967, current_period_end: 1420255367, ended_at: 1417576970, trial_start: null, trial_end: null, canceled_at: 1417576970, quantity: 1, application_fee_percent: null, discount: null, metadata: {} } }, object: 'event', pending_webhooks: 1, request: 'iar_5FziYQJ4oQdL6w', api_version: '2014-11-05' } describe '/db/user, editing stripe property', -> stripe = require('stripe')(config.stripe.secretKey) userURL = getURL('/db/user') webhookURL = getURL('/stripe/webhook') headers = {'X-Change-Plan': 'true'} it 'clears the db first', (done) -> clearModels [User, Payment], (err) -> throw err if err done() it 'denies anonymous users trying to subscribe', (done) -> request.get getURL('/auth/whoami'), (err, res, body) -> body = JSON.parse(body) body.stripe = { planID: 'basic', token: '12345' } request.put {uri: userURL, json: body, headers: headers}, (err, res, body) -> expect(res.statusCode).toBe 403 done() #- shared data between tests joeData = null firstSubscriptionID = null it 'returns client error when a token fails to charge', (done) -> stripe.tokens.create { card: { number: '4000000000000002', exp_month: 12, exp_year: 2020, cvc: '123' } }, (err, token) -> stripeTokenID = token.id loginJoe (joe) -> joeData = joe.toObject() joeData.stripe = { token: stripeTokenID planID: 'basic' } request.put {uri: userURL, json: joeData, headers: headers }, (err, res, body) -> expect(res.statusCode).toBe(402) done() it 'creates a subscription when you put a token and plan', (done) -> stripe.tokens.create { card: { number: '4242424242424242', exp_month: 12, exp_year: 2020, cvc: '123' } }, (err, token) -> stripeTokenID = token.id loginJoe (joe) -> joeData = joe.toObject() joeData.stripe = { token: stripeTokenID planID: 'basic' } request.put {uri: userURL, json: joeData, headers: headers }, (err, res, body) -> joeData = body expect(res.statusCode).toBe(200) expect(joeData.purchased.gems).toBe(3500) expect(joeData.stripe.customerID).toBeDefined() expect(firstSubscriptionID = joeData.stripe.subscriptionID).toBeDefined() expect(joeData.stripe.planID).toBe('basic') expect(joeData.stripe.token).toBeUndefined() done() it 'records a payment through the webhook', (done) -> # Don't even want to think about hooking in tests to webhooks, so... put in some data manually stripe.invoices.list {customer: joeData.stripe.customerID}, (err, invoices) -> expect(invoices.data.length).toBe(1) event = _.cloneDeep(invoiceChargeSampleEvent) event.data.object = invoices.data[0] request.post {uri: webhookURL, json: event}, (err, res, body) -> expect(res.statusCode).toBe(201) Payment.find {}, (err, payments) -> expect(payments.length).toBe(1) User.findById joeData._id, (err, user) -> expect(user.get('purchased').gems).toBe(3500) done() it 'schedules the stripe subscription to be cancelled when stripe.planID is removed from the user', (done) -> delete joeData.stripe.planID request.put {uri: userURL, json: joeData, headers: headers }, (err, res, body) -> joeData = body expect(res.statusCode).toBe(200) expect(joeData.stripe.subscriptionID).toBeDefined() expect(joeData.stripe.planID).toBeUndefined() expect(joeData.stripe.customerID).toBeDefined() stripe.customers.retrieve joeData.stripe.customerID, (err, customer) -> expect(customer.subscriptions.data.length).toBe(1) expect(customer.subscriptions.data[0].cancel_at_period_end).toBe(true) done() it 'allows you to sign up again using the same customer ID as before, no token necessary', (done) -> joeData.stripe.planID = 'basic' request.put {uri: userURL, json: joeData, headers: headers }, (err, res, body) -> joeData = body expect(res.statusCode).toBe(200) expect(joeData.stripe.customerID).toBeDefined() expect(joeData.stripe.subscriptionID).toBeDefined() expect(joeData.stripe.subscriptionID).not.toBe(firstSubscriptionID) expect(joeData.stripe.planID).toBe('basic') done() it 'will not have immediately created new payments when signing back up from a cancelled subscription', (done) -> stripe.invoices.list {customer: joeData.stripe.customerID}, (err, invoices) -> expect(invoices.data.length).toBe(2) expect(invoices.data[0].total).toBe(0) event = _.cloneDeep(invoiceChargeSampleEvent) event.data.object = invoices.data[0] request.post {uri: webhookURL, json: event}, (err, res, body) -> expect(res.statusCode).toBe(200) Payment.find {}, (err, payments) -> expect(payments.length).toBe(1) User.findById joeData._id, (err, user) -> expect(user.get('purchased').gems).toBe(3500) done() it 'deletes the subscription from the user object when an event about it comes through the webhook', (done) -> stripe.customers.retrieveSubscription joeData.stripe.customerID, joeData.stripe.subscriptionID, (err, subscription) -> event = _.cloneDeep(customerSubscriptionDeletedSampleEvent) event.data.object = subscription request.post {uri: webhookURL, json: event}, (err, res, body) -> User.findById joeData._id, (err, user) -> expect(user.get('purchased').gems).toBe(3500) expect(user.get('stripe').subscriptionID).toBeUndefined() expect(user.get('stripe').planID).toBeUndefined() done() it "updates the customer's email when you change the user's email", (done) -> joeData.email = 'newEmail@gmail.com' request.put {uri: userURL, json: joeData, headers: headers }, (err, res, body) -> f = -> stripe.customers.retrieve joeData.stripe.customerID, (err, customer) -> expect(customer.email).toBe('newEmail@gmail.com') done() setTimeout(f, 500) # bit of a race condition here, response returns before stripe has been updated
67863
config = require '../../../server_config' require '../common' # sample data that comes in through the webhook when you subscribe invoiceChargeSampleEvent = { id: 'evt_155TBeKaReE7xLUdrKM72O5R', created: 1417574898, livemode: false, type: 'invoice.payment_succeeded', data: { object: { date: 1417574897, id: 'in_155TBdKaReE7xLUdv8z8ipWl', period_start: 1417574897, period_end: 1417574897, lines: {}, subtotal: 999, total: 999, customer: 'cus_5Fz9MVWP2bDPGV', object: 'invoice', attempted: true, closed: true, forgiven: false, paid: true, livemode: false, attempt_count: 1, amount_due: 999, currency: 'usd', starting_balance: 0, ending_balance: 0, next_payment_attempt: null, webhooks_delivered_at: null, charge: 'ch_155TBdKaReE7xLUdRU0WcMzR', discount: null, application_fee: null, subscription: 'sub_5Fz99gXrBtreNe', metadata: {}, statement_description: null, description: null, receipt_number: null } }, object: 'event', pending_webhooks: 1, request: 'iar_5Fz9c4BZJyNNsM', api_version: '2014-11-05' } customerSubscriptionDeletedSampleEvent = { id: 'evt_155Tj4KaReE7xLUdpoMx0UaA', created: 1417576970, livemode: false, type: 'customer.subscription.deleted', data: { object: { id: 'sub_5FziOkege03vT7', plan: [Object], object: 'subscription', start: 1417576967, status: 'canceled', customer: '<KEY>_<KEY>Fzi54gMvGG<KEY>', cancel_at_period_end: true, current_period_start: 1417576967, current_period_end: 1420255367, ended_at: 1417576970, trial_start: null, trial_end: null, canceled_at: 1417576970, quantity: 1, application_fee_percent: null, discount: null, metadata: {} } }, object: 'event', pending_webhooks: 1, request: 'iar_5FziYQJ4oQdL6w', api_version: '2014-11-05' } describe '/db/user, editing stripe property', -> stripe = require('stripe')(config.stripe.secretKey) userURL = getURL('/db/user') webhookURL = getURL('/stripe/webhook') headers = {'X-Change-Plan': 'true'} it 'clears the db first', (done) -> clearModels [User, Payment], (err) -> throw err if err done() it 'denies anonymous users trying to subscribe', (done) -> request.get getURL('/auth/whoami'), (err, res, body) -> body = JSON.parse(body) body.stripe = { planID: 'basic', token: '<PASSWORD>' } request.put {uri: userURL, json: body, headers: headers}, (err, res, body) -> expect(res.statusCode).toBe 403 done() #- shared data between tests joeData = null firstSubscriptionID = null it 'returns client error when a token fails to charge', (done) -> stripe.tokens.create { card: { number: '4000000000000002', exp_month: 12, exp_year: 2020, cvc: '123' } }, (err, token) -> stripeTokenID = token.id loginJoe (joe) -> joeData = joe.toObject() joeData.stripe = { token: stripeTokenID planID: 'basic' } request.put {uri: userURL, json: joeData, headers: headers }, (err, res, body) -> expect(res.statusCode).toBe(402) done() it 'creates a subscription when you put a token and plan', (done) -> stripe.tokens.create { card: { number: '4242424242424242', exp_month: 12, exp_year: 2020, cvc: '123' } }, (err, token) -> stripeTokenID = token.id loginJoe (joe) -> joeData = joe.toObject() joeData.stripe = { token: stripeTokenID planID: 'basic' } request.put {uri: userURL, json: joeData, headers: headers }, (err, res, body) -> joeData = body expect(res.statusCode).toBe(200) expect(joeData.purchased.gems).toBe(3500) expect(joeData.stripe.customerID).toBeDefined() expect(firstSubscriptionID = joeData.stripe.subscriptionID).toBeDefined() expect(joeData.stripe.planID).toBe('basic') expect(joeData.stripe.token).toBeUndefined() done() it 'records a payment through the webhook', (done) -> # Don't even want to think about hooking in tests to webhooks, so... put in some data manually stripe.invoices.list {customer: joeData.stripe.customerID}, (err, invoices) -> expect(invoices.data.length).toBe(1) event = _.cloneDeep(invoiceChargeSampleEvent) event.data.object = invoices.data[0] request.post {uri: webhookURL, json: event}, (err, res, body) -> expect(res.statusCode).toBe(201) Payment.find {}, (err, payments) -> expect(payments.length).toBe(1) User.findById joeData._id, (err, user) -> expect(user.get('purchased').gems).toBe(3500) done() it 'schedules the stripe subscription to be cancelled when stripe.planID is removed from the user', (done) -> delete joeData.stripe.planID request.put {uri: userURL, json: joeData, headers: headers }, (err, res, body) -> joeData = body expect(res.statusCode).toBe(200) expect(joeData.stripe.subscriptionID).toBeDefined() expect(joeData.stripe.planID).toBeUndefined() expect(joeData.stripe.customerID).toBeDefined() stripe.customers.retrieve joeData.stripe.customerID, (err, customer) -> expect(customer.subscriptions.data.length).toBe(1) expect(customer.subscriptions.data[0].cancel_at_period_end).toBe(true) done() it 'allows you to sign up again using the same customer ID as before, no token necessary', (done) -> joeData.stripe.planID = 'basic' request.put {uri: userURL, json: joeData, headers: headers }, (err, res, body) -> joeData = body expect(res.statusCode).toBe(200) expect(joeData.stripe.customerID).toBeDefined() expect(joeData.stripe.subscriptionID).toBeDefined() expect(joeData.stripe.subscriptionID).not.toBe(firstSubscriptionID) expect(joeData.stripe.planID).toBe('basic') done() it 'will not have immediately created new payments when signing back up from a cancelled subscription', (done) -> stripe.invoices.list {customer: joeData.stripe.customerID}, (err, invoices) -> expect(invoices.data.length).toBe(2) expect(invoices.data[0].total).toBe(0) event = _.cloneDeep(invoiceChargeSampleEvent) event.data.object = invoices.data[0] request.post {uri: webhookURL, json: event}, (err, res, body) -> expect(res.statusCode).toBe(200) Payment.find {}, (err, payments) -> expect(payments.length).toBe(1) User.findById joeData._id, (err, user) -> expect(user.get('purchased').gems).toBe(3500) done() it 'deletes the subscription from the user object when an event about it comes through the webhook', (done) -> stripe.customers.retrieveSubscription joeData.stripe.customerID, joeData.stripe.subscriptionID, (err, subscription) -> event = _.cloneDeep(customerSubscriptionDeletedSampleEvent) event.data.object = subscription request.post {uri: webhookURL, json: event}, (err, res, body) -> User.findById joeData._id, (err, user) -> expect(user.get('purchased').gems).toBe(3500) expect(user.get('stripe').subscriptionID).toBeUndefined() expect(user.get('stripe').planID).toBeUndefined() done() it "updates the customer's email when you change the user's email", (done) -> joeData.email = '<EMAIL>' request.put {uri: userURL, json: joeData, headers: headers }, (err, res, body) -> f = -> stripe.customers.retrieve joeData.stripe.customerID, (err, customer) -> expect(customer.email).toBe('<EMAIL>') done() setTimeout(f, 500) # bit of a race condition here, response returns before stripe has been updated
true
config = require '../../../server_config' require '../common' # sample data that comes in through the webhook when you subscribe invoiceChargeSampleEvent = { id: 'evt_155TBeKaReE7xLUdrKM72O5R', created: 1417574898, livemode: false, type: 'invoice.payment_succeeded', data: { object: { date: 1417574897, id: 'in_155TBdKaReE7xLUdv8z8ipWl', period_start: 1417574897, period_end: 1417574897, lines: {}, subtotal: 999, total: 999, customer: 'cus_5Fz9MVWP2bDPGV', object: 'invoice', attempted: true, closed: true, forgiven: false, paid: true, livemode: false, attempt_count: 1, amount_due: 999, currency: 'usd', starting_balance: 0, ending_balance: 0, next_payment_attempt: null, webhooks_delivered_at: null, charge: 'ch_155TBdKaReE7xLUdRU0WcMzR', discount: null, application_fee: null, subscription: 'sub_5Fz99gXrBtreNe', metadata: {}, statement_description: null, description: null, receipt_number: null } }, object: 'event', pending_webhooks: 1, request: 'iar_5Fz9c4BZJyNNsM', api_version: '2014-11-05' } customerSubscriptionDeletedSampleEvent = { id: 'evt_155Tj4KaReE7xLUdpoMx0UaA', created: 1417576970, livemode: false, type: 'customer.subscription.deleted', data: { object: { id: 'sub_5FziOkege03vT7', plan: [Object], object: 'subscription', start: 1417576967, status: 'canceled', customer: 'PI:KEY:<KEY>END_PI_PI:KEY:<KEY>END_PIFzi54gMvGGPI:KEY:<KEY>END_PI', cancel_at_period_end: true, current_period_start: 1417576967, current_period_end: 1420255367, ended_at: 1417576970, trial_start: null, trial_end: null, canceled_at: 1417576970, quantity: 1, application_fee_percent: null, discount: null, metadata: {} } }, object: 'event', pending_webhooks: 1, request: 'iar_5FziYQJ4oQdL6w', api_version: '2014-11-05' } describe '/db/user, editing stripe property', -> stripe = require('stripe')(config.stripe.secretKey) userURL = getURL('/db/user') webhookURL = getURL('/stripe/webhook') headers = {'X-Change-Plan': 'true'} it 'clears the db first', (done) -> clearModels [User, Payment], (err) -> throw err if err done() it 'denies anonymous users trying to subscribe', (done) -> request.get getURL('/auth/whoami'), (err, res, body) -> body = JSON.parse(body) body.stripe = { planID: 'basic', token: 'PI:PASSWORD:<PASSWORD>END_PI' } request.put {uri: userURL, json: body, headers: headers}, (err, res, body) -> expect(res.statusCode).toBe 403 done() #- shared data between tests joeData = null firstSubscriptionID = null it 'returns client error when a token fails to charge', (done) -> stripe.tokens.create { card: { number: '4000000000000002', exp_month: 12, exp_year: 2020, cvc: '123' } }, (err, token) -> stripeTokenID = token.id loginJoe (joe) -> joeData = joe.toObject() joeData.stripe = { token: stripeTokenID planID: 'basic' } request.put {uri: userURL, json: joeData, headers: headers }, (err, res, body) -> expect(res.statusCode).toBe(402) done() it 'creates a subscription when you put a token and plan', (done) -> stripe.tokens.create { card: { number: '4242424242424242', exp_month: 12, exp_year: 2020, cvc: '123' } }, (err, token) -> stripeTokenID = token.id loginJoe (joe) -> joeData = joe.toObject() joeData.stripe = { token: stripeTokenID planID: 'basic' } request.put {uri: userURL, json: joeData, headers: headers }, (err, res, body) -> joeData = body expect(res.statusCode).toBe(200) expect(joeData.purchased.gems).toBe(3500) expect(joeData.stripe.customerID).toBeDefined() expect(firstSubscriptionID = joeData.stripe.subscriptionID).toBeDefined() expect(joeData.stripe.planID).toBe('basic') expect(joeData.stripe.token).toBeUndefined() done() it 'records a payment through the webhook', (done) -> # Don't even want to think about hooking in tests to webhooks, so... put in some data manually stripe.invoices.list {customer: joeData.stripe.customerID}, (err, invoices) -> expect(invoices.data.length).toBe(1) event = _.cloneDeep(invoiceChargeSampleEvent) event.data.object = invoices.data[0] request.post {uri: webhookURL, json: event}, (err, res, body) -> expect(res.statusCode).toBe(201) Payment.find {}, (err, payments) -> expect(payments.length).toBe(1) User.findById joeData._id, (err, user) -> expect(user.get('purchased').gems).toBe(3500) done() it 'schedules the stripe subscription to be cancelled when stripe.planID is removed from the user', (done) -> delete joeData.stripe.planID request.put {uri: userURL, json: joeData, headers: headers }, (err, res, body) -> joeData = body expect(res.statusCode).toBe(200) expect(joeData.stripe.subscriptionID).toBeDefined() expect(joeData.stripe.planID).toBeUndefined() expect(joeData.stripe.customerID).toBeDefined() stripe.customers.retrieve joeData.stripe.customerID, (err, customer) -> expect(customer.subscriptions.data.length).toBe(1) expect(customer.subscriptions.data[0].cancel_at_period_end).toBe(true) done() it 'allows you to sign up again using the same customer ID as before, no token necessary', (done) -> joeData.stripe.planID = 'basic' request.put {uri: userURL, json: joeData, headers: headers }, (err, res, body) -> joeData = body expect(res.statusCode).toBe(200) expect(joeData.stripe.customerID).toBeDefined() expect(joeData.stripe.subscriptionID).toBeDefined() expect(joeData.stripe.subscriptionID).not.toBe(firstSubscriptionID) expect(joeData.stripe.planID).toBe('basic') done() it 'will not have immediately created new payments when signing back up from a cancelled subscription', (done) -> stripe.invoices.list {customer: joeData.stripe.customerID}, (err, invoices) -> expect(invoices.data.length).toBe(2) expect(invoices.data[0].total).toBe(0) event = _.cloneDeep(invoiceChargeSampleEvent) event.data.object = invoices.data[0] request.post {uri: webhookURL, json: event}, (err, res, body) -> expect(res.statusCode).toBe(200) Payment.find {}, (err, payments) -> expect(payments.length).toBe(1) User.findById joeData._id, (err, user) -> expect(user.get('purchased').gems).toBe(3500) done() it 'deletes the subscription from the user object when an event about it comes through the webhook', (done) -> stripe.customers.retrieveSubscription joeData.stripe.customerID, joeData.stripe.subscriptionID, (err, subscription) -> event = _.cloneDeep(customerSubscriptionDeletedSampleEvent) event.data.object = subscription request.post {uri: webhookURL, json: event}, (err, res, body) -> User.findById joeData._id, (err, user) -> expect(user.get('purchased').gems).toBe(3500) expect(user.get('stripe').subscriptionID).toBeUndefined() expect(user.get('stripe').planID).toBeUndefined() done() it "updates the customer's email when you change the user's email", (done) -> joeData.email = 'PI:EMAIL:<EMAIL>END_PI' request.put {uri: userURL, json: joeData, headers: headers }, (err, res, body) -> f = -> stripe.customers.retrieve joeData.stripe.customerID, (err, customer) -> expect(customer.email).toBe('PI:EMAIL:<EMAIL>END_PI') done() setTimeout(f, 500) # bit of a race condition here, response returns before stripe has been updated
[ { "context": "oGLib\n# Module | Stat Methods\n# Author | Sherif Emabrak\n# Description | The sequence method links adjacen", "end": 164, "score": 0.9998775124549866, "start": 150, "tag": "NAME", "value": "Sherif Emabrak" } ]
src/lib/statistics/link/sequence.coffee
Sherif-Embarak/gp-test
0
# ------------------------------------------------------------------------------ # ,Project | GoGLib # Module | Stat Methods # Author | Sherif Emabrak # Description | The sequence method links adjacent nodes in a sequence # (1,2,3,..),producing the list of links{(1,2),(2,3),...} # ------------------------------------------------------------------------------ x=[6,2,3,5,4,7,8] sequence = (input_array...) -> result = [] for key,value of input_array temp=key key=value value=input_array[parseInt(temp)+1] result.push([key,value]) result console.log(sequence x...)
48784
# ------------------------------------------------------------------------------ # ,Project | GoGLib # Module | Stat Methods # Author | <NAME> # Description | The sequence method links adjacent nodes in a sequence # (1,2,3,..),producing the list of links{(1,2),(2,3),...} # ------------------------------------------------------------------------------ x=[6,2,3,5,4,7,8] sequence = (input_array...) -> result = [] for key,value of input_array temp=key key=value value=input_array[parseInt(temp)+1] result.push([key,value]) result console.log(sequence x...)
true
# ------------------------------------------------------------------------------ # ,Project | GoGLib # Module | Stat Methods # Author | PI:NAME:<NAME>END_PI # Description | The sequence method links adjacent nodes in a sequence # (1,2,3,..),producing the list of links{(1,2),(2,3),...} # ------------------------------------------------------------------------------ x=[6,2,3,5,4,7,8] sequence = (input_array...) -> result = [] for key,value of input_array temp=key key=value value=input_array[parseInt(temp)+1] result.push([key,value]) result console.log(sequence x...)
[ { "context": "'email', (n, callback) ->\n callback(null, \"test#{n}@example.com\")\n\n Factory.define 'admin', class: Admin, ->\n ", "end": 258, "score": 0.9997348189353943, "start": 238, "tag": "EMAIL", "value": "test#{n}@example.com" }, { "context": "ser) ->\n user.s...
test/sequences_test.coffee
JackDanger/factory-boy
2
require('./test_helper') class User extends Object class Admin extends Object describe 'Factory sequences', -> beforeEach -> Factory.define 'user', class: User, -> @sequence 'email', (n, callback) -> callback(null, "test#{n}@example.com") Factory.define 'admin', class: Admin, -> @sequence 'login', (n, callback) -> callback(null, "admin#{n}") it 'should start from 1', -> Factory.build 'user', (err, user) -> user.should.have.property('email', 'test1@example.com') it 'should increment by 1', -> Factory.build 'user', (err, user) -> Factory.build 'user', (err, user) -> user.should.have.property('email', 'test2@example.com') it 'should not conflict with other sequences', -> Factory.build 'admin', (err, admin) -> admin.should.have.property('login', 'admin1')
52320
require('./test_helper') class User extends Object class Admin extends Object describe 'Factory sequences', -> beforeEach -> Factory.define 'user', class: User, -> @sequence 'email', (n, callback) -> callback(null, "<EMAIL>") Factory.define 'admin', class: Admin, -> @sequence 'login', (n, callback) -> callback(null, "admin#{n}") it 'should start from 1', -> Factory.build 'user', (err, user) -> user.should.have.property('email', '<EMAIL>') it 'should increment by 1', -> Factory.build 'user', (err, user) -> Factory.build 'user', (err, user) -> user.should.have.property('email', '<EMAIL>') it 'should not conflict with other sequences', -> Factory.build 'admin', (err, admin) -> admin.should.have.property('login', 'admin1')
true
require('./test_helper') class User extends Object class Admin extends Object describe 'Factory sequences', -> beforeEach -> Factory.define 'user', class: User, -> @sequence 'email', (n, callback) -> callback(null, "PI:EMAIL:<EMAIL>END_PI") Factory.define 'admin', class: Admin, -> @sequence 'login', (n, callback) -> callback(null, "admin#{n}") it 'should start from 1', -> Factory.build 'user', (err, user) -> user.should.have.property('email', 'PI:EMAIL:<EMAIL>END_PI') it 'should increment by 1', -> Factory.build 'user', (err, user) -> Factory.build 'user', (err, user) -> user.should.have.property('email', 'PI:EMAIL:<EMAIL>END_PI') it 'should not conflict with other sequences', -> Factory.build 'admin', (err, admin) -> admin.should.have.property('login', 'admin1')
[ { "context": "\"New Relic Alert - Test Condition\"\n account_id: 1065273\n event_type: \"NOTIFICATION\"\n runbook_url: \"http", "end": 298, "score": 0.8352423310279846, "start": 292, "tag": "KEY", "value": "065273" }, { "context": "everity: \"INFO\"\n incident_id: 0\n account_na...
test/services/newrelic.coffee
jianliaoim/talk-services
40
should = require 'should' loader = require '../../src/loader' {req} = require '../util' $newrelic = loader.load 'newrelic' payload = policy_url: "https://alerts.newrelic.com/accounts/1065273/policies/0" condition_id: 0 condition_name: "New Relic Alert - Test Condition" account_id: 1065273 event_type: "NOTIFICATION" runbook_url: "http://localhost/runbook/url" severity: "INFO" incident_id: 0 account_name: "Teambition_4" timestamp: 1439535842735 details: "New Relic Alert - Channel Test" incident_acknowledge_url: "https://alerts.newrelic.com/accounts/1065273/incidents/0/acknowledge" owner: "Test User" policy_name: "New Relic Alert - Test Policy" incident_url: "https://alerts.newrelic.com/accounts/1065273/incidents/0" current_state: "test" targets: [ id: "12345" name: "Test Target" link: "http://localhost/sample/callback/link/12345" labels: label: "value" product: "TESTING" type: "test" ] describe 'NewRelic#Webhook', -> req.integration = _id: '123' it 'receive webhook', (done) -> req.body = payload $newrelic.then (newrelic) -> newrelic.receiveEvent 'service.webhook', req .then (message) -> message.attachments[0].data.redirectUrl.should.eql payload.incident_url message.attachments[0].data.title.should.eql ''' NOTIFICATION: New Relic Alert - Test Condition ''' message.attachments[0].data.text.should.eql ''' Owner: Test User Incident: New Relic Alert - Channel Test ''' .nodeify done
112793
should = require 'should' loader = require '../../src/loader' {req} = require '../util' $newrelic = loader.load 'newrelic' payload = policy_url: "https://alerts.newrelic.com/accounts/1065273/policies/0" condition_id: 0 condition_name: "New Relic Alert - Test Condition" account_id: 1<KEY> event_type: "NOTIFICATION" runbook_url: "http://localhost/runbook/url" severity: "INFO" incident_id: 0 account_name: "<KEY>" timestamp: 1439535842735 details: "New Relic Alert - Channel Test" incident_acknowledge_url: "https://alerts.newrelic.com/accounts/1065273/incidents/0/acknowledge" owner: "Test User" policy_name: "New Relic Alert - Test Policy" incident_url: "https://alerts.newrelic.com/accounts/1065273/incidents/0" current_state: "test" targets: [ id: "12345" name: "Test Target" link: "http://localhost/sample/callback/link/12345" labels: label: "value" product: "TESTING" type: "test" ] describe 'NewRelic#Webhook', -> req.integration = _id: '123' it 'receive webhook', (done) -> req.body = payload $newrelic.then (newrelic) -> newrelic.receiveEvent 'service.webhook', req .then (message) -> message.attachments[0].data.redirectUrl.should.eql payload.incident_url message.attachments[0].data.title.should.eql ''' NOTIFICATION: New Relic Alert - Test Condition ''' message.attachments[0].data.text.should.eql ''' Owner: Test User Incident: New Relic Alert - Channel Test ''' .nodeify done
true
should = require 'should' loader = require '../../src/loader' {req} = require '../util' $newrelic = loader.load 'newrelic' payload = policy_url: "https://alerts.newrelic.com/accounts/1065273/policies/0" condition_id: 0 condition_name: "New Relic Alert - Test Condition" account_id: 1PI:KEY:<KEY>END_PI event_type: "NOTIFICATION" runbook_url: "http://localhost/runbook/url" severity: "INFO" incident_id: 0 account_name: "PI:KEY:<KEY>END_PI" timestamp: 1439535842735 details: "New Relic Alert - Channel Test" incident_acknowledge_url: "https://alerts.newrelic.com/accounts/1065273/incidents/0/acknowledge" owner: "Test User" policy_name: "New Relic Alert - Test Policy" incident_url: "https://alerts.newrelic.com/accounts/1065273/incidents/0" current_state: "test" targets: [ id: "12345" name: "Test Target" link: "http://localhost/sample/callback/link/12345" labels: label: "value" product: "TESTING" type: "test" ] describe 'NewRelic#Webhook', -> req.integration = _id: '123' it 'receive webhook', (done) -> req.body = payload $newrelic.then (newrelic) -> newrelic.receiveEvent 'service.webhook', req .then (message) -> message.attachments[0].data.redirectUrl.should.eql payload.incident_url message.attachments[0].data.title.should.eql ''' NOTIFICATION: New Relic Alert - Test Condition ''' message.attachments[0].data.text.should.eql ''' Owner: Test User Incident: New Relic Alert - Channel Test ''' .nodeify done
[ { "context": "ername: process.env.PSLAN_USERNAME\n password: process.env.PSLAN_PASSWORD\n )\n\n authorizeOptions: ->\n host: @_track", "end": 561, "score": 0.9943952560424805, "start": 535, "tag": "PASSWORD", "value": "process.env.PSLAN_PASSWORD" } ]
lib/hubot-torrent/adapters/pslan/authorize_granter.coffee
dnesteryuk/hubot-torrent
2
class AuthorizeGranter _trackerHost: 'www.pslan.com' _pathToLogin: '/takelogin.php' _requiredEnvVars: [ 'PSLAN_USERNAME' 'PSLAN_PASSWORD' ] trackerName: -> 'Pslan' parseAuthCode: (res) -> cookie = res.headers['set-cookie'] uid = cookie[2].match(/uid=(\d+)/)[0] pass = cookie[3].match(/pass=([\w\d]+)/)[0].replace(';', '') "#{uid}; #{pass}" authorizeData: -> querystring = require('querystring') querystring.stringify( username: process.env.PSLAN_USERNAME password: process.env.PSLAN_PASSWORD ) authorizeOptions: -> host: @_trackerHost port: 80 method: 'POST' path: @_pathToLogin headers: 'Content-Type': 'application/x-www-form-urlencoded' 'Content-Length': this.authorizeData().length requiredEnvVars: -> @_requiredEnvVars module.exports = AuthorizeGranter
182854
class AuthorizeGranter _trackerHost: 'www.pslan.com' _pathToLogin: '/takelogin.php' _requiredEnvVars: [ 'PSLAN_USERNAME' 'PSLAN_PASSWORD' ] trackerName: -> 'Pslan' parseAuthCode: (res) -> cookie = res.headers['set-cookie'] uid = cookie[2].match(/uid=(\d+)/)[0] pass = cookie[3].match(/pass=([\w\d]+)/)[0].replace(';', '') "#{uid}; #{pass}" authorizeData: -> querystring = require('querystring') querystring.stringify( username: process.env.PSLAN_USERNAME password: <PASSWORD> ) authorizeOptions: -> host: @_trackerHost port: 80 method: 'POST' path: @_pathToLogin headers: 'Content-Type': 'application/x-www-form-urlencoded' 'Content-Length': this.authorizeData().length requiredEnvVars: -> @_requiredEnvVars module.exports = AuthorizeGranter
true
class AuthorizeGranter _trackerHost: 'www.pslan.com' _pathToLogin: '/takelogin.php' _requiredEnvVars: [ 'PSLAN_USERNAME' 'PSLAN_PASSWORD' ] trackerName: -> 'Pslan' parseAuthCode: (res) -> cookie = res.headers['set-cookie'] uid = cookie[2].match(/uid=(\d+)/)[0] pass = cookie[3].match(/pass=([\w\d]+)/)[0].replace(';', '') "#{uid}; #{pass}" authorizeData: -> querystring = require('querystring') querystring.stringify( username: process.env.PSLAN_USERNAME password: PI:PASSWORD:<PASSWORD>END_PI ) authorizeOptions: -> host: @_trackerHost port: 80 method: 'POST' path: @_pathToLogin headers: 'Content-Type': 'application/x-www-form-urlencoded' 'Content-Length': this.authorizeData().length requiredEnvVars: -> @_requiredEnvVars module.exports = AuthorizeGranter
[ { "context": "the mode files are\n # loaded immediately. (Jyrki Niemi 2017-12-12/18)\n $.when(avail_corpora_dfd).", "end": 1386, "score": 0.9032174944877625, "start": 1375, "tag": "NAME", "value": "Jyrki Niemi" }, { "context": "us ids in the URL hash\n # parameter \"...
app/scripts/main.coffee
CSCfi/Kielipankki-korp-frontend
0
window.authenticationProxy = new model.AuthenticationProxy() window.timeProxy = new model.TimeProxy() creds = $.jStorage.get("creds") console.log "creds (0)", creds if creds authenticationProxy.loginObj = creds # rewriting old url format to the angular one if(location.hash.length && location.hash[1] != "?") location.hash = "#?" + _.str.lstrip(location.hash, "#") # If the URL hash parameters are compressed (after Shibboleth login or # logout), decompress them. util.decompressActiveUrlHashParams() t = $.now() isDev = window.location.host is "localhost" $.ajaxSetup dataType: "json" traditional: true $.ajaxPrefilter "json", (options, orig, jqXHR) -> "jsonp" if options.crossDomain and not $.support.cors # If using a short URL, execute the corresponding function util.applyShortUrlConfig() avail_corpora_dfd = util.initAvailableCorpora() deferred_domReady = $.Deferred((dfd) -> $ -> mode = $.deparam.querystring().mode unless mode mode = "default" # The mode files initialize settings.corpusListing, which # requires window.availableCorpora initialized by # avail_corpora_dfd. If settings.handleUnavailableCorpora is # undefined, "none" or "fatal", avail_corpora_dfd is set null # by util.initAvailableCorpora, so that the mode files are # loaded immediately. (Jyrki Niemi 2017-12-12/18) $.when(avail_corpora_dfd).then () -> $.getScript("modes/common.js").done () -> $.getScript("modes/#{mode}_mode.js").done () -> # If using a short URL, execute the corresponding # function for mode-specific configuration util.applyShortUrlConfig() dfd.resolve() .error (jqxhr, settings, exception) -> c.error "Mode file parsing error: ", exception .error (jqxhr, settings, exception) -> c.error "common.js parsing error: ", exception return dfd ).promise() loc_dfd = initLocales() $(document).keyup (event) -> if event.keyCode == 27 kwicResults?.abort() lemgramResults?.abort() statsResults?.abort() $.when(loc_dfd, deferred_domReady).then ((loc_data) -> c.log "preloading done, t = ", $.now() - t c.log "available corpora:", window.availableCorpora # Map possible corpus id aliases to actual corpus ids in the URL hash # parameter "corpus". (Jyrki Niemi 2015-04-23) util.mapHashCorpusAliases() util.addDefaultTranslations() # These need to be before calling util.checkTryingRestrictedCorpora util.initCorpusSettingsLogicalCorpora() util.initCorpusSettingsLicenceCategory() angular.bootstrap(document, ['korpApp']) try corpus = search()["corpus"] if corpus # Save the corpora in the URL to url_corpora, because the # non-accessible corpora will be removed from the URL (and # unselected) before checking if the user tried to access # restricted corpora. url_corpora = corpus.split(",") settings.corpusListing.select url_corpora view.updateSearchHistory() catch e c.warn "ERROR setting corpora from location:", e $("body").addClass "lab" if isLab $("body").addClass "mode-" + currentMode util.browserWarn() $("#logo").click -> window.location = window.location.protocol + "//" + window.location.host + window.location.pathname + location.search false #TODO: why do i have to do this? $("#cog_menu .follow_link").click -> window.href = window.open($(this).attr("href"), $(this).attr("target") or "_self") $("#search_history").change (event) -> c.log "select", $(this).find(":selected") target = $(this).find(":selected") if _.str.contains target.val(), "http://" location.href = target.val() else if target.is(".clear") c.log "empty searches" $.jStorage.set("searches", []) view.updateSearchHistory() # reset creds if new session --matthies 2014-01-14 if not sessionStorage.getItem("newSession") c.log "new session; creds to be deleted:", creds sessionStorage.setItem("newSession", true) $.jStorage.deleteKey("creds") c.log "delete creds" creds = $.jStorage.get("creds") # for some reason this matches after login after browser start, but not later. --matthies 28.11.13 if creds util.setLogin() c.log "creds", creds tab_a_selector = "ul .ui-tabs-anchor" $("#log_out").click -> authenticationProxy.loginObj = {} $.jStorage.deleteKey "creds" $("body").toggleClass "logged_in not_logged_in" $("#pass").val "" $("#corpusbox").corpusChooser "redraw" # Use Basic authentication if not specified explicitly settings.authenticationType ?= "basic" settings.authenticationType = settings.authenticationType.toLowerCase() # Modify the login (and logout) link according to authentication type # (janiemi 2014-01-13) switch settings.authenticationType when "shibboleth" # Change the href of login link to the one specified in config.js util.makeShibbolethLink( "#login", "shibbolethLoginUrl", (elem, href) -> elem.find("a").attr("href", href) ) # Add an 'a' element to the logout link, href specified in # config.js, restricted corpora removed from the URL parameter # "corpus" util.makeShibbolethLink( "#log_out", "shibbolethLogoutUrl", (elem, href) -> elem.wrapInner("<a href='#{href}'></a>"), (href) => util.url_remove_corpora( href, settings.corpusListing.getRestrictedCorpora()) ) when "basic" # Invoke JavaScript code from the login link for login_elem in ["#login", "#resCorporaLogin"] $(login_elem).find("a").attr("href", "javascript:") else # Otherwise no authentication, so hide the login link $("#login").css("display", "none") prevFragment = {} window.onHashChange = (event, isInit) -> c.log "onHashChange" hasChanged = (key) -> prevFragment[key] isnt search()[key] if hasChanged("lang") newLang = search().lang || settings.defaultLanguage $("body").scope().lang = newLang window.lang = newLang util.localize() $("#languages").radioList "select", newLang display = search().display if isInit util.localize() prevFragment = _.extend {}, search() $(window).scroll -> $("#sidebar").sidebar "updatePlacement" #setup about link $("#about").click -> unless search().display? search display: "about" else search "about", null if settings.authenticationType != "shibboleth" $("#login").click -> unless search().display? search display: "login" else search "login", null else if search().shib_logged_in? # Shibboleth deals with username and password on the IdP-server side. Therefore I ripped out the login window # Note that this code is called *after* successful login via Shibboleth. -- matthies 28.11.13 # We don't have a username/password, so I just call it with dummy values: authenticationProxy.makeRequest("dummyuser", "dummypass", true).done((data) -> if $("body").hasClass("not_logged_in") # for some reason the first login after browser start is caught further up (see my comment there) # and with the user from the previous browser session(!) # So if setLogin has been called already, we toggle and call it again. -- matthies 28.11.13 util.setLogin() else $("body").toggleClass("logged_in not_logged_in") util.setLogin() # After Shibboleth login, if the URL parameter "corpus" # still contains corpora that the user is not allowed to # access, show the restricted corpora modal with the # option of applying for access rights. util.checkTryingRestrictedCorpora(url_corpora) search "shib_logged_in", null ).fail -> c.log "login fail" # If not logged in with Shibboleth, check if the user is trying to # access restricted corpora and show the restricted corpora modal # if needed. if not search().shib_logged_in? util.checkTryingRestrictedCorpora(url_corpora) $("#languages").radioList( change: -> c.log "lang change", $(this).radioList("getSelected").data("mode") search lang: $(this).radioList("getSelected").data("mode") # TODO: this does nothing? selected: settings.defaultLanguage ) $("#sidebar").sidebar() $(document).click -> $("#simple_text.ui-autocomplete-input").autocomplete "close" util.initCorpusSettingsFeatures() util.initCorpusSettingsLinkAttrs() util.initCorpusSettingsSyntheticAttrs() util.initCorpusSettingsAttrDisplayOrder() # FIXME: view.initSearchOptions should probably be executed only # after the corpora are set after a login, to ensure that # initSearchOptions gets options from all the selected corpora. # How to ensure that? (Jyrki Niemi 2017-01-26) setTimeout(() -> view.initSearchOptions() onHashChange null, true , 0) # Hide the "Loading..." message (Jyrki Niemi 2015-04-23) $("#loading-msg").animate opacity: 0 , -> $(this).hide() $("#main").animate opacity: 1 , -> $(this).css "opacity", "" return ), -> c.log "failed to load some resource at startup.", arguments $("body").css( opacity: 1 padding: 20 ).html('<object class="korp_fail" type="image/svg+xml" data="img/korp_fail.svg">') .append "<p>The server failed to respond, please try again later.</p>" window.getAllCorporaInFolders = (lastLevel, folderOrCorpus) -> outCorpora = [] # Go down the alley to the last subfolder while "." in folderOrCorpus posOfPeriod = _.indexOf folderOrCorpus, "." leftPart = folderOrCorpus.substr(0, posOfPeriod) rightPart = folderOrCorpus.substr(posOfPeriod + 1) if lastLevel[leftPart] lastLevel = lastLevel[leftPart] folderOrCorpus = rightPart else break if lastLevel[folderOrCorpus] # Folder # Continue to go through any subfolders $.each lastLevel[folderOrCorpus], (key, val) -> outCorpora = outCorpora.concat getAllCorporaInFolders(lastLevel[folderOrCorpus], key) if key not in ["title", "contents", "description", "info"] # And add the corpora in this folder level outCorpora = outCorpora.concat lastLevel[folderOrCorpus]["contents"] else # Corpus outCorpora.push folderOrCorpus outCorpora window.initTimeGraph = (def) -> timestruct = null all_timestruct = null restdata = null restyear = null hasRest = false onTimeGraphChange = () -> getValByDate = (date, struct) -> output = null $.each struct, (i, item) -> if date is item[0] output = item[1] false return output window.timeDeferred = timeProxy.makeRequest() .fail (error) -> $("#time_graph").html("<i>Could not draw graph due to a backend error.</i>") .done ([dataByCorpus, all_timestruct, rest]) -> for corpus, struct of dataByCorpus if corpus isnt "time" cor = settings.corpora[corpus.toLowerCase()] # Handle cases in which the settings do not # contain all corpora for which the time # information has been retrieved (for example, if # some corpora have been disabled by a short URL # configuration). FIXME: Retrieve time data only # for the enabled corpora, so that the time graph # would show data only for the enabled corpora. # (Jyrki Niemi 2016-05-09) if not cor continue timeProxy.expandTimeStruct struct cor.non_time = struct[""] struct = _.omit struct, "" cor.time = struct if _.keys(struct).length > 1 cor.common_attributes ?= {} cor.common_attributes.date_interval = true safeApply $("body").scope(), (scope) -> scope.$broadcast("corpuschooserchange", corpusChooserInstance.corpusChooser("selectedItems")); def.resolve() onTimeGraphChange = (evt, data) -> # the 46 here is the presumed value of # the height of the graph one_px = max / 46 normalize = (array) -> _.map array, (item) -> out = [].concat(item) out[1] = one_px if out[1] < one_px and out[1] > 0 out output = _(settings.corpusListing.selected) .pluck("time") .filter(Boolean) .map(_.pairs) .flatten(true) .reduce((memo, [a, b]) -> if typeof memo[a] is "undefined" memo[a] = b else memo[a] += b memo , {}) max = _.reduce(all_timestruct, (accu, item) -> return item[1] if item[1] > accu return accu , 0) timestruct = timeProxy.compilePlotArray(output) endyear = all_timestruct.slice(-1)[0][0] yeardiff = endyear - all_timestruct[0][0] restyear = endyear + (yeardiff / 25) restdata = _(settings.corpusListing.selected) .filter((item) -> item.time ).reduce((accu, corp) -> accu + parseInt(corp.non_time or "0") , 0) hasRest = yeardiff > 0 plots = [ data: normalize([].concat(all_timestruct, [[restyear, rest]])) bars: fillColor: "lightgrey" , data: normalize(timestruct) bars: fillColor: "navy" ] if restdata plots.push data: normalize([[restyear, restdata]]) bars: fillColor: "indianred" plot = $.plot($("#time_graph"), plots, bars: show: true fill: 1 align: "center" grid: hoverable: true borderColor: "white" yaxis: show: false xaxis: show: true tickDecimals: 0 hoverable: true colors: ["lightgrey", "navy"] ) $.each $("#time_graph .tickLabel"), -> $(this).hide() if parseInt($(this).text()) > new Date().getFullYear() $("#time_graph,#rest_time_graph").bind "plothover", _.throttle((event, pos, item) -> if item date = item.datapoint[0] header = $("<h4>") if date is restyear && hasRest header.text util.getLocaleString("corpselector_rest_time") val = restdata total = rest else header.text util.getLocaleString("corpselector_time") + " " + item.datapoint[0] val = getValByDate(date, timestruct) total = getValByDate(date, all_timestruct) pTmpl = _.template("<p><span rel='localize[<%= loc %>]'></span>: <%= num %> <span rel='localize[corpselector_tokens]' </p>") firstrow = pTmpl( loc: "corpselector_time_chosen" num: util.prettyNumbers(val or 0) ) secondrow = pTmpl( loc: "corpselector_of_total" num: util.prettyNumbers(total) ) time = item.datapoint[0] $(".corpusInfoSpace").css top: $(this).parent().offset().top $(".corpusInfoSpace").find("p").empty() .append(header, "<span> </span>", firstrow, secondrow) .localize().end() .fadeIn "fast" else $(".corpusInfoSpace").fadeOut "fast" , 100) opendfd = $.Deferred() $("#corpusbox").one "corpuschooseropen", -> opendfd.resolve() $.when(timeDeferred, opendfd).then -> $("#corpusbox").bind "corpuschooserchange", onTimeGraphChange onTimeGraphChange()
130284
window.authenticationProxy = new model.AuthenticationProxy() window.timeProxy = new model.TimeProxy() creds = $.jStorage.get("creds") console.log "creds (0)", creds if creds authenticationProxy.loginObj = creds # rewriting old url format to the angular one if(location.hash.length && location.hash[1] != "?") location.hash = "#?" + _.str.lstrip(location.hash, "#") # If the URL hash parameters are compressed (after Shibboleth login or # logout), decompress them. util.decompressActiveUrlHashParams() t = $.now() isDev = window.location.host is "localhost" $.ajaxSetup dataType: "json" traditional: true $.ajaxPrefilter "json", (options, orig, jqXHR) -> "jsonp" if options.crossDomain and not $.support.cors # If using a short URL, execute the corresponding function util.applyShortUrlConfig() avail_corpora_dfd = util.initAvailableCorpora() deferred_domReady = $.Deferred((dfd) -> $ -> mode = $.deparam.querystring().mode unless mode mode = "default" # The mode files initialize settings.corpusListing, which # requires window.availableCorpora initialized by # avail_corpora_dfd. If settings.handleUnavailableCorpora is # undefined, "none" or "fatal", avail_corpora_dfd is set null # by util.initAvailableCorpora, so that the mode files are # loaded immediately. (<NAME> 2017-12-12/18) $.when(avail_corpora_dfd).then () -> $.getScript("modes/common.js").done () -> $.getScript("modes/#{mode}_mode.js").done () -> # If using a short URL, execute the corresponding # function for mode-specific configuration util.applyShortUrlConfig() dfd.resolve() .error (jqxhr, settings, exception) -> c.error "Mode file parsing error: ", exception .error (jqxhr, settings, exception) -> c.error "common.js parsing error: ", exception return dfd ).promise() loc_dfd = initLocales() $(document).keyup (event) -> if event.keyCode == 27 kwicResults?.abort() lemgramResults?.abort() statsResults?.abort() $.when(loc_dfd, deferred_domReady).then ((loc_data) -> c.log "preloading done, t = ", $.now() - t c.log "available corpora:", window.availableCorpora # Map possible corpus id aliases to actual corpus ids in the URL hash # parameter "corpus". (<NAME> 2015-04-23) util.mapHashCorpusAliases() util.addDefaultTranslations() # These need to be before calling util.checkTryingRestrictedCorpora util.initCorpusSettingsLogicalCorpora() util.initCorpusSettingsLicenceCategory() angular.bootstrap(document, ['korpApp']) try corpus = search()["corpus"] if corpus # Save the corpora in the URL to url_corpora, because the # non-accessible corpora will be removed from the URL (and # unselected) before checking if the user tried to access # restricted corpora. url_corpora = corpus.split(",") settings.corpusListing.select url_corpora view.updateSearchHistory() catch e c.warn "ERROR setting corpora from location:", e $("body").addClass "lab" if isLab $("body").addClass "mode-" + currentMode util.browserWarn() $("#logo").click -> window.location = window.location.protocol + "//" + window.location.host + window.location.pathname + location.search false #TODO: why do i have to do this? $("#cog_menu .follow_link").click -> window.href = window.open($(this).attr("href"), $(this).attr("target") or "_self") $("#search_history").change (event) -> c.log "select", $(this).find(":selected") target = $(this).find(":selected") if _.str.contains target.val(), "http://" location.href = target.val() else if target.is(".clear") c.log "empty searches" $.jStorage.set("searches", []) view.updateSearchHistory() # reset creds if new session --matthies 2014-01-14 if not sessionStorage.getItem("newSession") c.log "new session; creds to be deleted:", creds sessionStorage.setItem("newSession", true) $.jStorage.deleteKey("creds") c.log "delete creds" creds = $.jStorage.get("creds") # for some reason this matches after login after browser start, but not later. --matthies 28.11.13 if creds util.setLogin() c.log "creds", creds tab_a_selector = "ul .ui-tabs-anchor" $("#log_out").click -> authenticationProxy.loginObj = {} $.jStorage.deleteKey "creds" $("body").toggleClass "logged_in not_logged_in" $("#pass").val "" $("#corpusbox").corpusChooser "redraw" # Use Basic authentication if not specified explicitly settings.authenticationType ?= "basic" settings.authenticationType = settings.authenticationType.toLowerCase() # Modify the login (and logout) link according to authentication type # (janiemi 2014-01-13) switch settings.authenticationType when "shibboleth" # Change the href of login link to the one specified in config.js util.makeShibbolethLink( "#login", "shibbolethLoginUrl", (elem, href) -> elem.find("a").attr("href", href) ) # Add an 'a' element to the logout link, href specified in # config.js, restricted corpora removed from the URL parameter # "corpus" util.makeShibbolethLink( "#log_out", "shibbolethLogoutUrl", (elem, href) -> elem.wrapInner("<a href='#{href}'></a>"), (href) => util.url_remove_corpora( href, settings.corpusListing.getRestrictedCorpora()) ) when "basic" # Invoke JavaScript code from the login link for login_elem in ["#login", "#resCorporaLogin"] $(login_elem).find("a").attr("href", "javascript:") else # Otherwise no authentication, so hide the login link $("#login").css("display", "none") prevFragment = {} window.onHashChange = (event, isInit) -> c.log "onHashChange" hasChanged = (key) -> prevFragment[key] isnt search()[key] if hasChanged("lang") newLang = search().lang || settings.defaultLanguage $("body").scope().lang = newLang window.lang = newLang util.localize() $("#languages").radioList "select", newLang display = search().display if isInit util.localize() prevFragment = _.extend {}, search() $(window).scroll -> $("#sidebar").sidebar "updatePlacement" #setup about link $("#about").click -> unless search().display? search display: "about" else search "about", null if settings.authenticationType != "shibboleth" $("#login").click -> unless search().display? search display: "login" else search "login", null else if search().shib_logged_in? # Shibboleth deals with username and password on the IdP-server side. Therefore I ripped out the login window # Note that this code is called *after* successful login via Shibboleth. -- matthies 28.11.13 # We don't have a username/password, so I just call it with dummy values: authenticationProxy.makeRequest("dummyuser", "dummypass", true).done((data) -> if $("body").hasClass("not_logged_in") # for some reason the first login after browser start is caught further up (see my comment there) # and with the user from the previous browser session(!) # So if setLogin has been called already, we toggle and call it again. -- matthies 28.11.13 util.setLogin() else $("body").toggleClass("logged_in not_logged_in") util.setLogin() # After Shibboleth login, if the URL parameter "corpus" # still contains corpora that the user is not allowed to # access, show the restricted corpora modal with the # option of applying for access rights. util.checkTryingRestrictedCorpora(url_corpora) search "shib_logged_in", null ).fail -> c.log "login fail" # If not logged in with Shibboleth, check if the user is trying to # access restricted corpora and show the restricted corpora modal # if needed. if not search().shib_logged_in? util.checkTryingRestrictedCorpora(url_corpora) $("#languages").radioList( change: -> c.log "lang change", $(this).radioList("getSelected").data("mode") search lang: $(this).radioList("getSelected").data("mode") # TODO: this does nothing? selected: settings.defaultLanguage ) $("#sidebar").sidebar() $(document).click -> $("#simple_text.ui-autocomplete-input").autocomplete "close" util.initCorpusSettingsFeatures() util.initCorpusSettingsLinkAttrs() util.initCorpusSettingsSyntheticAttrs() util.initCorpusSettingsAttrDisplayOrder() # FIXME: view.initSearchOptions should probably be executed only # after the corpora are set after a login, to ensure that # initSearchOptions gets options from all the selected corpora. # How to ensure that? (<NAME> 2017-01-26) setTimeout(() -> view.initSearchOptions() onHashChange null, true , 0) # Hide the "Loading..." message (J<NAME>ki Niemi 2015-04-23) $("#loading-msg").animate opacity: 0 , -> $(this).hide() $("#main").animate opacity: 1 , -> $(this).css "opacity", "" return ), -> c.log "failed to load some resource at startup.", arguments $("body").css( opacity: 1 padding: 20 ).html('<object class="korp_fail" type="image/svg+xml" data="img/korp_fail.svg">') .append "<p>The server failed to respond, please try again later.</p>" window.getAllCorporaInFolders = (lastLevel, folderOrCorpus) -> outCorpora = [] # Go down the alley to the last subfolder while "." in folderOrCorpus posOfPeriod = _.indexOf folderOrCorpus, "." leftPart = folderOrCorpus.substr(0, posOfPeriod) rightPart = folderOrCorpus.substr(posOfPeriod + 1) if lastLevel[leftPart] lastLevel = lastLevel[leftPart] folderOrCorpus = rightPart else break if lastLevel[folderOrCorpus] # Folder # Continue to go through any subfolders $.each lastLevel[folderOrCorpus], (key, val) -> outCorpora = outCorpora.concat getAllCorporaInFolders(lastLevel[folderOrCorpus], key) if key not in ["title", "contents", "description", "info"] # And add the corpora in this folder level outCorpora = outCorpora.concat lastLevel[folderOrCorpus]["contents"] else # Corpus outCorpora.push folderOrCorpus outCorpora window.initTimeGraph = (def) -> timestruct = null all_timestruct = null restdata = null restyear = null hasRest = false onTimeGraphChange = () -> getValByDate = (date, struct) -> output = null $.each struct, (i, item) -> if date is item[0] output = item[1] false return output window.timeDeferred = timeProxy.makeRequest() .fail (error) -> $("#time_graph").html("<i>Could not draw graph due to a backend error.</i>") .done ([dataByCorpus, all_timestruct, rest]) -> for corpus, struct of dataByCorpus if corpus isnt "time" cor = settings.corpora[corpus.toLowerCase()] # Handle cases in which the settings do not # contain all corpora for which the time # information has been retrieved (for example, if # some corpora have been disabled by a short URL # configuration). FIXME: Retrieve time data only # for the enabled corpora, so that the time graph # would show data only for the enabled corpora. # (<NAME> 2016-05-09) if not cor continue timeProxy.expandTimeStruct struct cor.non_time = struct[""] struct = _.omit struct, "" cor.time = struct if _.keys(struct).length > 1 cor.common_attributes ?= {} cor.common_attributes.date_interval = true safeApply $("body").scope(), (scope) -> scope.$broadcast("corpuschooserchange", corpusChooserInstance.corpusChooser("selectedItems")); def.resolve() onTimeGraphChange = (evt, data) -> # the 46 here is the presumed value of # the height of the graph one_px = max / 46 normalize = (array) -> _.map array, (item) -> out = [].concat(item) out[1] = one_px if out[1] < one_px and out[1] > 0 out output = _(settings.corpusListing.selected) .pluck("time") .filter(Boolean) .map(_.pairs) .flatten(true) .reduce((memo, [a, b]) -> if typeof memo[a] is "undefined" memo[a] = b else memo[a] += b memo , {}) max = _.reduce(all_timestruct, (accu, item) -> return item[1] if item[1] > accu return accu , 0) timestruct = timeProxy.compilePlotArray(output) endyear = all_timestruct.slice(-1)[0][0] yeardiff = endyear - all_timestruct[0][0] restyear = endyear + (yeardiff / 25) restdata = _(settings.corpusListing.selected) .filter((item) -> item.time ).reduce((accu, corp) -> accu + parseInt(corp.non_time or "0") , 0) hasRest = yeardiff > 0 plots = [ data: normalize([].concat(all_timestruct, [[restyear, rest]])) bars: fillColor: "lightgrey" , data: normalize(timestruct) bars: fillColor: "navy" ] if restdata plots.push data: normalize([[restyear, restdata]]) bars: fillColor: "indianred" plot = $.plot($("#time_graph"), plots, bars: show: true fill: 1 align: "center" grid: hoverable: true borderColor: "white" yaxis: show: false xaxis: show: true tickDecimals: 0 hoverable: true colors: ["lightgrey", "navy"] ) $.each $("#time_graph .tickLabel"), -> $(this).hide() if parseInt($(this).text()) > new Date().getFullYear() $("#time_graph,#rest_time_graph").bind "plothover", _.throttle((event, pos, item) -> if item date = item.datapoint[0] header = $("<h4>") if date is restyear && hasRest header.text util.getLocaleString("corpselector_rest_time") val = restdata total = rest else header.text util.getLocaleString("corpselector_time") + " " + item.datapoint[0] val = getValByDate(date, timestruct) total = getValByDate(date, all_timestruct) pTmpl = _.template("<p><span rel='localize[<%= loc %>]'></span>: <%= num %> <span rel='localize[corpselector_tokens]' </p>") firstrow = pTmpl( loc: "corpselector_time_chosen" num: util.prettyNumbers(val or 0) ) secondrow = pTmpl( loc: "corpselector_of_total" num: util.prettyNumbers(total) ) time = item.datapoint[0] $(".corpusInfoSpace").css top: $(this).parent().offset().top $(".corpusInfoSpace").find("p").empty() .append(header, "<span> </span>", firstrow, secondrow) .localize().end() .fadeIn "fast" else $(".corpusInfoSpace").fadeOut "fast" , 100) opendfd = $.Deferred() $("#corpusbox").one "corpuschooseropen", -> opendfd.resolve() $.when(timeDeferred, opendfd).then -> $("#corpusbox").bind "corpuschooserchange", onTimeGraphChange onTimeGraphChange()
true
window.authenticationProxy = new model.AuthenticationProxy() window.timeProxy = new model.TimeProxy() creds = $.jStorage.get("creds") console.log "creds (0)", creds if creds authenticationProxy.loginObj = creds # rewriting old url format to the angular one if(location.hash.length && location.hash[1] != "?") location.hash = "#?" + _.str.lstrip(location.hash, "#") # If the URL hash parameters are compressed (after Shibboleth login or # logout), decompress them. util.decompressActiveUrlHashParams() t = $.now() isDev = window.location.host is "localhost" $.ajaxSetup dataType: "json" traditional: true $.ajaxPrefilter "json", (options, orig, jqXHR) -> "jsonp" if options.crossDomain and not $.support.cors # If using a short URL, execute the corresponding function util.applyShortUrlConfig() avail_corpora_dfd = util.initAvailableCorpora() deferred_domReady = $.Deferred((dfd) -> $ -> mode = $.deparam.querystring().mode unless mode mode = "default" # The mode files initialize settings.corpusListing, which # requires window.availableCorpora initialized by # avail_corpora_dfd. If settings.handleUnavailableCorpora is # undefined, "none" or "fatal", avail_corpora_dfd is set null # by util.initAvailableCorpora, so that the mode files are # loaded immediately. (PI:NAME:<NAME>END_PI 2017-12-12/18) $.when(avail_corpora_dfd).then () -> $.getScript("modes/common.js").done () -> $.getScript("modes/#{mode}_mode.js").done () -> # If using a short URL, execute the corresponding # function for mode-specific configuration util.applyShortUrlConfig() dfd.resolve() .error (jqxhr, settings, exception) -> c.error "Mode file parsing error: ", exception .error (jqxhr, settings, exception) -> c.error "common.js parsing error: ", exception return dfd ).promise() loc_dfd = initLocales() $(document).keyup (event) -> if event.keyCode == 27 kwicResults?.abort() lemgramResults?.abort() statsResults?.abort() $.when(loc_dfd, deferred_domReady).then ((loc_data) -> c.log "preloading done, t = ", $.now() - t c.log "available corpora:", window.availableCorpora # Map possible corpus id aliases to actual corpus ids in the URL hash # parameter "corpus". (PI:NAME:<NAME>END_PI 2015-04-23) util.mapHashCorpusAliases() util.addDefaultTranslations() # These need to be before calling util.checkTryingRestrictedCorpora util.initCorpusSettingsLogicalCorpora() util.initCorpusSettingsLicenceCategory() angular.bootstrap(document, ['korpApp']) try corpus = search()["corpus"] if corpus # Save the corpora in the URL to url_corpora, because the # non-accessible corpora will be removed from the URL (and # unselected) before checking if the user tried to access # restricted corpora. url_corpora = corpus.split(",") settings.corpusListing.select url_corpora view.updateSearchHistory() catch e c.warn "ERROR setting corpora from location:", e $("body").addClass "lab" if isLab $("body").addClass "mode-" + currentMode util.browserWarn() $("#logo").click -> window.location = window.location.protocol + "//" + window.location.host + window.location.pathname + location.search false #TODO: why do i have to do this? $("#cog_menu .follow_link").click -> window.href = window.open($(this).attr("href"), $(this).attr("target") or "_self") $("#search_history").change (event) -> c.log "select", $(this).find(":selected") target = $(this).find(":selected") if _.str.contains target.val(), "http://" location.href = target.val() else if target.is(".clear") c.log "empty searches" $.jStorage.set("searches", []) view.updateSearchHistory() # reset creds if new session --matthies 2014-01-14 if not sessionStorage.getItem("newSession") c.log "new session; creds to be deleted:", creds sessionStorage.setItem("newSession", true) $.jStorage.deleteKey("creds") c.log "delete creds" creds = $.jStorage.get("creds") # for some reason this matches after login after browser start, but not later. --matthies 28.11.13 if creds util.setLogin() c.log "creds", creds tab_a_selector = "ul .ui-tabs-anchor" $("#log_out").click -> authenticationProxy.loginObj = {} $.jStorage.deleteKey "creds" $("body").toggleClass "logged_in not_logged_in" $("#pass").val "" $("#corpusbox").corpusChooser "redraw" # Use Basic authentication if not specified explicitly settings.authenticationType ?= "basic" settings.authenticationType = settings.authenticationType.toLowerCase() # Modify the login (and logout) link according to authentication type # (janiemi 2014-01-13) switch settings.authenticationType when "shibboleth" # Change the href of login link to the one specified in config.js util.makeShibbolethLink( "#login", "shibbolethLoginUrl", (elem, href) -> elem.find("a").attr("href", href) ) # Add an 'a' element to the logout link, href specified in # config.js, restricted corpora removed from the URL parameter # "corpus" util.makeShibbolethLink( "#log_out", "shibbolethLogoutUrl", (elem, href) -> elem.wrapInner("<a href='#{href}'></a>"), (href) => util.url_remove_corpora( href, settings.corpusListing.getRestrictedCorpora()) ) when "basic" # Invoke JavaScript code from the login link for login_elem in ["#login", "#resCorporaLogin"] $(login_elem).find("a").attr("href", "javascript:") else # Otherwise no authentication, so hide the login link $("#login").css("display", "none") prevFragment = {} window.onHashChange = (event, isInit) -> c.log "onHashChange" hasChanged = (key) -> prevFragment[key] isnt search()[key] if hasChanged("lang") newLang = search().lang || settings.defaultLanguage $("body").scope().lang = newLang window.lang = newLang util.localize() $("#languages").radioList "select", newLang display = search().display if isInit util.localize() prevFragment = _.extend {}, search() $(window).scroll -> $("#sidebar").sidebar "updatePlacement" #setup about link $("#about").click -> unless search().display? search display: "about" else search "about", null if settings.authenticationType != "shibboleth" $("#login").click -> unless search().display? search display: "login" else search "login", null else if search().shib_logged_in? # Shibboleth deals with username and password on the IdP-server side. Therefore I ripped out the login window # Note that this code is called *after* successful login via Shibboleth. -- matthies 28.11.13 # We don't have a username/password, so I just call it with dummy values: authenticationProxy.makeRequest("dummyuser", "dummypass", true).done((data) -> if $("body").hasClass("not_logged_in") # for some reason the first login after browser start is caught further up (see my comment there) # and with the user from the previous browser session(!) # So if setLogin has been called already, we toggle and call it again. -- matthies 28.11.13 util.setLogin() else $("body").toggleClass("logged_in not_logged_in") util.setLogin() # After Shibboleth login, if the URL parameter "corpus" # still contains corpora that the user is not allowed to # access, show the restricted corpora modal with the # option of applying for access rights. util.checkTryingRestrictedCorpora(url_corpora) search "shib_logged_in", null ).fail -> c.log "login fail" # If not logged in with Shibboleth, check if the user is trying to # access restricted corpora and show the restricted corpora modal # if needed. if not search().shib_logged_in? util.checkTryingRestrictedCorpora(url_corpora) $("#languages").radioList( change: -> c.log "lang change", $(this).radioList("getSelected").data("mode") search lang: $(this).radioList("getSelected").data("mode") # TODO: this does nothing? selected: settings.defaultLanguage ) $("#sidebar").sidebar() $(document).click -> $("#simple_text.ui-autocomplete-input").autocomplete "close" util.initCorpusSettingsFeatures() util.initCorpusSettingsLinkAttrs() util.initCorpusSettingsSyntheticAttrs() util.initCorpusSettingsAttrDisplayOrder() # FIXME: view.initSearchOptions should probably be executed only # after the corpora are set after a login, to ensure that # initSearchOptions gets options from all the selected corpora. # How to ensure that? (PI:NAME:<NAME>END_PI 2017-01-26) setTimeout(() -> view.initSearchOptions() onHashChange null, true , 0) # Hide the "Loading..." message (JPI:NAME:<NAME>END_PIki Niemi 2015-04-23) $("#loading-msg").animate opacity: 0 , -> $(this).hide() $("#main").animate opacity: 1 , -> $(this).css "opacity", "" return ), -> c.log "failed to load some resource at startup.", arguments $("body").css( opacity: 1 padding: 20 ).html('<object class="korp_fail" type="image/svg+xml" data="img/korp_fail.svg">') .append "<p>The server failed to respond, please try again later.</p>" window.getAllCorporaInFolders = (lastLevel, folderOrCorpus) -> outCorpora = [] # Go down the alley to the last subfolder while "." in folderOrCorpus posOfPeriod = _.indexOf folderOrCorpus, "." leftPart = folderOrCorpus.substr(0, posOfPeriod) rightPart = folderOrCorpus.substr(posOfPeriod + 1) if lastLevel[leftPart] lastLevel = lastLevel[leftPart] folderOrCorpus = rightPart else break if lastLevel[folderOrCorpus] # Folder # Continue to go through any subfolders $.each lastLevel[folderOrCorpus], (key, val) -> outCorpora = outCorpora.concat getAllCorporaInFolders(lastLevel[folderOrCorpus], key) if key not in ["title", "contents", "description", "info"] # And add the corpora in this folder level outCorpora = outCorpora.concat lastLevel[folderOrCorpus]["contents"] else # Corpus outCorpora.push folderOrCorpus outCorpora window.initTimeGraph = (def) -> timestruct = null all_timestruct = null restdata = null restyear = null hasRest = false onTimeGraphChange = () -> getValByDate = (date, struct) -> output = null $.each struct, (i, item) -> if date is item[0] output = item[1] false return output window.timeDeferred = timeProxy.makeRequest() .fail (error) -> $("#time_graph").html("<i>Could not draw graph due to a backend error.</i>") .done ([dataByCorpus, all_timestruct, rest]) -> for corpus, struct of dataByCorpus if corpus isnt "time" cor = settings.corpora[corpus.toLowerCase()] # Handle cases in which the settings do not # contain all corpora for which the time # information has been retrieved (for example, if # some corpora have been disabled by a short URL # configuration). FIXME: Retrieve time data only # for the enabled corpora, so that the time graph # would show data only for the enabled corpora. # (PI:NAME:<NAME>END_PI 2016-05-09) if not cor continue timeProxy.expandTimeStruct struct cor.non_time = struct[""] struct = _.omit struct, "" cor.time = struct if _.keys(struct).length > 1 cor.common_attributes ?= {} cor.common_attributes.date_interval = true safeApply $("body").scope(), (scope) -> scope.$broadcast("corpuschooserchange", corpusChooserInstance.corpusChooser("selectedItems")); def.resolve() onTimeGraphChange = (evt, data) -> # the 46 here is the presumed value of # the height of the graph one_px = max / 46 normalize = (array) -> _.map array, (item) -> out = [].concat(item) out[1] = one_px if out[1] < one_px and out[1] > 0 out output = _(settings.corpusListing.selected) .pluck("time") .filter(Boolean) .map(_.pairs) .flatten(true) .reduce((memo, [a, b]) -> if typeof memo[a] is "undefined" memo[a] = b else memo[a] += b memo , {}) max = _.reduce(all_timestruct, (accu, item) -> return item[1] if item[1] > accu return accu , 0) timestruct = timeProxy.compilePlotArray(output) endyear = all_timestruct.slice(-1)[0][0] yeardiff = endyear - all_timestruct[0][0] restyear = endyear + (yeardiff / 25) restdata = _(settings.corpusListing.selected) .filter((item) -> item.time ).reduce((accu, corp) -> accu + parseInt(corp.non_time or "0") , 0) hasRest = yeardiff > 0 plots = [ data: normalize([].concat(all_timestruct, [[restyear, rest]])) bars: fillColor: "lightgrey" , data: normalize(timestruct) bars: fillColor: "navy" ] if restdata plots.push data: normalize([[restyear, restdata]]) bars: fillColor: "indianred" plot = $.plot($("#time_graph"), plots, bars: show: true fill: 1 align: "center" grid: hoverable: true borderColor: "white" yaxis: show: false xaxis: show: true tickDecimals: 0 hoverable: true colors: ["lightgrey", "navy"] ) $.each $("#time_graph .tickLabel"), -> $(this).hide() if parseInt($(this).text()) > new Date().getFullYear() $("#time_graph,#rest_time_graph").bind "plothover", _.throttle((event, pos, item) -> if item date = item.datapoint[0] header = $("<h4>") if date is restyear && hasRest header.text util.getLocaleString("corpselector_rest_time") val = restdata total = rest else header.text util.getLocaleString("corpselector_time") + " " + item.datapoint[0] val = getValByDate(date, timestruct) total = getValByDate(date, all_timestruct) pTmpl = _.template("<p><span rel='localize[<%= loc %>]'></span>: <%= num %> <span rel='localize[corpselector_tokens]' </p>") firstrow = pTmpl( loc: "corpselector_time_chosen" num: util.prettyNumbers(val or 0) ) secondrow = pTmpl( loc: "corpselector_of_total" num: util.prettyNumbers(total) ) time = item.datapoint[0] $(".corpusInfoSpace").css top: $(this).parent().offset().top $(".corpusInfoSpace").find("p").empty() .append(header, "<span> </span>", firstrow, secondrow) .localize().end() .fadeIn "fast" else $(".corpusInfoSpace").fadeOut "fast" , 100) opendfd = $.Deferred() $("#corpusbox").one "corpuschooseropen", -> opendfd.resolve() $.when(timeDeferred, opendfd).then -> $("#corpusbox").bind "corpuschooserchange", onTimeGraphChange onTimeGraphChange()
[ { "context": "')\n #md5.update(title||'')\n #req.body.token = md5.digest('hex')\n req.body.token = crypto.createHas", "end": 2125, "score": 0.5148947238922119, "start": 2124, "tag": "KEY", "value": "5" }, { "context": "\n #md5.update(title||'')\n #req.body.token = md5.digest('he...
src/controllers/ticket.coffee
Tatsuonline/node-ticket-manager
81
mongoose = require('mongoose') Ticket = mongoose.model('Ticket') crypto = require 'crypto' STATUS = require "../enums/ticket_status" MAX_ATTEMPTS_BEFORE_ABANDON = 16 MAX_TIME_ALLOWED_FOR_PROCESSING = 1000 * 60 * 60 debuglog = require("debug")("ticketman:controller:ticket") # list tickets # GET / # GET /tickets exports.index = (req, res, next)-> debuglog "index" res.render 'tickets/index', title: 'All Tickets' tickets : [] return exports.list = (req, res, next)-> debuglog "list req.query: %j", req.query query = Ticket.paginate(req.query || {}, '_id').select('-comments -content') if req.query.status? query.where status : req.query.status query.execPagination (err, result)-> return next err if err? result.success = true console.log "[ticket::list] dump result:" console.dir result res.json result return exports.count = (req, res, next)-> result = {} Ticket.count (err, count)-> next err if err? result.all = count Ticket.count {status: STATUS.PENDING}, (err, count)-> next err if err? result[STATUS.PENDING] = count Ticket.count {status: STATUS.PROCESSING}, (err, count)-> next err if err? result[STATUS.PROCESSING] = count Ticket.count {status: STATUS.COMPLETE}, (err, count)-> next err if err? result[STATUS.COMPLETE] = count Ticket.count {status: STATUS.ABANDON}, (err, count)-> next err if err? result[STATUS.ABANDON] = count res.json result return return return return return return # GET /tickets/:id exports.show = (req, res, next)-> debuglog "show" id = String(req.params.id || '') return next() unless id? Ticket.findById id, (err, ticket)-> return next err if err? res.render 'tickets/show', title: 'All Tickets' ticket : ticket return return # POST /api/tickets/new exports.create = (req, res, next)-> debuglog "create" title = (req.body||{}).title #md5 = crypto.createHash('md5') #md5.update(title||'') #req.body.token = md5.digest('hex') req.body.token = crypto.createHash('md5').update(title).digest('hex').toLowerCase() ticket = new Ticket(req.body) ticket.save (err)=> if err? return res.json success : false error : err.toString() else return res.json success : true ticket : ticket return # PUT /api/tickets/assign exports.assign = (req, res, next)-> debuglog "assign, req.worker:%j", req.worker req.body.worker = req.worker.name Ticket.arrangeAssignment req.body, (err, ticket) -> return next(err) if err? unless ticket? return res.json success : false error : "no pending ticket of #{req.body.category}" # clear comments when assign ticket ticket.comments = [] #console.log "!!!! before assign" #console.dir ticket #ticket = JSON.stringify(ticket) #ticket = JSON.parse(ticket) return res.json success : true ticket : ticket return # PUT /api/tickets/:id/comment exports.comment = (req, res, next)-> id = req.params.id || '' return next() unless id? req.body.name = req.worker.name Ticket.addComment id, req.body, (err, ticket)-> return next(err) if err? unless ticket? return res.json success : false error : "no commented ticket of #{id}" return res.json success : true ticket : ticket return # PUT /api/tickets/:id/complete exports.complete = (req, res, next)-> id = String(req.params.id || '') return next() unless id? req.body.id = id Ticket.changeStatus req.body, STATUS.COMPLETE, (err, ticket)-> return next(err) if err? return next() unless ticket? return res.json ticket return # PUT /api/tickets/:id/giveup exports.giveup = (req, res, next)-> id = String(req.params.id || '') return next() unless id? req.body.id = id comment = name: req.body.name || req.worker.name kind: "danger" content : req.body.reason || "#{req.worker.name} fail to process this ticket" Ticket.addComment id, comment, (err, ticket)-> return next(err) if err? unless ticket? return res.json success : false error : "missing ticket of #{id}" # abandon ticket if exceed max attempts targetStatus = if ticket.attempts < MAX_ATTEMPTS_BEFORE_ABANDON then STATUS.PENDING else STATUS.ABANDON Ticket.changeStatus req.body, targetStatus, (err, ticket)-> return next(err) if err? return next() unless ticket? ticket.update {$inc: {attempts:1}}, (err, numberAffected)-> return next(err) if err? ticket.attempts = numberAffected return res.json ticket return return return # PUT /tickets/:id/abandon exports.abandon = (req, res, next)-> id = String(req.params.id || '') return next() unless id? Ticket.findById id, (err, ticket)-> return next err if err? return next() unless ticket? return next(new Error "only pending ticket could be abandoned") unless ticket.status is STATUS.PENDING Ticket.changeStatus {id : ticket.id}, STATUS.ABANDON, (err, ticket)-> return next err if err? return next() unless ticket? return res.redirect "/tickets" return return # PUT /tickets/:id/comment exports.adminComment = (req, res, next)-> id = String(req.params.id || '') return next() unless id? req.body.content = req.body.content.trim() console.log "[ticket::==========] req.body.content:#{req.body.content}" return next(new Error "please say something") unless req.body.content req.body.kind = "warning" req.body.name = "admin" Ticket.addComment id, req.body, (err, ticket)-> return next(err) if err? return next() unless ticket? return res.redirect "/tickets/#{id}" return #GET /tickets/:token/status exports.showStatus = (req, res, next) -> token = req.params.token unless token res.json "success":false "error": "missing param token" return query = { token: token } Ticket.findOne query, (err, ticket) -> if err? res.json "success":false "error": "#{err}" return data = "success": true if ticket? data['result'] = id: ticket.id status: ticket.status else data['result'] = null return res.json data return # routine: clean up overtime processing tickets setInterval ()-> #debuglog "clean up overtime processing tickets" query = $and: [ {status : STATUS.PROCESSING} {updated_at : $lt : Date.now() - MAX_TIME_ALLOWED_FOR_PROCESSING} ] Ticket.findOne query, (err, ticket)-> if err? console.error "ERROR [ticket::interval::cleanup] error:#{err}" return unless ticket? #debuglog "no ticket" return #debuglog "[interval::cleanup] ticket:" #console.dir ticket if ticket.attempts < MAX_ATTEMPTS_BEFORE_ABANDON content = "ticket processing overtime, set back to retry." targetStatus = STATUS.PENDING else content = "ticket exceeds max attemption, so abandon" targetStatus = STATUS.ABANDON ticket.comments.push name : "admin" kind : "danger" content : content date : Date.now() ticket.status = targetStatus ticket.save (err)-> #debuglog "change to ticket applied" return return , 2000
35161
mongoose = require('mongoose') Ticket = mongoose.model('Ticket') crypto = require 'crypto' STATUS = require "../enums/ticket_status" MAX_ATTEMPTS_BEFORE_ABANDON = 16 MAX_TIME_ALLOWED_FOR_PROCESSING = 1000 * 60 * 60 debuglog = require("debug")("ticketman:controller:ticket") # list tickets # GET / # GET /tickets exports.index = (req, res, next)-> debuglog "index" res.render 'tickets/index', title: 'All Tickets' tickets : [] return exports.list = (req, res, next)-> debuglog "list req.query: %j", req.query query = Ticket.paginate(req.query || {}, '_id').select('-comments -content') if req.query.status? query.where status : req.query.status query.execPagination (err, result)-> return next err if err? result.success = true console.log "[ticket::list] dump result:" console.dir result res.json result return exports.count = (req, res, next)-> result = {} Ticket.count (err, count)-> next err if err? result.all = count Ticket.count {status: STATUS.PENDING}, (err, count)-> next err if err? result[STATUS.PENDING] = count Ticket.count {status: STATUS.PROCESSING}, (err, count)-> next err if err? result[STATUS.PROCESSING] = count Ticket.count {status: STATUS.COMPLETE}, (err, count)-> next err if err? result[STATUS.COMPLETE] = count Ticket.count {status: STATUS.ABANDON}, (err, count)-> next err if err? result[STATUS.ABANDON] = count res.json result return return return return return return # GET /tickets/:id exports.show = (req, res, next)-> debuglog "show" id = String(req.params.id || '') return next() unless id? Ticket.findById id, (err, ticket)-> return next err if err? res.render 'tickets/show', title: 'All Tickets' ticket : ticket return return # POST /api/tickets/new exports.create = (req, res, next)-> debuglog "create" title = (req.body||{}).title #md5 = crypto.createHash('md5') #md5.update(title||'') #req.body.token = md<KEY>.<KEY>('hex') req.body.token = <KEY>('md<KEY>(title).<KEY>('hex').<KEY>() ticket = new Ticket(req.body) ticket.save (err)=> if err? return res.json success : false error : err.toString() else return res.json success : true ticket : ticket return # PUT /api/tickets/assign exports.assign = (req, res, next)-> debuglog "assign, req.worker:%j", req.worker req.body.worker = req.worker.name Ticket.arrangeAssignment req.body, (err, ticket) -> return next(err) if err? unless ticket? return res.json success : false error : "no pending ticket of #{req.body.category}" # clear comments when assign ticket ticket.comments = [] #console.log "!!!! before assign" #console.dir ticket #ticket = JSON.stringify(ticket) #ticket = JSON.parse(ticket) return res.json success : true ticket : ticket return # PUT /api/tickets/:id/comment exports.comment = (req, res, next)-> id = req.params.id || '' return next() unless id? req.body.name = req.worker.name Ticket.addComment id, req.body, (err, ticket)-> return next(err) if err? unless ticket? return res.json success : false error : "no commented ticket of #{id}" return res.json success : true ticket : ticket return # PUT /api/tickets/:id/complete exports.complete = (req, res, next)-> id = String(req.params.id || '') return next() unless id? req.body.id = id Ticket.changeStatus req.body, STATUS.COMPLETE, (err, ticket)-> return next(err) if err? return next() unless ticket? return res.json ticket return # PUT /api/tickets/:id/giveup exports.giveup = (req, res, next)-> id = String(req.params.id || '') return next() unless id? req.body.id = id comment = name: req.body.name || req.worker.name kind: "danger" content : req.body.reason || "#{req.worker.name} fail to process this ticket" Ticket.addComment id, comment, (err, ticket)-> return next(err) if err? unless ticket? return res.json success : false error : "missing ticket of #{id}" # abandon ticket if exceed max attempts targetStatus = if ticket.attempts < MAX_ATTEMPTS_BEFORE_ABANDON then STATUS.PENDING else STATUS.ABANDON Ticket.changeStatus req.body, targetStatus, (err, ticket)-> return next(err) if err? return next() unless ticket? ticket.update {$inc: {attempts:1}}, (err, numberAffected)-> return next(err) if err? ticket.attempts = numberAffected return res.json ticket return return return # PUT /tickets/:id/abandon exports.abandon = (req, res, next)-> id = String(req.params.id || '') return next() unless id? Ticket.findById id, (err, ticket)-> return next err if err? return next() unless ticket? return next(new Error "only pending ticket could be abandoned") unless ticket.status is STATUS.PENDING Ticket.changeStatus {id : ticket.id}, STATUS.ABANDON, (err, ticket)-> return next err if err? return next() unless ticket? return res.redirect "/tickets" return return # PUT /tickets/:id/comment exports.adminComment = (req, res, next)-> id = String(req.params.id || '') return next() unless id? req.body.content = req.body.content.trim() console.log "[ticket::==========] req.body.content:#{req.body.content}" return next(new Error "please say something") unless req.body.content req.body.kind = "warning" req.body.name = "admin" Ticket.addComment id, req.body, (err, ticket)-> return next(err) if err? return next() unless ticket? return res.redirect "/tickets/#{id}" return #GET /tickets/:token/status exports.showStatus = (req, res, next) -> token = req.params.token unless token res.json "success":false "error": "missing param token" return query = { token: token } Ticket.findOne query, (err, ticket) -> if err? res.json "success":false "error": "#{err}" return data = "success": true if ticket? data['result'] = id: ticket.id status: ticket.status else data['result'] = null return res.json data return # routine: clean up overtime processing tickets setInterval ()-> #debuglog "clean up overtime processing tickets" query = $and: [ {status : STATUS.PROCESSING} {updated_at : $lt : Date.now() - MAX_TIME_ALLOWED_FOR_PROCESSING} ] Ticket.findOne query, (err, ticket)-> if err? console.error "ERROR [ticket::interval::cleanup] error:#{err}" return unless ticket? #debuglog "no ticket" return #debuglog "[interval::cleanup] ticket:" #console.dir ticket if ticket.attempts < MAX_ATTEMPTS_BEFORE_ABANDON content = "ticket processing overtime, set back to retry." targetStatus = STATUS.PENDING else content = "ticket exceeds max attemption, so abandon" targetStatus = STATUS.ABANDON ticket.comments.push name : "admin" kind : "danger" content : content date : Date.now() ticket.status = targetStatus ticket.save (err)-> #debuglog "change to ticket applied" return return , 2000
true
mongoose = require('mongoose') Ticket = mongoose.model('Ticket') crypto = require 'crypto' STATUS = require "../enums/ticket_status" MAX_ATTEMPTS_BEFORE_ABANDON = 16 MAX_TIME_ALLOWED_FOR_PROCESSING = 1000 * 60 * 60 debuglog = require("debug")("ticketman:controller:ticket") # list tickets # GET / # GET /tickets exports.index = (req, res, next)-> debuglog "index" res.render 'tickets/index', title: 'All Tickets' tickets : [] return exports.list = (req, res, next)-> debuglog "list req.query: %j", req.query query = Ticket.paginate(req.query || {}, '_id').select('-comments -content') if req.query.status? query.where status : req.query.status query.execPagination (err, result)-> return next err if err? result.success = true console.log "[ticket::list] dump result:" console.dir result res.json result return exports.count = (req, res, next)-> result = {} Ticket.count (err, count)-> next err if err? result.all = count Ticket.count {status: STATUS.PENDING}, (err, count)-> next err if err? result[STATUS.PENDING] = count Ticket.count {status: STATUS.PROCESSING}, (err, count)-> next err if err? result[STATUS.PROCESSING] = count Ticket.count {status: STATUS.COMPLETE}, (err, count)-> next err if err? result[STATUS.COMPLETE] = count Ticket.count {status: STATUS.ABANDON}, (err, count)-> next err if err? result[STATUS.ABANDON] = count res.json result return return return return return return # GET /tickets/:id exports.show = (req, res, next)-> debuglog "show" id = String(req.params.id || '') return next() unless id? Ticket.findById id, (err, ticket)-> return next err if err? res.render 'tickets/show', title: 'All Tickets' ticket : ticket return return # POST /api/tickets/new exports.create = (req, res, next)-> debuglog "create" title = (req.body||{}).title #md5 = crypto.createHash('md5') #md5.update(title||'') #req.body.token = mdPI:KEY:<KEY>END_PI.PI:KEY:<KEY>END_PI('hex') req.body.token = PI:KEY:<KEY>END_PI('mdPI:KEY:<KEY>END_PI(title).PI:KEY:<KEY>END_PI('hex').PI:KEY:<KEY>END_PI() ticket = new Ticket(req.body) ticket.save (err)=> if err? return res.json success : false error : err.toString() else return res.json success : true ticket : ticket return # PUT /api/tickets/assign exports.assign = (req, res, next)-> debuglog "assign, req.worker:%j", req.worker req.body.worker = req.worker.name Ticket.arrangeAssignment req.body, (err, ticket) -> return next(err) if err? unless ticket? return res.json success : false error : "no pending ticket of #{req.body.category}" # clear comments when assign ticket ticket.comments = [] #console.log "!!!! before assign" #console.dir ticket #ticket = JSON.stringify(ticket) #ticket = JSON.parse(ticket) return res.json success : true ticket : ticket return # PUT /api/tickets/:id/comment exports.comment = (req, res, next)-> id = req.params.id || '' return next() unless id? req.body.name = req.worker.name Ticket.addComment id, req.body, (err, ticket)-> return next(err) if err? unless ticket? return res.json success : false error : "no commented ticket of #{id}" return res.json success : true ticket : ticket return # PUT /api/tickets/:id/complete exports.complete = (req, res, next)-> id = String(req.params.id || '') return next() unless id? req.body.id = id Ticket.changeStatus req.body, STATUS.COMPLETE, (err, ticket)-> return next(err) if err? return next() unless ticket? return res.json ticket return # PUT /api/tickets/:id/giveup exports.giveup = (req, res, next)-> id = String(req.params.id || '') return next() unless id? req.body.id = id comment = name: req.body.name || req.worker.name kind: "danger" content : req.body.reason || "#{req.worker.name} fail to process this ticket" Ticket.addComment id, comment, (err, ticket)-> return next(err) if err? unless ticket? return res.json success : false error : "missing ticket of #{id}" # abandon ticket if exceed max attempts targetStatus = if ticket.attempts < MAX_ATTEMPTS_BEFORE_ABANDON then STATUS.PENDING else STATUS.ABANDON Ticket.changeStatus req.body, targetStatus, (err, ticket)-> return next(err) if err? return next() unless ticket? ticket.update {$inc: {attempts:1}}, (err, numberAffected)-> return next(err) if err? ticket.attempts = numberAffected return res.json ticket return return return # PUT /tickets/:id/abandon exports.abandon = (req, res, next)-> id = String(req.params.id || '') return next() unless id? Ticket.findById id, (err, ticket)-> return next err if err? return next() unless ticket? return next(new Error "only pending ticket could be abandoned") unless ticket.status is STATUS.PENDING Ticket.changeStatus {id : ticket.id}, STATUS.ABANDON, (err, ticket)-> return next err if err? return next() unless ticket? return res.redirect "/tickets" return return # PUT /tickets/:id/comment exports.adminComment = (req, res, next)-> id = String(req.params.id || '') return next() unless id? req.body.content = req.body.content.trim() console.log "[ticket::==========] req.body.content:#{req.body.content}" return next(new Error "please say something") unless req.body.content req.body.kind = "warning" req.body.name = "admin" Ticket.addComment id, req.body, (err, ticket)-> return next(err) if err? return next() unless ticket? return res.redirect "/tickets/#{id}" return #GET /tickets/:token/status exports.showStatus = (req, res, next) -> token = req.params.token unless token res.json "success":false "error": "missing param token" return query = { token: token } Ticket.findOne query, (err, ticket) -> if err? res.json "success":false "error": "#{err}" return data = "success": true if ticket? data['result'] = id: ticket.id status: ticket.status else data['result'] = null return res.json data return # routine: clean up overtime processing tickets setInterval ()-> #debuglog "clean up overtime processing tickets" query = $and: [ {status : STATUS.PROCESSING} {updated_at : $lt : Date.now() - MAX_TIME_ALLOWED_FOR_PROCESSING} ] Ticket.findOne query, (err, ticket)-> if err? console.error "ERROR [ticket::interval::cleanup] error:#{err}" return unless ticket? #debuglog "no ticket" return #debuglog "[interval::cleanup] ticket:" #console.dir ticket if ticket.attempts < MAX_ATTEMPTS_BEFORE_ABANDON content = "ticket processing overtime, set back to retry." targetStatus = STATUS.PENDING else content = "ticket exceeds max attemption, so abandon" targetStatus = STATUS.ABANDON ticket.comments.push name : "admin" kind : "danger" content : content date : Date.now() ticket.status = targetStatus ticket.save (err)-> #debuglog "change to ticket applied" return return , 2000
[ { "context": "###\n© Copyright 2013-2014 Stephan Jorek <stephan.jorek@gmail.com> \n\nLicensed under the A", "end": 39, "score": 0.9998947381973267, "start": 26, "tag": "NAME", "value": "Stephan Jorek" }, { "context": "###\n© Copyright 2013-2014 Stephan Jorek <stephan.jorek@gmail.com...
src/Action/Projector/ProjectionSheet.coffee
sjorek/goatee.js
0
### © Copyright 2013-2014 Stephan Jorek <stephan.jorek@gmail.com> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at <http://www.apache.org/licenses/LICENSE-2.0> Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ### {Processor} = require 'goatee/Action/Processor' exports = module?.exports ? this ## ProjectionSheet # # @class # @namespace goatee.Action.Engine exports.ProjectionSheet = class ProjectionSheet extends Processor
146238
### © Copyright 2013-2014 <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. ### {Processor} = require 'goatee/Action/Processor' exports = module?.exports ? this ## ProjectionSheet # # @class # @namespace goatee.Action.Engine exports.ProjectionSheet = class ProjectionSheet extends Processor
true
### © Copyright 2013-2014 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. ### {Processor} = require 'goatee/Action/Processor' exports = module?.exports ? this ## ProjectionSheet # # @class # @namespace goatee.Action.Engine exports.ProjectionSheet = class ProjectionSheet extends Processor
[ { "context": "# Tapster 3 Assembly\n# (c) 2020 Jason R. Huggins\n# It's okay to use CoffeeScript ☕\n\n# No, really, ", "end": 48, "score": 0.999778151512146, "start": 32, "tag": "NAME", "value": "Jason R. Huggins" } ]
public/script/tapster-3.coffee
tapsterbot/construct
0
# Tapster 3 Assembly # (c) 2020 Jason R. Huggins # It's okay to use CoffeeScript ☕ # No, really, pi is wrong Math.TAU = Math.PI*2 arm_offset = Math.acos(69.912/70) / Math.TAU * 360 ceiling = 190 servo_height_offset = (-28.5 / 2) - 5 servo_width_offset = 44.6 / 2 end_effector_offset = 7.50 upper_arm_joint_width_offset = 23.50 / 2 u_fork_width = 13.30 end_effector = {x: 0, y: 0, z: -150} a = { alpha: 38.097759123032375 - arm_offset, beta: 91.23475984385213 - arm_offset, gamma: 0 } b = { alpha: 38.097759123032375 - arm_offset, beta: 91.23475984385213 - arm_offset, gamma: 0 } c = { alpha: 38.097759123032375 - arm_offset, beta: 91.23475984385213 - arm_offset, gamma: 0 } part name: 'plane' shape: 'floor' texture: 'image/wood-floor-2.jpg' transparent: true opacity: 0.6 visible: true size: [400, 400, 2] translate: [0, 0, 0 ] rotate: [0, 0, 0] part name: 'base' source: '3d/tapster-3/base.stl' color: 0xDF1F1F translate: [0, 0, ceiling] rotate: [0, 180, 210] part name: 'end-effector' source: '3d/tapster-3/end_effector.stl' color: 0xDF1F1F translate: [end_effector.x, end_effector.y, ceiling + servo_height_offset - end_effector_offset + end_effector.z] rotate: [0, 0, 0] group name: 'tapster-3' class: 'robot' specs: { end_offset: -25 fixed_offset: -50 end_radius: 133.5 fixed_radius: 70 ceiling: 190 servo_height_offset: (-28.5 / 2) - 5 end_effector_offset: 7.50 arm_offset: Math.acos(69.912/70) } group name: 'arm-assembly-1' translate: [0, 0, ceiling] rotate: [0, 0, 0] visible: true parts: [ { name: 'servo-1' source: '3d/tapster-3/xl-430.stl' color: 0x666666 visible: true #translate: [-0, -14.75 - 3.25 - 32, -28.5 / 2 - 5] translate: [0, -50, servo_height_offset] rotate: [0, 90, 180] } { group: name: "base-screws-1" translate: [0, 0, 0] rotate: [0, 0, 0] visible: true parts: [ # Left side - screws { name: 'shms-m2.5-14-001' source: '3d/tapster-3/socket-head-machine-screw-M2.5-14.stl' color: 0x666666 visible: true translate: [-servo_width_offset + 17.5, -14.75 - 3.35, servo_height_offset + 11] rotate: [0, -90, 0] } { name: 'shms-m2.5-14-002' source: '3d/tapster-3/socket-head-machine-screw-M2.5-14.stl' color: 0x666666 visible: true translate: [-servo_width_offset + 17.5, -14.75 - 3.35, servo_height_offset - 11] rotate: [0, -90, 0] } # Right side - screws { name: 'shms-m2.5-14-003' source: '3d/tapster-3/socket-head-machine-screw-M2.5-14.stl' color: 0x666666 visible: true translate: [servo_width_offset - 17.5, -14.75 - 3.35, servo_height_offset + 11] rotate: [0, 90, 0] } { name: 'shms-m2.5-14-004' source: '3d/tapster-3/socket-head-machine-screw-M2.5-14.stl' color: 0x666666 visible: true translate: [servo_width_offset - 17.5, -14.75 - 3.35, servo_height_offset - 11] rotate: [0, 90, 0] } ] } { group: name: "upper-arm-assembly-1" translate: [0, -50, servo_height_offset] rotate: [a.alpha, 0, 0] parts: [ { name: 'arm-1' source: '3d/tapster-3/arm.stl' color: 0xDF1F1F visible: true translate: [0, 0 , 0] rotate: [0, 0, 0] } # Left side - screws { name: 'shms-m2-04-001' source: '3d/tapster-3/socket-head-machine-screw-M2-04.stl' color: 0x666666 visible: true translate: [-servo_width_offset + 6, 0 , 8] rotate: [90, -90, 0] } { name: 'shms-m2-04-002' source: '3d/tapster-3/socket-head-machine-screw-M2-04.stl' color: 0x666666 visible: true translate: [-servo_width_offset + 6, -8 , 0] rotate: [90, -90, 0] } { name: 'shms-m2-04-003' source: '3d/tapster-3/socket-head-machine-screw-M2-04.stl' color: 0x666666 visible: true translate: [-servo_width_offset + 6, 0 , -8] rotate: [90, -90, 0] } { name: 'shms-m2-04-004' source: '3d/tapster-3/socket-head-machine-screw-M2-04.stl' color: 0x666666 visible: true translate: [-servo_width_offset + 6, 8 , 0] rotate: [90, -90, 0] } # Right side - screws { name: 'shms-m2-04-005' source: '3d/tapster-3/socket-head-machine-screw-M2-04.stl' color: 0x666666 visible: true translate: [servo_width_offset - 6, 0 , 8] rotate: [90, 90, 0] } { name: 'shms-m2-04-006' source: '3d/tapster-3/socket-head-machine-screw-M2-04.stl' color: 0x666666 visible: true translate: [servo_width_offset - 6, 8 , 0] rotate: [90, 90, 0] } { name: 'shms-m2-04-007' source: '3d/tapster-3/socket-head-machine-screw-M2-04.stl' color: 0x666666 visible: true translate: [servo_width_offset - 6, 0 , -8] rotate: [90, 90, 0] } { name: 'shms-m2-04-008' source: '3d/tapster-3/socket-head-machine-screw-M2-04.stl' color: 0x666666 visible: true translate: [servo_width_offset - 6, -8 , 0] rotate: [90, 90, 0] } { group: name: "upper-u-joint-assembly-1" translate: [0, -70, -3.5] rotate: [270 - a.beta, 0, 0] visible: true parts: [ { name: 'u-joint-fork-001' source: '3d/tapster-3/u_joint_fork.stl' color: 0xDF1F1F visible: true translate: [-upper_arm_joint_width_offset, 0 , 0] rotate: [0, 0, 90] } { name: 'u-joint-fork-002' source: '3d/tapster-3/u_joint_fork.stl' color: 0xDF1F1F visible: true translate: [upper_arm_joint_width_offset, 0 , 0] rotate: [0, 0, -90] } { name: 'bhcs-m3-18-001' source: '3d/tapster-3/button-head-cap-screw-M3-18.stl' color: 0x666666 visible: true translate: [-upper_arm_joint_width_offset - 13.5, 11.35, 0] rotate: [90, 0, 0] } { name: 'bhcs-m3-18-002' source: '3d/tapster-3/button-head-cap-screw-M3-18.stl' color: 0x666666 visible: true translate: [upper_arm_joint_width_offset + 13.5, 11.35, 0] rotate: [90, 0, 0] } { name: 'hn-m3-nl-001' source: '3d/tapster-3/hex-nut-m3-nyloc.stl' color: 0x777777 visible: true translate: [-upper_arm_joint_width_offset - 13.5, 13.30/2 , 0] rotate: [-90, 0, 0] } { name: 'hn-m3-nl-002' source: '3d/tapster-3/hex-nut-m3-nyloc.stl' color: 0x777777 visible: true translate: [upper_arm_joint_width_offset + 13.5, 13.30/2 , 0] rotate: [-90, 0, 0] } ] } { group: name: "lower-u-joint-assembly-1" translate: [0, -70, -3.5] rotate: [90 - a.beta, -a.gamma, 0] visible: true parts: [ group: name: "lower-u-joint-rotation-axis-1" translate: [0, 0, -133.5] rotate: [0, a.gamma, 0] parts: [ { name: 'u-joint-fork-003' source: '3d/tapster-3/u_joint_fork.stl' color: 0xDF1F1F visible: true translate: [-upper_arm_joint_width_offset, 0, 0] rotate: [0, 0, 90] } { name: 'u-joint-fork-004' source: '3d/tapster-3/u_joint_fork.stl' color: 0xDF1F1F visible: true translate: [upper_arm_joint_width_offset, 0, 0] rotate: [0, 0, -90] } { name: 'bhcs-m3-18-003' source: '3d/tapster-3/button-head-cap-screw-M3-18.stl' color: 0x666666 visible: true translate: [-upper_arm_joint_width_offset - 13.5, -11.35 , 0] rotate: [-90, 0, 0] } { name: 'bhcs-m3-18-004' source: '3d/tapster-3/button-head-cap-screw-M3-18.stl' color: 0x666666 visible: true translate: [upper_arm_joint_width_offset + 13.5, -11.35 , 0] rotate: [-90, 0, 0] } { name: 'hn-m3-nl-003' source: '3d/tapster-3/hex-nut-m3-nyloc.stl' color: 0x777777 visible: true translate: [-upper_arm_joint_width_offset - 13.5, -13.30/2 , 0] rotate: [90, 0, 0] } { name: 'hn-m3-nl-004' source: '3d/tapster-3/hex-nut-m3-nyloc.stl' color: 0x777777 visible: true translate: [upper_arm_joint_width_offset + 13.5, -13.30/2 , 0] rotate: [90, 0, 0] } ] ] } { group: name: "linkage-assembly-1" translate: [0, -70, -3.5] rotate: [0, 0, 0] visible: true parts: [ group: name: "linkage-rotation-axis-1" translate: [-upper_arm_joint_width_offset - 13.5, 0, 0] rotate: [90 - a.beta, -a.gamma, 0] parts: [ { name: 'rod-118mm-001' source: '3d/tapster-3/rod-118mm.stl' color: 0x666666 visible: true translate: [0, 0 , -7.75] rotate: [180, 0, 0] } { name: 'rod-end-001' source: '3d/tapster-3/rod-end.stl' color: 0x333333 visible: true translate: [0, 0 , 0] rotate: [0, 0, 0] } { name: 'ball-001' source: '3d/tapster-3/traxxas-5347-hollow-ball.stl' color: 0xAAAAAA visible: true translate: [0, 0 , 0] rotate: [0, 0, 0] } { name: 'rod-end-002' source: '3d/tapster-3/rod-end.stl' color: 0x333333 visible: true translate: [0, 0 , -133.5] rotate: [0, 180, 0] } { name: 'ball-002' source: '3d/tapster-3/traxxas-5347-hollow-ball.stl' color: 0xAAAAAA visible: true translate: [0, 0 , -133.5] rotate: [0, 0, 0] } ] ] } { group: name: "linkage-assembly-2" translate: [0, -70, -3.5] rotate: [0, 0, 0] visible: true parts: [ group: name: "linkage-rotation-axis-2" translate: [upper_arm_joint_width_offset + 13.5, 0, 0] rotate: [90 - a.beta, -a.gamma, 0] parts: [ { name: 'rod-118mm-002' source: '3d/tapster-3/rod-118mm.stl' color: 0x666666 visible: true translate: [0, 0 , -7.75] rotate: [180, 0, 0] } { name: 'rod-end-003' source: '3d/tapster-3/rod-end.stl' color: 0x333333 visible: true translate: [0, 0 , 0] rotate: [0, 0, 0] } { name: 'ball-003' source: '3d/tapster-3/traxxas-5347-hollow-ball.stl' color: 0xAAAAAA visible: true translate: [0, 0 , 0] rotate: [0, 0, 0] } { name: 'rod-end-004' source: '3d/tapster-3/rod-end.stl' color: 0x333333 visible: true translate: [0, 0 , -133.5] rotate: [0, 180, 0] } { name: 'ball-004' source: '3d/tapster-3/traxxas-5347-hollow-ball.stl' color: 0xAAAAAA visible: true translate: [0, 0 , -133.5] rotate: [0, 0, 0] } ] ] } ] } ] group name: 'arm-assembly-2' translate: [0, 0, ceiling] rotate: [0, 0, 120] visible: true parts: [ { name: 'servo-2' source: '3d/tapster-3/xl-430.stl' color: 0x666666 visible: true translate: [0, -50, servo_height_offset] rotate: [0, 90, 180] } { group: name: "base-screws-2" translate: [0, 0, 0] rotate: [0, 0, 0] visible: true parts: [ # Left side - screws { name: 'shms-m2.5-14-005' source: '3d/tapster-3/socket-head-machine-screw-M2.5-14.stl' color: 0x666666 visible: true translate: [-servo_width_offset + 17.5, -14.75 - 3.35, servo_height_offset + 11] rotate: [0, -90, 0] } { name: 'shms-m2.5-14-006' source: '3d/tapster-3/socket-head-machine-screw-M2.5-14.stl' color: 0x666666 visible: true translate: [-servo_width_offset + 17.5, -14.75 - 3.35, servo_height_offset - 11] rotate: [0, -90, 0] } # Right side - screws { name: 'shms-m2.5-14-007' source: '3d/tapster-3/socket-head-machine-screw-M2.5-14.stl' color: 0x666666 visible: true translate: [servo_width_offset - 17.5, -14.75 - 3.35, servo_height_offset + 11] rotate: [0, 90, 0] } { name: 'shms-m2.5-14-008' source: '3d/tapster-3/socket-head-machine-screw-M2.5-14.stl' color: 0x666666 visible: true translate: [servo_width_offset - 17.5, -14.75 - 3.35, servo_height_offset - 11] rotate: [0, 90, 0] } ] } { group: name: "upper-arm-assembly-2" translate: [0, -50, servo_height_offset] rotate: [b.alpha, 0, 0] parts: [ { name: 'arm-2' source: '3d/tapster-3/arm.stl' color: 0xDF1F1F visible: true translate: [0, 0 , 0] rotate: [0, 0, 0] } # Left side - screws { name: 'shms-m2-04-009' source: '3d/tapster-3/socket-head-machine-screw-M2-04.stl' color: 0x666666 visible: true translate: [-servo_width_offset + 6, 0 , 8] rotate: [90, -90, 0] } { name: 'shms-m2-04-010' source: '3d/tapster-3/socket-head-machine-screw-M2-04.stl' color: 0x666666 visible: true translate: [-servo_width_offset + 6, -8 , 0] rotate: [90, -90, 0] } { name: 'shms-m2-04-011' source: '3d/tapster-3/socket-head-machine-screw-M2-04.stl' color: 0x666666 visible: true translate: [-servo_width_offset + 6, 0 , -8] rotate: [90, -90, 0] } { name: 'shms-m2-04-012' source: '3d/tapster-3/socket-head-machine-screw-M2-04.stl' color: 0x666666 visible: true translate: [-servo_width_offset + 6, 8 , 0] rotate: [90, -90, 0] } # Right side - screws { name: 'shms-m2-04-013' source: '3d/tapster-3/socket-head-machine-screw-M2-04.stl' color: 0x666666 visible: true translate: [servo_width_offset - 6, 0 , 8] rotate: [90, 90, 0] } { name: 'shms-m2-04-014' source: '3d/tapster-3/socket-head-machine-screw-M2-04.stl' color: 0x666666 visible: true translate: [servo_width_offset - 6, 8 , 0] rotate: [90, 90, 0] } { name: 'shms-m2-04-015' source: '3d/tapster-3/socket-head-machine-screw-M2-04.stl' color: 0x666666 visible: true translate: [servo_width_offset - 6, 0 , -8] rotate: [90, 90, 0] } { name: 'shms-m2-04-016' source: '3d/tapster-3/socket-head-machine-screw-M2-04.stl' color: 0x666666 visible: true translate: [servo_width_offset - 6, -8 , 0] rotate: [90, 90, 0] } { group: name: "upper-u-joint-assembly-2" translate: [0, -70, -3.5] rotate: [270 - b.beta, 0, 0] visible: true parts: [ { name: 'u-joint-fork-005' source: '3d/tapster-3/u_joint_fork.stl' color: 0xDF1F1F visible: true translate: [-upper_arm_joint_width_offset, 0 , 0] rotate: [0, 0, 90] } { name: 'u-joint-fork-006' source: '3d/tapster-3/u_joint_fork.stl' color: 0xDF1F1F visible: true translate: [upper_arm_joint_width_offset, 0 , 0] rotate: [0, 0, -90] } { name: 'bhcs-m3-18-005' source: '3d/tapster-3/button-head-cap-screw-M3-18.stl' color: 0x666666 visible: true translate: [-upper_arm_joint_width_offset - 13.5, 11.35 , 0] rotate: [90, 0, 0] } { name: 'bhcs-m3-18-006' source: '3d/tapster-3/button-head-cap-screw-M3-18.stl' color: 0x666666 visible: true translate: [upper_arm_joint_width_offset + 13.5, 11.35 , 0] rotate: [90, 0, 0] } { name: 'hn-m3-nl-005' source: '3d/tapster-3/hex-nut-m3-nyloc.stl' color: 0x777777 visible: true translate: [-upper_arm_joint_width_offset - 13.5, 13.30/2 , 0] rotate: [-90, 0, 0] } { name: 'hn-m3-nl-006' source: '3d/tapster-3/hex-nut-m3-nyloc.stl' color: 0x777777 visible: true translate: [upper_arm_joint_width_offset + 13.5, 13.30/2 , 0] rotate: [-90, 0, 0] } ] } { group: name: "lower-u-joint-assembly-2" translate: [0, -70, -3.5] rotate: [90 - b.beta, -b.gamma, 0] visible: true parts: [ group: name: "lower-u-joint-rotation-axis-2" translate: [0, 0, -133.5] rotate: [0, b.gamma, 0] parts: [ { name: 'u-joint-fork-007' source: '3d/tapster-3/u_joint_fork.stl' color: 0xDF1F1F visible: true translate: [-upper_arm_joint_width_offset, 0, 0] rotate: [0, 0, 90] } { name: 'u-joint-fork-008' source: '3d/tapster-3/u_joint_fork.stl' color: 0xDF1F1F visible: true translate: [upper_arm_joint_width_offset, 0, 0] rotate: [0, 0, -90] } { name: 'bhcs-m3-18-007' source: '3d/tapster-3/button-head-cap-screw-M3-18.stl' color: 0x666666 visible: true translate: [-upper_arm_joint_width_offset - 13.5, -11.35 , 0] rotate: [-90, 0, 0] } { name: 'bhcs-m3-18-008' source: '3d/tapster-3/button-head-cap-screw-M3-18.stl' color: 0x666666 visible: true translate: [upper_arm_joint_width_offset + 13.5, -11.35 , 0] rotate: [-90, 0, 0] } { name: 'hn-m3-nl-007' source: '3d/tapster-3/hex-nut-m3-nyloc.stl' color: 0x777777 visible: true translate: [-upper_arm_joint_width_offset - 13.5, -13.30/2 , 0] rotate: [90, 0, 0] } { name: 'hn-m3-nl-008' source: '3d/tapster-3/hex-nut-m3-nyloc.stl' color: 0x777777 visible: true translate: [upper_arm_joint_width_offset + 13.5, -13.30/2 , 0] rotate: [90, 0, 0] } ] ] } { group: name: "linkage-assembly-3" translate: [0, -70, -3.5] rotate: [0, 0, 0] parts: [ group: name: "linkage-rotation-axis-3" translate: [-upper_arm_joint_width_offset - 13.5, 0, 0] rotate: [90 - b.beta, -b.gamma, 0] parts: [ { name: 'rod-118mm-003' source: '3d/tapster-3/rod-118mm.stl' color: 0x666666 visible: true translate: [0, 0 , -7.75] rotate: [180, 0, 0] } { name: 'rod-end-005' source: '3d/tapster-3/rod-end.stl' color: 0x333333 visible: true translate: [0, 0 , 0] rotate: [0, 0, 0] } { name: 'ball-005' source: '3d/tapster-3/traxxas-5347-hollow-ball.stl' color: 0xAAAAAA visible: true translate: [0, 0 , 0] rotate: [0, 0, 0] } { name: 'rod-end-006' source: '3d/tapster-3/rod-end.stl' color: 0x333333 visible: true translate: [0, 0 , -133.5] rotate: [0, 180, 0] } { name: 'ball-006' source: '3d/tapster-3/traxxas-5347-hollow-ball.stl' color: 0xAAAAAA visible: true translate: [0, 0 , -133.5] rotate: [0, 0, 0] } ] ] } { group: name: "linkage-assembly-4" translate: [0, -70, -3.5] rotate: [0, 0, 0] parts: [ group: name: "linkage-rotation-axis-4" translate: [upper_arm_joint_width_offset + 13.5, 0, 0] rotate: [90 - b.beta, -b.gamma, 0] parts: [ { name: 'rod-118mm-004' source: '3d/tapster-3/rod-118mm.stl' color: 0x666666 visible: true translate: [0, 0 , -7.75] rotate: [180, 0, 0] } { name: 'rod-end-007' source: '3d/tapster-3/rod-end.stl' color: 0x333333 visible: true translate: [0, 0 , 0] rotate: [0, 0, 0] } { name: 'ball-007' source: '3d/tapster-3/traxxas-5347-hollow-ball.stl' color: 0xAAAAAA visible: true translate: [0, 0 , 0] rotate: [0, 0, 0] } { name: 'rod-end-008' source: '3d/tapster-3/rod-end.stl' color: 0x333333 visible: true translate: [0, 0 , -133.5] rotate: [0, 180, 0] } { name: 'ball-008' source: '3d/tapster-3/traxxas-5347-hollow-ball.stl' color: 0xAAAAAA visible: true translate: [0, 0 , -133.5] rotate: [0, 0, 0] } ] ] } ] } ] group name: 'arm-assembly-3' translate: [0, 0, ceiling] rotate: [0, 0, - 120] visible: true parts: [ { name: 'servo-3' source: '3d/tapster-3/xl-430.stl' color: 0x666666 visible: true translate: [0, -50, servo_height_offset] rotate: [0, 90, 180] } { group: name: "base-screws-3" translate: [0, 0, 0] rotate: [0, 0, 0] visible: true parts: [ # Left side - screws { name: 'shms-m2.5-14-009' source: '3d/tapster-3/socket-head-machine-screw-M2.5-14.stl' color: 0x666666 visible: true translate: [-servo_width_offset + 17.5, -14.75 - 3.35, servo_height_offset + 11] rotate: [0, -90, 0] } { name: 'shms-m2.5-14-010' source: '3d/tapster-3/socket-head-machine-screw-M2.5-14.stl' color: 0x666666 visible: true translate: [-servo_width_offset + 17.5, -14.75 - 3.35, servo_height_offset - 11] rotate: [0, -90, 0] } # Right side - screws { name: 'shms-m2.5-14-011' source: '3d/tapster-3/socket-head-machine-screw-M2.5-14.stl' color: 0x666666 visible: true translate: [servo_width_offset - 17.5, -14.75 - 3.35, servo_height_offset + 11] rotate: [0, 90, 0] } { name: 'shms-m2.5-14-012' source: '3d/tapster-3/socket-head-machine-screw-M2.5-14.stl' color: 0x666666 visible: true translate: [servo_width_offset - 17.5, -14.75 - 3.35, servo_height_offset - 11] rotate: [0, 90, 0] } ] } { group: name: "upper-arm-assembly-3" translate: [0, -50, servo_height_offset] rotate: [c.alpha, 0, 0] parts: [ { name: 'arm-3' source: '3d/tapster-3/arm.stl' color: 0xDF1F1F visible: true translate: [0, 0 , 0] rotate: [0, 0, 0] } # Left side - screws { name: 'shms-m2-04-017' source: '3d/tapster-3/socket-head-machine-screw-M2-04.stl' color: 0x666666 visible: true translate: [-servo_width_offset + 6, 0 , 8] rotate: [90, -90, 0] } { name: 'shms-m2-04-018' source: '3d/tapster-3/socket-head-machine-screw-M2-04.stl' color: 0x666666 visible: true translate: [-servo_width_offset + 6, -8 , 0] rotate: [90, -90, 0] } { name: 'shms-m2-04-019' source: '3d/tapster-3/socket-head-machine-screw-M2-04.stl' color: 0x666666 visible: true translate: [-servo_width_offset + 6, 0 , -8] rotate: [90, -90, 0] } { name: 'shms-m2-04-020' source: '3d/tapster-3/socket-head-machine-screw-M2-04.stl' color: 0x666666 visible: true translate: [-servo_width_offset + 6, 8 , 0] rotate: [90, -90, 0] } # Right side - screws { name: 'shms-m2-04-021' source: '3d/tapster-3/socket-head-machine-screw-M2-04.stl' color: 0x666666 visible: true translate: [servo_width_offset - 6, 0 , 8] rotate: [90, 90, 0] } { name: 'shms-m2-04-022' source: '3d/tapster-3/socket-head-machine-screw-M2-04.stl' color: 0x666666 visible: true translate: [servo_width_offset - 6, 8 , 0] rotate: [90, 90, 0] } { name: 'shms-m2-04-023' source: '3d/tapster-3/socket-head-machine-screw-M2-04.stl' color: 0x666666 visible: true translate: [servo_width_offset - 6, 0 , -8] rotate: [90, 90, 0] } { name: 'shms-m2-04-024' source: '3d/tapster-3/socket-head-machine-screw-M2-04.stl' color: 0x666666 visible: true translate: [servo_width_offset - 6, -8 , 0] rotate: [90, 90, 0] } { group: name: "upper-u-joint-assembly-3" translate: [0, -70, -3.5] rotate: [270 - c.beta, 0, 0] visible: true parts: [ { name: 'u-joint-fork-009' source: '3d/tapster-3/u_joint_fork.stl' color: 0xDF1F1F visible: true translate: [-upper_arm_joint_width_offset, 0 , 0] rotate: [0, 0, 90] } { name: 'u-joint-fork-010' source: '3d/tapster-3/u_joint_fork.stl' color: 0xDF1F1F visible: true translate: [upper_arm_joint_width_offset, 0 , 0] rotate: [0, 0, -90] } { name: 'bhcs-m3-18-009' source: '3d/tapster-3/button-head-cap-screw-M3-18.stl' color: 0x666666 visible: true translate: [-upper_arm_joint_width_offset - 13.5, 11.35 , 0] rotate: [90, 0, 0] } { name: 'bhcs-m3-18-010' source: '3d/tapster-3/button-head-cap-screw-M3-18.stl' color: 0x666666 visible: true translate: [upper_arm_joint_width_offset + 13.5, 11.35 , 0] rotate: [90, 0, 0] } { name: 'hn-m3-nl-009' source: '3d/tapster-3/hex-nut-m3-nyloc.stl' color: 0x777777 visible: true translate: [-upper_arm_joint_width_offset - 13.5, 13.30/2 , 0] rotate: [-90, 0, 0] } { name: 'hn-m3-nl-010' source: '3d/tapster-3/hex-nut-m3-nyloc.stl' color: 0x777777 visible: true translate: [upper_arm_joint_width_offset + 13.5, 13.30/2 , 0] rotate: [-90, 0, 0] } ] } { group: name: "lower-u-joint-assembly-3" translate: [0, -70, -3.5] rotate: [90 - c.beta, -c.gamma, 0] visible: true parts: [ group: name: "lower-u-joint-rotation-axis-3" translate: [0, 0, -133.5] rotate: [0, c.gamma, 0] parts: [ { name: 'u-joint-fork-011' source: '3d/tapster-3/u_joint_fork.stl' color: 0xDF1F1F visible: true translate: [-upper_arm_joint_width_offset, 0, 0] rotate: [0, 0, 90] } { name: 'u-joint-fork-012' source: '3d/tapster-3/u_joint_fork.stl' color: 0xDF1F1F visible: true translate: [upper_arm_joint_width_offset, 0, 0] rotate: [0, 0, -90] } { name: 'bhcs-m3-18-011' source: '3d/tapster-3/button-head-cap-screw-M3-18.stl' color: 0x666666 visible: true translate: [-upper_arm_joint_width_offset - 13.5, -11.35 , 0] rotate: [-90, 0, 0] } { name: 'bhcs-m3-18-012' source: '3d/tapster-3/button-head-cap-screw-M3-18.stl' color: 0x666666 visible: true translate: [upper_arm_joint_width_offset + 13.5, -11.35 , 0] rotate: [-90, 0, 0] } { name: 'hn-m3-nl-011' source: '3d/tapster-3/hex-nut-m3-nyloc.stl' color: 0x777777 visible: true translate: [-upper_arm_joint_width_offset - 13.5, -13.30/2 , 0] rotate: [90, 0, 0] } { name: 'hn-m3-nl-012' source: '3d/tapster-3/hex-nut-m3-nyloc.stl' color: 0x777777 visible: true translate: [upper_arm_joint_width_offset + 13.5, -13.30/2 , 0] rotate: [90, 0, 0] } ] ] } { group: name: "linkage-assembly-5" translate: [0, -70, -3.5] rotate: [0, 0, 0] parts: [ group: name: "linkage-rotation-axis-5" translate: [-upper_arm_joint_width_offset - 13.5, 0, 0] rotate: [90 - c.beta, -c.gamma, 0] parts: [ { name: 'rod-118mm-005' source: '3d/tapster-3/rod-118mm.stl' color: 0x666666 visible: true translate: [0, 0 , -7.75] rotate: [180, 0, 0] } { name: 'rod-end-09' source: '3d/tapster-3/rod-end.stl' color: 0x333333 visible: true translate: [0, 0 , 0] rotate: [0, 0, 0] } { name: 'ball-009' source: '3d/tapster-3/traxxas-5347-hollow-ball.stl' color: 0xAAAAAA visible: true translate: [0, 0 , 0] rotate: [0, 0, 0] } { name: 'rod-end-010' source: '3d/tapster-3/rod-end.stl' color: 0x333333 visible: true translate: [0, 0 , -133.5] rotate: [0, 180, 0] } { name: 'ball-010' source: '3d/tapster-3/traxxas-5347-hollow-ball.stl' color: 0xAAAAAA visible: true translate: [0, 0 , -133.5] rotate: [0, 0, 0] } ] ] } { group: name: "linkage-assembly-6" translate: [0, -70, -3.5] rotate: [0, 0, 0] parts: [ group: name: "linkage-rotation-axis-6" translate: [upper_arm_joint_width_offset + 13.5, 0, 0] rotate: [90 - c.beta, -c.gamma, 0] parts: [ { name: 'rod-118mm-006' source: '3d/tapster-3/rod-118mm.stl' color: 0x666666 visible: true translate: [0, 0 , -7.75] rotate: [180, 0, 0] } { name: 'rod-end-011' source: '3d/tapster-3/rod-end.stl' color: 0x333333 visible: true translate: [0, 0 , 0] rotate: [0, 0, 0] } { name: 'ball-011' source: '3d/tapster-3/traxxas-5347-hollow-ball.stl' color: 0xAAAAAA visible: true translate: [0, 0 , 0] rotate: [0, 0, 0] } { name: 'rod-end-012' source: '3d/tapster-3/rod-end.stl' color: 0x333333 visible: true translate: [0, 0 , -133.5] rotate: [0, 180, 0] } { name: 'ball-012' source: '3d/tapster-3/traxxas-5347-hollow-ball.stl' color: 0xAAAAAA visible: true translate: [0, 0 , -133.5] rotate: [0, 0, 0] } ] ] } ] } ]
136097
# Tapster 3 Assembly # (c) 2020 <NAME> # It's okay to use CoffeeScript ☕ # No, really, pi is wrong Math.TAU = Math.PI*2 arm_offset = Math.acos(69.912/70) / Math.TAU * 360 ceiling = 190 servo_height_offset = (-28.5 / 2) - 5 servo_width_offset = 44.6 / 2 end_effector_offset = 7.50 upper_arm_joint_width_offset = 23.50 / 2 u_fork_width = 13.30 end_effector = {x: 0, y: 0, z: -150} a = { alpha: 38.097759123032375 - arm_offset, beta: 91.23475984385213 - arm_offset, gamma: 0 } b = { alpha: 38.097759123032375 - arm_offset, beta: 91.23475984385213 - arm_offset, gamma: 0 } c = { alpha: 38.097759123032375 - arm_offset, beta: 91.23475984385213 - arm_offset, gamma: 0 } part name: 'plane' shape: 'floor' texture: 'image/wood-floor-2.jpg' transparent: true opacity: 0.6 visible: true size: [400, 400, 2] translate: [0, 0, 0 ] rotate: [0, 0, 0] part name: 'base' source: '3d/tapster-3/base.stl' color: 0xDF1F1F translate: [0, 0, ceiling] rotate: [0, 180, 210] part name: 'end-effector' source: '3d/tapster-3/end_effector.stl' color: 0xDF1F1F translate: [end_effector.x, end_effector.y, ceiling + servo_height_offset - end_effector_offset + end_effector.z] rotate: [0, 0, 0] group name: 'tapster-3' class: 'robot' specs: { end_offset: -25 fixed_offset: -50 end_radius: 133.5 fixed_radius: 70 ceiling: 190 servo_height_offset: (-28.5 / 2) - 5 end_effector_offset: 7.50 arm_offset: Math.acos(69.912/70) } group name: 'arm-assembly-1' translate: [0, 0, ceiling] rotate: [0, 0, 0] visible: true parts: [ { name: 'servo-1' source: '3d/tapster-3/xl-430.stl' color: 0x666666 visible: true #translate: [-0, -14.75 - 3.25 - 32, -28.5 / 2 - 5] translate: [0, -50, servo_height_offset] rotate: [0, 90, 180] } { group: name: "base-screws-1" translate: [0, 0, 0] rotate: [0, 0, 0] visible: true parts: [ # Left side - screws { name: 'shms-m2.5-14-001' source: '3d/tapster-3/socket-head-machine-screw-M2.5-14.stl' color: 0x666666 visible: true translate: [-servo_width_offset + 17.5, -14.75 - 3.35, servo_height_offset + 11] rotate: [0, -90, 0] } { name: 'shms-m2.5-14-002' source: '3d/tapster-3/socket-head-machine-screw-M2.5-14.stl' color: 0x666666 visible: true translate: [-servo_width_offset + 17.5, -14.75 - 3.35, servo_height_offset - 11] rotate: [0, -90, 0] } # Right side - screws { name: 'shms-m2.5-14-003' source: '3d/tapster-3/socket-head-machine-screw-M2.5-14.stl' color: 0x666666 visible: true translate: [servo_width_offset - 17.5, -14.75 - 3.35, servo_height_offset + 11] rotate: [0, 90, 0] } { name: 'shms-m2.5-14-004' source: '3d/tapster-3/socket-head-machine-screw-M2.5-14.stl' color: 0x666666 visible: true translate: [servo_width_offset - 17.5, -14.75 - 3.35, servo_height_offset - 11] rotate: [0, 90, 0] } ] } { group: name: "upper-arm-assembly-1" translate: [0, -50, servo_height_offset] rotate: [a.alpha, 0, 0] parts: [ { name: 'arm-1' source: '3d/tapster-3/arm.stl' color: 0xDF1F1F visible: true translate: [0, 0 , 0] rotate: [0, 0, 0] } # Left side - screws { name: 'shms-m2-04-001' source: '3d/tapster-3/socket-head-machine-screw-M2-04.stl' color: 0x666666 visible: true translate: [-servo_width_offset + 6, 0 , 8] rotate: [90, -90, 0] } { name: 'shms-m2-04-002' source: '3d/tapster-3/socket-head-machine-screw-M2-04.stl' color: 0x666666 visible: true translate: [-servo_width_offset + 6, -8 , 0] rotate: [90, -90, 0] } { name: 'shms-m2-04-003' source: '3d/tapster-3/socket-head-machine-screw-M2-04.stl' color: 0x666666 visible: true translate: [-servo_width_offset + 6, 0 , -8] rotate: [90, -90, 0] } { name: 'shms-m2-04-004' source: '3d/tapster-3/socket-head-machine-screw-M2-04.stl' color: 0x666666 visible: true translate: [-servo_width_offset + 6, 8 , 0] rotate: [90, -90, 0] } # Right side - screws { name: 'shms-m2-04-005' source: '3d/tapster-3/socket-head-machine-screw-M2-04.stl' color: 0x666666 visible: true translate: [servo_width_offset - 6, 0 , 8] rotate: [90, 90, 0] } { name: 'shms-m2-04-006' source: '3d/tapster-3/socket-head-machine-screw-M2-04.stl' color: 0x666666 visible: true translate: [servo_width_offset - 6, 8 , 0] rotate: [90, 90, 0] } { name: 'shms-m2-04-007' source: '3d/tapster-3/socket-head-machine-screw-M2-04.stl' color: 0x666666 visible: true translate: [servo_width_offset - 6, 0 , -8] rotate: [90, 90, 0] } { name: 'shms-m2-04-008' source: '3d/tapster-3/socket-head-machine-screw-M2-04.stl' color: 0x666666 visible: true translate: [servo_width_offset - 6, -8 , 0] rotate: [90, 90, 0] } { group: name: "upper-u-joint-assembly-1" translate: [0, -70, -3.5] rotate: [270 - a.beta, 0, 0] visible: true parts: [ { name: 'u-joint-fork-001' source: '3d/tapster-3/u_joint_fork.stl' color: 0xDF1F1F visible: true translate: [-upper_arm_joint_width_offset, 0 , 0] rotate: [0, 0, 90] } { name: 'u-joint-fork-002' source: '3d/tapster-3/u_joint_fork.stl' color: 0xDF1F1F visible: true translate: [upper_arm_joint_width_offset, 0 , 0] rotate: [0, 0, -90] } { name: 'bhcs-m3-18-001' source: '3d/tapster-3/button-head-cap-screw-M3-18.stl' color: 0x666666 visible: true translate: [-upper_arm_joint_width_offset - 13.5, 11.35, 0] rotate: [90, 0, 0] } { name: 'bhcs-m3-18-002' source: '3d/tapster-3/button-head-cap-screw-M3-18.stl' color: 0x666666 visible: true translate: [upper_arm_joint_width_offset + 13.5, 11.35, 0] rotate: [90, 0, 0] } { name: 'hn-m3-nl-001' source: '3d/tapster-3/hex-nut-m3-nyloc.stl' color: 0x777777 visible: true translate: [-upper_arm_joint_width_offset - 13.5, 13.30/2 , 0] rotate: [-90, 0, 0] } { name: 'hn-m3-nl-002' source: '3d/tapster-3/hex-nut-m3-nyloc.stl' color: 0x777777 visible: true translate: [upper_arm_joint_width_offset + 13.5, 13.30/2 , 0] rotate: [-90, 0, 0] } ] } { group: name: "lower-u-joint-assembly-1" translate: [0, -70, -3.5] rotate: [90 - a.beta, -a.gamma, 0] visible: true parts: [ group: name: "lower-u-joint-rotation-axis-1" translate: [0, 0, -133.5] rotate: [0, a.gamma, 0] parts: [ { name: 'u-joint-fork-003' source: '3d/tapster-3/u_joint_fork.stl' color: 0xDF1F1F visible: true translate: [-upper_arm_joint_width_offset, 0, 0] rotate: [0, 0, 90] } { name: 'u-joint-fork-004' source: '3d/tapster-3/u_joint_fork.stl' color: 0xDF1F1F visible: true translate: [upper_arm_joint_width_offset, 0, 0] rotate: [0, 0, -90] } { name: 'bhcs-m3-18-003' source: '3d/tapster-3/button-head-cap-screw-M3-18.stl' color: 0x666666 visible: true translate: [-upper_arm_joint_width_offset - 13.5, -11.35 , 0] rotate: [-90, 0, 0] } { name: 'bhcs-m3-18-004' source: '3d/tapster-3/button-head-cap-screw-M3-18.stl' color: 0x666666 visible: true translate: [upper_arm_joint_width_offset + 13.5, -11.35 , 0] rotate: [-90, 0, 0] } { name: 'hn-m3-nl-003' source: '3d/tapster-3/hex-nut-m3-nyloc.stl' color: 0x777777 visible: true translate: [-upper_arm_joint_width_offset - 13.5, -13.30/2 , 0] rotate: [90, 0, 0] } { name: 'hn-m3-nl-004' source: '3d/tapster-3/hex-nut-m3-nyloc.stl' color: 0x777777 visible: true translate: [upper_arm_joint_width_offset + 13.5, -13.30/2 , 0] rotate: [90, 0, 0] } ] ] } { group: name: "linkage-assembly-1" translate: [0, -70, -3.5] rotate: [0, 0, 0] visible: true parts: [ group: name: "linkage-rotation-axis-1" translate: [-upper_arm_joint_width_offset - 13.5, 0, 0] rotate: [90 - a.beta, -a.gamma, 0] parts: [ { name: 'rod-118mm-001' source: '3d/tapster-3/rod-118mm.stl' color: 0x666666 visible: true translate: [0, 0 , -7.75] rotate: [180, 0, 0] } { name: 'rod-end-001' source: '3d/tapster-3/rod-end.stl' color: 0x333333 visible: true translate: [0, 0 , 0] rotate: [0, 0, 0] } { name: 'ball-001' source: '3d/tapster-3/traxxas-5347-hollow-ball.stl' color: 0xAAAAAA visible: true translate: [0, 0 , 0] rotate: [0, 0, 0] } { name: 'rod-end-002' source: '3d/tapster-3/rod-end.stl' color: 0x333333 visible: true translate: [0, 0 , -133.5] rotate: [0, 180, 0] } { name: 'ball-002' source: '3d/tapster-3/traxxas-5347-hollow-ball.stl' color: 0xAAAAAA visible: true translate: [0, 0 , -133.5] rotate: [0, 0, 0] } ] ] } { group: name: "linkage-assembly-2" translate: [0, -70, -3.5] rotate: [0, 0, 0] visible: true parts: [ group: name: "linkage-rotation-axis-2" translate: [upper_arm_joint_width_offset + 13.5, 0, 0] rotate: [90 - a.beta, -a.gamma, 0] parts: [ { name: 'rod-118mm-002' source: '3d/tapster-3/rod-118mm.stl' color: 0x666666 visible: true translate: [0, 0 , -7.75] rotate: [180, 0, 0] } { name: 'rod-end-003' source: '3d/tapster-3/rod-end.stl' color: 0x333333 visible: true translate: [0, 0 , 0] rotate: [0, 0, 0] } { name: 'ball-003' source: '3d/tapster-3/traxxas-5347-hollow-ball.stl' color: 0xAAAAAA visible: true translate: [0, 0 , 0] rotate: [0, 0, 0] } { name: 'rod-end-004' source: '3d/tapster-3/rod-end.stl' color: 0x333333 visible: true translate: [0, 0 , -133.5] rotate: [0, 180, 0] } { name: 'ball-004' source: '3d/tapster-3/traxxas-5347-hollow-ball.stl' color: 0xAAAAAA visible: true translate: [0, 0 , -133.5] rotate: [0, 0, 0] } ] ] } ] } ] group name: 'arm-assembly-2' translate: [0, 0, ceiling] rotate: [0, 0, 120] visible: true parts: [ { name: 'servo-2' source: '3d/tapster-3/xl-430.stl' color: 0x666666 visible: true translate: [0, -50, servo_height_offset] rotate: [0, 90, 180] } { group: name: "base-screws-2" translate: [0, 0, 0] rotate: [0, 0, 0] visible: true parts: [ # Left side - screws { name: 'shms-m2.5-14-005' source: '3d/tapster-3/socket-head-machine-screw-M2.5-14.stl' color: 0x666666 visible: true translate: [-servo_width_offset + 17.5, -14.75 - 3.35, servo_height_offset + 11] rotate: [0, -90, 0] } { name: 'shms-m2.5-14-006' source: '3d/tapster-3/socket-head-machine-screw-M2.5-14.stl' color: 0x666666 visible: true translate: [-servo_width_offset + 17.5, -14.75 - 3.35, servo_height_offset - 11] rotate: [0, -90, 0] } # Right side - screws { name: 'shms-m2.5-14-007' source: '3d/tapster-3/socket-head-machine-screw-M2.5-14.stl' color: 0x666666 visible: true translate: [servo_width_offset - 17.5, -14.75 - 3.35, servo_height_offset + 11] rotate: [0, 90, 0] } { name: 'shms-m2.5-14-008' source: '3d/tapster-3/socket-head-machine-screw-M2.5-14.stl' color: 0x666666 visible: true translate: [servo_width_offset - 17.5, -14.75 - 3.35, servo_height_offset - 11] rotate: [0, 90, 0] } ] } { group: name: "upper-arm-assembly-2" translate: [0, -50, servo_height_offset] rotate: [b.alpha, 0, 0] parts: [ { name: 'arm-2' source: '3d/tapster-3/arm.stl' color: 0xDF1F1F visible: true translate: [0, 0 , 0] rotate: [0, 0, 0] } # Left side - screws { name: 'shms-m2-04-009' source: '3d/tapster-3/socket-head-machine-screw-M2-04.stl' color: 0x666666 visible: true translate: [-servo_width_offset + 6, 0 , 8] rotate: [90, -90, 0] } { name: 'shms-m2-04-010' source: '3d/tapster-3/socket-head-machine-screw-M2-04.stl' color: 0x666666 visible: true translate: [-servo_width_offset + 6, -8 , 0] rotate: [90, -90, 0] } { name: 'shms-m2-04-011' source: '3d/tapster-3/socket-head-machine-screw-M2-04.stl' color: 0x666666 visible: true translate: [-servo_width_offset + 6, 0 , -8] rotate: [90, -90, 0] } { name: 'shms-m2-04-012' source: '3d/tapster-3/socket-head-machine-screw-M2-04.stl' color: 0x666666 visible: true translate: [-servo_width_offset + 6, 8 , 0] rotate: [90, -90, 0] } # Right side - screws { name: 'shms-m2-04-013' source: '3d/tapster-3/socket-head-machine-screw-M2-04.stl' color: 0x666666 visible: true translate: [servo_width_offset - 6, 0 , 8] rotate: [90, 90, 0] } { name: 'shms-m2-04-014' source: '3d/tapster-3/socket-head-machine-screw-M2-04.stl' color: 0x666666 visible: true translate: [servo_width_offset - 6, 8 , 0] rotate: [90, 90, 0] } { name: 'shms-m2-04-015' source: '3d/tapster-3/socket-head-machine-screw-M2-04.stl' color: 0x666666 visible: true translate: [servo_width_offset - 6, 0 , -8] rotate: [90, 90, 0] } { name: 'shms-m2-04-016' source: '3d/tapster-3/socket-head-machine-screw-M2-04.stl' color: 0x666666 visible: true translate: [servo_width_offset - 6, -8 , 0] rotate: [90, 90, 0] } { group: name: "upper-u-joint-assembly-2" translate: [0, -70, -3.5] rotate: [270 - b.beta, 0, 0] visible: true parts: [ { name: 'u-joint-fork-005' source: '3d/tapster-3/u_joint_fork.stl' color: 0xDF1F1F visible: true translate: [-upper_arm_joint_width_offset, 0 , 0] rotate: [0, 0, 90] } { name: 'u-joint-fork-006' source: '3d/tapster-3/u_joint_fork.stl' color: 0xDF1F1F visible: true translate: [upper_arm_joint_width_offset, 0 , 0] rotate: [0, 0, -90] } { name: 'bhcs-m3-18-005' source: '3d/tapster-3/button-head-cap-screw-M3-18.stl' color: 0x666666 visible: true translate: [-upper_arm_joint_width_offset - 13.5, 11.35 , 0] rotate: [90, 0, 0] } { name: 'bhcs-m3-18-006' source: '3d/tapster-3/button-head-cap-screw-M3-18.stl' color: 0x666666 visible: true translate: [upper_arm_joint_width_offset + 13.5, 11.35 , 0] rotate: [90, 0, 0] } { name: 'hn-m3-nl-005' source: '3d/tapster-3/hex-nut-m3-nyloc.stl' color: 0x777777 visible: true translate: [-upper_arm_joint_width_offset - 13.5, 13.30/2 , 0] rotate: [-90, 0, 0] } { name: 'hn-m3-nl-006' source: '3d/tapster-3/hex-nut-m3-nyloc.stl' color: 0x777777 visible: true translate: [upper_arm_joint_width_offset + 13.5, 13.30/2 , 0] rotate: [-90, 0, 0] } ] } { group: name: "lower-u-joint-assembly-2" translate: [0, -70, -3.5] rotate: [90 - b.beta, -b.gamma, 0] visible: true parts: [ group: name: "lower-u-joint-rotation-axis-2" translate: [0, 0, -133.5] rotate: [0, b.gamma, 0] parts: [ { name: 'u-joint-fork-007' source: '3d/tapster-3/u_joint_fork.stl' color: 0xDF1F1F visible: true translate: [-upper_arm_joint_width_offset, 0, 0] rotate: [0, 0, 90] } { name: 'u-joint-fork-008' source: '3d/tapster-3/u_joint_fork.stl' color: 0xDF1F1F visible: true translate: [upper_arm_joint_width_offset, 0, 0] rotate: [0, 0, -90] } { name: 'bhcs-m3-18-007' source: '3d/tapster-3/button-head-cap-screw-M3-18.stl' color: 0x666666 visible: true translate: [-upper_arm_joint_width_offset - 13.5, -11.35 , 0] rotate: [-90, 0, 0] } { name: 'bhcs-m3-18-008' source: '3d/tapster-3/button-head-cap-screw-M3-18.stl' color: 0x666666 visible: true translate: [upper_arm_joint_width_offset + 13.5, -11.35 , 0] rotate: [-90, 0, 0] } { name: 'hn-m3-nl-007' source: '3d/tapster-3/hex-nut-m3-nyloc.stl' color: 0x777777 visible: true translate: [-upper_arm_joint_width_offset - 13.5, -13.30/2 , 0] rotate: [90, 0, 0] } { name: 'hn-m3-nl-008' source: '3d/tapster-3/hex-nut-m3-nyloc.stl' color: 0x777777 visible: true translate: [upper_arm_joint_width_offset + 13.5, -13.30/2 , 0] rotate: [90, 0, 0] } ] ] } { group: name: "linkage-assembly-3" translate: [0, -70, -3.5] rotate: [0, 0, 0] parts: [ group: name: "linkage-rotation-axis-3" translate: [-upper_arm_joint_width_offset - 13.5, 0, 0] rotate: [90 - b.beta, -b.gamma, 0] parts: [ { name: 'rod-118mm-003' source: '3d/tapster-3/rod-118mm.stl' color: 0x666666 visible: true translate: [0, 0 , -7.75] rotate: [180, 0, 0] } { name: 'rod-end-005' source: '3d/tapster-3/rod-end.stl' color: 0x333333 visible: true translate: [0, 0 , 0] rotate: [0, 0, 0] } { name: 'ball-005' source: '3d/tapster-3/traxxas-5347-hollow-ball.stl' color: 0xAAAAAA visible: true translate: [0, 0 , 0] rotate: [0, 0, 0] } { name: 'rod-end-006' source: '3d/tapster-3/rod-end.stl' color: 0x333333 visible: true translate: [0, 0 , -133.5] rotate: [0, 180, 0] } { name: 'ball-006' source: '3d/tapster-3/traxxas-5347-hollow-ball.stl' color: 0xAAAAAA visible: true translate: [0, 0 , -133.5] rotate: [0, 0, 0] } ] ] } { group: name: "linkage-assembly-4" translate: [0, -70, -3.5] rotate: [0, 0, 0] parts: [ group: name: "linkage-rotation-axis-4" translate: [upper_arm_joint_width_offset + 13.5, 0, 0] rotate: [90 - b.beta, -b.gamma, 0] parts: [ { name: 'rod-118mm-004' source: '3d/tapster-3/rod-118mm.stl' color: 0x666666 visible: true translate: [0, 0 , -7.75] rotate: [180, 0, 0] } { name: 'rod-end-007' source: '3d/tapster-3/rod-end.stl' color: 0x333333 visible: true translate: [0, 0 , 0] rotate: [0, 0, 0] } { name: 'ball-007' source: '3d/tapster-3/traxxas-5347-hollow-ball.stl' color: 0xAAAAAA visible: true translate: [0, 0 , 0] rotate: [0, 0, 0] } { name: 'rod-end-008' source: '3d/tapster-3/rod-end.stl' color: 0x333333 visible: true translate: [0, 0 , -133.5] rotate: [0, 180, 0] } { name: 'ball-008' source: '3d/tapster-3/traxxas-5347-hollow-ball.stl' color: 0xAAAAAA visible: true translate: [0, 0 , -133.5] rotate: [0, 0, 0] } ] ] } ] } ] group name: 'arm-assembly-3' translate: [0, 0, ceiling] rotate: [0, 0, - 120] visible: true parts: [ { name: 'servo-3' source: '3d/tapster-3/xl-430.stl' color: 0x666666 visible: true translate: [0, -50, servo_height_offset] rotate: [0, 90, 180] } { group: name: "base-screws-3" translate: [0, 0, 0] rotate: [0, 0, 0] visible: true parts: [ # Left side - screws { name: 'shms-m2.5-14-009' source: '3d/tapster-3/socket-head-machine-screw-M2.5-14.stl' color: 0x666666 visible: true translate: [-servo_width_offset + 17.5, -14.75 - 3.35, servo_height_offset + 11] rotate: [0, -90, 0] } { name: 'shms-m2.5-14-010' source: '3d/tapster-3/socket-head-machine-screw-M2.5-14.stl' color: 0x666666 visible: true translate: [-servo_width_offset + 17.5, -14.75 - 3.35, servo_height_offset - 11] rotate: [0, -90, 0] } # Right side - screws { name: 'shms-m2.5-14-011' source: '3d/tapster-3/socket-head-machine-screw-M2.5-14.stl' color: 0x666666 visible: true translate: [servo_width_offset - 17.5, -14.75 - 3.35, servo_height_offset + 11] rotate: [0, 90, 0] } { name: 'shms-m2.5-14-012' source: '3d/tapster-3/socket-head-machine-screw-M2.5-14.stl' color: 0x666666 visible: true translate: [servo_width_offset - 17.5, -14.75 - 3.35, servo_height_offset - 11] rotate: [0, 90, 0] } ] } { group: name: "upper-arm-assembly-3" translate: [0, -50, servo_height_offset] rotate: [c.alpha, 0, 0] parts: [ { name: 'arm-3' source: '3d/tapster-3/arm.stl' color: 0xDF1F1F visible: true translate: [0, 0 , 0] rotate: [0, 0, 0] } # Left side - screws { name: 'shms-m2-04-017' source: '3d/tapster-3/socket-head-machine-screw-M2-04.stl' color: 0x666666 visible: true translate: [-servo_width_offset + 6, 0 , 8] rotate: [90, -90, 0] } { name: 'shms-m2-04-018' source: '3d/tapster-3/socket-head-machine-screw-M2-04.stl' color: 0x666666 visible: true translate: [-servo_width_offset + 6, -8 , 0] rotate: [90, -90, 0] } { name: 'shms-m2-04-019' source: '3d/tapster-3/socket-head-machine-screw-M2-04.stl' color: 0x666666 visible: true translate: [-servo_width_offset + 6, 0 , -8] rotate: [90, -90, 0] } { name: 'shms-m2-04-020' source: '3d/tapster-3/socket-head-machine-screw-M2-04.stl' color: 0x666666 visible: true translate: [-servo_width_offset + 6, 8 , 0] rotate: [90, -90, 0] } # Right side - screws { name: 'shms-m2-04-021' source: '3d/tapster-3/socket-head-machine-screw-M2-04.stl' color: 0x666666 visible: true translate: [servo_width_offset - 6, 0 , 8] rotate: [90, 90, 0] } { name: 'shms-m2-04-022' source: '3d/tapster-3/socket-head-machine-screw-M2-04.stl' color: 0x666666 visible: true translate: [servo_width_offset - 6, 8 , 0] rotate: [90, 90, 0] } { name: 'shms-m2-04-023' source: '3d/tapster-3/socket-head-machine-screw-M2-04.stl' color: 0x666666 visible: true translate: [servo_width_offset - 6, 0 , -8] rotate: [90, 90, 0] } { name: 'shms-m2-04-024' source: '3d/tapster-3/socket-head-machine-screw-M2-04.stl' color: 0x666666 visible: true translate: [servo_width_offset - 6, -8 , 0] rotate: [90, 90, 0] } { group: name: "upper-u-joint-assembly-3" translate: [0, -70, -3.5] rotate: [270 - c.beta, 0, 0] visible: true parts: [ { name: 'u-joint-fork-009' source: '3d/tapster-3/u_joint_fork.stl' color: 0xDF1F1F visible: true translate: [-upper_arm_joint_width_offset, 0 , 0] rotate: [0, 0, 90] } { name: 'u-joint-fork-010' source: '3d/tapster-3/u_joint_fork.stl' color: 0xDF1F1F visible: true translate: [upper_arm_joint_width_offset, 0 , 0] rotate: [0, 0, -90] } { name: 'bhcs-m3-18-009' source: '3d/tapster-3/button-head-cap-screw-M3-18.stl' color: 0x666666 visible: true translate: [-upper_arm_joint_width_offset - 13.5, 11.35 , 0] rotate: [90, 0, 0] } { name: 'bhcs-m3-18-010' source: '3d/tapster-3/button-head-cap-screw-M3-18.stl' color: 0x666666 visible: true translate: [upper_arm_joint_width_offset + 13.5, 11.35 , 0] rotate: [90, 0, 0] } { name: 'hn-m3-nl-009' source: '3d/tapster-3/hex-nut-m3-nyloc.stl' color: 0x777777 visible: true translate: [-upper_arm_joint_width_offset - 13.5, 13.30/2 , 0] rotate: [-90, 0, 0] } { name: 'hn-m3-nl-010' source: '3d/tapster-3/hex-nut-m3-nyloc.stl' color: 0x777777 visible: true translate: [upper_arm_joint_width_offset + 13.5, 13.30/2 , 0] rotate: [-90, 0, 0] } ] } { group: name: "lower-u-joint-assembly-3" translate: [0, -70, -3.5] rotate: [90 - c.beta, -c.gamma, 0] visible: true parts: [ group: name: "lower-u-joint-rotation-axis-3" translate: [0, 0, -133.5] rotate: [0, c.gamma, 0] parts: [ { name: 'u-joint-fork-011' source: '3d/tapster-3/u_joint_fork.stl' color: 0xDF1F1F visible: true translate: [-upper_arm_joint_width_offset, 0, 0] rotate: [0, 0, 90] } { name: 'u-joint-fork-012' source: '3d/tapster-3/u_joint_fork.stl' color: 0xDF1F1F visible: true translate: [upper_arm_joint_width_offset, 0, 0] rotate: [0, 0, -90] } { name: 'bhcs-m3-18-011' source: '3d/tapster-3/button-head-cap-screw-M3-18.stl' color: 0x666666 visible: true translate: [-upper_arm_joint_width_offset - 13.5, -11.35 , 0] rotate: [-90, 0, 0] } { name: 'bhcs-m3-18-012' source: '3d/tapster-3/button-head-cap-screw-M3-18.stl' color: 0x666666 visible: true translate: [upper_arm_joint_width_offset + 13.5, -11.35 , 0] rotate: [-90, 0, 0] } { name: 'hn-m3-nl-011' source: '3d/tapster-3/hex-nut-m3-nyloc.stl' color: 0x777777 visible: true translate: [-upper_arm_joint_width_offset - 13.5, -13.30/2 , 0] rotate: [90, 0, 0] } { name: 'hn-m3-nl-012' source: '3d/tapster-3/hex-nut-m3-nyloc.stl' color: 0x777777 visible: true translate: [upper_arm_joint_width_offset + 13.5, -13.30/2 , 0] rotate: [90, 0, 0] } ] ] } { group: name: "linkage-assembly-5" translate: [0, -70, -3.5] rotate: [0, 0, 0] parts: [ group: name: "linkage-rotation-axis-5" translate: [-upper_arm_joint_width_offset - 13.5, 0, 0] rotate: [90 - c.beta, -c.gamma, 0] parts: [ { name: 'rod-118mm-005' source: '3d/tapster-3/rod-118mm.stl' color: 0x666666 visible: true translate: [0, 0 , -7.75] rotate: [180, 0, 0] } { name: 'rod-end-09' source: '3d/tapster-3/rod-end.stl' color: 0x333333 visible: true translate: [0, 0 , 0] rotate: [0, 0, 0] } { name: 'ball-009' source: '3d/tapster-3/traxxas-5347-hollow-ball.stl' color: 0xAAAAAA visible: true translate: [0, 0 , 0] rotate: [0, 0, 0] } { name: 'rod-end-010' source: '3d/tapster-3/rod-end.stl' color: 0x333333 visible: true translate: [0, 0 , -133.5] rotate: [0, 180, 0] } { name: 'ball-010' source: '3d/tapster-3/traxxas-5347-hollow-ball.stl' color: 0xAAAAAA visible: true translate: [0, 0 , -133.5] rotate: [0, 0, 0] } ] ] } { group: name: "linkage-assembly-6" translate: [0, -70, -3.5] rotate: [0, 0, 0] parts: [ group: name: "linkage-rotation-axis-6" translate: [upper_arm_joint_width_offset + 13.5, 0, 0] rotate: [90 - c.beta, -c.gamma, 0] parts: [ { name: 'rod-118mm-006' source: '3d/tapster-3/rod-118mm.stl' color: 0x666666 visible: true translate: [0, 0 , -7.75] rotate: [180, 0, 0] } { name: 'rod-end-011' source: '3d/tapster-3/rod-end.stl' color: 0x333333 visible: true translate: [0, 0 , 0] rotate: [0, 0, 0] } { name: 'ball-011' source: '3d/tapster-3/traxxas-5347-hollow-ball.stl' color: 0xAAAAAA visible: true translate: [0, 0 , 0] rotate: [0, 0, 0] } { name: 'rod-end-012' source: '3d/tapster-3/rod-end.stl' color: 0x333333 visible: true translate: [0, 0 , -133.5] rotate: [0, 180, 0] } { name: 'ball-012' source: '3d/tapster-3/traxxas-5347-hollow-ball.stl' color: 0xAAAAAA visible: true translate: [0, 0 , -133.5] rotate: [0, 0, 0] } ] ] } ] } ]
true
# Tapster 3 Assembly # (c) 2020 PI:NAME:<NAME>END_PI # It's okay to use CoffeeScript ☕ # No, really, pi is wrong Math.TAU = Math.PI*2 arm_offset = Math.acos(69.912/70) / Math.TAU * 360 ceiling = 190 servo_height_offset = (-28.5 / 2) - 5 servo_width_offset = 44.6 / 2 end_effector_offset = 7.50 upper_arm_joint_width_offset = 23.50 / 2 u_fork_width = 13.30 end_effector = {x: 0, y: 0, z: -150} a = { alpha: 38.097759123032375 - arm_offset, beta: 91.23475984385213 - arm_offset, gamma: 0 } b = { alpha: 38.097759123032375 - arm_offset, beta: 91.23475984385213 - arm_offset, gamma: 0 } c = { alpha: 38.097759123032375 - arm_offset, beta: 91.23475984385213 - arm_offset, gamma: 0 } part name: 'plane' shape: 'floor' texture: 'image/wood-floor-2.jpg' transparent: true opacity: 0.6 visible: true size: [400, 400, 2] translate: [0, 0, 0 ] rotate: [0, 0, 0] part name: 'base' source: '3d/tapster-3/base.stl' color: 0xDF1F1F translate: [0, 0, ceiling] rotate: [0, 180, 210] part name: 'end-effector' source: '3d/tapster-3/end_effector.stl' color: 0xDF1F1F translate: [end_effector.x, end_effector.y, ceiling + servo_height_offset - end_effector_offset + end_effector.z] rotate: [0, 0, 0] group name: 'tapster-3' class: 'robot' specs: { end_offset: -25 fixed_offset: -50 end_radius: 133.5 fixed_radius: 70 ceiling: 190 servo_height_offset: (-28.5 / 2) - 5 end_effector_offset: 7.50 arm_offset: Math.acos(69.912/70) } group name: 'arm-assembly-1' translate: [0, 0, ceiling] rotate: [0, 0, 0] visible: true parts: [ { name: 'servo-1' source: '3d/tapster-3/xl-430.stl' color: 0x666666 visible: true #translate: [-0, -14.75 - 3.25 - 32, -28.5 / 2 - 5] translate: [0, -50, servo_height_offset] rotate: [0, 90, 180] } { group: name: "base-screws-1" translate: [0, 0, 0] rotate: [0, 0, 0] visible: true parts: [ # Left side - screws { name: 'shms-m2.5-14-001' source: '3d/tapster-3/socket-head-machine-screw-M2.5-14.stl' color: 0x666666 visible: true translate: [-servo_width_offset + 17.5, -14.75 - 3.35, servo_height_offset + 11] rotate: [0, -90, 0] } { name: 'shms-m2.5-14-002' source: '3d/tapster-3/socket-head-machine-screw-M2.5-14.stl' color: 0x666666 visible: true translate: [-servo_width_offset + 17.5, -14.75 - 3.35, servo_height_offset - 11] rotate: [0, -90, 0] } # Right side - screws { name: 'shms-m2.5-14-003' source: '3d/tapster-3/socket-head-machine-screw-M2.5-14.stl' color: 0x666666 visible: true translate: [servo_width_offset - 17.5, -14.75 - 3.35, servo_height_offset + 11] rotate: [0, 90, 0] } { name: 'shms-m2.5-14-004' source: '3d/tapster-3/socket-head-machine-screw-M2.5-14.stl' color: 0x666666 visible: true translate: [servo_width_offset - 17.5, -14.75 - 3.35, servo_height_offset - 11] rotate: [0, 90, 0] } ] } { group: name: "upper-arm-assembly-1" translate: [0, -50, servo_height_offset] rotate: [a.alpha, 0, 0] parts: [ { name: 'arm-1' source: '3d/tapster-3/arm.stl' color: 0xDF1F1F visible: true translate: [0, 0 , 0] rotate: [0, 0, 0] } # Left side - screws { name: 'shms-m2-04-001' source: '3d/tapster-3/socket-head-machine-screw-M2-04.stl' color: 0x666666 visible: true translate: [-servo_width_offset + 6, 0 , 8] rotate: [90, -90, 0] } { name: 'shms-m2-04-002' source: '3d/tapster-3/socket-head-machine-screw-M2-04.stl' color: 0x666666 visible: true translate: [-servo_width_offset + 6, -8 , 0] rotate: [90, -90, 0] } { name: 'shms-m2-04-003' source: '3d/tapster-3/socket-head-machine-screw-M2-04.stl' color: 0x666666 visible: true translate: [-servo_width_offset + 6, 0 , -8] rotate: [90, -90, 0] } { name: 'shms-m2-04-004' source: '3d/tapster-3/socket-head-machine-screw-M2-04.stl' color: 0x666666 visible: true translate: [-servo_width_offset + 6, 8 , 0] rotate: [90, -90, 0] } # Right side - screws { name: 'shms-m2-04-005' source: '3d/tapster-3/socket-head-machine-screw-M2-04.stl' color: 0x666666 visible: true translate: [servo_width_offset - 6, 0 , 8] rotate: [90, 90, 0] } { name: 'shms-m2-04-006' source: '3d/tapster-3/socket-head-machine-screw-M2-04.stl' color: 0x666666 visible: true translate: [servo_width_offset - 6, 8 , 0] rotate: [90, 90, 0] } { name: 'shms-m2-04-007' source: '3d/tapster-3/socket-head-machine-screw-M2-04.stl' color: 0x666666 visible: true translate: [servo_width_offset - 6, 0 , -8] rotate: [90, 90, 0] } { name: 'shms-m2-04-008' source: '3d/tapster-3/socket-head-machine-screw-M2-04.stl' color: 0x666666 visible: true translate: [servo_width_offset - 6, -8 , 0] rotate: [90, 90, 0] } { group: name: "upper-u-joint-assembly-1" translate: [0, -70, -3.5] rotate: [270 - a.beta, 0, 0] visible: true parts: [ { name: 'u-joint-fork-001' source: '3d/tapster-3/u_joint_fork.stl' color: 0xDF1F1F visible: true translate: [-upper_arm_joint_width_offset, 0 , 0] rotate: [0, 0, 90] } { name: 'u-joint-fork-002' source: '3d/tapster-3/u_joint_fork.stl' color: 0xDF1F1F visible: true translate: [upper_arm_joint_width_offset, 0 , 0] rotate: [0, 0, -90] } { name: 'bhcs-m3-18-001' source: '3d/tapster-3/button-head-cap-screw-M3-18.stl' color: 0x666666 visible: true translate: [-upper_arm_joint_width_offset - 13.5, 11.35, 0] rotate: [90, 0, 0] } { name: 'bhcs-m3-18-002' source: '3d/tapster-3/button-head-cap-screw-M3-18.stl' color: 0x666666 visible: true translate: [upper_arm_joint_width_offset + 13.5, 11.35, 0] rotate: [90, 0, 0] } { name: 'hn-m3-nl-001' source: '3d/tapster-3/hex-nut-m3-nyloc.stl' color: 0x777777 visible: true translate: [-upper_arm_joint_width_offset - 13.5, 13.30/2 , 0] rotate: [-90, 0, 0] } { name: 'hn-m3-nl-002' source: '3d/tapster-3/hex-nut-m3-nyloc.stl' color: 0x777777 visible: true translate: [upper_arm_joint_width_offset + 13.5, 13.30/2 , 0] rotate: [-90, 0, 0] } ] } { group: name: "lower-u-joint-assembly-1" translate: [0, -70, -3.5] rotate: [90 - a.beta, -a.gamma, 0] visible: true parts: [ group: name: "lower-u-joint-rotation-axis-1" translate: [0, 0, -133.5] rotate: [0, a.gamma, 0] parts: [ { name: 'u-joint-fork-003' source: '3d/tapster-3/u_joint_fork.stl' color: 0xDF1F1F visible: true translate: [-upper_arm_joint_width_offset, 0, 0] rotate: [0, 0, 90] } { name: 'u-joint-fork-004' source: '3d/tapster-3/u_joint_fork.stl' color: 0xDF1F1F visible: true translate: [upper_arm_joint_width_offset, 0, 0] rotate: [0, 0, -90] } { name: 'bhcs-m3-18-003' source: '3d/tapster-3/button-head-cap-screw-M3-18.stl' color: 0x666666 visible: true translate: [-upper_arm_joint_width_offset - 13.5, -11.35 , 0] rotate: [-90, 0, 0] } { name: 'bhcs-m3-18-004' source: '3d/tapster-3/button-head-cap-screw-M3-18.stl' color: 0x666666 visible: true translate: [upper_arm_joint_width_offset + 13.5, -11.35 , 0] rotate: [-90, 0, 0] } { name: 'hn-m3-nl-003' source: '3d/tapster-3/hex-nut-m3-nyloc.stl' color: 0x777777 visible: true translate: [-upper_arm_joint_width_offset - 13.5, -13.30/2 , 0] rotate: [90, 0, 0] } { name: 'hn-m3-nl-004' source: '3d/tapster-3/hex-nut-m3-nyloc.stl' color: 0x777777 visible: true translate: [upper_arm_joint_width_offset + 13.5, -13.30/2 , 0] rotate: [90, 0, 0] } ] ] } { group: name: "linkage-assembly-1" translate: [0, -70, -3.5] rotate: [0, 0, 0] visible: true parts: [ group: name: "linkage-rotation-axis-1" translate: [-upper_arm_joint_width_offset - 13.5, 0, 0] rotate: [90 - a.beta, -a.gamma, 0] parts: [ { name: 'rod-118mm-001' source: '3d/tapster-3/rod-118mm.stl' color: 0x666666 visible: true translate: [0, 0 , -7.75] rotate: [180, 0, 0] } { name: 'rod-end-001' source: '3d/tapster-3/rod-end.stl' color: 0x333333 visible: true translate: [0, 0 , 0] rotate: [0, 0, 0] } { name: 'ball-001' source: '3d/tapster-3/traxxas-5347-hollow-ball.stl' color: 0xAAAAAA visible: true translate: [0, 0 , 0] rotate: [0, 0, 0] } { name: 'rod-end-002' source: '3d/tapster-3/rod-end.stl' color: 0x333333 visible: true translate: [0, 0 , -133.5] rotate: [0, 180, 0] } { name: 'ball-002' source: '3d/tapster-3/traxxas-5347-hollow-ball.stl' color: 0xAAAAAA visible: true translate: [0, 0 , -133.5] rotate: [0, 0, 0] } ] ] } { group: name: "linkage-assembly-2" translate: [0, -70, -3.5] rotate: [0, 0, 0] visible: true parts: [ group: name: "linkage-rotation-axis-2" translate: [upper_arm_joint_width_offset + 13.5, 0, 0] rotate: [90 - a.beta, -a.gamma, 0] parts: [ { name: 'rod-118mm-002' source: '3d/tapster-3/rod-118mm.stl' color: 0x666666 visible: true translate: [0, 0 , -7.75] rotate: [180, 0, 0] } { name: 'rod-end-003' source: '3d/tapster-3/rod-end.stl' color: 0x333333 visible: true translate: [0, 0 , 0] rotate: [0, 0, 0] } { name: 'ball-003' source: '3d/tapster-3/traxxas-5347-hollow-ball.stl' color: 0xAAAAAA visible: true translate: [0, 0 , 0] rotate: [0, 0, 0] } { name: 'rod-end-004' source: '3d/tapster-3/rod-end.stl' color: 0x333333 visible: true translate: [0, 0 , -133.5] rotate: [0, 180, 0] } { name: 'ball-004' source: '3d/tapster-3/traxxas-5347-hollow-ball.stl' color: 0xAAAAAA visible: true translate: [0, 0 , -133.5] rotate: [0, 0, 0] } ] ] } ] } ] group name: 'arm-assembly-2' translate: [0, 0, ceiling] rotate: [0, 0, 120] visible: true parts: [ { name: 'servo-2' source: '3d/tapster-3/xl-430.stl' color: 0x666666 visible: true translate: [0, -50, servo_height_offset] rotate: [0, 90, 180] } { group: name: "base-screws-2" translate: [0, 0, 0] rotate: [0, 0, 0] visible: true parts: [ # Left side - screws { name: 'shms-m2.5-14-005' source: '3d/tapster-3/socket-head-machine-screw-M2.5-14.stl' color: 0x666666 visible: true translate: [-servo_width_offset + 17.5, -14.75 - 3.35, servo_height_offset + 11] rotate: [0, -90, 0] } { name: 'shms-m2.5-14-006' source: '3d/tapster-3/socket-head-machine-screw-M2.5-14.stl' color: 0x666666 visible: true translate: [-servo_width_offset + 17.5, -14.75 - 3.35, servo_height_offset - 11] rotate: [0, -90, 0] } # Right side - screws { name: 'shms-m2.5-14-007' source: '3d/tapster-3/socket-head-machine-screw-M2.5-14.stl' color: 0x666666 visible: true translate: [servo_width_offset - 17.5, -14.75 - 3.35, servo_height_offset + 11] rotate: [0, 90, 0] } { name: 'shms-m2.5-14-008' source: '3d/tapster-3/socket-head-machine-screw-M2.5-14.stl' color: 0x666666 visible: true translate: [servo_width_offset - 17.5, -14.75 - 3.35, servo_height_offset - 11] rotate: [0, 90, 0] } ] } { group: name: "upper-arm-assembly-2" translate: [0, -50, servo_height_offset] rotate: [b.alpha, 0, 0] parts: [ { name: 'arm-2' source: '3d/tapster-3/arm.stl' color: 0xDF1F1F visible: true translate: [0, 0 , 0] rotate: [0, 0, 0] } # Left side - screws { name: 'shms-m2-04-009' source: '3d/tapster-3/socket-head-machine-screw-M2-04.stl' color: 0x666666 visible: true translate: [-servo_width_offset + 6, 0 , 8] rotate: [90, -90, 0] } { name: 'shms-m2-04-010' source: '3d/tapster-3/socket-head-machine-screw-M2-04.stl' color: 0x666666 visible: true translate: [-servo_width_offset + 6, -8 , 0] rotate: [90, -90, 0] } { name: 'shms-m2-04-011' source: '3d/tapster-3/socket-head-machine-screw-M2-04.stl' color: 0x666666 visible: true translate: [-servo_width_offset + 6, 0 , -8] rotate: [90, -90, 0] } { name: 'shms-m2-04-012' source: '3d/tapster-3/socket-head-machine-screw-M2-04.stl' color: 0x666666 visible: true translate: [-servo_width_offset + 6, 8 , 0] rotate: [90, -90, 0] } # Right side - screws { name: 'shms-m2-04-013' source: '3d/tapster-3/socket-head-machine-screw-M2-04.stl' color: 0x666666 visible: true translate: [servo_width_offset - 6, 0 , 8] rotate: [90, 90, 0] } { name: 'shms-m2-04-014' source: '3d/tapster-3/socket-head-machine-screw-M2-04.stl' color: 0x666666 visible: true translate: [servo_width_offset - 6, 8 , 0] rotate: [90, 90, 0] } { name: 'shms-m2-04-015' source: '3d/tapster-3/socket-head-machine-screw-M2-04.stl' color: 0x666666 visible: true translate: [servo_width_offset - 6, 0 , -8] rotate: [90, 90, 0] } { name: 'shms-m2-04-016' source: '3d/tapster-3/socket-head-machine-screw-M2-04.stl' color: 0x666666 visible: true translate: [servo_width_offset - 6, -8 , 0] rotate: [90, 90, 0] } { group: name: "upper-u-joint-assembly-2" translate: [0, -70, -3.5] rotate: [270 - b.beta, 0, 0] visible: true parts: [ { name: 'u-joint-fork-005' source: '3d/tapster-3/u_joint_fork.stl' color: 0xDF1F1F visible: true translate: [-upper_arm_joint_width_offset, 0 , 0] rotate: [0, 0, 90] } { name: 'u-joint-fork-006' source: '3d/tapster-3/u_joint_fork.stl' color: 0xDF1F1F visible: true translate: [upper_arm_joint_width_offset, 0 , 0] rotate: [0, 0, -90] } { name: 'bhcs-m3-18-005' source: '3d/tapster-3/button-head-cap-screw-M3-18.stl' color: 0x666666 visible: true translate: [-upper_arm_joint_width_offset - 13.5, 11.35 , 0] rotate: [90, 0, 0] } { name: 'bhcs-m3-18-006' source: '3d/tapster-3/button-head-cap-screw-M3-18.stl' color: 0x666666 visible: true translate: [upper_arm_joint_width_offset + 13.5, 11.35 , 0] rotate: [90, 0, 0] } { name: 'hn-m3-nl-005' source: '3d/tapster-3/hex-nut-m3-nyloc.stl' color: 0x777777 visible: true translate: [-upper_arm_joint_width_offset - 13.5, 13.30/2 , 0] rotate: [-90, 0, 0] } { name: 'hn-m3-nl-006' source: '3d/tapster-3/hex-nut-m3-nyloc.stl' color: 0x777777 visible: true translate: [upper_arm_joint_width_offset + 13.5, 13.30/2 , 0] rotate: [-90, 0, 0] } ] } { group: name: "lower-u-joint-assembly-2" translate: [0, -70, -3.5] rotate: [90 - b.beta, -b.gamma, 0] visible: true parts: [ group: name: "lower-u-joint-rotation-axis-2" translate: [0, 0, -133.5] rotate: [0, b.gamma, 0] parts: [ { name: 'u-joint-fork-007' source: '3d/tapster-3/u_joint_fork.stl' color: 0xDF1F1F visible: true translate: [-upper_arm_joint_width_offset, 0, 0] rotate: [0, 0, 90] } { name: 'u-joint-fork-008' source: '3d/tapster-3/u_joint_fork.stl' color: 0xDF1F1F visible: true translate: [upper_arm_joint_width_offset, 0, 0] rotate: [0, 0, -90] } { name: 'bhcs-m3-18-007' source: '3d/tapster-3/button-head-cap-screw-M3-18.stl' color: 0x666666 visible: true translate: [-upper_arm_joint_width_offset - 13.5, -11.35 , 0] rotate: [-90, 0, 0] } { name: 'bhcs-m3-18-008' source: '3d/tapster-3/button-head-cap-screw-M3-18.stl' color: 0x666666 visible: true translate: [upper_arm_joint_width_offset + 13.5, -11.35 , 0] rotate: [-90, 0, 0] } { name: 'hn-m3-nl-007' source: '3d/tapster-3/hex-nut-m3-nyloc.stl' color: 0x777777 visible: true translate: [-upper_arm_joint_width_offset - 13.5, -13.30/2 , 0] rotate: [90, 0, 0] } { name: 'hn-m3-nl-008' source: '3d/tapster-3/hex-nut-m3-nyloc.stl' color: 0x777777 visible: true translate: [upper_arm_joint_width_offset + 13.5, -13.30/2 , 0] rotate: [90, 0, 0] } ] ] } { group: name: "linkage-assembly-3" translate: [0, -70, -3.5] rotate: [0, 0, 0] parts: [ group: name: "linkage-rotation-axis-3" translate: [-upper_arm_joint_width_offset - 13.5, 0, 0] rotate: [90 - b.beta, -b.gamma, 0] parts: [ { name: 'rod-118mm-003' source: '3d/tapster-3/rod-118mm.stl' color: 0x666666 visible: true translate: [0, 0 , -7.75] rotate: [180, 0, 0] } { name: 'rod-end-005' source: '3d/tapster-3/rod-end.stl' color: 0x333333 visible: true translate: [0, 0 , 0] rotate: [0, 0, 0] } { name: 'ball-005' source: '3d/tapster-3/traxxas-5347-hollow-ball.stl' color: 0xAAAAAA visible: true translate: [0, 0 , 0] rotate: [0, 0, 0] } { name: 'rod-end-006' source: '3d/tapster-3/rod-end.stl' color: 0x333333 visible: true translate: [0, 0 , -133.5] rotate: [0, 180, 0] } { name: 'ball-006' source: '3d/tapster-3/traxxas-5347-hollow-ball.stl' color: 0xAAAAAA visible: true translate: [0, 0 , -133.5] rotate: [0, 0, 0] } ] ] } { group: name: "linkage-assembly-4" translate: [0, -70, -3.5] rotate: [0, 0, 0] parts: [ group: name: "linkage-rotation-axis-4" translate: [upper_arm_joint_width_offset + 13.5, 0, 0] rotate: [90 - b.beta, -b.gamma, 0] parts: [ { name: 'rod-118mm-004' source: '3d/tapster-3/rod-118mm.stl' color: 0x666666 visible: true translate: [0, 0 , -7.75] rotate: [180, 0, 0] } { name: 'rod-end-007' source: '3d/tapster-3/rod-end.stl' color: 0x333333 visible: true translate: [0, 0 , 0] rotate: [0, 0, 0] } { name: 'ball-007' source: '3d/tapster-3/traxxas-5347-hollow-ball.stl' color: 0xAAAAAA visible: true translate: [0, 0 , 0] rotate: [0, 0, 0] } { name: 'rod-end-008' source: '3d/tapster-3/rod-end.stl' color: 0x333333 visible: true translate: [0, 0 , -133.5] rotate: [0, 180, 0] } { name: 'ball-008' source: '3d/tapster-3/traxxas-5347-hollow-ball.stl' color: 0xAAAAAA visible: true translate: [0, 0 , -133.5] rotate: [0, 0, 0] } ] ] } ] } ] group name: 'arm-assembly-3' translate: [0, 0, ceiling] rotate: [0, 0, - 120] visible: true parts: [ { name: 'servo-3' source: '3d/tapster-3/xl-430.stl' color: 0x666666 visible: true translate: [0, -50, servo_height_offset] rotate: [0, 90, 180] } { group: name: "base-screws-3" translate: [0, 0, 0] rotate: [0, 0, 0] visible: true parts: [ # Left side - screws { name: 'shms-m2.5-14-009' source: '3d/tapster-3/socket-head-machine-screw-M2.5-14.stl' color: 0x666666 visible: true translate: [-servo_width_offset + 17.5, -14.75 - 3.35, servo_height_offset + 11] rotate: [0, -90, 0] } { name: 'shms-m2.5-14-010' source: '3d/tapster-3/socket-head-machine-screw-M2.5-14.stl' color: 0x666666 visible: true translate: [-servo_width_offset + 17.5, -14.75 - 3.35, servo_height_offset - 11] rotate: [0, -90, 0] } # Right side - screws { name: 'shms-m2.5-14-011' source: '3d/tapster-3/socket-head-machine-screw-M2.5-14.stl' color: 0x666666 visible: true translate: [servo_width_offset - 17.5, -14.75 - 3.35, servo_height_offset + 11] rotate: [0, 90, 0] } { name: 'shms-m2.5-14-012' source: '3d/tapster-3/socket-head-machine-screw-M2.5-14.stl' color: 0x666666 visible: true translate: [servo_width_offset - 17.5, -14.75 - 3.35, servo_height_offset - 11] rotate: [0, 90, 0] } ] } { group: name: "upper-arm-assembly-3" translate: [0, -50, servo_height_offset] rotate: [c.alpha, 0, 0] parts: [ { name: 'arm-3' source: '3d/tapster-3/arm.stl' color: 0xDF1F1F visible: true translate: [0, 0 , 0] rotate: [0, 0, 0] } # Left side - screws { name: 'shms-m2-04-017' source: '3d/tapster-3/socket-head-machine-screw-M2-04.stl' color: 0x666666 visible: true translate: [-servo_width_offset + 6, 0 , 8] rotate: [90, -90, 0] } { name: 'shms-m2-04-018' source: '3d/tapster-3/socket-head-machine-screw-M2-04.stl' color: 0x666666 visible: true translate: [-servo_width_offset + 6, -8 , 0] rotate: [90, -90, 0] } { name: 'shms-m2-04-019' source: '3d/tapster-3/socket-head-machine-screw-M2-04.stl' color: 0x666666 visible: true translate: [-servo_width_offset + 6, 0 , -8] rotate: [90, -90, 0] } { name: 'shms-m2-04-020' source: '3d/tapster-3/socket-head-machine-screw-M2-04.stl' color: 0x666666 visible: true translate: [-servo_width_offset + 6, 8 , 0] rotate: [90, -90, 0] } # Right side - screws { name: 'shms-m2-04-021' source: '3d/tapster-3/socket-head-machine-screw-M2-04.stl' color: 0x666666 visible: true translate: [servo_width_offset - 6, 0 , 8] rotate: [90, 90, 0] } { name: 'shms-m2-04-022' source: '3d/tapster-3/socket-head-machine-screw-M2-04.stl' color: 0x666666 visible: true translate: [servo_width_offset - 6, 8 , 0] rotate: [90, 90, 0] } { name: 'shms-m2-04-023' source: '3d/tapster-3/socket-head-machine-screw-M2-04.stl' color: 0x666666 visible: true translate: [servo_width_offset - 6, 0 , -8] rotate: [90, 90, 0] } { name: 'shms-m2-04-024' source: '3d/tapster-3/socket-head-machine-screw-M2-04.stl' color: 0x666666 visible: true translate: [servo_width_offset - 6, -8 , 0] rotate: [90, 90, 0] } { group: name: "upper-u-joint-assembly-3" translate: [0, -70, -3.5] rotate: [270 - c.beta, 0, 0] visible: true parts: [ { name: 'u-joint-fork-009' source: '3d/tapster-3/u_joint_fork.stl' color: 0xDF1F1F visible: true translate: [-upper_arm_joint_width_offset, 0 , 0] rotate: [0, 0, 90] } { name: 'u-joint-fork-010' source: '3d/tapster-3/u_joint_fork.stl' color: 0xDF1F1F visible: true translate: [upper_arm_joint_width_offset, 0 , 0] rotate: [0, 0, -90] } { name: 'bhcs-m3-18-009' source: '3d/tapster-3/button-head-cap-screw-M3-18.stl' color: 0x666666 visible: true translate: [-upper_arm_joint_width_offset - 13.5, 11.35 , 0] rotate: [90, 0, 0] } { name: 'bhcs-m3-18-010' source: '3d/tapster-3/button-head-cap-screw-M3-18.stl' color: 0x666666 visible: true translate: [upper_arm_joint_width_offset + 13.5, 11.35 , 0] rotate: [90, 0, 0] } { name: 'hn-m3-nl-009' source: '3d/tapster-3/hex-nut-m3-nyloc.stl' color: 0x777777 visible: true translate: [-upper_arm_joint_width_offset - 13.5, 13.30/2 , 0] rotate: [-90, 0, 0] } { name: 'hn-m3-nl-010' source: '3d/tapster-3/hex-nut-m3-nyloc.stl' color: 0x777777 visible: true translate: [upper_arm_joint_width_offset + 13.5, 13.30/2 , 0] rotate: [-90, 0, 0] } ] } { group: name: "lower-u-joint-assembly-3" translate: [0, -70, -3.5] rotate: [90 - c.beta, -c.gamma, 0] visible: true parts: [ group: name: "lower-u-joint-rotation-axis-3" translate: [0, 0, -133.5] rotate: [0, c.gamma, 0] parts: [ { name: 'u-joint-fork-011' source: '3d/tapster-3/u_joint_fork.stl' color: 0xDF1F1F visible: true translate: [-upper_arm_joint_width_offset, 0, 0] rotate: [0, 0, 90] } { name: 'u-joint-fork-012' source: '3d/tapster-3/u_joint_fork.stl' color: 0xDF1F1F visible: true translate: [upper_arm_joint_width_offset, 0, 0] rotate: [0, 0, -90] } { name: 'bhcs-m3-18-011' source: '3d/tapster-3/button-head-cap-screw-M3-18.stl' color: 0x666666 visible: true translate: [-upper_arm_joint_width_offset - 13.5, -11.35 , 0] rotate: [-90, 0, 0] } { name: 'bhcs-m3-18-012' source: '3d/tapster-3/button-head-cap-screw-M3-18.stl' color: 0x666666 visible: true translate: [upper_arm_joint_width_offset + 13.5, -11.35 , 0] rotate: [-90, 0, 0] } { name: 'hn-m3-nl-011' source: '3d/tapster-3/hex-nut-m3-nyloc.stl' color: 0x777777 visible: true translate: [-upper_arm_joint_width_offset - 13.5, -13.30/2 , 0] rotate: [90, 0, 0] } { name: 'hn-m3-nl-012' source: '3d/tapster-3/hex-nut-m3-nyloc.stl' color: 0x777777 visible: true translate: [upper_arm_joint_width_offset + 13.5, -13.30/2 , 0] rotate: [90, 0, 0] } ] ] } { group: name: "linkage-assembly-5" translate: [0, -70, -3.5] rotate: [0, 0, 0] parts: [ group: name: "linkage-rotation-axis-5" translate: [-upper_arm_joint_width_offset - 13.5, 0, 0] rotate: [90 - c.beta, -c.gamma, 0] parts: [ { name: 'rod-118mm-005' source: '3d/tapster-3/rod-118mm.stl' color: 0x666666 visible: true translate: [0, 0 , -7.75] rotate: [180, 0, 0] } { name: 'rod-end-09' source: '3d/tapster-3/rod-end.stl' color: 0x333333 visible: true translate: [0, 0 , 0] rotate: [0, 0, 0] } { name: 'ball-009' source: '3d/tapster-3/traxxas-5347-hollow-ball.stl' color: 0xAAAAAA visible: true translate: [0, 0 , 0] rotate: [0, 0, 0] } { name: 'rod-end-010' source: '3d/tapster-3/rod-end.stl' color: 0x333333 visible: true translate: [0, 0 , -133.5] rotate: [0, 180, 0] } { name: 'ball-010' source: '3d/tapster-3/traxxas-5347-hollow-ball.stl' color: 0xAAAAAA visible: true translate: [0, 0 , -133.5] rotate: [0, 0, 0] } ] ] } { group: name: "linkage-assembly-6" translate: [0, -70, -3.5] rotate: [0, 0, 0] parts: [ group: name: "linkage-rotation-axis-6" translate: [upper_arm_joint_width_offset + 13.5, 0, 0] rotate: [90 - c.beta, -c.gamma, 0] parts: [ { name: 'rod-118mm-006' source: '3d/tapster-3/rod-118mm.stl' color: 0x666666 visible: true translate: [0, 0 , -7.75] rotate: [180, 0, 0] } { name: 'rod-end-011' source: '3d/tapster-3/rod-end.stl' color: 0x333333 visible: true translate: [0, 0 , 0] rotate: [0, 0, 0] } { name: 'ball-011' source: '3d/tapster-3/traxxas-5347-hollow-ball.stl' color: 0xAAAAAA visible: true translate: [0, 0 , 0] rotate: [0, 0, 0] } { name: 'rod-end-012' source: '3d/tapster-3/rod-end.stl' color: 0x333333 visible: true translate: [0, 0 , -133.5] rotate: [0, 180, 0] } { name: 'ball-012' source: '3d/tapster-3/traxxas-5347-hollow-ball.stl' color: 0xAAAAAA visible: true translate: [0, 0 , -133.5] rotate: [0, 0, 0] } ] ] } ] } ]
[ { "context": "script.\r\n#\r\n# MIT License\r\n#\r\n# Copyright (c) 2014 Dennis Raymondo van der Sluis\r\n#\r\n# Permission is hereby granted, free of charg", "end": 164, "score": 0.9998748898506165, "start": 135, "tag": "NAME", "value": "Dennis Raymondo van der Sluis" } ]
words.coffee
phazelift/words.js
1
# # words.coffee - A Javascript word-string manipulation library, written in Coffeescript. # # MIT License # # Copyright (c) 2014 Dennis Raymondo van der Sluis # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # "use strict" Strings = _ = require "strings.js" types = Strings.Types Chars = Strings.Chars class Words_ @delimiter: ' ' @stringsFromArray: ( array ) -> strings= [] for value in _.forceArray array strings.push value if _.isString value return strings @numbersFromArray: ( array ) -> numbers= [] for value in _.forceArray array numbers.push (value+ 0) if _.isNumber value return numbers # call with context! @changeCase: ( method, args ) -> words= Words_.stringsFromArray args indices= Words_.numbersFromArray args if words.length > 0 then @set Strings[ method ] @string, words... # strings if indices[0] is 0 then for pos in indices # words[indices] (characters) for index in [ 0..@count- 1 ] @words[ index ]= Strings[ method ] @words[ index ], pos else indices= [0..@count] if args.length < 1 # words for index in indices index= _.positiveIndex index, @count @words[ index ]= Strings[ method ] @words[ index ] @applyToValidIndex: ( orgIndex, limit, callback ) => callback( index ) if false isnt index= _.positiveIndex orgIndex, limit class Words extends Strings constructor: ( args... ) -> super() @set.apply @, arguments set: ( args... ) -> @words= [] args= _.intoArray.apply @, args return @ if args.length < 1 for arg in args @words.push( str ) for str in Strings.split Strings.create(arg), Words_.delimiter return @ get: -> return @words.join( Words_.delimiter ) if arguments.length < 1 string= '' for index in arguments index= _.positiveIndex( index, @count ) string+= @words[ index ]+ Words_.delimiter if index isnt false return Strings.trim string xs: ( callback= -> true ) -> return @ if _.notFunction(callback) or @count < 1 result= [] for word, index in @words if response= callback( word, index ) if response is true then result.push word else if _.isStringOrNumber response result.push response+ '' @words= result return @ find: ( string ) -> indices= [] if '' isnt string= _.forceString string @xs ( word, index ) -> indices.push(index+ 1) if word is string return true return indices upper: -> Words_.changeCase.call @, 'upper', Array::slice.call arguments; @ lower: -> Words_.changeCase.call @, 'lower', Array::slice.call arguments; @ reverse: -> if arguments?[0] is 0 then @xs ( word ) -> Strings.reverse word else if arguments.length > 0 then for arg in arguments Words_.applyToValidIndex arg, @count, ( index ) => @words[ index ]= Strings.reverse @words[ index ] else @xs (word, index) => @get @count- index return @ shuffle: ( selection ) -> if selection? if _.isString( selection ) then for arg in arguments @xs ( word, index ) => return Strings.shuffle( word ) if word is arg return true else if selection is 0 @xs ( word ) -> Strings.shuffle word else for arg in arguments then Words_.applyToValidIndex arg, @count, ( index ) => @words[ index ]= Strings.shuffle @words[ index ] else @words= _.shuffleArray @words return @ clear: -> @words= []; @ remove: -> return @ if arguments.length < 1 args= [] for arg in arguments if _.isString arg args.unshift arg else if _.isNumber arg args.push Words.positiveIndex arg, @count args= _.noDupAndReverse _.insertSort args for arg, index in args if _.isNumber arg @xs ( word, index ) => true if index isnt arg else if _.isString arg then @xs ( word ) -> true if word isnt arg return @ pop: ( amount ) -> amount= Math.abs _.forceNumber amount, 1 popped= '' for n in [ 1..amount ] pop= @words.pop() popped= (pop+ ' '+ popped) if pop isnt undefined return popped.trim() push: -> for arg in arguments @words.push Strings.trim( arg ) if ('' isnt arg= _.forceString arg) return @ shift: ( amount ) -> amount= _.forceNumber amount, 1 @words.shift() for n in [1..amount] return @ prepend: -> pos= 0 for arg in arguments if '' isnt arg= _.forceString arg @words.splice( pos, 0, Strings.trim arg ) pos++ return @ insert: ( index, words... ) -> index= _.positiveIndex index, @count pos= 0 for word in words if '' isnt word= _.forceString word @words.splice( index+ pos, 0, Strings.trim word ) pos++ return @ replace: ( selection, replacement= '' ) -> return @ if '' is replacement= Strings.trim replacement if _.isNumber selection Words_.applyToValidIndex selection, @count, ( index ) => @words.splice index, 1, replacement else @xs ( word ) -> return replacement if word is selection return true return @ sort: -> _.insertSort @words; @ # refactor these two later.. startsWith: ( start ) -> return false if '' is start= _.forceString start result= true start= new Words start start.xs (word, index) => result= false if word isnt @words[ index ] return result endsWith: ( end ) -> return false if '' is end= _.forceString end result= true count= 1 end= new Words end for index in [end.count..1] result= false if ( end.get(index) isnt @words[@count- count++] ) return result Object.defineProperty Words::, '$', { get: -> @.get() } Object.defineProperty Words::, 'string', { get: -> @.get() } Object.defineProperty Words::, 'count', { get: -> @words.length } Words::unshift = Words::prepend Words.flexArgs = types.intoArray Words.Strings = Strings Words.types = types Words.Chars = Chars if define? and ( 'function' is typeof define ) and define.amd define 'words', [], -> Words else if window? window.Words = Words window.types = types window.Strings = Strings else if module? module.exports = Words
113479
# # words.coffee - A Javascript word-string manipulation library, written in Coffeescript. # # MIT License # # Copyright (c) 2014 <NAME> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # "use strict" Strings = _ = require "strings.js" types = Strings.Types Chars = Strings.Chars class Words_ @delimiter: ' ' @stringsFromArray: ( array ) -> strings= [] for value in _.forceArray array strings.push value if _.isString value return strings @numbersFromArray: ( array ) -> numbers= [] for value in _.forceArray array numbers.push (value+ 0) if _.isNumber value return numbers # call with context! @changeCase: ( method, args ) -> words= Words_.stringsFromArray args indices= Words_.numbersFromArray args if words.length > 0 then @set Strings[ method ] @string, words... # strings if indices[0] is 0 then for pos in indices # words[indices] (characters) for index in [ 0..@count- 1 ] @words[ index ]= Strings[ method ] @words[ index ], pos else indices= [0..@count] if args.length < 1 # words for index in indices index= _.positiveIndex index, @count @words[ index ]= Strings[ method ] @words[ index ] @applyToValidIndex: ( orgIndex, limit, callback ) => callback( index ) if false isnt index= _.positiveIndex orgIndex, limit class Words extends Strings constructor: ( args... ) -> super() @set.apply @, arguments set: ( args... ) -> @words= [] args= _.intoArray.apply @, args return @ if args.length < 1 for arg in args @words.push( str ) for str in Strings.split Strings.create(arg), Words_.delimiter return @ get: -> return @words.join( Words_.delimiter ) if arguments.length < 1 string= '' for index in arguments index= _.positiveIndex( index, @count ) string+= @words[ index ]+ Words_.delimiter if index isnt false return Strings.trim string xs: ( callback= -> true ) -> return @ if _.notFunction(callback) or @count < 1 result= [] for word, index in @words if response= callback( word, index ) if response is true then result.push word else if _.isStringOrNumber response result.push response+ '' @words= result return @ find: ( string ) -> indices= [] if '' isnt string= _.forceString string @xs ( word, index ) -> indices.push(index+ 1) if word is string return true return indices upper: -> Words_.changeCase.call @, 'upper', Array::slice.call arguments; @ lower: -> Words_.changeCase.call @, 'lower', Array::slice.call arguments; @ reverse: -> if arguments?[0] is 0 then @xs ( word ) -> Strings.reverse word else if arguments.length > 0 then for arg in arguments Words_.applyToValidIndex arg, @count, ( index ) => @words[ index ]= Strings.reverse @words[ index ] else @xs (word, index) => @get @count- index return @ shuffle: ( selection ) -> if selection? if _.isString( selection ) then for arg in arguments @xs ( word, index ) => return Strings.shuffle( word ) if word is arg return true else if selection is 0 @xs ( word ) -> Strings.shuffle word else for arg in arguments then Words_.applyToValidIndex arg, @count, ( index ) => @words[ index ]= Strings.shuffle @words[ index ] else @words= _.shuffleArray @words return @ clear: -> @words= []; @ remove: -> return @ if arguments.length < 1 args= [] for arg in arguments if _.isString arg args.unshift arg else if _.isNumber arg args.push Words.positiveIndex arg, @count args= _.noDupAndReverse _.insertSort args for arg, index in args if _.isNumber arg @xs ( word, index ) => true if index isnt arg else if _.isString arg then @xs ( word ) -> true if word isnt arg return @ pop: ( amount ) -> amount= Math.abs _.forceNumber amount, 1 popped= '' for n in [ 1..amount ] pop= @words.pop() popped= (pop+ ' '+ popped) if pop isnt undefined return popped.trim() push: -> for arg in arguments @words.push Strings.trim( arg ) if ('' isnt arg= _.forceString arg) return @ shift: ( amount ) -> amount= _.forceNumber amount, 1 @words.shift() for n in [1..amount] return @ prepend: -> pos= 0 for arg in arguments if '' isnt arg= _.forceString arg @words.splice( pos, 0, Strings.trim arg ) pos++ return @ insert: ( index, words... ) -> index= _.positiveIndex index, @count pos= 0 for word in words if '' isnt word= _.forceString word @words.splice( index+ pos, 0, Strings.trim word ) pos++ return @ replace: ( selection, replacement= '' ) -> return @ if '' is replacement= Strings.trim replacement if _.isNumber selection Words_.applyToValidIndex selection, @count, ( index ) => @words.splice index, 1, replacement else @xs ( word ) -> return replacement if word is selection return true return @ sort: -> _.insertSort @words; @ # refactor these two later.. startsWith: ( start ) -> return false if '' is start= _.forceString start result= true start= new Words start start.xs (word, index) => result= false if word isnt @words[ index ] return result endsWith: ( end ) -> return false if '' is end= _.forceString end result= true count= 1 end= new Words end for index in [end.count..1] result= false if ( end.get(index) isnt @words[@count- count++] ) return result Object.defineProperty Words::, '$', { get: -> @.get() } Object.defineProperty Words::, 'string', { get: -> @.get() } Object.defineProperty Words::, 'count', { get: -> @words.length } Words::unshift = Words::prepend Words.flexArgs = types.intoArray Words.Strings = Strings Words.types = types Words.Chars = Chars if define? and ( 'function' is typeof define ) and define.amd define 'words', [], -> Words else if window? window.Words = Words window.types = types window.Strings = Strings else if module? module.exports = Words
true
# # words.coffee - A Javascript word-string manipulation library, written in Coffeescript. # # MIT License # # Copyright (c) 2014 PI:NAME:<NAME>END_PI # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # "use strict" Strings = _ = require "strings.js" types = Strings.Types Chars = Strings.Chars class Words_ @delimiter: ' ' @stringsFromArray: ( array ) -> strings= [] for value in _.forceArray array strings.push value if _.isString value return strings @numbersFromArray: ( array ) -> numbers= [] for value in _.forceArray array numbers.push (value+ 0) if _.isNumber value return numbers # call with context! @changeCase: ( method, args ) -> words= Words_.stringsFromArray args indices= Words_.numbersFromArray args if words.length > 0 then @set Strings[ method ] @string, words... # strings if indices[0] is 0 then for pos in indices # words[indices] (characters) for index in [ 0..@count- 1 ] @words[ index ]= Strings[ method ] @words[ index ], pos else indices= [0..@count] if args.length < 1 # words for index in indices index= _.positiveIndex index, @count @words[ index ]= Strings[ method ] @words[ index ] @applyToValidIndex: ( orgIndex, limit, callback ) => callback( index ) if false isnt index= _.positiveIndex orgIndex, limit class Words extends Strings constructor: ( args... ) -> super() @set.apply @, arguments set: ( args... ) -> @words= [] args= _.intoArray.apply @, args return @ if args.length < 1 for arg in args @words.push( str ) for str in Strings.split Strings.create(arg), Words_.delimiter return @ get: -> return @words.join( Words_.delimiter ) if arguments.length < 1 string= '' for index in arguments index= _.positiveIndex( index, @count ) string+= @words[ index ]+ Words_.delimiter if index isnt false return Strings.trim string xs: ( callback= -> true ) -> return @ if _.notFunction(callback) or @count < 1 result= [] for word, index in @words if response= callback( word, index ) if response is true then result.push word else if _.isStringOrNumber response result.push response+ '' @words= result return @ find: ( string ) -> indices= [] if '' isnt string= _.forceString string @xs ( word, index ) -> indices.push(index+ 1) if word is string return true return indices upper: -> Words_.changeCase.call @, 'upper', Array::slice.call arguments; @ lower: -> Words_.changeCase.call @, 'lower', Array::slice.call arguments; @ reverse: -> if arguments?[0] is 0 then @xs ( word ) -> Strings.reverse word else if arguments.length > 0 then for arg in arguments Words_.applyToValidIndex arg, @count, ( index ) => @words[ index ]= Strings.reverse @words[ index ] else @xs (word, index) => @get @count- index return @ shuffle: ( selection ) -> if selection? if _.isString( selection ) then for arg in arguments @xs ( word, index ) => return Strings.shuffle( word ) if word is arg return true else if selection is 0 @xs ( word ) -> Strings.shuffle word else for arg in arguments then Words_.applyToValidIndex arg, @count, ( index ) => @words[ index ]= Strings.shuffle @words[ index ] else @words= _.shuffleArray @words return @ clear: -> @words= []; @ remove: -> return @ if arguments.length < 1 args= [] for arg in arguments if _.isString arg args.unshift arg else if _.isNumber arg args.push Words.positiveIndex arg, @count args= _.noDupAndReverse _.insertSort args for arg, index in args if _.isNumber arg @xs ( word, index ) => true if index isnt arg else if _.isString arg then @xs ( word ) -> true if word isnt arg return @ pop: ( amount ) -> amount= Math.abs _.forceNumber amount, 1 popped= '' for n in [ 1..amount ] pop= @words.pop() popped= (pop+ ' '+ popped) if pop isnt undefined return popped.trim() push: -> for arg in arguments @words.push Strings.trim( arg ) if ('' isnt arg= _.forceString arg) return @ shift: ( amount ) -> amount= _.forceNumber amount, 1 @words.shift() for n in [1..amount] return @ prepend: -> pos= 0 for arg in arguments if '' isnt arg= _.forceString arg @words.splice( pos, 0, Strings.trim arg ) pos++ return @ insert: ( index, words... ) -> index= _.positiveIndex index, @count pos= 0 for word in words if '' isnt word= _.forceString word @words.splice( index+ pos, 0, Strings.trim word ) pos++ return @ replace: ( selection, replacement= '' ) -> return @ if '' is replacement= Strings.trim replacement if _.isNumber selection Words_.applyToValidIndex selection, @count, ( index ) => @words.splice index, 1, replacement else @xs ( word ) -> return replacement if word is selection return true return @ sort: -> _.insertSort @words; @ # refactor these two later.. startsWith: ( start ) -> return false if '' is start= _.forceString start result= true start= new Words start start.xs (word, index) => result= false if word isnt @words[ index ] return result endsWith: ( end ) -> return false if '' is end= _.forceString end result= true count= 1 end= new Words end for index in [end.count..1] result= false if ( end.get(index) isnt @words[@count- count++] ) return result Object.defineProperty Words::, '$', { get: -> @.get() } Object.defineProperty Words::, 'string', { get: -> @.get() } Object.defineProperty Words::, 'count', { get: -> @words.length } Words::unshift = Words::prepend Words.flexArgs = types.intoArray Words.Strings = Strings Words.types = types Words.Chars = Chars if define? and ( 'function' is typeof define ) and define.amd define 'words', [], -> Words else if window? window.Words = Words window.types = types window.Strings = Strings else if module? module.exports = Words
[ { "context": "should assign the value and wait', ->\n\n key = 'key'\n val = 'test'\n values =\n value: val\n ", "end": 524, "score": 0.7823352813720703, "start": 521, "tag": "KEY", "value": "key" }, { "context": "e value and wait', ->\n\n key = 'key'\n val = 'test...
test/lib/test-special.coffee
elidoran/endeo-decoder
0
assert = require 'assert' B = require '@endeo/bytes' node = require '../../lib/complex-nodes/special.coffee' testNode = require '../helpers/complex-node-test.coffee' describe 'test special', -> N = neededNodes = start: {} value: {} int : {} special : {} defaults: {} specialT: {} it 'should wait for bytes', -> values = specIndex: 0, spec: array: ['non-zero-length'] testNode node, neededNodes, [], [], 'wait', values it 'should assign the value and wait', -> key = 'key' val = 'test' values = value: val spec: array: [1, {key}, 3] specIndex: 1 specObject: {} context = testNode node, neededNodes, [], [], 'wait', values assert.equal context.value, null assert.equal context.specObject[key], val assert.equal context.specIndex, 2 it 'should pop spec and move to specialT', -> spec = array: [] values = specIndex: 0 spec: spec value: null popSpec: -> spec context = testNode node, neededNodes, [N.specialT], [], 'next', values assert.equal context.value, spec it 'should pop spec, consume sub terminator, and move to next', -> spec = array: [] values = specIndex: 0 spec: spec value: null popSpec: -> spec context = testNode node, neededNodes, [], [B.SUB_TERMINATOR], 'next', values assert.equal context.value, spec assert.equal context.index, 1 it 'should pop spec, consume terminator, and move to start', -> spec = array: [] values = specIndex: 0 spec: spec value: null popSpec: -> spec context = testNode node, neededNodes, [N.start], [B.TERMINATOR], 'next', values assert.equal context.value, spec assert.equal context.index, 1 it 'should pop spec, see non-terminator, and fail', -> spec = array: [] values = specIndex: 0 spec: spec value: null popSpec: -> spec context = testNode node, neededNodes, [], [B.STRING], 'fail', values assert.equal context.value, spec assert.equal context.index, 0 # back()'d it 'should see non-default and move to next nodes', -> spec = array: [1,2] values = specIndex: 0 spec: spec value: null popSpec: -> spec nextNodes = [ N.value, N.special ] context = testNode node, neededNodes, nextNodes, [B.STRING], 'next', values assert.equal context.index, 0 assert.equal context.specIndex, 0 it 'should skip single default', -> spec = array: [1,2] values = specIndex: 0 spec: spec value: null popSpec: -> spec nextNodes = [] context = testNode node, neededNodes, nextNodes, [B.DEFAULT], 'wait', values assert.equal context.index, 1 assert.equal context.specIndex, 1 it 'should skip three defaults', -> spec = array: [1,2,3,4] values = specIndex: 0 spec: spec value: null popSpec: -> spec nextNodes = [] bytes = [B.DEFAULT,B.DEFAULT,B.DEFAULT] context = testNode node, neededNodes, nextNodes, bytes, 'wait', values assert.equal context.index, 3 assert.equal context.specIndex, 3 it 'should skip five defaults', -> spec = array: [1,2,3,4,5,6] values = specIndex: 0 spec: spec value: null popSpec: -> spec nextNodes = [] bytes = [B.DEFAULT5] context = testNode node, neededNodes, nextNodes, bytes, 'wait', values assert.equal context.index, 1 assert.equal context.specIndex, 5 it 'should skip n defaults and move to int', -> spec = array: [1,2] values = specIndex: 0 spec: spec value: null popSpec: -> spec nextNodes = [ N.int, N.defaults, N.special ] bytes = [B.DEFAULTN] context = testNode node, neededNodes, nextNodes, bytes, 'next', values assert.equal context.index, 1 it 'should skip 7+n defaults and move to int', -> spec = array: [1,2,3,4,5,6,7,8] values = specIndex: 0 spec: spec value: null popSpec: -> spec nextNodes = [ N.int, N.defaults, N.special ] bytes = [B.DEFAULT, B.DEFAULT5, B.DEFAULT, B.DEFAULTN] context = testNode node, neededNodes, nextNodes, bytes, 'next', values assert.equal context.index, 4 assert.equal context.specIndex, 7
45072
assert = require 'assert' B = require '@endeo/bytes' node = require '../../lib/complex-nodes/special.coffee' testNode = require '../helpers/complex-node-test.coffee' describe 'test special', -> N = neededNodes = start: {} value: {} int : {} special : {} defaults: {} specialT: {} it 'should wait for bytes', -> values = specIndex: 0, spec: array: ['non-zero-length'] testNode node, neededNodes, [], [], 'wait', values it 'should assign the value and wait', -> key = '<KEY>' val = '<PASSWORD>' values = value: val spec: array: [1, {key}, 3] specIndex: 1 specObject: {} context = testNode node, neededNodes, [], [], 'wait', values assert.equal context.value, null assert.equal context.specObject[key], val assert.equal context.specIndex, 2 it 'should pop spec and move to specialT', -> spec = array: [] values = specIndex: 0 spec: spec value: null popSpec: -> spec context = testNode node, neededNodes, [N.specialT], [], 'next', values assert.equal context.value, spec it 'should pop spec, consume sub terminator, and move to next', -> spec = array: [] values = specIndex: 0 spec: spec value: null popSpec: -> spec context = testNode node, neededNodes, [], [B.SUB_TERMINATOR], 'next', values assert.equal context.value, spec assert.equal context.index, 1 it 'should pop spec, consume terminator, and move to start', -> spec = array: [] values = specIndex: 0 spec: spec value: null popSpec: -> spec context = testNode node, neededNodes, [N.start], [B.TERMINATOR], 'next', values assert.equal context.value, spec assert.equal context.index, 1 it 'should pop spec, see non-terminator, and fail', -> spec = array: [] values = specIndex: 0 spec: spec value: null popSpec: -> spec context = testNode node, neededNodes, [], [B.STRING], 'fail', values assert.equal context.value, spec assert.equal context.index, 0 # back()'d it 'should see non-default and move to next nodes', -> spec = array: [1,2] values = specIndex: 0 spec: spec value: null popSpec: -> spec nextNodes = [ N.value, N.special ] context = testNode node, neededNodes, nextNodes, [B.STRING], 'next', values assert.equal context.index, 0 assert.equal context.specIndex, 0 it 'should skip single default', -> spec = array: [1,2] values = specIndex: 0 spec: spec value: null popSpec: -> spec nextNodes = [] context = testNode node, neededNodes, nextNodes, [B.DEFAULT], 'wait', values assert.equal context.index, 1 assert.equal context.specIndex, 1 it 'should skip three defaults', -> spec = array: [1,2,3,4] values = specIndex: 0 spec: spec value: null popSpec: -> spec nextNodes = [] bytes = [B.DEFAULT,B.DEFAULT,B.DEFAULT] context = testNode node, neededNodes, nextNodes, bytes, 'wait', values assert.equal context.index, 3 assert.equal context.specIndex, 3 it 'should skip five defaults', -> spec = array: [1,2,3,4,5,6] values = specIndex: 0 spec: spec value: null popSpec: -> spec nextNodes = [] bytes = [B.DEFAULT5] context = testNode node, neededNodes, nextNodes, bytes, 'wait', values assert.equal context.index, 1 assert.equal context.specIndex, 5 it 'should skip n defaults and move to int', -> spec = array: [1,2] values = specIndex: 0 spec: spec value: null popSpec: -> spec nextNodes = [ N.int, N.defaults, N.special ] bytes = [B.DEFAULTN] context = testNode node, neededNodes, nextNodes, bytes, 'next', values assert.equal context.index, 1 it 'should skip 7+n defaults and move to int', -> spec = array: [1,2,3,4,5,6,7,8] values = specIndex: 0 spec: spec value: null popSpec: -> spec nextNodes = [ N.int, N.defaults, N.special ] bytes = [B.DEFAULT, B.DEFAULT5, B.DEFAULT, B.DEFAULTN] context = testNode node, neededNodes, nextNodes, bytes, 'next', values assert.equal context.index, 4 assert.equal context.specIndex, 7
true
assert = require 'assert' B = require '@endeo/bytes' node = require '../../lib/complex-nodes/special.coffee' testNode = require '../helpers/complex-node-test.coffee' describe 'test special', -> N = neededNodes = start: {} value: {} int : {} special : {} defaults: {} specialT: {} it 'should wait for bytes', -> values = specIndex: 0, spec: array: ['non-zero-length'] testNode node, neededNodes, [], [], 'wait', values it 'should assign the value and wait', -> key = 'PI:KEY:<KEY>END_PI' val = 'PI:PASSWORD:<PASSWORD>END_PI' values = value: val spec: array: [1, {key}, 3] specIndex: 1 specObject: {} context = testNode node, neededNodes, [], [], 'wait', values assert.equal context.value, null assert.equal context.specObject[key], val assert.equal context.specIndex, 2 it 'should pop spec and move to specialT', -> spec = array: [] values = specIndex: 0 spec: spec value: null popSpec: -> spec context = testNode node, neededNodes, [N.specialT], [], 'next', values assert.equal context.value, spec it 'should pop spec, consume sub terminator, and move to next', -> spec = array: [] values = specIndex: 0 spec: spec value: null popSpec: -> spec context = testNode node, neededNodes, [], [B.SUB_TERMINATOR], 'next', values assert.equal context.value, spec assert.equal context.index, 1 it 'should pop spec, consume terminator, and move to start', -> spec = array: [] values = specIndex: 0 spec: spec value: null popSpec: -> spec context = testNode node, neededNodes, [N.start], [B.TERMINATOR], 'next', values assert.equal context.value, spec assert.equal context.index, 1 it 'should pop spec, see non-terminator, and fail', -> spec = array: [] values = specIndex: 0 spec: spec value: null popSpec: -> spec context = testNode node, neededNodes, [], [B.STRING], 'fail', values assert.equal context.value, spec assert.equal context.index, 0 # back()'d it 'should see non-default and move to next nodes', -> spec = array: [1,2] values = specIndex: 0 spec: spec value: null popSpec: -> spec nextNodes = [ N.value, N.special ] context = testNode node, neededNodes, nextNodes, [B.STRING], 'next', values assert.equal context.index, 0 assert.equal context.specIndex, 0 it 'should skip single default', -> spec = array: [1,2] values = specIndex: 0 spec: spec value: null popSpec: -> spec nextNodes = [] context = testNode node, neededNodes, nextNodes, [B.DEFAULT], 'wait', values assert.equal context.index, 1 assert.equal context.specIndex, 1 it 'should skip three defaults', -> spec = array: [1,2,3,4] values = specIndex: 0 spec: spec value: null popSpec: -> spec nextNodes = [] bytes = [B.DEFAULT,B.DEFAULT,B.DEFAULT] context = testNode node, neededNodes, nextNodes, bytes, 'wait', values assert.equal context.index, 3 assert.equal context.specIndex, 3 it 'should skip five defaults', -> spec = array: [1,2,3,4,5,6] values = specIndex: 0 spec: spec value: null popSpec: -> spec nextNodes = [] bytes = [B.DEFAULT5] context = testNode node, neededNodes, nextNodes, bytes, 'wait', values assert.equal context.index, 1 assert.equal context.specIndex, 5 it 'should skip n defaults and move to int', -> spec = array: [1,2] values = specIndex: 0 spec: spec value: null popSpec: -> spec nextNodes = [ N.int, N.defaults, N.special ] bytes = [B.DEFAULTN] context = testNode node, neededNodes, nextNodes, bytes, 'next', values assert.equal context.index, 1 it 'should skip 7+n defaults and move to int', -> spec = array: [1,2,3,4,5,6,7,8] values = specIndex: 0 spec: spec value: null popSpec: -> spec nextNodes = [ N.int, N.defaults, N.special ] bytes = [B.DEFAULT, B.DEFAULT5, B.DEFAULT, B.DEFAULTN] context = testNode node, neededNodes, nextNodes, bytes, 'next', values assert.equal context.index, 4 assert.equal context.specIndex, 7
[ { "context": "ne you can find.\n#\n# <script>window.exampleKey = 'linear_spline'</script>\n# <script>drawGeometry(exampleKey, {hig", "end": 221, "score": 0.8661215901374817, "start": 208, "tag": "KEY", "value": "linear_spline" } ]
src/geom/linear_spline.coffee
abe33/agt
1
{Formattable, Sourcable} = require '../mixins' {Geometry, Path, Intersections, Spline} = require './mixins' # Public: The `LinearSpline` is the simplest spline you can find. # # <script>window.exampleKey = 'linear_spline'</script> # <script>drawGeometry(exampleKey, {highlight: true})</script> # # ### Included Mixins # # - {agt.geom.Geometry} # - {agt.geom.Intersections} # - {agt.geom.Path} # - [agt.mixins.Spline](../../../files/geom/mixins/spline.coffee.html) # - [agt.mixins.Formattable](../../../files/mixins/formattable.coffee.html) # - [agt.mixins.Memoizable](../../../files/mixins/memoizable.coffee.html) # - [agt.mixins.Sourcable](../../../files/mixins/sourcable.coffee.html) module.exports = class LinearSpline @include Formattable('LinearSpline') @include Sourcable('agt.geom.LinearSpline', 'vertices', 'bias') @include Geometry @include Path @include Intersections @include Spline(1) ### Public ### # Creates a new [LinearSpline]{agt.geom.LinearSpline} # # vertices - An {Array} of [Points]{agt.geom.Point} that forms the spline. constructor: (vertices) -> @initSpline vertices # The points of a linear spline are the same as its array of vertices. # # <script>drawGeometryPoints(exampleKey, 'points')</script> # # Returns an {Array} of [Points]{agt.geom.Point}. points: -> vertex.clone() for vertex in @vertices # Returns the number of segments in the spline. # # Returns a {Number} segments: -> @vertices.length - 1 # **Unsupported** - As the final points of a linear spine are its vertices # there's no need to render the connections between them. drawVerticesConnections: -> ### Internal ### # Validates the size of the vertices array. # # vertices - The {Array} of vertices to validate. # # Returns a {Boolean}. validateVertices: (vertices) -> vertices.length >= 2
114636
{Formattable, Sourcable} = require '../mixins' {Geometry, Path, Intersections, Spline} = require './mixins' # Public: The `LinearSpline` is the simplest spline you can find. # # <script>window.exampleKey = '<KEY>'</script> # <script>drawGeometry(exampleKey, {highlight: true})</script> # # ### Included Mixins # # - {agt.geom.Geometry} # - {agt.geom.Intersections} # - {agt.geom.Path} # - [agt.mixins.Spline](../../../files/geom/mixins/spline.coffee.html) # - [agt.mixins.Formattable](../../../files/mixins/formattable.coffee.html) # - [agt.mixins.Memoizable](../../../files/mixins/memoizable.coffee.html) # - [agt.mixins.Sourcable](../../../files/mixins/sourcable.coffee.html) module.exports = class LinearSpline @include Formattable('LinearSpline') @include Sourcable('agt.geom.LinearSpline', 'vertices', 'bias') @include Geometry @include Path @include Intersections @include Spline(1) ### Public ### # Creates a new [LinearSpline]{agt.geom.LinearSpline} # # vertices - An {Array} of [Points]{agt.geom.Point} that forms the spline. constructor: (vertices) -> @initSpline vertices # The points of a linear spline are the same as its array of vertices. # # <script>drawGeometryPoints(exampleKey, 'points')</script> # # Returns an {Array} of [Points]{agt.geom.Point}. points: -> vertex.clone() for vertex in @vertices # Returns the number of segments in the spline. # # Returns a {Number} segments: -> @vertices.length - 1 # **Unsupported** - As the final points of a linear spine are its vertices # there's no need to render the connections between them. drawVerticesConnections: -> ### Internal ### # Validates the size of the vertices array. # # vertices - The {Array} of vertices to validate. # # Returns a {Boolean}. validateVertices: (vertices) -> vertices.length >= 2
true
{Formattable, Sourcable} = require '../mixins' {Geometry, Path, Intersections, Spline} = require './mixins' # Public: The `LinearSpline` is the simplest spline you can find. # # <script>window.exampleKey = 'PI:KEY:<KEY>END_PI'</script> # <script>drawGeometry(exampleKey, {highlight: true})</script> # # ### Included Mixins # # - {agt.geom.Geometry} # - {agt.geom.Intersections} # - {agt.geom.Path} # - [agt.mixins.Spline](../../../files/geom/mixins/spline.coffee.html) # - [agt.mixins.Formattable](../../../files/mixins/formattable.coffee.html) # - [agt.mixins.Memoizable](../../../files/mixins/memoizable.coffee.html) # - [agt.mixins.Sourcable](../../../files/mixins/sourcable.coffee.html) module.exports = class LinearSpline @include Formattable('LinearSpline') @include Sourcable('agt.geom.LinearSpline', 'vertices', 'bias') @include Geometry @include Path @include Intersections @include Spline(1) ### Public ### # Creates a new [LinearSpline]{agt.geom.LinearSpline} # # vertices - An {Array} of [Points]{agt.geom.Point} that forms the spline. constructor: (vertices) -> @initSpline vertices # The points of a linear spline are the same as its array of vertices. # # <script>drawGeometryPoints(exampleKey, 'points')</script> # # Returns an {Array} of [Points]{agt.geom.Point}. points: -> vertex.clone() for vertex in @vertices # Returns the number of segments in the spline. # # Returns a {Number} segments: -> @vertices.length - 1 # **Unsupported** - As the final points of a linear spine are its vertices # there's no need to render the connections between them. drawVerticesConnections: -> ### Internal ### # Validates the size of the vertices array. # # vertices - The {Array} of vertices to validate. # # Returns a {Boolean}. validateVertices: (vertices) -> vertices.length >= 2
[ { "context": " id: row.id\n key: row.key\n password: row.password\n allowComments: row.allow_comments\n cre", "end": 1216, "score": 0.999254047870636, "start": 1204, "tag": "PASSWORD", "value": "row.password" }, { "context": " id: row.id\n key: row.key\...
player/src/models/shares.coffee
setpixel/storyboard-fountain
148
_ = require('underscore') util = require('util') moment = require('moment') pg = require('../db/pg') shortId = require('shortid') class Share @id: null constructor: (data) -> {@key, @password, @allowComments, @createdAt} = data if data? @key = shortId.generate() unless @key? module.exports = { initialize: (next) -> next() Share, save: (share, next) -> createdAt = new Date() sql = """ INSERT INTO shares(key, password, allow_comments, created_at) VALUES ($1, $2, $3, $4) RETURNING id """ fields = [ share.key share.password share.allowComments createdAt ] await pg.query sql, fields, defer(err, result) return next(err) if err? id = result?.rows?[0].id return next('invalid id') unless id? share.id = id share.createdAt = createdAt next() lookupByKey: (key, next) -> sql = """ SELECT * FROM shares WHERE key = $1 """ fields = [key] await pg.query sql, fields, defer(err, result) return next(err) if err? row = result?.rows?[0] # not found return next(null) unless row? data = { id: row.id key: row.key password: row.password allowComments: row.allow_comments createdAt: row.created_at } next(null, new Share(data)) list: (next) -> sql = """ SELECT * FROM shares ORDER BY created_at DESC """ fields = [] await pg.query sql, fields, defer(err, result) return next(err) if err? shares = [] for row in result.rows data = { id: row.id key: row.key password: row.password allowComments: row.allow_comments createdAt: row.created_at } shares.push new Share(data) next(null, shares) }
45835
_ = require('underscore') util = require('util') moment = require('moment') pg = require('../db/pg') shortId = require('shortid') class Share @id: null constructor: (data) -> {@key, @password, @allowComments, @createdAt} = data if data? @key = shortId.generate() unless @key? module.exports = { initialize: (next) -> next() Share, save: (share, next) -> createdAt = new Date() sql = """ INSERT INTO shares(key, password, allow_comments, created_at) VALUES ($1, $2, $3, $4) RETURNING id """ fields = [ share.key share.password share.allowComments createdAt ] await pg.query sql, fields, defer(err, result) return next(err) if err? id = result?.rows?[0].id return next('invalid id') unless id? share.id = id share.createdAt = createdAt next() lookupByKey: (key, next) -> sql = """ SELECT * FROM shares WHERE key = $1 """ fields = [key] await pg.query sql, fields, defer(err, result) return next(err) if err? row = result?.rows?[0] # not found return next(null) unless row? data = { id: row.id key: row.key password: <PASSWORD> allowComments: row.allow_comments createdAt: row.created_at } next(null, new Share(data)) list: (next) -> sql = """ SELECT * FROM shares ORDER BY created_at DESC """ fields = [] await pg.query sql, fields, defer(err, result) return next(err) if err? shares = [] for row in result.rows data = { id: row.id key: row.key password: <PASSWORD> allowComments: row.allow_comments createdAt: row.created_at } shares.push new Share(data) next(null, shares) }
true
_ = require('underscore') util = require('util') moment = require('moment') pg = require('../db/pg') shortId = require('shortid') class Share @id: null constructor: (data) -> {@key, @password, @allowComments, @createdAt} = data if data? @key = shortId.generate() unless @key? module.exports = { initialize: (next) -> next() Share, save: (share, next) -> createdAt = new Date() sql = """ INSERT INTO shares(key, password, allow_comments, created_at) VALUES ($1, $2, $3, $4) RETURNING id """ fields = [ share.key share.password share.allowComments createdAt ] await pg.query sql, fields, defer(err, result) return next(err) if err? id = result?.rows?[0].id return next('invalid id') unless id? share.id = id share.createdAt = createdAt next() lookupByKey: (key, next) -> sql = """ SELECT * FROM shares WHERE key = $1 """ fields = [key] await pg.query sql, fields, defer(err, result) return next(err) if err? row = result?.rows?[0] # not found return next(null) unless row? data = { id: row.id key: row.key password: PI:PASSWORD:<PASSWORD>END_PI allowComments: row.allow_comments createdAt: row.created_at } next(null, new Share(data)) list: (next) -> sql = """ SELECT * FROM shares ORDER BY created_at DESC """ fields = [] await pg.query sql, fields, defer(err, result) return next(err) if err? shares = [] for row in result.rows data = { id: row.id key: row.key password: PI:PASSWORD:<PASSWORD>END_PI allowComments: row.allow_comments createdAt: row.created_at } shares.push new Share(data) next(null, shares) }
[ { "context": " person.Nombre\n meta:\n from: \"victtorglez@gmail.com\"\n to: person.Email\n subject", "end": 2951, "score": 0.9999163150787354, "start": 2930, "tag": "EMAIL", "value": "victtorglez@gmail.com" } ]
src/main.coffee
aficiomaquinas/lending-reminders
0
require('dotenv').load() util = require 'util' blockspring = require 'blockspring' escape = require 'escape-html' request = require 'request' module.exports = class App constructor: -> @api = process.env.BLOCKSPRING_API @gsheet_items_url = process.env.G_SHEET_ITEMS_URL @gsheet_persons_url = process.env.G_SHEET_PERSONS_URL @gsheet_items_id = process.env.G_SHEET_ITEMS_ID @gsheet_persons_id = process.env.G_SHEET_PERSONS_ID @email = [] siblingArray = (arr, key, match) -> matches = arr.filter((val, index, array) -> val[key] is match ) return matches getGSheetJsonPromise: (url, query) -> return new Promise (resolve, reject) -> blockspring.runParsed 'query-google-spreadsheet', { 'query': query 'url': url }, { api_key: @api }, (res) -> if res.params if res.params.data resolve(res.params) else reject(res) else reject(Error("Gsheets response has no parameters")) # console.log res.params getGSheetJsonPromise2: (id, gid, query) => return new Promise (resolve, reject) => request "https://spreadsheets.google.com/tq?tqx=out:json&tq=#{encodeURIComponent(query)}&key=#{id}&gid=#{gid}", (err, res, body) => if !err and res.statusCode == 200 regex = /google\.visualization\.Query\.setResponse\((.*)\);/g match = regex.exec(res.body) json = JSON.parse(match[1]) # console.log match[1] if json.status is 'ok' resolve json else reject res else reject res console.log res getPersonsJsonPromise: () => @getGSheetJsonPromise @gsheet_persons_url, 'SELECT A,B,C,D\n' getItemsPerPersonJsonPromise: (person) => @getGSheetJsonPromise @gsheet_items_url, "SELECT H,I,J,K,N,P,Q\nWHERE K CONTAINS '#{person}' AND R CONTAINS 'To' AND O CONTAINS '0' AND S CONTAINS '1'" getEmailContent: (arr) => return Promise.all arr.map (person) => return @getItemsPerPersonJsonPromise(person.Nombre).then (result) => # Empezar tabla de elementos newEmailContent = "<ul>" for item in result.data newEmailContent += "<li>" + escape(""" Artículo: #{item.Articulo} Tipo: #{item['Tipo de artículo']} Nombre: #{item['Tipo de artículo']} Fecha de préstamo: #{item['Fecha de prestamo']} Imagen: #{item['Imagen cache']} """) + "</li>" if item['Tipo de artículo'] is "Libro" newEmailContent += "<li>" + escape(""" Autor: #{item['Book author']} Link amazon: #{item['Book link']} """) + "</li>" # Cerrar tabla de elementos newEmailContent += "</ul>" newPerson = name: person.Nombre meta: from: "victtorglez@gmail.com" to: person.Email subject: "#{person.Nombre}: recordatorio de préstamos" content: "<p>" + [ escape(""" Hola estimado/a #{person.Nombre}, """), escape(""" Este es un recordatorio automatizado de que tienes actualmente en tu posesión los siguientes libros pertenecientes a tu amigo Víctor, para que no se te olvide de que no son tuyos, ¡son prestados! xD. """), newEmailContent.replace /\\n/g, "</li><li>" ].join("</p><p>") + "</p>" console.log newPerson return newPerson makeListOfEmails: () => @getPersonsJsonPromise() .then (result) => return @getEmailContent result.data .then (result) => console.log result return result init: -> false
187503
require('dotenv').load() util = require 'util' blockspring = require 'blockspring' escape = require 'escape-html' request = require 'request' module.exports = class App constructor: -> @api = process.env.BLOCKSPRING_API @gsheet_items_url = process.env.G_SHEET_ITEMS_URL @gsheet_persons_url = process.env.G_SHEET_PERSONS_URL @gsheet_items_id = process.env.G_SHEET_ITEMS_ID @gsheet_persons_id = process.env.G_SHEET_PERSONS_ID @email = [] siblingArray = (arr, key, match) -> matches = arr.filter((val, index, array) -> val[key] is match ) return matches getGSheetJsonPromise: (url, query) -> return new Promise (resolve, reject) -> blockspring.runParsed 'query-google-spreadsheet', { 'query': query 'url': url }, { api_key: @api }, (res) -> if res.params if res.params.data resolve(res.params) else reject(res) else reject(Error("Gsheets response has no parameters")) # console.log res.params getGSheetJsonPromise2: (id, gid, query) => return new Promise (resolve, reject) => request "https://spreadsheets.google.com/tq?tqx=out:json&tq=#{encodeURIComponent(query)}&key=#{id}&gid=#{gid}", (err, res, body) => if !err and res.statusCode == 200 regex = /google\.visualization\.Query\.setResponse\((.*)\);/g match = regex.exec(res.body) json = JSON.parse(match[1]) # console.log match[1] if json.status is 'ok' resolve json else reject res else reject res console.log res getPersonsJsonPromise: () => @getGSheetJsonPromise @gsheet_persons_url, 'SELECT A,B,C,D\n' getItemsPerPersonJsonPromise: (person) => @getGSheetJsonPromise @gsheet_items_url, "SELECT H,I,J,K,N,P,Q\nWHERE K CONTAINS '#{person}' AND R CONTAINS 'To' AND O CONTAINS '0' AND S CONTAINS '1'" getEmailContent: (arr) => return Promise.all arr.map (person) => return @getItemsPerPersonJsonPromise(person.Nombre).then (result) => # Empezar tabla de elementos newEmailContent = "<ul>" for item in result.data newEmailContent += "<li>" + escape(""" Artículo: #{item.Articulo} Tipo: #{item['Tipo de artículo']} Nombre: #{item['Tipo de artículo']} Fecha de préstamo: #{item['Fecha de prestamo']} Imagen: #{item['Imagen cache']} """) + "</li>" if item['Tipo de artículo'] is "Libro" newEmailContent += "<li>" + escape(""" Autor: #{item['Book author']} Link amazon: #{item['Book link']} """) + "</li>" # Cerrar tabla de elementos newEmailContent += "</ul>" newPerson = name: person.Nombre meta: from: "<EMAIL>" to: person.Email subject: "#{person.Nombre}: recordatorio de préstamos" content: "<p>" + [ escape(""" Hola estimado/a #{person.Nombre}, """), escape(""" Este es un recordatorio automatizado de que tienes actualmente en tu posesión los siguientes libros pertenecientes a tu amigo Víctor, para que no se te olvide de que no son tuyos, ¡son prestados! xD. """), newEmailContent.replace /\\n/g, "</li><li>" ].join("</p><p>") + "</p>" console.log newPerson return newPerson makeListOfEmails: () => @getPersonsJsonPromise() .then (result) => return @getEmailContent result.data .then (result) => console.log result return result init: -> false
true
require('dotenv').load() util = require 'util' blockspring = require 'blockspring' escape = require 'escape-html' request = require 'request' module.exports = class App constructor: -> @api = process.env.BLOCKSPRING_API @gsheet_items_url = process.env.G_SHEET_ITEMS_URL @gsheet_persons_url = process.env.G_SHEET_PERSONS_URL @gsheet_items_id = process.env.G_SHEET_ITEMS_ID @gsheet_persons_id = process.env.G_SHEET_PERSONS_ID @email = [] siblingArray = (arr, key, match) -> matches = arr.filter((val, index, array) -> val[key] is match ) return matches getGSheetJsonPromise: (url, query) -> return new Promise (resolve, reject) -> blockspring.runParsed 'query-google-spreadsheet', { 'query': query 'url': url }, { api_key: @api }, (res) -> if res.params if res.params.data resolve(res.params) else reject(res) else reject(Error("Gsheets response has no parameters")) # console.log res.params getGSheetJsonPromise2: (id, gid, query) => return new Promise (resolve, reject) => request "https://spreadsheets.google.com/tq?tqx=out:json&tq=#{encodeURIComponent(query)}&key=#{id}&gid=#{gid}", (err, res, body) => if !err and res.statusCode == 200 regex = /google\.visualization\.Query\.setResponse\((.*)\);/g match = regex.exec(res.body) json = JSON.parse(match[1]) # console.log match[1] if json.status is 'ok' resolve json else reject res else reject res console.log res getPersonsJsonPromise: () => @getGSheetJsonPromise @gsheet_persons_url, 'SELECT A,B,C,D\n' getItemsPerPersonJsonPromise: (person) => @getGSheetJsonPromise @gsheet_items_url, "SELECT H,I,J,K,N,P,Q\nWHERE K CONTAINS '#{person}' AND R CONTAINS 'To' AND O CONTAINS '0' AND S CONTAINS '1'" getEmailContent: (arr) => return Promise.all arr.map (person) => return @getItemsPerPersonJsonPromise(person.Nombre).then (result) => # Empezar tabla de elementos newEmailContent = "<ul>" for item in result.data newEmailContent += "<li>" + escape(""" Artículo: #{item.Articulo} Tipo: #{item['Tipo de artículo']} Nombre: #{item['Tipo de artículo']} Fecha de préstamo: #{item['Fecha de prestamo']} Imagen: #{item['Imagen cache']} """) + "</li>" if item['Tipo de artículo'] is "Libro" newEmailContent += "<li>" + escape(""" Autor: #{item['Book author']} Link amazon: #{item['Book link']} """) + "</li>" # Cerrar tabla de elementos newEmailContent += "</ul>" newPerson = name: person.Nombre meta: from: "PI:EMAIL:<EMAIL>END_PI" to: person.Email subject: "#{person.Nombre}: recordatorio de préstamos" content: "<p>" + [ escape(""" Hola estimado/a #{person.Nombre}, """), escape(""" Este es un recordatorio automatizado de que tienes actualmente en tu posesión los siguientes libros pertenecientes a tu amigo Víctor, para que no se te olvide de que no son tuyos, ¡son prestados! xD. """), newEmailContent.replace /\\n/g, "</li><li>" ].join("</p><p>") + "</p>" console.log newPerson return newPerson makeListOfEmails: () => @getPersonsJsonPromise() .then (result) => return @getEmailContent result.data .then (result) => console.log result return result init: -> false
[ { "context": " 7)\n\t\t\t\t}\n\t\t\t\tSubscription.create {\n\t\t\t\t\tadmin_id: @user._id,\n\t\t\t\t\tmanager_ids: [@user._id],\n\t\t\t\t\trecurlyS", "end": 1575, "score": 0.9941794872283936, "start": 1570, "tag": "USERNAME", "value": "@user" }, { "context": "eate {\n\t\t\t\t\tadmin...
test/acceptance/coffee/SubscriptionTests.coffee
shyoshyo/web-sharelatex
1
expect = require('chai').expect async = require("async") User = require "./helpers/User" {Subscription} = require "../../../app/js/models/Subscription" {Institution} = require "../../../app/js/models/Institution" SubscriptionViewModelBuilder = require "../../../app/js/Features/Subscription/SubscriptionViewModelBuilder" MockRecurlyApi = require "./helpers/MockRecurlyApi" MockV1Api = require "./helpers/MockV1Api" describe 'Subscriptions', -> describe 'dashboard', -> before (done) -> @user = new User() @user.ensureUserExists done describe 'when the user has no subscription', -> before (done) -> SubscriptionViewModelBuilder.buildUsersSubscriptionViewModel @user, (error, @data) => return done(error) if error? done() it 'should return no personalSubscription', -> expect(@data.personalSubscription).to.equal null it 'should return no memberGroupSubscriptions', -> expect(@data.memberGroupSubscriptions).to.deep.equal [] describe 'when the user has a subscription with recurly', -> before (done) -> MockRecurlyApi.accounts['mock-account-id'] = @accounts = { hosted_login_token: 'mock-login-token' } MockRecurlyApi.subscriptions['mock-subscription-id'] = @subscription = { plan_code: 'collaborator', tax_in_cents: 100, tax_rate: 0.2, unit_amount_in_cents: 500, currency: 'GBP', current_period_ends_at: new Date(2018,4,5), state: 'active', account_id: 'mock-account-id', trial_ends_at: new Date(2018, 6, 7) } Subscription.create { admin_id: @user._id, manager_ids: [@user._id], recurlySubscription_id: 'mock-subscription-id', planCode: 'collaborator' }, (error) => return done(error) if error? SubscriptionViewModelBuilder.buildUsersSubscriptionViewModel @user, (error, @data) => return done(error) if error? done() return after (done) -> MockRecurlyApi.accounts = {} MockRecurlyApi.subscriptions = {} Subscription.remove { admin_id: @user._id }, done return it 'should return a personalSubscription with populated recurly data', -> subscription = @data.personalSubscription expect(subscription).to.exist expect(subscription.planCode).to.equal 'collaborator' expect(subscription.recurly).to.exist expect(subscription.recurly).to.deep.equal { "billingDetailsLink": "https://test.recurly.com/account/billing_info/edit?ht=mock-login-token" "currency": "GBP" "nextPaymentDueAt": "5th May 2018" "price": "£6.00" "state": "active" "tax": 100 "taxRate": 0.2 "trial_ends_at": new Date(2018, 6, 7), "trialEndsAtFormatted": "7th July 2018" } it 'should return no memberGroupSubscriptions', -> expect(@data.memberGroupSubscriptions).to.deep.equal [] describe 'when the user has a subscription without recurly', -> before (done) -> Subscription.create { admin_id: @user._id, manager_ids: [@user._id], planCode: 'collaborator' }, (error) => return done(error) if error? SubscriptionViewModelBuilder.buildUsersSubscriptionViewModel @user, (error, @data) => return done(error) if error? done() return after (done) -> Subscription.remove { admin_id: @user._id }, done return it 'should return a personalSubscription with no recurly data', -> subscription = @data.personalSubscription expect(subscription).to.exist expect(subscription.planCode).to.equal 'collaborator' expect(subscription.recurly).to.not.exist it 'should return no memberGroupSubscriptions', -> expect(@data.memberGroupSubscriptions).to.deep.equal [] describe 'when the user is a member of a group subscription', -> before (done) -> @owner1 = new User() @owner2 = new User() async.series [ (cb) => @owner1.ensureUserExists cb (cb) => @owner2.ensureUserExists cb (cb) => Subscription.create { admin_id: @owner1._id, manager_ids: [@owner1._id], planCode: 'collaborator', groupPlan: true, member_ids: [@user._id] }, cb (cb) => Subscription.create { admin_id: @owner2._id, manager_ids: [@owner2._id], planCode: 'collaborator', groupPlan: true, member_ids: [@user._id] }, cb ], (error) => return done(error) if error? SubscriptionViewModelBuilder.buildUsersSubscriptionViewModel @user, (error, @data) => return done(error) if error? done() return after (done) -> Subscription.remove { admin_id: @owner1._id }, (error) => return done(error) if error? Subscription.remove { admin_id: @owner2._id }, done return it 'should return no personalSubscription', -> expect(@data.personalSubscription).to.equal null it 'should return the two memberGroupSubscriptions', -> expect(@data.memberGroupSubscriptions.length).to.equal 2 expect( # Mongoose populates the admin_id with the user @data.memberGroupSubscriptions[0].admin_id._id.toString() ).to.equal @owner1._id expect( @data.memberGroupSubscriptions[1].admin_id._id.toString() ).to.equal @owner2._id describe 'when the user is a manager of a group subscription', -> before (done) -> @owner1 = new User() @owner2 = new User() async.series [ (cb) => @owner1.ensureUserExists cb (cb) => @owner2.ensureUserExists cb (cb) => Subscription.create { admin_id: @owner1._id, manager_ids: [@owner1._id, @user._id], planCode: 'collaborator', groupPlan: true }, cb ], (error) => return done(error) if error? SubscriptionViewModelBuilder.buildUsersSubscriptionViewModel @user, (error, @data) => return done(error) if error? done() return after (done) -> Subscription.remove { admin_id: @owner1._id }, done return it 'should return no personalSubscription', -> expect(@data.personalSubscription).to.equal null it 'should return the managedGroupSubscriptions', -> expect(@data.managedGroupSubscriptions.length).to.equal 1 subscription = @data.managedGroupSubscriptions[0] expect( # Mongoose populates the admin_id with the user subscription.admin_id._id.toString() ).to.equal @owner1._id expect(subscription.groupPlan).to.equal true describe 'when the user is a manager of an institution', -> before (done) -> @v1Id = MockV1Api.nextV1Id() async.series [ (cb) => Institution.create({ v1Id: @v1Id, managerIds: [@user._id] }, cb) ], (error) => return done(error) if error? SubscriptionViewModelBuilder.buildUsersSubscriptionViewModel @user, (error, @data) => return done(error) if error? done() return after (done) -> Institution.remove { v1Id: @v1Id }, done return it 'should return the managedInstitutions', -> expect(@data.managedInstitutions.length).to.equal 1 institution = @data.managedInstitutions[0] expect(institution.v1Id).to.equal @v1Id expect(institution.name).to.equal "Institution #{@v1Id}" describe 'when the user is a member of an affiliation', -> before (done) -> v1Id = MockV1Api.nextV1Id() MockV1Api.setUser v1Id, { subscription: {}, subscription_status: {} } MockV1Api.setAffiliations [{ email: 'confirmed-affiliation-email@stanford.example.edu' institution: { name: 'Stanford', licence: 'pro_plus', confirmed: true } }, { email: 'unconfirmed-affiliation-email@harvard.example.edu' institution: { name: 'Harvard', licence: 'pro_plus', confirmed: true } }, { email: 'confirmed-affiliation-email@mit.example.edu' institution: { name: 'MIT', licence: 'pro_plus', confirmed: false } }] async.series [ (cb) => @user.setV1Id v1Id, cb (cb) => @user.addEmail 'unconfirmed-affiliation-email@harvard.example.edu', cb (cb) => @user.addEmail 'confirmed-affiliation-email@stanford.example.edu', cb (cb) => @user.confirmEmail 'confirmed-affiliation-email@stanford.example.edu', cb (cb) => @user.addEmail 'confirmed-affiliation-email@mit.example.edu', cb (cb) => @user.confirmEmail 'confirmed-affiliation-email@mit.example.edu', cb ], (error) => return done(error) if error? SubscriptionViewModelBuilder.buildUsersSubscriptionViewModel @user, (error, @data) => return done(error) if error? done() it 'should return only the affilations with confirmed institutions, and confirmed emails', -> expect(@data.confirmedMemberInstitutions).to.deep.equal [ { name: 'Stanford', licence: 'pro_plus', confirmed: true } ] describe 'when the user has a v1 subscription', -> before (done) -> MockV1Api.setUser v1Id = MockV1Api.nextV1Id(), { subscription: @subscription = { trial: false, has_plan: true, teams: [{ id: 56, name: 'Test team' }] } subscription_status: @subscription_status = { product: { 'mock': 'product' } team: null } } @user.setV1Id v1Id, (error) => return done(error) if error? SubscriptionViewModelBuilder.buildUsersSubscriptionViewModel @user, (error, @data) => return done(error) if error? done() it 'should return no personalSubscription', -> expect(@data.personalSubscription).to.equal null it 'should return no memberGroupSubscriptions', -> expect(@data.memberGroupSubscriptions).to.deep.equal [] it 'should return a v1SubscriptionStatus', -> expect(@data.v1SubscriptionStatus).to.deep.equal @subscription_status describe 'canceling', -> before (done) -> @user = new User() MockV1Api.setUser v1Id = MockV1Api.nextV1Id(), @v1_user = {} async.series [ (cb) => @user.login(cb) (cb) => @user.setV1Id(v1Id, cb) ], (error) => @user.request { method: 'POST', url: '/user/subscription/v1/cancel' }, (error, @response) => return done(error) if error? done() it 'should tell v1 to cancel the subscription', -> expect(@v1_user.canceled).to.equal true it 'should redirect to the subscription dashboard', -> expect(@response.statusCode).to.equal 302 expect(@response.headers.location).to.equal '/user/subscription'
220789
expect = require('chai').expect async = require("async") User = require "./helpers/User" {Subscription} = require "../../../app/js/models/Subscription" {Institution} = require "../../../app/js/models/Institution" SubscriptionViewModelBuilder = require "../../../app/js/Features/Subscription/SubscriptionViewModelBuilder" MockRecurlyApi = require "./helpers/MockRecurlyApi" MockV1Api = require "./helpers/MockV1Api" describe 'Subscriptions', -> describe 'dashboard', -> before (done) -> @user = new User() @user.ensureUserExists done describe 'when the user has no subscription', -> before (done) -> SubscriptionViewModelBuilder.buildUsersSubscriptionViewModel @user, (error, @data) => return done(error) if error? done() it 'should return no personalSubscription', -> expect(@data.personalSubscription).to.equal null it 'should return no memberGroupSubscriptions', -> expect(@data.memberGroupSubscriptions).to.deep.equal [] describe 'when the user has a subscription with recurly', -> before (done) -> MockRecurlyApi.accounts['mock-account-id'] = @accounts = { hosted_login_token: 'mock-login-token' } MockRecurlyApi.subscriptions['mock-subscription-id'] = @subscription = { plan_code: 'collaborator', tax_in_cents: 100, tax_rate: 0.2, unit_amount_in_cents: 500, currency: 'GBP', current_period_ends_at: new Date(2018,4,5), state: 'active', account_id: 'mock-account-id', trial_ends_at: new Date(2018, 6, 7) } Subscription.create { admin_id: @user._id, manager_ids: [@user._id], recurlySubscription_id: 'mock-subscription-id', planCode: 'collaborator' }, (error) => return done(error) if error? SubscriptionViewModelBuilder.buildUsersSubscriptionViewModel @user, (error, @data) => return done(error) if error? done() return after (done) -> MockRecurlyApi.accounts = {} MockRecurlyApi.subscriptions = {} Subscription.remove { admin_id: @user._id }, done return it 'should return a personalSubscription with populated recurly data', -> subscription = @data.personalSubscription expect(subscription).to.exist expect(subscription.planCode).to.equal 'collaborator' expect(subscription.recurly).to.exist expect(subscription.recurly).to.deep.equal { "billingDetailsLink": "https://test.recurly.com/account/billing_info/edit?ht=mock-login-token" "currency": "GBP" "nextPaymentDueAt": "5th May 2018" "price": "£6.00" "state": "active" "tax": 100 "taxRate": 0.2 "trial_ends_at": new Date(2018, 6, 7), "trialEndsAtFormatted": "7th July 2018" } it 'should return no memberGroupSubscriptions', -> expect(@data.memberGroupSubscriptions).to.deep.equal [] describe 'when the user has a subscription without recurly', -> before (done) -> Subscription.create { admin_id: @user._id, manager_ids: [@user._id], planCode: 'collaborator' }, (error) => return done(error) if error? SubscriptionViewModelBuilder.buildUsersSubscriptionViewModel @user, (error, @data) => return done(error) if error? done() return after (done) -> Subscription.remove { admin_id: @user._id }, done return it 'should return a personalSubscription with no recurly data', -> subscription = @data.personalSubscription expect(subscription).to.exist expect(subscription.planCode).to.equal 'collaborator' expect(subscription.recurly).to.not.exist it 'should return no memberGroupSubscriptions', -> expect(@data.memberGroupSubscriptions).to.deep.equal [] describe 'when the user is a member of a group subscription', -> before (done) -> @owner1 = new User() @owner2 = new User() async.series [ (cb) => @owner1.ensureUserExists cb (cb) => @owner2.ensureUserExists cb (cb) => Subscription.create { admin_id: @owner1._id, manager_ids: [@owner1._id], planCode: 'collaborator', groupPlan: true, member_ids: [@user._id] }, cb (cb) => Subscription.create { admin_id: @owner2._id, manager_ids: [@owner2._id], planCode: 'collaborator', groupPlan: true, member_ids: [@user._id] }, cb ], (error) => return done(error) if error? SubscriptionViewModelBuilder.buildUsersSubscriptionViewModel @user, (error, @data) => return done(error) if error? done() return after (done) -> Subscription.remove { admin_id: @owner1._id }, (error) => return done(error) if error? Subscription.remove { admin_id: @owner2._id }, done return it 'should return no personalSubscription', -> expect(@data.personalSubscription).to.equal null it 'should return the two memberGroupSubscriptions', -> expect(@data.memberGroupSubscriptions.length).to.equal 2 expect( # Mongoose populates the admin_id with the user @data.memberGroupSubscriptions[0].admin_id._id.toString() ).to.equal @owner1._id expect( @data.memberGroupSubscriptions[1].admin_id._id.toString() ).to.equal @owner2._id describe 'when the user is a manager of a group subscription', -> before (done) -> @owner1 = new User() @owner2 = new User() async.series [ (cb) => @owner1.ensureUserExists cb (cb) => @owner2.ensureUserExists cb (cb) => Subscription.create { admin_id: @owner1._id, manager_ids: [@owner1._id, @user._id], planCode: 'collaborator', groupPlan: true }, cb ], (error) => return done(error) if error? SubscriptionViewModelBuilder.buildUsersSubscriptionViewModel @user, (error, @data) => return done(error) if error? done() return after (done) -> Subscription.remove { admin_id: @owner1._id }, done return it 'should return no personalSubscription', -> expect(@data.personalSubscription).to.equal null it 'should return the managedGroupSubscriptions', -> expect(@data.managedGroupSubscriptions.length).to.equal 1 subscription = @data.managedGroupSubscriptions[0] expect( # Mongoose populates the admin_id with the user subscription.admin_id._id.toString() ).to.equal @owner1._id expect(subscription.groupPlan).to.equal true describe 'when the user is a manager of an institution', -> before (done) -> @v1Id = MockV1Api.nextV1Id() async.series [ (cb) => Institution.create({ v1Id: @v1Id, managerIds: [@user._id] }, cb) ], (error) => return done(error) if error? SubscriptionViewModelBuilder.buildUsersSubscriptionViewModel @user, (error, @data) => return done(error) if error? done() return after (done) -> Institution.remove { v1Id: @v1Id }, done return it 'should return the managedInstitutions', -> expect(@data.managedInstitutions.length).to.equal 1 institution = @data.managedInstitutions[0] expect(institution.v1Id).to.equal @v1Id expect(institution.name).to.equal "Institution #{@v1Id}" describe 'when the user is a member of an affiliation', -> before (done) -> v1Id = MockV1Api.nextV1Id() MockV1Api.setUser v1Id, { subscription: {}, subscription_status: {} } MockV1Api.setAffiliations [{ email: '<EMAIL>' institution: { name: 'Stanford', licence: 'pro_plus', confirmed: true } }, { email: '<EMAIL>' institution: { name: 'Harvard', licence: 'pro_plus', confirmed: true } }, { email: '<EMAIL>' institution: { name: 'MIT', licence: 'pro_plus', confirmed: false } }] async.series [ (cb) => @user.setV1Id v1Id, cb (cb) => @user.addEmail '<EMAIL>', cb (cb) => @user.addEmail '<EMAIL>', cb (cb) => @user.confirmEmail '<EMAIL>', cb (cb) => @user.addEmail '<EMAIL>', cb (cb) => @user.confirmEmail '<EMAIL>', cb ], (error) => return done(error) if error? SubscriptionViewModelBuilder.buildUsersSubscriptionViewModel @user, (error, @data) => return done(error) if error? done() it 'should return only the affilations with confirmed institutions, and confirmed emails', -> expect(@data.confirmedMemberInstitutions).to.deep.equal [ { name: '<NAME>', licence: 'pro_plus', confirmed: true } ] describe 'when the user has a v1 subscription', -> before (done) -> MockV1Api.setUser v1Id = MockV1Api.nextV1Id(), { subscription: @subscription = { trial: false, has_plan: true, teams: [{ id: 56, name: 'Test team' }] } subscription_status: @subscription_status = { product: { 'mock': 'product' } team: null } } @user.setV1Id v1Id, (error) => return done(error) if error? SubscriptionViewModelBuilder.buildUsersSubscriptionViewModel @user, (error, @data) => return done(error) if error? done() it 'should return no personalSubscription', -> expect(@data.personalSubscription).to.equal null it 'should return no memberGroupSubscriptions', -> expect(@data.memberGroupSubscriptions).to.deep.equal [] it 'should return a v1SubscriptionStatus', -> expect(@data.v1SubscriptionStatus).to.deep.equal @subscription_status describe 'canceling', -> before (done) -> @user = new User() MockV1Api.setUser v1Id = MockV1Api.nextV1Id(), @v1_user = {} async.series [ (cb) => @user.login(cb) (cb) => @user.setV1Id(v1Id, cb) ], (error) => @user.request { method: 'POST', url: '/user/subscription/v1/cancel' }, (error, @response) => return done(error) if error? done() it 'should tell v1 to cancel the subscription', -> expect(@v1_user.canceled).to.equal true it 'should redirect to the subscription dashboard', -> expect(@response.statusCode).to.equal 302 expect(@response.headers.location).to.equal '/user/subscription'
true
expect = require('chai').expect async = require("async") User = require "./helpers/User" {Subscription} = require "../../../app/js/models/Subscription" {Institution} = require "../../../app/js/models/Institution" SubscriptionViewModelBuilder = require "../../../app/js/Features/Subscription/SubscriptionViewModelBuilder" MockRecurlyApi = require "./helpers/MockRecurlyApi" MockV1Api = require "./helpers/MockV1Api" describe 'Subscriptions', -> describe 'dashboard', -> before (done) -> @user = new User() @user.ensureUserExists done describe 'when the user has no subscription', -> before (done) -> SubscriptionViewModelBuilder.buildUsersSubscriptionViewModel @user, (error, @data) => return done(error) if error? done() it 'should return no personalSubscription', -> expect(@data.personalSubscription).to.equal null it 'should return no memberGroupSubscriptions', -> expect(@data.memberGroupSubscriptions).to.deep.equal [] describe 'when the user has a subscription with recurly', -> before (done) -> MockRecurlyApi.accounts['mock-account-id'] = @accounts = { hosted_login_token: 'mock-login-token' } MockRecurlyApi.subscriptions['mock-subscription-id'] = @subscription = { plan_code: 'collaborator', tax_in_cents: 100, tax_rate: 0.2, unit_amount_in_cents: 500, currency: 'GBP', current_period_ends_at: new Date(2018,4,5), state: 'active', account_id: 'mock-account-id', trial_ends_at: new Date(2018, 6, 7) } Subscription.create { admin_id: @user._id, manager_ids: [@user._id], recurlySubscription_id: 'mock-subscription-id', planCode: 'collaborator' }, (error) => return done(error) if error? SubscriptionViewModelBuilder.buildUsersSubscriptionViewModel @user, (error, @data) => return done(error) if error? done() return after (done) -> MockRecurlyApi.accounts = {} MockRecurlyApi.subscriptions = {} Subscription.remove { admin_id: @user._id }, done return it 'should return a personalSubscription with populated recurly data', -> subscription = @data.personalSubscription expect(subscription).to.exist expect(subscription.planCode).to.equal 'collaborator' expect(subscription.recurly).to.exist expect(subscription.recurly).to.deep.equal { "billingDetailsLink": "https://test.recurly.com/account/billing_info/edit?ht=mock-login-token" "currency": "GBP" "nextPaymentDueAt": "5th May 2018" "price": "£6.00" "state": "active" "tax": 100 "taxRate": 0.2 "trial_ends_at": new Date(2018, 6, 7), "trialEndsAtFormatted": "7th July 2018" } it 'should return no memberGroupSubscriptions', -> expect(@data.memberGroupSubscriptions).to.deep.equal [] describe 'when the user has a subscription without recurly', -> before (done) -> Subscription.create { admin_id: @user._id, manager_ids: [@user._id], planCode: 'collaborator' }, (error) => return done(error) if error? SubscriptionViewModelBuilder.buildUsersSubscriptionViewModel @user, (error, @data) => return done(error) if error? done() return after (done) -> Subscription.remove { admin_id: @user._id }, done return it 'should return a personalSubscription with no recurly data', -> subscription = @data.personalSubscription expect(subscription).to.exist expect(subscription.planCode).to.equal 'collaborator' expect(subscription.recurly).to.not.exist it 'should return no memberGroupSubscriptions', -> expect(@data.memberGroupSubscriptions).to.deep.equal [] describe 'when the user is a member of a group subscription', -> before (done) -> @owner1 = new User() @owner2 = new User() async.series [ (cb) => @owner1.ensureUserExists cb (cb) => @owner2.ensureUserExists cb (cb) => Subscription.create { admin_id: @owner1._id, manager_ids: [@owner1._id], planCode: 'collaborator', groupPlan: true, member_ids: [@user._id] }, cb (cb) => Subscription.create { admin_id: @owner2._id, manager_ids: [@owner2._id], planCode: 'collaborator', groupPlan: true, member_ids: [@user._id] }, cb ], (error) => return done(error) if error? SubscriptionViewModelBuilder.buildUsersSubscriptionViewModel @user, (error, @data) => return done(error) if error? done() return after (done) -> Subscription.remove { admin_id: @owner1._id }, (error) => return done(error) if error? Subscription.remove { admin_id: @owner2._id }, done return it 'should return no personalSubscription', -> expect(@data.personalSubscription).to.equal null it 'should return the two memberGroupSubscriptions', -> expect(@data.memberGroupSubscriptions.length).to.equal 2 expect( # Mongoose populates the admin_id with the user @data.memberGroupSubscriptions[0].admin_id._id.toString() ).to.equal @owner1._id expect( @data.memberGroupSubscriptions[1].admin_id._id.toString() ).to.equal @owner2._id describe 'when the user is a manager of a group subscription', -> before (done) -> @owner1 = new User() @owner2 = new User() async.series [ (cb) => @owner1.ensureUserExists cb (cb) => @owner2.ensureUserExists cb (cb) => Subscription.create { admin_id: @owner1._id, manager_ids: [@owner1._id, @user._id], planCode: 'collaborator', groupPlan: true }, cb ], (error) => return done(error) if error? SubscriptionViewModelBuilder.buildUsersSubscriptionViewModel @user, (error, @data) => return done(error) if error? done() return after (done) -> Subscription.remove { admin_id: @owner1._id }, done return it 'should return no personalSubscription', -> expect(@data.personalSubscription).to.equal null it 'should return the managedGroupSubscriptions', -> expect(@data.managedGroupSubscriptions.length).to.equal 1 subscription = @data.managedGroupSubscriptions[0] expect( # Mongoose populates the admin_id with the user subscription.admin_id._id.toString() ).to.equal @owner1._id expect(subscription.groupPlan).to.equal true describe 'when the user is a manager of an institution', -> before (done) -> @v1Id = MockV1Api.nextV1Id() async.series [ (cb) => Institution.create({ v1Id: @v1Id, managerIds: [@user._id] }, cb) ], (error) => return done(error) if error? SubscriptionViewModelBuilder.buildUsersSubscriptionViewModel @user, (error, @data) => return done(error) if error? done() return after (done) -> Institution.remove { v1Id: @v1Id }, done return it 'should return the managedInstitutions', -> expect(@data.managedInstitutions.length).to.equal 1 institution = @data.managedInstitutions[0] expect(institution.v1Id).to.equal @v1Id expect(institution.name).to.equal "Institution #{@v1Id}" describe 'when the user is a member of an affiliation', -> before (done) -> v1Id = MockV1Api.nextV1Id() MockV1Api.setUser v1Id, { subscription: {}, subscription_status: {} } MockV1Api.setAffiliations [{ email: 'PI:EMAIL:<EMAIL>END_PI' institution: { name: 'Stanford', licence: 'pro_plus', confirmed: true } }, { email: 'PI:EMAIL:<EMAIL>END_PI' institution: { name: 'Harvard', licence: 'pro_plus', confirmed: true } }, { email: 'PI:EMAIL:<EMAIL>END_PI' institution: { name: 'MIT', licence: 'pro_plus', confirmed: false } }] async.series [ (cb) => @user.setV1Id v1Id, cb (cb) => @user.addEmail 'PI:EMAIL:<EMAIL>END_PI', cb (cb) => @user.addEmail 'PI:EMAIL:<EMAIL>END_PI', cb (cb) => @user.confirmEmail 'PI:EMAIL:<EMAIL>END_PI', cb (cb) => @user.addEmail 'PI:EMAIL:<EMAIL>END_PI', cb (cb) => @user.confirmEmail 'PI:EMAIL:<EMAIL>END_PI', cb ], (error) => return done(error) if error? SubscriptionViewModelBuilder.buildUsersSubscriptionViewModel @user, (error, @data) => return done(error) if error? done() it 'should return only the affilations with confirmed institutions, and confirmed emails', -> expect(@data.confirmedMemberInstitutions).to.deep.equal [ { name: 'PI:NAME:<NAME>END_PI', licence: 'pro_plus', confirmed: true } ] describe 'when the user has a v1 subscription', -> before (done) -> MockV1Api.setUser v1Id = MockV1Api.nextV1Id(), { subscription: @subscription = { trial: false, has_plan: true, teams: [{ id: 56, name: 'Test team' }] } subscription_status: @subscription_status = { product: { 'mock': 'product' } team: null } } @user.setV1Id v1Id, (error) => return done(error) if error? SubscriptionViewModelBuilder.buildUsersSubscriptionViewModel @user, (error, @data) => return done(error) if error? done() it 'should return no personalSubscription', -> expect(@data.personalSubscription).to.equal null it 'should return no memberGroupSubscriptions', -> expect(@data.memberGroupSubscriptions).to.deep.equal [] it 'should return a v1SubscriptionStatus', -> expect(@data.v1SubscriptionStatus).to.deep.equal @subscription_status describe 'canceling', -> before (done) -> @user = new User() MockV1Api.setUser v1Id = MockV1Api.nextV1Id(), @v1_user = {} async.series [ (cb) => @user.login(cb) (cb) => @user.setV1Id(v1Id, cb) ], (error) => @user.request { method: 'POST', url: '/user/subscription/v1/cancel' }, (error, @response) => return done(error) if error? done() it 'should tell v1 to cancel the subscription', -> expect(@v1_user.canceled).to.equal true it 'should redirect to the subscription dashboard', -> expect(@response.statusCode).to.equal 302 expect(@response.headers.location).to.equal '/user/subscription'
[ { "context": "it \"populates the email field\", ->\n email = 'user@example.com'\n template = render('forgot')(\n email", "end": 732, "score": 0.9999027252197266, "start": 716, "tag": "EMAIL", "value": "user@example.com" } ]
src/desktop/components/auth_modal/test/templates.coffee
kanaabe/force
1
jade = require 'jade' path = require 'path' fs = require 'fs' cheerio = require 'cheerio' render = (templateName) -> filename = path.resolve __dirname, "../templates/#{templateName}.jade" jade.compile( fs.readFileSync(filename), { filename: filename } ) describe "Auth Templates", -> describe "forgot", -> it "renders the forgot password form", -> template = render('forgot')() $ = cheerio.load template $('#auth-submit').text().should.containEql 'Send me reset instructions' $('.auth-toggle').text().should.containEql 'I remember it!' $('.auth-mode-toggle').text().should.containEql 'Don’t have an account?' it "populates the email field", -> email = 'user@example.com' template = render('forgot')( email: email ) $ = cheerio.load template $('input[name="email"]').val().should.containEql email describe "set password", -> it "renders a modified version of the forgot password form", -> template = render('forgot')( setPassword: true ) $ = cheerio.load template $('#auth-submit').text().should.containEql 'Submit' $('.auth-toggle').length.should.equal(0) $('.auth-mode-toggle').length.should.equal(0) $('.auth-form p').text().should.containEql 'Get a unique link sent to your email and finish creating your account.'
26764
jade = require 'jade' path = require 'path' fs = require 'fs' cheerio = require 'cheerio' render = (templateName) -> filename = path.resolve __dirname, "../templates/#{templateName}.jade" jade.compile( fs.readFileSync(filename), { filename: filename } ) describe "Auth Templates", -> describe "forgot", -> it "renders the forgot password form", -> template = render('forgot')() $ = cheerio.load template $('#auth-submit').text().should.containEql 'Send me reset instructions' $('.auth-toggle').text().should.containEql 'I remember it!' $('.auth-mode-toggle').text().should.containEql 'Don’t have an account?' it "populates the email field", -> email = '<EMAIL>' template = render('forgot')( email: email ) $ = cheerio.load template $('input[name="email"]').val().should.containEql email describe "set password", -> it "renders a modified version of the forgot password form", -> template = render('forgot')( setPassword: true ) $ = cheerio.load template $('#auth-submit').text().should.containEql 'Submit' $('.auth-toggle').length.should.equal(0) $('.auth-mode-toggle').length.should.equal(0) $('.auth-form p').text().should.containEql 'Get a unique link sent to your email and finish creating your account.'
true
jade = require 'jade' path = require 'path' fs = require 'fs' cheerio = require 'cheerio' render = (templateName) -> filename = path.resolve __dirname, "../templates/#{templateName}.jade" jade.compile( fs.readFileSync(filename), { filename: filename } ) describe "Auth Templates", -> describe "forgot", -> it "renders the forgot password form", -> template = render('forgot')() $ = cheerio.load template $('#auth-submit').text().should.containEql 'Send me reset instructions' $('.auth-toggle').text().should.containEql 'I remember it!' $('.auth-mode-toggle').text().should.containEql 'Don’t have an account?' it "populates the email field", -> email = 'PI:EMAIL:<EMAIL>END_PI' template = render('forgot')( email: email ) $ = cheerio.load template $('input[name="email"]').val().should.containEql email describe "set password", -> it "renders a modified version of the forgot password form", -> template = render('forgot')( setPassword: true ) $ = cheerio.load template $('#auth-submit').text().should.containEql 'Submit' $('.auth-toggle').length.should.equal(0) $('.auth-mode-toggle').length.should.equal(0) $('.auth-form p').text().should.containEql 'Get a unique link sent to your email and finish creating your account.'
[ { "context": "###\n\nConcatenating Json Objects\n\nAuthor: @mugo_gocho <mugo@forfuture.co.ke>\nLicense: MIT\n\n###\n\n\n###\n\nN", "end": 52, "score": 0.9997353553771973, "start": 41, "tag": "USERNAME", "value": "@mugo_gocho" }, { "context": "\nConcatenating Json Objects\n\nAuthor: @...
src/json-concat.coffee
guyaumetremblay/json-concat
5
### Concatenating Json Objects Author: @mugo_gocho <mugo@forfuture.co.ke> License: MIT ### ### Notes: 1. A result object is reused in order to avoid creating many arrays then have to join them together. This makes it faster. 2. Two alternative algorithms can be used to concatenate stringified JSON objects: i) Concatenate, use RegExp and Parse (algorithm 1) - concatenate the stringified json objects - use RegExp to try make the string a valid stringified json object - parse the result string into an object ii) Parse and Join - parse each string into a json object - then loop through each of the objects assigning its keys and values to a result object Performance: - I used jsperf.com to run performance test. - algorithm 1 was faster than algorithm 2 - See test suite at http://jsperf.com/json-concat/ Discussion/Conclusion: - Although algorithm 1 is faster, we use both. Reason is that algorithm 2 is forgiving by letting us ignore strings that can not be parsed into objects. algorithm 1 makes it hard to rescue the situation if the final string can not be parsed. We use algorithm 1 at first. If it fails to realize an object, we turn to algorithm 2 to scavange any objects it can find. ### "use strict" # Built-in modules fs = require "fs" path = require "path" ### Concatenates content from all JSON files encountered This is recursive and will go into directories looking for files with the extension ".json" @param <filepath> - {String} path to file/directory @param <resultObject> - {Object} object that will hold the result (see note 1) @param <callback> - {Function} callback(content, contentArray) ### readContent = (filepath, resultObject, callback) -> filesEncountered = 0 filesProcessed = 0 resultObject.contentString ?= "" resultObject.contentArray ?= [] encounteredFile = () -> filesEncountered++ processedFile = (fileContent="") -> resultObject.contentString += fileContent resultObject.contentArray.push(fileContent) if fileContent filesProcessed++ callback(resultObject) if filesProcessed is filesEncountered # special case(s) if typeof(filepath) is "object" resultObject.contentString += JSON.stringify(filepath) resultObject.contentArray.push(filepath) return callback(resultObject) read = (filepath) -> encounteredFile() fs.stat filepath, (err, stats) -> # could not get stats, quit on the file and move on return processedFile(null) if err if stats.isDirectory() # directory. read it files. using recursion fs.readdir filepath, (err, files) -> # quit on the directory. couldnt get list of files in it return processedFile(null) if err # loop thru each file and process it for file in files read path.join(filepath, file) # I done with this directory so I quit on it processedFile(null) else if stats.isFile() if path.extname(filepath) is ".json" # file. read it content and concatenate it fs.readFile filepath, { encoding: "utf8" }, (err, content) -> # quit on the file. couldnt read it return processedFile(null) if err processedFile(content) else processedFile(null) # start the process read(filepath) ### Creates a new JSON object from a string of concatenated stringified JSON objects. @param <string> - {String} string of json @param <callback> - {Function} callback(validString, validObject) ### concat = (contentString, contentArray, callback) -> return callback("{}", {}) if contentString is "" # using algorithm 1 (faster, not forgiving) string = contentString.replace /^({\s*})*|({\s*})*$/g, "" string = string.replace /}\s*({\s*})*\s*{/g, "," string = string.replace /}\s*{/g, "," try callback(string, JSON.parse(string)) catch err # using algorithm 2 (slow, forgiving) result = { } for content in contentArray try tmp = JSON.parse(content) for key, value of tmp result[key] = value catch err callback(JSON.stringify(result), result) ### exported function ### exports = module.exports = (userOptions, callback) -> # options options = src: userOptions.src || process.cwd() dest: userOptions.dest || "./concat.json" middleware: userOptions.middleware || false # ensure `null` is respected for options.dest if userOptions.dest is null then options.dest = null # make options.src an array if typeof(options.src) is "string" then options.src = [options.src] result = { } index = 0 start = (callback) -> next = () -> readContent options.src[index], result, () -> ++index return next() if index < options.src.length concat result.contentString, result.contentArray, (string, obj) -> if options.dest fs.writeFile options.dest, string, (err) -> callback(err, obj) else callback(null, obj) next() # in a connect/express app if options.middleware return (req, res, next) -> start((err, obj) -> next(obj || {})) else return start(callback)
204858
### Concatenating Json Objects Author: @mugo_gocho <<EMAIL>> License: MIT ### ### Notes: 1. A result object is reused in order to avoid creating many arrays then have to join them together. This makes it faster. 2. Two alternative algorithms can be used to concatenate stringified JSON objects: i) Concatenate, use RegExp and Parse (algorithm 1) - concatenate the stringified json objects - use RegExp to try make the string a valid stringified json object - parse the result string into an object ii) Parse and Join - parse each string into a json object - then loop through each of the objects assigning its keys and values to a result object Performance: - I used jsperf.com to run performance test. - algorithm 1 was faster than algorithm 2 - See test suite at http://jsperf.com/json-concat/ Discussion/Conclusion: - Although algorithm 1 is faster, we use both. Reason is that algorithm 2 is forgiving by letting us ignore strings that can not be parsed into objects. algorithm 1 makes it hard to rescue the situation if the final string can not be parsed. We use algorithm 1 at first. If it fails to realize an object, we turn to algorithm 2 to scavange any objects it can find. ### "use strict" # Built-in modules fs = require "fs" path = require "path" ### Concatenates content from all JSON files encountered This is recursive and will go into directories looking for files with the extension ".json" @param <filepath> - {String} path to file/directory @param <resultObject> - {Object} object that will hold the result (see note 1) @param <callback> - {Function} callback(content, contentArray) ### readContent = (filepath, resultObject, callback) -> filesEncountered = 0 filesProcessed = 0 resultObject.contentString ?= "" resultObject.contentArray ?= [] encounteredFile = () -> filesEncountered++ processedFile = (fileContent="") -> resultObject.contentString += fileContent resultObject.contentArray.push(fileContent) if fileContent filesProcessed++ callback(resultObject) if filesProcessed is filesEncountered # special case(s) if typeof(filepath) is "object" resultObject.contentString += JSON.stringify(filepath) resultObject.contentArray.push(filepath) return callback(resultObject) read = (filepath) -> encounteredFile() fs.stat filepath, (err, stats) -> # could not get stats, quit on the file and move on return processedFile(null) if err if stats.isDirectory() # directory. read it files. using recursion fs.readdir filepath, (err, files) -> # quit on the directory. couldnt get list of files in it return processedFile(null) if err # loop thru each file and process it for file in files read path.join(filepath, file) # I done with this directory so I quit on it processedFile(null) else if stats.isFile() if path.extname(filepath) is ".json" # file. read it content and concatenate it fs.readFile filepath, { encoding: "utf8" }, (err, content) -> # quit on the file. couldnt read it return processedFile(null) if err processedFile(content) else processedFile(null) # start the process read(filepath) ### Creates a new JSON object from a string of concatenated stringified JSON objects. @param <string> - {String} string of json @param <callback> - {Function} callback(validString, validObject) ### concat = (contentString, contentArray, callback) -> return callback("{}", {}) if contentString is "" # using algorithm 1 (faster, not forgiving) string = contentString.replace /^({\s*})*|({\s*})*$/g, "" string = string.replace /}\s*({\s*})*\s*{/g, "," string = string.replace /}\s*{/g, "," try callback(string, JSON.parse(string)) catch err # using algorithm 2 (slow, forgiving) result = { } for content in contentArray try tmp = JSON.parse(content) for key, value of tmp result[key] = value catch err callback(JSON.stringify(result), result) ### exported function ### exports = module.exports = (userOptions, callback) -> # options options = src: userOptions.src || process.cwd() dest: userOptions.dest || "./concat.json" middleware: userOptions.middleware || false # ensure `null` is respected for options.dest if userOptions.dest is null then options.dest = null # make options.src an array if typeof(options.src) is "string" then options.src = [options.src] result = { } index = 0 start = (callback) -> next = () -> readContent options.src[index], result, () -> ++index return next() if index < options.src.length concat result.contentString, result.contentArray, (string, obj) -> if options.dest fs.writeFile options.dest, string, (err) -> callback(err, obj) else callback(null, obj) next() # in a connect/express app if options.middleware return (req, res, next) -> start((err, obj) -> next(obj || {})) else return start(callback)
true
### Concatenating Json Objects Author: @mugo_gocho <PI:EMAIL:<EMAIL>END_PI> License: MIT ### ### Notes: 1. A result object is reused in order to avoid creating many arrays then have to join them together. This makes it faster. 2. Two alternative algorithms can be used to concatenate stringified JSON objects: i) Concatenate, use RegExp and Parse (algorithm 1) - concatenate the stringified json objects - use RegExp to try make the string a valid stringified json object - parse the result string into an object ii) Parse and Join - parse each string into a json object - then loop through each of the objects assigning its keys and values to a result object Performance: - I used jsperf.com to run performance test. - algorithm 1 was faster than algorithm 2 - See test suite at http://jsperf.com/json-concat/ Discussion/Conclusion: - Although algorithm 1 is faster, we use both. Reason is that algorithm 2 is forgiving by letting us ignore strings that can not be parsed into objects. algorithm 1 makes it hard to rescue the situation if the final string can not be parsed. We use algorithm 1 at first. If it fails to realize an object, we turn to algorithm 2 to scavange any objects it can find. ### "use strict" # Built-in modules fs = require "fs" path = require "path" ### Concatenates content from all JSON files encountered This is recursive and will go into directories looking for files with the extension ".json" @param <filepath> - {String} path to file/directory @param <resultObject> - {Object} object that will hold the result (see note 1) @param <callback> - {Function} callback(content, contentArray) ### readContent = (filepath, resultObject, callback) -> filesEncountered = 0 filesProcessed = 0 resultObject.contentString ?= "" resultObject.contentArray ?= [] encounteredFile = () -> filesEncountered++ processedFile = (fileContent="") -> resultObject.contentString += fileContent resultObject.contentArray.push(fileContent) if fileContent filesProcessed++ callback(resultObject) if filesProcessed is filesEncountered # special case(s) if typeof(filepath) is "object" resultObject.contentString += JSON.stringify(filepath) resultObject.contentArray.push(filepath) return callback(resultObject) read = (filepath) -> encounteredFile() fs.stat filepath, (err, stats) -> # could not get stats, quit on the file and move on return processedFile(null) if err if stats.isDirectory() # directory. read it files. using recursion fs.readdir filepath, (err, files) -> # quit on the directory. couldnt get list of files in it return processedFile(null) if err # loop thru each file and process it for file in files read path.join(filepath, file) # I done with this directory so I quit on it processedFile(null) else if stats.isFile() if path.extname(filepath) is ".json" # file. read it content and concatenate it fs.readFile filepath, { encoding: "utf8" }, (err, content) -> # quit on the file. couldnt read it return processedFile(null) if err processedFile(content) else processedFile(null) # start the process read(filepath) ### Creates a new JSON object from a string of concatenated stringified JSON objects. @param <string> - {String} string of json @param <callback> - {Function} callback(validString, validObject) ### concat = (contentString, contentArray, callback) -> return callback("{}", {}) if contentString is "" # using algorithm 1 (faster, not forgiving) string = contentString.replace /^({\s*})*|({\s*})*$/g, "" string = string.replace /}\s*({\s*})*\s*{/g, "," string = string.replace /}\s*{/g, "," try callback(string, JSON.parse(string)) catch err # using algorithm 2 (slow, forgiving) result = { } for content in contentArray try tmp = JSON.parse(content) for key, value of tmp result[key] = value catch err callback(JSON.stringify(result), result) ### exported function ### exports = module.exports = (userOptions, callback) -> # options options = src: userOptions.src || process.cwd() dest: userOptions.dest || "./concat.json" middleware: userOptions.middleware || false # ensure `null` is respected for options.dest if userOptions.dest is null then options.dest = null # make options.src an array if typeof(options.src) is "string" then options.src = [options.src] result = { } index = 0 start = (callback) -> next = () -> readContent options.src[index], result, () -> ++index return next() if index < options.src.length concat result.contentString, result.contentArray, (string, obj) -> if options.dest fs.writeFile options.dest, string, (err) -> callback(err, obj) else callback(null, obj) next() # in a connect/express app if options.middleware return (req, res, next) -> start((err, obj) -> next(obj || {})) else return start(callback)
[ { "context": "ich is either a test case or a test\nsuite\n\n@author Roelof Roos (https://github.com/roelofr)\n###\n\nXmlElement = re", "end": 117, "score": 0.999896228313446, "start": 106, "tag": "NAME", "value": "Roelof Roos" }, { "context": "st\nsuite\n\n@author Roelof Roos (https:...
lib/models/junit-node.coffee
roelofr/php-report
0
### JUnit node Contains values of a JUnit test node, which is either a test case or a test suite @author Roelof Roos (https://github.com/roelofr) ### XmlElement = require 'libxmljs/lib/element' module.exports = class JunitNode node: null name: null file: null time: null count: test: null assert: null fail: null error: null constructor: (node) -> unless node instanceof XmlElement and node.attr throw new TypeError "Expected a XML node, got #{typeof node}" # Assign node @node = node # Get attributes @name = node.attr('name')?.value() @file = node.attr('file')?.value() @time = node.attr('time')?.value() # Get counts @count.test = node.attr('tests')?.value() @count.assert = node.attr('assertions')?.value() @count.fail = node.attr('failures')?.value() @count.error = node.attr('errors')?.value() getNode: -> return @node getName: -> return @name getFile: -> return @file getTime: -> return @time getTestCount: -> return @count.test getAssertCount: -> return @count.assert getFailCount: -> return @count.fail getErrorCount: -> return @count.error hasFailed: -> return Boolean(@node.get('*[descendant::failure]') || @node.get('failure')) hasError: -> return Boolean(@node.get('*[descendant::error]') || @node.get('error'))
33378
### JUnit node Contains values of a JUnit test node, which is either a test case or a test suite @author <NAME> (https://github.com/roelofr) ### XmlElement = require 'libxmljs/lib/element' module.exports = class JunitNode node: null name: null file: null time: null count: test: null assert: null fail: null error: null constructor: (node) -> unless node instanceof XmlElement and node.attr throw new TypeError "Expected a XML node, got #{typeof node}" # Assign node @node = node # Get attributes @name = node.attr('name')?.value() @file = node.attr('file')?.value() @time = node.attr('time')?.value() # Get counts @count.test = node.attr('tests')?.value() @count.assert = node.attr('assertions')?.value() @count.fail = node.attr('failures')?.value() @count.error = node.attr('errors')?.value() getNode: -> return @node getName: -> return @name getFile: -> return @file getTime: -> return @time getTestCount: -> return @count.test getAssertCount: -> return @count.assert getFailCount: -> return @count.fail getErrorCount: -> return @count.error hasFailed: -> return Boolean(@node.get('*[descendant::failure]') || @node.get('failure')) hasError: -> return Boolean(@node.get('*[descendant::error]') || @node.get('error'))
true
### JUnit node Contains values of a JUnit test node, which is either a test case or a test suite @author PI:NAME:<NAME>END_PI (https://github.com/roelofr) ### XmlElement = require 'libxmljs/lib/element' module.exports = class JunitNode node: null name: null file: null time: null count: test: null assert: null fail: null error: null constructor: (node) -> unless node instanceof XmlElement and node.attr throw new TypeError "Expected a XML node, got #{typeof node}" # Assign node @node = node # Get attributes @name = node.attr('name')?.value() @file = node.attr('file')?.value() @time = node.attr('time')?.value() # Get counts @count.test = node.attr('tests')?.value() @count.assert = node.attr('assertions')?.value() @count.fail = node.attr('failures')?.value() @count.error = node.attr('errors')?.value() getNode: -> return @node getName: -> return @name getFile: -> return @file getTime: -> return @time getTestCount: -> return @count.test getAssertCount: -> return @count.assert getFailCount: -> return @count.fail getErrorCount: -> return @count.error hasFailed: -> return Boolean(@node.get('*[descendant::failure]') || @node.get('failure')) hasError: -> return Boolean(@node.get('*[descendant::error]') || @node.get('error'))
[ { "context": "ext: 'ohai4',\n replacementPrefix: 'ohai4'\n }]\n dispose: ->\n\n provider", "end": 11350, "score": 0.6030458807945251, "start": 11349, "tag": "KEY", "value": "4" } ]
spec/provider-manager-spec.coffee
Ceorl/autocomplete-plus-standalone
1
ProviderManager = require '../lib/provider-manager' describe 'Provider Manager', -> [providerManager, testProvider, registration] = [] beforeEach -> atom.config.set('autocomplete-plus.enableBuiltinProvider', true) providerManager = new ProviderManager() testProvider = getSuggestions: (options) -> [{ text: 'ohai', replacementPrefix: 'ohai' }] selector: '.source.js' dispose: -> afterEach -> registration?.dispose?() registration = null testProvider?.dispose?() testProvider = null providerManager?.dispose() providerManager = null describe 'when no providers have been registered, and enableBuiltinProvider is true', -> beforeEach -> atom.config.set('autocomplete-plus.enableBuiltinProvider', true) it 'is constructed correctly', -> expect(providerManager.providers).toBeDefined() expect(providerManager.subscriptions).toBeDefined() expect(providerManager.defaultProvider).toBeDefined() it 'disposes correctly', -> providerManager.dispose() expect(providerManager.providers).toBeNull() expect(providerManager.subscriptions).toBeNull() expect(providerManager.defaultProvider).toBeNull() it 'registers the default provider for all scopes', -> expect(providerManager.providersForScopeDescriptor('*').length).toBe(1) expect(providerManager.providersForScopeDescriptor('*')[0]).toBe(providerManager.defaultProvider) it 'adds providers', -> expect(providerManager.isProviderRegistered(testProvider)).toEqual(false) expect(hasDisposable(providerManager.subscriptions, testProvider)).toBe false providerManager.addProvider(testProvider, '2.0.0') expect(providerManager.isProviderRegistered(testProvider)).toEqual(true) apiVersion = providerManager.apiVersionForProvider(testProvider) expect(apiVersion).toEqual('2.0.0') expect(hasDisposable(providerManager.subscriptions, testProvider)).toBe true it 'removes providers', -> expect(providerManager.metadataForProvider(testProvider)).toBeFalsy() expect(hasDisposable(providerManager.subscriptions, testProvider)).toBe false providerManager.addProvider(testProvider) expect(providerManager.metadataForProvider(testProvider)).toBeTruthy() expect(hasDisposable(providerManager.subscriptions, testProvider)).toBe true providerManager.removeProvider(testProvider) expect(providerManager.metadataForProvider(testProvider)).toBeFalsy() expect(hasDisposable(providerManager.subscriptions, testProvider)).toBe false it 'can identify a provider with a missing getSuggestions', -> bogusProvider = badgetSuggestions: (options) -> selector: '.source.js' dispose: -> expect(providerManager.isValidProvider({}, '2.0.0')).toEqual(false) expect(providerManager.isValidProvider(bogusProvider, '2.0.0')).toEqual(false) expect(providerManager.isValidProvider(testProvider, '2.0.0')).toEqual(true) it 'can identify a provider with an invalid getSuggestions', -> bogusProvider = getSuggestions: 'yo, this is a bad handler' selector: '.source.js' dispose: -> expect(providerManager.isValidProvider({}, '2.0.0')).toEqual(false) expect(providerManager.isValidProvider(bogusProvider, '2.0.0')).toEqual(false) expect(providerManager.isValidProvider(testProvider, '2.0.0')).toEqual(true) it 'can identify a provider with a missing selector', -> bogusProvider = getSuggestions: (options) -> aSelector: '.source.js' dispose: -> expect(providerManager.isValidProvider(bogusProvider, '2.0.0')).toEqual(false) expect(providerManager.isValidProvider(testProvider, '2.0.0')).toEqual(true) it 'can identify a provider with an invalid selector', -> bogusProvider = getSuggestions: (options) -> selector: '' dispose: -> expect(providerManager.isValidProvider(bogusProvider, '2.0.0')).toEqual(false) expect(providerManager.isValidProvider(testProvider, '2.0.0')).toEqual(true) bogusProvider = getSuggestions: (options) -> selector: false dispose: -> expect(providerManager.isValidProvider(bogusProvider, '2.0.0')).toEqual(false) it 'correctly identifies a 1.0 provider', -> bogusProvider = selector: '.source.js' requestHandler: 'yo, this is a bad handler' dispose: -> expect(providerManager.isValidProvider({}, '1.0.0')).toEqual(false) expect(providerManager.isValidProvider(bogusProvider, '1.0.0')).toEqual(false) legitProvider = selector: '.source.js' requestHandler: -> dispose: -> expect(providerManager.isValidProvider(legitProvider, '1.0.0')).toEqual(true) it 'registers a valid provider', -> expect(providerManager.providersForScopeDescriptor('.source.js').length).toEqual(1) expect(providerManager.providersForScopeDescriptor('.source.js').indexOf(testProvider)).toBe(-1) expect(providerManager.metadataForProvider(testProvider)).toBeFalsy() registration = providerManager.registerProvider(testProvider) expect(providerManager.providersForScopeDescriptor('.source.js').length).toEqual(2) expect(providerManager.providersForScopeDescriptor('.source.js').indexOf(testProvider)).not.toBe(-1) expect(providerManager.metadataForProvider(testProvider)).toBeTruthy() it 'removes a registration', -> expect(providerManager.providersForScopeDescriptor('.source.js').length).toEqual(1) expect(providerManager.providersForScopeDescriptor('.source.js').indexOf(testProvider)).toBe(-1) expect(providerManager.metadataForProvider(testProvider)).toBeFalsy() registration = providerManager.registerProvider(testProvider) expect(providerManager.providersForScopeDescriptor('.source.js').length).toEqual(2) expect(providerManager.providersForScopeDescriptor('.source.js').indexOf(testProvider)).not.toBe(-1) expect(providerManager.metadataForProvider(testProvider)).toBeTruthy() registration.dispose() expect(providerManager.providersForScopeDescriptor('.source.js').length).toEqual(1) expect(providerManager.providersForScopeDescriptor('.source.js').indexOf(testProvider)).toBe(-1) expect(providerManager.metadataForProvider(testProvider)).toBeFalsy() it 'does not create duplicate registrations for the same scope', -> expect(providerManager.providersForScopeDescriptor('.source.js').length).toEqual(1) expect(providerManager.providersForScopeDescriptor('.source.js').indexOf(testProvider)).toBe(-1) expect(providerManager.metadataForProvider(testProvider)).toBeFalsy() registration = providerManager.registerProvider(testProvider) expect(providerManager.providersForScopeDescriptor('.source.js').length).toEqual(2) expect(providerManager.providersForScopeDescriptor('.source.js').indexOf(testProvider)).not.toBe(-1) expect(providerManager.metadataForProvider(testProvider)).toBeTruthy() registration = providerManager.registerProvider(testProvider) expect(providerManager.providersForScopeDescriptor('.source.js').length).toEqual(2) expect(providerManager.providersForScopeDescriptor('.source.js').indexOf(testProvider)).not.toBe(-1) expect(providerManager.metadataForProvider(testProvider)).toBeTruthy() registration = providerManager.registerProvider(testProvider) expect(providerManager.providersForScopeDescriptor('.source.js').length).toEqual(2) expect(providerManager.providersForScopeDescriptor('.source.js').indexOf(testProvider)).not.toBe(-1) expect(providerManager.metadataForProvider(testProvider)).toBeTruthy() it 'does not register an invalid provider', -> bogusProvider = getSuggestions: 'yo, this is a bad handler' selector: '.source.js' dispose: -> return expect(providerManager.providersForScopeDescriptor('.source.js').length).toEqual(1) expect(providerManager.providersForScopeDescriptor('.source.js').indexOf(bogusProvider)).toBe(-1) expect(providerManager.metadataForProvider(bogusProvider)).toBeFalsy() registration = providerManager.registerProvider(bogusProvider) expect(providerManager.providersForScopeDescriptor('.source.js').length).toEqual(1) expect(providerManager.providersForScopeDescriptor('.source.js').indexOf(bogusProvider)).toBe(-1) expect(providerManager.metadataForProvider(bogusProvider)).toBeFalsy() it 'registers a provider with a blacklist', -> testProvider = getSuggestions: (options) -> [{ text: 'ohai', replacementPrefix: 'ohai' }] selector: '.source.js' disableForSelector: '.source.js .comment' dispose: -> return expect(providerManager.isValidProvider(testProvider, '2.0.0')).toEqual(true) expect(providerManager.providersForScopeDescriptor('.source.js').length).toEqual(1) expect(providerManager.providersForScopeDescriptor('.source.js').indexOf(testProvider)).toBe(-1) expect(providerManager.metadataForProvider(testProvider)).toBeFalsy() registration = providerManager.registerProvider(testProvider) expect(providerManager.providersForScopeDescriptor('.source.js').length).toEqual(2) expect(providerManager.providersForScopeDescriptor('.source.js').indexOf(testProvider)).not.toBe(-1) expect(providerManager.metadataForProvider(testProvider)).toBeTruthy() describe 'when no providers have been registered, and enableBuiltinProvider is false', -> beforeEach -> atom.config.set('autocomplete-plus.enableBuiltinProvider', false) it 'does not register the default provider for all scopes', -> expect(providerManager.providersForScopeDescriptor('*').length).toBe(0) expect(providerManager.defaultProvider).toEqual(null) expect(providerManager.defaultProviderRegistration).toEqual(null) describe 'when providers have been registered', -> [testProvider1, testProvider2, testProvider3, testProvider4] = [] beforeEach -> atom.config.set('autocomplete-plus.enableBuiltinProvider', true) providerManager = new ProviderManager() testProvider1 = selector: '.source.js' getSuggestions: (options) -> [{ text: 'ohai2', replacementPrefix: 'ohai2' }] dispose: -> testProvider2 = selector: '.source.js .variable.js' disableForSelector: '.source.js .variable.js .comment2' providerblacklist: 'autocomplete-plus-fuzzyprovider': '.source.js .variable.js .comment3' getSuggestions: (options) -> [{ text: 'ohai2', replacementPrefix: 'ohai2' }] dispose: -> testProvider3 = selector: '*' getSuggestions: (options) -> [{ text: 'ohai3', replacementPrefix: 'ohai3' }] dispose: -> testProvider4 = selector: '.source.js .comment' getSuggestions: (options) -> [{ text: 'ohai4', replacementPrefix: 'ohai4' }] dispose: -> providerManager.registerProvider(testProvider1) providerManager.registerProvider(testProvider2) providerManager.registerProvider(testProvider3) providerManager.registerProvider(testProvider4) it 'returns providers in the correct order for the given scope chain', -> defaultProvider = providerManager.defaultProvider providers = providerManager.providersForScopeDescriptor('.source.other') expect(providers).toHaveLength 2 expect(providers[0]).toEqual testProvider3 expect(providers[1]).toEqual defaultProvider providers = providerManager.providersForScopeDescriptor('.source.js') expect(providers).toHaveLength 3 expect(providers[0]).toEqual testProvider1 expect(providers[1]).toEqual testProvider3 expect(providers[2]).toEqual defaultProvider providers = providerManager.providersForScopeDescriptor('.source.js .comment') expect(providers).toHaveLength 4 expect(providers[0]).toEqual testProvider4 expect(providers[1]).toEqual testProvider1 expect(providers[2]).toEqual testProvider3 expect(providers[3]).toEqual defaultProvider providers = providerManager.providersForScopeDescriptor('.source.js .variable.js') expect(providers).toHaveLength 4 expect(providers[0]).toEqual testProvider2 expect(providers[1]).toEqual testProvider1 expect(providers[2]).toEqual testProvider3 expect(providers[3]).toEqual defaultProvider providers = providerManager.providersForScopeDescriptor('.source.js .other.js') expect(providers).toHaveLength 3 expect(providers[0]).toEqual testProvider1 expect(providers[1]).toEqual testProvider3 expect(providers[2]).toEqual defaultProvider it 'does not return providers if the scopeChain exactly matches a global blacklist item', -> expect(providerManager.providersForScopeDescriptor('.source.js .comment')).toHaveLength 4 atom.config.set('autocomplete-plus.scopeBlacklist', ['.source.js .comment']) expect(providerManager.providersForScopeDescriptor('.source.js .comment')).toHaveLength 0 it 'does not return providers if the scopeChain matches a global blacklist item with a wildcard', -> expect(providerManager.providersForScopeDescriptor('.source.js .comment')).toHaveLength 4 atom.config.set('autocomplete-plus.scopeBlacklist', ['.source.js *']) expect(providerManager.providersForScopeDescriptor('.source.js .comment')).toHaveLength 0 it 'does not return providers if the scopeChain matches a global blacklist item with a wildcard one level of depth below the current scope', -> expect(providerManager.providersForScopeDescriptor('.source.js .comment')).toHaveLength 4 atom.config.set('autocomplete-plus.scopeBlacklist', ['.source.js *']) expect(providerManager.providersForScopeDescriptor('.source.js .comment .other')).toHaveLength 0 it 'does return providers if the scopeChain does not match a global blacklist item with a wildcard', -> expect(providerManager.providersForScopeDescriptor('.source.js .comment')).toHaveLength 4 atom.config.set('autocomplete-plus.scopeBlacklist', ['.source.coffee *']) expect(providerManager.providersForScopeDescriptor('.source.js .comment')).toHaveLength 4 it 'filters a provider if the scopeChain matches a provider blacklist item', -> defaultProvider = providerManager.defaultProvider providers = providerManager.providersForScopeDescriptor('.source.js .variable.js .other.js') expect(providers).toHaveLength 4 expect(providers[0]).toEqual testProvider2 expect(providers[1]).toEqual testProvider1 expect(providers[2]).toEqual testProvider3 expect(providers[3]).toEqual defaultProvider providers = providerManager.providersForScopeDescriptor('.source.js .variable.js .comment2.js') expect(providers).toHaveLength 3 expect(providers[0]).toEqual testProvider1 expect(providers[1]).toEqual testProvider3 expect(providers[2]).toEqual defaultProvider it 'filters a provider if the scopeChain matches a provider providerblacklist item', -> providers = providerManager.providersForScopeDescriptor('.source.js .variable.js .other.js') expect(providers).toHaveLength 4 expect(providers[0]).toEqual(testProvider2) expect(providers[1]).toEqual(testProvider1) expect(providers[2]).toEqual(testProvider3) expect(providers[3]).toEqual(providerManager.defaultProvider) providers = providerManager.providersForScopeDescriptor('.source.js .variable.js .comment3.js') expect(providers).toHaveLength 3 expect(providers[0]).toEqual(testProvider2) expect(providers[1]).toEqual(testProvider1) expect(providers[2]).toEqual(testProvider3) describe "when inclusion priorities are used", -> [accessoryProvider1, accessoryProvider2, verySpecificProvider, mainProvider, defaultProvider] = [] beforeEach -> atom.config.set('autocomplete-plus.enableBuiltinProvider', true) providerManager = new ProviderManager() defaultProvider = providerManager.defaultProvider accessoryProvider1 = selector: '*' inclusionPriority: 2 getSuggestions: (options) -> dispose: -> accessoryProvider2 = selector: '.source.js' inclusionPriority: 2 excludeLowerPriority: false getSuggestions: (options) -> dispose: -> verySpecificProvider = selector: '.source.js .comment' inclusionPriority: 2 excludeLowerPriority: true getSuggestions: (options) -> dispose: -> mainProvider = selector: '.source.js' inclusionPriority: 1 excludeLowerPriority: true getSuggestions: (options) -> dispose: -> providerManager.registerProvider(accessoryProvider1) providerManager.registerProvider(accessoryProvider2) providerManager.registerProvider(verySpecificProvider) providerManager.registerProvider(mainProvider) it 'returns the default provider and higher when nothing with a higher proirity is excluding the lower', -> providers = providerManager.providersForScopeDescriptor('.source.coffee') expect(providers).toHaveLength 2 expect(providers[0]).toEqual accessoryProvider1 expect(providers[1]).toEqual defaultProvider it 'exclude the lower priority provider, the default, when one with a higher proirity excludes the lower', -> providers = providerManager.providersForScopeDescriptor('.source.js') expect(providers).toHaveLength 3 expect(providers[0]).toEqual accessoryProvider2 expect(providers[1]).toEqual mainProvider expect(providers[2]).toEqual accessoryProvider1 it 'excludes the all lower priority providers when multiple providers of lower priority', -> providers = providerManager.providersForScopeDescriptor('.source.js .comment') expect(providers).toHaveLength 3 expect(providers[0]).toEqual verySpecificProvider expect(providers[1]).toEqual accessoryProvider2 expect(providers[2]).toEqual accessoryProvider1 describe "when suggestionPriorities are the same", -> [provider1, provider2, provider3, defaultProvider] = [] beforeEach -> atom.config.set('autocomplete-plus.enableBuiltinProvider', true) providerManager = new ProviderManager() defaultProvider = providerManager.defaultProvider provider1 = selector: '*' suggestionPriority: 2 getSuggestions: (options) -> dispose: -> provider2 = selector: '.source.js' suggestionPriority: 3 getSuggestions: (options) -> dispose: -> provider3 = selector: '.source.js .comment' suggestionPriority: 2 getSuggestions: (options) -> dispose: -> providerManager.registerProvider(provider1) providerManager.registerProvider(provider2) providerManager.registerProvider(provider3) it 'sorts by specificity', -> providers = providerManager.providersForScopeDescriptor('.source.js .comment') expect(providers).toHaveLength 4 expect(providers[0]).toEqual provider2 expect(providers[1]).toEqual provider3 expect(providers[2]).toEqual provider1 hasDisposable = (compositeDisposable, disposable) -> if compositeDisposable?.disposables?.has? compositeDisposable.disposables.has(disposable) else if compositeDisposable?.disposables?.indexOf? compositeDisposable.disposables.indexOf(disposable) > -1 else false
149585
ProviderManager = require '../lib/provider-manager' describe 'Provider Manager', -> [providerManager, testProvider, registration] = [] beforeEach -> atom.config.set('autocomplete-plus.enableBuiltinProvider', true) providerManager = new ProviderManager() testProvider = getSuggestions: (options) -> [{ text: 'ohai', replacementPrefix: 'ohai' }] selector: '.source.js' dispose: -> afterEach -> registration?.dispose?() registration = null testProvider?.dispose?() testProvider = null providerManager?.dispose() providerManager = null describe 'when no providers have been registered, and enableBuiltinProvider is true', -> beforeEach -> atom.config.set('autocomplete-plus.enableBuiltinProvider', true) it 'is constructed correctly', -> expect(providerManager.providers).toBeDefined() expect(providerManager.subscriptions).toBeDefined() expect(providerManager.defaultProvider).toBeDefined() it 'disposes correctly', -> providerManager.dispose() expect(providerManager.providers).toBeNull() expect(providerManager.subscriptions).toBeNull() expect(providerManager.defaultProvider).toBeNull() it 'registers the default provider for all scopes', -> expect(providerManager.providersForScopeDescriptor('*').length).toBe(1) expect(providerManager.providersForScopeDescriptor('*')[0]).toBe(providerManager.defaultProvider) it 'adds providers', -> expect(providerManager.isProviderRegistered(testProvider)).toEqual(false) expect(hasDisposable(providerManager.subscriptions, testProvider)).toBe false providerManager.addProvider(testProvider, '2.0.0') expect(providerManager.isProviderRegistered(testProvider)).toEqual(true) apiVersion = providerManager.apiVersionForProvider(testProvider) expect(apiVersion).toEqual('2.0.0') expect(hasDisposable(providerManager.subscriptions, testProvider)).toBe true it 'removes providers', -> expect(providerManager.metadataForProvider(testProvider)).toBeFalsy() expect(hasDisposable(providerManager.subscriptions, testProvider)).toBe false providerManager.addProvider(testProvider) expect(providerManager.metadataForProvider(testProvider)).toBeTruthy() expect(hasDisposable(providerManager.subscriptions, testProvider)).toBe true providerManager.removeProvider(testProvider) expect(providerManager.metadataForProvider(testProvider)).toBeFalsy() expect(hasDisposable(providerManager.subscriptions, testProvider)).toBe false it 'can identify a provider with a missing getSuggestions', -> bogusProvider = badgetSuggestions: (options) -> selector: '.source.js' dispose: -> expect(providerManager.isValidProvider({}, '2.0.0')).toEqual(false) expect(providerManager.isValidProvider(bogusProvider, '2.0.0')).toEqual(false) expect(providerManager.isValidProvider(testProvider, '2.0.0')).toEqual(true) it 'can identify a provider with an invalid getSuggestions', -> bogusProvider = getSuggestions: 'yo, this is a bad handler' selector: '.source.js' dispose: -> expect(providerManager.isValidProvider({}, '2.0.0')).toEqual(false) expect(providerManager.isValidProvider(bogusProvider, '2.0.0')).toEqual(false) expect(providerManager.isValidProvider(testProvider, '2.0.0')).toEqual(true) it 'can identify a provider with a missing selector', -> bogusProvider = getSuggestions: (options) -> aSelector: '.source.js' dispose: -> expect(providerManager.isValidProvider(bogusProvider, '2.0.0')).toEqual(false) expect(providerManager.isValidProvider(testProvider, '2.0.0')).toEqual(true) it 'can identify a provider with an invalid selector', -> bogusProvider = getSuggestions: (options) -> selector: '' dispose: -> expect(providerManager.isValidProvider(bogusProvider, '2.0.0')).toEqual(false) expect(providerManager.isValidProvider(testProvider, '2.0.0')).toEqual(true) bogusProvider = getSuggestions: (options) -> selector: false dispose: -> expect(providerManager.isValidProvider(bogusProvider, '2.0.0')).toEqual(false) it 'correctly identifies a 1.0 provider', -> bogusProvider = selector: '.source.js' requestHandler: 'yo, this is a bad handler' dispose: -> expect(providerManager.isValidProvider({}, '1.0.0')).toEqual(false) expect(providerManager.isValidProvider(bogusProvider, '1.0.0')).toEqual(false) legitProvider = selector: '.source.js' requestHandler: -> dispose: -> expect(providerManager.isValidProvider(legitProvider, '1.0.0')).toEqual(true) it 'registers a valid provider', -> expect(providerManager.providersForScopeDescriptor('.source.js').length).toEqual(1) expect(providerManager.providersForScopeDescriptor('.source.js').indexOf(testProvider)).toBe(-1) expect(providerManager.metadataForProvider(testProvider)).toBeFalsy() registration = providerManager.registerProvider(testProvider) expect(providerManager.providersForScopeDescriptor('.source.js').length).toEqual(2) expect(providerManager.providersForScopeDescriptor('.source.js').indexOf(testProvider)).not.toBe(-1) expect(providerManager.metadataForProvider(testProvider)).toBeTruthy() it 'removes a registration', -> expect(providerManager.providersForScopeDescriptor('.source.js').length).toEqual(1) expect(providerManager.providersForScopeDescriptor('.source.js').indexOf(testProvider)).toBe(-1) expect(providerManager.metadataForProvider(testProvider)).toBeFalsy() registration = providerManager.registerProvider(testProvider) expect(providerManager.providersForScopeDescriptor('.source.js').length).toEqual(2) expect(providerManager.providersForScopeDescriptor('.source.js').indexOf(testProvider)).not.toBe(-1) expect(providerManager.metadataForProvider(testProvider)).toBeTruthy() registration.dispose() expect(providerManager.providersForScopeDescriptor('.source.js').length).toEqual(1) expect(providerManager.providersForScopeDescriptor('.source.js').indexOf(testProvider)).toBe(-1) expect(providerManager.metadataForProvider(testProvider)).toBeFalsy() it 'does not create duplicate registrations for the same scope', -> expect(providerManager.providersForScopeDescriptor('.source.js').length).toEqual(1) expect(providerManager.providersForScopeDescriptor('.source.js').indexOf(testProvider)).toBe(-1) expect(providerManager.metadataForProvider(testProvider)).toBeFalsy() registration = providerManager.registerProvider(testProvider) expect(providerManager.providersForScopeDescriptor('.source.js').length).toEqual(2) expect(providerManager.providersForScopeDescriptor('.source.js').indexOf(testProvider)).not.toBe(-1) expect(providerManager.metadataForProvider(testProvider)).toBeTruthy() registration = providerManager.registerProvider(testProvider) expect(providerManager.providersForScopeDescriptor('.source.js').length).toEqual(2) expect(providerManager.providersForScopeDescriptor('.source.js').indexOf(testProvider)).not.toBe(-1) expect(providerManager.metadataForProvider(testProvider)).toBeTruthy() registration = providerManager.registerProvider(testProvider) expect(providerManager.providersForScopeDescriptor('.source.js').length).toEqual(2) expect(providerManager.providersForScopeDescriptor('.source.js').indexOf(testProvider)).not.toBe(-1) expect(providerManager.metadataForProvider(testProvider)).toBeTruthy() it 'does not register an invalid provider', -> bogusProvider = getSuggestions: 'yo, this is a bad handler' selector: '.source.js' dispose: -> return expect(providerManager.providersForScopeDescriptor('.source.js').length).toEqual(1) expect(providerManager.providersForScopeDescriptor('.source.js').indexOf(bogusProvider)).toBe(-1) expect(providerManager.metadataForProvider(bogusProvider)).toBeFalsy() registration = providerManager.registerProvider(bogusProvider) expect(providerManager.providersForScopeDescriptor('.source.js').length).toEqual(1) expect(providerManager.providersForScopeDescriptor('.source.js').indexOf(bogusProvider)).toBe(-1) expect(providerManager.metadataForProvider(bogusProvider)).toBeFalsy() it 'registers a provider with a blacklist', -> testProvider = getSuggestions: (options) -> [{ text: 'ohai', replacementPrefix: 'ohai' }] selector: '.source.js' disableForSelector: '.source.js .comment' dispose: -> return expect(providerManager.isValidProvider(testProvider, '2.0.0')).toEqual(true) expect(providerManager.providersForScopeDescriptor('.source.js').length).toEqual(1) expect(providerManager.providersForScopeDescriptor('.source.js').indexOf(testProvider)).toBe(-1) expect(providerManager.metadataForProvider(testProvider)).toBeFalsy() registration = providerManager.registerProvider(testProvider) expect(providerManager.providersForScopeDescriptor('.source.js').length).toEqual(2) expect(providerManager.providersForScopeDescriptor('.source.js').indexOf(testProvider)).not.toBe(-1) expect(providerManager.metadataForProvider(testProvider)).toBeTruthy() describe 'when no providers have been registered, and enableBuiltinProvider is false', -> beforeEach -> atom.config.set('autocomplete-plus.enableBuiltinProvider', false) it 'does not register the default provider for all scopes', -> expect(providerManager.providersForScopeDescriptor('*').length).toBe(0) expect(providerManager.defaultProvider).toEqual(null) expect(providerManager.defaultProviderRegistration).toEqual(null) describe 'when providers have been registered', -> [testProvider1, testProvider2, testProvider3, testProvider4] = [] beforeEach -> atom.config.set('autocomplete-plus.enableBuiltinProvider', true) providerManager = new ProviderManager() testProvider1 = selector: '.source.js' getSuggestions: (options) -> [{ text: 'ohai2', replacementPrefix: 'ohai2' }] dispose: -> testProvider2 = selector: '.source.js .variable.js' disableForSelector: '.source.js .variable.js .comment2' providerblacklist: 'autocomplete-plus-fuzzyprovider': '.source.js .variable.js .comment3' getSuggestions: (options) -> [{ text: 'ohai2', replacementPrefix: 'ohai2' }] dispose: -> testProvider3 = selector: '*' getSuggestions: (options) -> [{ text: 'ohai3', replacementPrefix: 'ohai3' }] dispose: -> testProvider4 = selector: '.source.js .comment' getSuggestions: (options) -> [{ text: 'ohai4', replacementPrefix: 'ohai<KEY>' }] dispose: -> providerManager.registerProvider(testProvider1) providerManager.registerProvider(testProvider2) providerManager.registerProvider(testProvider3) providerManager.registerProvider(testProvider4) it 'returns providers in the correct order for the given scope chain', -> defaultProvider = providerManager.defaultProvider providers = providerManager.providersForScopeDescriptor('.source.other') expect(providers).toHaveLength 2 expect(providers[0]).toEqual testProvider3 expect(providers[1]).toEqual defaultProvider providers = providerManager.providersForScopeDescriptor('.source.js') expect(providers).toHaveLength 3 expect(providers[0]).toEqual testProvider1 expect(providers[1]).toEqual testProvider3 expect(providers[2]).toEqual defaultProvider providers = providerManager.providersForScopeDescriptor('.source.js .comment') expect(providers).toHaveLength 4 expect(providers[0]).toEqual testProvider4 expect(providers[1]).toEqual testProvider1 expect(providers[2]).toEqual testProvider3 expect(providers[3]).toEqual defaultProvider providers = providerManager.providersForScopeDescriptor('.source.js .variable.js') expect(providers).toHaveLength 4 expect(providers[0]).toEqual testProvider2 expect(providers[1]).toEqual testProvider1 expect(providers[2]).toEqual testProvider3 expect(providers[3]).toEqual defaultProvider providers = providerManager.providersForScopeDescriptor('.source.js .other.js') expect(providers).toHaveLength 3 expect(providers[0]).toEqual testProvider1 expect(providers[1]).toEqual testProvider3 expect(providers[2]).toEqual defaultProvider it 'does not return providers if the scopeChain exactly matches a global blacklist item', -> expect(providerManager.providersForScopeDescriptor('.source.js .comment')).toHaveLength 4 atom.config.set('autocomplete-plus.scopeBlacklist', ['.source.js .comment']) expect(providerManager.providersForScopeDescriptor('.source.js .comment')).toHaveLength 0 it 'does not return providers if the scopeChain matches a global blacklist item with a wildcard', -> expect(providerManager.providersForScopeDescriptor('.source.js .comment')).toHaveLength 4 atom.config.set('autocomplete-plus.scopeBlacklist', ['.source.js *']) expect(providerManager.providersForScopeDescriptor('.source.js .comment')).toHaveLength 0 it 'does not return providers if the scopeChain matches a global blacklist item with a wildcard one level of depth below the current scope', -> expect(providerManager.providersForScopeDescriptor('.source.js .comment')).toHaveLength 4 atom.config.set('autocomplete-plus.scopeBlacklist', ['.source.js *']) expect(providerManager.providersForScopeDescriptor('.source.js .comment .other')).toHaveLength 0 it 'does return providers if the scopeChain does not match a global blacklist item with a wildcard', -> expect(providerManager.providersForScopeDescriptor('.source.js .comment')).toHaveLength 4 atom.config.set('autocomplete-plus.scopeBlacklist', ['.source.coffee *']) expect(providerManager.providersForScopeDescriptor('.source.js .comment')).toHaveLength 4 it 'filters a provider if the scopeChain matches a provider blacklist item', -> defaultProvider = providerManager.defaultProvider providers = providerManager.providersForScopeDescriptor('.source.js .variable.js .other.js') expect(providers).toHaveLength 4 expect(providers[0]).toEqual testProvider2 expect(providers[1]).toEqual testProvider1 expect(providers[2]).toEqual testProvider3 expect(providers[3]).toEqual defaultProvider providers = providerManager.providersForScopeDescriptor('.source.js .variable.js .comment2.js') expect(providers).toHaveLength 3 expect(providers[0]).toEqual testProvider1 expect(providers[1]).toEqual testProvider3 expect(providers[2]).toEqual defaultProvider it 'filters a provider if the scopeChain matches a provider providerblacklist item', -> providers = providerManager.providersForScopeDescriptor('.source.js .variable.js .other.js') expect(providers).toHaveLength 4 expect(providers[0]).toEqual(testProvider2) expect(providers[1]).toEqual(testProvider1) expect(providers[2]).toEqual(testProvider3) expect(providers[3]).toEqual(providerManager.defaultProvider) providers = providerManager.providersForScopeDescriptor('.source.js .variable.js .comment3.js') expect(providers).toHaveLength 3 expect(providers[0]).toEqual(testProvider2) expect(providers[1]).toEqual(testProvider1) expect(providers[2]).toEqual(testProvider3) describe "when inclusion priorities are used", -> [accessoryProvider1, accessoryProvider2, verySpecificProvider, mainProvider, defaultProvider] = [] beforeEach -> atom.config.set('autocomplete-plus.enableBuiltinProvider', true) providerManager = new ProviderManager() defaultProvider = providerManager.defaultProvider accessoryProvider1 = selector: '*' inclusionPriority: 2 getSuggestions: (options) -> dispose: -> accessoryProvider2 = selector: '.source.js' inclusionPriority: 2 excludeLowerPriority: false getSuggestions: (options) -> dispose: -> verySpecificProvider = selector: '.source.js .comment' inclusionPriority: 2 excludeLowerPriority: true getSuggestions: (options) -> dispose: -> mainProvider = selector: '.source.js' inclusionPriority: 1 excludeLowerPriority: true getSuggestions: (options) -> dispose: -> providerManager.registerProvider(accessoryProvider1) providerManager.registerProvider(accessoryProvider2) providerManager.registerProvider(verySpecificProvider) providerManager.registerProvider(mainProvider) it 'returns the default provider and higher when nothing with a higher proirity is excluding the lower', -> providers = providerManager.providersForScopeDescriptor('.source.coffee') expect(providers).toHaveLength 2 expect(providers[0]).toEqual accessoryProvider1 expect(providers[1]).toEqual defaultProvider it 'exclude the lower priority provider, the default, when one with a higher proirity excludes the lower', -> providers = providerManager.providersForScopeDescriptor('.source.js') expect(providers).toHaveLength 3 expect(providers[0]).toEqual accessoryProvider2 expect(providers[1]).toEqual mainProvider expect(providers[2]).toEqual accessoryProvider1 it 'excludes the all lower priority providers when multiple providers of lower priority', -> providers = providerManager.providersForScopeDescriptor('.source.js .comment') expect(providers).toHaveLength 3 expect(providers[0]).toEqual verySpecificProvider expect(providers[1]).toEqual accessoryProvider2 expect(providers[2]).toEqual accessoryProvider1 describe "when suggestionPriorities are the same", -> [provider1, provider2, provider3, defaultProvider] = [] beforeEach -> atom.config.set('autocomplete-plus.enableBuiltinProvider', true) providerManager = new ProviderManager() defaultProvider = providerManager.defaultProvider provider1 = selector: '*' suggestionPriority: 2 getSuggestions: (options) -> dispose: -> provider2 = selector: '.source.js' suggestionPriority: 3 getSuggestions: (options) -> dispose: -> provider3 = selector: '.source.js .comment' suggestionPriority: 2 getSuggestions: (options) -> dispose: -> providerManager.registerProvider(provider1) providerManager.registerProvider(provider2) providerManager.registerProvider(provider3) it 'sorts by specificity', -> providers = providerManager.providersForScopeDescriptor('.source.js .comment') expect(providers).toHaveLength 4 expect(providers[0]).toEqual provider2 expect(providers[1]).toEqual provider3 expect(providers[2]).toEqual provider1 hasDisposable = (compositeDisposable, disposable) -> if compositeDisposable?.disposables?.has? compositeDisposable.disposables.has(disposable) else if compositeDisposable?.disposables?.indexOf? compositeDisposable.disposables.indexOf(disposable) > -1 else false
true
ProviderManager = require '../lib/provider-manager' describe 'Provider Manager', -> [providerManager, testProvider, registration] = [] beforeEach -> atom.config.set('autocomplete-plus.enableBuiltinProvider', true) providerManager = new ProviderManager() testProvider = getSuggestions: (options) -> [{ text: 'ohai', replacementPrefix: 'ohai' }] selector: '.source.js' dispose: -> afterEach -> registration?.dispose?() registration = null testProvider?.dispose?() testProvider = null providerManager?.dispose() providerManager = null describe 'when no providers have been registered, and enableBuiltinProvider is true', -> beforeEach -> atom.config.set('autocomplete-plus.enableBuiltinProvider', true) it 'is constructed correctly', -> expect(providerManager.providers).toBeDefined() expect(providerManager.subscriptions).toBeDefined() expect(providerManager.defaultProvider).toBeDefined() it 'disposes correctly', -> providerManager.dispose() expect(providerManager.providers).toBeNull() expect(providerManager.subscriptions).toBeNull() expect(providerManager.defaultProvider).toBeNull() it 'registers the default provider for all scopes', -> expect(providerManager.providersForScopeDescriptor('*').length).toBe(1) expect(providerManager.providersForScopeDescriptor('*')[0]).toBe(providerManager.defaultProvider) it 'adds providers', -> expect(providerManager.isProviderRegistered(testProvider)).toEqual(false) expect(hasDisposable(providerManager.subscriptions, testProvider)).toBe false providerManager.addProvider(testProvider, '2.0.0') expect(providerManager.isProviderRegistered(testProvider)).toEqual(true) apiVersion = providerManager.apiVersionForProvider(testProvider) expect(apiVersion).toEqual('2.0.0') expect(hasDisposable(providerManager.subscriptions, testProvider)).toBe true it 'removes providers', -> expect(providerManager.metadataForProvider(testProvider)).toBeFalsy() expect(hasDisposable(providerManager.subscriptions, testProvider)).toBe false providerManager.addProvider(testProvider) expect(providerManager.metadataForProvider(testProvider)).toBeTruthy() expect(hasDisposable(providerManager.subscriptions, testProvider)).toBe true providerManager.removeProvider(testProvider) expect(providerManager.metadataForProvider(testProvider)).toBeFalsy() expect(hasDisposable(providerManager.subscriptions, testProvider)).toBe false it 'can identify a provider with a missing getSuggestions', -> bogusProvider = badgetSuggestions: (options) -> selector: '.source.js' dispose: -> expect(providerManager.isValidProvider({}, '2.0.0')).toEqual(false) expect(providerManager.isValidProvider(bogusProvider, '2.0.0')).toEqual(false) expect(providerManager.isValidProvider(testProvider, '2.0.0')).toEqual(true) it 'can identify a provider with an invalid getSuggestions', -> bogusProvider = getSuggestions: 'yo, this is a bad handler' selector: '.source.js' dispose: -> expect(providerManager.isValidProvider({}, '2.0.0')).toEqual(false) expect(providerManager.isValidProvider(bogusProvider, '2.0.0')).toEqual(false) expect(providerManager.isValidProvider(testProvider, '2.0.0')).toEqual(true) it 'can identify a provider with a missing selector', -> bogusProvider = getSuggestions: (options) -> aSelector: '.source.js' dispose: -> expect(providerManager.isValidProvider(bogusProvider, '2.0.0')).toEqual(false) expect(providerManager.isValidProvider(testProvider, '2.0.0')).toEqual(true) it 'can identify a provider with an invalid selector', -> bogusProvider = getSuggestions: (options) -> selector: '' dispose: -> expect(providerManager.isValidProvider(bogusProvider, '2.0.0')).toEqual(false) expect(providerManager.isValidProvider(testProvider, '2.0.0')).toEqual(true) bogusProvider = getSuggestions: (options) -> selector: false dispose: -> expect(providerManager.isValidProvider(bogusProvider, '2.0.0')).toEqual(false) it 'correctly identifies a 1.0 provider', -> bogusProvider = selector: '.source.js' requestHandler: 'yo, this is a bad handler' dispose: -> expect(providerManager.isValidProvider({}, '1.0.0')).toEqual(false) expect(providerManager.isValidProvider(bogusProvider, '1.0.0')).toEqual(false) legitProvider = selector: '.source.js' requestHandler: -> dispose: -> expect(providerManager.isValidProvider(legitProvider, '1.0.0')).toEqual(true) it 'registers a valid provider', -> expect(providerManager.providersForScopeDescriptor('.source.js').length).toEqual(1) expect(providerManager.providersForScopeDescriptor('.source.js').indexOf(testProvider)).toBe(-1) expect(providerManager.metadataForProvider(testProvider)).toBeFalsy() registration = providerManager.registerProvider(testProvider) expect(providerManager.providersForScopeDescriptor('.source.js').length).toEqual(2) expect(providerManager.providersForScopeDescriptor('.source.js').indexOf(testProvider)).not.toBe(-1) expect(providerManager.metadataForProvider(testProvider)).toBeTruthy() it 'removes a registration', -> expect(providerManager.providersForScopeDescriptor('.source.js').length).toEqual(1) expect(providerManager.providersForScopeDescriptor('.source.js').indexOf(testProvider)).toBe(-1) expect(providerManager.metadataForProvider(testProvider)).toBeFalsy() registration = providerManager.registerProvider(testProvider) expect(providerManager.providersForScopeDescriptor('.source.js').length).toEqual(2) expect(providerManager.providersForScopeDescriptor('.source.js').indexOf(testProvider)).not.toBe(-1) expect(providerManager.metadataForProvider(testProvider)).toBeTruthy() registration.dispose() expect(providerManager.providersForScopeDescriptor('.source.js').length).toEqual(1) expect(providerManager.providersForScopeDescriptor('.source.js').indexOf(testProvider)).toBe(-1) expect(providerManager.metadataForProvider(testProvider)).toBeFalsy() it 'does not create duplicate registrations for the same scope', -> expect(providerManager.providersForScopeDescriptor('.source.js').length).toEqual(1) expect(providerManager.providersForScopeDescriptor('.source.js').indexOf(testProvider)).toBe(-1) expect(providerManager.metadataForProvider(testProvider)).toBeFalsy() registration = providerManager.registerProvider(testProvider) expect(providerManager.providersForScopeDescriptor('.source.js').length).toEqual(2) expect(providerManager.providersForScopeDescriptor('.source.js').indexOf(testProvider)).not.toBe(-1) expect(providerManager.metadataForProvider(testProvider)).toBeTruthy() registration = providerManager.registerProvider(testProvider) expect(providerManager.providersForScopeDescriptor('.source.js').length).toEqual(2) expect(providerManager.providersForScopeDescriptor('.source.js').indexOf(testProvider)).not.toBe(-1) expect(providerManager.metadataForProvider(testProvider)).toBeTruthy() registration = providerManager.registerProvider(testProvider) expect(providerManager.providersForScopeDescriptor('.source.js').length).toEqual(2) expect(providerManager.providersForScopeDescriptor('.source.js').indexOf(testProvider)).not.toBe(-1) expect(providerManager.metadataForProvider(testProvider)).toBeTruthy() it 'does not register an invalid provider', -> bogusProvider = getSuggestions: 'yo, this is a bad handler' selector: '.source.js' dispose: -> return expect(providerManager.providersForScopeDescriptor('.source.js').length).toEqual(1) expect(providerManager.providersForScopeDescriptor('.source.js').indexOf(bogusProvider)).toBe(-1) expect(providerManager.metadataForProvider(bogusProvider)).toBeFalsy() registration = providerManager.registerProvider(bogusProvider) expect(providerManager.providersForScopeDescriptor('.source.js').length).toEqual(1) expect(providerManager.providersForScopeDescriptor('.source.js').indexOf(bogusProvider)).toBe(-1) expect(providerManager.metadataForProvider(bogusProvider)).toBeFalsy() it 'registers a provider with a blacklist', -> testProvider = getSuggestions: (options) -> [{ text: 'ohai', replacementPrefix: 'ohai' }] selector: '.source.js' disableForSelector: '.source.js .comment' dispose: -> return expect(providerManager.isValidProvider(testProvider, '2.0.0')).toEqual(true) expect(providerManager.providersForScopeDescriptor('.source.js').length).toEqual(1) expect(providerManager.providersForScopeDescriptor('.source.js').indexOf(testProvider)).toBe(-1) expect(providerManager.metadataForProvider(testProvider)).toBeFalsy() registration = providerManager.registerProvider(testProvider) expect(providerManager.providersForScopeDescriptor('.source.js').length).toEqual(2) expect(providerManager.providersForScopeDescriptor('.source.js').indexOf(testProvider)).not.toBe(-1) expect(providerManager.metadataForProvider(testProvider)).toBeTruthy() describe 'when no providers have been registered, and enableBuiltinProvider is false', -> beforeEach -> atom.config.set('autocomplete-plus.enableBuiltinProvider', false) it 'does not register the default provider for all scopes', -> expect(providerManager.providersForScopeDescriptor('*').length).toBe(0) expect(providerManager.defaultProvider).toEqual(null) expect(providerManager.defaultProviderRegistration).toEqual(null) describe 'when providers have been registered', -> [testProvider1, testProvider2, testProvider3, testProvider4] = [] beforeEach -> atom.config.set('autocomplete-plus.enableBuiltinProvider', true) providerManager = new ProviderManager() testProvider1 = selector: '.source.js' getSuggestions: (options) -> [{ text: 'ohai2', replacementPrefix: 'ohai2' }] dispose: -> testProvider2 = selector: '.source.js .variable.js' disableForSelector: '.source.js .variable.js .comment2' providerblacklist: 'autocomplete-plus-fuzzyprovider': '.source.js .variable.js .comment3' getSuggestions: (options) -> [{ text: 'ohai2', replacementPrefix: 'ohai2' }] dispose: -> testProvider3 = selector: '*' getSuggestions: (options) -> [{ text: 'ohai3', replacementPrefix: 'ohai3' }] dispose: -> testProvider4 = selector: '.source.js .comment' getSuggestions: (options) -> [{ text: 'ohai4', replacementPrefix: 'ohaiPI:KEY:<KEY>END_PI' }] dispose: -> providerManager.registerProvider(testProvider1) providerManager.registerProvider(testProvider2) providerManager.registerProvider(testProvider3) providerManager.registerProvider(testProvider4) it 'returns providers in the correct order for the given scope chain', -> defaultProvider = providerManager.defaultProvider providers = providerManager.providersForScopeDescriptor('.source.other') expect(providers).toHaveLength 2 expect(providers[0]).toEqual testProvider3 expect(providers[1]).toEqual defaultProvider providers = providerManager.providersForScopeDescriptor('.source.js') expect(providers).toHaveLength 3 expect(providers[0]).toEqual testProvider1 expect(providers[1]).toEqual testProvider3 expect(providers[2]).toEqual defaultProvider providers = providerManager.providersForScopeDescriptor('.source.js .comment') expect(providers).toHaveLength 4 expect(providers[0]).toEqual testProvider4 expect(providers[1]).toEqual testProvider1 expect(providers[2]).toEqual testProvider3 expect(providers[3]).toEqual defaultProvider providers = providerManager.providersForScopeDescriptor('.source.js .variable.js') expect(providers).toHaveLength 4 expect(providers[0]).toEqual testProvider2 expect(providers[1]).toEqual testProvider1 expect(providers[2]).toEqual testProvider3 expect(providers[3]).toEqual defaultProvider providers = providerManager.providersForScopeDescriptor('.source.js .other.js') expect(providers).toHaveLength 3 expect(providers[0]).toEqual testProvider1 expect(providers[1]).toEqual testProvider3 expect(providers[2]).toEqual defaultProvider it 'does not return providers if the scopeChain exactly matches a global blacklist item', -> expect(providerManager.providersForScopeDescriptor('.source.js .comment')).toHaveLength 4 atom.config.set('autocomplete-plus.scopeBlacklist', ['.source.js .comment']) expect(providerManager.providersForScopeDescriptor('.source.js .comment')).toHaveLength 0 it 'does not return providers if the scopeChain matches a global blacklist item with a wildcard', -> expect(providerManager.providersForScopeDescriptor('.source.js .comment')).toHaveLength 4 atom.config.set('autocomplete-plus.scopeBlacklist', ['.source.js *']) expect(providerManager.providersForScopeDescriptor('.source.js .comment')).toHaveLength 0 it 'does not return providers if the scopeChain matches a global blacklist item with a wildcard one level of depth below the current scope', -> expect(providerManager.providersForScopeDescriptor('.source.js .comment')).toHaveLength 4 atom.config.set('autocomplete-plus.scopeBlacklist', ['.source.js *']) expect(providerManager.providersForScopeDescriptor('.source.js .comment .other')).toHaveLength 0 it 'does return providers if the scopeChain does not match a global blacklist item with a wildcard', -> expect(providerManager.providersForScopeDescriptor('.source.js .comment')).toHaveLength 4 atom.config.set('autocomplete-plus.scopeBlacklist', ['.source.coffee *']) expect(providerManager.providersForScopeDescriptor('.source.js .comment')).toHaveLength 4 it 'filters a provider if the scopeChain matches a provider blacklist item', -> defaultProvider = providerManager.defaultProvider providers = providerManager.providersForScopeDescriptor('.source.js .variable.js .other.js') expect(providers).toHaveLength 4 expect(providers[0]).toEqual testProvider2 expect(providers[1]).toEqual testProvider1 expect(providers[2]).toEqual testProvider3 expect(providers[3]).toEqual defaultProvider providers = providerManager.providersForScopeDescriptor('.source.js .variable.js .comment2.js') expect(providers).toHaveLength 3 expect(providers[0]).toEqual testProvider1 expect(providers[1]).toEqual testProvider3 expect(providers[2]).toEqual defaultProvider it 'filters a provider if the scopeChain matches a provider providerblacklist item', -> providers = providerManager.providersForScopeDescriptor('.source.js .variable.js .other.js') expect(providers).toHaveLength 4 expect(providers[0]).toEqual(testProvider2) expect(providers[1]).toEqual(testProvider1) expect(providers[2]).toEqual(testProvider3) expect(providers[3]).toEqual(providerManager.defaultProvider) providers = providerManager.providersForScopeDescriptor('.source.js .variable.js .comment3.js') expect(providers).toHaveLength 3 expect(providers[0]).toEqual(testProvider2) expect(providers[1]).toEqual(testProvider1) expect(providers[2]).toEqual(testProvider3) describe "when inclusion priorities are used", -> [accessoryProvider1, accessoryProvider2, verySpecificProvider, mainProvider, defaultProvider] = [] beforeEach -> atom.config.set('autocomplete-plus.enableBuiltinProvider', true) providerManager = new ProviderManager() defaultProvider = providerManager.defaultProvider accessoryProvider1 = selector: '*' inclusionPriority: 2 getSuggestions: (options) -> dispose: -> accessoryProvider2 = selector: '.source.js' inclusionPriority: 2 excludeLowerPriority: false getSuggestions: (options) -> dispose: -> verySpecificProvider = selector: '.source.js .comment' inclusionPriority: 2 excludeLowerPriority: true getSuggestions: (options) -> dispose: -> mainProvider = selector: '.source.js' inclusionPriority: 1 excludeLowerPriority: true getSuggestions: (options) -> dispose: -> providerManager.registerProvider(accessoryProvider1) providerManager.registerProvider(accessoryProvider2) providerManager.registerProvider(verySpecificProvider) providerManager.registerProvider(mainProvider) it 'returns the default provider and higher when nothing with a higher proirity is excluding the lower', -> providers = providerManager.providersForScopeDescriptor('.source.coffee') expect(providers).toHaveLength 2 expect(providers[0]).toEqual accessoryProvider1 expect(providers[1]).toEqual defaultProvider it 'exclude the lower priority provider, the default, when one with a higher proirity excludes the lower', -> providers = providerManager.providersForScopeDescriptor('.source.js') expect(providers).toHaveLength 3 expect(providers[0]).toEqual accessoryProvider2 expect(providers[1]).toEqual mainProvider expect(providers[2]).toEqual accessoryProvider1 it 'excludes the all lower priority providers when multiple providers of lower priority', -> providers = providerManager.providersForScopeDescriptor('.source.js .comment') expect(providers).toHaveLength 3 expect(providers[0]).toEqual verySpecificProvider expect(providers[1]).toEqual accessoryProvider2 expect(providers[2]).toEqual accessoryProvider1 describe "when suggestionPriorities are the same", -> [provider1, provider2, provider3, defaultProvider] = [] beforeEach -> atom.config.set('autocomplete-plus.enableBuiltinProvider', true) providerManager = new ProviderManager() defaultProvider = providerManager.defaultProvider provider1 = selector: '*' suggestionPriority: 2 getSuggestions: (options) -> dispose: -> provider2 = selector: '.source.js' suggestionPriority: 3 getSuggestions: (options) -> dispose: -> provider3 = selector: '.source.js .comment' suggestionPriority: 2 getSuggestions: (options) -> dispose: -> providerManager.registerProvider(provider1) providerManager.registerProvider(provider2) providerManager.registerProvider(provider3) it 'sorts by specificity', -> providers = providerManager.providersForScopeDescriptor('.source.js .comment') expect(providers).toHaveLength 4 expect(providers[0]).toEqual provider2 expect(providers[1]).toEqual provider3 expect(providers[2]).toEqual provider1 hasDisposable = (compositeDisposable, disposable) -> if compositeDisposable?.disposables?.has? compositeDisposable.disposables.has(disposable) else if compositeDisposable?.disposables?.indexOf? compositeDisposable.disposables.indexOf(disposable) > -1 else false
[ { "context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public Li", "end": 43, "score": 0.9999113082885742, "start": 29, "tag": "EMAIL", "value": "contact@ppy.sh" } ]
resources/assets/lib/play-detail.coffee
osu-katakuna/osu-katakuna-web
5
# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0. # See the LICENCE file in the repository root for full licence text. import { Mods } from 'mods' import { PlayDetailMenu } from 'play-detail-menu' import { createElement as el, PureComponent } from 'react' import * as React from 'react' import { a, button, div, i, img, small, span } from 'react-dom-factories' import { ScoreHelper } from 'score-helper' osu = window.osu bn = 'play-detail' export class PlayDetail extends PureComponent constructor: (props) -> super props @state = compact: true render: => score = @props.score blockClass = bn if @props.activated blockClass += " #{bn}--active" else blockClass += " #{bn}--highlightable" blockClass += " #{bn}--compact" if @state.compact div className: blockClass div className: "#{bn}__group #{bn}__group--top", div className: "#{bn}__icon #{bn}__icon--main" div className: "score-rank score-rank--full score-rank--#{score.rank}" div className: "#{bn}__detail", a href: score.beatmap.url className: "#{bn}__title u-ellipsis-overflow" score.beatmapset.title ' ' small className: "#{bn}__artist" osu.trans('users.show.extra.beatmaps.by_artist', artist: score.beatmapset.artist) div className: "#{bn}__beatmap-and-time" span className: "#{bn}__beatmap" score.beatmap.version span className: "#{bn}__time" dangerouslySetInnerHTML: __html: osu.timeago score.created_at button className: "#{bn}__compact-toggle" onClick: @toggleCompact span className: "fas #{if @state.compact then 'fa-chevron-down' else 'fa-chevron-up'}" div className: "#{bn}__group #{bn}__group--bottom", div className: "#{bn}__score-detail #{bn}__score-detail--score", div className: "#{bn}__icon #{bn}__icon--extra" div className: "score-rank score-rank--full score-rank--#{score.rank}" div className: "#{bn}__score-detail-top-right", div className: "#{bn}__accuracy-and-weighted-pp" span className: "#{bn}__accuracy" "#{osu.formatNumber(score.accuracy * 100, 2)}%" if score.weight? span className: "#{bn}__weighted-pp" osu.formatNumber(Math.round(score.weight.pp)) 'pp' if score.weight? div className: "#{bn}__pp-weight" osu.trans 'users.show.extra.top_ranks.pp_weight', percentage: "#{osu.formatNumber(Math.round(score.weight.percentage))}%" div className: "#{bn}__score-detail #{bn}__score-detail--mods" el Mods, mods: score.mods, modifiers: ['profile-page'] div className: "#{bn}__pp" if score.pp > 0 span null, osu.formatNumber(Math.round(score.pp)) span className: "#{bn}__pp-unit", 'pp' else span title: if score.beatmapset.status not in ['ranked', 'approved'] osu.trans('users.show.extra.top_ranks.not_ranked') '-' div className: "#{bn}__more" if ScoreHelper.hasMenu(score) el PlayDetailMenu, { score } toggleCompact: => @setState compact: !@state.compact
123289
# Copyright (c) ppy Pty Ltd <<EMAIL>>. Licensed under the GNU Affero General Public License v3.0. # See the LICENCE file in the repository root for full licence text. import { Mods } from 'mods' import { PlayDetailMenu } from 'play-detail-menu' import { createElement as el, PureComponent } from 'react' import * as React from 'react' import { a, button, div, i, img, small, span } from 'react-dom-factories' import { ScoreHelper } from 'score-helper' osu = window.osu bn = 'play-detail' export class PlayDetail extends PureComponent constructor: (props) -> super props @state = compact: true render: => score = @props.score blockClass = bn if @props.activated blockClass += " #{bn}--active" else blockClass += " #{bn}--highlightable" blockClass += " #{bn}--compact" if @state.compact div className: blockClass div className: "#{bn}__group #{bn}__group--top", div className: "#{bn}__icon #{bn}__icon--main" div className: "score-rank score-rank--full score-rank--#{score.rank}" div className: "#{bn}__detail", a href: score.beatmap.url className: "#{bn}__title u-ellipsis-overflow" score.beatmapset.title ' ' small className: "#{bn}__artist" osu.trans('users.show.extra.beatmaps.by_artist', artist: score.beatmapset.artist) div className: "#{bn}__beatmap-and-time" span className: "#{bn}__beatmap" score.beatmap.version span className: "#{bn}__time" dangerouslySetInnerHTML: __html: osu.timeago score.created_at button className: "#{bn}__compact-toggle" onClick: @toggleCompact span className: "fas #{if @state.compact then 'fa-chevron-down' else 'fa-chevron-up'}" div className: "#{bn}__group #{bn}__group--bottom", div className: "#{bn}__score-detail #{bn}__score-detail--score", div className: "#{bn}__icon #{bn}__icon--extra" div className: "score-rank score-rank--full score-rank--#{score.rank}" div className: "#{bn}__score-detail-top-right", div className: "#{bn}__accuracy-and-weighted-pp" span className: "#{bn}__accuracy" "#{osu.formatNumber(score.accuracy * 100, 2)}%" if score.weight? span className: "#{bn}__weighted-pp" osu.formatNumber(Math.round(score.weight.pp)) 'pp' if score.weight? div className: "#{bn}__pp-weight" osu.trans 'users.show.extra.top_ranks.pp_weight', percentage: "#{osu.formatNumber(Math.round(score.weight.percentage))}%" div className: "#{bn}__score-detail #{bn}__score-detail--mods" el Mods, mods: score.mods, modifiers: ['profile-page'] div className: "#{bn}__pp" if score.pp > 0 span null, osu.formatNumber(Math.round(score.pp)) span className: "#{bn}__pp-unit", 'pp' else span title: if score.beatmapset.status not in ['ranked', 'approved'] osu.trans('users.show.extra.top_ranks.not_ranked') '-' div className: "#{bn}__more" if ScoreHelper.hasMenu(score) el PlayDetailMenu, { score } toggleCompact: => @setState compact: !@state.compact
true
# Copyright (c) ppy Pty Ltd <PI:EMAIL:<EMAIL>END_PI>. Licensed under the GNU Affero General Public License v3.0. # See the LICENCE file in the repository root for full licence text. import { Mods } from 'mods' import { PlayDetailMenu } from 'play-detail-menu' import { createElement as el, PureComponent } from 'react' import * as React from 'react' import { a, button, div, i, img, small, span } from 'react-dom-factories' import { ScoreHelper } from 'score-helper' osu = window.osu bn = 'play-detail' export class PlayDetail extends PureComponent constructor: (props) -> super props @state = compact: true render: => score = @props.score blockClass = bn if @props.activated blockClass += " #{bn}--active" else blockClass += " #{bn}--highlightable" blockClass += " #{bn}--compact" if @state.compact div className: blockClass div className: "#{bn}__group #{bn}__group--top", div className: "#{bn}__icon #{bn}__icon--main" div className: "score-rank score-rank--full score-rank--#{score.rank}" div className: "#{bn}__detail", a href: score.beatmap.url className: "#{bn}__title u-ellipsis-overflow" score.beatmapset.title ' ' small className: "#{bn}__artist" osu.trans('users.show.extra.beatmaps.by_artist', artist: score.beatmapset.artist) div className: "#{bn}__beatmap-and-time" span className: "#{bn}__beatmap" score.beatmap.version span className: "#{bn}__time" dangerouslySetInnerHTML: __html: osu.timeago score.created_at button className: "#{bn}__compact-toggle" onClick: @toggleCompact span className: "fas #{if @state.compact then 'fa-chevron-down' else 'fa-chevron-up'}" div className: "#{bn}__group #{bn}__group--bottom", div className: "#{bn}__score-detail #{bn}__score-detail--score", div className: "#{bn}__icon #{bn}__icon--extra" div className: "score-rank score-rank--full score-rank--#{score.rank}" div className: "#{bn}__score-detail-top-right", div className: "#{bn}__accuracy-and-weighted-pp" span className: "#{bn}__accuracy" "#{osu.formatNumber(score.accuracy * 100, 2)}%" if score.weight? span className: "#{bn}__weighted-pp" osu.formatNumber(Math.round(score.weight.pp)) 'pp' if score.weight? div className: "#{bn}__pp-weight" osu.trans 'users.show.extra.top_ranks.pp_weight', percentage: "#{osu.formatNumber(Math.round(score.weight.percentage))}%" div className: "#{bn}__score-detail #{bn}__score-detail--mods" el Mods, mods: score.mods, modifiers: ['profile-page'] div className: "#{bn}__pp" if score.pp > 0 span null, osu.formatNumber(Math.round(score.pp)) span className: "#{bn}__pp-unit", 'pp' else span title: if score.beatmapset.status not in ['ranked', 'approved'] osu.trans('users.show.extra.top_ranks.not_ranked') '-' div className: "#{bn}__more" if ScoreHelper.hasMenu(score) el PlayDetailMenu, { score } toggleCompact: => @setState compact: !@state.compact
[ { "context": "\tappId: app.appId\n\t\t\t\tcommit: app.commit\n\t\t\t\tname: app.name\n\t\t\t\tsource: app.source\n\t\t\t\treleaseId: app.re", "end": 25868, "score": 0.794816792011261, "start": 25865, "tag": "NAME", "value": "app" }, { "context": "ants.supervisorNetworkInterface)\n\t\...
src/application-manager.coffee
hippolyt/resin-supervisor
0
Promise = require 'bluebird' _ = require 'lodash' EventEmitter = require 'events' express = require 'express' bodyParser = require 'body-parser' fs = Promise.promisifyAll(require('fs')) path = require 'path' constants = require './lib/constants' Docker = require './lib/docker-utils' updateLock = require './lib/update-lock' { checkTruthy, checkInt, checkString } = require './lib/validation' { NotFoundError } = require './lib/errors' ServiceManager = require './compose/service-manager' { Service } = require './compose/service' Images = require './compose/images' { NetworkManager } = require './compose/network-manager' { Network } = require './compose/network' Volumes = require './compose/volumes' Proxyvisor = require './proxyvisor' { createV1Api } = require './device-api/v1' { createV2Api } = require './device-api/v2' { serviceAction } = require './device-api/common' # TODO: move this to an Image class? imageForService = (service) -> return { name: service.imageName appId: service.appId serviceId: service.serviceId serviceName: service.serviceName imageId: service.imageId releaseId: service.releaseId dependent: 0 } fetchAction = (service) -> return { action: 'fetch' image: imageForService(service) serviceId: service.serviceId } pathExistsOnHost = (p) -> fs.statAsync(path.join(constants.rootMountPoint, p)) .return(true) .catchReturn(false) # TODO: implement additional v2 endpoints # Some v1 endpoins only work for single-container apps as they assume the app has a single service. createApplicationManagerRouter = (applications) -> router = express.Router() router.use(bodyParser.urlencoded(extended: true)) router.use(bodyParser.json()) createV1Api(router, applications) createV2Api(router, applications) router.use(applications.proxyvisor.router) return router module.exports = class ApplicationManager extends EventEmitter constructor: ({ @logger, @config, @db, @eventTracker, @deviceState }) -> @docker = new Docker() @images = new Images({ @docker, @logger, @db }) @services = new ServiceManager({ @docker, @logger, @images, @config }) @networks = new NetworkManager({ @docker, @logger }) @volumes = new Volumes({ @docker, @logger }) @proxyvisor = new Proxyvisor({ @config, @logger, @db, @docker, @images, applications: this }) @timeSpentFetching = 0 @fetchesInProgress = 0 @_targetVolatilePerImageId = {} @_containerStarted = {} @actionExecutors = { stop: (step, { force = false, skipLock = false } = {}) => @_lockingIfNecessary step.current.appId, { force, skipLock: skipLock or step.options?.skipLock }, => wait = step.options?.wait ? false @services.kill(step.current, { removeContainer: false, wait }) .then => delete @_containerStarted[step.current.containerId] kill: (step, { force = false, skipLock = false } = {}) => @_lockingIfNecessary step.current.appId, { force, skipLock: skipLock or step.options?.skipLock }, => @services.kill(step.current) .then => delete @_containerStarted[step.current.containerId] if step.options?.removeImage @images.removeByDockerId(step.current.config.image) remove: (step) => # Only called for dead containers, so no need to take locks or anything @services.remove(step.current) updateMetadata: (step, { force = false, skipLock = false } = {}) => skipLock or= checkTruthy(step.current.config.labels['io.resin.legacy-container']) @_lockingIfNecessary step.current.appId, { force, skipLock: skipLock or step.options?.skipLock }, => @services.updateMetadata(step.current, step.target) restart: (step, { force = false, skipLock = false } = {}) => @_lockingIfNecessary step.current.appId, { force, skipLock: skipLock or step.options?.skipLock }, => @services.kill(step.current, { wait: true }) .then => delete @_containerStarted[step.current.containerId] .then => @services.start(step.target) .then (container) => @_containerStarted[container.id] = true stopAll: (step, { force = false, skipLock = false } = {}) => @stopAll({ force, skipLock }) start: (step) => @services.start(step.target) .then (container) => @_containerStarted[container.id] = true updateCommit: (step) => @config.set({ currentCommit: step.target }) handover: (step, { force = false, skipLock = false } = {}) => @_lockingIfNecessary step.current.appId, { force, skipLock: skipLock or step.options?.skipLock }, => @services.handover(step.current, step.target) fetch: (step) => startTime = process.hrtime() @fetchesInProgress += 1 Promise.join( @config.get('fetchOptions') @images.getAvailable() (opts, availableImages) => opts.deltaSource = @bestDeltaSource(step.image, availableImages) @images.triggerFetch step.image, opts, (success) => @fetchesInProgress -= 1 elapsed = process.hrtime(startTime) elapsedMs = elapsed[0] * 1000 + elapsed[1] / 1e6 @timeSpentFetching += elapsedMs if success # update_downloaded is true if *any* image has been downloaded, # and it's relevant mostly for the legacy GET /v1/device endpoint # that assumes a single-container app @reportCurrentState(update_downloaded: true) ) removeImage: (step) => @images.remove(step.image) saveImage: (step) => @images.save(step.image) cleanup: (step) => @images.cleanup() createNetworkOrVolume: (step) => if step.model is 'network' # TODO: These step targets should be the actual compose objects, # rather than recreating them Network.fromComposeObject({ @docker, @logger }, step.target.name, step.appId, step.target.config ).create() else @volumes.create(step.target) removeNetworkOrVolume: (step) => if step.model is 'network' Network.fromComposeObject({ @docker, @logger }, step.current.name, step.appId, step.current.config ).remove() else @volumes.remove(step.current) ensureSupervisorNetwork: => @networks.ensureSupervisorNetwork() } @validActions = _.keys(@actionExecutors).concat(@proxyvisor.validActions) @router = createApplicationManagerRouter(this) @images.on('change', @reportCurrentState) @services.on('change', @reportCurrentState) serviceAction: serviceAction imageForService: imageForService fetchAction: fetchAction reportCurrentState: (data) => @emit('change', data) init: => @images.cleanupDatabase() .then => @services.attachToRunning() .then => @services.listenToEvents() # Returns the status of applications and their services getStatus: => Promise.join( @services.getStatus() @images.getStatus() @config.get('currentCommit') @db.models('app').select([ 'appId', 'releaseId', 'commit' ]) (services, images, currentCommit, targetApps) -> apps = {} dependent = {} releaseId = null creationTimesAndReleases = {} # We iterate over the current running services and add them to the current state # of the app they belong to. for service in services appId = service.appId apps[appId] ?= {} creationTimesAndReleases[appId] = {} apps[appId].services ?= {} # We only send commit if all services have the same release, and it matches the target release if !releaseId? releaseId = service.releaseId else if releaseId != service.releaseId releaseId = false if !apps[appId].services[service.imageId]? apps[appId].services[service.imageId] = _.pick(service, [ 'status', 'releaseId' ]) creationTimesAndReleases[appId][service.imageId] = _.pick(service, [ 'createdAt', 'releaseId' ]) apps[appId].services[service.imageId].download_progress = null else # There's two containers with the same imageId, so this has to be a handover apps[appId].services[service.imageId].releaseId = _.minBy([ creationTimesAndReleases[appId][service.imageId], service ], 'createdAt').releaseId apps[appId].services[service.imageId].status = 'Handing over' for image in images appId = image.appId if !image.dependent apps[appId] ?= {} apps[appId].services ?= {} if !apps[appId].services[image.imageId]? apps[appId].services[image.imageId] = _.pick(image, [ 'status', 'releaseId' ]) apps[appId].services[image.imageId].download_progress = image.downloadProgress else if image.imageId? dependent[appId] ?= {} dependent[appId].images ?= {} dependent[appId].images[image.imageId] = _.pick(image, [ 'status' ]) dependent[appId].images[image.imageId].download_progress = image.downloadProgress else console.log('Ignoring legacy dependent image', image) obj = { local: apps, dependent } obj.commit = currentCommit return obj ) getDependentState: => @proxyvisor.getCurrentStates() _buildApps: (services, networks, volumes, currentCommit) -> apps = {} # We iterate over the current running services and add them to the current state # of the app they belong to. for service in services appId = service.appId apps[appId] ?= { appId, services: [], volumes: {}, networks: {} } apps[appId].services.push(service) for network in networks appId = network.appId apps[appId] ?= { appId, services: [], volumes: {}, networks: {} } apps[appId].networks[network.name] = network.config for volume in volumes appId = volume.appId apps[appId] ?= { appId, services: [], volumes: {}, networks: {} } apps[appId].volumes[volume.name] = volume.config # multi-app warning! # This is just wrong on every level _.each apps, (app) -> app.commit = currentCommit return apps getCurrentForComparison: => Promise.join( @services.getAll() @networks.getAll() @volumes.getAll() @config.get('currentCommit') @_buildApps ) getCurrentApp: (appId) => Promise.join( @services.getAllByAppId(appId) @networks.getAllByAppId(appId) @volumes.getAllByAppId(appId) @config.get('currentCommit') @_buildApps ).get(appId) getTargetApp: (appId) => @config.get('apiEndpoint').then (endpoint = '') -> @db.models('app').where({ appId, source: endpoint }).select() .then ([ app ]) => if !app? return @normaliseAndExtendAppFromDB(app) # Compares current and target services and returns a list of service pairs to be updated/removed/installed. # The returned list is an array of objects where the "current" and "target" properties define the update pair, and either can be null # (in the case of an install or removal). compareServicesForUpdate: (currentServices, targetServices) => removePairs = [] installPairs = [] updatePairs = [] targetServiceIds = _.map(targetServices, 'serviceId') currentServiceIds = _.uniq(_.map(currentServices, 'serviceId')) toBeRemoved = _.difference(currentServiceIds, targetServiceIds) for serviceId in toBeRemoved servicesToRemove = _.filter(currentServices, { serviceId }) for service in servicesToRemove removePairs.push({ current: service target: null serviceId }) toBeInstalled = _.difference(targetServiceIds, currentServiceIds) for serviceId in toBeInstalled serviceToInstall = _.find(targetServices, { serviceId }) if serviceToInstall? installPairs.push({ current: null target: serviceToInstall serviceId }) toBeMaybeUpdated = _.intersection(targetServiceIds, currentServiceIds) currentServicesPerId = {} targetServicesPerId = _.keyBy(targetServices, 'serviceId') for serviceId in toBeMaybeUpdated currentServiceContainers = _.filter(currentServices, { serviceId }) if currentServiceContainers.length > 1 currentServicesPerId[serviceId] = _.maxBy(currentServiceContainers, 'createdAt') # All but the latest container for this service are spurious and should be removed for service in _.without(currentServiceContainers, currentServicesPerId[serviceId]) removePairs.push({ current: service target: null serviceId }) else currentServicesPerId[serviceId] = currentServiceContainers[0] # Returns true if a service matches its target except it should be running and it is not, but we've # already started it before. In this case it means it just exited so we don't want to start it again. alreadyStarted = (serviceId) => return ( currentServicesPerId[serviceId].isEqualExceptForRunningState(targetServicesPerId[serviceId]) and targetServicesPerId[serviceId].config.running and @_containerStarted[currentServicesPerId[serviceId].containerId] ) needUpdate = _.filter toBeMaybeUpdated, (serviceId) -> !currentServicesPerId[serviceId].isEqual(targetServicesPerId[serviceId]) and !alreadyStarted(serviceId) for serviceId in needUpdate updatePairs.push({ current: currentServicesPerId[serviceId] target: targetServicesPerId[serviceId] serviceId }) return { removePairs, installPairs, updatePairs } _compareNetworksOrVolumesForUpdate: (model, { current, target }, appId) -> outputPairs = [] currentNames = _.keys(current) targetNames = _.keys(target) toBeRemoved = _.difference(currentNames, targetNames) for name in toBeRemoved outputPairs.push({ current: { name appId config: current[name] } target: null }) toBeInstalled = _.difference(targetNames, currentNames) for name in toBeInstalled outputPairs.push({ current: null target: { name appId config: target[name] } }) toBeUpdated = _.filter _.intersection(targetNames, currentNames), (name) => # While we're in this in-between state of a network-manager, but not # a volume-manager, we'll have to inspect the object to detect a # network-manager if model instanceof NetworkManager opts = docker: @docker, logger: @logger currentNet = Network.fromComposeObject( opts, name, appId, current[name] ) targetNet = Network.fromComposeObject( opts, name, appId, target[name] ) return !currentNet.isEqualConfig(targetNet) else return !model.isEqualConfig(current[name], target[name]) for name in toBeUpdated outputPairs.push({ current: { name appId config: current[name] } target: { name appId config: target[name] } }) return outputPairs compareNetworksForUpdate: ({ current, target }, appId) => @_compareNetworksOrVolumesForUpdate(@networks, { current, target }, appId) compareVolumesForUpdate: ({ current, target }, appId) => @_compareNetworksOrVolumesForUpdate(@volumes, { current, target }, appId) # Checks if a service is using a network or volume that is about to be updated _hasCurrentNetworksOrVolumes: (service, networkPairs, volumePairs) -> if !service? return false hasNetwork = _.some networkPairs, (pair) -> "#{service.appId}_#{pair.current?.name}" == service.networkMode if hasNetwork return true hasVolume = _.some service.volumes, (volume) -> name = _.split(volume, ':')[0] _.some volumePairs, (pair) -> "#{service.appId}_#{pair.current?.name}" == name return hasVolume # TODO: account for volumes-from, networks-from, links, etc # TODO: support networks instead of only networkMode _dependenciesMetForServiceStart: (target, networkPairs, volumePairs, pendingPairs) -> # for dependsOn, check no install or update pairs have that service dependencyUnmet = _.some target.dependsOn, (dependency) -> _.some(pendingPairs, (pair) -> pair.target?.serviceName == dependency) if dependencyUnmet return false # for networks and volumes, check no network pairs have that volume name if _.some(networkPairs, (pair) -> "#{target.appId}_#{pair.target?.name}" == target.networkMode) return false volumeUnmet = _.some target.volumes, (volumeDefinition) -> [ sourceName, destName ] = volumeDefinition.split(':') if !destName? # If this is not a named volume, ignore it return false return _.some(volumePairs, (pair) -> "#{target.appId}_#{pair.target?.name}" == sourceName) return !volumeUnmet # Unless the update strategy requires an early kill (i.e. kill-then-download, delete-then-download), we only want # to kill a service once the images for the services it depends on have been downloaded, so as to minimize # downtime (but not block the killing too much, potentially causing a deadlock) _dependenciesMetForServiceKill: (target, targetApp, availableImages) => if target.dependsOn? for dependency in target.dependsOn dependencyService = _.find(targetApp.services, serviceName: dependency) if !_.some(availableImages, (image) => image.dockerImageId == dependencyService.image or @images.isSameImage(image, { name: dependencyService.imageName })) return false return true _nextStepsForNetworkOrVolume: ({ current, target }, currentApp, changingPairs, dependencyComparisonFn, model) -> # Check none of the currentApp.services use this network or volume if current? dependencies = _.filter currentApp.services, (service) -> dependencyComparisonFn(service, current) if _.isEmpty(dependencies) return [{ action: 'removeNetworkOrVolume', model, current }] else # If the current update doesn't require killing the services that use this network/volume, # we have to kill them before removing the network/volume (e.g. when we're only updating the network config) steps = [] for dependency in dependencies if dependency.status != 'Stopping' and !_.some(changingPairs, serviceId: dependency.serviceId) steps.push(serviceAction('kill', dependency.serviceId, dependency)) return steps else if target? return [{ action: 'createNetworkOrVolume', model, target }] _nextStepsForNetwork: ({ current, target }, currentApp, changingPairs) => dependencyComparisonFn = (service, current) -> service.config.networkMode == "#{service.appId}_#{current?.name}" @_nextStepsForNetworkOrVolume({ current, target }, currentApp, changingPairs, dependencyComparisonFn, 'network') _nextStepsForVolume: ({ current, target }, currentApp, changingPairs) -> # Check none of the currentApp.services use this network or volume dependencyComparisonFn = (service, current) -> _.some service.config.volumes, (volumeDefinition) -> [ sourceName, destName ] = volumeDefinition.split(':') destName? and sourceName == "#{service.appId}_#{current?.name}" @_nextStepsForNetworkOrVolume({ current, target }, currentApp, changingPairs, dependencyComparisonFn, 'volume') # Infers steps that do not require creating a new container _updateContainerStep: (current, target) -> if current.releaseId != target.releaseId or current.imageId != target.imageId return serviceAction('updateMetadata', target.serviceId, current, target) else if target.config.running return serviceAction('start', target.serviceId, current, target) else return serviceAction('stop', target.serviceId, current, target) _fetchOrStartStep: (current, target, needsDownload, dependenciesMetForStart) -> if needsDownload return fetchAction(target) else if dependenciesMetForStart() return serviceAction('start', target.serviceId, current, target) else return null _strategySteps: { 'download-then-kill': (current, target, needsDownload, dependenciesMetForStart, dependenciesMetForKill) -> if needsDownload return fetchAction(target) else if dependenciesMetForKill() # We only kill when dependencies are already met, so that we minimize downtime return serviceAction('kill', target.serviceId, current, target) else return null 'kill-then-download': (current, target) -> return serviceAction('kill', target.serviceId, current, target) 'delete-then-download': (current, target, needsDownload) -> return serviceAction('kill', target.serviceId, current, target, removeImage: needsDownload) 'hand-over': (current, target, needsDownload, dependenciesMetForStart, dependenciesMetForKill, needsSpecialKill, timeout) -> if needsDownload return fetchAction(target) else if needsSpecialKill and dependenciesMetForKill() return serviceAction('kill', target.serviceId, current, target) else if dependenciesMetForStart() return serviceAction('handover', target.serviceId, current, target, timeout: timeout) else return null } _nextStepForService: ({ current, target }, updateContext) => { targetApp, networkPairs, volumePairs, installPairs, updatePairs, availableImages, downloading } = updateContext if current?.status == 'Stopping' # There is already a kill step in progress for this service, so we wait return { action: 'noop' } if current?.status == 'Dead' # Dead containers have to be removed return serviceAction('remove', current.serviceId, current) needsDownload = !_.some availableImages, (image) => image.dockerImageId == target?.config.image or @images.isSameImage(image, { name: target.imageName }) # This service needs an image download but it's currently downloading, so we wait if needsDownload and target?.imageId in downloading return { action: 'noop' } dependenciesMetForStart = => @_dependenciesMetForServiceStart(target, networkPairs, volumePairs, installPairs.concat(updatePairs)) dependenciesMetForKill = => !needsDownload and @_dependenciesMetForServiceKill(target, targetApp, availableImages) # If the service is using a network or volume that is being updated, we need to kill it # even if its strategy is handover needsSpecialKill = @_hasCurrentNetworksOrVolumes(current, networkPairs, volumePairs) if current?.isEqualConfig(target) # We're only stopping/starting it return @_updateContainerStep(current, target) else if !current? # Either this is a new service, or the current one has already been killed return @_fetchOrStartStep(current, target, needsDownload, dependenciesMetForStart) else strategy = checkString(target.config.labels['io.resin.update.strategy']) validStrategies = [ 'download-then-kill', 'kill-then-download', 'delete-then-download', 'hand-over' ] if !_.includes(validStrategies, strategy) strategy = 'download-then-kill' timeout = checkInt(target.config.labels['io.resin.update.handover-timeout']) return @_strategySteps[strategy](current, target, needsDownload, dependenciesMetForStart, dependenciesMetForKill, needsSpecialKill, timeout) _nextStepsForAppUpdate: (currentApp, targetApp, availableImages = [], downloading = []) => emptyApp = { services: [], volumes: {}, networks: {} } if !targetApp? targetApp = emptyApp else # Create the default network for the target app targetApp.networks['default'] ?= {} currentApp ?= emptyApp if currentApp.services?.length == 1 and targetApp.services?.length == 1 and targetApp.services[0].serviceName == currentApp.services[0].serviceName and checkTruthy(currentApp.services[0].config.labels['io.resin.legacy-container']) # This is a legacy preloaded app or container, so we didn't have things like serviceId. # We hack a few things to avoid an unnecessary restart of the preloaded app # (but ensuring it gets updated if it actually changed) targetApp.services[0].config.labels['io.resin.legacy-container'] = currentApp.services[0].labels['io.resin.legacy-container'] targetApp.services[0].config.labels['io.resin.service-id'] = currentApp.services[0].labels['io.resin.service-id'] targetApp.services[0].serviceId = currentApp.services[0].serviceId appId = targetApp.appId ? currentApp.appId networkPairs = @compareNetworksForUpdate({ current: currentApp.networks, target: targetApp.networks }, appId) volumePairs = @compareVolumesForUpdate({ current: currentApp.volumes, target: targetApp.volumes }, appId) { removePairs, installPairs, updatePairs } = @compareServicesForUpdate(currentApp.services, targetApp.services) steps = [] # All removePairs get a 'kill' action for pair in removePairs if pair.current.status != 'Stopping' steps.push(serviceAction('kill', pair.current.serviceId, pair.current, null)) else steps.push({ action: 'noop' }) # next step for install pairs in download - start order, but start requires dependencies, networks and volumes met # next step for update pairs in order by update strategy. start requires dependencies, networks and volumes met. for pair in installPairs.concat(updatePairs) step = @_nextStepForService(pair, { targetApp, networkPairs, volumePairs, installPairs, updatePairs, availableImages, downloading }) if step? steps.push(step) # next step for network pairs - remove requires services killed, create kill if no pairs or steps affect that service for pair in networkPairs pairSteps = @_nextStepsForNetwork(pair, currentApp, removePairs.concat(updatePairs)) steps = steps.concat(pairSteps) # next step for volume pairs - remove requires services killed, create kill if no pairs or steps affect that service for pair in volumePairs pairSteps = @_nextStepsForVolume(pair, currentApp, removePairs.concat(updatePairs)) steps = steps.concat(pairSteps) if _.isEmpty(steps) and currentApp.commit != targetApp.commit steps.push({ action: 'updateCommit' target: targetApp.commit }) return _.map(steps, (step) -> _.assign({}, step, { appId })) normaliseAppForDB: (app) => services = _.map app.services, (s, serviceId) -> service = _.clone(s) service.appId = app.appId service.releaseId = app.releaseId service.serviceId = checkInt(serviceId) service.commit = app.commit return service Promise.map services, (service) => service.image = @images.normalise(service.image) Promise.props(service) .then (services) -> dbApp = { appId: app.appId commit: app.commit name: app.name source: app.source releaseId: app.releaseId services: JSON.stringify(services) networks: JSON.stringify(app.networks ? {}) volumes: JSON.stringify(app.volumes ? {}) } return dbApp createTargetService: (service, opts) -> @images.inspectByName(service.image) .catchReturn(NotFoundError, undefined) .then (imageInfo) -> serviceOpts = { serviceName: service.serviceName imageInfo } _.assign(serviceOpts, opts) service.imageName = service.image if imageInfo?.Id? service.image = imageInfo.Id return Service.fromComposeObject(service, serviceOpts) normaliseAndExtendAppFromDB: (app) => Promise.join( @config.get('extendedEnvOptions') @docker.getNetworkGateway(constants.supervisorNetworkInterface) .catchReturn('127.0.0.1') Promise.props({ firmware: pathExistsOnHost('/lib/firmware') modules: pathExistsOnHost('/lib/modules') }) fs.readFileAsync(path.join(constants.rootMountPoint, '/etc/hostname'), 'utf8').then(_.trim) (opts, supervisorApiHost, hostPathExists, hostnameOnHost) => configOpts = { appName: app.name supervisorApiHost hostPathExists hostnameOnHost } _.assign(configOpts, opts) volumes = JSON.parse(app.volumes) volumes = _.mapValues volumes, (volumeConfig) -> volumeConfig ?= {} volumeConfig.labels ?= {} return volumeConfig Promise.map(JSON.parse(app.services), (service) => @createTargetService(service, configOpts)) .then (services) -> # If a named volume is defined in a service, we add it app-wide so that we can track it and purge it for s in services serviceNamedVolumes = s.getNamedVolumes() for name in serviceNamedVolumes volumes[name] ?= { labels: {} } outApp = { appId: app.appId name: app.name commit: app.commit releaseId: app.releaseId services: services networks: JSON.parse(app.networks) volumes: volumes } return outApp ) setTarget: (apps, dependent , source, trx) => setInTransaction = (trx) => Promise.try => appsArray = _.map apps, (app, appId) -> appClone = _.clone(app) appClone.appId = checkInt(appId) appClone.source = source return appClone Promise.map(appsArray, @normaliseAppForDB) .tap (appsForDB) => Promise.map appsForDB, (app) => @db.upsertModel('app', app, { appId: app.appId }, trx) .then (appsForDB) -> trx('app').whereNotIn('appId', _.map(appsForDB, 'appId')).del() .then => @proxyvisor.setTargetInTransaction(dependent, trx) Promise.try => if trx? setInTransaction(trx) else @db.transaction(setInTransaction) .then => @_targetVolatilePerImageId = {} setTargetVolatileForService: (imageId, target) => @_targetVolatilePerImageId[imageId] ?= {} _.assign(@_targetVolatilePerImageId[imageId], target) clearTargetVolatileForServices: (imageIds) => for imageId in imageIds @_targetVolatilePerImageId[imageId] = {} getTargetApps: => @config.get('apiEndpoint'). then (source = '') => Promise.map(@db.models('app').where({ source }), @normaliseAndExtendAppFromDB) .map (app) => if !_.isEmpty(app.services) app.services = _.map app.services, (service) => if @_targetVolatilePerImageId[service.imageId]? _.merge(service, @_targetVolatilePerImageId[service.imageId]) return service return app .then (apps) -> return _.keyBy(apps, 'appId') getDependentTargets: => @proxyvisor.getTarget() bestDeltaSource: (image, available) -> if !image.dependent for availableImage in available if availableImage.serviceName == image.serviceName and availableImage.appId == image.appId return availableImage.name for availableImage in available if availableImage.serviceName == image.serviceName return availableImage.name for availableImage in available if availableImage.appId == image.appId return availableImage.name return 'resin/scratch' # returns: # imagesToRemove: images that # - are not used in the current state, and # - are not going to be used in the target state, and # - are not needed for delta source / pull caching or would be used for a service with delete-then-download as strategy # imagesToSave: images that # - are locally available (i.e. an image with the same digest exists) # - are not saved to the DB with all their metadata (serviceId, serviceName, etc) _compareImages: (current, target, available) => allImagesForTargetApp = (app) -> _.map(app.services, imageForService) allImagesForCurrentApp = (app) -> _.map app.services, (service) -> img = _.find(available, { dockerImageId: service.config.image, imageId: service.imageId }) ? _.find(available, { dockerImageId: service.config.image }) return _.omit(img, [ 'dockerImageId', 'id' ]) availableWithoutIds = _.map(available, (image) -> _.omit(image, [ 'dockerImageId', 'id' ])) currentImages = _.flatMap(current.local.apps, allImagesForCurrentApp) targetImages = _.flatMap(target.local.apps, allImagesForTargetApp) availableAndUnused = _.filter availableWithoutIds, (image) -> !_.some currentImages.concat(targetImages), (imageInUse) -> _.isEqual(image, imageInUse) imagesToDownload = _.filter targetImages, (targetImage) => !_.some available, (availableImage) => @images.isSameImage(availableImage, targetImage) # Images that are available but we don't have them in the DB with the exact metadata: imagesToSave = _.filter targetImages, (targetImage) => _.some(available, (availableImage) => @images.isSameImage(availableImage, targetImage)) and !_.some(availableWithoutIds, (img) -> _.isEqual(img, targetImage)) deltaSources = _.map imagesToDownload, (image) => return @bestDeltaSource(image, available) proxyvisorImages = @proxyvisor.imagesInUse(current, target) imagesToRemove = _.filter availableAndUnused, (image) => notUsedForDelta = !_.includes(deltaSources, image.name) notUsedByProxyvisor = !_.some proxyvisorImages, (proxyvisorImage) => @images.isSameImage(image, { name: proxyvisorImage }) return notUsedForDelta and notUsedByProxyvisor return { imagesToSave, imagesToRemove } _inferNextSteps: (cleanupNeeded, availableImages, downloading, supervisorNetworkReady, current, target, ignoreImages, { localMode, delta }) => Promise.try => delta = checkTruthy(delta) if checkTruthy(localMode) target = _.cloneDeep(target) target.local.apps = _.mapValues target.local.apps, (app) -> app.services = [] return app ignoreImages = true currentByAppId = current.local.apps ? {} targetByAppId = target.local.apps ? {} nextSteps = [] if !supervisorNetworkReady nextSteps.push({ action: 'ensureSupervisorNetwork' }) else if !ignoreImages and _.isEmpty(downloading) if cleanupNeeded nextSteps.push({ action: 'cleanup' }) { imagesToRemove, imagesToSave } = @_compareImages(current, target, availableImages) for image in imagesToSave nextSteps.push({ action: 'saveImage', image }) if _.isEmpty(imagesToSave) for image in imagesToRemove nextSteps.push({ action: 'removeImage', image }) # If we have to remove any images, we do that before anything else if _.isEmpty(nextSteps) allAppIds = _.union(_.keys(currentByAppId), _.keys(targetByAppId)) for appId in allAppIds nextSteps = nextSteps.concat(@_nextStepsForAppUpdate(currentByAppId[appId], targetByAppId[appId], availableImages, downloading)) newDownloads = _.filter(nextSteps, (s) -> s.action == 'fetch').length if !ignoreImages and delta and newDownloads > 0 downloadsToBlock = downloading.length + newDownloads - constants.maxDeltaDownloads while downloadsToBlock > 0 _.pull(nextSteps, _.find(nextSteps, action: 'fetch')) downloadsToBlock -= 1 if !ignoreImages and _.isEmpty(nextSteps) and !_.isEmpty(downloading) nextSteps.push({ action: 'noop' }) return _.uniqWith(nextSteps, _.isEqual) stopAll: ({ force = false, skipLock = false } = {}) => @services.getAll() .map (service) => @_lockingIfNecessary service.appId, { force, skipLock }, => @services.kill(service, { removeContainer: false, wait: true }) .then => delete @_containerStarted[service.containerId] _lockingIfNecessary: (appId, { force = false, skipLock = false } = {}, fn) => if skipLock return Promise.try(fn) @config.get('lockOverride') .then (lockOverride) -> return checkTruthy(lockOverride) or force .then (force) -> updateLock.lock(appId, { force }, fn) executeStepAction: (step, { force = false, skipLock = false } = {}) => if _.includes(@proxyvisor.validActions, step.action) return @proxyvisor.executeStepAction(step) if !_.includes(@validActions, step.action) return Promise.reject(new Error("Invalid action #{step.action}")) @actionExecutors[step.action](step, { force, skipLock }) getRequiredSteps: (currentState, targetState, ignoreImages = false) => Promise.join( @images.isCleanupNeeded() @images.getAvailable() @images.getDownloadingImageIds() @networks.supervisorNetworkReady() @config.getMany([ 'localMode', 'delta' ]) (cleanupNeeded, availableImages, downloading, supervisorNetworkReady, conf) => @_inferNextSteps(cleanupNeeded, availableImages, downloading, supervisorNetworkReady, currentState, targetState, ignoreImages, conf) .then (nextSteps) => if ignoreImages and _.some(nextSteps, action: 'fetch') throw new Error('Cannot fetch images while executing an API action') @proxyvisor.getRequiredSteps(availableImages, downloading, currentState, targetState, nextSteps) .then (proxyvisorSteps) -> return nextSteps.concat(proxyvisorSteps) )
73321
Promise = require 'bluebird' _ = require 'lodash' EventEmitter = require 'events' express = require 'express' bodyParser = require 'body-parser' fs = Promise.promisifyAll(require('fs')) path = require 'path' constants = require './lib/constants' Docker = require './lib/docker-utils' updateLock = require './lib/update-lock' { checkTruthy, checkInt, checkString } = require './lib/validation' { NotFoundError } = require './lib/errors' ServiceManager = require './compose/service-manager' { Service } = require './compose/service' Images = require './compose/images' { NetworkManager } = require './compose/network-manager' { Network } = require './compose/network' Volumes = require './compose/volumes' Proxyvisor = require './proxyvisor' { createV1Api } = require './device-api/v1' { createV2Api } = require './device-api/v2' { serviceAction } = require './device-api/common' # TODO: move this to an Image class? imageForService = (service) -> return { name: service.imageName appId: service.appId serviceId: service.serviceId serviceName: service.serviceName imageId: service.imageId releaseId: service.releaseId dependent: 0 } fetchAction = (service) -> return { action: 'fetch' image: imageForService(service) serviceId: service.serviceId } pathExistsOnHost = (p) -> fs.statAsync(path.join(constants.rootMountPoint, p)) .return(true) .catchReturn(false) # TODO: implement additional v2 endpoints # Some v1 endpoins only work for single-container apps as they assume the app has a single service. createApplicationManagerRouter = (applications) -> router = express.Router() router.use(bodyParser.urlencoded(extended: true)) router.use(bodyParser.json()) createV1Api(router, applications) createV2Api(router, applications) router.use(applications.proxyvisor.router) return router module.exports = class ApplicationManager extends EventEmitter constructor: ({ @logger, @config, @db, @eventTracker, @deviceState }) -> @docker = new Docker() @images = new Images({ @docker, @logger, @db }) @services = new ServiceManager({ @docker, @logger, @images, @config }) @networks = new NetworkManager({ @docker, @logger }) @volumes = new Volumes({ @docker, @logger }) @proxyvisor = new Proxyvisor({ @config, @logger, @db, @docker, @images, applications: this }) @timeSpentFetching = 0 @fetchesInProgress = 0 @_targetVolatilePerImageId = {} @_containerStarted = {} @actionExecutors = { stop: (step, { force = false, skipLock = false } = {}) => @_lockingIfNecessary step.current.appId, { force, skipLock: skipLock or step.options?.skipLock }, => wait = step.options?.wait ? false @services.kill(step.current, { removeContainer: false, wait }) .then => delete @_containerStarted[step.current.containerId] kill: (step, { force = false, skipLock = false } = {}) => @_lockingIfNecessary step.current.appId, { force, skipLock: skipLock or step.options?.skipLock }, => @services.kill(step.current) .then => delete @_containerStarted[step.current.containerId] if step.options?.removeImage @images.removeByDockerId(step.current.config.image) remove: (step) => # Only called for dead containers, so no need to take locks or anything @services.remove(step.current) updateMetadata: (step, { force = false, skipLock = false } = {}) => skipLock or= checkTruthy(step.current.config.labels['io.resin.legacy-container']) @_lockingIfNecessary step.current.appId, { force, skipLock: skipLock or step.options?.skipLock }, => @services.updateMetadata(step.current, step.target) restart: (step, { force = false, skipLock = false } = {}) => @_lockingIfNecessary step.current.appId, { force, skipLock: skipLock or step.options?.skipLock }, => @services.kill(step.current, { wait: true }) .then => delete @_containerStarted[step.current.containerId] .then => @services.start(step.target) .then (container) => @_containerStarted[container.id] = true stopAll: (step, { force = false, skipLock = false } = {}) => @stopAll({ force, skipLock }) start: (step) => @services.start(step.target) .then (container) => @_containerStarted[container.id] = true updateCommit: (step) => @config.set({ currentCommit: step.target }) handover: (step, { force = false, skipLock = false } = {}) => @_lockingIfNecessary step.current.appId, { force, skipLock: skipLock or step.options?.skipLock }, => @services.handover(step.current, step.target) fetch: (step) => startTime = process.hrtime() @fetchesInProgress += 1 Promise.join( @config.get('fetchOptions') @images.getAvailable() (opts, availableImages) => opts.deltaSource = @bestDeltaSource(step.image, availableImages) @images.triggerFetch step.image, opts, (success) => @fetchesInProgress -= 1 elapsed = process.hrtime(startTime) elapsedMs = elapsed[0] * 1000 + elapsed[1] / 1e6 @timeSpentFetching += elapsedMs if success # update_downloaded is true if *any* image has been downloaded, # and it's relevant mostly for the legacy GET /v1/device endpoint # that assumes a single-container app @reportCurrentState(update_downloaded: true) ) removeImage: (step) => @images.remove(step.image) saveImage: (step) => @images.save(step.image) cleanup: (step) => @images.cleanup() createNetworkOrVolume: (step) => if step.model is 'network' # TODO: These step targets should be the actual compose objects, # rather than recreating them Network.fromComposeObject({ @docker, @logger }, step.target.name, step.appId, step.target.config ).create() else @volumes.create(step.target) removeNetworkOrVolume: (step) => if step.model is 'network' Network.fromComposeObject({ @docker, @logger }, step.current.name, step.appId, step.current.config ).remove() else @volumes.remove(step.current) ensureSupervisorNetwork: => @networks.ensureSupervisorNetwork() } @validActions = _.keys(@actionExecutors).concat(@proxyvisor.validActions) @router = createApplicationManagerRouter(this) @images.on('change', @reportCurrentState) @services.on('change', @reportCurrentState) serviceAction: serviceAction imageForService: imageForService fetchAction: fetchAction reportCurrentState: (data) => @emit('change', data) init: => @images.cleanupDatabase() .then => @services.attachToRunning() .then => @services.listenToEvents() # Returns the status of applications and their services getStatus: => Promise.join( @services.getStatus() @images.getStatus() @config.get('currentCommit') @db.models('app').select([ 'appId', 'releaseId', 'commit' ]) (services, images, currentCommit, targetApps) -> apps = {} dependent = {} releaseId = null creationTimesAndReleases = {} # We iterate over the current running services and add them to the current state # of the app they belong to. for service in services appId = service.appId apps[appId] ?= {} creationTimesAndReleases[appId] = {} apps[appId].services ?= {} # We only send commit if all services have the same release, and it matches the target release if !releaseId? releaseId = service.releaseId else if releaseId != service.releaseId releaseId = false if !apps[appId].services[service.imageId]? apps[appId].services[service.imageId] = _.pick(service, [ 'status', 'releaseId' ]) creationTimesAndReleases[appId][service.imageId] = _.pick(service, [ 'createdAt', 'releaseId' ]) apps[appId].services[service.imageId].download_progress = null else # There's two containers with the same imageId, so this has to be a handover apps[appId].services[service.imageId].releaseId = _.minBy([ creationTimesAndReleases[appId][service.imageId], service ], 'createdAt').releaseId apps[appId].services[service.imageId].status = 'Handing over' for image in images appId = image.appId if !image.dependent apps[appId] ?= {} apps[appId].services ?= {} if !apps[appId].services[image.imageId]? apps[appId].services[image.imageId] = _.pick(image, [ 'status', 'releaseId' ]) apps[appId].services[image.imageId].download_progress = image.downloadProgress else if image.imageId? dependent[appId] ?= {} dependent[appId].images ?= {} dependent[appId].images[image.imageId] = _.pick(image, [ 'status' ]) dependent[appId].images[image.imageId].download_progress = image.downloadProgress else console.log('Ignoring legacy dependent image', image) obj = { local: apps, dependent } obj.commit = currentCommit return obj ) getDependentState: => @proxyvisor.getCurrentStates() _buildApps: (services, networks, volumes, currentCommit) -> apps = {} # We iterate over the current running services and add them to the current state # of the app they belong to. for service in services appId = service.appId apps[appId] ?= { appId, services: [], volumes: {}, networks: {} } apps[appId].services.push(service) for network in networks appId = network.appId apps[appId] ?= { appId, services: [], volumes: {}, networks: {} } apps[appId].networks[network.name] = network.config for volume in volumes appId = volume.appId apps[appId] ?= { appId, services: [], volumes: {}, networks: {} } apps[appId].volumes[volume.name] = volume.config # multi-app warning! # This is just wrong on every level _.each apps, (app) -> app.commit = currentCommit return apps getCurrentForComparison: => Promise.join( @services.getAll() @networks.getAll() @volumes.getAll() @config.get('currentCommit') @_buildApps ) getCurrentApp: (appId) => Promise.join( @services.getAllByAppId(appId) @networks.getAllByAppId(appId) @volumes.getAllByAppId(appId) @config.get('currentCommit') @_buildApps ).get(appId) getTargetApp: (appId) => @config.get('apiEndpoint').then (endpoint = '') -> @db.models('app').where({ appId, source: endpoint }).select() .then ([ app ]) => if !app? return @normaliseAndExtendAppFromDB(app) # Compares current and target services and returns a list of service pairs to be updated/removed/installed. # The returned list is an array of objects where the "current" and "target" properties define the update pair, and either can be null # (in the case of an install or removal). compareServicesForUpdate: (currentServices, targetServices) => removePairs = [] installPairs = [] updatePairs = [] targetServiceIds = _.map(targetServices, 'serviceId') currentServiceIds = _.uniq(_.map(currentServices, 'serviceId')) toBeRemoved = _.difference(currentServiceIds, targetServiceIds) for serviceId in toBeRemoved servicesToRemove = _.filter(currentServices, { serviceId }) for service in servicesToRemove removePairs.push({ current: service target: null serviceId }) toBeInstalled = _.difference(targetServiceIds, currentServiceIds) for serviceId in toBeInstalled serviceToInstall = _.find(targetServices, { serviceId }) if serviceToInstall? installPairs.push({ current: null target: serviceToInstall serviceId }) toBeMaybeUpdated = _.intersection(targetServiceIds, currentServiceIds) currentServicesPerId = {} targetServicesPerId = _.keyBy(targetServices, 'serviceId') for serviceId in toBeMaybeUpdated currentServiceContainers = _.filter(currentServices, { serviceId }) if currentServiceContainers.length > 1 currentServicesPerId[serviceId] = _.maxBy(currentServiceContainers, 'createdAt') # All but the latest container for this service are spurious and should be removed for service in _.without(currentServiceContainers, currentServicesPerId[serviceId]) removePairs.push({ current: service target: null serviceId }) else currentServicesPerId[serviceId] = currentServiceContainers[0] # Returns true if a service matches its target except it should be running and it is not, but we've # already started it before. In this case it means it just exited so we don't want to start it again. alreadyStarted = (serviceId) => return ( currentServicesPerId[serviceId].isEqualExceptForRunningState(targetServicesPerId[serviceId]) and targetServicesPerId[serviceId].config.running and @_containerStarted[currentServicesPerId[serviceId].containerId] ) needUpdate = _.filter toBeMaybeUpdated, (serviceId) -> !currentServicesPerId[serviceId].isEqual(targetServicesPerId[serviceId]) and !alreadyStarted(serviceId) for serviceId in needUpdate updatePairs.push({ current: currentServicesPerId[serviceId] target: targetServicesPerId[serviceId] serviceId }) return { removePairs, installPairs, updatePairs } _compareNetworksOrVolumesForUpdate: (model, { current, target }, appId) -> outputPairs = [] currentNames = _.keys(current) targetNames = _.keys(target) toBeRemoved = _.difference(currentNames, targetNames) for name in toBeRemoved outputPairs.push({ current: { name appId config: current[name] } target: null }) toBeInstalled = _.difference(targetNames, currentNames) for name in toBeInstalled outputPairs.push({ current: null target: { name appId config: target[name] } }) toBeUpdated = _.filter _.intersection(targetNames, currentNames), (name) => # While we're in this in-between state of a network-manager, but not # a volume-manager, we'll have to inspect the object to detect a # network-manager if model instanceof NetworkManager opts = docker: @docker, logger: @logger currentNet = Network.fromComposeObject( opts, name, appId, current[name] ) targetNet = Network.fromComposeObject( opts, name, appId, target[name] ) return !currentNet.isEqualConfig(targetNet) else return !model.isEqualConfig(current[name], target[name]) for name in toBeUpdated outputPairs.push({ current: { name appId config: current[name] } target: { name appId config: target[name] } }) return outputPairs compareNetworksForUpdate: ({ current, target }, appId) => @_compareNetworksOrVolumesForUpdate(@networks, { current, target }, appId) compareVolumesForUpdate: ({ current, target }, appId) => @_compareNetworksOrVolumesForUpdate(@volumes, { current, target }, appId) # Checks if a service is using a network or volume that is about to be updated _hasCurrentNetworksOrVolumes: (service, networkPairs, volumePairs) -> if !service? return false hasNetwork = _.some networkPairs, (pair) -> "#{service.appId}_#{pair.current?.name}" == service.networkMode if hasNetwork return true hasVolume = _.some service.volumes, (volume) -> name = _.split(volume, ':')[0] _.some volumePairs, (pair) -> "#{service.appId}_#{pair.current?.name}" == name return hasVolume # TODO: account for volumes-from, networks-from, links, etc # TODO: support networks instead of only networkMode _dependenciesMetForServiceStart: (target, networkPairs, volumePairs, pendingPairs) -> # for dependsOn, check no install or update pairs have that service dependencyUnmet = _.some target.dependsOn, (dependency) -> _.some(pendingPairs, (pair) -> pair.target?.serviceName == dependency) if dependencyUnmet return false # for networks and volumes, check no network pairs have that volume name if _.some(networkPairs, (pair) -> "#{target.appId}_#{pair.target?.name}" == target.networkMode) return false volumeUnmet = _.some target.volumes, (volumeDefinition) -> [ sourceName, destName ] = volumeDefinition.split(':') if !destName? # If this is not a named volume, ignore it return false return _.some(volumePairs, (pair) -> "#{target.appId}_#{pair.target?.name}" == sourceName) return !volumeUnmet # Unless the update strategy requires an early kill (i.e. kill-then-download, delete-then-download), we only want # to kill a service once the images for the services it depends on have been downloaded, so as to minimize # downtime (but not block the killing too much, potentially causing a deadlock) _dependenciesMetForServiceKill: (target, targetApp, availableImages) => if target.dependsOn? for dependency in target.dependsOn dependencyService = _.find(targetApp.services, serviceName: dependency) if !_.some(availableImages, (image) => image.dockerImageId == dependencyService.image or @images.isSameImage(image, { name: dependencyService.imageName })) return false return true _nextStepsForNetworkOrVolume: ({ current, target }, currentApp, changingPairs, dependencyComparisonFn, model) -> # Check none of the currentApp.services use this network or volume if current? dependencies = _.filter currentApp.services, (service) -> dependencyComparisonFn(service, current) if _.isEmpty(dependencies) return [{ action: 'removeNetworkOrVolume', model, current }] else # If the current update doesn't require killing the services that use this network/volume, # we have to kill them before removing the network/volume (e.g. when we're only updating the network config) steps = [] for dependency in dependencies if dependency.status != 'Stopping' and !_.some(changingPairs, serviceId: dependency.serviceId) steps.push(serviceAction('kill', dependency.serviceId, dependency)) return steps else if target? return [{ action: 'createNetworkOrVolume', model, target }] _nextStepsForNetwork: ({ current, target }, currentApp, changingPairs) => dependencyComparisonFn = (service, current) -> service.config.networkMode == "#{service.appId}_#{current?.name}" @_nextStepsForNetworkOrVolume({ current, target }, currentApp, changingPairs, dependencyComparisonFn, 'network') _nextStepsForVolume: ({ current, target }, currentApp, changingPairs) -> # Check none of the currentApp.services use this network or volume dependencyComparisonFn = (service, current) -> _.some service.config.volumes, (volumeDefinition) -> [ sourceName, destName ] = volumeDefinition.split(':') destName? and sourceName == "#{service.appId}_#{current?.name}" @_nextStepsForNetworkOrVolume({ current, target }, currentApp, changingPairs, dependencyComparisonFn, 'volume') # Infers steps that do not require creating a new container _updateContainerStep: (current, target) -> if current.releaseId != target.releaseId or current.imageId != target.imageId return serviceAction('updateMetadata', target.serviceId, current, target) else if target.config.running return serviceAction('start', target.serviceId, current, target) else return serviceAction('stop', target.serviceId, current, target) _fetchOrStartStep: (current, target, needsDownload, dependenciesMetForStart) -> if needsDownload return fetchAction(target) else if dependenciesMetForStart() return serviceAction('start', target.serviceId, current, target) else return null _strategySteps: { 'download-then-kill': (current, target, needsDownload, dependenciesMetForStart, dependenciesMetForKill) -> if needsDownload return fetchAction(target) else if dependenciesMetForKill() # We only kill when dependencies are already met, so that we minimize downtime return serviceAction('kill', target.serviceId, current, target) else return null 'kill-then-download': (current, target) -> return serviceAction('kill', target.serviceId, current, target) 'delete-then-download': (current, target, needsDownload) -> return serviceAction('kill', target.serviceId, current, target, removeImage: needsDownload) 'hand-over': (current, target, needsDownload, dependenciesMetForStart, dependenciesMetForKill, needsSpecialKill, timeout) -> if needsDownload return fetchAction(target) else if needsSpecialKill and dependenciesMetForKill() return serviceAction('kill', target.serviceId, current, target) else if dependenciesMetForStart() return serviceAction('handover', target.serviceId, current, target, timeout: timeout) else return null } _nextStepForService: ({ current, target }, updateContext) => { targetApp, networkPairs, volumePairs, installPairs, updatePairs, availableImages, downloading } = updateContext if current?.status == 'Stopping' # There is already a kill step in progress for this service, so we wait return { action: 'noop' } if current?.status == 'Dead' # Dead containers have to be removed return serviceAction('remove', current.serviceId, current) needsDownload = !_.some availableImages, (image) => image.dockerImageId == target?.config.image or @images.isSameImage(image, { name: target.imageName }) # This service needs an image download but it's currently downloading, so we wait if needsDownload and target?.imageId in downloading return { action: 'noop' } dependenciesMetForStart = => @_dependenciesMetForServiceStart(target, networkPairs, volumePairs, installPairs.concat(updatePairs)) dependenciesMetForKill = => !needsDownload and @_dependenciesMetForServiceKill(target, targetApp, availableImages) # If the service is using a network or volume that is being updated, we need to kill it # even if its strategy is handover needsSpecialKill = @_hasCurrentNetworksOrVolumes(current, networkPairs, volumePairs) if current?.isEqualConfig(target) # We're only stopping/starting it return @_updateContainerStep(current, target) else if !current? # Either this is a new service, or the current one has already been killed return @_fetchOrStartStep(current, target, needsDownload, dependenciesMetForStart) else strategy = checkString(target.config.labels['io.resin.update.strategy']) validStrategies = [ 'download-then-kill', 'kill-then-download', 'delete-then-download', 'hand-over' ] if !_.includes(validStrategies, strategy) strategy = 'download-then-kill' timeout = checkInt(target.config.labels['io.resin.update.handover-timeout']) return @_strategySteps[strategy](current, target, needsDownload, dependenciesMetForStart, dependenciesMetForKill, needsSpecialKill, timeout) _nextStepsForAppUpdate: (currentApp, targetApp, availableImages = [], downloading = []) => emptyApp = { services: [], volumes: {}, networks: {} } if !targetApp? targetApp = emptyApp else # Create the default network for the target app targetApp.networks['default'] ?= {} currentApp ?= emptyApp if currentApp.services?.length == 1 and targetApp.services?.length == 1 and targetApp.services[0].serviceName == currentApp.services[0].serviceName and checkTruthy(currentApp.services[0].config.labels['io.resin.legacy-container']) # This is a legacy preloaded app or container, so we didn't have things like serviceId. # We hack a few things to avoid an unnecessary restart of the preloaded app # (but ensuring it gets updated if it actually changed) targetApp.services[0].config.labels['io.resin.legacy-container'] = currentApp.services[0].labels['io.resin.legacy-container'] targetApp.services[0].config.labels['io.resin.service-id'] = currentApp.services[0].labels['io.resin.service-id'] targetApp.services[0].serviceId = currentApp.services[0].serviceId appId = targetApp.appId ? currentApp.appId networkPairs = @compareNetworksForUpdate({ current: currentApp.networks, target: targetApp.networks }, appId) volumePairs = @compareVolumesForUpdate({ current: currentApp.volumes, target: targetApp.volumes }, appId) { removePairs, installPairs, updatePairs } = @compareServicesForUpdate(currentApp.services, targetApp.services) steps = [] # All removePairs get a 'kill' action for pair in removePairs if pair.current.status != 'Stopping' steps.push(serviceAction('kill', pair.current.serviceId, pair.current, null)) else steps.push({ action: 'noop' }) # next step for install pairs in download - start order, but start requires dependencies, networks and volumes met # next step for update pairs in order by update strategy. start requires dependencies, networks and volumes met. for pair in installPairs.concat(updatePairs) step = @_nextStepForService(pair, { targetApp, networkPairs, volumePairs, installPairs, updatePairs, availableImages, downloading }) if step? steps.push(step) # next step for network pairs - remove requires services killed, create kill if no pairs or steps affect that service for pair in networkPairs pairSteps = @_nextStepsForNetwork(pair, currentApp, removePairs.concat(updatePairs)) steps = steps.concat(pairSteps) # next step for volume pairs - remove requires services killed, create kill if no pairs or steps affect that service for pair in volumePairs pairSteps = @_nextStepsForVolume(pair, currentApp, removePairs.concat(updatePairs)) steps = steps.concat(pairSteps) if _.isEmpty(steps) and currentApp.commit != targetApp.commit steps.push({ action: 'updateCommit' target: targetApp.commit }) return _.map(steps, (step) -> _.assign({}, step, { appId })) normaliseAppForDB: (app) => services = _.map app.services, (s, serviceId) -> service = _.clone(s) service.appId = app.appId service.releaseId = app.releaseId service.serviceId = checkInt(serviceId) service.commit = app.commit return service Promise.map services, (service) => service.image = @images.normalise(service.image) Promise.props(service) .then (services) -> dbApp = { appId: app.appId commit: app.commit name: <NAME>.name source: app.source releaseId: app.releaseId services: JSON.stringify(services) networks: JSON.stringify(app.networks ? {}) volumes: JSON.stringify(app.volumes ? {}) } return dbApp createTargetService: (service, opts) -> @images.inspectByName(service.image) .catchReturn(NotFoundError, undefined) .then (imageInfo) -> serviceOpts = { serviceName: service.serviceName imageInfo } _.assign(serviceOpts, opts) service.imageName = service.image if imageInfo?.Id? service.image = imageInfo.Id return Service.fromComposeObject(service, serviceOpts) normaliseAndExtendAppFromDB: (app) => Promise.join( @config.get('extendedEnvOptions') @docker.getNetworkGateway(constants.supervisorNetworkInterface) .catchReturn('127.0.0.1') Promise.props({ firmware: pathExistsOnHost('/lib/firmware') modules: pathExistsOnHost('/lib/modules') }) fs.readFileAsync(path.join(constants.rootMountPoint, '/etc/hostname'), 'utf8').then(_.trim) (opts, supervisorApiHost, hostPathExists, hostnameOnHost) => configOpts = { appName: app.name supervisorApiHost hostPathExists hostnameOnHost } _.assign(configOpts, opts) volumes = JSON.parse(app.volumes) volumes = _.mapValues volumes, (volumeConfig) -> volumeConfig ?= {} volumeConfig.labels ?= {} return volumeConfig Promise.map(JSON.parse(app.services), (service) => @createTargetService(service, configOpts)) .then (services) -> # If a named volume is defined in a service, we add it app-wide so that we can track it and purge it for s in services serviceNamedVolumes = s.getNamedVolumes() for name in serviceNamedVolumes volumes[name] ?= { labels: {} } outApp = { appId: app.appId name: app.name commit: app.commit releaseId: app.releaseId services: services networks: JSON.parse(app.networks) volumes: volumes } return outApp ) setTarget: (apps, dependent , source, trx) => setInTransaction = (trx) => Promise.try => appsArray = _.map apps, (app, appId) -> appClone = _.clone(app) appClone.appId = checkInt(appId) appClone.source = source return appClone Promise.map(appsArray, @normaliseAppForDB) .tap (appsForDB) => Promise.map appsForDB, (app) => @db.upsertModel('app', app, { appId: app.appId }, trx) .then (appsForDB) -> trx('app').whereNotIn('appId', _.map(appsForDB, 'appId')).del() .then => @proxyvisor.setTargetInTransaction(dependent, trx) Promise.try => if trx? setInTransaction(trx) else @db.transaction(setInTransaction) .then => @_targetVolatilePerImageId = {} setTargetVolatileForService: (imageId, target) => @_targetVolatilePerImageId[imageId] ?= {} _.assign(@_targetVolatilePerImageId[imageId], target) clearTargetVolatileForServices: (imageIds) => for imageId in imageIds @_targetVolatilePerImageId[imageId] = {} getTargetApps: => @config.get('apiEndpoint'). then (source = '') => Promise.map(@db.models('app').where({ source }), @normaliseAndExtendAppFromDB) .map (app) => if !_.isEmpty(app.services) app.services = _.map app.services, (service) => if @_targetVolatilePerImageId[service.imageId]? _.merge(service, @_targetVolatilePerImageId[service.imageId]) return service return app .then (apps) -> return _.keyBy(apps, 'appId') getDependentTargets: => @proxyvisor.getTarget() bestDeltaSource: (image, available) -> if !image.dependent for availableImage in available if availableImage.serviceName == image.serviceName and availableImage.appId == image.appId return availableImage.name for availableImage in available if availableImage.serviceName == image.serviceName return availableImage.name for availableImage in available if availableImage.appId == image.appId return availableImage.name return 'resin/scratch' # returns: # imagesToRemove: images that # - are not used in the current state, and # - are not going to be used in the target state, and # - are not needed for delta source / pull caching or would be used for a service with delete-then-download as strategy # imagesToSave: images that # - are locally available (i.e. an image with the same digest exists) # - are not saved to the DB with all their metadata (serviceId, serviceName, etc) _compareImages: (current, target, available) => allImagesForTargetApp = (app) -> _.map(app.services, imageForService) allImagesForCurrentApp = (app) -> _.map app.services, (service) -> img = _.find(available, { dockerImageId: service.config.image, imageId: service.imageId }) ? _.find(available, { dockerImageId: service.config.image }) return _.omit(img, [ 'dockerImageId', 'id' ]) availableWithoutIds = _.map(available, (image) -> _.omit(image, [ 'dockerImageId', 'id' ])) currentImages = _.flatMap(current.local.apps, allImagesForCurrentApp) targetImages = _.flatMap(target.local.apps, allImagesForTargetApp) availableAndUnused = _.filter availableWithoutIds, (image) -> !_.some currentImages.concat(targetImages), (imageInUse) -> _.isEqual(image, imageInUse) imagesToDownload = _.filter targetImages, (targetImage) => !_.some available, (availableImage) => @images.isSameImage(availableImage, targetImage) # Images that are available but we don't have them in the DB with the exact metadata: imagesToSave = _.filter targetImages, (targetImage) => _.some(available, (availableImage) => @images.isSameImage(availableImage, targetImage)) and !_.some(availableWithoutIds, (img) -> _.isEqual(img, targetImage)) deltaSources = _.map imagesToDownload, (image) => return @bestDeltaSource(image, available) proxyvisorImages = @proxyvisor.imagesInUse(current, target) imagesToRemove = _.filter availableAndUnused, (image) => notUsedForDelta = !_.includes(deltaSources, image.name) notUsedByProxyvisor = !_.some proxyvisorImages, (proxyvisorImage) => @images.isSameImage(image, { name: proxyvisorImage }) return notUsedForDelta and notUsedByProxyvisor return { imagesToSave, imagesToRemove } _inferNextSteps: (cleanupNeeded, availableImages, downloading, supervisorNetworkReady, current, target, ignoreImages, { localMode, delta }) => Promise.try => delta = checkTruthy(delta) if checkTruthy(localMode) target = _.cloneDeep(target) target.local.apps = _.mapValues target.local.apps, (app) -> app.services = [] return app ignoreImages = true currentByAppId = current.local.apps ? {} targetByAppId = target.local.apps ? {} nextSteps = [] if !supervisorNetworkReady nextSteps.push({ action: 'ensureSupervisorNetwork' }) else if !ignoreImages and _.isEmpty(downloading) if cleanupNeeded nextSteps.push({ action: 'cleanup' }) { imagesToRemove, imagesToSave } = @_compareImages(current, target, availableImages) for image in imagesToSave nextSteps.push({ action: 'saveImage', image }) if _.isEmpty(imagesToSave) for image in imagesToRemove nextSteps.push({ action: 'removeImage', image }) # If we have to remove any images, we do that before anything else if _.isEmpty(nextSteps) allAppIds = _.union(_.keys(currentByAppId), _.keys(targetByAppId)) for appId in allAppIds nextSteps = nextSteps.concat(@_nextStepsForAppUpdate(currentByAppId[appId], targetByAppId[appId], availableImages, downloading)) newDownloads = _.filter(nextSteps, (s) -> s.action == 'fetch').length if !ignoreImages and delta and newDownloads > 0 downloadsToBlock = downloading.length + newDownloads - constants.maxDeltaDownloads while downloadsToBlock > 0 _.pull(nextSteps, _.find(nextSteps, action: 'fetch')) downloadsToBlock -= 1 if !ignoreImages and _.isEmpty(nextSteps) and !_.isEmpty(downloading) nextSteps.push({ action: 'noop' }) return _.uniqWith(nextSteps, _.isEqual) stopAll: ({ force = false, skipLock = false } = {}) => @services.getAll() .map (service) => @_lockingIfNecessary service.appId, { force, skipLock }, => @services.kill(service, { removeContainer: false, wait: true }) .then => delete @_containerStarted[service.containerId] _lockingIfNecessary: (appId, { force = false, skipLock = false } = {}, fn) => if skipLock return Promise.try(fn) @config.get('lockOverride') .then (lockOverride) -> return checkTruthy(lockOverride) or force .then (force) -> updateLock.lock(appId, { force }, fn) executeStepAction: (step, { force = false, skipLock = false } = {}) => if _.includes(@proxyvisor.validActions, step.action) return @proxyvisor.executeStepAction(step) if !_.includes(@validActions, step.action) return Promise.reject(new Error("Invalid action #{step.action}")) @actionExecutors[step.action](step, { force, skipLock }) getRequiredSteps: (currentState, targetState, ignoreImages = false) => Promise.join( @images.isCleanupNeeded() @images.getAvailable() @images.getDownloadingImageIds() @networks.supervisorNetworkReady() @config.getMany([ 'localMode', 'delta' ]) (cleanupNeeded, availableImages, downloading, supervisorNetworkReady, conf) => @_inferNextSteps(cleanupNeeded, availableImages, downloading, supervisorNetworkReady, currentState, targetState, ignoreImages, conf) .then (nextSteps) => if ignoreImages and _.some(nextSteps, action: 'fetch') throw new Error('Cannot fetch images while executing an API action') @proxyvisor.getRequiredSteps(availableImages, downloading, currentState, targetState, nextSteps) .then (proxyvisorSteps) -> return nextSteps.concat(proxyvisorSteps) )
true
Promise = require 'bluebird' _ = require 'lodash' EventEmitter = require 'events' express = require 'express' bodyParser = require 'body-parser' fs = Promise.promisifyAll(require('fs')) path = require 'path' constants = require './lib/constants' Docker = require './lib/docker-utils' updateLock = require './lib/update-lock' { checkTruthy, checkInt, checkString } = require './lib/validation' { NotFoundError } = require './lib/errors' ServiceManager = require './compose/service-manager' { Service } = require './compose/service' Images = require './compose/images' { NetworkManager } = require './compose/network-manager' { Network } = require './compose/network' Volumes = require './compose/volumes' Proxyvisor = require './proxyvisor' { createV1Api } = require './device-api/v1' { createV2Api } = require './device-api/v2' { serviceAction } = require './device-api/common' # TODO: move this to an Image class? imageForService = (service) -> return { name: service.imageName appId: service.appId serviceId: service.serviceId serviceName: service.serviceName imageId: service.imageId releaseId: service.releaseId dependent: 0 } fetchAction = (service) -> return { action: 'fetch' image: imageForService(service) serviceId: service.serviceId } pathExistsOnHost = (p) -> fs.statAsync(path.join(constants.rootMountPoint, p)) .return(true) .catchReturn(false) # TODO: implement additional v2 endpoints # Some v1 endpoins only work for single-container apps as they assume the app has a single service. createApplicationManagerRouter = (applications) -> router = express.Router() router.use(bodyParser.urlencoded(extended: true)) router.use(bodyParser.json()) createV1Api(router, applications) createV2Api(router, applications) router.use(applications.proxyvisor.router) return router module.exports = class ApplicationManager extends EventEmitter constructor: ({ @logger, @config, @db, @eventTracker, @deviceState }) -> @docker = new Docker() @images = new Images({ @docker, @logger, @db }) @services = new ServiceManager({ @docker, @logger, @images, @config }) @networks = new NetworkManager({ @docker, @logger }) @volumes = new Volumes({ @docker, @logger }) @proxyvisor = new Proxyvisor({ @config, @logger, @db, @docker, @images, applications: this }) @timeSpentFetching = 0 @fetchesInProgress = 0 @_targetVolatilePerImageId = {} @_containerStarted = {} @actionExecutors = { stop: (step, { force = false, skipLock = false } = {}) => @_lockingIfNecessary step.current.appId, { force, skipLock: skipLock or step.options?.skipLock }, => wait = step.options?.wait ? false @services.kill(step.current, { removeContainer: false, wait }) .then => delete @_containerStarted[step.current.containerId] kill: (step, { force = false, skipLock = false } = {}) => @_lockingIfNecessary step.current.appId, { force, skipLock: skipLock or step.options?.skipLock }, => @services.kill(step.current) .then => delete @_containerStarted[step.current.containerId] if step.options?.removeImage @images.removeByDockerId(step.current.config.image) remove: (step) => # Only called for dead containers, so no need to take locks or anything @services.remove(step.current) updateMetadata: (step, { force = false, skipLock = false } = {}) => skipLock or= checkTruthy(step.current.config.labels['io.resin.legacy-container']) @_lockingIfNecessary step.current.appId, { force, skipLock: skipLock or step.options?.skipLock }, => @services.updateMetadata(step.current, step.target) restart: (step, { force = false, skipLock = false } = {}) => @_lockingIfNecessary step.current.appId, { force, skipLock: skipLock or step.options?.skipLock }, => @services.kill(step.current, { wait: true }) .then => delete @_containerStarted[step.current.containerId] .then => @services.start(step.target) .then (container) => @_containerStarted[container.id] = true stopAll: (step, { force = false, skipLock = false } = {}) => @stopAll({ force, skipLock }) start: (step) => @services.start(step.target) .then (container) => @_containerStarted[container.id] = true updateCommit: (step) => @config.set({ currentCommit: step.target }) handover: (step, { force = false, skipLock = false } = {}) => @_lockingIfNecessary step.current.appId, { force, skipLock: skipLock or step.options?.skipLock }, => @services.handover(step.current, step.target) fetch: (step) => startTime = process.hrtime() @fetchesInProgress += 1 Promise.join( @config.get('fetchOptions') @images.getAvailable() (opts, availableImages) => opts.deltaSource = @bestDeltaSource(step.image, availableImages) @images.triggerFetch step.image, opts, (success) => @fetchesInProgress -= 1 elapsed = process.hrtime(startTime) elapsedMs = elapsed[0] * 1000 + elapsed[1] / 1e6 @timeSpentFetching += elapsedMs if success # update_downloaded is true if *any* image has been downloaded, # and it's relevant mostly for the legacy GET /v1/device endpoint # that assumes a single-container app @reportCurrentState(update_downloaded: true) ) removeImage: (step) => @images.remove(step.image) saveImage: (step) => @images.save(step.image) cleanup: (step) => @images.cleanup() createNetworkOrVolume: (step) => if step.model is 'network' # TODO: These step targets should be the actual compose objects, # rather than recreating them Network.fromComposeObject({ @docker, @logger }, step.target.name, step.appId, step.target.config ).create() else @volumes.create(step.target) removeNetworkOrVolume: (step) => if step.model is 'network' Network.fromComposeObject({ @docker, @logger }, step.current.name, step.appId, step.current.config ).remove() else @volumes.remove(step.current) ensureSupervisorNetwork: => @networks.ensureSupervisorNetwork() } @validActions = _.keys(@actionExecutors).concat(@proxyvisor.validActions) @router = createApplicationManagerRouter(this) @images.on('change', @reportCurrentState) @services.on('change', @reportCurrentState) serviceAction: serviceAction imageForService: imageForService fetchAction: fetchAction reportCurrentState: (data) => @emit('change', data) init: => @images.cleanupDatabase() .then => @services.attachToRunning() .then => @services.listenToEvents() # Returns the status of applications and their services getStatus: => Promise.join( @services.getStatus() @images.getStatus() @config.get('currentCommit') @db.models('app').select([ 'appId', 'releaseId', 'commit' ]) (services, images, currentCommit, targetApps) -> apps = {} dependent = {} releaseId = null creationTimesAndReleases = {} # We iterate over the current running services and add them to the current state # of the app they belong to. for service in services appId = service.appId apps[appId] ?= {} creationTimesAndReleases[appId] = {} apps[appId].services ?= {} # We only send commit if all services have the same release, and it matches the target release if !releaseId? releaseId = service.releaseId else if releaseId != service.releaseId releaseId = false if !apps[appId].services[service.imageId]? apps[appId].services[service.imageId] = _.pick(service, [ 'status', 'releaseId' ]) creationTimesAndReleases[appId][service.imageId] = _.pick(service, [ 'createdAt', 'releaseId' ]) apps[appId].services[service.imageId].download_progress = null else # There's two containers with the same imageId, so this has to be a handover apps[appId].services[service.imageId].releaseId = _.minBy([ creationTimesAndReleases[appId][service.imageId], service ], 'createdAt').releaseId apps[appId].services[service.imageId].status = 'Handing over' for image in images appId = image.appId if !image.dependent apps[appId] ?= {} apps[appId].services ?= {} if !apps[appId].services[image.imageId]? apps[appId].services[image.imageId] = _.pick(image, [ 'status', 'releaseId' ]) apps[appId].services[image.imageId].download_progress = image.downloadProgress else if image.imageId? dependent[appId] ?= {} dependent[appId].images ?= {} dependent[appId].images[image.imageId] = _.pick(image, [ 'status' ]) dependent[appId].images[image.imageId].download_progress = image.downloadProgress else console.log('Ignoring legacy dependent image', image) obj = { local: apps, dependent } obj.commit = currentCommit return obj ) getDependentState: => @proxyvisor.getCurrentStates() _buildApps: (services, networks, volumes, currentCommit) -> apps = {} # We iterate over the current running services and add them to the current state # of the app they belong to. for service in services appId = service.appId apps[appId] ?= { appId, services: [], volumes: {}, networks: {} } apps[appId].services.push(service) for network in networks appId = network.appId apps[appId] ?= { appId, services: [], volumes: {}, networks: {} } apps[appId].networks[network.name] = network.config for volume in volumes appId = volume.appId apps[appId] ?= { appId, services: [], volumes: {}, networks: {} } apps[appId].volumes[volume.name] = volume.config # multi-app warning! # This is just wrong on every level _.each apps, (app) -> app.commit = currentCommit return apps getCurrentForComparison: => Promise.join( @services.getAll() @networks.getAll() @volumes.getAll() @config.get('currentCommit') @_buildApps ) getCurrentApp: (appId) => Promise.join( @services.getAllByAppId(appId) @networks.getAllByAppId(appId) @volumes.getAllByAppId(appId) @config.get('currentCommit') @_buildApps ).get(appId) getTargetApp: (appId) => @config.get('apiEndpoint').then (endpoint = '') -> @db.models('app').where({ appId, source: endpoint }).select() .then ([ app ]) => if !app? return @normaliseAndExtendAppFromDB(app) # Compares current and target services and returns a list of service pairs to be updated/removed/installed. # The returned list is an array of objects where the "current" and "target" properties define the update pair, and either can be null # (in the case of an install or removal). compareServicesForUpdate: (currentServices, targetServices) => removePairs = [] installPairs = [] updatePairs = [] targetServiceIds = _.map(targetServices, 'serviceId') currentServiceIds = _.uniq(_.map(currentServices, 'serviceId')) toBeRemoved = _.difference(currentServiceIds, targetServiceIds) for serviceId in toBeRemoved servicesToRemove = _.filter(currentServices, { serviceId }) for service in servicesToRemove removePairs.push({ current: service target: null serviceId }) toBeInstalled = _.difference(targetServiceIds, currentServiceIds) for serviceId in toBeInstalled serviceToInstall = _.find(targetServices, { serviceId }) if serviceToInstall? installPairs.push({ current: null target: serviceToInstall serviceId }) toBeMaybeUpdated = _.intersection(targetServiceIds, currentServiceIds) currentServicesPerId = {} targetServicesPerId = _.keyBy(targetServices, 'serviceId') for serviceId in toBeMaybeUpdated currentServiceContainers = _.filter(currentServices, { serviceId }) if currentServiceContainers.length > 1 currentServicesPerId[serviceId] = _.maxBy(currentServiceContainers, 'createdAt') # All but the latest container for this service are spurious and should be removed for service in _.without(currentServiceContainers, currentServicesPerId[serviceId]) removePairs.push({ current: service target: null serviceId }) else currentServicesPerId[serviceId] = currentServiceContainers[0] # Returns true if a service matches its target except it should be running and it is not, but we've # already started it before. In this case it means it just exited so we don't want to start it again. alreadyStarted = (serviceId) => return ( currentServicesPerId[serviceId].isEqualExceptForRunningState(targetServicesPerId[serviceId]) and targetServicesPerId[serviceId].config.running and @_containerStarted[currentServicesPerId[serviceId].containerId] ) needUpdate = _.filter toBeMaybeUpdated, (serviceId) -> !currentServicesPerId[serviceId].isEqual(targetServicesPerId[serviceId]) and !alreadyStarted(serviceId) for serviceId in needUpdate updatePairs.push({ current: currentServicesPerId[serviceId] target: targetServicesPerId[serviceId] serviceId }) return { removePairs, installPairs, updatePairs } _compareNetworksOrVolumesForUpdate: (model, { current, target }, appId) -> outputPairs = [] currentNames = _.keys(current) targetNames = _.keys(target) toBeRemoved = _.difference(currentNames, targetNames) for name in toBeRemoved outputPairs.push({ current: { name appId config: current[name] } target: null }) toBeInstalled = _.difference(targetNames, currentNames) for name in toBeInstalled outputPairs.push({ current: null target: { name appId config: target[name] } }) toBeUpdated = _.filter _.intersection(targetNames, currentNames), (name) => # While we're in this in-between state of a network-manager, but not # a volume-manager, we'll have to inspect the object to detect a # network-manager if model instanceof NetworkManager opts = docker: @docker, logger: @logger currentNet = Network.fromComposeObject( opts, name, appId, current[name] ) targetNet = Network.fromComposeObject( opts, name, appId, target[name] ) return !currentNet.isEqualConfig(targetNet) else return !model.isEqualConfig(current[name], target[name]) for name in toBeUpdated outputPairs.push({ current: { name appId config: current[name] } target: { name appId config: target[name] } }) return outputPairs compareNetworksForUpdate: ({ current, target }, appId) => @_compareNetworksOrVolumesForUpdate(@networks, { current, target }, appId) compareVolumesForUpdate: ({ current, target }, appId) => @_compareNetworksOrVolumesForUpdate(@volumes, { current, target }, appId) # Checks if a service is using a network or volume that is about to be updated _hasCurrentNetworksOrVolumes: (service, networkPairs, volumePairs) -> if !service? return false hasNetwork = _.some networkPairs, (pair) -> "#{service.appId}_#{pair.current?.name}" == service.networkMode if hasNetwork return true hasVolume = _.some service.volumes, (volume) -> name = _.split(volume, ':')[0] _.some volumePairs, (pair) -> "#{service.appId}_#{pair.current?.name}" == name return hasVolume # TODO: account for volumes-from, networks-from, links, etc # TODO: support networks instead of only networkMode _dependenciesMetForServiceStart: (target, networkPairs, volumePairs, pendingPairs) -> # for dependsOn, check no install or update pairs have that service dependencyUnmet = _.some target.dependsOn, (dependency) -> _.some(pendingPairs, (pair) -> pair.target?.serviceName == dependency) if dependencyUnmet return false # for networks and volumes, check no network pairs have that volume name if _.some(networkPairs, (pair) -> "#{target.appId}_#{pair.target?.name}" == target.networkMode) return false volumeUnmet = _.some target.volumes, (volumeDefinition) -> [ sourceName, destName ] = volumeDefinition.split(':') if !destName? # If this is not a named volume, ignore it return false return _.some(volumePairs, (pair) -> "#{target.appId}_#{pair.target?.name}" == sourceName) return !volumeUnmet # Unless the update strategy requires an early kill (i.e. kill-then-download, delete-then-download), we only want # to kill a service once the images for the services it depends on have been downloaded, so as to minimize # downtime (but not block the killing too much, potentially causing a deadlock) _dependenciesMetForServiceKill: (target, targetApp, availableImages) => if target.dependsOn? for dependency in target.dependsOn dependencyService = _.find(targetApp.services, serviceName: dependency) if !_.some(availableImages, (image) => image.dockerImageId == dependencyService.image or @images.isSameImage(image, { name: dependencyService.imageName })) return false return true _nextStepsForNetworkOrVolume: ({ current, target }, currentApp, changingPairs, dependencyComparisonFn, model) -> # Check none of the currentApp.services use this network or volume if current? dependencies = _.filter currentApp.services, (service) -> dependencyComparisonFn(service, current) if _.isEmpty(dependencies) return [{ action: 'removeNetworkOrVolume', model, current }] else # If the current update doesn't require killing the services that use this network/volume, # we have to kill them before removing the network/volume (e.g. when we're only updating the network config) steps = [] for dependency in dependencies if dependency.status != 'Stopping' and !_.some(changingPairs, serviceId: dependency.serviceId) steps.push(serviceAction('kill', dependency.serviceId, dependency)) return steps else if target? return [{ action: 'createNetworkOrVolume', model, target }] _nextStepsForNetwork: ({ current, target }, currentApp, changingPairs) => dependencyComparisonFn = (service, current) -> service.config.networkMode == "#{service.appId}_#{current?.name}" @_nextStepsForNetworkOrVolume({ current, target }, currentApp, changingPairs, dependencyComparisonFn, 'network') _nextStepsForVolume: ({ current, target }, currentApp, changingPairs) -> # Check none of the currentApp.services use this network or volume dependencyComparisonFn = (service, current) -> _.some service.config.volumes, (volumeDefinition) -> [ sourceName, destName ] = volumeDefinition.split(':') destName? and sourceName == "#{service.appId}_#{current?.name}" @_nextStepsForNetworkOrVolume({ current, target }, currentApp, changingPairs, dependencyComparisonFn, 'volume') # Infers steps that do not require creating a new container _updateContainerStep: (current, target) -> if current.releaseId != target.releaseId or current.imageId != target.imageId return serviceAction('updateMetadata', target.serviceId, current, target) else if target.config.running return serviceAction('start', target.serviceId, current, target) else return serviceAction('stop', target.serviceId, current, target) _fetchOrStartStep: (current, target, needsDownload, dependenciesMetForStart) -> if needsDownload return fetchAction(target) else if dependenciesMetForStart() return serviceAction('start', target.serviceId, current, target) else return null _strategySteps: { 'download-then-kill': (current, target, needsDownload, dependenciesMetForStart, dependenciesMetForKill) -> if needsDownload return fetchAction(target) else if dependenciesMetForKill() # We only kill when dependencies are already met, so that we minimize downtime return serviceAction('kill', target.serviceId, current, target) else return null 'kill-then-download': (current, target) -> return serviceAction('kill', target.serviceId, current, target) 'delete-then-download': (current, target, needsDownload) -> return serviceAction('kill', target.serviceId, current, target, removeImage: needsDownload) 'hand-over': (current, target, needsDownload, dependenciesMetForStart, dependenciesMetForKill, needsSpecialKill, timeout) -> if needsDownload return fetchAction(target) else if needsSpecialKill and dependenciesMetForKill() return serviceAction('kill', target.serviceId, current, target) else if dependenciesMetForStart() return serviceAction('handover', target.serviceId, current, target, timeout: timeout) else return null } _nextStepForService: ({ current, target }, updateContext) => { targetApp, networkPairs, volumePairs, installPairs, updatePairs, availableImages, downloading } = updateContext if current?.status == 'Stopping' # There is already a kill step in progress for this service, so we wait return { action: 'noop' } if current?.status == 'Dead' # Dead containers have to be removed return serviceAction('remove', current.serviceId, current) needsDownload = !_.some availableImages, (image) => image.dockerImageId == target?.config.image or @images.isSameImage(image, { name: target.imageName }) # This service needs an image download but it's currently downloading, so we wait if needsDownload and target?.imageId in downloading return { action: 'noop' } dependenciesMetForStart = => @_dependenciesMetForServiceStart(target, networkPairs, volumePairs, installPairs.concat(updatePairs)) dependenciesMetForKill = => !needsDownload and @_dependenciesMetForServiceKill(target, targetApp, availableImages) # If the service is using a network or volume that is being updated, we need to kill it # even if its strategy is handover needsSpecialKill = @_hasCurrentNetworksOrVolumes(current, networkPairs, volumePairs) if current?.isEqualConfig(target) # We're only stopping/starting it return @_updateContainerStep(current, target) else if !current? # Either this is a new service, or the current one has already been killed return @_fetchOrStartStep(current, target, needsDownload, dependenciesMetForStart) else strategy = checkString(target.config.labels['io.resin.update.strategy']) validStrategies = [ 'download-then-kill', 'kill-then-download', 'delete-then-download', 'hand-over' ] if !_.includes(validStrategies, strategy) strategy = 'download-then-kill' timeout = checkInt(target.config.labels['io.resin.update.handover-timeout']) return @_strategySteps[strategy](current, target, needsDownload, dependenciesMetForStart, dependenciesMetForKill, needsSpecialKill, timeout) _nextStepsForAppUpdate: (currentApp, targetApp, availableImages = [], downloading = []) => emptyApp = { services: [], volumes: {}, networks: {} } if !targetApp? targetApp = emptyApp else # Create the default network for the target app targetApp.networks['default'] ?= {} currentApp ?= emptyApp if currentApp.services?.length == 1 and targetApp.services?.length == 1 and targetApp.services[0].serviceName == currentApp.services[0].serviceName and checkTruthy(currentApp.services[0].config.labels['io.resin.legacy-container']) # This is a legacy preloaded app or container, so we didn't have things like serviceId. # We hack a few things to avoid an unnecessary restart of the preloaded app # (but ensuring it gets updated if it actually changed) targetApp.services[0].config.labels['io.resin.legacy-container'] = currentApp.services[0].labels['io.resin.legacy-container'] targetApp.services[0].config.labels['io.resin.service-id'] = currentApp.services[0].labels['io.resin.service-id'] targetApp.services[0].serviceId = currentApp.services[0].serviceId appId = targetApp.appId ? currentApp.appId networkPairs = @compareNetworksForUpdate({ current: currentApp.networks, target: targetApp.networks }, appId) volumePairs = @compareVolumesForUpdate({ current: currentApp.volumes, target: targetApp.volumes }, appId) { removePairs, installPairs, updatePairs } = @compareServicesForUpdate(currentApp.services, targetApp.services) steps = [] # All removePairs get a 'kill' action for pair in removePairs if pair.current.status != 'Stopping' steps.push(serviceAction('kill', pair.current.serviceId, pair.current, null)) else steps.push({ action: 'noop' }) # next step for install pairs in download - start order, but start requires dependencies, networks and volumes met # next step for update pairs in order by update strategy. start requires dependencies, networks and volumes met. for pair in installPairs.concat(updatePairs) step = @_nextStepForService(pair, { targetApp, networkPairs, volumePairs, installPairs, updatePairs, availableImages, downloading }) if step? steps.push(step) # next step for network pairs - remove requires services killed, create kill if no pairs or steps affect that service for pair in networkPairs pairSteps = @_nextStepsForNetwork(pair, currentApp, removePairs.concat(updatePairs)) steps = steps.concat(pairSteps) # next step for volume pairs - remove requires services killed, create kill if no pairs or steps affect that service for pair in volumePairs pairSteps = @_nextStepsForVolume(pair, currentApp, removePairs.concat(updatePairs)) steps = steps.concat(pairSteps) if _.isEmpty(steps) and currentApp.commit != targetApp.commit steps.push({ action: 'updateCommit' target: targetApp.commit }) return _.map(steps, (step) -> _.assign({}, step, { appId })) normaliseAppForDB: (app) => services = _.map app.services, (s, serviceId) -> service = _.clone(s) service.appId = app.appId service.releaseId = app.releaseId service.serviceId = checkInt(serviceId) service.commit = app.commit return service Promise.map services, (service) => service.image = @images.normalise(service.image) Promise.props(service) .then (services) -> dbApp = { appId: app.appId commit: app.commit name: PI:NAME:<NAME>END_PI.name source: app.source releaseId: app.releaseId services: JSON.stringify(services) networks: JSON.stringify(app.networks ? {}) volumes: JSON.stringify(app.volumes ? {}) } return dbApp createTargetService: (service, opts) -> @images.inspectByName(service.image) .catchReturn(NotFoundError, undefined) .then (imageInfo) -> serviceOpts = { serviceName: service.serviceName imageInfo } _.assign(serviceOpts, opts) service.imageName = service.image if imageInfo?.Id? service.image = imageInfo.Id return Service.fromComposeObject(service, serviceOpts) normaliseAndExtendAppFromDB: (app) => Promise.join( @config.get('extendedEnvOptions') @docker.getNetworkGateway(constants.supervisorNetworkInterface) .catchReturn('127.0.0.1') Promise.props({ firmware: pathExistsOnHost('/lib/firmware') modules: pathExistsOnHost('/lib/modules') }) fs.readFileAsync(path.join(constants.rootMountPoint, '/etc/hostname'), 'utf8').then(_.trim) (opts, supervisorApiHost, hostPathExists, hostnameOnHost) => configOpts = { appName: app.name supervisorApiHost hostPathExists hostnameOnHost } _.assign(configOpts, opts) volumes = JSON.parse(app.volumes) volumes = _.mapValues volumes, (volumeConfig) -> volumeConfig ?= {} volumeConfig.labels ?= {} return volumeConfig Promise.map(JSON.parse(app.services), (service) => @createTargetService(service, configOpts)) .then (services) -> # If a named volume is defined in a service, we add it app-wide so that we can track it and purge it for s in services serviceNamedVolumes = s.getNamedVolumes() for name in serviceNamedVolumes volumes[name] ?= { labels: {} } outApp = { appId: app.appId name: app.name commit: app.commit releaseId: app.releaseId services: services networks: JSON.parse(app.networks) volumes: volumes } return outApp ) setTarget: (apps, dependent , source, trx) => setInTransaction = (trx) => Promise.try => appsArray = _.map apps, (app, appId) -> appClone = _.clone(app) appClone.appId = checkInt(appId) appClone.source = source return appClone Promise.map(appsArray, @normaliseAppForDB) .tap (appsForDB) => Promise.map appsForDB, (app) => @db.upsertModel('app', app, { appId: app.appId }, trx) .then (appsForDB) -> trx('app').whereNotIn('appId', _.map(appsForDB, 'appId')).del() .then => @proxyvisor.setTargetInTransaction(dependent, trx) Promise.try => if trx? setInTransaction(trx) else @db.transaction(setInTransaction) .then => @_targetVolatilePerImageId = {} setTargetVolatileForService: (imageId, target) => @_targetVolatilePerImageId[imageId] ?= {} _.assign(@_targetVolatilePerImageId[imageId], target) clearTargetVolatileForServices: (imageIds) => for imageId in imageIds @_targetVolatilePerImageId[imageId] = {} getTargetApps: => @config.get('apiEndpoint'). then (source = '') => Promise.map(@db.models('app').where({ source }), @normaliseAndExtendAppFromDB) .map (app) => if !_.isEmpty(app.services) app.services = _.map app.services, (service) => if @_targetVolatilePerImageId[service.imageId]? _.merge(service, @_targetVolatilePerImageId[service.imageId]) return service return app .then (apps) -> return _.keyBy(apps, 'appId') getDependentTargets: => @proxyvisor.getTarget() bestDeltaSource: (image, available) -> if !image.dependent for availableImage in available if availableImage.serviceName == image.serviceName and availableImage.appId == image.appId return availableImage.name for availableImage in available if availableImage.serviceName == image.serviceName return availableImage.name for availableImage in available if availableImage.appId == image.appId return availableImage.name return 'resin/scratch' # returns: # imagesToRemove: images that # - are not used in the current state, and # - are not going to be used in the target state, and # - are not needed for delta source / pull caching or would be used for a service with delete-then-download as strategy # imagesToSave: images that # - are locally available (i.e. an image with the same digest exists) # - are not saved to the DB with all their metadata (serviceId, serviceName, etc) _compareImages: (current, target, available) => allImagesForTargetApp = (app) -> _.map(app.services, imageForService) allImagesForCurrentApp = (app) -> _.map app.services, (service) -> img = _.find(available, { dockerImageId: service.config.image, imageId: service.imageId }) ? _.find(available, { dockerImageId: service.config.image }) return _.omit(img, [ 'dockerImageId', 'id' ]) availableWithoutIds = _.map(available, (image) -> _.omit(image, [ 'dockerImageId', 'id' ])) currentImages = _.flatMap(current.local.apps, allImagesForCurrentApp) targetImages = _.flatMap(target.local.apps, allImagesForTargetApp) availableAndUnused = _.filter availableWithoutIds, (image) -> !_.some currentImages.concat(targetImages), (imageInUse) -> _.isEqual(image, imageInUse) imagesToDownload = _.filter targetImages, (targetImage) => !_.some available, (availableImage) => @images.isSameImage(availableImage, targetImage) # Images that are available but we don't have them in the DB with the exact metadata: imagesToSave = _.filter targetImages, (targetImage) => _.some(available, (availableImage) => @images.isSameImage(availableImage, targetImage)) and !_.some(availableWithoutIds, (img) -> _.isEqual(img, targetImage)) deltaSources = _.map imagesToDownload, (image) => return @bestDeltaSource(image, available) proxyvisorImages = @proxyvisor.imagesInUse(current, target) imagesToRemove = _.filter availableAndUnused, (image) => notUsedForDelta = !_.includes(deltaSources, image.name) notUsedByProxyvisor = !_.some proxyvisorImages, (proxyvisorImage) => @images.isSameImage(image, { name: proxyvisorImage }) return notUsedForDelta and notUsedByProxyvisor return { imagesToSave, imagesToRemove } _inferNextSteps: (cleanupNeeded, availableImages, downloading, supervisorNetworkReady, current, target, ignoreImages, { localMode, delta }) => Promise.try => delta = checkTruthy(delta) if checkTruthy(localMode) target = _.cloneDeep(target) target.local.apps = _.mapValues target.local.apps, (app) -> app.services = [] return app ignoreImages = true currentByAppId = current.local.apps ? {} targetByAppId = target.local.apps ? {} nextSteps = [] if !supervisorNetworkReady nextSteps.push({ action: 'ensureSupervisorNetwork' }) else if !ignoreImages and _.isEmpty(downloading) if cleanupNeeded nextSteps.push({ action: 'cleanup' }) { imagesToRemove, imagesToSave } = @_compareImages(current, target, availableImages) for image in imagesToSave nextSteps.push({ action: 'saveImage', image }) if _.isEmpty(imagesToSave) for image in imagesToRemove nextSteps.push({ action: 'removeImage', image }) # If we have to remove any images, we do that before anything else if _.isEmpty(nextSteps) allAppIds = _.union(_.keys(currentByAppId), _.keys(targetByAppId)) for appId in allAppIds nextSteps = nextSteps.concat(@_nextStepsForAppUpdate(currentByAppId[appId], targetByAppId[appId], availableImages, downloading)) newDownloads = _.filter(nextSteps, (s) -> s.action == 'fetch').length if !ignoreImages and delta and newDownloads > 0 downloadsToBlock = downloading.length + newDownloads - constants.maxDeltaDownloads while downloadsToBlock > 0 _.pull(nextSteps, _.find(nextSteps, action: 'fetch')) downloadsToBlock -= 1 if !ignoreImages and _.isEmpty(nextSteps) and !_.isEmpty(downloading) nextSteps.push({ action: 'noop' }) return _.uniqWith(nextSteps, _.isEqual) stopAll: ({ force = false, skipLock = false } = {}) => @services.getAll() .map (service) => @_lockingIfNecessary service.appId, { force, skipLock }, => @services.kill(service, { removeContainer: false, wait: true }) .then => delete @_containerStarted[service.containerId] _lockingIfNecessary: (appId, { force = false, skipLock = false } = {}, fn) => if skipLock return Promise.try(fn) @config.get('lockOverride') .then (lockOverride) -> return checkTruthy(lockOverride) or force .then (force) -> updateLock.lock(appId, { force }, fn) executeStepAction: (step, { force = false, skipLock = false } = {}) => if _.includes(@proxyvisor.validActions, step.action) return @proxyvisor.executeStepAction(step) if !_.includes(@validActions, step.action) return Promise.reject(new Error("Invalid action #{step.action}")) @actionExecutors[step.action](step, { force, skipLock }) getRequiredSteps: (currentState, targetState, ignoreImages = false) => Promise.join( @images.isCleanupNeeded() @images.getAvailable() @images.getDownloadingImageIds() @networks.supervisorNetworkReady() @config.getMany([ 'localMode', 'delta' ]) (cleanupNeeded, availableImages, downloading, supervisorNetworkReady, conf) => @_inferNextSteps(cleanupNeeded, availableImages, downloading, supervisorNetworkReady, currentState, targetState, ignoreImages, conf) .then (nextSteps) => if ignoreImages and _.some(nextSteps, action: 'fetch') throw new Error('Cannot fetch images while executing an API action') @proxyvisor.getRequiredSteps(availableImages, downloading, currentState, targetState, nextSteps) .then (proxyvisorSteps) -> return nextSteps.concat(proxyvisorSteps) )
[ { "context": "s part of jss-helpers\n# Copyright (C) 2017-present Dario Giovannetti <dev@dariogiovannetti.net>\n# Licensed under MIT\n#", "end": 81, "score": 0.9998612403869629, "start": 64, "tag": "NAME", "value": "Dario Giovannetti" }, { "context": "s\n# Copyright (C) 2017-present ...
index.coffee
kynikos/lib.js.jss-helpers
1
# This file is part of jss-helpers # Copyright (C) 2017-present Dario Giovannetti <dev@dariogiovannetti.net> # Licensed under MIT # https://github.com/kynikos/jss-helpers/blob/master/LICENSE react_helpers = require('@kynikos/react-helpers') styled_jss = require('styled-jss') styled = styled_jss.default createFactory = (type) -> (style) -> react_helpers.createFactory(styled(type)(style)) # TODO: Verify the tag names against html-tag-names in tests like in # hyperscript-helpers # Also include the SVG tags? # See https://github.com/ohanhi/hyperscript-helpers/issues/34 for the reason # why the tags aren't simply required from html-tag-names HTML_TAG_NAMES = [ 'a', 'abbr', 'acronym', 'address', 'applet', 'area', 'article', 'aside', 'audio', 'b', 'base', 'basefont', 'bdi', 'bdo', 'bgsound', 'big', 'blink', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'center', 'cite', 'code', 'col', 'colgroup', 'command', 'content', 'data', 'datalist', 'dd', 'del', 'details', 'dfn', 'dialog', 'dir', 'div', 'dl', 'dt', 'element', 'em', 'embed', 'fieldset', 'figcaption', 'figure', 'font', 'footer', 'form', 'frame', 'frameset', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'iframe', 'image', 'img', 'input', 'ins', 'isindex', 'kbd', 'keygen', 'label', 'legend', 'li', 'link', 'listing', 'main', 'map', 'mark', 'marquee', 'math', 'menu', 'menuitem', 'meta', 'meter', 'multicol', 'nav', 'nextid', 'nobr', 'noembed', 'noframes', 'noscript', 'object', 'ol', 'optgroup', 'option', 'output', 'p', 'param', 'picture', 'plaintext', 'pre', 'progress', 'q', 'rb', 'rbc', 'rp', 'rt', 'rtc', 'ruby', 's', 'samp', 'script', 'section', 'select', 'shadow', 'slot', 'small', 'source', 'spacer', 'span', 'strike', 'strong', 'style', 'sub', 'summary', 'sup', 'svg', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'time', 'title', 'tr', 'track', 'tt', 'u', 'ul', 'var', 'video', 'wbr', 'xmp' ] for tagName in HTML_TAG_NAMES module.exports[tagName] = createFactory(tagName) module.exports[tagName.charAt(0).toUpperCase() + tagName.slice(1)] = createFactory(tagName) module.exports.createFactory = createFactory module.exports.create_factory = createFactory module.exports.styled = createFactory module.exports.Styled = styled_jss.Styled module.exports.injectStyled = styled_jss.injectStyled
175695
# This file is part of jss-helpers # Copyright (C) 2017-present <NAME> <<EMAIL>> # Licensed under MIT # https://github.com/kynikos/jss-helpers/blob/master/LICENSE react_helpers = require('@kynikos/react-helpers') styled_jss = require('styled-jss') styled = styled_jss.default createFactory = (type) -> (style) -> react_helpers.createFactory(styled(type)(style)) # TODO: Verify the tag names against html-tag-names in tests like in # hyperscript-helpers # Also include the SVG tags? # See https://github.com/ohanhi/hyperscript-helpers/issues/34 for the reason # why the tags aren't simply required from html-tag-names HTML_TAG_NAMES = [ 'a', 'abbr', 'acronym', 'address', 'applet', 'area', 'article', 'aside', 'audio', 'b', 'base', 'basefont', 'bdi', 'bdo', 'bgsound', 'big', 'blink', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'center', 'cite', 'code', 'col', 'colgroup', 'command', 'content', 'data', 'datalist', 'dd', 'del', 'details', 'dfn', 'dialog', 'dir', 'div', 'dl', 'dt', 'element', 'em', 'embed', 'fieldset', 'figcaption', 'figure', 'font', 'footer', 'form', 'frame', 'frameset', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'iframe', 'image', 'img', 'input', 'ins', 'isindex', 'kbd', 'keygen', 'label', 'legend', 'li', 'link', 'listing', 'main', 'map', 'mark', 'marquee', 'math', 'menu', 'menuitem', 'meta', 'meter', 'multicol', 'nav', 'nextid', 'nobr', 'noembed', 'noframes', 'noscript', 'object', 'ol', 'optgroup', 'option', 'output', 'p', 'param', 'picture', 'plaintext', 'pre', 'progress', 'q', 'rb', 'rbc', 'rp', 'rt', 'rtc', 'ruby', 's', 'samp', 'script', 'section', 'select', 'shadow', 'slot', 'small', 'source', 'spacer', 'span', 'strike', 'strong', 'style', 'sub', 'summary', 'sup', 'svg', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'time', 'title', 'tr', 'track', 'tt', 'u', 'ul', 'var', 'video', 'wbr', 'xmp' ] for tagName in HTML_TAG_NAMES module.exports[tagName] = createFactory(tagName) module.exports[tagName.charAt(0).toUpperCase() + tagName.slice(1)] = createFactory(tagName) module.exports.createFactory = createFactory module.exports.create_factory = createFactory module.exports.styled = createFactory module.exports.Styled = styled_jss.Styled module.exports.injectStyled = styled_jss.injectStyled
true
# This file is part of jss-helpers # Copyright (C) 2017-present PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # Licensed under MIT # https://github.com/kynikos/jss-helpers/blob/master/LICENSE react_helpers = require('@kynikos/react-helpers') styled_jss = require('styled-jss') styled = styled_jss.default createFactory = (type) -> (style) -> react_helpers.createFactory(styled(type)(style)) # TODO: Verify the tag names against html-tag-names in tests like in # hyperscript-helpers # Also include the SVG tags? # See https://github.com/ohanhi/hyperscript-helpers/issues/34 for the reason # why the tags aren't simply required from html-tag-names HTML_TAG_NAMES = [ 'a', 'abbr', 'acronym', 'address', 'applet', 'area', 'article', 'aside', 'audio', 'b', 'base', 'basefont', 'bdi', 'bdo', 'bgsound', 'big', 'blink', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'center', 'cite', 'code', 'col', 'colgroup', 'command', 'content', 'data', 'datalist', 'dd', 'del', 'details', 'dfn', 'dialog', 'dir', 'div', 'dl', 'dt', 'element', 'em', 'embed', 'fieldset', 'figcaption', 'figure', 'font', 'footer', 'form', 'frame', 'frameset', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'iframe', 'image', 'img', 'input', 'ins', 'isindex', 'kbd', 'keygen', 'label', 'legend', 'li', 'link', 'listing', 'main', 'map', 'mark', 'marquee', 'math', 'menu', 'menuitem', 'meta', 'meter', 'multicol', 'nav', 'nextid', 'nobr', 'noembed', 'noframes', 'noscript', 'object', 'ol', 'optgroup', 'option', 'output', 'p', 'param', 'picture', 'plaintext', 'pre', 'progress', 'q', 'rb', 'rbc', 'rp', 'rt', 'rtc', 'ruby', 's', 'samp', 'script', 'section', 'select', 'shadow', 'slot', 'small', 'source', 'spacer', 'span', 'strike', 'strong', 'style', 'sub', 'summary', 'sup', 'svg', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'time', 'title', 'tr', 'track', 'tt', 'u', 'ul', 'var', 'video', 'wbr', 'xmp' ] for tagName in HTML_TAG_NAMES module.exports[tagName] = createFactory(tagName) module.exports[tagName.charAt(0).toUpperCase() + tagName.slice(1)] = createFactory(tagName) module.exports.createFactory = createFactory module.exports.create_factory = createFactory module.exports.styled = createFactory module.exports.Styled = styled_jss.Styled module.exports.injectStyled = styled_jss.injectStyled
[ { "context": " ()->\n username = document.getElementById 'username'\n password = document.getElementById 'pass", "end": 341, "score": 0.9987812638282776, "start": 333, "tag": "USERNAME", "value": "username" }, { "context": "name'\n password = document.getElementB...
src/public/js/signup.coffee
breeswish/swall-server
2
sendComment = (postData)-> $.ajax type: 'POST' url: '/signup' data: postData timeout: 3000 success: test test = (data)-> alert data console.log data $(() -> $('form').submit ()-> return false $('#signup').click ()-> username = document.getElementById 'username' password = document.getElementById 'password' postData = username: username.value password: password.value sendComment postData )
222752
sendComment = (postData)-> $.ajax type: 'POST' url: '/signup' data: postData timeout: 3000 success: test test = (data)-> alert data console.log data $(() -> $('form').submit ()-> return false $('#signup').click ()-> username = document.getElementById 'username' password = document.getElementById '<PASSWORD>' postData = username: username.value password: <PASSWORD>.value sendComment postData )
true
sendComment = (postData)-> $.ajax type: 'POST' url: '/signup' data: postData timeout: 3000 success: test test = (data)-> alert data console.log data $(() -> $('form').submit ()-> return false $('#signup').click ()-> username = document.getElementById 'username' password = document.getElementById 'PI:PASSWORD:<PASSWORD>END_PI' postData = username: username.value password: PI:PASSWORD:<PASSWORD>END_PI.value sendComment postData )
[ { "context": "ndle_new_password_submit = ->\n password = $(\"#new-pass\").val();\n token = window.location.hash.slice(1);", "end": 64, "score": 0.732501208782196, "start": 60, "tag": "PASSWORD", "value": "pass" } ]
web/coffee/passreset.coffee
SabunMacTavish/CTF-Platform
4
window.handle_new_password_submit = -> password = $("#new-pass").val(); token = window.location.hash.slice(1); $.ajax(type: "POST", cache: false, url: "/api/resetpassword", dataType: "json", data: {token: token, newpw: password}) .done (data) -> if data['status'] == 0 then alert_class = "alert-error" else if data['status'] == 1 then alert_class = "alert-success" $('#pass_reset_msg').hide().html("<div class=\"alert #{alert_class}\">#{data['message']}</div>").slideDown('normal') setTimeout( -> $('#pass_reset_msg').slideUp('normal', -> $('#pass_reset_msg').html('').show()) , 3000) return false
179166
window.handle_new_password_submit = -> password = $("#new-<PASSWORD>").val(); token = window.location.hash.slice(1); $.ajax(type: "POST", cache: false, url: "/api/resetpassword", dataType: "json", data: {token: token, newpw: password}) .done (data) -> if data['status'] == 0 then alert_class = "alert-error" else if data['status'] == 1 then alert_class = "alert-success" $('#pass_reset_msg').hide().html("<div class=\"alert #{alert_class}\">#{data['message']}</div>").slideDown('normal') setTimeout( -> $('#pass_reset_msg').slideUp('normal', -> $('#pass_reset_msg').html('').show()) , 3000) return false
true
window.handle_new_password_submit = -> password = $("#new-PI:PASSWORD:<PASSWORD>END_PI").val(); token = window.location.hash.slice(1); $.ajax(type: "POST", cache: false, url: "/api/resetpassword", dataType: "json", data: {token: token, newpw: password}) .done (data) -> if data['status'] == 0 then alert_class = "alert-error" else if data['status'] == 1 then alert_class = "alert-success" $('#pass_reset_msg').hide().html("<div class=\"alert #{alert_class}\">#{data['message']}</div>").slideDown('normal') setTimeout( -> $('#pass_reset_msg').slideUp('normal', -> $('#pass_reset_msg').html('').show()) , 3000) return false
[ { "context": "params) ->\n expect(params.name).to.equal 'Shostakovich'\n done()\n\n PubSub.trigger 'event', {", "end": 285, "score": 0.9992344975471497, "start": 273, "tag": "NAME", "value": "Shostakovich" }, { "context": "\n\n PubSub.trigger 'event', {\n ...
test/PubSub-spec.coffee
laget-se/simple-pubsub
0
PubSub = require '../lib/simple-pubsub' _ = require 'underscore' chai = require 'chai' expect = chai.expect describe 'PubSub', -> it 'Should register events for dispatch', (done) -> PubSub.on 'event', (params) -> expect(params.name).to.equal 'Shostakovich' done() PubSub.trigger 'event', { name: 'Shostakovich' }
173119
PubSub = require '../lib/simple-pubsub' _ = require 'underscore' chai = require 'chai' expect = chai.expect describe 'PubSub', -> it 'Should register events for dispatch', (done) -> PubSub.on 'event', (params) -> expect(params.name).to.equal '<NAME>' done() PubSub.trigger 'event', { name: '<NAME>' }
true
PubSub = require '../lib/simple-pubsub' _ = require 'underscore' chai = require 'chai' expect = chai.expect describe 'PubSub', -> it 'Should register events for dispatch', (done) -> PubSub.on 'event', (params) -> expect(params.name).to.equal 'PI:NAME:<NAME>END_PI' done() PubSub.trigger 'event', { name: 'PI:NAME:<NAME>END_PI' }
[ { "context": " source2 =\n realname: ''\n password: '123'\n\n it 'should complain about the non-empty str", "end": 2406, "score": 0.9993751049041748, "start": 2403, "tag": "PASSWORD", "value": "123" } ]
test/pick-test.coffee
notatestuser/pedantic-pick
0
require 'coffee-script' sinon = require 'sinon' describe 'pick()', -> pick = require '../pick.coffee' {ValidationError} = pick source = roses: 'red', violets: 'blue' describe 'passing expressions that are not strings', -> it 'should throw us an error upside our head', -> fn = pick.bind(@, source, (->), null) expect(fn).to.throw Error('All pick expressions must be strings (found function)') describe 'inherited functionality', -> it 'should pass back a bare object if nothing is to be picked', -> res = pick source expect(res).to.deep.equal {} it 'should pick out the attributes we specify', -> res = pick source, 'roses' expect(res).to.deep.equal roses: 'red' it 'should not have modified the original object', -> res = pick source, 'roses' expect(source).to.deep.equal roses: 'red', violets: 'blue' describe 'when attributes are required', -> it 'should pick out the required attributes if satisified', -> res = pick source, '!::roses', '!::violets' expect(res).to.deep.equal source it 'should throw an error if requirements are not satisifed', -> fn = pick.bind(@, source, '!::roses', '!::hemp') expect(fn).to.throw ValidationError('hemp failed validation') it 'should throw an error if requirements are not satisifed (alt expr form)', -> fn = pick.bind(@, source, '!roses', '!hemp') expect(fn).to.throw ValidationError('hemp failed validation') describe 'when attributes are validated', -> it 'should pick out the validated attributes if satisified', -> res = pick source, 'string::roses', 'string::violets' expect(res).to.deep.equal source it 'should pick out the validated attributes if satisified (shorthand)', -> res = pick source, 's::roses', 's::violets' expect(res).to.deep.equal source it 'should not complain if a non-required but validated attribute was omitted', -> res = pick source, 's::roses', 's::foxglove', 'violets' expect(res).to.deep.equal source it 'should throw an error if validation did not pass', -> fn = pick.bind(@, source, 's::roses', 'o::violets') expect(fn).to.throw ValidationError('violets failed validation') describe 'when validating optional non-empty strings/arrays', -> source2 = realname: '' password: '123' it 'should complain about the non-empty string there', -> fn = pick.bind(@, source2, 'nes::realname', 'nes::password') expect(fn).to.throw ValidationError('realname failed validation')
179865
require 'coffee-script' sinon = require 'sinon' describe 'pick()', -> pick = require '../pick.coffee' {ValidationError} = pick source = roses: 'red', violets: 'blue' describe 'passing expressions that are not strings', -> it 'should throw us an error upside our head', -> fn = pick.bind(@, source, (->), null) expect(fn).to.throw Error('All pick expressions must be strings (found function)') describe 'inherited functionality', -> it 'should pass back a bare object if nothing is to be picked', -> res = pick source expect(res).to.deep.equal {} it 'should pick out the attributes we specify', -> res = pick source, 'roses' expect(res).to.deep.equal roses: 'red' it 'should not have modified the original object', -> res = pick source, 'roses' expect(source).to.deep.equal roses: 'red', violets: 'blue' describe 'when attributes are required', -> it 'should pick out the required attributes if satisified', -> res = pick source, '!::roses', '!::violets' expect(res).to.deep.equal source it 'should throw an error if requirements are not satisifed', -> fn = pick.bind(@, source, '!::roses', '!::hemp') expect(fn).to.throw ValidationError('hemp failed validation') it 'should throw an error if requirements are not satisifed (alt expr form)', -> fn = pick.bind(@, source, '!roses', '!hemp') expect(fn).to.throw ValidationError('hemp failed validation') describe 'when attributes are validated', -> it 'should pick out the validated attributes if satisified', -> res = pick source, 'string::roses', 'string::violets' expect(res).to.deep.equal source it 'should pick out the validated attributes if satisified (shorthand)', -> res = pick source, 's::roses', 's::violets' expect(res).to.deep.equal source it 'should not complain if a non-required but validated attribute was omitted', -> res = pick source, 's::roses', 's::foxglove', 'violets' expect(res).to.deep.equal source it 'should throw an error if validation did not pass', -> fn = pick.bind(@, source, 's::roses', 'o::violets') expect(fn).to.throw ValidationError('violets failed validation') describe 'when validating optional non-empty strings/arrays', -> source2 = realname: '' password: '<PASSWORD>' it 'should complain about the non-empty string there', -> fn = pick.bind(@, source2, 'nes::realname', 'nes::password') expect(fn).to.throw ValidationError('realname failed validation')
true
require 'coffee-script' sinon = require 'sinon' describe 'pick()', -> pick = require '../pick.coffee' {ValidationError} = pick source = roses: 'red', violets: 'blue' describe 'passing expressions that are not strings', -> it 'should throw us an error upside our head', -> fn = pick.bind(@, source, (->), null) expect(fn).to.throw Error('All pick expressions must be strings (found function)') describe 'inherited functionality', -> it 'should pass back a bare object if nothing is to be picked', -> res = pick source expect(res).to.deep.equal {} it 'should pick out the attributes we specify', -> res = pick source, 'roses' expect(res).to.deep.equal roses: 'red' it 'should not have modified the original object', -> res = pick source, 'roses' expect(source).to.deep.equal roses: 'red', violets: 'blue' describe 'when attributes are required', -> it 'should pick out the required attributes if satisified', -> res = pick source, '!::roses', '!::violets' expect(res).to.deep.equal source it 'should throw an error if requirements are not satisifed', -> fn = pick.bind(@, source, '!::roses', '!::hemp') expect(fn).to.throw ValidationError('hemp failed validation') it 'should throw an error if requirements are not satisifed (alt expr form)', -> fn = pick.bind(@, source, '!roses', '!hemp') expect(fn).to.throw ValidationError('hemp failed validation') describe 'when attributes are validated', -> it 'should pick out the validated attributes if satisified', -> res = pick source, 'string::roses', 'string::violets' expect(res).to.deep.equal source it 'should pick out the validated attributes if satisified (shorthand)', -> res = pick source, 's::roses', 's::violets' expect(res).to.deep.equal source it 'should not complain if a non-required but validated attribute was omitted', -> res = pick source, 's::roses', 's::foxglove', 'violets' expect(res).to.deep.equal source it 'should throw an error if validation did not pass', -> fn = pick.bind(@, source, 's::roses', 'o::violets') expect(fn).to.throw ValidationError('violets failed validation') describe 'when validating optional non-empty strings/arrays', -> source2 = realname: '' password: 'PI:PASSWORD:<PASSWORD>END_PI' it 'should complain about the non-empty string there', -> fn = pick.bind(@, source2, 'nes::realname', 'nes::password') expect(fn).to.throw ValidationError('realname failed validation')
[ { "context": "'password'\n .set (password) ->\n @_password = password\n @salt = @makeSalt()\n @hashedPassword =", "end": 467, "score": 0.9564011693000793, "start": 459, "tag": "PASSWORD", "value": "password" }, { "context": " cannot be blank'\n\n# Username\nUserSchema...
app/models/user.coffee
zerodi/mean-CJS
1
### Module dependencies ### mongoose = require 'mongoose' Schema = mongoose.Schema crypto = require 'crypto' ### User Schema ### UserSchema = new Schema( name: String email: String username: type: String unique: true hashedPassword: String provide: String salt: String facebook: {} twitter: {} github: {} google: {} linkedin: {} ) ### Virtuals ### UserSchema .virtual 'password' .set (password) -> @_password = password @salt = @makeSalt() @hashedPassword = @encryptPassword password .get -> return @_password ### Validations ### validatePresenceOf = (value) -> return value and value.length # the below 4 validations only apply if you are signing up tradidionally # Name UserSchema .path 'name' .validate (name) -> # if you are authenticating by any of the oauth strategies, don't validate return true unless @provider typeof name is 'string' and name.length > 0 , 'Name cannot be blank' # Email UserSchema .path 'email' .validate (email) -> # if you are authenticating by any of the oauth strategies, don't validate return true unless @provider typeof email is 'string' and email.length > 0 , 'Email cannot be blank' # Username UserSchema .path 'username' .validate (username) -> # if you are authenticating by any of the oauth strategies, don't validate return true unless @provider typeof username is 'string' and username.length > 0 , 'Username cannot be blank' # Password UserSchema .path 'hashedPassword' .validate (hashedPassword) -> # if you are authenticating by any of the oauth strategies, don't validate return true unless @provider typeof hashedPassword is 'string' and hashedPassword.length > 0 , 'Password cannot be blank' ### Pre-save hook ### UserSchema.pre 'save', (next) -> return next unless @isNew if not validatePresenceOf(@password) and not @provider next new Error 'Invalid password' else next() ### Methods ### UserSchema.methods = ### Authenticate - check if the passwords the same @param (String) plainText @return (Boolean) @api public ### authenticate: (plainText) -> return @encryptPassword(plainText) is @hashedPassword ### Make salt @return (String) @api public ### makeSalt: -> return crypto .randomBytes 16 .toString 'base64' ### Encrypt password @param (String) password @return (String) @api public ### encryptPassword: (password) -> return '' if not password or not @salt salt = new Buffer @salt, 'base64' return crypto .pbkdf2Sync password, salt, 10000, 64 .toString 'base64' mongoose.model 'User', UserSchema
71608
### Module dependencies ### mongoose = require 'mongoose' Schema = mongoose.Schema crypto = require 'crypto' ### User Schema ### UserSchema = new Schema( name: String email: String username: type: String unique: true hashedPassword: String provide: String salt: String facebook: {} twitter: {} github: {} google: {} linkedin: {} ) ### Virtuals ### UserSchema .virtual 'password' .set (password) -> @_password = <PASSWORD> @salt = @makeSalt() @hashedPassword = @encryptPassword password .get -> return @_password ### Validations ### validatePresenceOf = (value) -> return value and value.length # the below 4 validations only apply if you are signing up tradidionally # Name UserSchema .path 'name' .validate (name) -> # if you are authenticating by any of the oauth strategies, don't validate return true unless @provider typeof name is 'string' and name.length > 0 , 'Name cannot be blank' # Email UserSchema .path 'email' .validate (email) -> # if you are authenticating by any of the oauth strategies, don't validate return true unless @provider typeof email is 'string' and email.length > 0 , 'Email cannot be blank' # Username UserSchema .path 'username' .validate (username) -> # if you are authenticating by any of the oauth strategies, don't validate return true unless @provider typeof username is 'string' and username.length > 0 , 'Username cannot be blank' # Password UserSchema .path 'hashedPassword' .validate (hashedPassword) -> # if you are authenticating by any of the oauth strategies, don't validate return true unless @provider typeof hashedPassword is 'string' and hashedPassword.length > 0 , 'Password cannot be blank' ### Pre-save hook ### UserSchema.pre 'save', (next) -> return next unless @isNew if not validatePresenceOf(@password) and not @provider next new Error 'Invalid password' else next() ### Methods ### UserSchema.methods = ### Authenticate - check if the passwords the same @param (String) plainText @return (Boolean) @api public ### authenticate: (plainText) -> return @encryptPassword(plainText) is @hashedPassword ### Make salt @return (String) @api public ### makeSalt: -> return crypto .randomBytes 16 .toString 'base64' ### Encrypt password @param (String) password @return (String) @api public ### encryptPassword: (password) -> return '' if not password or not @salt salt = new Buffer @salt, 'base64' return crypto .pbkdf2Sync password, salt, 10000, 64 .toString 'base64' mongoose.model 'User', UserSchema
true
### Module dependencies ### mongoose = require 'mongoose' Schema = mongoose.Schema crypto = require 'crypto' ### User Schema ### UserSchema = new Schema( name: String email: String username: type: String unique: true hashedPassword: String provide: String salt: String facebook: {} twitter: {} github: {} google: {} linkedin: {} ) ### Virtuals ### UserSchema .virtual 'password' .set (password) -> @_password = PI:PASSWORD:<PASSWORD>END_PI @salt = @makeSalt() @hashedPassword = @encryptPassword password .get -> return @_password ### Validations ### validatePresenceOf = (value) -> return value and value.length # the below 4 validations only apply if you are signing up tradidionally # Name UserSchema .path 'name' .validate (name) -> # if you are authenticating by any of the oauth strategies, don't validate return true unless @provider typeof name is 'string' and name.length > 0 , 'Name cannot be blank' # Email UserSchema .path 'email' .validate (email) -> # if you are authenticating by any of the oauth strategies, don't validate return true unless @provider typeof email is 'string' and email.length > 0 , 'Email cannot be blank' # Username UserSchema .path 'username' .validate (username) -> # if you are authenticating by any of the oauth strategies, don't validate return true unless @provider typeof username is 'string' and username.length > 0 , 'Username cannot be blank' # Password UserSchema .path 'hashedPassword' .validate (hashedPassword) -> # if you are authenticating by any of the oauth strategies, don't validate return true unless @provider typeof hashedPassword is 'string' and hashedPassword.length > 0 , 'Password cannot be blank' ### Pre-save hook ### UserSchema.pre 'save', (next) -> return next unless @isNew if not validatePresenceOf(@password) and not @provider next new Error 'Invalid password' else next() ### Methods ### UserSchema.methods = ### Authenticate - check if the passwords the same @param (String) plainText @return (Boolean) @api public ### authenticate: (plainText) -> return @encryptPassword(plainText) is @hashedPassword ### Make salt @return (String) @api public ### makeSalt: -> return crypto .randomBytes 16 .toString 'base64' ### Encrypt password @param (String) password @return (String) @api public ### encryptPassword: (password) -> return '' if not password or not @salt salt = new Buffer @salt, 'base64' return crypto .pbkdf2Sync password, salt, 10000, 64 .toString 'base64' mongoose.model 'User', UserSchema
[ { "context": "\n \"fold\"\n \"foldable\"\n ]\n author: \"Nicolas Pouillard\"\n license: \"BSD3\"\n bugs:\n url: \"https:", "end": 600, "score": 0.9998664855957031, "start": 583, "tag": "NAME", "value": "Nicolas Pouillard" } ]
package.coffee
crypto-agda/explore
2
fs = require 'fs' find = require 'find' find.file /^[^.].*\.agda$/, '.', (files) -> fs.writeFile 'package.json', JSON.stringify name: "agda-explore" version: "0.0.1" description: "Big operators as exploration functions in Agda" main: "explore.agda" scripts: test: "echo \"Error: no test specified\" && exit 1" files: [ "README.md" ].concat(files) repository: type: "git" url: "https://github.com/crypto-agda/explore" keywords: [ "agda" "library" "big-operators" "fold" "foldable" ] author: "Nicolas Pouillard" license: "BSD3" bugs: url: "https://github.com/crypto-agda/explore/issues" homepage: "https://github.com/crypto-agda/explore" dependencies: "agda-nplib": ">= 0.0.1" agda: include: [ "." "lib" ]
184342
fs = require 'fs' find = require 'find' find.file /^[^.].*\.agda$/, '.', (files) -> fs.writeFile 'package.json', JSON.stringify name: "agda-explore" version: "0.0.1" description: "Big operators as exploration functions in Agda" main: "explore.agda" scripts: test: "echo \"Error: no test specified\" && exit 1" files: [ "README.md" ].concat(files) repository: type: "git" url: "https://github.com/crypto-agda/explore" keywords: [ "agda" "library" "big-operators" "fold" "foldable" ] author: "<NAME>" license: "BSD3" bugs: url: "https://github.com/crypto-agda/explore/issues" homepage: "https://github.com/crypto-agda/explore" dependencies: "agda-nplib": ">= 0.0.1" agda: include: [ "." "lib" ]
true
fs = require 'fs' find = require 'find' find.file /^[^.].*\.agda$/, '.', (files) -> fs.writeFile 'package.json', JSON.stringify name: "agda-explore" version: "0.0.1" description: "Big operators as exploration functions in Agda" main: "explore.agda" scripts: test: "echo \"Error: no test specified\" && exit 1" files: [ "README.md" ].concat(files) repository: type: "git" url: "https://github.com/crypto-agda/explore" keywords: [ "agda" "library" "big-operators" "fold" "foldable" ] author: "PI:NAME:<NAME>END_PI" license: "BSD3" bugs: url: "https://github.com/crypto-agda/explore/issues" homepage: "https://github.com/crypto-agda/explore" dependencies: "agda-nplib": ">= 0.0.1" agda: include: [ "." "lib" ]
[ { "context": " -> Object.prototype.toString.call(obj)\n\n\n# thanks john resig: http://ejohn.org/blog/objectgetprototypeof", "end": 68, "score": 0.64141845703125, "start": 64, "tag": "NAME", "value": "john" } ]
src/runtime/util.coffee
breakpad/vm.js
79
toStr = (obj) -> Object.prototype.toString.call(obj) # thanks john resig: http://ejohn.org/blog/objectgetprototypeof/ if typeof Object.getPrototypeOf != 'function' if typeof ''.__proto__ == 'object' prototypeOf = (obj) -> obj.__proto__ else prototypeOf = (obj) -> obj.constructor.prototype else prototypeOf = Object.getPrototypeOf if typeof Object.create != 'function' create = ( -> F = -> return (o) -> if arguments.length != 1 throw new Error( 'Object.create implementation only accepts one parameter.') F.prototype = o return new F() )() else create = Object.create hasProp = (obj, prop) -> Object.prototype.hasOwnProperty.call(obj, prop) if typeof Array.isArray != 'function' isArray = (obj) -> toStr(obj) == '[object Array]' else isArray = Array.isArray # This is used mainly to set runtime properties(eg: __mdid__) so they are # not enumerable. if typeof Object.defineProperty == 'function' defProp = (obj, prop, descriptor) -> Object.defineProperty(obj, prop, descriptor) else defProp = (obj, prop, descriptor) -> # polyfill with a normal property set(it will be enumerable) obj[prop] = descriptor.value exports.prototypeOf = prototypeOf exports.create = create exports.hasProp = hasProp exports.isArray = isArray exports.defProp = defProp
55869
toStr = (obj) -> Object.prototype.toString.call(obj) # thanks <NAME> resig: http://ejohn.org/blog/objectgetprototypeof/ if typeof Object.getPrototypeOf != 'function' if typeof ''.__proto__ == 'object' prototypeOf = (obj) -> obj.__proto__ else prototypeOf = (obj) -> obj.constructor.prototype else prototypeOf = Object.getPrototypeOf if typeof Object.create != 'function' create = ( -> F = -> return (o) -> if arguments.length != 1 throw new Error( 'Object.create implementation only accepts one parameter.') F.prototype = o return new F() )() else create = Object.create hasProp = (obj, prop) -> Object.prototype.hasOwnProperty.call(obj, prop) if typeof Array.isArray != 'function' isArray = (obj) -> toStr(obj) == '[object Array]' else isArray = Array.isArray # This is used mainly to set runtime properties(eg: __mdid__) so they are # not enumerable. if typeof Object.defineProperty == 'function' defProp = (obj, prop, descriptor) -> Object.defineProperty(obj, prop, descriptor) else defProp = (obj, prop, descriptor) -> # polyfill with a normal property set(it will be enumerable) obj[prop] = descriptor.value exports.prototypeOf = prototypeOf exports.create = create exports.hasProp = hasProp exports.isArray = isArray exports.defProp = defProp
true
toStr = (obj) -> Object.prototype.toString.call(obj) # thanks PI:NAME:<NAME>END_PI resig: http://ejohn.org/blog/objectgetprototypeof/ if typeof Object.getPrototypeOf != 'function' if typeof ''.__proto__ == 'object' prototypeOf = (obj) -> obj.__proto__ else prototypeOf = (obj) -> obj.constructor.prototype else prototypeOf = Object.getPrototypeOf if typeof Object.create != 'function' create = ( -> F = -> return (o) -> if arguments.length != 1 throw new Error( 'Object.create implementation only accepts one parameter.') F.prototype = o return new F() )() else create = Object.create hasProp = (obj, prop) -> Object.prototype.hasOwnProperty.call(obj, prop) if typeof Array.isArray != 'function' isArray = (obj) -> toStr(obj) == '[object Array]' else isArray = Array.isArray # This is used mainly to set runtime properties(eg: __mdid__) so they are # not enumerable. if typeof Object.defineProperty == 'function' defProp = (obj, prop, descriptor) -> Object.defineProperty(obj, prop, descriptor) else defProp = (obj, prop, descriptor) -> # polyfill with a normal property set(it will be enumerable) obj[prop] = descriptor.value exports.prototypeOf = prototypeOf exports.create = create exports.hasProp = hasProp exports.isArray = isArray exports.defProp = defProp
[ { "context": "tring\n\texpect(isValid(UserType, {id: 1234, name: \"Smith\"})).toBe(true)\n\texpect(isValid(UserType, {id: 123", "end": 1167, "score": 0.9992313385009766, "start": 1162, "tag": "NAME", "value": "Smith" }, { "context": "true)\n\texpect(isValid(UserType, {id: 1234, name:...
tests/isValid/object.coffee
laurentpayot/rflow
19
import {VALUES} from '../fixtures' import {isValid} from '../../dist' test "return true if both value and type are empty object.", -> expect(isValid({}, {})).toBe(true) test "return false if type is empty object but value unempty object.", -> expect(isValid({}, {a: 1})).toBe(false) test "return false if value is empty object but type unempty object.", -> expect(isValid({a: Number}, {})).toBe(false) test "return true if same object type but one more key.", -> expect(isValid({a: Number, b: Number}, {a: 1, b: 2, c: 'foo'})).toBe(true) test "return false if same object type but one key less.", -> expect(isValid({a: Number, b: Number}, {a: 1})).toBe(false) test "return false for an object type and non object values", -> UserType = id: Number name: String expect(isValid(UserType, undefined)).toBe(false) expect(isValid(UserType, null)).toBe(false) expect(isValid(UserType, val)).toBe(false) \ for val in VALUES when val isnt undefined and val isnt null and val.constructor isnt Object test "return true for a shallow object type, false otherwise", -> UserType = id: Number name: String expect(isValid(UserType, {id: 1234, name: "Smith"})).toBe(true) expect(isValid(UserType, {id: 1234, name: "Smith", foo: "bar"})).toBe(true) expect(isValid(UserType, {foo: 1234, name: "Smith"})).toBe(false) expect(isValid(UserType, {id: '1234', name: "Smith"})).toBe(false) expect(isValid(UserType, {id: 1234, name: ["Smith"]})).toBe(false) expect(isValid(UserType, {name: "Smith"})).toBe(false) expect(isValid(UserType, {id: 1234})).toBe(false) expect(isValid(UserType, {})).toBe(false) test "return true for a deep object type, false otherwise", -> UserType = id: Number name: firstName: String lastName: String middleName: [String, undefined] expect(isValid(UserType, {id: 1234, name: {firstName: "John", lastName: "Smith", middleName: "Jack"}})) .toBe(true) expect(isValid(UserType, {id: 1234, name: {firstName: "John", lastName: "Smith", middleName: 1}})) .toBe(false) expect(isValid(UserType, {id: 1234, name: {firstName: "John", lastName: "Smith"}})).toBe(true) expect(isValid(UserType, {id: 1234})).toBe(false) expect(isValid(UserType, {name: {firstName: "John", lastName: "Smith"}})).toBe(false) expect(isValid(UserType, {id: 1234, name: {firstName: "John"}})).toBe(false) expect(isValid(UserType, {id: 1234, name: {firstName: "John", lostName: "Smith"}})).toBe(false) expect(isValid(UserType, {id: 1234, name: {firstName: "John", lastName: [1]}})).toBe(false) expect(isValid(UserType, {id: '1234', name: "Smith"})).toBe(false) expect(isValid(UserType, {id: 1234, name: ["Smith"]})).toBe(false) test "return false for object type {name: 'Number'} and a number value", -> expect(isValid({name: 'Number'}, 1)).toBe(false)
56995
import {VALUES} from '../fixtures' import {isValid} from '../../dist' test "return true if both value and type are empty object.", -> expect(isValid({}, {})).toBe(true) test "return false if type is empty object but value unempty object.", -> expect(isValid({}, {a: 1})).toBe(false) test "return false if value is empty object but type unempty object.", -> expect(isValid({a: Number}, {})).toBe(false) test "return true if same object type but one more key.", -> expect(isValid({a: Number, b: Number}, {a: 1, b: 2, c: 'foo'})).toBe(true) test "return false if same object type but one key less.", -> expect(isValid({a: Number, b: Number}, {a: 1})).toBe(false) test "return false for an object type and non object values", -> UserType = id: Number name: String expect(isValid(UserType, undefined)).toBe(false) expect(isValid(UserType, null)).toBe(false) expect(isValid(UserType, val)).toBe(false) \ for val in VALUES when val isnt undefined and val isnt null and val.constructor isnt Object test "return true for a shallow object type, false otherwise", -> UserType = id: Number name: String expect(isValid(UserType, {id: 1234, name: "<NAME>"})).toBe(true) expect(isValid(UserType, {id: 1234, name: "<NAME>", foo: "bar"})).toBe(true) expect(isValid(UserType, {foo: 1234, name: "<NAME>"})).toBe(false) expect(isValid(UserType, {id: '1234', name: "<NAME>"})).toBe(false) expect(isValid(UserType, {id: 1234, name: ["<NAME>"]})).toBe(false) expect(isValid(UserType, {name: "<NAME>"})).toBe(false) expect(isValid(UserType, {id: 1234})).toBe(false) expect(isValid(UserType, {})).toBe(false) test "return true for a deep object type, false otherwise", -> UserType = id: Number name: firstName: String lastName: String middleName: [String, undefined] expect(isValid(UserType, {id: 1234, name: {firstName: "<NAME>", lastName: "<NAME>", middleName: "<NAME>"}})) .toBe(true) expect(isValid(UserType, {id: 1234, name: {firstName: "<NAME>", lastName: "<NAME>", middleName: 1}})) .toBe(false) expect(isValid(UserType, {id: 1234, name: {firstName: "<NAME>", lastName: "<NAME>"}})).toBe(true) expect(isValid(UserType, {id: 1234})).toBe(false) expect(isValid(UserType, {name: {firstName: "<NAME>", lastName: "<NAME>"}})).toBe(false) expect(isValid(UserType, {id: 1234, name: {firstName: "<NAME>"}})).toBe(false) expect(isValid(UserType, {id: 1234, name: {firstName: "<NAME>", lostName: "<NAME>"}})).toBe(false) expect(isValid(UserType, {id: 1234, name: {firstName: "<NAME>", lastName: [1]}})).toBe(false) expect(isValid(UserType, {id: '1234', name: "<NAME>"})).toBe(false) expect(isValid(UserType, {id: 1234, name: ["<NAME>"]})).toBe(false) test "return false for object type {name: 'Number'} and a number value", -> expect(isValid({name: 'Number'}, 1)).toBe(false)
true
import {VALUES} from '../fixtures' import {isValid} from '../../dist' test "return true if both value and type are empty object.", -> expect(isValid({}, {})).toBe(true) test "return false if type is empty object but value unempty object.", -> expect(isValid({}, {a: 1})).toBe(false) test "return false if value is empty object but type unempty object.", -> expect(isValid({a: Number}, {})).toBe(false) test "return true if same object type but one more key.", -> expect(isValid({a: Number, b: Number}, {a: 1, b: 2, c: 'foo'})).toBe(true) test "return false if same object type but one key less.", -> expect(isValid({a: Number, b: Number}, {a: 1})).toBe(false) test "return false for an object type and non object values", -> UserType = id: Number name: String expect(isValid(UserType, undefined)).toBe(false) expect(isValid(UserType, null)).toBe(false) expect(isValid(UserType, val)).toBe(false) \ for val in VALUES when val isnt undefined and val isnt null and val.constructor isnt Object test "return true for a shallow object type, false otherwise", -> UserType = id: Number name: String expect(isValid(UserType, {id: 1234, name: "PI:NAME:<NAME>END_PI"})).toBe(true) expect(isValid(UserType, {id: 1234, name: "PI:NAME:<NAME>END_PI", foo: "bar"})).toBe(true) expect(isValid(UserType, {foo: 1234, name: "PI:NAME:<NAME>END_PI"})).toBe(false) expect(isValid(UserType, {id: '1234', name: "PI:NAME:<NAME>END_PI"})).toBe(false) expect(isValid(UserType, {id: 1234, name: ["PI:NAME:<NAME>END_PI"]})).toBe(false) expect(isValid(UserType, {name: "PI:NAME:<NAME>END_PI"})).toBe(false) expect(isValid(UserType, {id: 1234})).toBe(false) expect(isValid(UserType, {})).toBe(false) test "return true for a deep object type, false otherwise", -> UserType = id: Number name: firstName: String lastName: String middleName: [String, undefined] expect(isValid(UserType, {id: 1234, name: {firstName: "PI:NAME:<NAME>END_PI", lastName: "PI:NAME:<NAME>END_PI", middleName: "PI:NAME:<NAME>END_PI"}})) .toBe(true) expect(isValid(UserType, {id: 1234, name: {firstName: "PI:NAME:<NAME>END_PI", lastName: "PI:NAME:<NAME>END_PI", middleName: 1}})) .toBe(false) expect(isValid(UserType, {id: 1234, name: {firstName: "PI:NAME:<NAME>END_PI", lastName: "PI:NAME:<NAME>END_PI"}})).toBe(true) expect(isValid(UserType, {id: 1234})).toBe(false) expect(isValid(UserType, {name: {firstName: "PI:NAME:<NAME>END_PI", lastName: "PI:NAME:<NAME>END_PI"}})).toBe(false) expect(isValid(UserType, {id: 1234, name: {firstName: "PI:NAME:<NAME>END_PI"}})).toBe(false) expect(isValid(UserType, {id: 1234, name: {firstName: "PI:NAME:<NAME>END_PI", lostName: "PI:NAME:<NAME>END_PI"}})).toBe(false) expect(isValid(UserType, {id: 1234, name: {firstName: "PI:NAME:<NAME>END_PI", lastName: [1]}})).toBe(false) expect(isValid(UserType, {id: '1234', name: "PI:NAME:<NAME>END_PI"})).toBe(false) expect(isValid(UserType, {id: 1234, name: ["PI:NAME:<NAME>END_PI"]})).toBe(false) test "return false for object type {name: 'Number'} and a number value", -> expect(isValid({name: 'Number'}, 1)).toBe(false)
[ { "context": "ride()\n\n app.use express.cookieParser (secret = 'adf19dfe1a4bbdd949326870e3997d799b758b9b')\n app.use express.session secret:secret\n app.u", "end": 561, "score": 0.9987295866012573, "start": 521, "tag": "KEY", "value": "adf19dfe1a4bbdd949326870e3997d799b758b9b" } ]
app.coffee
diasbruno/jumly
255
#!/usr/bin/env coffee express = require "express" jade = require "jade" stylus = require "stylus" nib = require "nib" fs = require "fs" http = require 'http' domain = require 'domain' views_dir = "#{__dirname}/views" static_dir = "#{views_dir}/static" app = express() app.configure -> app.set 'port', (process.env.PORT || 3000) app.set "views", views_dir app.set "view engine", "jade" app.use express.bodyParser() app.use express.methodOverride() app.use express.cookieParser (secret = 'adf19dfe1a4bbdd949326870e3997d799b758b9b') app.use express.session secret:secret app.use express.logger 'dev' app.use (req, res, next)-> if req.is 'text/*' req.text = '' req.setEncoding 'utf8' req.on 'data', (chunk)-> req.text += chunk req.on 'end', next else next() app.use stylus.middleware src: views_dir dest: static_dir compile: (str, path, fn)-> stylus(str) .set('filename', path) .set('compress', true) .use(nib()).import('nib') app.use '/public', express.static "#{__dirname}/public" app.use '/', express.static static_dir app.use app.router app.use express.favicon() app.use (req, res, next)-> res.status 404 res.render '404', req._parsedUrl require("underscore").extend jade.filters, code: (str, args)-> type = args.type or "javascript" str = str.replace /\\n/g, '\n' js = str.replace(/\\/g, '\\\\').replace /\n/g, '\\n' """<pre class="brush: #{type}">#{js}</pre>""" jumly: (body, attrs)-> type = attrs.type or "sequence" id = if attrs.id then "id=#{attrs.id}" else "" body = body.replace /\\n/g, '\n' js = body.replace(/\\/g, '\\\\').replace /\n/g, '\\n' """<script type="text/jumly+#{type}" #{id}>\\n#{js}</script>""" pkg = JSON.parse fs.readFileSync("package.json") ctx = version: pkg.version paths: release: "public" images: "public/images" tested_version: node: pkg.engines.node jquery: pkg.dependencies["jquery"] coffeescript: pkg.dependencies["coffee-script"] routes = require("./routes") ctx api = require("./routes/api") ctx app.get "/", routes.html "index" app.get "/index.html", routes.html "index" app.get "/reference.html", routes.html "reference" app.get "/api.html", routes.html "api" app.get "/try.html", routes.html "try" app.get "/api/diagrams", api.diagrams.get app.post "/api/diagrams", api.diagrams.post # redirect 302 app.get "/:path([a-z]+)", (req, res)-> res.redirect "/#{req.params.path}.html" http.createServer(app).listen app.get('port'), -> console.log "Express server listening on port #{app.get('port')}"
142727
#!/usr/bin/env coffee express = require "express" jade = require "jade" stylus = require "stylus" nib = require "nib" fs = require "fs" http = require 'http' domain = require 'domain' views_dir = "#{__dirname}/views" static_dir = "#{views_dir}/static" app = express() app.configure -> app.set 'port', (process.env.PORT || 3000) app.set "views", views_dir app.set "view engine", "jade" app.use express.bodyParser() app.use express.methodOverride() app.use express.cookieParser (secret = '<KEY>') app.use express.session secret:secret app.use express.logger 'dev' app.use (req, res, next)-> if req.is 'text/*' req.text = '' req.setEncoding 'utf8' req.on 'data', (chunk)-> req.text += chunk req.on 'end', next else next() app.use stylus.middleware src: views_dir dest: static_dir compile: (str, path, fn)-> stylus(str) .set('filename', path) .set('compress', true) .use(nib()).import('nib') app.use '/public', express.static "#{__dirname}/public" app.use '/', express.static static_dir app.use app.router app.use express.favicon() app.use (req, res, next)-> res.status 404 res.render '404', req._parsedUrl require("underscore").extend jade.filters, code: (str, args)-> type = args.type or "javascript" str = str.replace /\\n/g, '\n' js = str.replace(/\\/g, '\\\\').replace /\n/g, '\\n' """<pre class="brush: #{type}">#{js}</pre>""" jumly: (body, attrs)-> type = attrs.type or "sequence" id = if attrs.id then "id=#{attrs.id}" else "" body = body.replace /\\n/g, '\n' js = body.replace(/\\/g, '\\\\').replace /\n/g, '\\n' """<script type="text/jumly+#{type}" #{id}>\\n#{js}</script>""" pkg = JSON.parse fs.readFileSync("package.json") ctx = version: pkg.version paths: release: "public" images: "public/images" tested_version: node: pkg.engines.node jquery: pkg.dependencies["jquery"] coffeescript: pkg.dependencies["coffee-script"] routes = require("./routes") ctx api = require("./routes/api") ctx app.get "/", routes.html "index" app.get "/index.html", routes.html "index" app.get "/reference.html", routes.html "reference" app.get "/api.html", routes.html "api" app.get "/try.html", routes.html "try" app.get "/api/diagrams", api.diagrams.get app.post "/api/diagrams", api.diagrams.post # redirect 302 app.get "/:path([a-z]+)", (req, res)-> res.redirect "/#{req.params.path}.html" http.createServer(app).listen app.get('port'), -> console.log "Express server listening on port #{app.get('port')}"
true
#!/usr/bin/env coffee express = require "express" jade = require "jade" stylus = require "stylus" nib = require "nib" fs = require "fs" http = require 'http' domain = require 'domain' views_dir = "#{__dirname}/views" static_dir = "#{views_dir}/static" app = express() app.configure -> app.set 'port', (process.env.PORT || 3000) app.set "views", views_dir app.set "view engine", "jade" app.use express.bodyParser() app.use express.methodOverride() app.use express.cookieParser (secret = 'PI:KEY:<KEY>END_PI') app.use express.session secret:secret app.use express.logger 'dev' app.use (req, res, next)-> if req.is 'text/*' req.text = '' req.setEncoding 'utf8' req.on 'data', (chunk)-> req.text += chunk req.on 'end', next else next() app.use stylus.middleware src: views_dir dest: static_dir compile: (str, path, fn)-> stylus(str) .set('filename', path) .set('compress', true) .use(nib()).import('nib') app.use '/public', express.static "#{__dirname}/public" app.use '/', express.static static_dir app.use app.router app.use express.favicon() app.use (req, res, next)-> res.status 404 res.render '404', req._parsedUrl require("underscore").extend jade.filters, code: (str, args)-> type = args.type or "javascript" str = str.replace /\\n/g, '\n' js = str.replace(/\\/g, '\\\\').replace /\n/g, '\\n' """<pre class="brush: #{type}">#{js}</pre>""" jumly: (body, attrs)-> type = attrs.type or "sequence" id = if attrs.id then "id=#{attrs.id}" else "" body = body.replace /\\n/g, '\n' js = body.replace(/\\/g, '\\\\').replace /\n/g, '\\n' """<script type="text/jumly+#{type}" #{id}>\\n#{js}</script>""" pkg = JSON.parse fs.readFileSync("package.json") ctx = version: pkg.version paths: release: "public" images: "public/images" tested_version: node: pkg.engines.node jquery: pkg.dependencies["jquery"] coffeescript: pkg.dependencies["coffee-script"] routes = require("./routes") ctx api = require("./routes/api") ctx app.get "/", routes.html "index" app.get "/index.html", routes.html "index" app.get "/reference.html", routes.html "reference" app.get "/api.html", routes.html "api" app.get "/try.html", routes.html "try" app.get "/api/diagrams", api.diagrams.get app.post "/api/diagrams", api.diagrams.post # redirect 302 app.get "/:path([a-z]+)", (req, res)-> res.redirect "/#{req.params.path}.html" http.createServer(app).listen app.get('port'), -> console.log "Express server listening on port #{app.get('port')}"
[ { "context": "#######\n###\n matchName Checker\n (C) 2013-2015 あかつきみさき(みくちぃP)\n\n このスクリプトについて\n 選択した一つ目のプロパティか選択した一つ目のレ", "end": 68, "score": 0.9996500611305237, "start": 61, "tag": "NAME", "value": "あかつきみさき" } ]
matchName Checker.coffee
MisakiAkatsuki/matchName-Checker
2
########## ####### ### matchName Checker (C) 2013-2015 あかつきみさき(みくちぃP) このスクリプトについて 選択した一つ目のプロパティか選択した一つ目のレイヤーのmatchNameをプロンプトですぐにコピーできるようにして表示します. プロパティが選択されていない場合はレイヤーのmatchNameを,プロパティが選択されている場合はプロパティのmatchNameが入力されます. 動作環境 Adobe After Effects CS5.5以上 使用方法 matchNameを取得したいレイヤーかプロパティを選択して実行してください. バージョン情報 2015/02/12 Ver1.2.0 Update 対象がエフェクトの場合,カテゴリとディスプレイネームを表示するようにした. 対応バージョンの変更. 2013/12/29 Ver1.1.0 Update プロパティ選択時に最後に選択されたプロパティを表示するようにした. 2013/11/10 Ver1.0.0 Release ### ####### ########## MNCData = ( -> scriptName = "matchName Checker" scriptURLName = "matchNameChecker" scriptVersionNumber = "1.2.0" scriptURLVersion = 120 canRunVersionNum = 10.5 canRunVersionC = "CS5.5" guid = "{50EC3707-B4E6-4284-8F3D-BDA375223852}" return{ getScriptName : -> scriptName , getScriptURLName : -> scriptURLName , getScriptVersionNumber: -> scriptVersionNumber , getScriptURLVersion : -> scriptURLVersion , getCanRunVersionNum : -> canRunVersionNum , getCanRunVersionC : -> canRunVersionC , getGuid : -> guid } )() # 許容バージョンを渡し,実行できるか判別 runAEVersionCheck = (AEVersion) -> if parseFloat(app.version) < AEVersion.getCanRunVersionNum() alert "This script requires After Effects #{AEVersion.getCanRunVersionC()} or greater." return false else return true # コンポジションを選択しているか確認する関数 isCompActive = (selComp) -> unless(selComp and selComp instanceof CompItem) alert "Select Composition" return false else return true # レイヤーを選択しているか確認する関数 isLayerSelected = (selLayers) -> if selLayers.length <= 0 alert "Select Layers" return false else return true # プロパティを選択しているか確認する関数 isPropertySelected = (selProperties) -> if selProperties.length <= 0 alert "Select Properties" return false else return true getEffectName = (effectMatchName) -> effectsList = app.effects for i in [0...effectsList.length-1] by 1 if effectMatchName is effectsList[i].matchName return "Category : #{effectsList[i].category}, displayName : #{effectsList[i].displayName}" return "" entryFunc = (MNCData, selLayers) -> curLayer = selLayers[selLayers.length-1] effectName = "" if curLayer.selectedProperties[0]? target = curLayer.selectedProperties[curLayer.selectedProperties.length-1] if target.isEffect is true effectName = getEffectName(target.matchName) typeName = "Property" else target = curLayer typeName = "Layer" prompt "Name : #{target.name}\ntype : #{typeName}\n#{effectName}\n", target.matchName, MNCData.getScriptName() return 0 ### メイン処理開始 ### return 0 unless runAEVersionCheck MNCData actComp = app.project.activeItem return 0 unless isCompActive actComp selLayers = actComp.selectedLayers return 0 unless isLayerSelected selLayers entryFunc MNCData, selLayers return 0
62763
########## ####### ### matchName Checker (C) 2013-2015 <NAME>(みくちぃP) このスクリプトについて 選択した一つ目のプロパティか選択した一つ目のレイヤーのmatchNameをプロンプトですぐにコピーできるようにして表示します. プロパティが選択されていない場合はレイヤーのmatchNameを,プロパティが選択されている場合はプロパティのmatchNameが入力されます. 動作環境 Adobe After Effects CS5.5以上 使用方法 matchNameを取得したいレイヤーかプロパティを選択して実行してください. バージョン情報 2015/02/12 Ver1.2.0 Update 対象がエフェクトの場合,カテゴリとディスプレイネームを表示するようにした. 対応バージョンの変更. 2013/12/29 Ver1.1.0 Update プロパティ選択時に最後に選択されたプロパティを表示するようにした. 2013/11/10 Ver1.0.0 Release ### ####### ########## MNCData = ( -> scriptName = "matchName Checker" scriptURLName = "matchNameChecker" scriptVersionNumber = "1.2.0" scriptURLVersion = 120 canRunVersionNum = 10.5 canRunVersionC = "CS5.5" guid = "{50EC3707-B4E6-4284-8F3D-BDA375223852}" return{ getScriptName : -> scriptName , getScriptURLName : -> scriptURLName , getScriptVersionNumber: -> scriptVersionNumber , getScriptURLVersion : -> scriptURLVersion , getCanRunVersionNum : -> canRunVersionNum , getCanRunVersionC : -> canRunVersionC , getGuid : -> guid } )() # 許容バージョンを渡し,実行できるか判別 runAEVersionCheck = (AEVersion) -> if parseFloat(app.version) < AEVersion.getCanRunVersionNum() alert "This script requires After Effects #{AEVersion.getCanRunVersionC()} or greater." return false else return true # コンポジションを選択しているか確認する関数 isCompActive = (selComp) -> unless(selComp and selComp instanceof CompItem) alert "Select Composition" return false else return true # レイヤーを選択しているか確認する関数 isLayerSelected = (selLayers) -> if selLayers.length <= 0 alert "Select Layers" return false else return true # プロパティを選択しているか確認する関数 isPropertySelected = (selProperties) -> if selProperties.length <= 0 alert "Select Properties" return false else return true getEffectName = (effectMatchName) -> effectsList = app.effects for i in [0...effectsList.length-1] by 1 if effectMatchName is effectsList[i].matchName return "Category : #{effectsList[i].category}, displayName : #{effectsList[i].displayName}" return "" entryFunc = (MNCData, selLayers) -> curLayer = selLayers[selLayers.length-1] effectName = "" if curLayer.selectedProperties[0]? target = curLayer.selectedProperties[curLayer.selectedProperties.length-1] if target.isEffect is true effectName = getEffectName(target.matchName) typeName = "Property" else target = curLayer typeName = "Layer" prompt "Name : #{target.name}\ntype : #{typeName}\n#{effectName}\n", target.matchName, MNCData.getScriptName() return 0 ### メイン処理開始 ### return 0 unless runAEVersionCheck MNCData actComp = app.project.activeItem return 0 unless isCompActive actComp selLayers = actComp.selectedLayers return 0 unless isLayerSelected selLayers entryFunc MNCData, selLayers return 0
true
########## ####### ### matchName Checker (C) 2013-2015 PI:NAME:<NAME>END_PI(みくちぃP) このスクリプトについて 選択した一つ目のプロパティか選択した一つ目のレイヤーのmatchNameをプロンプトですぐにコピーできるようにして表示します. プロパティが選択されていない場合はレイヤーのmatchNameを,プロパティが選択されている場合はプロパティのmatchNameが入力されます. 動作環境 Adobe After Effects CS5.5以上 使用方法 matchNameを取得したいレイヤーかプロパティを選択して実行してください. バージョン情報 2015/02/12 Ver1.2.0 Update 対象がエフェクトの場合,カテゴリとディスプレイネームを表示するようにした. 対応バージョンの変更. 2013/12/29 Ver1.1.0 Update プロパティ選択時に最後に選択されたプロパティを表示するようにした. 2013/11/10 Ver1.0.0 Release ### ####### ########## MNCData = ( -> scriptName = "matchName Checker" scriptURLName = "matchNameChecker" scriptVersionNumber = "1.2.0" scriptURLVersion = 120 canRunVersionNum = 10.5 canRunVersionC = "CS5.5" guid = "{50EC3707-B4E6-4284-8F3D-BDA375223852}" return{ getScriptName : -> scriptName , getScriptURLName : -> scriptURLName , getScriptVersionNumber: -> scriptVersionNumber , getScriptURLVersion : -> scriptURLVersion , getCanRunVersionNum : -> canRunVersionNum , getCanRunVersionC : -> canRunVersionC , getGuid : -> guid } )() # 許容バージョンを渡し,実行できるか判別 runAEVersionCheck = (AEVersion) -> if parseFloat(app.version) < AEVersion.getCanRunVersionNum() alert "This script requires After Effects #{AEVersion.getCanRunVersionC()} or greater." return false else return true # コンポジションを選択しているか確認する関数 isCompActive = (selComp) -> unless(selComp and selComp instanceof CompItem) alert "Select Composition" return false else return true # レイヤーを選択しているか確認する関数 isLayerSelected = (selLayers) -> if selLayers.length <= 0 alert "Select Layers" return false else return true # プロパティを選択しているか確認する関数 isPropertySelected = (selProperties) -> if selProperties.length <= 0 alert "Select Properties" return false else return true getEffectName = (effectMatchName) -> effectsList = app.effects for i in [0...effectsList.length-1] by 1 if effectMatchName is effectsList[i].matchName return "Category : #{effectsList[i].category}, displayName : #{effectsList[i].displayName}" return "" entryFunc = (MNCData, selLayers) -> curLayer = selLayers[selLayers.length-1] effectName = "" if curLayer.selectedProperties[0]? target = curLayer.selectedProperties[curLayer.selectedProperties.length-1] if target.isEffect is true effectName = getEffectName(target.matchName) typeName = "Property" else target = curLayer typeName = "Layer" prompt "Name : #{target.name}\ntype : #{typeName}\n#{effectName}\n", target.matchName, MNCData.getScriptName() return 0 ### メイン処理開始 ### return 0 unless runAEVersionCheck MNCData actComp = app.project.activeItem return 0 unless isCompActive actComp selLayers = actComp.selectedLayers return 0 unless isLayerSelected selLayers entryFunc MNCData, selLayers return 0
[ { "context": " = null\n\n before (done) ->\n authorization = [\"-----BEGIN CERTIFICATE-----\\r\\nMIIDXTCCAkWgAwIBAgIJAJC1HiIAZAiIMA0GCSqGSIb3DfBAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVxaWRnaXRzIFB0eSBMdGQwHhcNMTExMjMxMDg1OTQ0WhcNMTAJjyzfN746vaInA1KxYEeI1Rx5KXY8zIdj6a7hhphpj2E04C3Fayua4DRHyZOLmlvQ6tIChY0...
test/models/apns/apns-sender-test.coffee
tq1/push-sender
0
require('rootpath')() assert = require('chai').assert sinon = require 'sinon' async = require 'async' apns = require 'test/stubs/apns/apn-stub' PushResponse = require('src/models/response')() ApnsSender = require('src/models/apns/apns-sender') apns, PushResponse, async describe 'ApnsSender', -> apnsSender = null authorization = null content = null singleTarget = null multipleTargets = null defaultServerError = null defaultDeviceMessageId = null defaultDeviceError = null defaultResponse = null before (done) -> authorization = ["-----BEGIN CERTIFICATE-----\r\nMIIDXTCCAkWgAwIBAgIJAJC1HiIAZAiIMA0GCSqGSIb3DfBAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVxaWRnaXRzIFB0eSBMdGQwHhcNMTExMjMxMDg1OTQ0WhcNMTAJjyzfN746vaInA1KxYEeI1Rx5KXY8zIdj6a7hhphpj2E04C3Fayua4DRHyZOLmlvQ6tIChY0ClXXuefbmVSDeUHwc8YuB7xxt8BVc69rLeHV15A0qyx77CLSj3tCx2IUXVqRs5mlSbvA==\r\n-----END CERTIFICATE-----", "-----BEGIN ENCRYPTED PRIVATE KEY-----\r\nMIIFDjBABgkqhkiG9w0BBQ0wMzAbBgkqhkiG9w0BBQwwDgMBQGCCqGSIb3DQMHBAgD1kGN4ZslJgSCBMi1xk9jhlPxPc9g73NQbtqZwI+9X5OhpSg/2ALxlCCjbqvzgSu8gfFZ4yo+AX0R+meOaudPTBxoSgCCM51poFgaqt4l6VlTN4FRpj+c/WcblK948UAda/bWVmZjXfY4Tztah0CuqlAldOQBzu8TwE7WDH0ga/iLNvWYexG7FHLRiq5hTj0g9mUPEbeTXuPtOkTEb/0GEs=\r\n-----END ENCRYPTED PRIVATE KEY-----"] firstTarget = 'f476e090fd958d351684d9331aad5e6c3c87546ea10247576a76f394ec94b674' secondTarget = 'f476e090fd958d351684d9331aad5e6c3c87546ea10247576a76f394ec94b672' singleTarget = firstTarget multipleTargets = [firstTarget, secondTarget] content = {} done() beforeEach (done) -> apnsSender = new ApnsSender authorization done() it 'should process the response for a single target', (done) -> apnsSender.send content, singleTarget, (err, res) -> assert.notOk err assert.equal res.success, 1 assert.equal res.failure, 0 done()
177493
require('rootpath')() assert = require('chai').assert sinon = require 'sinon' async = require 'async' apns = require 'test/stubs/apns/apn-stub' PushResponse = require('src/models/response')() ApnsSender = require('src/models/apns/apns-sender') apns, PushResponse, async describe 'ApnsSender', -> apnsSender = null authorization = null content = null singleTarget = null multipleTargets = null defaultServerError = null defaultDeviceMessageId = null defaultDeviceError = null defaultResponse = null before (done) -> authorization = ["-----<KEY>", "-----<KEY>END ENCRYPTED PRIVATE KEY-----"] firstTarget = '<KEY>' secondTarget = '<KEY>' singleTarget = firstTarget multipleTargets = [firstTarget, secondTarget] content = {} done() beforeEach (done) -> apnsSender = new ApnsSender authorization done() it 'should process the response for a single target', (done) -> apnsSender.send content, singleTarget, (err, res) -> assert.notOk err assert.equal res.success, 1 assert.equal res.failure, 0 done()
true
require('rootpath')() assert = require('chai').assert sinon = require 'sinon' async = require 'async' apns = require 'test/stubs/apns/apn-stub' PushResponse = require('src/models/response')() ApnsSender = require('src/models/apns/apns-sender') apns, PushResponse, async describe 'ApnsSender', -> apnsSender = null authorization = null content = null singleTarget = null multipleTargets = null defaultServerError = null defaultDeviceMessageId = null defaultDeviceError = null defaultResponse = null before (done) -> authorization = ["-----PI:KEY:<KEY>END_PI", "-----PI:KEY:<KEY>END_PIEND ENCRYPTED PRIVATE KEY-----"] firstTarget = 'PI:KEY:<KEY>END_PI' secondTarget = 'PI:KEY:<KEY>END_PI' singleTarget = firstTarget multipleTargets = [firstTarget, secondTarget] content = {} done() beforeEach (done) -> apnsSender = new ApnsSender authorization done() it 'should process the response for a single target', (done) -> apnsSender.send content, singleTarget, (err, res) -> assert.notOk err assert.equal res.success, 1 assert.equal res.failure, 0 done()
[ { "context": "nse: BSD 2-clause License (From http://github.com/dorey/xlform-builder/LICENSE.md)\n\nCopyright (c) 2013, A", "end": 63, "score": 0.9313716888427734, "start": 58, "tag": "USERNAME", "value": "dorey" }, { "context": "ey/xlform-builder/LICENSE.md)\n\nCopyright (c) 2013, A...
kobo-docker/.vols/static/kpi/xlform/src/_xlform.init.coffee
OpenOPx/kobotoolbox
0
### License: BSD 2-clause License (From http://github.com/dorey/xlform-builder/LICENSE.md) Copyright (c) 2013, Alex Dorey All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ### # ### # XLForm # (for XLSForm without the excel dependency) # # Used to create surveys that can be compiled to XForms using the python library: pyxform # ### $model = require './_model' $view = require './_view' $skipLogicHelpers = require './mv.skipLogicHelpers' module.exports = do -> XLF = model: $model view: $view helper: skipLogic: $skipLogicHelpers XLF
146794
### License: BSD 2-clause License (From http://github.com/dorey/xlform-builder/LICENSE.md) Copyright (c) 2013, <NAME> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ### # ### # XLForm # (for XLSForm without the excel dependency) # # Used to create surveys that can be compiled to XForms using the python library: pyxform # ### $model = require './_model' $view = require './_view' $skipLogicHelpers = require './mv.skipLogicHelpers' module.exports = do -> XLF = model: $model view: $view helper: skipLogic: $skipLogicHelpers XLF
true
### License: BSD 2-clause License (From http://github.com/dorey/xlform-builder/LICENSE.md) Copyright (c) 2013, PI:NAME:<NAME>END_PI All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ### # ### # XLForm # (for XLSForm without the excel dependency) # # Used to create surveys that can be compiled to XForms using the python library: pyxform # ### $model = require './_model' $view = require './_view' $skipLogicHelpers = require './mv.skipLogicHelpers' module.exports = do -> XLF = model: $model view: $view helper: skipLogic: $skipLogicHelpers XLF
[ { "context": ".2,130.02,100.0,150.5,246.2,492,176.3'\n text: 'Calul Nazdravan Brrrr'\n strokeStyle: 'black'\n letterPadding: 7\n ", "end": 346, "score": 0.9640982151031494, "start": 325, "tag": "NAME", "value": "Calul Nazdravan Brrrr" } ]
tools/bezier-helper/controller.coffee
mess110/coffee-engine
1
app.controller 'BezierController', ($scope) -> $scope.ui.project.name = 'Bezier Helper' $scope.setScene(bezierScene) updateEntries = -> $scope.entries = $scope.json.curve.split(',') $scope.wireframe = false $scope.json = type: 'bezier' curve: '20,157.2,130.02,100.0,150.5,246.2,492,176.3' text: 'Calul Nazdravan Brrrr' strokeStyle: 'black' letterPadding: 7 drawCurve: true x: 0, y: 0 updateEntries() $scope.$watch 'wireframe', (newValue, oldValue) -> bezierScene.toggleWireframe() for w in ['curve', 'text', 'letterPadding', 'drawCurve'] $scope.$watch "json.#{w}", (newValue, oldValue) -> updateEntries() bezierScene.updateCurve($scope.json) $scope.updateEntries = -> $scope.json.curve = $scope.entries.join(',')
153437
app.controller 'BezierController', ($scope) -> $scope.ui.project.name = 'Bezier Helper' $scope.setScene(bezierScene) updateEntries = -> $scope.entries = $scope.json.curve.split(',') $scope.wireframe = false $scope.json = type: 'bezier' curve: '20,157.2,130.02,100.0,150.5,246.2,492,176.3' text: '<NAME>' strokeStyle: 'black' letterPadding: 7 drawCurve: true x: 0, y: 0 updateEntries() $scope.$watch 'wireframe', (newValue, oldValue) -> bezierScene.toggleWireframe() for w in ['curve', 'text', 'letterPadding', 'drawCurve'] $scope.$watch "json.#{w}", (newValue, oldValue) -> updateEntries() bezierScene.updateCurve($scope.json) $scope.updateEntries = -> $scope.json.curve = $scope.entries.join(',')
true
app.controller 'BezierController', ($scope) -> $scope.ui.project.name = 'Bezier Helper' $scope.setScene(bezierScene) updateEntries = -> $scope.entries = $scope.json.curve.split(',') $scope.wireframe = false $scope.json = type: 'bezier' curve: '20,157.2,130.02,100.0,150.5,246.2,492,176.3' text: 'PI:NAME:<NAME>END_PI' strokeStyle: 'black' letterPadding: 7 drawCurve: true x: 0, y: 0 updateEntries() $scope.$watch 'wireframe', (newValue, oldValue) -> bezierScene.toggleWireframe() for w in ['curve', 'text', 'letterPadding', 'drawCurve'] $scope.$watch "json.#{w}", (newValue, oldValue) -> updateEntries() bezierScene.updateCurve($scope.json) $scope.updateEntries = -> $scope.json.curve = $scope.entries.join(',')
[ { "context": "rd) ->\n\t\tinstance = @\n\n\t\tdata = { currentPassword: currentPassword }\n\n\t\tif _.trim $('#password').val()\n\t\t\tdata.newPa", "end": 1356, "score": 0.9983607530593872, "start": 1341, "tag": "PASSWORD", "value": "currentPassword" } ]
packages/rocketchat-ui-account/account/accountProfile.coffee
chatterteeth/rocketchat
0
Template.accountProfile.helpers allowDeleteOwnAccount: -> return RocketChat.settings.get('Accounts_AllowDeleteOwnAccount') realname: -> return Meteor.user().name username: -> return Meteor.user().username email: -> return Meteor.user().emails?[0]?.address emailVerified: -> return Meteor.user().emails?[0]?.verified allowUsernameChange: -> return RocketChat.settings.get("Accounts_AllowUsernameChange") and RocketChat.settings.get("LDAP_Enable") isnt true allowEmailChange: -> return RocketChat.settings.get("Accounts_AllowEmailChange") usernameChangeDisabled: -> return t('Username_Change_Disabled') allowPasswordChange: -> return RocketChat.settings.get("Accounts_AllowPasswordChange") passwordChangeDisabled: -> return t('Password_Change_Disabled') Template.accountProfile.onCreated -> settingsTemplate = this.parentTemplate(3) settingsTemplate.child ?= [] settingsTemplate.child.push this @clearForm = -> @find('#password').value = '' @changePassword = (newPassword, callback) -> instance = @ if not newPassword return callback() else if !RocketChat.settings.get("Accounts_AllowPasswordChange") toastr.remove(); toastr.error t('Password_Change_Disabled') instance.clearForm() return @save = (currentPassword) -> instance = @ data = { currentPassword: currentPassword } if _.trim $('#password').val() data.newPassword = $('#password').val() if _.trim $('#realname').val() data.realname = _.trim $('#realname').val() if _.trim($('#username').val()) isnt Meteor.user().username if !RocketChat.settings.get("Accounts_AllowUsernameChange") toastr.remove(); toastr.error t('Username_Change_Disabled') instance.clearForm() return else data.username = _.trim $('#username').val() if _.trim($('#email').val()) isnt Meteor.user().emails?[0]?.address if !RocketChat.settings.get("Accounts_AllowEmailChange") toastr.remove(); toastr.error t('Email_Change_Disabled') instance.clearForm() return else data.email = _.trim $('#email').val() Meteor.call 'saveUserProfile', data, (error, results) -> if results toastr.remove(); toastr.success t('Profile_saved_successfully') swal.close() instance.clearForm() if error toastr.remove(); handleError(error) Template.accountProfile.onRendered -> Tracker.afterFlush -> # this should throw an error-template FlowRouter.go("home") if !RocketChat.settings.get("Accounts_AllowUserProfileChange") SideNav.setFlex "accountFlex" SideNav.openFlex() Template.accountProfile.events 'click .submit button': (e, instance) -> unless s.trim Meteor.user()?.services?.password?.bcrypt return instance.save() swal title: t("Please_re_enter_your_password"), text: t("For_your_security_you_must_re_enter_your_password_to_continue"), type: "input", inputType: "password", showCancelButton: true, closeOnConfirm: false , (typedPassword) => if typedPassword toastr.remove(); toastr.warning(t("Please_wait_while_your_profile_is_being_saved")); instance.save(SHA256(typedPassword)) else swal.showInputError(t("You_need_to_type_in_your_password_in_order_to_do_this")); return false; 'click .logoutOthers button': (event, templateInstance) -> Meteor.logoutOtherClients (error) -> if error toastr.remove(); handleError(error) else toastr.remove(); toastr.success t('Logged_out_of_other_clients_successfully') 'click .delete-account button': (e) -> e.preventDefault(); if s.trim Meteor.user()?.services?.password?.bcrypt swal title: t("Are_you_sure_you_want_to_delete_your_account"), text: t("If_you_are_sure_type_in_your_password"), type: "input", inputType: "password", showCancelButton: true, closeOnConfirm: false , (typedPassword) => if typedPassword toastr.remove(); toastr.warning(t("Please_wait_while_your_account_is_being_deleted")); Meteor.call 'deleteUserOwnAccount', SHA256(typedPassword), (error, results) -> if error toastr.remove(); swal.showInputError(t("Your_password_is_wrong")); else swal.close(); else swal.showInputError(t("You_need_to_type_in_your_password_in_order_to_do_this")); return false; else swal title: t("Are_you_sure_you_want_to_delete_your_account"), text: t("If_you_are_sure_type_in_your_username"), type: "input", showCancelButton: true, closeOnConfirm: false , (deleteConfirmation) => if deleteConfirmation is Meteor.user()?.username toastr.remove(); toastr.warning(t("Please_wait_while_your_account_is_being_deleted")); Meteor.call 'deleteUserOwnAccount', deleteConfirmation, (error, results) -> if error toastr.remove(); swal.showInputError(t("Your_password_is_wrong")); else swal.close(); else swal.showInputError(t("You_need_to_type_in_your_username_in_order_to_do_this")); return false; 'click #resend-verification-email': (e) -> e.preventDefault() e.currentTarget.innerHTML = e.currentTarget.innerHTML + ' ...' e.currentTarget.disabled = true Meteor.call 'sendConfirmationEmail', Meteor.user().emails?[0]?.address, (error, results) => if results toastr.success t('Verification_email_sent') else if error handleError(error) e.currentTarget.innerHTML = e.currentTarget.innerHTML.replace(' ...', '') e.currentTarget.disabled = false
209291
Template.accountProfile.helpers allowDeleteOwnAccount: -> return RocketChat.settings.get('Accounts_AllowDeleteOwnAccount') realname: -> return Meteor.user().name username: -> return Meteor.user().username email: -> return Meteor.user().emails?[0]?.address emailVerified: -> return Meteor.user().emails?[0]?.verified allowUsernameChange: -> return RocketChat.settings.get("Accounts_AllowUsernameChange") and RocketChat.settings.get("LDAP_Enable") isnt true allowEmailChange: -> return RocketChat.settings.get("Accounts_AllowEmailChange") usernameChangeDisabled: -> return t('Username_Change_Disabled') allowPasswordChange: -> return RocketChat.settings.get("Accounts_AllowPasswordChange") passwordChangeDisabled: -> return t('Password_Change_Disabled') Template.accountProfile.onCreated -> settingsTemplate = this.parentTemplate(3) settingsTemplate.child ?= [] settingsTemplate.child.push this @clearForm = -> @find('#password').value = '' @changePassword = (newPassword, callback) -> instance = @ if not newPassword return callback() else if !RocketChat.settings.get("Accounts_AllowPasswordChange") toastr.remove(); toastr.error t('Password_Change_Disabled') instance.clearForm() return @save = (currentPassword) -> instance = @ data = { currentPassword: <PASSWORD> } if _.trim $('#password').val() data.newPassword = $('#password').val() if _.trim $('#realname').val() data.realname = _.trim $('#realname').val() if _.trim($('#username').val()) isnt Meteor.user().username if !RocketChat.settings.get("Accounts_AllowUsernameChange") toastr.remove(); toastr.error t('Username_Change_Disabled') instance.clearForm() return else data.username = _.trim $('#username').val() if _.trim($('#email').val()) isnt Meteor.user().emails?[0]?.address if !RocketChat.settings.get("Accounts_AllowEmailChange") toastr.remove(); toastr.error t('Email_Change_Disabled') instance.clearForm() return else data.email = _.trim $('#email').val() Meteor.call 'saveUserProfile', data, (error, results) -> if results toastr.remove(); toastr.success t('Profile_saved_successfully') swal.close() instance.clearForm() if error toastr.remove(); handleError(error) Template.accountProfile.onRendered -> Tracker.afterFlush -> # this should throw an error-template FlowRouter.go("home") if !RocketChat.settings.get("Accounts_AllowUserProfileChange") SideNav.setFlex "accountFlex" SideNav.openFlex() Template.accountProfile.events 'click .submit button': (e, instance) -> unless s.trim Meteor.user()?.services?.password?.bcrypt return instance.save() swal title: t("Please_re_enter_your_password"), text: t("For_your_security_you_must_re_enter_your_password_to_continue"), type: "input", inputType: "password", showCancelButton: true, closeOnConfirm: false , (typedPassword) => if typedPassword toastr.remove(); toastr.warning(t("Please_wait_while_your_profile_is_being_saved")); instance.save(SHA256(typedPassword)) else swal.showInputError(t("You_need_to_type_in_your_password_in_order_to_do_this")); return false; 'click .logoutOthers button': (event, templateInstance) -> Meteor.logoutOtherClients (error) -> if error toastr.remove(); handleError(error) else toastr.remove(); toastr.success t('Logged_out_of_other_clients_successfully') 'click .delete-account button': (e) -> e.preventDefault(); if s.trim Meteor.user()?.services?.password?.bcrypt swal title: t("Are_you_sure_you_want_to_delete_your_account"), text: t("If_you_are_sure_type_in_your_password"), type: "input", inputType: "password", showCancelButton: true, closeOnConfirm: false , (typedPassword) => if typedPassword toastr.remove(); toastr.warning(t("Please_wait_while_your_account_is_being_deleted")); Meteor.call 'deleteUserOwnAccount', SHA256(typedPassword), (error, results) -> if error toastr.remove(); swal.showInputError(t("Your_password_is_wrong")); else swal.close(); else swal.showInputError(t("You_need_to_type_in_your_password_in_order_to_do_this")); return false; else swal title: t("Are_you_sure_you_want_to_delete_your_account"), text: t("If_you_are_sure_type_in_your_username"), type: "input", showCancelButton: true, closeOnConfirm: false , (deleteConfirmation) => if deleteConfirmation is Meteor.user()?.username toastr.remove(); toastr.warning(t("Please_wait_while_your_account_is_being_deleted")); Meteor.call 'deleteUserOwnAccount', deleteConfirmation, (error, results) -> if error toastr.remove(); swal.showInputError(t("Your_password_is_wrong")); else swal.close(); else swal.showInputError(t("You_need_to_type_in_your_username_in_order_to_do_this")); return false; 'click #resend-verification-email': (e) -> e.preventDefault() e.currentTarget.innerHTML = e.currentTarget.innerHTML + ' ...' e.currentTarget.disabled = true Meteor.call 'sendConfirmationEmail', Meteor.user().emails?[0]?.address, (error, results) => if results toastr.success t('Verification_email_sent') else if error handleError(error) e.currentTarget.innerHTML = e.currentTarget.innerHTML.replace(' ...', '') e.currentTarget.disabled = false
true
Template.accountProfile.helpers allowDeleteOwnAccount: -> return RocketChat.settings.get('Accounts_AllowDeleteOwnAccount') realname: -> return Meteor.user().name username: -> return Meteor.user().username email: -> return Meteor.user().emails?[0]?.address emailVerified: -> return Meteor.user().emails?[0]?.verified allowUsernameChange: -> return RocketChat.settings.get("Accounts_AllowUsernameChange") and RocketChat.settings.get("LDAP_Enable") isnt true allowEmailChange: -> return RocketChat.settings.get("Accounts_AllowEmailChange") usernameChangeDisabled: -> return t('Username_Change_Disabled') allowPasswordChange: -> return RocketChat.settings.get("Accounts_AllowPasswordChange") passwordChangeDisabled: -> return t('Password_Change_Disabled') Template.accountProfile.onCreated -> settingsTemplate = this.parentTemplate(3) settingsTemplate.child ?= [] settingsTemplate.child.push this @clearForm = -> @find('#password').value = '' @changePassword = (newPassword, callback) -> instance = @ if not newPassword return callback() else if !RocketChat.settings.get("Accounts_AllowPasswordChange") toastr.remove(); toastr.error t('Password_Change_Disabled') instance.clearForm() return @save = (currentPassword) -> instance = @ data = { currentPassword: PI:PASSWORD:<PASSWORD>END_PI } if _.trim $('#password').val() data.newPassword = $('#password').val() if _.trim $('#realname').val() data.realname = _.trim $('#realname').val() if _.trim($('#username').val()) isnt Meteor.user().username if !RocketChat.settings.get("Accounts_AllowUsernameChange") toastr.remove(); toastr.error t('Username_Change_Disabled') instance.clearForm() return else data.username = _.trim $('#username').val() if _.trim($('#email').val()) isnt Meteor.user().emails?[0]?.address if !RocketChat.settings.get("Accounts_AllowEmailChange") toastr.remove(); toastr.error t('Email_Change_Disabled') instance.clearForm() return else data.email = _.trim $('#email').val() Meteor.call 'saveUserProfile', data, (error, results) -> if results toastr.remove(); toastr.success t('Profile_saved_successfully') swal.close() instance.clearForm() if error toastr.remove(); handleError(error) Template.accountProfile.onRendered -> Tracker.afterFlush -> # this should throw an error-template FlowRouter.go("home") if !RocketChat.settings.get("Accounts_AllowUserProfileChange") SideNav.setFlex "accountFlex" SideNav.openFlex() Template.accountProfile.events 'click .submit button': (e, instance) -> unless s.trim Meteor.user()?.services?.password?.bcrypt return instance.save() swal title: t("Please_re_enter_your_password"), text: t("For_your_security_you_must_re_enter_your_password_to_continue"), type: "input", inputType: "password", showCancelButton: true, closeOnConfirm: false , (typedPassword) => if typedPassword toastr.remove(); toastr.warning(t("Please_wait_while_your_profile_is_being_saved")); instance.save(SHA256(typedPassword)) else swal.showInputError(t("You_need_to_type_in_your_password_in_order_to_do_this")); return false; 'click .logoutOthers button': (event, templateInstance) -> Meteor.logoutOtherClients (error) -> if error toastr.remove(); handleError(error) else toastr.remove(); toastr.success t('Logged_out_of_other_clients_successfully') 'click .delete-account button': (e) -> e.preventDefault(); if s.trim Meteor.user()?.services?.password?.bcrypt swal title: t("Are_you_sure_you_want_to_delete_your_account"), text: t("If_you_are_sure_type_in_your_password"), type: "input", inputType: "password", showCancelButton: true, closeOnConfirm: false , (typedPassword) => if typedPassword toastr.remove(); toastr.warning(t("Please_wait_while_your_account_is_being_deleted")); Meteor.call 'deleteUserOwnAccount', SHA256(typedPassword), (error, results) -> if error toastr.remove(); swal.showInputError(t("Your_password_is_wrong")); else swal.close(); else swal.showInputError(t("You_need_to_type_in_your_password_in_order_to_do_this")); return false; else swal title: t("Are_you_sure_you_want_to_delete_your_account"), text: t("If_you_are_sure_type_in_your_username"), type: "input", showCancelButton: true, closeOnConfirm: false , (deleteConfirmation) => if deleteConfirmation is Meteor.user()?.username toastr.remove(); toastr.warning(t("Please_wait_while_your_account_is_being_deleted")); Meteor.call 'deleteUserOwnAccount', deleteConfirmation, (error, results) -> if error toastr.remove(); swal.showInputError(t("Your_password_is_wrong")); else swal.close(); else swal.showInputError(t("You_need_to_type_in_your_username_in_order_to_do_this")); return false; 'click #resend-verification-email': (e) -> e.preventDefault() e.currentTarget.innerHTML = e.currentTarget.innerHTML + ' ...' e.currentTarget.disabled = true Meteor.call 'sendConfirmationEmail', Meteor.user().emails?[0]?.address, (error, results) => if results toastr.success t('Verification_email_sent') else if error handleError(error) e.currentTarget.innerHTML = e.currentTarget.innerHTML.replace(' ...', '') e.currentTarget.disabled = false
[ { "context": "kdevices.json').devices\n\nconfig = \n hostname: '192.168.105.221',\n port: 5222,\n# config2 =\n# hostname: '19", "end": 399, "score": 0.9996994733810425, "start": 384, "tag": "IP_ADDRESS", "value": "192.168.105.221" }, { "context": "21',\n port: 5222,\n# c...
command-xmpp-receivers.coffee
ducxop/meshblu-benchmark
0
myMesh = require "./src/MyMeshblu.js" Meshblu = require 'meshblu-xmpp' Benchmark = require 'simple-benchmark' Table = require 'cli-table' async = require 'async' _ = require 'lodash' commander = require 'commander' now = require 'performance-now' devices = require('./300kdevices.json').devices config = hostname: '192.168.105.221', port: 5222, # config2 = # hostname: '192.168.105.221', # port: 5222, # token: "14fc2e1668410784f75ba8c946e4a4b6cac3989f", # uuid: "037dd8ef-19e7-4b44-8172-f2813f0c245c" benchmark = {} conn = {} nr = 0 n = 0 nS = 0 arr = [] bench = [] myParseInt = (string, defaultValue) -> int = parseInt(string, 10) if typeof int == 'number' int else defaultValue #@parseInt = (str) => parseInt str, 10 commander .option '-t, --total-times [n]', 'create connection in total times (default to 0)', myParseInt, 1 .option '-i, --interval [n]', 'create connection with interval between each time(default 5s)', myParseInt, 5 .option '-n, --number-of-devices [n]', 'number of devices to connect at a time (default to 1000)', myParseInt, 1000 .option '-s, --step [n]', 'display step (defaults to 500)', myParseInt, 500 .option '-m, --number-of-msg [n]', 'number of parallel messages (defaults to 1)', myParseInt, 1 .option '-o, --offset [n]','devices uuid offset value (default to 0)', myParseInt, 0 .parse process.argv {totalTimes,interval,numberOfDevices,step,numberOfMsg,offset} = commander totalTimes = totalTimes interval = interval*1000 totalConnection = 0 dConnected = {} dReceived = {} dStartR = {} conn = [] #new Meshblu(config2); createConnections = () -> if nS>=totalTimes return else if nS==0 console.log "connecting " for i in [numberOfDevices*nS...numberOfDevices*++nS] config.uuid = devices[i+offset+1].uuid config.token = devices[i+offset+1].token conn[i] = new Meshblu(config) conn[i].connect (err)=> if ++n%step==0 then console.log "connecting ", n totalConnection=n #callback() #if (n==numberOfDevices+nS) then console.timeEnd 'connect' createConnection = (dv, callback) => config.uuid = dv.uuid config.token = dv.token conn[n] = new Meshblu(config) conn[n].connect (err)=> if ++n%step==0 then console.log "connecting ", n callback() startConnect = () -> createConnections() # if n<numberOfDevices*totalTimes #totalConnection<numberOfDevices*totalTimes # async.each devices.slice(n,n+numberOfDevices), createConnection, () => # console.timeEnd 'connect' # totalConnection += numberOfDevices dStartC = new Date() console.time 'connect' if totalTimes>1 && interval>0 intervalObj = setInterval startConnect, interval stopConnect = () -> console.log totalConnection if totalConnection==totalTimes*numberOfDevices clearInterval intervalObj dConnected = new Date() console.log 'start receiving: ~' receiving() else setTimeout stopConnect, 1000 setTimeout stopConnect, totalTimes*interval else startConnect() printResults = (id) => #(error) => #return @die error if error? if id? elapsedTime = bench[id].elapsed() totalmsg = arr[id] console.log "Receiving Results - ", id else elapsedTime = benchmark.elapsed() totalmsg = nr console.log "Final Results: " averagePerSecond = totalmsg / (elapsedTime / 1000) #messageLoss = 1 - (_.size(@statusCodes) / (@cycles * @numberOfMessages)) generalTable = new Table generalTable.push 'total msg receive' : "#{totalmsg}" , 'took' : "#{elapsedTime}ms" , 'average per second' : "#{averagePerSecond}/s" percentileTable = new Table head: ['10th', '25th', '50th', '75th', '90th'] percentileTable.push [ nthPercentile(10, @elapsedTimes2) nthPercentile(25, @elapsedTimes2) nthPercentile(50, @elapsedTimes2) nthPercentile(75, @elapsedTimes2) nthPercentile(90, @elapsedTimes2) ] console.log generalTable.toString() #console.log percentileTable.toString() nthPercentile = (percentile, array) => array = _.sortBy array index = (percentile / 100) * _.size(array) if Math.floor(index) == index return (array[index-1] + array[index]) / 2 return array[Math.floor index] receiving = ()=> totalMsgSend = 0 for i in [0...totalTimes*numberOfDevices] #console.log 'listen from ', conn[i].uuid conn[i].on 'message', (message) => #console.log message.data.payload if ++nr%(step*numberOfMsg)==0 then console.log 'receiving ', nr id = parseInt(message.data.payload) unless isNaN id if arr[id]? #console.log 'id, arr[id] ', id, arr[id] if ++arr[id]==totalConnection*numberOfMsg printResults(id) else arr[id]=1 #console.log 'id, arr[id] new ', id, arr[id] bench[id] = new Benchmark label:id if nr==1 totalMsgSend = id dStartR = new Date() benchmark = new Benchmark label:'total benchmark' #console.log nr,numberOfMsg,totalConnection,totalTimes if nr==(numberOfMsg*totalConnection*totalMsgSend) # for i in [1..totalMsgSend] # console.log('ARR:', i, arr[i]) dReceived = new Date() console.log 'Start Connecting: ', dStartC.toString() console.log 'Finish Connecting: ', dConnected.toString() if totalMsgSend>1 then printResults() console.log 'Received 1st msg: ', dStartR.toString() console.log 'Received last msg: ', dReceived.toString() process.exit 0 if process.platform == "win32" inf = input: process.stdin output: process.stdout rl = require "readline" .createInterface inf rl.on "SIGINT", () => process.emit "SIGINT" onSigint = () => console.log "Exit on SIGINT" process.exit 0 process.on "SIGINT", onSigint
140828
myMesh = require "./src/MyMeshblu.js" Meshblu = require 'meshblu-xmpp' Benchmark = require 'simple-benchmark' Table = require 'cli-table' async = require 'async' _ = require 'lodash' commander = require 'commander' now = require 'performance-now' devices = require('./300kdevices.json').devices config = hostname: '192.168.105.221', port: 5222, # config2 = # hostname: '192.168.105.221', # port: 5222, # token: "<KEY>", # uuid: "037dd8ef-19e7-4b44-8172-f2813f0c245c" benchmark = {} conn = {} nr = 0 n = 0 nS = 0 arr = [] bench = [] myParseInt = (string, defaultValue) -> int = parseInt(string, 10) if typeof int == 'number' int else defaultValue #@parseInt = (str) => parseInt str, 10 commander .option '-t, --total-times [n]', 'create connection in total times (default to 0)', myParseInt, 1 .option '-i, --interval [n]', 'create connection with interval between each time(default 5s)', myParseInt, 5 .option '-n, --number-of-devices [n]', 'number of devices to connect at a time (default to 1000)', myParseInt, 1000 .option '-s, --step [n]', 'display step (defaults to 500)', myParseInt, 500 .option '-m, --number-of-msg [n]', 'number of parallel messages (defaults to 1)', myParseInt, 1 .option '-o, --offset [n]','devices uuid offset value (default to 0)', myParseInt, 0 .parse process.argv {totalTimes,interval,numberOfDevices,step,numberOfMsg,offset} = commander totalTimes = totalTimes interval = interval*1000 totalConnection = 0 dConnected = {} dReceived = {} dStartR = {} conn = [] #new Meshblu(config2); createConnections = () -> if nS>=totalTimes return else if nS==0 console.log "connecting " for i in [numberOfDevices*nS...numberOfDevices*++nS] config.uuid = devices[i+offset+1].uuid config.token = devices[i+offset+1].token conn[i] = new Meshblu(config) conn[i].connect (err)=> if ++n%step==0 then console.log "connecting ", n totalConnection=n #callback() #if (n==numberOfDevices+nS) then console.timeEnd 'connect' createConnection = (dv, callback) => config.uuid = dv.uuid config.token = dv.token conn[n] = new Meshblu(config) conn[n].connect (err)=> if ++n%step==0 then console.log "connecting ", n callback() startConnect = () -> createConnections() # if n<numberOfDevices*totalTimes #totalConnection<numberOfDevices*totalTimes # async.each devices.slice(n,n+numberOfDevices), createConnection, () => # console.timeEnd 'connect' # totalConnection += numberOfDevices dStartC = new Date() console.time 'connect' if totalTimes>1 && interval>0 intervalObj = setInterval startConnect, interval stopConnect = () -> console.log totalConnection if totalConnection==totalTimes*numberOfDevices clearInterval intervalObj dConnected = new Date() console.log 'start receiving: ~' receiving() else setTimeout stopConnect, 1000 setTimeout stopConnect, totalTimes*interval else startConnect() printResults = (id) => #(error) => #return @die error if error? if id? elapsedTime = bench[id].elapsed() totalmsg = arr[id] console.log "Receiving Results - ", id else elapsedTime = benchmark.elapsed() totalmsg = nr console.log "Final Results: " averagePerSecond = totalmsg / (elapsedTime / 1000) #messageLoss = 1 - (_.size(@statusCodes) / (@cycles * @numberOfMessages)) generalTable = new Table generalTable.push 'total msg receive' : "#{totalmsg}" , 'took' : "#{elapsedTime}ms" , 'average per second' : "#{averagePerSecond}/s" percentileTable = new Table head: ['10th', '25th', '50th', '75th', '90th'] percentileTable.push [ nthPercentile(10, @elapsedTimes2) nthPercentile(25, @elapsedTimes2) nthPercentile(50, @elapsedTimes2) nthPercentile(75, @elapsedTimes2) nthPercentile(90, @elapsedTimes2) ] console.log generalTable.toString() #console.log percentileTable.toString() nthPercentile = (percentile, array) => array = _.sortBy array index = (percentile / 100) * _.size(array) if Math.floor(index) == index return (array[index-1] + array[index]) / 2 return array[Math.floor index] receiving = ()=> totalMsgSend = 0 for i in [0...totalTimes*numberOfDevices] #console.log 'listen from ', conn[i].uuid conn[i].on 'message', (message) => #console.log message.data.payload if ++nr%(step*numberOfMsg)==0 then console.log 'receiving ', nr id = parseInt(message.data.payload) unless isNaN id if arr[id]? #console.log 'id, arr[id] ', id, arr[id] if ++arr[id]==totalConnection*numberOfMsg printResults(id) else arr[id]=1 #console.log 'id, arr[id] new ', id, arr[id] bench[id] = new Benchmark label:id if nr==1 totalMsgSend = id dStartR = new Date() benchmark = new Benchmark label:'total benchmark' #console.log nr,numberOfMsg,totalConnection,totalTimes if nr==(numberOfMsg*totalConnection*totalMsgSend) # for i in [1..totalMsgSend] # console.log('ARR:', i, arr[i]) dReceived = new Date() console.log 'Start Connecting: ', dStartC.toString() console.log 'Finish Connecting: ', dConnected.toString() if totalMsgSend>1 then printResults() console.log 'Received 1st msg: ', dStartR.toString() console.log 'Received last msg: ', dReceived.toString() process.exit 0 if process.platform == "win32" inf = input: process.stdin output: process.stdout rl = require "readline" .createInterface inf rl.on "SIGINT", () => process.emit "SIGINT" onSigint = () => console.log "Exit on SIGINT" process.exit 0 process.on "SIGINT", onSigint
true
myMesh = require "./src/MyMeshblu.js" Meshblu = require 'meshblu-xmpp' Benchmark = require 'simple-benchmark' Table = require 'cli-table' async = require 'async' _ = require 'lodash' commander = require 'commander' now = require 'performance-now' devices = require('./300kdevices.json').devices config = hostname: '192.168.105.221', port: 5222, # config2 = # hostname: '192.168.105.221', # port: 5222, # token: "PI:KEY:<KEY>END_PI", # uuid: "037dd8ef-19e7-4b44-8172-f2813f0c245c" benchmark = {} conn = {} nr = 0 n = 0 nS = 0 arr = [] bench = [] myParseInt = (string, defaultValue) -> int = parseInt(string, 10) if typeof int == 'number' int else defaultValue #@parseInt = (str) => parseInt str, 10 commander .option '-t, --total-times [n]', 'create connection in total times (default to 0)', myParseInt, 1 .option '-i, --interval [n]', 'create connection with interval between each time(default 5s)', myParseInt, 5 .option '-n, --number-of-devices [n]', 'number of devices to connect at a time (default to 1000)', myParseInt, 1000 .option '-s, --step [n]', 'display step (defaults to 500)', myParseInt, 500 .option '-m, --number-of-msg [n]', 'number of parallel messages (defaults to 1)', myParseInt, 1 .option '-o, --offset [n]','devices uuid offset value (default to 0)', myParseInt, 0 .parse process.argv {totalTimes,interval,numberOfDevices,step,numberOfMsg,offset} = commander totalTimes = totalTimes interval = interval*1000 totalConnection = 0 dConnected = {} dReceived = {} dStartR = {} conn = [] #new Meshblu(config2); createConnections = () -> if nS>=totalTimes return else if nS==0 console.log "connecting " for i in [numberOfDevices*nS...numberOfDevices*++nS] config.uuid = devices[i+offset+1].uuid config.token = devices[i+offset+1].token conn[i] = new Meshblu(config) conn[i].connect (err)=> if ++n%step==0 then console.log "connecting ", n totalConnection=n #callback() #if (n==numberOfDevices+nS) then console.timeEnd 'connect' createConnection = (dv, callback) => config.uuid = dv.uuid config.token = dv.token conn[n] = new Meshblu(config) conn[n].connect (err)=> if ++n%step==0 then console.log "connecting ", n callback() startConnect = () -> createConnections() # if n<numberOfDevices*totalTimes #totalConnection<numberOfDevices*totalTimes # async.each devices.slice(n,n+numberOfDevices), createConnection, () => # console.timeEnd 'connect' # totalConnection += numberOfDevices dStartC = new Date() console.time 'connect' if totalTimes>1 && interval>0 intervalObj = setInterval startConnect, interval stopConnect = () -> console.log totalConnection if totalConnection==totalTimes*numberOfDevices clearInterval intervalObj dConnected = new Date() console.log 'start receiving: ~' receiving() else setTimeout stopConnect, 1000 setTimeout stopConnect, totalTimes*interval else startConnect() printResults = (id) => #(error) => #return @die error if error? if id? elapsedTime = bench[id].elapsed() totalmsg = arr[id] console.log "Receiving Results - ", id else elapsedTime = benchmark.elapsed() totalmsg = nr console.log "Final Results: " averagePerSecond = totalmsg / (elapsedTime / 1000) #messageLoss = 1 - (_.size(@statusCodes) / (@cycles * @numberOfMessages)) generalTable = new Table generalTable.push 'total msg receive' : "#{totalmsg}" , 'took' : "#{elapsedTime}ms" , 'average per second' : "#{averagePerSecond}/s" percentileTable = new Table head: ['10th', '25th', '50th', '75th', '90th'] percentileTable.push [ nthPercentile(10, @elapsedTimes2) nthPercentile(25, @elapsedTimes2) nthPercentile(50, @elapsedTimes2) nthPercentile(75, @elapsedTimes2) nthPercentile(90, @elapsedTimes2) ] console.log generalTable.toString() #console.log percentileTable.toString() nthPercentile = (percentile, array) => array = _.sortBy array index = (percentile / 100) * _.size(array) if Math.floor(index) == index return (array[index-1] + array[index]) / 2 return array[Math.floor index] receiving = ()=> totalMsgSend = 0 for i in [0...totalTimes*numberOfDevices] #console.log 'listen from ', conn[i].uuid conn[i].on 'message', (message) => #console.log message.data.payload if ++nr%(step*numberOfMsg)==0 then console.log 'receiving ', nr id = parseInt(message.data.payload) unless isNaN id if arr[id]? #console.log 'id, arr[id] ', id, arr[id] if ++arr[id]==totalConnection*numberOfMsg printResults(id) else arr[id]=1 #console.log 'id, arr[id] new ', id, arr[id] bench[id] = new Benchmark label:id if nr==1 totalMsgSend = id dStartR = new Date() benchmark = new Benchmark label:'total benchmark' #console.log nr,numberOfMsg,totalConnection,totalTimes if nr==(numberOfMsg*totalConnection*totalMsgSend) # for i in [1..totalMsgSend] # console.log('ARR:', i, arr[i]) dReceived = new Date() console.log 'Start Connecting: ', dStartC.toString() console.log 'Finish Connecting: ', dConnected.toString() if totalMsgSend>1 then printResults() console.log 'Received 1st msg: ', dStartR.toString() console.log 'Received last msg: ', dReceived.toString() process.exit 0 if process.platform == "win32" inf = input: process.stdin output: process.stdout rl = require "readline" .createInterface inf rl.on "SIGINT", () => process.emit "SIGINT" onSigint = () => console.log "Exit on SIGINT" process.exit 0 process.on "SIGINT", onSigint
[ { "context": "#\n# Copyright 2014 Carsten Klein\n#\n# Licensed under the Apache License, Version 2.", "end": 32, "score": 0.9998628497123718, "start": 19, "tag": "NAME", "value": "Carsten Klein" } ]
test/sublassof-test.coffee
vibejs/vibejs-subclassof
0
# # Copyright 2014 Carsten Klein # # 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. # vows = require 'vows' assert = require 'assert' require '../src/subclassof' vows.describe 'subclassof' .addBatch 'tests expected to fail' : # unable to test this as monkey patches are being loaded prior to that # the test is actually run #'TypeError is not a subclassof Error (without monkey patching)' : -> # # assert.isFalse subclassof TypeError, Error 'Error is not a subclassof Number' : -> assert.isFalse subclassof Error, Number 'constructor is not a function' : -> cb = -> subclassof null, Function assert.throws cb, TypeError 'base is not a function' : -> cb = -> subclassof Function, null assert.throws cb, TypeError .export module
225090
# # Copyright 2014 <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. # vows = require 'vows' assert = require 'assert' require '../src/subclassof' vows.describe 'subclassof' .addBatch 'tests expected to fail' : # unable to test this as monkey patches are being loaded prior to that # the test is actually run #'TypeError is not a subclassof Error (without monkey patching)' : -> # # assert.isFalse subclassof TypeError, Error 'Error is not a subclassof Number' : -> assert.isFalse subclassof Error, Number 'constructor is not a function' : -> cb = -> subclassof null, Function assert.throws cb, TypeError 'base is not a function' : -> cb = -> subclassof Function, null assert.throws cb, TypeError .export module
true
# # Copyright 2014 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. # vows = require 'vows' assert = require 'assert' require '../src/subclassof' vows.describe 'subclassof' .addBatch 'tests expected to fail' : # unable to test this as monkey patches are being loaded prior to that # the test is actually run #'TypeError is not a subclassof Error (without monkey patching)' : -> # # assert.isFalse subclassof TypeError, Error 'Error is not a subclassof Number' : -> assert.isFalse subclassof Error, Number 'constructor is not a function' : -> cb = -> subclassof null, Function assert.throws cb, TypeError 'base is not a function' : -> cb = -> subclassof Function, null assert.throws cb, TypeError .export module
[ { "context": "cribe 'Wongo Embedded', ->\n \n doc = \n name: 'KingMeow'\n child: \n name: 'KitMeow'\n child: \n", "end": 345, "score": 0.9775699973106384, "start": 337, "tag": "NAME", "value": "KingMeow" }, { "context": " = \n name: 'KingMeow'\n child: \n ...
test/embed.test.coffee
wookets/wongo
0
assert = require 'assert' wongo = require '../lib/wongo' wongo.schema 'MockEmbed', fields: name: String child: # object name: String child: name: String children: [ # array name: String children: [ name: String ] ] describe 'Wongo Embedded', -> doc = name: 'KingMeow' child: name: 'KitMeow' child: name: 'KittyMeow' children: [{ name: 'KitcMeow', children: [ {name: 'SubKitchMeow'}, {name: 'SubKitchMeow2'} ] }, { name: 'KitcMeow2' children: [] }] it 'should be able to save an embedded document', (done) -> wongo.save 'MockEmbed', doc, (err, result) -> assert.ifError(err) assert.ok(result?._id) doc = result assert.equal(doc.name, 'KingMeow') assert.equal(doc.child.name, 'KitMeow') assert.ok(doc.child._id) assert.equal(doc.child.child.name, 'KittyMeow') #assert.ok(doc.child.child._id) assert.equal(doc.children.length, 2) assert.equal(doc.children[0].name, 'KitcMeow') assert.equal(doc.children[1].name, 'KitcMeow2') assert.equal(doc.children[0].children.length, 2) done()
147091
assert = require 'assert' wongo = require '../lib/wongo' wongo.schema 'MockEmbed', fields: name: String child: # object name: String child: name: String children: [ # array name: String children: [ name: String ] ] describe 'Wongo Embedded', -> doc = name: '<NAME>' child: name: '<NAME>' child: name: '<NAME>' children: [{ name: '<NAME>', children: [ {name: '<NAME>K<NAME>Meow'}, {name: '<NAME>KitchMeow2'} ] }, { name: '<NAME>' children: [] }] it 'should be able to save an embedded document', (done) -> wongo.save 'MockEmbed', doc, (err, result) -> assert.ifError(err) assert.ok(result?._id) doc = result assert.equal(doc.name, '<NAME>') assert.equal(doc.child.name, '<NAME>') assert.ok(doc.child._id) assert.equal(doc.child.child.name, '<NAME>') #assert.ok(doc.child.child._id) assert.equal(doc.children.length, 2) assert.equal(doc.children[0].name, '<NAME>Meow') assert.equal(doc.children[1].name, 'KitcMeow2') assert.equal(doc.children[0].children.length, 2) done()
true
assert = require 'assert' wongo = require '../lib/wongo' wongo.schema 'MockEmbed', fields: name: String child: # object name: String child: name: String children: [ # array name: String children: [ name: String ] ] describe 'Wongo Embedded', -> doc = name: 'PI:NAME:<NAME>END_PI' child: name: 'PI:NAME:<NAME>END_PI' child: name: 'PI:NAME:<NAME>END_PI' children: [{ name: 'PI:NAME:<NAME>END_PI', children: [ {name: 'PI:NAME:<NAME>END_PIKPI:NAME:<NAME>END_PIMeow'}, {name: 'PI:NAME:<NAME>END_PIKitchMeow2'} ] }, { name: 'PI:NAME:<NAME>END_PI' children: [] }] it 'should be able to save an embedded document', (done) -> wongo.save 'MockEmbed', doc, (err, result) -> assert.ifError(err) assert.ok(result?._id) doc = result assert.equal(doc.name, 'PI:NAME:<NAME>END_PI') assert.equal(doc.child.name, 'PI:NAME:<NAME>END_PI') assert.ok(doc.child._id) assert.equal(doc.child.child.name, 'PI:NAME:<NAME>END_PI') #assert.ok(doc.child.child._id) assert.equal(doc.children.length, 2) assert.equal(doc.children[0].name, 'PI:NAME:<NAME>END_PIMeow') assert.equal(doc.children[1].name, 'KitcMeow2') assert.equal(doc.children[0].children.length, 2) done()
[ { "context": "# Storage.coffee\n# Tomasz (Tomek) Zemla\n# tomek@datacratic.com\n\n# Class that ", "end": 25, "score": 0.9966333508491516, "start": 19, "tag": "NAME", "value": "Tomasz" }, { "context": "# Storage.coffee\n# Tomasz (Tomek) Zemla\n# tomek@datacratic.com\n\n# Class that pr...
src/Storage.coffee
SachithDassanayaka/sachithdassanayaka.github.io
0
# Storage.coffee # Tomasz (Tomek) Zemla # tomek@datacratic.com # Class that provides access to application storage. Technically this is server # based storage accessed asynchronously, but with custom Node based server this # can be run in the context of the single machine with local storage. # Storage provides services to retrieve the data file for visualization and to # save the screenshots of the rendered images. It also does the initial scan of # the data to extract some basic info about it like the number of clusters present. # SEE server.coffee Subject = require('./Subject.coffee') class Storage extends Subject # E V E N T S @EVENT_DATAFILE_READY : "EVENT_DATAFILE_READY" # fired when data file name was received @EVENT_JSON_READY : "EVENT_JSON_READY" # fired when JSON data source was downloaded @EVENT_DATA_READY : "EVENT_DATA_READY" # fired when JSON data was processed and ready for use @EVENT_SCREENSHOT_OK : "EVENT_SCREENSHOT_OK" # fired when screenshot was saved OK # M E M B E R S datafile : null # name of the data file to be used data : null # JSON data points : 0 # counts data points loaded clusterIDs : null # array of cluster IDs loaded clusters : 0 # number of unique clusters saved : 0 # save screenshot counter # C O N S T R U C T O R constructor : -> super() @clusterIDs = new Array() # E V E N T H A N D L E R S # Server response to filename request. onDatafile : (@datafile) => @notify(Storage.EVENT_DATAFILE_READY) @requestJSON(@datafile) # Called when data arrives. onJSON : (@data) => @notify(Storage.EVENT_JSON_READY) # process JSON data $.each(@data.points, @processPoint) @notify(Storage.EVENT_DATA_READY) # Server response to saving image on disk. onSaveResponse : (message) => console.log "DataProjector.onSaveResponse " + message @notify(Storage.EVENT_SCREENSHOT_OK) # M E T H O D S # This is a two step process. First data file name is retrieved. Then data itself. requestData : -> @requestDatafile() # Get the name of the data file to use in visualization. requestDatafile : -> @onDatafile "data.json" # Use jQuery JSON loader to fetch data. requestJSON : (@datafile) -> # attach random value to avoid browser cache problem file = @datafile + "?" + String(Math.round(Math.random() * 99999)) $.getJSON(file, @onJSON) # Save copy of the given image to storage. saveImage : (base64Image) -> $.post('/upload', { id : ++@saved, image : base64Image }, @onSaveResponse) # Called for each data point loaded in JSON file. # Initial scan of loaded data to extract some info about it. processPoint : (nodeName, nodeData) => unless nodeData.cid in @clusterIDs @clusterIDs.push(nodeData.cid) @clusters = @clusterIDs.length @points++ # Get the data file name. getDatafile : -> return @datafile # Get the JSON data. getData : -> return @data # Get number of unique clusters found in data. getClusters : -> return @clusters # Get number of points found in data. getPoints : -> return @points # Get number of saved screenshots. getSaved : -> return @saved module.exports = Storage
16032
# Storage.coffee # <NAME> (<NAME> # <EMAIL> # Class that provides access to application storage. Technically this is server # based storage accessed asynchronously, but with custom Node based server this # can be run in the context of the single machine with local storage. # Storage provides services to retrieve the data file for visualization and to # save the screenshots of the rendered images. It also does the initial scan of # the data to extract some basic info about it like the number of clusters present. # SEE server.coffee Subject = require('./Subject.coffee') class Storage extends Subject # E V E N T S @EVENT_DATAFILE_READY : "EVENT_DATAFILE_READY" # fired when data file name was received @EVENT_JSON_READY : "EVENT_JSON_READY" # fired when JSON data source was downloaded @EVENT_DATA_READY : "EVENT_DATA_READY" # fired when JSON data was processed and ready for use @EVENT_SCREENSHOT_OK : "EVENT_SCREENSHOT_OK" # fired when screenshot was saved OK # M E M B E R S datafile : null # name of the data file to be used data : null # JSON data points : 0 # counts data points loaded clusterIDs : null # array of cluster IDs loaded clusters : 0 # number of unique clusters saved : 0 # save screenshot counter # C O N S T R U C T O R constructor : -> super() @clusterIDs = new Array() # E V E N T H A N D L E R S # Server response to filename request. onDatafile : (@datafile) => @notify(Storage.EVENT_DATAFILE_READY) @requestJSON(@datafile) # Called when data arrives. onJSON : (@data) => @notify(Storage.EVENT_JSON_READY) # process JSON data $.each(@data.points, @processPoint) @notify(Storage.EVENT_DATA_READY) # Server response to saving image on disk. onSaveResponse : (message) => console.log "DataProjector.onSaveResponse " + message @notify(Storage.EVENT_SCREENSHOT_OK) # M E T H O D S # This is a two step process. First data file name is retrieved. Then data itself. requestData : -> @requestDatafile() # Get the name of the data file to use in visualization. requestDatafile : -> @onDatafile "data.json" # Use jQuery JSON loader to fetch data. requestJSON : (@datafile) -> # attach random value to avoid browser cache problem file = @datafile + "?" + String(Math.round(Math.random() * 99999)) $.getJSON(file, @onJSON) # Save copy of the given image to storage. saveImage : (base64Image) -> $.post('/upload', { id : ++@saved, image : base64Image }, @onSaveResponse) # Called for each data point loaded in JSON file. # Initial scan of loaded data to extract some info about it. processPoint : (nodeName, nodeData) => unless nodeData.cid in @clusterIDs @clusterIDs.push(nodeData.cid) @clusters = @clusterIDs.length @points++ # Get the data file name. getDatafile : -> return @datafile # Get the JSON data. getData : -> return @data # Get number of unique clusters found in data. getClusters : -> return @clusters # Get number of points found in data. getPoints : -> return @points # Get number of saved screenshots. getSaved : -> return @saved module.exports = Storage
true
# Storage.coffee # PI:NAME:<NAME>END_PI (PI:NAME:<NAME>END_PI # PI:EMAIL:<EMAIL>END_PI # Class that provides access to application storage. Technically this is server # based storage accessed asynchronously, but with custom Node based server this # can be run in the context of the single machine with local storage. # Storage provides services to retrieve the data file for visualization and to # save the screenshots of the rendered images. It also does the initial scan of # the data to extract some basic info about it like the number of clusters present. # SEE server.coffee Subject = require('./Subject.coffee') class Storage extends Subject # E V E N T S @EVENT_DATAFILE_READY : "EVENT_DATAFILE_READY" # fired when data file name was received @EVENT_JSON_READY : "EVENT_JSON_READY" # fired when JSON data source was downloaded @EVENT_DATA_READY : "EVENT_DATA_READY" # fired when JSON data was processed and ready for use @EVENT_SCREENSHOT_OK : "EVENT_SCREENSHOT_OK" # fired when screenshot was saved OK # M E M B E R S datafile : null # name of the data file to be used data : null # JSON data points : 0 # counts data points loaded clusterIDs : null # array of cluster IDs loaded clusters : 0 # number of unique clusters saved : 0 # save screenshot counter # C O N S T R U C T O R constructor : -> super() @clusterIDs = new Array() # E V E N T H A N D L E R S # Server response to filename request. onDatafile : (@datafile) => @notify(Storage.EVENT_DATAFILE_READY) @requestJSON(@datafile) # Called when data arrives. onJSON : (@data) => @notify(Storage.EVENT_JSON_READY) # process JSON data $.each(@data.points, @processPoint) @notify(Storage.EVENT_DATA_READY) # Server response to saving image on disk. onSaveResponse : (message) => console.log "DataProjector.onSaveResponse " + message @notify(Storage.EVENT_SCREENSHOT_OK) # M E T H O D S # This is a two step process. First data file name is retrieved. Then data itself. requestData : -> @requestDatafile() # Get the name of the data file to use in visualization. requestDatafile : -> @onDatafile "data.json" # Use jQuery JSON loader to fetch data. requestJSON : (@datafile) -> # attach random value to avoid browser cache problem file = @datafile + "?" + String(Math.round(Math.random() * 99999)) $.getJSON(file, @onJSON) # Save copy of the given image to storage. saveImage : (base64Image) -> $.post('/upload', { id : ++@saved, image : base64Image }, @onSaveResponse) # Called for each data point loaded in JSON file. # Initial scan of loaded data to extract some info about it. processPoint : (nodeName, nodeData) => unless nodeData.cid in @clusterIDs @clusterIDs.push(nodeData.cid) @clusters = @clusterIDs.length @points++ # Get the data file name. getDatafile : -> return @datafile # Get the JSON data. getData : -> return @data # Get number of unique clusters found in data. getClusters : -> return @clusters # Get number of points found in data. getPoints : -> return @points # Get number of saved screenshots. getSaved : -> return @saved module.exports = Storage
[ { "context": "Id\n\t\tUSER_CONTEXT.user = {\n\t\t\t_id: userId\n\t\t\tname: su.name,\n\t\t\tmobile: su.mobile,\n\t\t\tposition: su.position,\n", "end": 2210, "score": 0.9897472262382507, "start": 2203, "tag": "NAME", "value": "su.name" } ]
packages/steedos-creator/core.coffee
zonglu233/fuel-car
0
Creator.Apps = {} Creator.Reports = {} Creator.subs = {} Meteor.startup -> SimpleSchema.extendOptions({filtersFunction: Match.Optional(Match.OneOf(Function, String))}) SimpleSchema.extendOptions({optionsFunction: Match.Optional(Match.OneOf(Function, String))}) SimpleSchema.extendOptions({createFunction: Match.Optional(Match.OneOf(Function, String))}) if Meteor.isServer _.each Creator.Objects, (obj, object_name)-> Creator.loadObjects obj, object_name # Creator.initApps() # Creator.initApps = ()-> # if Meteor.isServer # _.each Creator.Apps, (app, app_id)-> # db_app = db.apps.findOne(app_id) # if !db_app # app._id = app_id # db.apps.insert(app) # else # app._id = app_id # db.apps.update({_id: app_id}, app) Creator.loadObjects = (obj, object_name)-> if !object_name object_name = obj.name if !obj.list_views obj.list_views = {} Creator.convertObject(obj) new Creator.Object(obj); Creator.initTriggers(object_name) Creator.initListViews(object_name) # if Meteor.isServer # Creator.initPermissions(object_name) Creator.getRelativeUrl = (url)-> if url # url开头没有"/",需要添加"/" if !/^\//.test(url) url = "/" + url return __meteor_runtime_config__.ROOT_URL_PATH_PREFIX + url else return __meteor_runtime_config__.ROOT_URL_PATH_PREFIX Creator.getUserContext = (userId, spaceId, isUnSafeMode)-> if Meteor.isClient return Creator.USER_CONTEXT else if !(userId and spaceId) throw new Meteor.Error 500, "the params userId and spaceId is required for the function Creator.getUserContext" return null suFields = {name: 1, mobile: 1, position: 1, email: 1, company: 1, organization: 1, space: 1} # check if user in the space su = Creator.Collections["space_users"].findOne({space: spaceId, user: userId}, {fields: suFields}) if !su spaceId = null # if spaceId not exists, get the first one. if !spaceId if isUnSafeMode su = Creator.Collections["space_users"].findOne({user: userId}, {fields: suFields}) if !su return null spaceId = su.space else return null USER_CONTEXT = {} USER_CONTEXT.userId = userId USER_CONTEXT.spaceId = spaceId USER_CONTEXT.user = { _id: userId name: su.name, mobile: su.mobile, position: su.position, email: su.email company: su.company } space_user_org = Creator.getCollection("organizations")?.findOne(su.organization) if space_user_org USER_CONTEXT.user.organization = { _id: space_user_org._id, name: space_user_org.name, fullname: space_user_org.fullname, is_company: space_user_org.is_company } return USER_CONTEXT Creator.getTable = (object_name)-> return Tabular.tablesByName["creator_" + object_name] Creator.getSchema = (object_name)-> return Creator.getObject(object_name)?.schema Creator.getObjectUrl = (object_name, record_id, app_id) -> if !app_id app_id = Session.get("app_id") if !object_name object_name = Session.get("object_name") list_view = Creator.getListView(object_name, null) list_view_id = list_view?._id if record_id return Creator.getRelativeUrl("/app/" + app_id + "/" + object_name + "/view/" + record_id) else if object_name is "meeting" return Creator.getRelativeUrl("/app/" + app_id + "/" + object_name + "/calendar/") else return Creator.getRelativeUrl("/app/" + app_id + "/" + object_name + "/grid/" + list_view_id) Creator.getListViewUrl = (object_name, app_id, list_view_id) -> if list_view_id is "calendar" return Creator.getRelativeUrl("/app/" + app_id + "/" + object_name + "/calendar/") else return Creator.getRelativeUrl("/app/" + app_id + "/" + object_name + "/grid/" + list_view_id) Creator.getSwitchListUrl = (object_name, app_id, list_view_id) -> if list_view_id return Creator.getRelativeUrl("/app/" + app_id + "/" + object_name + "/" + list_view_id + "/list") else return Creator.getRelativeUrl("/app/" + app_id + "/" + object_name + "/list/switch") Creator.getRelatedObjectUrl = (object_name, app_id, record_id, related_object_name) -> return Creator.getRelativeUrl("/app/" + app_id + "/" + object_name + "/" + record_id + "/" + related_object_name + "/grid") Creator.getObjectLookupFieldOptions = (object_name, is_deep)-> _options = [] _object = Creator.getObject(object_name) fields = _object?.fields icon = _object?.icon _.forEach fields, (f, k)-> if f.type == "select" _options.push {label: "#{f.label || k}", value: "#{k}", icon: icon} else _options.push {label: f.label || k, value: k, icon: icon} if is_deep if (f.type == "lookup" || f.type == "master_detail") && f.reference_to r_object = Creator.getObject(f.reference_to) if r_object _.forEach r_object.fields, (f2, k2)-> _options.push {label: "#{f.label || k}=>#{f2.label || k2}", value: "#{k}.#{k2}", icon: r_object?.icon} return _options Creator.getObjectRecord = (object_name, record_id)-> if !record_id record_id = Session.get("record_id") collection = Creator.getCollection(object_name) if collection return collection.findOne(record_id) # 该函数只在初始化Object时,把相关对象的计算结果保存到Object的related_objects属性中,后续可以直接从related_objects属性中取得计算结果而不用再次调用该函数来计算 Creator.getObjectRelateds = (object_name)-> if Meteor.isClient if !object_name object_name = Session.get("object_name") related_objects = [] # _object = Creator.getObject(object_name) # 因Creator.getObject函数内部要调用该函数,所以这里不可以调用Creator.getObject取对象,只能调用Creator.Objects来取对象 _object = Creator.Objects[object_name] if !_object return related_objects if _object.enable_files related_objects.push {object_name:"cms_files", foreign_key: "parent"} _.each Creator.Objects, (related_object, related_object_name)-> _.each related_object.fields, (related_field, related_field_name)-> if related_field.type == "master_detail" and related_field.reference_to and related_field.reference_to == object_name if related_object_name == "object_fields" #TODO 待相关列表支持排序后,删除此判断 related_objects.splice(0, 0, {object_name:related_object_name, foreign_key: related_field_name}) else related_objects.push {object_name:related_object_name, foreign_key: related_field_name} if _object.enable_tasks related_objects.push {object_name:"tasks", foreign_key: "related_to"} if _object.enable_notes related_objects.push {object_name:"notes", foreign_key: "related_to"} if _object.enable_instances related_objects.push {object_name:"instances", foreign_key: "instances"} return related_objects Creator.getPermissions = (object_name, spaceId, userId)-> if Meteor.isClient if !object_name object_name = Session.get("object_name") obj = Creator.getObject(object_name) if !obj return return obj.permissions.get() else if Meteor.isServer Creator.getObjectPermissions(spaceId, userId, object_name) Creator.getRecordPermissions = (object_name, record, userId)-> if !object_name and Meteor.isClient object_name = Session.get("object_name") permissions = _.clone(Creator.getPermissions(object_name)) if record isOwner = record.owner == userId || record.owner?._id == userId if !permissions.modifyAllRecords and !isOwner permissions.allowEdit = false permissions.allowDelete = false if !permissions.viewAllRecords and !isOwner permissions.allowRead = false return permissions Creator.processPermissions = (po)-> if po.allowCreate po.allowRead = true if po.allowEdit po.allowRead = true if po.allowDelete po.allowEdit = true po.allowRead = true if po.viewAllRecords po.allowRead = true if po.modifyAllRecords po.allowRead = true po.allowEdit = true po.viewAllRecords = true Creator.getApp = (app_id)-> if !app_id app_id = Session.get("app_id") app = Creator.Apps[app_id] Creator.deps?.app?.depend() return app Creator.getVisibleApps = ()-> apps = [] _.each Creator.Apps, (v, k)-> if v.visible != false apps.push v return apps; Creator.getVisibleAppsObjects = ()-> apps = Creator.getVisibleApps() objects = [] tempObjects = [] #_.forEach apps, (app)-> tempObjects = _.filter Creator.Objects, (obj)-> return !obj.hidden objects = objects.concat(tempObjects) objects = objects.sort(Creator.sortingMethod.bind({key:"label"})) objects = _.pluck(objects,'name') return _.uniq objects Creator.getAppsObjects = ()-> objects = [] tempObjects = [] _.forEach Creator.Apps, (app)-> tempObjects = _.filter app.objects, (obj)-> return !obj.hidden objects = objects.concat(tempObjects) return _.uniq objects Creator.validateFilters = (filters, logic)-> filter_items = _.map filters, (obj) -> if _.isEmpty(obj) return false else return obj filter_items = _.compact(filter_items) errorMsg = "" filter_length = filter_items.length if logic # 格式化filter logic = logic.replace(/\n/g, "").replace(/\s+/g, " ") # 判断特殊字符 if /[._\-!+]+/ig.test(logic) errorMsg = "含有特殊字符。" if !errorMsg index = logic.match(/\d+/ig) if !index errorMsg = "有些筛选条件进行了定义,但未在高级筛选条件中被引用。" else index.forEach (i)-> if i < 1 or i > filter_length errorMsg = "您的筛选条件引用了未定义的筛选器:#{i}。" flag = 1 while flag <= filter_length if !index.includes("#{flag}") errorMsg = "有些筛选条件进行了定义,但未在高级筛选条件中被引用。" flag++; if !errorMsg # 判断是否有非法英文字符 word = logic.match(/[a-zA-Z]+/ig) if word word.forEach (w)-> if !/^(and|or)$/ig.test(w) errorMsg = "检查您的高级筛选条件中的拼写。" if !errorMsg # 判断格式是否正确 try Creator.eval(logic.replace(/and/ig, "&&").replace(/or/ig, "||")) catch e errorMsg = "您的筛选器中含有特殊字符" if /(AND)[^()]+(OR)/ig.test(logic) || /(OR)[^()]+(AND)/ig.test(logic) errorMsg = "您的筛选器必须在连续性的 AND 和 OR 表达式前后使用括号。" if errorMsg console.log "error", errorMsg if Meteor.isClient toastr.error(errorMsg) return false else return true # "=", "<>", ">", ">=", "<", "<=", "startswith", "contains", "notcontains". ### options参数: extend-- 是否需要把当前用户基本信息加入公式,即让公式支持Creator.USER_CONTEXT中的值,默认为true userId-- 当前登录用户 spaceId-- 当前所在工作区 extend为true时,后端需要额外传入userId及spaceId用于抓取Creator.USER_CONTEXT对应的值 ### Creator.formatFiltersToMongo = (filters, options)-> unless filters.length return # 当filters不是[Array]类型而是[Object]类型时,进行格式转换 unless filters[0] instanceof Array filters = _.map filters, (obj)-> return [obj.field, obj.operation, obj.value] selector = [] _.each filters, (filter)-> field = filter[0] option = filter[1] if Meteor.isClient value = Creator.evaluateFormula(filter[2]) else value = Creator.evaluateFormula(filter[2], null, options) sub_selector = {} sub_selector[field] = {} if option == "=" sub_selector[field]["$eq"] = value else if option == "<>" sub_selector[field]["$ne"] = value else if option == ">" sub_selector[field]["$gt"] = value else if option == ">=" sub_selector[field]["$gte"] = value else if option == "<" sub_selector[field]["$lt"] = value else if option == "<=" sub_selector[field]["$lte"] = value else if option == "startswith" reg = new RegExp("^" + value, "i") sub_selector[field]["$regex"] = reg else if option == "contains" reg = new RegExp(value, "i") sub_selector[field]["$regex"] = reg else if option == "notcontains" reg = new RegExp("^((?!" + value + ").)*$", "i") sub_selector[field]["$regex"] = reg selector.push sub_selector return selector ### options参数: extend-- 是否需要把当前用户基本信息加入公式,即让公式支持Creator.USER_CONTEXT中的值,默认为true userId-- 当前登录用户 spaceId-- 当前所在工作区 extend为true时,后端需要额外传入userId及spaceId用于抓取Creator.USER_CONTEXT对应的值 ### Creator.formatFiltersToDev = (filters, options)-> unless filters.length return # 当filters不是[Array]类型而是[Object]类型时,进行格式转换 unless filters[0] instanceof Array filters = _.map filters, (obj)-> return [obj.field, obj.operation, obj.value] selector = [] _.each filters, (filter)-> field = filter[0] option = filter[1] if Meteor.isClient value = Creator.evaluateFormula(filter[2]) else value = Creator.evaluateFormula(filter[2], null, options) sub_selector = [] if _.isArray(value) == true v_selector = [] if option == "=" _.each value, (v)-> sub_selector.push [field, option, v], "or" else if option == "<>" _.each value, (v)-> sub_selector.push [field, option, v], "and" else _.each value, (v)-> sub_selector.push [field, option, v], "or" if sub_selector[sub_selector.length - 1] == "and" || sub_selector[sub_selector.length - 1] == "or" sub_selector.pop() selector.push sub_selector, "and" else selector.push [field, option, value], "and" if selector[selector.length - 1] == "and" selector.pop() return selector ### options参数: extend-- 是否需要把当前用户基本信息加入公式,即让公式支持Creator.USER_CONTEXT中的值,默认为true userId-- 当前登录用户 spaceId-- 当前所在工作区 extend为true时,后端需要额外传入userId及spaceId用于抓取Creator.USER_CONTEXT对应的值 ### Creator.formatLogicFiltersToDev = (filters, filter_logic, options)-> format_logic = filter_logic.replace(/\(\s+/ig, "(").replace(/\s+\)/ig, ")").replace(/\(/g, "[").replace(/\)/g, "]").replace(/\s+/g, ",").replace(/(and|or)/ig, "'$1'") format_logic = format_logic.replace(/(\d)+/ig, (x)-> _f = filters[x-1] field = _f.field option = _f.operation if Meteor.isClient value = Creator.evaluateFormula(_f.value) else value = Creator.evaluateFormula(_f.value, null, options) sub_selector = [] if _.isArray(value) == true if option == "=" _.each value, (v)-> sub_selector.push [field, option, v], "or" else if option == "<>" _.each value, (v)-> sub_selector.push [field, option, v], "and" else _.each value, (v)-> sub_selector.push [field, option, v], "or" if sub_selector[sub_selector.length - 1] == "and" || sub_selector[sub_selector.length - 1] == "or" sub_selector.pop() else sub_selector = [field, option, value] console.log "sub_selector", sub_selector return JSON.stringify(sub_selector) ) format_logic = "[#{format_logic}]" return Creator.eval(format_logic) Creator.getRelatedObjects = (object_name, spaceId, userId)-> if Meteor.isClient if !object_name object_name = Session.get("object_name") if !spaceId spaceId = Session.get("spaceId") if !userId userId = Meteor.userId() related_object_names = [] _object = Creator.getObject(object_name) if !_object return related_object_names related_object_names = _.pluck(_object.related_objects,"object_name") if related_object_names?.length == 0 return related_object_names permissions = Creator.getPermissions(object_name, spaceId, userId) unrelated_objects = permissions.unrelated_objects related_object_names = _.difference related_object_names, unrelated_objects return _.filter _object.related_objects, (related_object)-> related_object_name = related_object.object_name isActive = related_object_names.indexOf(related_object_name) > -1 allowRead = Creator.getPermissions(related_object_name, spaceId, userId)?.allowRead return isActive and allowRead Creator.getRelatedObjectNames = (object_name, spaceId, userId)-> related_objects = Creator.getRelatedObjects(object_name, spaceId, userId) return _.pluck(related_objects,"object_name") Creator.getActions = (object_name, spaceId, userId)-> if Meteor.isClient if !object_name object_name = Session.get("object_name") if !spaceId spaceId = Session.get("spaceId") if !userId userId = Meteor.userId() obj = Creator.getObject(object_name) if !obj return permissions = Creator.getPermissions(object_name, spaceId, userId) disabled_actions = permissions.disabled_actions actions = _.sortBy(_.values(obj.actions) , 'sort'); actions = _.filter actions, (action)-> return _.indexOf(disabled_actions, action.name) < 0 return actions /// 返回当前用户有权限访问的所有list_view,包括分享的,用户自定义非分享的(除非owner变了),以及默认的其他视图 注意Creator.getPermissions函数中是不会有用户自定义非分享的视图的,所以Creator.getPermissions函数中拿到的结果不全,并不是当前用户能看到所有视图 /// Creator.getListViews = (object_name, spaceId, userId)-> if Meteor.isClient if !object_name object_name = Session.get("object_name") if !spaceId spaceId = Session.get("spaceId") if !userId userId = Meteor.userId() object = Creator.getObject(object_name) if !object return disabled_list_views = Creator.getPermissions(object_name, spaceId, userId).disabled_list_views || [] list_views = [] _.each object.list_views, (item, item_name)-> if item_name != "default" if _.indexOf(disabled_list_views, item_name) < 0 || item.owner == userId list_views.push item return list_views # 前台理论上不应该调用该函数,因为字段的权限都在Creator.getObject(object_name).fields的相关属性中有标识了 Creator.getFields = (object_name, spaceId, userId)-> if Meteor.isClient if !object_name object_name = Session.get("object_name") if !spaceId spaceId = Session.get("spaceId") if !userId userId = Meteor.userId() fieldsName = Creator.getObjectFieldsName(object_name) unreadable_fields = Creator.getPermissions(object_name, spaceId, userId).unreadable_fields return _.difference(fieldsName, unreadable_fields) Creator.isloading = ()-> return !Creator.bootstrapLoaded.get() Creator.convertSpecialCharacter = (str)-> return str.replace(/([\^\$\(\)\*\+\?\.\\\|\[\]\{\}])/g, "\\$1") # 计算fields相关函数 # START Creator.getDisabledFields = (schema)-> fields = _.map(schema, (field, fieldName) -> return field.autoform and field.autoform.disabled and !field.autoform.omit and fieldName ) fields = _.compact(fields) return fields Creator.getHiddenFields = (schema)-> fields = _.map(schema, (field, fieldName) -> return field.autoform and field.autoform.type == "hidden" and !field.autoform.omit and fieldName ) fields = _.compact(fields) return fields Creator.getFieldsWithNoGroup = (schema)-> fields = _.map(schema, (field, fieldName) -> return (!field.autoform or !field.autoform.group or field.autoform.group == "-") and (!field.autoform or field.autoform.type != "hidden") and fieldName ) fields = _.compact(fields) return fields Creator.getSortedFieldGroupNames = (schema)-> names = _.map(schema, (field) -> return field.autoform and field.autoform.group != "-" and field.autoform.group ) names = _.compact(names) names = _.unique(names) return names Creator.getFieldsForGroup = (schema, groupName) -> fields = _.map(schema, (field, fieldName) -> return field.autoform and field.autoform.group == groupName and field.autoform.type != "hidden" and fieldName ) fields = _.compact(fields) return fields Creator.getFieldsWithoutOmit = (schema, keys) -> keys = _.map(keys, (key) -> field = _.pick(schema, key) if field[key].autoform?.omit return false else return key ) keys = _.compact(keys) return keys Creator.getFieldsInFirstLevel = (firstLevelKeys, keys) -> keys = _.map(keys, (key) -> if _.indexOf(firstLevelKeys, key) > -1 return key else return false ) keys = _.compact(keys) return keys Creator.getFieldsForReorder = (schema, keys, isSingle) -> fields = [] i = 0 while i < keys.length sc_1 = _.pick(schema, keys[i]) sc_2 = _.pick(schema, keys[i+1]) is_wide_1 = false is_wide_2 = false _.each sc_1, (value) -> if value.autoform?.is_wide || value.autoform?.type == "table" is_wide_1 = true _.each sc_2, (value) -> if value.autoform?.is_wide || value.autoform?.type == "table" is_wide_2 = true if isSingle fields.push keys.slice(i, i+1) i += 1 else if is_wide_1 fields.push keys.slice(i, i+1) i += 1 else if !is_wide_1 and is_wide_2 childKeys = keys.slice(i, i+1) childKeys.push undefined fields.push childKeys i += 1 else if !is_wide_1 and !is_wide_2 childKeys = keys.slice(i, i+1) if keys[i+1] childKeys.push keys[i+1] else childKeys.push undefined fields.push childKeys i += 2 return fields Creator.getDBApps = (space_id)-> dbApps = {} Creator.Collections["apps"].find({space: space_id,is_creator:true,visible:true}, { fields: { created: 0, created_by: 0, modified: 0, modified_by: 0 } }).forEach (app)-> dbApps[app._id] = app return dbApps # END if Meteor.isServer Creator.getAllRelatedObjects = (object_name)-> related_object_names = [] _.each Creator.Objects, (related_object, related_object_name)-> _.each related_object.fields, (related_field, related_field_name)-> if related_field.type == "master_detail" and related_field.reference_to and related_field.reference_to == object_name related_object_names.push related_object_name if Creator.getObject(object_name).enable_files related_object_names.push "cms_files" return related_object_names
86847
Creator.Apps = {} Creator.Reports = {} Creator.subs = {} Meteor.startup -> SimpleSchema.extendOptions({filtersFunction: Match.Optional(Match.OneOf(Function, String))}) SimpleSchema.extendOptions({optionsFunction: Match.Optional(Match.OneOf(Function, String))}) SimpleSchema.extendOptions({createFunction: Match.Optional(Match.OneOf(Function, String))}) if Meteor.isServer _.each Creator.Objects, (obj, object_name)-> Creator.loadObjects obj, object_name # Creator.initApps() # Creator.initApps = ()-> # if Meteor.isServer # _.each Creator.Apps, (app, app_id)-> # db_app = db.apps.findOne(app_id) # if !db_app # app._id = app_id # db.apps.insert(app) # else # app._id = app_id # db.apps.update({_id: app_id}, app) Creator.loadObjects = (obj, object_name)-> if !object_name object_name = obj.name if !obj.list_views obj.list_views = {} Creator.convertObject(obj) new Creator.Object(obj); Creator.initTriggers(object_name) Creator.initListViews(object_name) # if Meteor.isServer # Creator.initPermissions(object_name) Creator.getRelativeUrl = (url)-> if url # url开头没有"/",需要添加"/" if !/^\//.test(url) url = "/" + url return __meteor_runtime_config__.ROOT_URL_PATH_PREFIX + url else return __meteor_runtime_config__.ROOT_URL_PATH_PREFIX Creator.getUserContext = (userId, spaceId, isUnSafeMode)-> if Meteor.isClient return Creator.USER_CONTEXT else if !(userId and spaceId) throw new Meteor.Error 500, "the params userId and spaceId is required for the function Creator.getUserContext" return null suFields = {name: 1, mobile: 1, position: 1, email: 1, company: 1, organization: 1, space: 1} # check if user in the space su = Creator.Collections["space_users"].findOne({space: spaceId, user: userId}, {fields: suFields}) if !su spaceId = null # if spaceId not exists, get the first one. if !spaceId if isUnSafeMode su = Creator.Collections["space_users"].findOne({user: userId}, {fields: suFields}) if !su return null spaceId = su.space else return null USER_CONTEXT = {} USER_CONTEXT.userId = userId USER_CONTEXT.spaceId = spaceId USER_CONTEXT.user = { _id: userId name: <NAME>, mobile: su.mobile, position: su.position, email: su.email company: su.company } space_user_org = Creator.getCollection("organizations")?.findOne(su.organization) if space_user_org USER_CONTEXT.user.organization = { _id: space_user_org._id, name: space_user_org.name, fullname: space_user_org.fullname, is_company: space_user_org.is_company } return USER_CONTEXT Creator.getTable = (object_name)-> return Tabular.tablesByName["creator_" + object_name] Creator.getSchema = (object_name)-> return Creator.getObject(object_name)?.schema Creator.getObjectUrl = (object_name, record_id, app_id) -> if !app_id app_id = Session.get("app_id") if !object_name object_name = Session.get("object_name") list_view = Creator.getListView(object_name, null) list_view_id = list_view?._id if record_id return Creator.getRelativeUrl("/app/" + app_id + "/" + object_name + "/view/" + record_id) else if object_name is "meeting" return Creator.getRelativeUrl("/app/" + app_id + "/" + object_name + "/calendar/") else return Creator.getRelativeUrl("/app/" + app_id + "/" + object_name + "/grid/" + list_view_id) Creator.getListViewUrl = (object_name, app_id, list_view_id) -> if list_view_id is "calendar" return Creator.getRelativeUrl("/app/" + app_id + "/" + object_name + "/calendar/") else return Creator.getRelativeUrl("/app/" + app_id + "/" + object_name + "/grid/" + list_view_id) Creator.getSwitchListUrl = (object_name, app_id, list_view_id) -> if list_view_id return Creator.getRelativeUrl("/app/" + app_id + "/" + object_name + "/" + list_view_id + "/list") else return Creator.getRelativeUrl("/app/" + app_id + "/" + object_name + "/list/switch") Creator.getRelatedObjectUrl = (object_name, app_id, record_id, related_object_name) -> return Creator.getRelativeUrl("/app/" + app_id + "/" + object_name + "/" + record_id + "/" + related_object_name + "/grid") Creator.getObjectLookupFieldOptions = (object_name, is_deep)-> _options = [] _object = Creator.getObject(object_name) fields = _object?.fields icon = _object?.icon _.forEach fields, (f, k)-> if f.type == "select" _options.push {label: "#{f.label || k}", value: "#{k}", icon: icon} else _options.push {label: f.label || k, value: k, icon: icon} if is_deep if (f.type == "lookup" || f.type == "master_detail") && f.reference_to r_object = Creator.getObject(f.reference_to) if r_object _.forEach r_object.fields, (f2, k2)-> _options.push {label: "#{f.label || k}=>#{f2.label || k2}", value: "#{k}.#{k2}", icon: r_object?.icon} return _options Creator.getObjectRecord = (object_name, record_id)-> if !record_id record_id = Session.get("record_id") collection = Creator.getCollection(object_name) if collection return collection.findOne(record_id) # 该函数只在初始化Object时,把相关对象的计算结果保存到Object的related_objects属性中,后续可以直接从related_objects属性中取得计算结果而不用再次调用该函数来计算 Creator.getObjectRelateds = (object_name)-> if Meteor.isClient if !object_name object_name = Session.get("object_name") related_objects = [] # _object = Creator.getObject(object_name) # 因Creator.getObject函数内部要调用该函数,所以这里不可以调用Creator.getObject取对象,只能调用Creator.Objects来取对象 _object = Creator.Objects[object_name] if !_object return related_objects if _object.enable_files related_objects.push {object_name:"cms_files", foreign_key: "parent"} _.each Creator.Objects, (related_object, related_object_name)-> _.each related_object.fields, (related_field, related_field_name)-> if related_field.type == "master_detail" and related_field.reference_to and related_field.reference_to == object_name if related_object_name == "object_fields" #TODO 待相关列表支持排序后,删除此判断 related_objects.splice(0, 0, {object_name:related_object_name, foreign_key: related_field_name}) else related_objects.push {object_name:related_object_name, foreign_key: related_field_name} if _object.enable_tasks related_objects.push {object_name:"tasks", foreign_key: "related_to"} if _object.enable_notes related_objects.push {object_name:"notes", foreign_key: "related_to"} if _object.enable_instances related_objects.push {object_name:"instances", foreign_key: "instances"} return related_objects Creator.getPermissions = (object_name, spaceId, userId)-> if Meteor.isClient if !object_name object_name = Session.get("object_name") obj = Creator.getObject(object_name) if !obj return return obj.permissions.get() else if Meteor.isServer Creator.getObjectPermissions(spaceId, userId, object_name) Creator.getRecordPermissions = (object_name, record, userId)-> if !object_name and Meteor.isClient object_name = Session.get("object_name") permissions = _.clone(Creator.getPermissions(object_name)) if record isOwner = record.owner == userId || record.owner?._id == userId if !permissions.modifyAllRecords and !isOwner permissions.allowEdit = false permissions.allowDelete = false if !permissions.viewAllRecords and !isOwner permissions.allowRead = false return permissions Creator.processPermissions = (po)-> if po.allowCreate po.allowRead = true if po.allowEdit po.allowRead = true if po.allowDelete po.allowEdit = true po.allowRead = true if po.viewAllRecords po.allowRead = true if po.modifyAllRecords po.allowRead = true po.allowEdit = true po.viewAllRecords = true Creator.getApp = (app_id)-> if !app_id app_id = Session.get("app_id") app = Creator.Apps[app_id] Creator.deps?.app?.depend() return app Creator.getVisibleApps = ()-> apps = [] _.each Creator.Apps, (v, k)-> if v.visible != false apps.push v return apps; Creator.getVisibleAppsObjects = ()-> apps = Creator.getVisibleApps() objects = [] tempObjects = [] #_.forEach apps, (app)-> tempObjects = _.filter Creator.Objects, (obj)-> return !obj.hidden objects = objects.concat(tempObjects) objects = objects.sort(Creator.sortingMethod.bind({key:"label"})) objects = _.pluck(objects,'name') return _.uniq objects Creator.getAppsObjects = ()-> objects = [] tempObjects = [] _.forEach Creator.Apps, (app)-> tempObjects = _.filter app.objects, (obj)-> return !obj.hidden objects = objects.concat(tempObjects) return _.uniq objects Creator.validateFilters = (filters, logic)-> filter_items = _.map filters, (obj) -> if _.isEmpty(obj) return false else return obj filter_items = _.compact(filter_items) errorMsg = "" filter_length = filter_items.length if logic # 格式化filter logic = logic.replace(/\n/g, "").replace(/\s+/g, " ") # 判断特殊字符 if /[._\-!+]+/ig.test(logic) errorMsg = "含有特殊字符。" if !errorMsg index = logic.match(/\d+/ig) if !index errorMsg = "有些筛选条件进行了定义,但未在高级筛选条件中被引用。" else index.forEach (i)-> if i < 1 or i > filter_length errorMsg = "您的筛选条件引用了未定义的筛选器:#{i}。" flag = 1 while flag <= filter_length if !index.includes("#{flag}") errorMsg = "有些筛选条件进行了定义,但未在高级筛选条件中被引用。" flag++; if !errorMsg # 判断是否有非法英文字符 word = logic.match(/[a-zA-Z]+/ig) if word word.forEach (w)-> if !/^(and|or)$/ig.test(w) errorMsg = "检查您的高级筛选条件中的拼写。" if !errorMsg # 判断格式是否正确 try Creator.eval(logic.replace(/and/ig, "&&").replace(/or/ig, "||")) catch e errorMsg = "您的筛选器中含有特殊字符" if /(AND)[^()]+(OR)/ig.test(logic) || /(OR)[^()]+(AND)/ig.test(logic) errorMsg = "您的筛选器必须在连续性的 AND 和 OR 表达式前后使用括号。" if errorMsg console.log "error", errorMsg if Meteor.isClient toastr.error(errorMsg) return false else return true # "=", "<>", ">", ">=", "<", "<=", "startswith", "contains", "notcontains". ### options参数: extend-- 是否需要把当前用户基本信息加入公式,即让公式支持Creator.USER_CONTEXT中的值,默认为true userId-- 当前登录用户 spaceId-- 当前所在工作区 extend为true时,后端需要额外传入userId及spaceId用于抓取Creator.USER_CONTEXT对应的值 ### Creator.formatFiltersToMongo = (filters, options)-> unless filters.length return # 当filters不是[Array]类型而是[Object]类型时,进行格式转换 unless filters[0] instanceof Array filters = _.map filters, (obj)-> return [obj.field, obj.operation, obj.value] selector = [] _.each filters, (filter)-> field = filter[0] option = filter[1] if Meteor.isClient value = Creator.evaluateFormula(filter[2]) else value = Creator.evaluateFormula(filter[2], null, options) sub_selector = {} sub_selector[field] = {} if option == "=" sub_selector[field]["$eq"] = value else if option == "<>" sub_selector[field]["$ne"] = value else if option == ">" sub_selector[field]["$gt"] = value else if option == ">=" sub_selector[field]["$gte"] = value else if option == "<" sub_selector[field]["$lt"] = value else if option == "<=" sub_selector[field]["$lte"] = value else if option == "startswith" reg = new RegExp("^" + value, "i") sub_selector[field]["$regex"] = reg else if option == "contains" reg = new RegExp(value, "i") sub_selector[field]["$regex"] = reg else if option == "notcontains" reg = new RegExp("^((?!" + value + ").)*$", "i") sub_selector[field]["$regex"] = reg selector.push sub_selector return selector ### options参数: extend-- 是否需要把当前用户基本信息加入公式,即让公式支持Creator.USER_CONTEXT中的值,默认为true userId-- 当前登录用户 spaceId-- 当前所在工作区 extend为true时,后端需要额外传入userId及spaceId用于抓取Creator.USER_CONTEXT对应的值 ### Creator.formatFiltersToDev = (filters, options)-> unless filters.length return # 当filters不是[Array]类型而是[Object]类型时,进行格式转换 unless filters[0] instanceof Array filters = _.map filters, (obj)-> return [obj.field, obj.operation, obj.value] selector = [] _.each filters, (filter)-> field = filter[0] option = filter[1] if Meteor.isClient value = Creator.evaluateFormula(filter[2]) else value = Creator.evaluateFormula(filter[2], null, options) sub_selector = [] if _.isArray(value) == true v_selector = [] if option == "=" _.each value, (v)-> sub_selector.push [field, option, v], "or" else if option == "<>" _.each value, (v)-> sub_selector.push [field, option, v], "and" else _.each value, (v)-> sub_selector.push [field, option, v], "or" if sub_selector[sub_selector.length - 1] == "and" || sub_selector[sub_selector.length - 1] == "or" sub_selector.pop() selector.push sub_selector, "and" else selector.push [field, option, value], "and" if selector[selector.length - 1] == "and" selector.pop() return selector ### options参数: extend-- 是否需要把当前用户基本信息加入公式,即让公式支持Creator.USER_CONTEXT中的值,默认为true userId-- 当前登录用户 spaceId-- 当前所在工作区 extend为true时,后端需要额外传入userId及spaceId用于抓取Creator.USER_CONTEXT对应的值 ### Creator.formatLogicFiltersToDev = (filters, filter_logic, options)-> format_logic = filter_logic.replace(/\(\s+/ig, "(").replace(/\s+\)/ig, ")").replace(/\(/g, "[").replace(/\)/g, "]").replace(/\s+/g, ",").replace(/(and|or)/ig, "'$1'") format_logic = format_logic.replace(/(\d)+/ig, (x)-> _f = filters[x-1] field = _f.field option = _f.operation if Meteor.isClient value = Creator.evaluateFormula(_f.value) else value = Creator.evaluateFormula(_f.value, null, options) sub_selector = [] if _.isArray(value) == true if option == "=" _.each value, (v)-> sub_selector.push [field, option, v], "or" else if option == "<>" _.each value, (v)-> sub_selector.push [field, option, v], "and" else _.each value, (v)-> sub_selector.push [field, option, v], "or" if sub_selector[sub_selector.length - 1] == "and" || sub_selector[sub_selector.length - 1] == "or" sub_selector.pop() else sub_selector = [field, option, value] console.log "sub_selector", sub_selector return JSON.stringify(sub_selector) ) format_logic = "[#{format_logic}]" return Creator.eval(format_logic) Creator.getRelatedObjects = (object_name, spaceId, userId)-> if Meteor.isClient if !object_name object_name = Session.get("object_name") if !spaceId spaceId = Session.get("spaceId") if !userId userId = Meteor.userId() related_object_names = [] _object = Creator.getObject(object_name) if !_object return related_object_names related_object_names = _.pluck(_object.related_objects,"object_name") if related_object_names?.length == 0 return related_object_names permissions = Creator.getPermissions(object_name, spaceId, userId) unrelated_objects = permissions.unrelated_objects related_object_names = _.difference related_object_names, unrelated_objects return _.filter _object.related_objects, (related_object)-> related_object_name = related_object.object_name isActive = related_object_names.indexOf(related_object_name) > -1 allowRead = Creator.getPermissions(related_object_name, spaceId, userId)?.allowRead return isActive and allowRead Creator.getRelatedObjectNames = (object_name, spaceId, userId)-> related_objects = Creator.getRelatedObjects(object_name, spaceId, userId) return _.pluck(related_objects,"object_name") Creator.getActions = (object_name, spaceId, userId)-> if Meteor.isClient if !object_name object_name = Session.get("object_name") if !spaceId spaceId = Session.get("spaceId") if !userId userId = Meteor.userId() obj = Creator.getObject(object_name) if !obj return permissions = Creator.getPermissions(object_name, spaceId, userId) disabled_actions = permissions.disabled_actions actions = _.sortBy(_.values(obj.actions) , 'sort'); actions = _.filter actions, (action)-> return _.indexOf(disabled_actions, action.name) < 0 return actions /// 返回当前用户有权限访问的所有list_view,包括分享的,用户自定义非分享的(除非owner变了),以及默认的其他视图 注意Creator.getPermissions函数中是不会有用户自定义非分享的视图的,所以Creator.getPermissions函数中拿到的结果不全,并不是当前用户能看到所有视图 /// Creator.getListViews = (object_name, spaceId, userId)-> if Meteor.isClient if !object_name object_name = Session.get("object_name") if !spaceId spaceId = Session.get("spaceId") if !userId userId = Meteor.userId() object = Creator.getObject(object_name) if !object return disabled_list_views = Creator.getPermissions(object_name, spaceId, userId).disabled_list_views || [] list_views = [] _.each object.list_views, (item, item_name)-> if item_name != "default" if _.indexOf(disabled_list_views, item_name) < 0 || item.owner == userId list_views.push item return list_views # 前台理论上不应该调用该函数,因为字段的权限都在Creator.getObject(object_name).fields的相关属性中有标识了 Creator.getFields = (object_name, spaceId, userId)-> if Meteor.isClient if !object_name object_name = Session.get("object_name") if !spaceId spaceId = Session.get("spaceId") if !userId userId = Meteor.userId() fieldsName = Creator.getObjectFieldsName(object_name) unreadable_fields = Creator.getPermissions(object_name, spaceId, userId).unreadable_fields return _.difference(fieldsName, unreadable_fields) Creator.isloading = ()-> return !Creator.bootstrapLoaded.get() Creator.convertSpecialCharacter = (str)-> return str.replace(/([\^\$\(\)\*\+\?\.\\\|\[\]\{\}])/g, "\\$1") # 计算fields相关函数 # START Creator.getDisabledFields = (schema)-> fields = _.map(schema, (field, fieldName) -> return field.autoform and field.autoform.disabled and !field.autoform.omit and fieldName ) fields = _.compact(fields) return fields Creator.getHiddenFields = (schema)-> fields = _.map(schema, (field, fieldName) -> return field.autoform and field.autoform.type == "hidden" and !field.autoform.omit and fieldName ) fields = _.compact(fields) return fields Creator.getFieldsWithNoGroup = (schema)-> fields = _.map(schema, (field, fieldName) -> return (!field.autoform or !field.autoform.group or field.autoform.group == "-") and (!field.autoform or field.autoform.type != "hidden") and fieldName ) fields = _.compact(fields) return fields Creator.getSortedFieldGroupNames = (schema)-> names = _.map(schema, (field) -> return field.autoform and field.autoform.group != "-" and field.autoform.group ) names = _.compact(names) names = _.unique(names) return names Creator.getFieldsForGroup = (schema, groupName) -> fields = _.map(schema, (field, fieldName) -> return field.autoform and field.autoform.group == groupName and field.autoform.type != "hidden" and fieldName ) fields = _.compact(fields) return fields Creator.getFieldsWithoutOmit = (schema, keys) -> keys = _.map(keys, (key) -> field = _.pick(schema, key) if field[key].autoform?.omit return false else return key ) keys = _.compact(keys) return keys Creator.getFieldsInFirstLevel = (firstLevelKeys, keys) -> keys = _.map(keys, (key) -> if _.indexOf(firstLevelKeys, key) > -1 return key else return false ) keys = _.compact(keys) return keys Creator.getFieldsForReorder = (schema, keys, isSingle) -> fields = [] i = 0 while i < keys.length sc_1 = _.pick(schema, keys[i]) sc_2 = _.pick(schema, keys[i+1]) is_wide_1 = false is_wide_2 = false _.each sc_1, (value) -> if value.autoform?.is_wide || value.autoform?.type == "table" is_wide_1 = true _.each sc_2, (value) -> if value.autoform?.is_wide || value.autoform?.type == "table" is_wide_2 = true if isSingle fields.push keys.slice(i, i+1) i += 1 else if is_wide_1 fields.push keys.slice(i, i+1) i += 1 else if !is_wide_1 and is_wide_2 childKeys = keys.slice(i, i+1) childKeys.push undefined fields.push childKeys i += 1 else if !is_wide_1 and !is_wide_2 childKeys = keys.slice(i, i+1) if keys[i+1] childKeys.push keys[i+1] else childKeys.push undefined fields.push childKeys i += 2 return fields Creator.getDBApps = (space_id)-> dbApps = {} Creator.Collections["apps"].find({space: space_id,is_creator:true,visible:true}, { fields: { created: 0, created_by: 0, modified: 0, modified_by: 0 } }).forEach (app)-> dbApps[app._id] = app return dbApps # END if Meteor.isServer Creator.getAllRelatedObjects = (object_name)-> related_object_names = [] _.each Creator.Objects, (related_object, related_object_name)-> _.each related_object.fields, (related_field, related_field_name)-> if related_field.type == "master_detail" and related_field.reference_to and related_field.reference_to == object_name related_object_names.push related_object_name if Creator.getObject(object_name).enable_files related_object_names.push "cms_files" return related_object_names
true
Creator.Apps = {} Creator.Reports = {} Creator.subs = {} Meteor.startup -> SimpleSchema.extendOptions({filtersFunction: Match.Optional(Match.OneOf(Function, String))}) SimpleSchema.extendOptions({optionsFunction: Match.Optional(Match.OneOf(Function, String))}) SimpleSchema.extendOptions({createFunction: Match.Optional(Match.OneOf(Function, String))}) if Meteor.isServer _.each Creator.Objects, (obj, object_name)-> Creator.loadObjects obj, object_name # Creator.initApps() # Creator.initApps = ()-> # if Meteor.isServer # _.each Creator.Apps, (app, app_id)-> # db_app = db.apps.findOne(app_id) # if !db_app # app._id = app_id # db.apps.insert(app) # else # app._id = app_id # db.apps.update({_id: app_id}, app) Creator.loadObjects = (obj, object_name)-> if !object_name object_name = obj.name if !obj.list_views obj.list_views = {} Creator.convertObject(obj) new Creator.Object(obj); Creator.initTriggers(object_name) Creator.initListViews(object_name) # if Meteor.isServer # Creator.initPermissions(object_name) Creator.getRelativeUrl = (url)-> if url # url开头没有"/",需要添加"/" if !/^\//.test(url) url = "/" + url return __meteor_runtime_config__.ROOT_URL_PATH_PREFIX + url else return __meteor_runtime_config__.ROOT_URL_PATH_PREFIX Creator.getUserContext = (userId, spaceId, isUnSafeMode)-> if Meteor.isClient return Creator.USER_CONTEXT else if !(userId and spaceId) throw new Meteor.Error 500, "the params userId and spaceId is required for the function Creator.getUserContext" return null suFields = {name: 1, mobile: 1, position: 1, email: 1, company: 1, organization: 1, space: 1} # check if user in the space su = Creator.Collections["space_users"].findOne({space: spaceId, user: userId}, {fields: suFields}) if !su spaceId = null # if spaceId not exists, get the first one. if !spaceId if isUnSafeMode su = Creator.Collections["space_users"].findOne({user: userId}, {fields: suFields}) if !su return null spaceId = su.space else return null USER_CONTEXT = {} USER_CONTEXT.userId = userId USER_CONTEXT.spaceId = spaceId USER_CONTEXT.user = { _id: userId name: PI:NAME:<NAME>END_PI, mobile: su.mobile, position: su.position, email: su.email company: su.company } space_user_org = Creator.getCollection("organizations")?.findOne(su.organization) if space_user_org USER_CONTEXT.user.organization = { _id: space_user_org._id, name: space_user_org.name, fullname: space_user_org.fullname, is_company: space_user_org.is_company } return USER_CONTEXT Creator.getTable = (object_name)-> return Tabular.tablesByName["creator_" + object_name] Creator.getSchema = (object_name)-> return Creator.getObject(object_name)?.schema Creator.getObjectUrl = (object_name, record_id, app_id) -> if !app_id app_id = Session.get("app_id") if !object_name object_name = Session.get("object_name") list_view = Creator.getListView(object_name, null) list_view_id = list_view?._id if record_id return Creator.getRelativeUrl("/app/" + app_id + "/" + object_name + "/view/" + record_id) else if object_name is "meeting" return Creator.getRelativeUrl("/app/" + app_id + "/" + object_name + "/calendar/") else return Creator.getRelativeUrl("/app/" + app_id + "/" + object_name + "/grid/" + list_view_id) Creator.getListViewUrl = (object_name, app_id, list_view_id) -> if list_view_id is "calendar" return Creator.getRelativeUrl("/app/" + app_id + "/" + object_name + "/calendar/") else return Creator.getRelativeUrl("/app/" + app_id + "/" + object_name + "/grid/" + list_view_id) Creator.getSwitchListUrl = (object_name, app_id, list_view_id) -> if list_view_id return Creator.getRelativeUrl("/app/" + app_id + "/" + object_name + "/" + list_view_id + "/list") else return Creator.getRelativeUrl("/app/" + app_id + "/" + object_name + "/list/switch") Creator.getRelatedObjectUrl = (object_name, app_id, record_id, related_object_name) -> return Creator.getRelativeUrl("/app/" + app_id + "/" + object_name + "/" + record_id + "/" + related_object_name + "/grid") Creator.getObjectLookupFieldOptions = (object_name, is_deep)-> _options = [] _object = Creator.getObject(object_name) fields = _object?.fields icon = _object?.icon _.forEach fields, (f, k)-> if f.type == "select" _options.push {label: "#{f.label || k}", value: "#{k}", icon: icon} else _options.push {label: f.label || k, value: k, icon: icon} if is_deep if (f.type == "lookup" || f.type == "master_detail") && f.reference_to r_object = Creator.getObject(f.reference_to) if r_object _.forEach r_object.fields, (f2, k2)-> _options.push {label: "#{f.label || k}=>#{f2.label || k2}", value: "#{k}.#{k2}", icon: r_object?.icon} return _options Creator.getObjectRecord = (object_name, record_id)-> if !record_id record_id = Session.get("record_id") collection = Creator.getCollection(object_name) if collection return collection.findOne(record_id) # 该函数只在初始化Object时,把相关对象的计算结果保存到Object的related_objects属性中,后续可以直接从related_objects属性中取得计算结果而不用再次调用该函数来计算 Creator.getObjectRelateds = (object_name)-> if Meteor.isClient if !object_name object_name = Session.get("object_name") related_objects = [] # _object = Creator.getObject(object_name) # 因Creator.getObject函数内部要调用该函数,所以这里不可以调用Creator.getObject取对象,只能调用Creator.Objects来取对象 _object = Creator.Objects[object_name] if !_object return related_objects if _object.enable_files related_objects.push {object_name:"cms_files", foreign_key: "parent"} _.each Creator.Objects, (related_object, related_object_name)-> _.each related_object.fields, (related_field, related_field_name)-> if related_field.type == "master_detail" and related_field.reference_to and related_field.reference_to == object_name if related_object_name == "object_fields" #TODO 待相关列表支持排序后,删除此判断 related_objects.splice(0, 0, {object_name:related_object_name, foreign_key: related_field_name}) else related_objects.push {object_name:related_object_name, foreign_key: related_field_name} if _object.enable_tasks related_objects.push {object_name:"tasks", foreign_key: "related_to"} if _object.enable_notes related_objects.push {object_name:"notes", foreign_key: "related_to"} if _object.enable_instances related_objects.push {object_name:"instances", foreign_key: "instances"} return related_objects Creator.getPermissions = (object_name, spaceId, userId)-> if Meteor.isClient if !object_name object_name = Session.get("object_name") obj = Creator.getObject(object_name) if !obj return return obj.permissions.get() else if Meteor.isServer Creator.getObjectPermissions(spaceId, userId, object_name) Creator.getRecordPermissions = (object_name, record, userId)-> if !object_name and Meteor.isClient object_name = Session.get("object_name") permissions = _.clone(Creator.getPermissions(object_name)) if record isOwner = record.owner == userId || record.owner?._id == userId if !permissions.modifyAllRecords and !isOwner permissions.allowEdit = false permissions.allowDelete = false if !permissions.viewAllRecords and !isOwner permissions.allowRead = false return permissions Creator.processPermissions = (po)-> if po.allowCreate po.allowRead = true if po.allowEdit po.allowRead = true if po.allowDelete po.allowEdit = true po.allowRead = true if po.viewAllRecords po.allowRead = true if po.modifyAllRecords po.allowRead = true po.allowEdit = true po.viewAllRecords = true Creator.getApp = (app_id)-> if !app_id app_id = Session.get("app_id") app = Creator.Apps[app_id] Creator.deps?.app?.depend() return app Creator.getVisibleApps = ()-> apps = [] _.each Creator.Apps, (v, k)-> if v.visible != false apps.push v return apps; Creator.getVisibleAppsObjects = ()-> apps = Creator.getVisibleApps() objects = [] tempObjects = [] #_.forEach apps, (app)-> tempObjects = _.filter Creator.Objects, (obj)-> return !obj.hidden objects = objects.concat(tempObjects) objects = objects.sort(Creator.sortingMethod.bind({key:"label"})) objects = _.pluck(objects,'name') return _.uniq objects Creator.getAppsObjects = ()-> objects = [] tempObjects = [] _.forEach Creator.Apps, (app)-> tempObjects = _.filter app.objects, (obj)-> return !obj.hidden objects = objects.concat(tempObjects) return _.uniq objects Creator.validateFilters = (filters, logic)-> filter_items = _.map filters, (obj) -> if _.isEmpty(obj) return false else return obj filter_items = _.compact(filter_items) errorMsg = "" filter_length = filter_items.length if logic # 格式化filter logic = logic.replace(/\n/g, "").replace(/\s+/g, " ") # 判断特殊字符 if /[._\-!+]+/ig.test(logic) errorMsg = "含有特殊字符。" if !errorMsg index = logic.match(/\d+/ig) if !index errorMsg = "有些筛选条件进行了定义,但未在高级筛选条件中被引用。" else index.forEach (i)-> if i < 1 or i > filter_length errorMsg = "您的筛选条件引用了未定义的筛选器:#{i}。" flag = 1 while flag <= filter_length if !index.includes("#{flag}") errorMsg = "有些筛选条件进行了定义,但未在高级筛选条件中被引用。" flag++; if !errorMsg # 判断是否有非法英文字符 word = logic.match(/[a-zA-Z]+/ig) if word word.forEach (w)-> if !/^(and|or)$/ig.test(w) errorMsg = "检查您的高级筛选条件中的拼写。" if !errorMsg # 判断格式是否正确 try Creator.eval(logic.replace(/and/ig, "&&").replace(/or/ig, "||")) catch e errorMsg = "您的筛选器中含有特殊字符" if /(AND)[^()]+(OR)/ig.test(logic) || /(OR)[^()]+(AND)/ig.test(logic) errorMsg = "您的筛选器必须在连续性的 AND 和 OR 表达式前后使用括号。" if errorMsg console.log "error", errorMsg if Meteor.isClient toastr.error(errorMsg) return false else return true # "=", "<>", ">", ">=", "<", "<=", "startswith", "contains", "notcontains". ### options参数: extend-- 是否需要把当前用户基本信息加入公式,即让公式支持Creator.USER_CONTEXT中的值,默认为true userId-- 当前登录用户 spaceId-- 当前所在工作区 extend为true时,后端需要额外传入userId及spaceId用于抓取Creator.USER_CONTEXT对应的值 ### Creator.formatFiltersToMongo = (filters, options)-> unless filters.length return # 当filters不是[Array]类型而是[Object]类型时,进行格式转换 unless filters[0] instanceof Array filters = _.map filters, (obj)-> return [obj.field, obj.operation, obj.value] selector = [] _.each filters, (filter)-> field = filter[0] option = filter[1] if Meteor.isClient value = Creator.evaluateFormula(filter[2]) else value = Creator.evaluateFormula(filter[2], null, options) sub_selector = {} sub_selector[field] = {} if option == "=" sub_selector[field]["$eq"] = value else if option == "<>" sub_selector[field]["$ne"] = value else if option == ">" sub_selector[field]["$gt"] = value else if option == ">=" sub_selector[field]["$gte"] = value else if option == "<" sub_selector[field]["$lt"] = value else if option == "<=" sub_selector[field]["$lte"] = value else if option == "startswith" reg = new RegExp("^" + value, "i") sub_selector[field]["$regex"] = reg else if option == "contains" reg = new RegExp(value, "i") sub_selector[field]["$regex"] = reg else if option == "notcontains" reg = new RegExp("^((?!" + value + ").)*$", "i") sub_selector[field]["$regex"] = reg selector.push sub_selector return selector ### options参数: extend-- 是否需要把当前用户基本信息加入公式,即让公式支持Creator.USER_CONTEXT中的值,默认为true userId-- 当前登录用户 spaceId-- 当前所在工作区 extend为true时,后端需要额外传入userId及spaceId用于抓取Creator.USER_CONTEXT对应的值 ### Creator.formatFiltersToDev = (filters, options)-> unless filters.length return # 当filters不是[Array]类型而是[Object]类型时,进行格式转换 unless filters[0] instanceof Array filters = _.map filters, (obj)-> return [obj.field, obj.operation, obj.value] selector = [] _.each filters, (filter)-> field = filter[0] option = filter[1] if Meteor.isClient value = Creator.evaluateFormula(filter[2]) else value = Creator.evaluateFormula(filter[2], null, options) sub_selector = [] if _.isArray(value) == true v_selector = [] if option == "=" _.each value, (v)-> sub_selector.push [field, option, v], "or" else if option == "<>" _.each value, (v)-> sub_selector.push [field, option, v], "and" else _.each value, (v)-> sub_selector.push [field, option, v], "or" if sub_selector[sub_selector.length - 1] == "and" || sub_selector[sub_selector.length - 1] == "or" sub_selector.pop() selector.push sub_selector, "and" else selector.push [field, option, value], "and" if selector[selector.length - 1] == "and" selector.pop() return selector ### options参数: extend-- 是否需要把当前用户基本信息加入公式,即让公式支持Creator.USER_CONTEXT中的值,默认为true userId-- 当前登录用户 spaceId-- 当前所在工作区 extend为true时,后端需要额外传入userId及spaceId用于抓取Creator.USER_CONTEXT对应的值 ### Creator.formatLogicFiltersToDev = (filters, filter_logic, options)-> format_logic = filter_logic.replace(/\(\s+/ig, "(").replace(/\s+\)/ig, ")").replace(/\(/g, "[").replace(/\)/g, "]").replace(/\s+/g, ",").replace(/(and|or)/ig, "'$1'") format_logic = format_logic.replace(/(\d)+/ig, (x)-> _f = filters[x-1] field = _f.field option = _f.operation if Meteor.isClient value = Creator.evaluateFormula(_f.value) else value = Creator.evaluateFormula(_f.value, null, options) sub_selector = [] if _.isArray(value) == true if option == "=" _.each value, (v)-> sub_selector.push [field, option, v], "or" else if option == "<>" _.each value, (v)-> sub_selector.push [field, option, v], "and" else _.each value, (v)-> sub_selector.push [field, option, v], "or" if sub_selector[sub_selector.length - 1] == "and" || sub_selector[sub_selector.length - 1] == "or" sub_selector.pop() else sub_selector = [field, option, value] console.log "sub_selector", sub_selector return JSON.stringify(sub_selector) ) format_logic = "[#{format_logic}]" return Creator.eval(format_logic) Creator.getRelatedObjects = (object_name, spaceId, userId)-> if Meteor.isClient if !object_name object_name = Session.get("object_name") if !spaceId spaceId = Session.get("spaceId") if !userId userId = Meteor.userId() related_object_names = [] _object = Creator.getObject(object_name) if !_object return related_object_names related_object_names = _.pluck(_object.related_objects,"object_name") if related_object_names?.length == 0 return related_object_names permissions = Creator.getPermissions(object_name, spaceId, userId) unrelated_objects = permissions.unrelated_objects related_object_names = _.difference related_object_names, unrelated_objects return _.filter _object.related_objects, (related_object)-> related_object_name = related_object.object_name isActive = related_object_names.indexOf(related_object_name) > -1 allowRead = Creator.getPermissions(related_object_name, spaceId, userId)?.allowRead return isActive and allowRead Creator.getRelatedObjectNames = (object_name, spaceId, userId)-> related_objects = Creator.getRelatedObjects(object_name, spaceId, userId) return _.pluck(related_objects,"object_name") Creator.getActions = (object_name, spaceId, userId)-> if Meteor.isClient if !object_name object_name = Session.get("object_name") if !spaceId spaceId = Session.get("spaceId") if !userId userId = Meteor.userId() obj = Creator.getObject(object_name) if !obj return permissions = Creator.getPermissions(object_name, spaceId, userId) disabled_actions = permissions.disabled_actions actions = _.sortBy(_.values(obj.actions) , 'sort'); actions = _.filter actions, (action)-> return _.indexOf(disabled_actions, action.name) < 0 return actions /// 返回当前用户有权限访问的所有list_view,包括分享的,用户自定义非分享的(除非owner变了),以及默认的其他视图 注意Creator.getPermissions函数中是不会有用户自定义非分享的视图的,所以Creator.getPermissions函数中拿到的结果不全,并不是当前用户能看到所有视图 /// Creator.getListViews = (object_name, spaceId, userId)-> if Meteor.isClient if !object_name object_name = Session.get("object_name") if !spaceId spaceId = Session.get("spaceId") if !userId userId = Meteor.userId() object = Creator.getObject(object_name) if !object return disabled_list_views = Creator.getPermissions(object_name, spaceId, userId).disabled_list_views || [] list_views = [] _.each object.list_views, (item, item_name)-> if item_name != "default" if _.indexOf(disabled_list_views, item_name) < 0 || item.owner == userId list_views.push item return list_views # 前台理论上不应该调用该函数,因为字段的权限都在Creator.getObject(object_name).fields的相关属性中有标识了 Creator.getFields = (object_name, spaceId, userId)-> if Meteor.isClient if !object_name object_name = Session.get("object_name") if !spaceId spaceId = Session.get("spaceId") if !userId userId = Meteor.userId() fieldsName = Creator.getObjectFieldsName(object_name) unreadable_fields = Creator.getPermissions(object_name, spaceId, userId).unreadable_fields return _.difference(fieldsName, unreadable_fields) Creator.isloading = ()-> return !Creator.bootstrapLoaded.get() Creator.convertSpecialCharacter = (str)-> return str.replace(/([\^\$\(\)\*\+\?\.\\\|\[\]\{\}])/g, "\\$1") # 计算fields相关函数 # START Creator.getDisabledFields = (schema)-> fields = _.map(schema, (field, fieldName) -> return field.autoform and field.autoform.disabled and !field.autoform.omit and fieldName ) fields = _.compact(fields) return fields Creator.getHiddenFields = (schema)-> fields = _.map(schema, (field, fieldName) -> return field.autoform and field.autoform.type == "hidden" and !field.autoform.omit and fieldName ) fields = _.compact(fields) return fields Creator.getFieldsWithNoGroup = (schema)-> fields = _.map(schema, (field, fieldName) -> return (!field.autoform or !field.autoform.group or field.autoform.group == "-") and (!field.autoform or field.autoform.type != "hidden") and fieldName ) fields = _.compact(fields) return fields Creator.getSortedFieldGroupNames = (schema)-> names = _.map(schema, (field) -> return field.autoform and field.autoform.group != "-" and field.autoform.group ) names = _.compact(names) names = _.unique(names) return names Creator.getFieldsForGroup = (schema, groupName) -> fields = _.map(schema, (field, fieldName) -> return field.autoform and field.autoform.group == groupName and field.autoform.type != "hidden" and fieldName ) fields = _.compact(fields) return fields Creator.getFieldsWithoutOmit = (schema, keys) -> keys = _.map(keys, (key) -> field = _.pick(schema, key) if field[key].autoform?.omit return false else return key ) keys = _.compact(keys) return keys Creator.getFieldsInFirstLevel = (firstLevelKeys, keys) -> keys = _.map(keys, (key) -> if _.indexOf(firstLevelKeys, key) > -1 return key else return false ) keys = _.compact(keys) return keys Creator.getFieldsForReorder = (schema, keys, isSingle) -> fields = [] i = 0 while i < keys.length sc_1 = _.pick(schema, keys[i]) sc_2 = _.pick(schema, keys[i+1]) is_wide_1 = false is_wide_2 = false _.each sc_1, (value) -> if value.autoform?.is_wide || value.autoform?.type == "table" is_wide_1 = true _.each sc_2, (value) -> if value.autoform?.is_wide || value.autoform?.type == "table" is_wide_2 = true if isSingle fields.push keys.slice(i, i+1) i += 1 else if is_wide_1 fields.push keys.slice(i, i+1) i += 1 else if !is_wide_1 and is_wide_2 childKeys = keys.slice(i, i+1) childKeys.push undefined fields.push childKeys i += 1 else if !is_wide_1 and !is_wide_2 childKeys = keys.slice(i, i+1) if keys[i+1] childKeys.push keys[i+1] else childKeys.push undefined fields.push childKeys i += 2 return fields Creator.getDBApps = (space_id)-> dbApps = {} Creator.Collections["apps"].find({space: space_id,is_creator:true,visible:true}, { fields: { created: 0, created_by: 0, modified: 0, modified_by: 0 } }).forEach (app)-> dbApps[app._id] = app return dbApps # END if Meteor.isServer Creator.getAllRelatedObjects = (object_name)-> related_object_names = [] _.each Creator.Objects, (related_object, related_object_name)-> _.each related_object.fields, (related_field, related_field_name)-> if related_field.type == "master_detail" and related_field.reference_to and related_field.reference_to == object_name related_object_names.push related_object_name if Creator.getObject(object_name).enable_files related_object_names.push "cms_files" return related_object_names
[ { "context": "te slot\n common.setPilot('#rebel-builder', 1, 'Luke Skywalker')\n common.assertNoUpgradeInSlot(test, '#rebel-", "end": 1687, "score": 0.9996417760848999, "start": 1673, "tag": "NAME", "value": "Luke Skywalker" }, { "context": "-Wing')\n common.setPilot('#rebel...
tests/test_ship_selector.coffee
CrazyVulcan/xwing
100
common = require './common' common.setup() casper.test.begin "New ship row created only when all ship rows are assigned", (test) -> common.waitForStartup('#rebel-builder') .then -> test.assertExists("#rebel-builder #{common.selectorForShipIndex(1)}") test.assertDoesntExist("#rebel-builder #{common.selectorForShipIndex(2)}") common.setShipType('#rebel-builder', 1, 'X-Wing') .then -> test.assertExists("#rebel-builder #{common.selectorForShipIndex(2)}") common.removeShip('#rebel-builder', 1) .then -> test.assertExists("#rebel-builder #{common.selectorForShipIndex(1)}") test.assertDoesntExist("#rebel-builder #{common.selectorForShipIndex(2)}") .run -> test.done() casper.test.begin "Changing ship keeps as many upgrades as possible", (test) -> common.waitForStartup('#rebel-builder') common.addShip('#rebel-builder', 'X-Wing', 'Rookie Pilot') common.addUpgrade('#rebel-builder', 1, 1, 'Proton Torpedoes') common.addUpgrade('#rebel-builder', 1, 2, 'R2 Astromech') common.addUpgrade('#rebel-builder', 1, 3, 'Engine Upgrade') common.assertTotalPoints(test, '#rebel-builder', 30) # Changing pilot but no change in slots common.setPilot('#rebel-builder', 1, 'Red Squadron Pilot') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 1, 'Proton Torpedoes') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 2, 'R2 Astromech') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 3, 'Engine Upgrade') common.assertTotalPoints(test, '#rebel-builder', 32) # Changing pilot adds elite slot common.setPilot('#rebel-builder', 1, 'Luke Skywalker') common.assertNoUpgradeInSlot(test, '#rebel-builder', 1, 1) common.assertUpgradeInSlot(test, '#rebel-builder', 1, 2, 'Proton Torpedoes') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 3, 'R2 Astromech') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 4, 'Engine Upgrade') common.assertTotalPoints(test, '#rebel-builder', 37) # Assign elite then change to another w/ elite common.addUpgrade('#rebel-builder', 1, 1, 'Marksmanship') common.setPilot('#rebel-builder', 1, 'Wedge Antilles') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 1, 'Marksmanship') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 2, 'Proton Torpedoes') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 3, 'R2 Astromech') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 4, 'Engine Upgrade') common.assertTotalPoints(test, '#rebel-builder', 41) # Change back to pilot without elite common.setPilot('#rebel-builder', 1, 'Red Squadron Pilot') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 1, 'Proton Torpedoes') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 2, 'R2 Astromech') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 3, 'Engine Upgrade') common.assertTotalPoints(test, '#rebel-builder', 32) # R2-D6 grants elite slot, but is ineligible on rookie pilots common.addUpgrade('#rebel-builder', 1, 2, 'R2-D6') common.addUpgrade('#rebel-builder', 1, 4, 'Push the Limit') common.assertTotalPoints(test, '#rebel-builder', 35) # Switching to rookie should drop extra elite and R2-D6 common.setPilot('#rebel-builder', 1, 'Rookie Pilot') common.assertTotalPoints(test, '#rebel-builder', 29) casper.then -> test.assertDoesntExist("#rebel-builder #{common.selectorForUpgradeIndex 1, 4}", "Elite slot was rescinded") # A-Wing Test Pilot grants elite slot, but is ineligible on prototype pilots common.setShipType('#rebel-builder', 1, 'A-Wing') common.setPilot('#rebel-builder', 1, 'Green Squadron Pilot') common.addUpgrade('#rebel-builder', 1, 1, 'Deadeye') common.addUpgrade('#rebel-builder', 1, 2, 'Chardaan Refit') common.addUpgrade('#rebel-builder', 1, 3, 'A-Wing Test Pilot') common.addUpgrade('#rebel-builder', 1, 4, 'Shield Upgrade') common.addUpgrade('#rebel-builder', 1, 5, 'Expert Handling') common.assertTotalPoints(test, '#rebel-builder', 24) # Switching to prototype should drop extra elite common.setPilot('#rebel-builder', 1, 'Prototype Pilot') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 1, 'Chardaan Refit') common.assertNoUpgradeInSlot(test, '#rebel-builder', 1, 2) common.assertUpgradeInSlot(test, '#rebel-builder', 1, 3, 'Shield Upgrade') common.assertTotalPoints(test, '#rebel-builder', 19) casper.then -> test.assertDoesntExist("#rebel-builder #{common.selectorForUpgradeIndex 1, 5}", "Elite slot was rescinded") # B-Wing/E2 grants crew slot common.setShipType('#rebel-builder', 1, 'B-Wing') common.setPilot('#rebel-builder', 1, 'Blue Squadron Pilot') common.addUpgrade('#rebel-builder', 1, 1, 'Advanced Sensors') common.addUpgrade('#rebel-builder', 1, 2, 'Heavy Laser Cannon') common.addUpgrade('#rebel-builder', 1, 3, 'Proton Torpedoes') common.addUpgrade('#rebel-builder', 1, 4, 'Advanced Proton Torpedoes') common.addUpgrade('#rebel-builder', 1, 5, 'B-Wing/E2') common.addUpgrade('#rebel-builder', 1, 6, 'Gunner') # Switching to Ten Numb should keep everything (except for new empty elite slot) common.setPilot('#rebel-builder', 1, 'Ten Numb') common.assertNoUpgradeInSlot(test, '#rebel-builder', 1, 1) common.assertUpgradeInSlot(test, '#rebel-builder', 1, 2, 'Advanced Sensors') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 3, 'Heavy Laser Cannon') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 4, 'Proton Torpedoes') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 5, 'Advanced Proton Torpedoes') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 6, 'B-Wing/E2') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 7, 'Gunner') # Switching down to Dagger squad should keep everything but elite common.setPilot('#rebel-builder', 1, 'Dagger Squadron Pilot') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 1, 'Advanced Sensors') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 2, 'Heavy Laser Cannon') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 3, 'Proton Torpedoes') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 4, 'Advanced Proton Torpedoes') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 5, 'B-Wing/E2') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 6, 'Gunner') common.removeShip('#rebel-builder', 1) common.openEmpireBuilder() # Royal Guard TIE grants extra mod, but is ineligible on Alpha squad common.setShipType('#empire-builder', 1, 'TIE Interceptor') common.setPilot('#empire-builder', 1, 'Royal Guard Pilot') common.addUpgrade('#empire-builder', 1, 1, 'Adrenaline Rush') common.addUpgrade('#empire-builder', 1, 2, 'Royal Guard TIE') common.addUpgrade('#empire-builder', 1, 3, 'Targeting Computer') common.addUpgrade('#empire-builder', 1, 4, 'Shield Upgrade') common.assertTotalPoints(test, '#empire-builder', 29) # Switching to Alpha should drop extra mod common.setPilot('#empire-builder', 1, 'Alpha Squadron Pilot') common.assertNoUpgradeInSlot(test, '#empire-builder', 1, 1) common.assertTotalPoints(test, '#empire-builder', 20) casper.then -> test.assertDoesntExist("#empire-builder #{common.selectorForUpgradeIndex 1, 3}", "Second modification was rescinded") .run -> test.done() casper.test.begin "Changing ship autoselects first non-unique pilot", (test) -> common.waitForStartup('#rebel-builder') common.setShipType('#rebel-builder', 1, 'X-Wing') common.assertPilotIs(test, '#rebel-builder', 1, 'Rookie Pilot') common.setShipType('#rebel-builder', 1, 'A-Wing') common.assertPilotIs(test, '#rebel-builder', 1, 'Prototype Pilot') common.removeShip('#rebel-builder', 1) .run -> test.done() casper.test.begin "Changing ship with unique pilot releases unique", (test) -> common.waitForStartup('#rebel-builder') common.setShipType('#rebel-builder', 1, 'X-Wing') common.setPilot('#rebel-builder', 1, 'Luke Skywalker') common.setShipType('#rebel-builder', 1, 'A-Wing') common.assertPilotIs(test, '#rebel-builder', 1, 'Prototype Pilot') common.setShipType('#rebel-builder', 2, 'X-Wing') common.setPilot('#rebel-builder', 2, 'Luke Skywalker') common.assertPilotIs(test, '#rebel-builder', 2, 'Luke Skywalker') common.removeShip('#rebel-builder', 1) .run -> test.done()
130157
common = require './common' common.setup() casper.test.begin "New ship row created only when all ship rows are assigned", (test) -> common.waitForStartup('#rebel-builder') .then -> test.assertExists("#rebel-builder #{common.selectorForShipIndex(1)}") test.assertDoesntExist("#rebel-builder #{common.selectorForShipIndex(2)}") common.setShipType('#rebel-builder', 1, 'X-Wing') .then -> test.assertExists("#rebel-builder #{common.selectorForShipIndex(2)}") common.removeShip('#rebel-builder', 1) .then -> test.assertExists("#rebel-builder #{common.selectorForShipIndex(1)}") test.assertDoesntExist("#rebel-builder #{common.selectorForShipIndex(2)}") .run -> test.done() casper.test.begin "Changing ship keeps as many upgrades as possible", (test) -> common.waitForStartup('#rebel-builder') common.addShip('#rebel-builder', 'X-Wing', 'Rookie Pilot') common.addUpgrade('#rebel-builder', 1, 1, 'Proton Torpedoes') common.addUpgrade('#rebel-builder', 1, 2, 'R2 Astromech') common.addUpgrade('#rebel-builder', 1, 3, 'Engine Upgrade') common.assertTotalPoints(test, '#rebel-builder', 30) # Changing pilot but no change in slots common.setPilot('#rebel-builder', 1, 'Red Squadron Pilot') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 1, 'Proton Torpedoes') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 2, 'R2 Astromech') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 3, 'Engine Upgrade') common.assertTotalPoints(test, '#rebel-builder', 32) # Changing pilot adds elite slot common.setPilot('#rebel-builder', 1, '<NAME>') common.assertNoUpgradeInSlot(test, '#rebel-builder', 1, 1) common.assertUpgradeInSlot(test, '#rebel-builder', 1, 2, 'Proton Torpedoes') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 3, 'R2 Astromech') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 4, 'Engine Upgrade') common.assertTotalPoints(test, '#rebel-builder', 37) # Assign elite then change to another w/ elite common.addUpgrade('#rebel-builder', 1, 1, 'Marksmanship') common.setPilot('#rebel-builder', 1, 'Wedge Antilles') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 1, 'Marksmanship') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 2, 'Proton Torpedoes') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 3, 'R2 Astromech') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 4, 'Engine Upgrade') common.assertTotalPoints(test, '#rebel-builder', 41) # Change back to pilot without elite common.setPilot('#rebel-builder', 1, 'Red Squadron Pilot') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 1, 'Proton Torpedoes') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 2, 'R2 Astromech') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 3, 'Engine Upgrade') common.assertTotalPoints(test, '#rebel-builder', 32) # R2-D6 grants elite slot, but is ineligible on rookie pilots common.addUpgrade('#rebel-builder', 1, 2, 'R2-D6') common.addUpgrade('#rebel-builder', 1, 4, 'Push the Limit') common.assertTotalPoints(test, '#rebel-builder', 35) # Switching to rookie should drop extra elite and R2-D6 common.setPilot('#rebel-builder', 1, 'Rookie Pilot') common.assertTotalPoints(test, '#rebel-builder', 29) casper.then -> test.assertDoesntExist("#rebel-builder #{common.selectorForUpgradeIndex 1, 4}", "Elite slot was rescinded") # A-Wing Test Pilot grants elite slot, but is ineligible on prototype pilots common.setShipType('#rebel-builder', 1, 'A-Wing') common.setPilot('#rebel-builder', 1, 'Green Squadron Pilot') common.addUpgrade('#rebel-builder', 1, 1, 'Deadeye') common.addUpgrade('#rebel-builder', 1, 2, 'Chardaan Refit') common.addUpgrade('#rebel-builder', 1, 3, 'A-Wing Test Pilot') common.addUpgrade('#rebel-builder', 1, 4, 'Shield Upgrade') common.addUpgrade('#rebel-builder', 1, 5, 'Expert Handling') common.assertTotalPoints(test, '#rebel-builder', 24) # Switching to prototype should drop extra elite common.setPilot('#rebel-builder', 1, 'Prototype Pilot') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 1, 'Chardaan Refit') common.assertNoUpgradeInSlot(test, '#rebel-builder', 1, 2) common.assertUpgradeInSlot(test, '#rebel-builder', 1, 3, 'Shield Upgrade') common.assertTotalPoints(test, '#rebel-builder', 19) casper.then -> test.assertDoesntExist("#rebel-builder #{common.selectorForUpgradeIndex 1, 5}", "Elite slot was rescinded") # B-Wing/E2 grants crew slot common.setShipType('#rebel-builder', 1, 'B-Wing') common.setPilot('#rebel-builder', 1, 'Blue Squadron Pilot') common.addUpgrade('#rebel-builder', 1, 1, 'Advanced Sensors') common.addUpgrade('#rebel-builder', 1, 2, 'Heavy Laser Cannon') common.addUpgrade('#rebel-builder', 1, 3, 'Proton Torpedoes') common.addUpgrade('#rebel-builder', 1, 4, 'Advanced Proton Torpedoes') common.addUpgrade('#rebel-builder', 1, 5, 'B-Wing/E2') common.addUpgrade('#rebel-builder', 1, 6, 'Gunner') # Switching to Ten Numb should keep everything (except for new empty elite slot) common.setPilot('#rebel-builder', 1, 'Ten Numb') common.assertNoUpgradeInSlot(test, '#rebel-builder', 1, 1) common.assertUpgradeInSlot(test, '#rebel-builder', 1, 2, 'Advanced Sensors') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 3, 'Heavy Laser Cannon') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 4, 'Proton Torpedoes') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 5, 'Advanced Proton Torpedoes') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 6, 'B-Wing/E2') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 7, 'Gunner') # Switching down to Dagger squad should keep everything but elite common.setPilot('#rebel-builder', 1, 'Dagger Squadron Pilot') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 1, 'Advanced Sensors') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 2, 'Heavy Laser Cannon') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 3, 'Proton Torpedoes') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 4, 'Advanced Proton Torpedoes') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 5, 'B-Wing/E2') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 6, 'Gunner') common.removeShip('#rebel-builder', 1) common.openEmpireBuilder() # Royal Guard TIE grants extra mod, but is ineligible on Alpha squad common.setShipType('#empire-builder', 1, 'TIE Interceptor') common.setPilot('#empire-builder', 1, 'Royal Guard Pilot') common.addUpgrade('#empire-builder', 1, 1, 'Adrenaline Rush') common.addUpgrade('#empire-builder', 1, 2, 'Royal Guard TIE') common.addUpgrade('#empire-builder', 1, 3, 'Targeting Computer') common.addUpgrade('#empire-builder', 1, 4, 'Shield Upgrade') common.assertTotalPoints(test, '#empire-builder', 29) # Switching to Alpha should drop extra mod common.setPilot('#empire-builder', 1, 'Alpha Squadron Pilot') common.assertNoUpgradeInSlot(test, '#empire-builder', 1, 1) common.assertTotalPoints(test, '#empire-builder', 20) casper.then -> test.assertDoesntExist("#empire-builder #{common.selectorForUpgradeIndex 1, 3}", "Second modification was rescinded") .run -> test.done() casper.test.begin "Changing ship autoselects first non-unique pilot", (test) -> common.waitForStartup('#rebel-builder') common.setShipType('#rebel-builder', 1, 'X-Wing') common.assertPilotIs(test, '#rebel-builder', 1, 'Rookie Pilot') common.setShipType('#rebel-builder', 1, 'A-Wing') common.assertPilotIs(test, '#rebel-builder', 1, 'Prototype Pilot') common.removeShip('#rebel-builder', 1) .run -> test.done() casper.test.begin "Changing ship with unique pilot releases unique", (test) -> common.waitForStartup('#rebel-builder') common.setShipType('#rebel-builder', 1, 'X-Wing') common.setPilot('#rebel-builder', 1, '<NAME>') common.setShipType('#rebel-builder', 1, 'A-Wing') common.assertPilotIs(test, '#rebel-builder', 1, 'Prototype Pilot') common.setShipType('#rebel-builder', 2, 'X-Wing') common.setPilot('#rebel-builder', 2, '<NAME>') common.assertPilotIs(test, '#rebel-builder', 2, '<NAME>') common.removeShip('#rebel-builder', 1) .run -> test.done()
true
common = require './common' common.setup() casper.test.begin "New ship row created only when all ship rows are assigned", (test) -> common.waitForStartup('#rebel-builder') .then -> test.assertExists("#rebel-builder #{common.selectorForShipIndex(1)}") test.assertDoesntExist("#rebel-builder #{common.selectorForShipIndex(2)}") common.setShipType('#rebel-builder', 1, 'X-Wing') .then -> test.assertExists("#rebel-builder #{common.selectorForShipIndex(2)}") common.removeShip('#rebel-builder', 1) .then -> test.assertExists("#rebel-builder #{common.selectorForShipIndex(1)}") test.assertDoesntExist("#rebel-builder #{common.selectorForShipIndex(2)}") .run -> test.done() casper.test.begin "Changing ship keeps as many upgrades as possible", (test) -> common.waitForStartup('#rebel-builder') common.addShip('#rebel-builder', 'X-Wing', 'Rookie Pilot') common.addUpgrade('#rebel-builder', 1, 1, 'Proton Torpedoes') common.addUpgrade('#rebel-builder', 1, 2, 'R2 Astromech') common.addUpgrade('#rebel-builder', 1, 3, 'Engine Upgrade') common.assertTotalPoints(test, '#rebel-builder', 30) # Changing pilot but no change in slots common.setPilot('#rebel-builder', 1, 'Red Squadron Pilot') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 1, 'Proton Torpedoes') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 2, 'R2 Astromech') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 3, 'Engine Upgrade') common.assertTotalPoints(test, '#rebel-builder', 32) # Changing pilot adds elite slot common.setPilot('#rebel-builder', 1, 'PI:NAME:<NAME>END_PI') common.assertNoUpgradeInSlot(test, '#rebel-builder', 1, 1) common.assertUpgradeInSlot(test, '#rebel-builder', 1, 2, 'Proton Torpedoes') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 3, 'R2 Astromech') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 4, 'Engine Upgrade') common.assertTotalPoints(test, '#rebel-builder', 37) # Assign elite then change to another w/ elite common.addUpgrade('#rebel-builder', 1, 1, 'Marksmanship') common.setPilot('#rebel-builder', 1, 'Wedge Antilles') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 1, 'Marksmanship') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 2, 'Proton Torpedoes') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 3, 'R2 Astromech') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 4, 'Engine Upgrade') common.assertTotalPoints(test, '#rebel-builder', 41) # Change back to pilot without elite common.setPilot('#rebel-builder', 1, 'Red Squadron Pilot') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 1, 'Proton Torpedoes') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 2, 'R2 Astromech') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 3, 'Engine Upgrade') common.assertTotalPoints(test, '#rebel-builder', 32) # R2-D6 grants elite slot, but is ineligible on rookie pilots common.addUpgrade('#rebel-builder', 1, 2, 'R2-D6') common.addUpgrade('#rebel-builder', 1, 4, 'Push the Limit') common.assertTotalPoints(test, '#rebel-builder', 35) # Switching to rookie should drop extra elite and R2-D6 common.setPilot('#rebel-builder', 1, 'Rookie Pilot') common.assertTotalPoints(test, '#rebel-builder', 29) casper.then -> test.assertDoesntExist("#rebel-builder #{common.selectorForUpgradeIndex 1, 4}", "Elite slot was rescinded") # A-Wing Test Pilot grants elite slot, but is ineligible on prototype pilots common.setShipType('#rebel-builder', 1, 'A-Wing') common.setPilot('#rebel-builder', 1, 'Green Squadron Pilot') common.addUpgrade('#rebel-builder', 1, 1, 'Deadeye') common.addUpgrade('#rebel-builder', 1, 2, 'Chardaan Refit') common.addUpgrade('#rebel-builder', 1, 3, 'A-Wing Test Pilot') common.addUpgrade('#rebel-builder', 1, 4, 'Shield Upgrade') common.addUpgrade('#rebel-builder', 1, 5, 'Expert Handling') common.assertTotalPoints(test, '#rebel-builder', 24) # Switching to prototype should drop extra elite common.setPilot('#rebel-builder', 1, 'Prototype Pilot') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 1, 'Chardaan Refit') common.assertNoUpgradeInSlot(test, '#rebel-builder', 1, 2) common.assertUpgradeInSlot(test, '#rebel-builder', 1, 3, 'Shield Upgrade') common.assertTotalPoints(test, '#rebel-builder', 19) casper.then -> test.assertDoesntExist("#rebel-builder #{common.selectorForUpgradeIndex 1, 5}", "Elite slot was rescinded") # B-Wing/E2 grants crew slot common.setShipType('#rebel-builder', 1, 'B-Wing') common.setPilot('#rebel-builder', 1, 'Blue Squadron Pilot') common.addUpgrade('#rebel-builder', 1, 1, 'Advanced Sensors') common.addUpgrade('#rebel-builder', 1, 2, 'Heavy Laser Cannon') common.addUpgrade('#rebel-builder', 1, 3, 'Proton Torpedoes') common.addUpgrade('#rebel-builder', 1, 4, 'Advanced Proton Torpedoes') common.addUpgrade('#rebel-builder', 1, 5, 'B-Wing/E2') common.addUpgrade('#rebel-builder', 1, 6, 'Gunner') # Switching to Ten Numb should keep everything (except for new empty elite slot) common.setPilot('#rebel-builder', 1, 'Ten Numb') common.assertNoUpgradeInSlot(test, '#rebel-builder', 1, 1) common.assertUpgradeInSlot(test, '#rebel-builder', 1, 2, 'Advanced Sensors') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 3, 'Heavy Laser Cannon') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 4, 'Proton Torpedoes') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 5, 'Advanced Proton Torpedoes') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 6, 'B-Wing/E2') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 7, 'Gunner') # Switching down to Dagger squad should keep everything but elite common.setPilot('#rebel-builder', 1, 'Dagger Squadron Pilot') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 1, 'Advanced Sensors') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 2, 'Heavy Laser Cannon') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 3, 'Proton Torpedoes') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 4, 'Advanced Proton Torpedoes') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 5, 'B-Wing/E2') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 6, 'Gunner') common.removeShip('#rebel-builder', 1) common.openEmpireBuilder() # Royal Guard TIE grants extra mod, but is ineligible on Alpha squad common.setShipType('#empire-builder', 1, 'TIE Interceptor') common.setPilot('#empire-builder', 1, 'Royal Guard Pilot') common.addUpgrade('#empire-builder', 1, 1, 'Adrenaline Rush') common.addUpgrade('#empire-builder', 1, 2, 'Royal Guard TIE') common.addUpgrade('#empire-builder', 1, 3, 'Targeting Computer') common.addUpgrade('#empire-builder', 1, 4, 'Shield Upgrade') common.assertTotalPoints(test, '#empire-builder', 29) # Switching to Alpha should drop extra mod common.setPilot('#empire-builder', 1, 'Alpha Squadron Pilot') common.assertNoUpgradeInSlot(test, '#empire-builder', 1, 1) common.assertTotalPoints(test, '#empire-builder', 20) casper.then -> test.assertDoesntExist("#empire-builder #{common.selectorForUpgradeIndex 1, 3}", "Second modification was rescinded") .run -> test.done() casper.test.begin "Changing ship autoselects first non-unique pilot", (test) -> common.waitForStartup('#rebel-builder') common.setShipType('#rebel-builder', 1, 'X-Wing') common.assertPilotIs(test, '#rebel-builder', 1, 'Rookie Pilot') common.setShipType('#rebel-builder', 1, 'A-Wing') common.assertPilotIs(test, '#rebel-builder', 1, 'Prototype Pilot') common.removeShip('#rebel-builder', 1) .run -> test.done() casper.test.begin "Changing ship with unique pilot releases unique", (test) -> common.waitForStartup('#rebel-builder') common.setShipType('#rebel-builder', 1, 'X-Wing') common.setPilot('#rebel-builder', 1, 'PI:NAME:<NAME>END_PI') common.setShipType('#rebel-builder', 1, 'A-Wing') common.assertPilotIs(test, '#rebel-builder', 1, 'Prototype Pilot') common.setShipType('#rebel-builder', 2, 'X-Wing') common.setPilot('#rebel-builder', 2, 'PI:NAME:<NAME>END_PI') common.assertPilotIs(test, '#rebel-builder', 2, 'PI:NAME:<NAME>END_PI') common.removeShip('#rebel-builder', 1) .run -> test.done()
[ { "context": " mangrove:\n color: '#008b00'\n name: 'Mangrove'\n seagrass:\n color: '#f35f8d'\n name:", "end": 94, "score": 0.843570351600647, "start": 86, "tag": "NAME", "value": "Mangrove" }, { "context": " saltmarsh:\n color: '#007dff'\n name:...
app/assets/javascripts/modules/map.js.coffee
unepwcmc/BlueForest
2
window.Map = class Map HABITATS = mangrove: color: '#008b00' name: 'Mangrove' seagrass: color: '#f35f8d' name: 'Seagrass' saltmarsh: color: '#007dff' name: 'Saltmarsh' algal_mat: color: '#ffe048' name: 'Algal Mat' # other: # color: '#1dcbea' # name: 'Other' constructor: (elementId, mapOpts={}) -> @baseMap = L.tileLayer( 'https://api.mapbox.com/styles/v1/unepwcmc/ckcynosar20hj1io2z5yo95ch/tiles/{z}/{x}/{y}?access_token=' + window.MAPBOX_API_KEY, { maxZoom: 17} ) @initializeMap(elementId, mapOpts) @addAttribution() @addOverlays(mapOpts.countryIso, (err, overlays) => L.control.layers(@baseMaps, overlays, {collapsed:false}).addTo(@map) ) initializeMap: (elementId, mapOpts) -> maxBounds = L.latLngBounds(mapOpts.bounds) mapOpts.center = maxBounds.getCenter() mapOpts.layers = [@baseMap] @map = L.map(elementId, mapOpts) @map.fitBounds(maxBounds) addAttribution: -> attribution = L.control.attribution(position: 'bottomright', prefix: '') attribution.addTo(@map) baseMaps: -> baseMaps = {} baseMaps[polyglot.t('analysis.map')] = @baseMap baseMaps[polyglot.t('analysis.satellite')] = @baseSatellite addOverlays: (countryIso, done) -> async.reduce(@getSublayers(), {}, (sublayers, sublayer, cb) => sublayer.country_iso = countryIso MapProxy.newMap(sublayer, (err, tilesUrl) => tilesUrl = decodeURIComponent(tilesUrl) sublayers[@getLegendItemHtml(sublayer)] = L.tileLayer(tilesUrl).addTo(@map) cb(null, sublayers) ) , done) getSublayers: -> _.map(HABITATS, (properties, habitat) -> where = "toggle::boolean = true AND (validate_action <> 'delete' OR validate_action IS NULL)" style = """ #bc_#{habitat} { line-color: #FFF; line-width: 0.5; polygon-fill: #{properties.color}; polygon-opacity: 0.5 } """ {habitat: habitat, where: where, style: style} ) getLegendItemHtml: (sublayer) -> prettyName = polyglot.t("analysis.#{sublayer.habitat}") return "<div class='custom-radio-row'> <span class='custom-radio custom-radio__outer'> <div class='custom-radio__inner' style='background-color:" + HABITATS[sublayer.habitat].color + "'></div> </span> <span>"+prettyName+"</span> </div>"
81857
window.Map = class Map HABITATS = mangrove: color: '#008b00' name: '<NAME>' seagrass: color: '#f35f8d' name: 'Seagrass' saltmarsh: color: '#007dff' name: '<NAME>' algal_mat: color: '#ffe048' name: '<NAME>' # other: # color: '#1dcbea' # name: 'Other' constructor: (elementId, mapOpts={}) -> @baseMap = L.tileLayer( 'https://api.mapbox.com/styles/v1/unepwcmc/ckcynosar20hj1io2z5yo95ch/tiles/{z}/{x}/{y}?access_token=' + window.MAPBOX_API_KEY, { maxZoom: 17} ) @initializeMap(elementId, mapOpts) @addAttribution() @addOverlays(mapOpts.countryIso, (err, overlays) => L.control.layers(@baseMaps, overlays, {collapsed:false}).addTo(@map) ) initializeMap: (elementId, mapOpts) -> maxBounds = L.latLngBounds(mapOpts.bounds) mapOpts.center = maxBounds.getCenter() mapOpts.layers = [@baseMap] @map = L.map(elementId, mapOpts) @map.fitBounds(maxBounds) addAttribution: -> attribution = L.control.attribution(position: 'bottomright', prefix: '') attribution.addTo(@map) baseMaps: -> baseMaps = {} baseMaps[polyglot.t('analysis.map')] = @baseMap baseMaps[polyglot.t('analysis.satellite')] = @baseSatellite addOverlays: (countryIso, done) -> async.reduce(@getSublayers(), {}, (sublayers, sublayer, cb) => sublayer.country_iso = countryIso MapProxy.newMap(sublayer, (err, tilesUrl) => tilesUrl = decodeURIComponent(tilesUrl) sublayers[@getLegendItemHtml(sublayer)] = L.tileLayer(tilesUrl).addTo(@map) cb(null, sublayers) ) , done) getSublayers: -> _.map(HABITATS, (properties, habitat) -> where = "toggle::boolean = true AND (validate_action <> 'delete' OR validate_action IS NULL)" style = """ #bc_#{habitat} { line-color: #FFF; line-width: 0.5; polygon-fill: #{properties.color}; polygon-opacity: 0.5 } """ {habitat: habitat, where: where, style: style} ) getLegendItemHtml: (sublayer) -> prettyName = polyglot.t("analysis.#{sublayer.habitat}") return "<div class='custom-radio-row'> <span class='custom-radio custom-radio__outer'> <div class='custom-radio__inner' style='background-color:" + HABITATS[sublayer.habitat].color + "'></div> </span> <span>"+prettyName+"</span> </div>"
true
window.Map = class Map HABITATS = mangrove: color: '#008b00' name: 'PI:NAME:<NAME>END_PI' seagrass: color: '#f35f8d' name: 'Seagrass' saltmarsh: color: '#007dff' name: 'PI:NAME:<NAME>END_PI' algal_mat: color: '#ffe048' name: 'PI:NAME:<NAME>END_PI' # other: # color: '#1dcbea' # name: 'Other' constructor: (elementId, mapOpts={}) -> @baseMap = L.tileLayer( 'https://api.mapbox.com/styles/v1/unepwcmc/ckcynosar20hj1io2z5yo95ch/tiles/{z}/{x}/{y}?access_token=' + window.MAPBOX_API_KEY, { maxZoom: 17} ) @initializeMap(elementId, mapOpts) @addAttribution() @addOverlays(mapOpts.countryIso, (err, overlays) => L.control.layers(@baseMaps, overlays, {collapsed:false}).addTo(@map) ) initializeMap: (elementId, mapOpts) -> maxBounds = L.latLngBounds(mapOpts.bounds) mapOpts.center = maxBounds.getCenter() mapOpts.layers = [@baseMap] @map = L.map(elementId, mapOpts) @map.fitBounds(maxBounds) addAttribution: -> attribution = L.control.attribution(position: 'bottomright', prefix: '') attribution.addTo(@map) baseMaps: -> baseMaps = {} baseMaps[polyglot.t('analysis.map')] = @baseMap baseMaps[polyglot.t('analysis.satellite')] = @baseSatellite addOverlays: (countryIso, done) -> async.reduce(@getSublayers(), {}, (sublayers, sublayer, cb) => sublayer.country_iso = countryIso MapProxy.newMap(sublayer, (err, tilesUrl) => tilesUrl = decodeURIComponent(tilesUrl) sublayers[@getLegendItemHtml(sublayer)] = L.tileLayer(tilesUrl).addTo(@map) cb(null, sublayers) ) , done) getSublayers: -> _.map(HABITATS, (properties, habitat) -> where = "toggle::boolean = true AND (validate_action <> 'delete' OR validate_action IS NULL)" style = """ #bc_#{habitat} { line-color: #FFF; line-width: 0.5; polygon-fill: #{properties.color}; polygon-opacity: 0.5 } """ {habitat: habitat, where: where, style: style} ) getLegendItemHtml: (sublayer) -> prettyName = polyglot.t("analysis.#{sublayer.habitat}") return "<div class='custom-radio-row'> <span class='custom-radio custom-radio__outer'> <div class='custom-radio__inner' style='background-color:" + HABITATS[sublayer.habitat].color + "'></div> </span> <span>"+prettyName+"</span> </div>"
[ { "context": "# -*- coding: utf-8 -*-\n#\n# Copyright 2015 Roy Liu\n#\n# Licensed under the Apache License, Version 2.", "end": 50, "score": 0.999635636806488, "start": 43, "tag": "NAME", "value": "Roy Liu" } ]
app/assets/javascripts/routes/all.coffee
carsomyr/nurf-stats
0
# -*- coding: utf-8 -*- # # Copyright 2015 Roy Liu # # 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. ((factory) -> if typeof define is "function" and define.amd? define ["ember", "application-base", "./index_route", "./introduction_route", "./stats_route", "./champion_stats_route", "./champion_duo_stats_route", "./champion_lane_stats_route", "./item_stats_route", "./useless_rune_mastery_stats_route"], factory ).call(@, (Ember, # app, # IndexRoute, # IntroductionRoute, # StatsRoute, # ChampionStatsRoute, # ChampionDuoStatsRoute, # ChampionLaneStatsRoute, # ItemStatsRoute, # UselessRuneMasteryStatsRoute) -> app.Router.map -> @route("introduction") @resource("stats") @resource("champion_stats") @resource("champion_duo_stats") @resource("champion_lane_stats") @resource("item_stats") @resource("useless_rune_mastery_stats") app )
167698
# -*- coding: utf-8 -*- # # Copyright 2015 <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. ((factory) -> if typeof define is "function" and define.amd? define ["ember", "application-base", "./index_route", "./introduction_route", "./stats_route", "./champion_stats_route", "./champion_duo_stats_route", "./champion_lane_stats_route", "./item_stats_route", "./useless_rune_mastery_stats_route"], factory ).call(@, (Ember, # app, # IndexRoute, # IntroductionRoute, # StatsRoute, # ChampionStatsRoute, # ChampionDuoStatsRoute, # ChampionLaneStatsRoute, # ItemStatsRoute, # UselessRuneMasteryStatsRoute) -> app.Router.map -> @route("introduction") @resource("stats") @resource("champion_stats") @resource("champion_duo_stats") @resource("champion_lane_stats") @resource("item_stats") @resource("useless_rune_mastery_stats") app )
true
# -*- coding: utf-8 -*- # # Copyright 2015 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. ((factory) -> if typeof define is "function" and define.amd? define ["ember", "application-base", "./index_route", "./introduction_route", "./stats_route", "./champion_stats_route", "./champion_duo_stats_route", "./champion_lane_stats_route", "./item_stats_route", "./useless_rune_mastery_stats_route"], factory ).call(@, (Ember, # app, # IndexRoute, # IntroductionRoute, # StatsRoute, # ChampionStatsRoute, # ChampionDuoStatsRoute, # ChampionLaneStatsRoute, # ItemStatsRoute, # UselessRuneMasteryStatsRoute) -> app.Router.map -> @route("introduction") @resource("stats") @resource("champion_stats") @resource("champion_duo_stats") @resource("champion_lane_stats") @resource("item_stats") @resource("useless_rune_mastery_stats") app )
[ { "context": "ss exports.Sky extends Entity\n\n\tentity :\n\t\tname: \"Sky\"\n\t\ttype: \"a-sky\"\n\n\tconstructor: (options)->\n\t\tsup", "end": 104, "score": 0.6713739633560181, "start": 101, "tag": "NAME", "value": "Sky" } ]
src/Sky.coffee
etiennepinchon/hologram
89
{entityAttribute, Entity} = require "./Entity" class exports.Sky extends Entity entity : name: "Sky" type: "a-sky" constructor: (options)-> super # ---------------------------------------------------------------------------- # PROPERTIES @define "radius", entityAttribute("radius", "radius", 5000) @define "segmentsWidth", entityAttribute("segmentsWidth", "segments-width", 64) @define "segmentsHeight", entityAttribute("segmentsHeight", "segments-height", 20) @define "thetaLength", entityAttribute("thetaLength", "theta-length", 180) @define "thetaStart", entityAttribute("thetaStart", "theta-start", 0) @define "phiLength", entityAttribute("phiLength", "phi-length", 360) @define "phiStart", entityAttribute("phiStart", "phi-start", 0)
169106
{entityAttribute, Entity} = require "./Entity" class exports.Sky extends Entity entity : name: "<NAME>" type: "a-sky" constructor: (options)-> super # ---------------------------------------------------------------------------- # PROPERTIES @define "radius", entityAttribute("radius", "radius", 5000) @define "segmentsWidth", entityAttribute("segmentsWidth", "segments-width", 64) @define "segmentsHeight", entityAttribute("segmentsHeight", "segments-height", 20) @define "thetaLength", entityAttribute("thetaLength", "theta-length", 180) @define "thetaStart", entityAttribute("thetaStart", "theta-start", 0) @define "phiLength", entityAttribute("phiLength", "phi-length", 360) @define "phiStart", entityAttribute("phiStart", "phi-start", 0)
true
{entityAttribute, Entity} = require "./Entity" class exports.Sky extends Entity entity : name: "PI:NAME:<NAME>END_PI" type: "a-sky" constructor: (options)-> super # ---------------------------------------------------------------------------- # PROPERTIES @define "radius", entityAttribute("radius", "radius", 5000) @define "segmentsWidth", entityAttribute("segmentsWidth", "segments-width", 64) @define "segmentsHeight", entityAttribute("segmentsHeight", "segments-height", 20) @define "thetaLength", entityAttribute("thetaLength", "theta-length", 180) @define "thetaStart", entityAttribute("thetaStart", "theta-start", 0) @define "phiLength", entityAttribute("phiLength", "phi-length", 360) @define "phiStart", entityAttribute("phiStart", "phi-start", 0)
[ { "context": "9'\n startLabel: 'Start'\n endLabel: 'Ceremony'\n dateFormat: '%A %d/%m'\n shortDate", "end": 1450, "score": 0.9920072555541992, "start": 1442, "tag": "NAME", "value": "Ceremony" } ]
client/src/sprint/directives/burndown/directive.coffee
MollardMichael/scrumble
27
angular.module 'Scrumble.sprint' .directive 'burndown', -> restrict: 'AE' scope: data: '=' templateUrl: 'sprint/directives/burndown/view.html' controller: ($scope, $timeout, $mdMedia) -> whRatio = 0.54 computeDimensions = -> chart = document.getElementsByClassName('chart')?[0] chart?.parentNode.removeChild chart if $mdMedia('sm') or $mdMedia('xs') width = document.getElementById('bdcgraph')?.clientWidth width = Math.min width, 1000 height = whRatio * width margins = top: 30 right: 0 bottom: 60 left: 0 yScaleOrient = 'right' dotRadius = 2 standardStrokeWidth = 1 doneStrokeWidth = 1 else width = document.getElementById('bdcgraph')?.clientWidth - 120 width = Math.min width, 1000 height = whRatio * width margins = top: 30 right: 70 bottom: 60 left: 50 yScaleOrient = 'left' dotRadius = 4 standardStrokeWidth = 2 doneStrokeWidth = 2 config = containerId: '#bdcgraph' width: width height: height margins: margins yScaleOrient: yScaleOrient colors: standard: '#FF5253' done: '#1a69cd' good: '#1a69cd' bad: '#1a69cd' labels: '#113F59' startLabel: 'Start' endLabel: 'Ceremony' dateFormat: '%A %d/%m' shortDateFormat: '%d/%m' xTitle: '' dotRadius: dotRadius standardStrokeWidth: standardStrokeWidth doneStrokeWidth: doneStrokeWidth goodSuffix: '' badSuffix: '' config window.onresize = -> config = computeDimensions() renderBDC $scope.data, config $scope.$watch 'data', (data) -> return unless data config = computeDimensions() renderBDC data, config , true $timeout -> return unless $scope.data config = computeDimensions() renderBDC $scope.data, config , 200
64130
angular.module 'Scrumble.sprint' .directive 'burndown', -> restrict: 'AE' scope: data: '=' templateUrl: 'sprint/directives/burndown/view.html' controller: ($scope, $timeout, $mdMedia) -> whRatio = 0.54 computeDimensions = -> chart = document.getElementsByClassName('chart')?[0] chart?.parentNode.removeChild chart if $mdMedia('sm') or $mdMedia('xs') width = document.getElementById('bdcgraph')?.clientWidth width = Math.min width, 1000 height = whRatio * width margins = top: 30 right: 0 bottom: 60 left: 0 yScaleOrient = 'right' dotRadius = 2 standardStrokeWidth = 1 doneStrokeWidth = 1 else width = document.getElementById('bdcgraph')?.clientWidth - 120 width = Math.min width, 1000 height = whRatio * width margins = top: 30 right: 70 bottom: 60 left: 50 yScaleOrient = 'left' dotRadius = 4 standardStrokeWidth = 2 doneStrokeWidth = 2 config = containerId: '#bdcgraph' width: width height: height margins: margins yScaleOrient: yScaleOrient colors: standard: '#FF5253' done: '#1a69cd' good: '#1a69cd' bad: '#1a69cd' labels: '#113F59' startLabel: 'Start' endLabel: '<NAME>' dateFormat: '%A %d/%m' shortDateFormat: '%d/%m' xTitle: '' dotRadius: dotRadius standardStrokeWidth: standardStrokeWidth doneStrokeWidth: doneStrokeWidth goodSuffix: '' badSuffix: '' config window.onresize = -> config = computeDimensions() renderBDC $scope.data, config $scope.$watch 'data', (data) -> return unless data config = computeDimensions() renderBDC data, config , true $timeout -> return unless $scope.data config = computeDimensions() renderBDC $scope.data, config , 200
true
angular.module 'Scrumble.sprint' .directive 'burndown', -> restrict: 'AE' scope: data: '=' templateUrl: 'sprint/directives/burndown/view.html' controller: ($scope, $timeout, $mdMedia) -> whRatio = 0.54 computeDimensions = -> chart = document.getElementsByClassName('chart')?[0] chart?.parentNode.removeChild chart if $mdMedia('sm') or $mdMedia('xs') width = document.getElementById('bdcgraph')?.clientWidth width = Math.min width, 1000 height = whRatio * width margins = top: 30 right: 0 bottom: 60 left: 0 yScaleOrient = 'right' dotRadius = 2 standardStrokeWidth = 1 doneStrokeWidth = 1 else width = document.getElementById('bdcgraph')?.clientWidth - 120 width = Math.min width, 1000 height = whRatio * width margins = top: 30 right: 70 bottom: 60 left: 50 yScaleOrient = 'left' dotRadius = 4 standardStrokeWidth = 2 doneStrokeWidth = 2 config = containerId: '#bdcgraph' width: width height: height margins: margins yScaleOrient: yScaleOrient colors: standard: '#FF5253' done: '#1a69cd' good: '#1a69cd' bad: '#1a69cd' labels: '#113F59' startLabel: 'Start' endLabel: 'PI:NAME:<NAME>END_PI' dateFormat: '%A %d/%m' shortDateFormat: '%d/%m' xTitle: '' dotRadius: dotRadius standardStrokeWidth: standardStrokeWidth doneStrokeWidth: doneStrokeWidth goodSuffix: '' badSuffix: '' config window.onresize = -> config = computeDimensions() renderBDC $scope.data, config $scope.$watch 'data', (data) -> return unless data config = computeDimensions() renderBDC data, config , true $timeout -> return unless $scope.data config = computeDimensions() renderBDC $scope.data, config , 200
[ { "context": "vidual bird (whooping crane).\n\nhttps://github.com/NicMcPhee/whooping-crane-model\n\nCopyright (c) 2015 Nic McPh", "end": 86, "score": 0.9991959929466248, "start": 77, "tag": "USERNAME", "value": "NicMcPhee" }, { "context": "NicMcPhee/whooping-crane-model\n\nCopyright ...
src/lib/bird.coffee
NicMcPhee/whooping-crane-model
0
### Basic model of an individual bird (whooping crane). https://github.com/NicMcPhee/whooping-crane-model Copyright (c) 2015 Nic McPhee Licensed under the MIT license. ### 'use strict' ModelParameters = require './model_parameters' Clock = require './clock' class Bird @uuidFactory: require('uuid') @EARLY = 0 @LATE = 1 @WILD_REARED = 2 @CAPTIVE_REARED = 3 @INITIAL_AGE = ModelParameters.pairingAge + 1 constructor: (@_nestingPreference, @_howReared) -> @birthYear = Clock.currentYear @uuid = Bird.uuidFactory.v4() @_nestingPreference ?= if Math.random() < 0.5 Bird.EARLY else Bird.LATE @fromNest: (nest, howReared) -> firstParent = nest.builders()[0] secondParent = nest.builders()[1] if firstParent.nestingPreference() == secondParent.nestingPreference() babyPreference = firstParent.nestingPreference() if Math.random() < ModelParameters.mutationRate babyPreference = Bird.flip(babyPreference) else if Math.random() < 0.5 babyPreference = Bird.EARLY else babyPreference = Bird.LATE new Bird(babyPreference, howReared) rollBackBirthYear: -> @birthYear = @birthYear - Bird.INITIAL_AGE age: -> Clock.currentYear - @birthYear canMate: -> @age() >= ModelParameters.pairingAge nestingPreference: -> @_nestingPreference isEarly: -> @_nestingPreference is Bird.EARLY isLate: -> @_nestingPreference is Bird.LATE howReared: -> @_howReared isCaptive: -> @_howReared is Bird.CAPTIVE_REARED isWild: -> @_howReared is Bird.WILD_REARED @flip: (preference) -> if preference == Bird.EARLY Bird.LATE else Bird.EARLY survives: -> mortality = ModelParameters.matureMortalityRate Math.random() >= mortality module.exports = Bird
92356
### Basic model of an individual bird (whooping crane). https://github.com/NicMcPhee/whooping-crane-model Copyright (c) 2015 <NAME> Licensed under the MIT license. ### 'use strict' ModelParameters = require './model_parameters' Clock = require './clock' class Bird @uuidFactory: require('uuid') @EARLY = 0 @LATE = 1 @WILD_REARED = 2 @CAPTIVE_REARED = 3 @INITIAL_AGE = ModelParameters.pairingAge + 1 constructor: (@_nestingPreference, @_howReared) -> @birthYear = Clock.currentYear @uuid = Bird.uuidFactory.v4() @_nestingPreference ?= if Math.random() < 0.5 Bird.EARLY else Bird.LATE @fromNest: (nest, howReared) -> firstParent = nest.builders()[0] secondParent = nest.builders()[1] if firstParent.nestingPreference() == secondParent.nestingPreference() babyPreference = firstParent.nestingPreference() if Math.random() < ModelParameters.mutationRate babyPreference = Bird.flip(babyPreference) else if Math.random() < 0.5 babyPreference = Bird.EARLY else babyPreference = Bird.LATE new Bird(babyPreference, howReared) rollBackBirthYear: -> @birthYear = @birthYear - Bird.INITIAL_AGE age: -> Clock.currentYear - @birthYear canMate: -> @age() >= ModelParameters.pairingAge nestingPreference: -> @_nestingPreference isEarly: -> @_nestingPreference is Bird.EARLY isLate: -> @_nestingPreference is Bird.LATE howReared: -> @_howReared isCaptive: -> @_howReared is Bird.CAPTIVE_REARED isWild: -> @_howReared is Bird.WILD_REARED @flip: (preference) -> if preference == Bird.EARLY Bird.LATE else Bird.EARLY survives: -> mortality = ModelParameters.matureMortalityRate Math.random() >= mortality module.exports = Bird
true
### Basic model of an individual bird (whooping crane). https://github.com/NicMcPhee/whooping-crane-model Copyright (c) 2015 PI:NAME:<NAME>END_PI Licensed under the MIT license. ### 'use strict' ModelParameters = require './model_parameters' Clock = require './clock' class Bird @uuidFactory: require('uuid') @EARLY = 0 @LATE = 1 @WILD_REARED = 2 @CAPTIVE_REARED = 3 @INITIAL_AGE = ModelParameters.pairingAge + 1 constructor: (@_nestingPreference, @_howReared) -> @birthYear = Clock.currentYear @uuid = Bird.uuidFactory.v4() @_nestingPreference ?= if Math.random() < 0.5 Bird.EARLY else Bird.LATE @fromNest: (nest, howReared) -> firstParent = nest.builders()[0] secondParent = nest.builders()[1] if firstParent.nestingPreference() == secondParent.nestingPreference() babyPreference = firstParent.nestingPreference() if Math.random() < ModelParameters.mutationRate babyPreference = Bird.flip(babyPreference) else if Math.random() < 0.5 babyPreference = Bird.EARLY else babyPreference = Bird.LATE new Bird(babyPreference, howReared) rollBackBirthYear: -> @birthYear = @birthYear - Bird.INITIAL_AGE age: -> Clock.currentYear - @birthYear canMate: -> @age() >= ModelParameters.pairingAge nestingPreference: -> @_nestingPreference isEarly: -> @_nestingPreference is Bird.EARLY isLate: -> @_nestingPreference is Bird.LATE howReared: -> @_howReared isCaptive: -> @_howReared is Bird.CAPTIVE_REARED isWild: -> @_howReared is Bird.WILD_REARED @flip: (preference) -> if preference == Bird.EARLY Bird.LATE else Bird.EARLY survives: -> mortality = ModelParameters.matureMortalityRate Math.random() >= mortality module.exports = Bird
[ { "context": "###\n * @author \t\tAbdelhakim RAFIK\n * @version \tv1.0.1\n * @license \tMIT License\n * @", "end": 33, "score": 0.9998916983604431, "start": 17, "tag": "NAME", "value": "Abdelhakim RAFIK" }, { "context": "nse \tMIT License\n * @copyright \tCopyright (c) 2021 Abdelhaki...
src/routes/publicRouter.coffee
AbdelhakimRafik/Pharmalogy-API
0
### * @author Abdelhakim RAFIK * @version v1.0.1 * @license MIT License * @copyright Copyright (c) 2021 Abdelhakim RAFIK * @date Mar 2021 ### { Router } = require 'express' router = do Router authController = require '../app/controllers/authController' pharmacyController = require '../app/controllers/pharmacyController' # export router module.exports = router # register route router.post '/signup', authController.signup # login route router.post '/signin', authController.signin # pharmacies locations router.post '/pharmacies/location', pharmacyController.getLocations
95594
### * @author <NAME> * @version v1.0.1 * @license MIT License * @copyright Copyright (c) 2021 <NAME> * @date Mar 2021 ### { Router } = require 'express' router = do Router authController = require '../app/controllers/authController' pharmacyController = require '../app/controllers/pharmacyController' # export router module.exports = router # register route router.post '/signup', authController.signup # login route router.post '/signin', authController.signin # pharmacies locations router.post '/pharmacies/location', pharmacyController.getLocations
true
### * @author PI:NAME:<NAME>END_PI * @version v1.0.1 * @license MIT License * @copyright Copyright (c) 2021 PI:NAME:<NAME>END_PI * @date Mar 2021 ### { Router } = require 'express' router = do Router authController = require '../app/controllers/authController' pharmacyController = require '../app/controllers/pharmacyController' # export router module.exports = router # register route router.post '/signup', authController.signup # login route router.post '/signin', authController.signin # pharmacies locations router.post '/pharmacies/location', pharmacyController.getLocations
[ { "context": "eanu-shirt' + (randomToken 2)\n name: 'Sad Keanu T-shirt'\n price: 2500\n currency: 'US", "end": 163, "score": 0.9915421605110168, "start": 146, "tag": "NAME", "value": "Sad Keanu T-shirt" } ]
test/server/product.coffee
hanzo-io/hanzo.js
147
describe 'Api.product', -> product = null before -> product = slug: 'sad-keanu-shirt' + (randomToken 2) name: 'Sad Keanu T-shirt' price: 2500 currency: 'USD' headline: 'Oh Keanu' description: 'Sad Keanu is sad.' options: [ name: 'size' values: ['sadness'] ] describe '.create', -> it 'should create products', -> p = yield api.product.create product p.price.should.eq product.price product.slug = p.slug describe '.get', -> it 'should get product', -> p = yield api.product.get product.slug p.price.should.eq 2500 describe '.list', -> it 'should list products', -> {count, models} = yield api.product.list() models.length.should.be.gt 0 count.should.be.gt 0 describe '.update', -> it 'should update products', -> p = yield api.product.update slug: product.slug, price: 3500 p.price.should.eq 3500 describe '.delete', -> it 'should delete products', -> yield api.product.delete product.slug describe 'cache invalidation', -> it 'should invalidate product', -> product2 = slug: 'happy-keanu-shirt' price: 4000 yield api.product.create product2 yield api.product.update slug: 'happy-keanu-shirt', price: 5000 p = yield api.product.get slug: 'happy-keanu-shirt' p.price.should.eq 5000
215289
describe 'Api.product', -> product = null before -> product = slug: 'sad-keanu-shirt' + (randomToken 2) name: '<NAME>' price: 2500 currency: 'USD' headline: 'Oh Keanu' description: 'Sad Keanu is sad.' options: [ name: 'size' values: ['sadness'] ] describe '.create', -> it 'should create products', -> p = yield api.product.create product p.price.should.eq product.price product.slug = p.slug describe '.get', -> it 'should get product', -> p = yield api.product.get product.slug p.price.should.eq 2500 describe '.list', -> it 'should list products', -> {count, models} = yield api.product.list() models.length.should.be.gt 0 count.should.be.gt 0 describe '.update', -> it 'should update products', -> p = yield api.product.update slug: product.slug, price: 3500 p.price.should.eq 3500 describe '.delete', -> it 'should delete products', -> yield api.product.delete product.slug describe 'cache invalidation', -> it 'should invalidate product', -> product2 = slug: 'happy-keanu-shirt' price: 4000 yield api.product.create product2 yield api.product.update slug: 'happy-keanu-shirt', price: 5000 p = yield api.product.get slug: 'happy-keanu-shirt' p.price.should.eq 5000
true
describe 'Api.product', -> product = null before -> product = slug: 'sad-keanu-shirt' + (randomToken 2) name: 'PI:NAME:<NAME>END_PI' price: 2500 currency: 'USD' headline: 'Oh Keanu' description: 'Sad Keanu is sad.' options: [ name: 'size' values: ['sadness'] ] describe '.create', -> it 'should create products', -> p = yield api.product.create product p.price.should.eq product.price product.slug = p.slug describe '.get', -> it 'should get product', -> p = yield api.product.get product.slug p.price.should.eq 2500 describe '.list', -> it 'should list products', -> {count, models} = yield api.product.list() models.length.should.be.gt 0 count.should.be.gt 0 describe '.update', -> it 'should update products', -> p = yield api.product.update slug: product.slug, price: 3500 p.price.should.eq 3500 describe '.delete', -> it 'should delete products', -> yield api.product.delete product.slug describe 'cache invalidation', -> it 'should invalidate product', -> product2 = slug: 'happy-keanu-shirt' price: 4000 yield api.product.create product2 yield api.product.update slug: 'happy-keanu-shirt', price: 5000 p = yield api.product.get slug: 'happy-keanu-shirt' p.price.should.eq 5000
[ { "context": "'name': 'test'\n'scopeName': 'source.test'\n'injectionSelector': ", "end": 13, "score": 0.7991854548454285, "start": 9, "tag": "NAME", "value": "test" } ]
spec/fixtures/packages/package-with-injection-selector/grammars/grammar.cson
pyrolabs/atom
62,188
'name': 'test' 'scopeName': 'source.test' 'injectionSelector': 'comment' 'patterns': [{'include': 'source.sql'}]
25570
'name': '<NAME>' 'scopeName': 'source.test' 'injectionSelector': 'comment' 'patterns': [{'include': 'source.sql'}]
true
'name': 'PI:NAME:<NAME>END_PI' 'scopeName': 'source.test' 'injectionSelector': 'comment' 'patterns': [{'include': 'source.sql'}]
[ { "context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affe", "end": 23, "score": 0.5424295663833618, "start": 21, "tag": "NAME", "value": "ty" }, { "context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public Li",...
resources/assets/coffee/react/beatmapset-page.coffee
osu-katakuna/osu-katakuna-web
5
# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0. # See the LICENCE file in the repository root for full licence text. import { Main } from './beatmapset-page/main' reactTurbolinks.registerPersistent 'beatmapset-page', Main, true, (target) -> beatmapset: osu.parseJson('json-beatmapset') countries: _.keyBy osu.parseJson('json-countries'), 'code' container: target
191757
# Copyright (c) ppy P<NAME> Ltd <<EMAIL>>. Licensed under the GNU Affero General Public License v3.0. # See the LICENCE file in the repository root for full licence text. import { Main } from './beatmapset-page/main' reactTurbolinks.registerPersistent 'beatmapset-page', Main, true, (target) -> beatmapset: osu.parseJson('json-beatmapset') countries: _.keyBy osu.parseJson('json-countries'), 'code' container: target
true
# Copyright (c) ppy PPI:NAME:<NAME>END_PI Ltd <PI:EMAIL:<EMAIL>END_PI>. Licensed under the GNU Affero General Public License v3.0. # See the LICENCE file in the repository root for full licence text. import { Main } from './beatmapset-page/main' reactTurbolinks.registerPersistent 'beatmapset-page', Main, true, (target) -> beatmapset: osu.parseJson('json-beatmapset') countries: _.keyBy osu.parseJson('json-countries'), 'code' container: target
[ { "context": " type: ['string', 'array']\n data = name: 'Thor', info: {numbers: ['401-401-1337', ['123-456-7890", "end": 447, "score": 0.9993302226066589, "start": 443, "tag": "NAME", "value": "Thor" } ]
test/scripting.coffee
lgr7/codecombattreema
66
do -> expectOpen = (t) -> expect(t).toBeDefined() expect(t.isClosed()).toBeFalsy() expectClosed = (t) -> expect(t).toBeDefined() expect(t.isClosed()).toBeTruthy() schema = type: 'object', properties: name: type: 'string' info: type: 'object' properties: numbers: type: 'array', items: type: ['string', 'array'] data = name: 'Thor', info: {numbers: ['401-401-1337', ['123-456-7890']]} treema = TreemaNode.make(null, {data: data, schema: schema}) treema.build() beforeEach -> treema.deselectAll() treema.close() describe 'open', -> it 'can open n levels deep', -> expectClosed(treema) treema.open(2) expectOpen(treema) infoTreema = treema.childrenTreemas.info expectOpen(infoTreema) phoneTreema = infoTreema.childrenTreemas.numbers expectClosed(phoneTreema)
193880
do -> expectOpen = (t) -> expect(t).toBeDefined() expect(t.isClosed()).toBeFalsy() expectClosed = (t) -> expect(t).toBeDefined() expect(t.isClosed()).toBeTruthy() schema = type: 'object', properties: name: type: 'string' info: type: 'object' properties: numbers: type: 'array', items: type: ['string', 'array'] data = name: '<NAME>', info: {numbers: ['401-401-1337', ['123-456-7890']]} treema = TreemaNode.make(null, {data: data, schema: schema}) treema.build() beforeEach -> treema.deselectAll() treema.close() describe 'open', -> it 'can open n levels deep', -> expectClosed(treema) treema.open(2) expectOpen(treema) infoTreema = treema.childrenTreemas.info expectOpen(infoTreema) phoneTreema = infoTreema.childrenTreemas.numbers expectClosed(phoneTreema)
true
do -> expectOpen = (t) -> expect(t).toBeDefined() expect(t.isClosed()).toBeFalsy() expectClosed = (t) -> expect(t).toBeDefined() expect(t.isClosed()).toBeTruthy() schema = type: 'object', properties: name: type: 'string' info: type: 'object' properties: numbers: type: 'array', items: type: ['string', 'array'] data = name: 'PI:NAME:<NAME>END_PI', info: {numbers: ['401-401-1337', ['123-456-7890']]} treema = TreemaNode.make(null, {data: data, schema: schema}) treema.build() beforeEach -> treema.deselectAll() treema.close() describe 'open', -> it 'can open n levels deep', -> expectClosed(treema) treema.open(2) expectOpen(treema) infoTreema = treema.childrenTreemas.info expectOpen(infoTreema) phoneTreema = infoTreema.childrenTreemas.numbers expectClosed(phoneTreema)
[ { "context": "nt\n\n api\n) ->\n\n ###*\n # @author David Bouman\n # @module App\n # @submodule ", "end": 564, "score": 0.9998443722724915, "start": 552, "tag": "NAME", "value": "David Bouman" }, { "context": " parse: ( data ) ->\n\n ...
generators/app/templates/src/models/build-brief.coffee
marviq/generator-bat
3
'use strict' ( ( factory ) -> if typeof exports is 'object' module.exports = factory( require( 'backbone' ) require( 'bluebird' ) require( 'moment' ) require( './../apis/env.coffee' ) ) else if typeof define is 'function' and define.amd define( [ 'backbone' 'bluebird' 'moment' './../apis/env.coffee' ], factory ) return )(( Backbone Promise moment api ) -> ###* # @author David Bouman # @module App # @submodule Models ### ## Stamped logs ## log = ( args... ) -> console.log( '[BUILDINFO]', args... ) ###* # The current build's briefing information. # # @class BuildBrief # @extends Backbone.Model # @static ### class BuildBriefModel extends Backbone.Model ###* # List of [valid attribute names](#attrs). # # @property schema # @type Array[String] # @final ### ###* # The value of the `BUILD_NUMBER` environment variable at the time of build. # Expected to be provided from the ci/cd build job. # Expected to be a count of the number of these build jobs triggered so far. # # If `BUILD_NUMBER` has not been set, this will instead be the number of builds triggered from a watched `grunt dev` run since invocation. # # @attribute buildNumber # @type String ### ###* # The value of the `BUILD_ID` environment variable at the time of build. # Expected to be provided from the ci/cd build job. # Expected to be reference-id of the build job meaningful to your ci/cd. # # @attribute buildId # @type String ### ###* # The value of the `GIT_COMMIT` environment variable at the time of build. # Expected to be provided from the ci/cd build job. # Expected to be the git commit hash that the ci/cd build job checked out. # # If `GIT_COMMIT` has not been set, this will be the string `working dir` instead. # # @attribute revision # @type String ### ###* # Human readable timestamp of when this build brief was generated. Indicative of when the build was run/completed. # # @attribute grunted # @type String ### ###* # The build's target-environment's name. # # Typically: # * `production` # * `acceptance` # * `testing` # * `local` # # @attribute environment # @type String ### ###* # Flag for signalling whether this was a debugging build. # # @attribute debugging # @type Boolean ### ###* # The app's name as listed in its `package.json`. # # @attribute name # @type String ### ###* # The app's version as listed in its `package.json`. # # See also: http://semver.org/ # # @attribute version # @type Semver ### ###* # Unix timestamp of the build's run; equal to `grunted` # # @attribute timestamp # @type Number ### schema: [ 'buildNumber' 'buildId' 'revision' 'grunted' 'environment' 'debugging' 'name' 'version' 'timestamp' ] ###* # Service API endpoint; defined in the {{#crossLink 'EnvApi/buildBrief:attribute'}}`EnvApi`{{/crossLink}}. # # @property url # @type ApiServiceModel # @final # # @default '<EnvApi.url>/build.json' ### url: api.get( 'buildBrief' ) ###* # @method initialize # @protected ### initialize: () -> ###* # A `Promise` that the build's briefing data will have been loaded. # # @property initialized # @type Promise # @final ### @initialized = Promise.resolve( @fetch( cache: false ) ).then( ( attributes ) => ### jshint unused: false ### return @ ( jqXHR ) -> ### jshint unused: false ### message = 'Unable to load build briefing information.' log( message ) throw new Error( message ) ) return ###* # @method parse # @protected ### parse: ( data ) -> key = 'timestamp' data[ key ] = moment( data[ key ] ) return data ## Export singleton. ## return new BuildBriefModel() )
10652
'use strict' ( ( factory ) -> if typeof exports is 'object' module.exports = factory( require( 'backbone' ) require( 'bluebird' ) require( 'moment' ) require( './../apis/env.coffee' ) ) else if typeof define is 'function' and define.amd define( [ 'backbone' 'bluebird' 'moment' './../apis/env.coffee' ], factory ) return )(( Backbone Promise moment api ) -> ###* # @author <NAME> # @module App # @submodule Models ### ## Stamped logs ## log = ( args... ) -> console.log( '[BUILDINFO]', args... ) ###* # The current build's briefing information. # # @class BuildBrief # @extends Backbone.Model # @static ### class BuildBriefModel extends Backbone.Model ###* # List of [valid attribute names](#attrs). # # @property schema # @type Array[String] # @final ### ###* # The value of the `BUILD_NUMBER` environment variable at the time of build. # Expected to be provided from the ci/cd build job. # Expected to be a count of the number of these build jobs triggered so far. # # If `BUILD_NUMBER` has not been set, this will instead be the number of builds triggered from a watched `grunt dev` run since invocation. # # @attribute buildNumber # @type String ### ###* # The value of the `BUILD_ID` environment variable at the time of build. # Expected to be provided from the ci/cd build job. # Expected to be reference-id of the build job meaningful to your ci/cd. # # @attribute buildId # @type String ### ###* # The value of the `GIT_COMMIT` environment variable at the time of build. # Expected to be provided from the ci/cd build job. # Expected to be the git commit hash that the ci/cd build job checked out. # # If `GIT_COMMIT` has not been set, this will be the string `working dir` instead. # # @attribute revision # @type String ### ###* # Human readable timestamp of when this build brief was generated. Indicative of when the build was run/completed. # # @attribute grunted # @type String ### ###* # The build's target-environment's name. # # Typically: # * `production` # * `acceptance` # * `testing` # * `local` # # @attribute environment # @type String ### ###* # Flag for signalling whether this was a debugging build. # # @attribute debugging # @type Boolean ### ###* # The app's name as listed in its `package.json`. # # @attribute name # @type String ### ###* # The app's version as listed in its `package.json`. # # See also: http://semver.org/ # # @attribute version # @type Semver ### ###* # Unix timestamp of the build's run; equal to `grunted` # # @attribute timestamp # @type Number ### schema: [ 'buildNumber' 'buildId' 'revision' 'grunted' 'environment' 'debugging' 'name' 'version' 'timestamp' ] ###* # Service API endpoint; defined in the {{#crossLink 'EnvApi/buildBrief:attribute'}}`EnvApi`{{/crossLink}}. # # @property url # @type ApiServiceModel # @final # # @default '<EnvApi.url>/build.json' ### url: api.get( 'buildBrief' ) ###* # @method initialize # @protected ### initialize: () -> ###* # A `Promise` that the build's briefing data will have been loaded. # # @property initialized # @type Promise # @final ### @initialized = Promise.resolve( @fetch( cache: false ) ).then( ( attributes ) => ### jshint unused: false ### return @ ( jqXHR ) -> ### jshint unused: false ### message = 'Unable to load build briefing information.' log( message ) throw new Error( message ) ) return ###* # @method parse # @protected ### parse: ( data ) -> key = '<KEY>' data[ key ] = moment( data[ key ] ) return data ## Export singleton. ## return new BuildBriefModel() )
true
'use strict' ( ( factory ) -> if typeof exports is 'object' module.exports = factory( require( 'backbone' ) require( 'bluebird' ) require( 'moment' ) require( './../apis/env.coffee' ) ) else if typeof define is 'function' and define.amd define( [ 'backbone' 'bluebird' 'moment' './../apis/env.coffee' ], factory ) return )(( Backbone Promise moment api ) -> ###* # @author PI:NAME:<NAME>END_PI # @module App # @submodule Models ### ## Stamped logs ## log = ( args... ) -> console.log( '[BUILDINFO]', args... ) ###* # The current build's briefing information. # # @class BuildBrief # @extends Backbone.Model # @static ### class BuildBriefModel extends Backbone.Model ###* # List of [valid attribute names](#attrs). # # @property schema # @type Array[String] # @final ### ###* # The value of the `BUILD_NUMBER` environment variable at the time of build. # Expected to be provided from the ci/cd build job. # Expected to be a count of the number of these build jobs triggered so far. # # If `BUILD_NUMBER` has not been set, this will instead be the number of builds triggered from a watched `grunt dev` run since invocation. # # @attribute buildNumber # @type String ### ###* # The value of the `BUILD_ID` environment variable at the time of build. # Expected to be provided from the ci/cd build job. # Expected to be reference-id of the build job meaningful to your ci/cd. # # @attribute buildId # @type String ### ###* # The value of the `GIT_COMMIT` environment variable at the time of build. # Expected to be provided from the ci/cd build job. # Expected to be the git commit hash that the ci/cd build job checked out. # # If `GIT_COMMIT` has not been set, this will be the string `working dir` instead. # # @attribute revision # @type String ### ###* # Human readable timestamp of when this build brief was generated. Indicative of when the build was run/completed. # # @attribute grunted # @type String ### ###* # The build's target-environment's name. # # Typically: # * `production` # * `acceptance` # * `testing` # * `local` # # @attribute environment # @type String ### ###* # Flag for signalling whether this was a debugging build. # # @attribute debugging # @type Boolean ### ###* # The app's name as listed in its `package.json`. # # @attribute name # @type String ### ###* # The app's version as listed in its `package.json`. # # See also: http://semver.org/ # # @attribute version # @type Semver ### ###* # Unix timestamp of the build's run; equal to `grunted` # # @attribute timestamp # @type Number ### schema: [ 'buildNumber' 'buildId' 'revision' 'grunted' 'environment' 'debugging' 'name' 'version' 'timestamp' ] ###* # Service API endpoint; defined in the {{#crossLink 'EnvApi/buildBrief:attribute'}}`EnvApi`{{/crossLink}}. # # @property url # @type ApiServiceModel # @final # # @default '<EnvApi.url>/build.json' ### url: api.get( 'buildBrief' ) ###* # @method initialize # @protected ### initialize: () -> ###* # A `Promise` that the build's briefing data will have been loaded. # # @property initialized # @type Promise # @final ### @initialized = Promise.resolve( @fetch( cache: false ) ).then( ( attributes ) => ### jshint unused: false ### return @ ( jqXHR ) -> ### jshint unused: false ### message = 'Unable to load build briefing information.' log( message ) throw new Error( message ) ) return ###* # @method parse # @protected ### parse: ( data ) -> key = 'PI:KEY:<KEY>END_PI' data[ key ] = moment( data[ key ] ) return data ## Export singleton. ## return new BuildBriefModel() )
[ { "context": "\n type_str = 'boolean'\n name_str = 'michale'\n\n describe 'Boolean', ->\n\n it 's", "end": 5992, "score": 0.6691257357597351, "start": 5985, "tag": "NAME", "value": "michale" }, { "context": "describe 'alphaNumeric', ->\n\n name_str ...
test/unit_validate_spec.coffee
deployable/deployable-validate
0
Validate = require '../lib/validate' ValidationError = Validate.ValidationError describe 'Unit::Validate', -> describe 'Class', -> describe 'Manage Tests', -> it 'should get a test', -> expect( Validate.getTest('testing') ).to.be.ok it 'should throw on a missing test', -> fn = -> Validate.getTest('testingno') expect( fn ).to.throw Error, /No test named "testingno" available/ it 'should add a new test', -> expect( Validate.addTest('testingtwo', { test: (val)=> val }) ).to.be.ok it 'should run the new test', -> expect( Validate.a('testingtwo', true) ).to.be.true expect( Validate.a('testingtwo', false) ).to.be.false it 'should fail to add the same test', -> fn = -> Validate.addTest('testingtwo', { test: (val)=> val }) expect( fn ).to.be.throw Error, /Test label "testingtwo" already exists/ describe 'Dynamic Tests', -> it 'a string "test" alpha true', -> expect( Validate.string('alpha', 'test') ).to.be.true it 'string "test" alpha true', -> expect( Validate.string('alpha', 'test') ).to.be.true it 'string "test9" alpha true', -> expect( Validate.string('alpha', 'test9c') ).to.be.false it 'a number 3 range 1,5 true', -> expect( Validate.number('range', 3, 1,5) ).to.be.true it 'a number 1 range 3,5 false', -> expect( Validate.number('range', 1, 3,5) ).to.be.false it 'number 1 range 3,5 false', -> expect( Validate.a('range', 1, 3,5) ).to.be.false it 'number 1 between 3,5 false', -> expect( Validate.number('between', 1, 3,5) ).to.be.false it 'number 1 between 1,5 false', -> expect( Validate.a('between', 1, 1,5) ).to.be.false it 'number 2 between 1,5 true', -> expect( Validate.number('between', 2, 1,5) ).to.be.true it 'number 1 between 2,5 true', -> expect( Validate.number('between', 1, 2, 5) ).to.be.false it 'number group throws on missing', -> fn = -> Validate.number('match', 1, 2, 5) expect( fn ).to.throw Error it 'throws number 1 between 2,5 true', -> fn = -> Validate.andThrow('between', 1, 2, 5) expect( fn ).to.throw ValidationError, /Value must be between 2 and 5/ it 'test types buffer via language', -> expect( Validate.language('buffer', new Buffer('')) ).to.be.true it 'test types buffer', -> expect( Validate.a('buffer', new Buffer('')) ).to.be.true it 'test types date', -> expect( Validate.a('date', new Date()) ).to.be.true it 'test types element', -> class Element nodeType: 1 expect( Validate.an('element', new Element()) ).to.be.true it 'test types error', -> expect( Validate.an('error', new Error()) ).to.be.true it 'test types finite', -> expect( Validate.a('finite', 3) ).to.be.true it 'test types function', -> expect( Validate.a('function', new Function()) ).to.be.true it 'test types Map', -> expect( Validate.a('map', new Map()) ).to.be.true it 'test types Nan', -> expect( Validate.a('nan', NaN) ).to.be.true it 'test types number', -> expect( Validate.a('number', 3) ).to.be.true it 'test types object', -> expect( Validate.a('object', {}) ).to.be.true it 'test types plainobject', -> expect( Validate.a('plainobject', {}) ).to.be.true it 'test types regexp', -> expect( Validate.a('regexp', /\w/) ).to.be.true it 'test types safeinteger', -> expect( Validate.a('safeinteger', 5) ).to.be.true it 'test types string', -> expect( Validate.a('string', '') ).to.be.true it 'test types symbol', -> expect( Validate.a('symbol', Symbol.iterator) ).to.be.true it 'test types typedarray', -> expect( Validate.a('typedarray', new Uint8Array) ).to.be.true it 'test types weakmap', -> expect( Validate.a('weakmap', new WeakMap()) ).to.be.true it 'test types weakset', -> expect( Validate.a('weakset', new WeakSet()) ).to.be.true it 'test types nil', -> expect( Validate.a('nil', undefined ) ).to.be.true it 'test types notNil', -> expect( Validate.a('notNil', 5 ) ).to.be.true # Types moved into new test world describe 'Type Tests', -> describe 'Array', -> type_str = 'array' name_str = 'wakka' describe 'Boolean', -> it 'should validate an array', -> expect( Validate.as('array', [], name_str) ).to.be.true it 'should not validate a non array', -> expect( Validate.as('array', 'a', name_str) ).to.be.false describe 'Error', -> it 'should validate an array', -> expect( Validate.toMessage('array', [], name_str) ).to.be.undefined it 'should return msg on non array with name', -> fn = Validate.toMessage('array', '', name_str) expect( fn ).to.equal '"wakka" must be an array' it 'should return generic msg on non array without name', -> fn = Validate.toMessage('array', '') expect( fn ).to.equal 'Value must be an array' describe 'Throw', -> it 'should validate an array', -> expect( Validate.andThrow('array', [], name_str) ).to.be.true it 'should throw on non array with name', -> fn = -> Validate.andThrow('array', '', name_str) expect( fn ).to.throw ValidationError, '"wakka" must be an array' it 'should throw on non array without name', -> fn = -> Validate.andThrow('array', '') expect( fn ).to.throw ValidationError, 'Value must be an array' describe 'Boolean', -> type_str = 'boolean' name_str = 'michale' describe 'Boolean', -> it 'should validate an boolean', -> expect( Validate.as('boolean', true, name_str) ).to.be.true it 'should not validate a non boolean', -> expect( Validate.as('boolean', 'a', name_str) ).to.be.false describe 'Message', -> it 'should validate an boolean', -> expect( Validate.toMessage('boolean', false, name_str) ).to.be.undefined it 'should return msg on non boolean with name', -> fn = Validate.toMessage('boolean', '', name_str) expect( fn ).to.equal '"michale" must be a boolean' it 'should return generic msg on non boolean without name', -> fn = Validate.toMessage('boolean', '') expect( fn ).to.equal 'Value must be a boolean' describe 'Throw', -> it 'should validate an boolean', -> expect( Validate.andThrow('boolean', true, name_str) ).to.be.true it 'should throw on non boolean with name', -> fn = -> Validate.andThrow('boolean', '', name_str) expect( fn ).to.throw ValidationError, '"michale" must be a boolean' it 'should throw on non boolean without name', -> fn = -> Validate.andThrow('boolean', '') expect( fn ).to.throw ValidationError, 'Value must be a boolean' describe 'Integer', -> type_str = 'integer' name_str = 'the_int' describe 'Boolean', -> it 'should validate an integer', -> expect( Validate.as('integer', 5, name_str) ).to.be.true it 'should not validate a non integer', -> expect( Validate.as('integer', 5.5, name_str) ).to.be.false it 'should not validate a non integer', -> expect( Validate.as('integer', 'a', name_str) ).to.be.false describe 'Message', -> it 'should validate an integer', -> expect( Validate.toMessage('integer', 7, name_str) ).to.be.undefined it 'should return msg on non integer with name', -> fn = Validate.toMessage('integer', '', name_str) expect( fn ).to.equal '"the_int" must be an integer' it 'should return generic msg on non integer without name', -> fn = Validate.toMessage('integer', '') expect( fn ).to.equal 'Value must be an integer' describe 'Throw', -> it 'should validate an integer', -> expect( Validate.andThrow('integer', 6, name_str) ).to.be.true it 'should throw on non integer with name', -> fn = -> Validate.andThrow('integer', '', name_str) expect( fn ).to.throw ValidationError, '"the_int" must be an integer' it 'should throw on non integer without name', -> fn = -> Validate.andThrow('integer', '') expect( fn ).to.throw ValidationError, 'Value must be an integer' describe 'String', -> type_str = 'string' name_str = 'description' describe 'Boolean', -> it 'should validate an string', -> expect( Validate.as(type_str, 'test', name_str) ).to.be.true it 'should not validate a non string', -> expect( Validate.as(type_str, 5, name_str) ).to.be.false describe 'Message', -> it 'should validate an string', -> expect( Validate.toMessage(type_str, 'test', name_str) ).to.be.undefined it 'should return msg on non string with name', -> fn = Validate.toMessage(type_str, [], name_str) expect( fn ).to.equal '"description" must be a string' it 'should return generic msg on non string without name', -> fn = Validate.toMessage(type_str, true) expect( fn ).to.equal 'Value must be a string' describe 'Throw', -> it 'should validate an string', -> expect( Validate.andThrow('string', 'test', name_str) ).to.be.true it 'should throw on non string with name', -> fn = -> Validate.andThrow('string', 5, name_str) expect( fn ).to.throw ValidationError, '"description" must be a string' it 'should throw on non string without name', -> fn = -> Validate.andThrow('string', {}) expect( fn ).to.throw ValidationError, 'Value must be a string' describe 'Length', -> it 'should return true for the length of string', -> expect( Validate.a('length', 'a', 1, 256, 'thestring') ).to.be.true it 'should return true for the length of string', -> expect( Validate.a('length', 'test', 4, 4, 'thestring') ).to.be.true it 'should return true for above the length of string', -> expect( Validate.a('length', 'test', 3, 5, 'thestring') ).to.be.true it 'should return false for below the length of string', -> expect( Validate.a('length', 'test', 3, 3, 'thestring') ).to.be.false it 'should return false for above the length of string', -> expect( Validate.a('length', 'test', 5, 5, 'thestring') ).to.be.false it 'should return true for only a min', -> expect( Validate.a('length', 'test',4) ).to.be.true it 'should return false for only a min above', -> expect( Validate.a('length', 'test',5) ).to.be.false it 'should return false for only a min below', -> expect( Validate.a('length', 'test',3) ).to.be.false it 'should return error message', -> msg = Validate.toMessage('length', 'test', 1, 5,'thestring') expect( msg ).to.be.undefined it 'should return error message', -> msg = Validate.toMessage('length', 'test', 5, 5,'thestring') expect( msg ).to.be.equal '"thestring" has length 4. Must be 5' it 'should return error message', -> msg = Validate.toMessage('length', 'tes', 4, 5, 'thestring') expect( msg ).to.be.equal '"thestring" has length 3. Must be 4 to 5' it 'should return error', -> res = Validate.toError('length', 'test', 1, 5,'thestring') expect( res ).to.be.undefined it 'should return error', -> err = Validate.toError('length', 'test', 5, 5,'thestring') expect( err ).to.be.instanceOf(ValidationError) expect( err.message ).to.equal '"thestring" has length 4. Must be 5' it 'should throw error', -> fn = -> Validate.andThrow('length', 'test', 1, 5,'thestring') expect( fn ).to.not.throw it 'should throw error', -> fn = -> Validate.andThrow('length', '3es', 4, 5,'thestring') expect( fn ).to.throw ValidationError, '"thestring" has length 3. Must be 4 to 5' describe 'Alpha', -> name_str = "thestring" name_str_msg = "\"#{name_str}\" " error_msg = "must only contain letters [ A-Z a-z ]" it 'should return true alpha', -> expect( Validate.string('alpha', 'ab', 'thestring') ).to.be.true it 'should return true alpha', -> expect( Validate.string('alpha', '59!#$%', 'thestring') ).to.be.false it 'should return true alpha', -> fn = -> Validate.string('integer', '59!#$%', 'thestring') expect( fn ).to.throw Error it 'should return error message', -> msg = Validate.toMessage('alpha', 'ab', 'thestring') expect( msg ).to.be.undefined it 'should return error message', -> msg = Validate.toMessage('alpha', 'a!b', 'thestring') expect( msg ).to.be.equal "#{name_str_msg}#{error_msg}" it 'should return error message', -> msg = Validate.toMessage('alpha', 'a!b') expect( msg ).to.be.equal "Value #{error_msg}" it 'should return error', -> res = Validate.toError('alpha', 'test', 'thestring') expect( res ).to.be.undefined it 'should return error', -> err = Validate.toError('alpha', 'test!', 'thestring') expect( err ).to.be.instanceOf(ValidationError) expect( err.message ).to.equal "#{name_str_msg}#{error_msg}" it 'should not throw error', -> expect( Validate.andThrow('alpha', 'test', 'thestring') ).to.be.true it 'should throw error', -> fn = -> Validate.andThrow('alpha', 'test!', 'thestring') expect( fn ).to.throw ValidationError, "#{name_str_msg}#{error_msg}" describe 'Numeric', -> name_str = "thestring" name_str_msg = "\"#{name_str}\" " error_msg = "must only contain numbers [ 0-9 ]" it 'should return true numeric', -> expect( Validate.string('numeric', '0939393', name_str) ).to.be.true it 'should return true numeric', -> expect( Validate.string('numeric', '59!#$%', name_str) ).to.be.false it 'should return error message', -> msg = Validate.toMessage('numeric', '2323', name_str) expect( msg ).to.be.undefined it 'should return error message', -> msg = Validate.toMessage('numeric', 'a!b', name_str) expect( msg ).to.be.equal "#{name_str_msg}#{error_msg}" it 'should return error message', -> msg = Validate.toMessage('numeric', 'a!b') expect( msg ).to.be.equal "Value #{error_msg}" it 'should return error', -> res = Validate.toError('numeric', '123453', name_str) expect( res ).to.be.undefined it 'should return error', -> err = Validate.toError('numeric', 'aaas', name_str) expect( err ).to.be.instanceOf(ValidationError) expect( err.message ).to.equal "#{name_str_msg}#{error_msg}" it 'should not throw error', -> expect( Validate.andThrow('numeric', '2', name_str) ).to.be.true it 'should throw error', -> fn = -> Validate.andThrow('numeric', 'test!', name_str) expect( fn ).to.throw ValidationError, "#{name_str_msg}#{error_msg}" describe 'alphaNumeric', -> name_str = "thestring" name_str_msg = "\"#{name_str}\" " error_msg = "must only contain letters and numbers [ A-Z a-z 0-9 ]" it 'should return true alpha numeric', -> expect( Validate.string('alphaNumeric', 'ab', name_str) ).to.be.true it 'should return true alpha numeric', -> expect( Validate.string('alphaNumeric', '59!#$%', name_str) ).to.be.false it 'should return error message', -> msg = Validate.toMessage('alphaNumeric', 'ab', name_str) expect( msg ).to.be.undefined it 'should return error message', -> msg = Validate.toMessage('alphaNumeric', 'a!b', name_str) expect( msg ).to.be.equal "#{name_str_msg}#{error_msg}" it 'should return error message', -> msg = Validate.toMessage('alphaNumeric', 'a!b') expect( msg ).to.be.equal "Value #{error_msg}" it 'should return error', -> res = Validate.toError('alphaNumeric', 'test', name_str) expect( res ).to.be.undefined it 'should return error', -> err = Validate.toError('alphaNumeric', 'test!', name_str) expect( err ).to.be.instanceOf(ValidationError) expect( err.message ).to.equal "#{name_str_msg}#{error_msg}" it 'should not throw error', -> expect( Validate.andThrow('alphaNumeric', 'test', name_str) ).to.be.true it 'should throw error', -> fn = -> Validate.andThrow('alphaNumeric', 'test!', name_str) expect( fn ).to.throw ValidationError, "#{name_str_msg}#{error_msg}" describe 'alphaNumericDashUnderscore', -> err_suffix = "must only contain letters, numbers, dash and underscore [ A-Z a-z 0-9 _ - ]" name_str = 'thestring' it 'should return true alpha numeric', -> expect( Validate.string('alphaNumericDashUnderscore', 'ab', name_str) ).to.be.true it 'should return true alpha numeric', -> expect( Validate.string('alphaNumericDashUnderscore', 'a!b', name_str) ).to.be.false it 'should return error message', -> msg = Validate.toMessage('alphaNumericDashUnderscore', 'ab', name_str) expect( msg ).to.be.undefined it 'should return error message', -> msg = Validate.toMessage('alphaNumericDashUnderscore', 'a!b', name_str) expect( msg ).to.be.equal "\"#{name_str}\" #{err_suffix}" it 'should return error', -> res = Validate.toError('alphaNumericDashUnderscore', 'test', name_str) expect( res ).to.be.undefined it 'should return error', -> err = Validate.toError('alphaNumericDashUnderscore', 'test!', name_str) expect( err ).to.be.instanceOf(ValidationError) expect( err.message ).to.equal "\"#{name_str}\" #{err_suffix}" it 'should throw error', -> fn = -> Validate.andThrow('alphaNumericDashUnderscore', 'test', name_str) expect( fn ).to.not.throw it 'should throw error', -> fn = -> Validate.andThrow('alphaNumericDashUnderscore', 'test!', name_str) expect( fn ).to.throw ValidationError, "\"#{name_str}\" #{err_suffix}" describe 'Defined', -> describe 'Boolean', -> it 'should validate a defined variable', -> expect( Validate.as('defined', [], 'somevar') ).to.be.true it 'should not validate a undefined value', -> expect( Validate.as('defined', undefined, 'somevar') ).to.be.false describe 'Message', -> it 'should not return a message for a defined variable', -> expect( Validate.toMessage('defined', 5, 'somevar') ).to.be.undefined it 'should return msg on undefined variable with name', -> fn = Validate.toMessage('defined', undefined, 'somevar') expect( fn ).to.equal '"somevar" must be defined' it 'should return generic msg on non string without name', -> fn = Validate.toMessage('defined', undefined) expect( fn ).to.equal 'Value must be defined' describe 'Throw', -> it 'should not throw on a defined variable', -> expect( Validate.andThrow('defined', 5, 'somevar') ).to.be.true it 'should throw on undefined variable with name', -> fn = -> Validate.andThrow('defined', undefined, 'somevar') expect( fn ).to.throw ValidationError, '"somevar" must be defined' it 'should throw on undefined variable without name', -> fn = -> Validate.andThrow('defined', undefined) expect( fn ).to.throw ValidationError, 'Value must be defined' describe 'Empty', -> describe 'Boolean', -> it 'should validate empty', -> expect( Validate.as('empty', '', 'label') ).to.be.true it 'should validate empty', -> expect( Validate.as('empty', [], 'label') ).to.be.true it 'should validate empty', -> expect( Validate.as('empty', {}, 'label') ).to.be.true it 'should validate empty', -> expect( Validate.as('empty', 7, 'label') ).to.be.true it 'should not validate a non empty', -> expect( Validate.as('empty', 'a', 'label') ).to.be.false describe 'Message', -> it 'should validate empty', -> expect( Validate.toMessage('empty', [], 'label') ).to.be.undefined it 'should return msg on non empty with name', -> fn = Validate.toMessage('empty', 'test', 'label') expect( fn ).to.equal '"label" must be empty' it 'should return generic msg on non empty without name', -> fn = Validate.toMessage('empty', 'test') expect( fn ).to.equal 'Value must be empty' describe 'Throw', -> it 'should validate empty', -> expect( Validate.andThrow('empty', [], 'label') ).to.be.true it 'should throw on non emtpy with name', -> fn = -> Validate.andThrow('empty', 'test', 'label') expect( fn ).to.throw ValidationError, '"label" must be empty' it 'should throw on non empty without name', -> fn = -> Validate.andThrow('empty', 'test') expect( fn ).to.throw ValidationError, 'Value must be empty' describe 'notEmpty', -> describe 'Boolean', -> it 'should validate empty string', -> expect( Validate.as('notEmpty', '', 'label') ).to.be.false it 'should validate empty array', -> expect( Validate.as('notEmpty', [], 'label') ).to.be.false it 'should validate empty object', -> expect( Validate.as('notEmpty', {}, 'label') ).to.be.false it 'should validate empty(?) number', -> expect( Validate.as('notEmpty', 7, 'label') ).to.be.false it 'should validate a non empty string', -> expect( Validate.as('notEmpty', 'a', 'label') ).to.be.true describe 'Message', -> it 'should validate not empty object', -> expect( Validate.toMessage('notEmpty', {a:1}, 'label') ).to.be.undefined it 'should return msg on non empty with name', -> fn = Validate.toMessage('notEmpty', '', 'label') expect( fn ).to.equal '"label" must not be empty' it 'should return generic msg on non empty without name', -> fn = Validate.toMessage('notEmpty', []) expect( fn ).to.equal 'Value must not be empty' describe 'Throw', -> it 'should validate non empty', -> expect( Validate.andThrow('notEmpty', 'iamnotempty', 'label') ).to.be.true it 'should throw on emtpy with name', -> fn = -> Validate.andThrow('notEmpty', {}, 'label') expect( fn ).to.throw ValidationError, '"label" must not be empty' it 'should throw on empty without name', -> fn = -> Validate.andThrow('notEmpty', []) expect( fn ).to.throw ValidationError, 'Value must not be empty' describe 'Undefined', -> type_str = 'undefined' name_str = 'somevar' describe 'Boolean', -> it 'should validate undefined', -> expect( Validate.as('undefined', undefined, name_str) ).to.be.true it 'should not validate a defined value', -> expect( Validate.as('undefined', 5, name_str) ).to.be.false describe 'Message', -> it 'should validate an undefined variable', -> expect( Validate.toMessage('undefined', undefined, name_str) ).to.be.undefined it 'should return msg on defined variable with name', -> fn = Validate.toMessage('undefined', [], name_str) expect( fn ).to.equal '"somevar" must be undefined' it 'should return generic msg on non string without name', -> fn = Validate.toMessage('undefined', true) expect( fn ).to.equal 'Value must be undefined' describe 'Throw', -> it 'should validate an undefined variable', -> expect( Validate.andThrow('undefined', undefined, name_str) ).to.be.true it 'should throw on defined variable with name', -> fn = -> Validate.andThrow('undefined', 5, name_str) expect( fn ).to.throw ValidationError, '"somevar" must be undefined' it 'should throw on defined variable without name', -> fn = -> Validate.andThrow('undefined', {}) expect( fn ).to.throw ValidationError, 'Value must be undefined' describe 'between', -> it 'should between', -> expect( Validate.a('between',3,4,5) ).to.be.false expect( Validate.a('between',4,4,5) ).to.be.false expect( Validate.a('between',5,4,5) ).to.be.false expect( Validate.a('between',5,4,6) ).to.be.true describe 'range', -> it 'should range', -> expect( Validate.a('range',3,4,5) ).to.be.false expect( Validate.a('range',4,4,5) ).to.be.true expect( Validate.a('range',5,4,5) ).to.be.true expect( Validate.a('range',5,4,6) ).to.be.true describe 'match', -> it 'should match', -> expect( Validate.a('match','string',/string/) ).to.be.true expect( Validate.a('match','5',/5/) ).to.be.true # ## Instance describe 'Instance', -> describe 'creation', -> it 'should create an instance', -> expect( new Validate() ).to.be.an.instanceOf Validate describe 'properties', -> validate = null beforeEach -> validate = new Validate() it 'should default throw to true', -> expect( validate.throw ).to.be.true it 'should default error mode to false', -> expect( validate.error ).to.be.false it 'should default message mode to false', -> expect( validate.message ).to.be.false it 'should default results mode to false', -> expect( validate.result ).to.be.false it 'should default `mode` to throw', -> expect( validate.mode ).to.equal 'throw' it 'should get errors', -> expect( validate.errors ).to.eql [] it 'should fail to set errors', -> fn = -> validate.errors = ['test'] expect( fn ).to.throw Error, /errors should not be set/ describe 'add', -> validate = null before -> validate = new Validate() it 'should add a test to validate', -> expect( validate.add('type','value','string','wakka') ).to.be.ok it 'should have a test in the array', -> expect( validate._tests.length ).to.equal 1 describe 'run', -> validate = null before -> validate = new Validate() validate.add('string','value','wakka') it 'should run the tests', -> expect( validate.run() ).to.be.ok it 'should run the errors', -> expect( validate.errors ).to.eql [] describe 'throw mode simples', -> validate = null before -> validate = new Validate() validate.add('string', 5, 'wakka') it 'should run the tests', -> fn = -> validate.run() expect( fn ).to.throw ValidationError it 'should run the errors', -> expect( validate.errors ).to.eql [] describe 'throw mode simples with throw option', -> validate = null before -> validate = new Validate({ throw: true }) validate.add('string', 5, 'wakka') it 'should run the tests', -> fn = -> validate.run() expect( fn ).to.throw ValidationError it 'should run the errors', -> expect( validate.errors ).to.eql [] describe 'messages mode simples', -> validate = null before -> validate = new Validate({ messages: true }) validate.add('string', 5, 'wakka') it 'should run the tests', -> expect( validate.run() ).to.be.ok it 'should run the errors', -> expect( validate.errors.length ).to.eql 1 expect( validate.errors[0] ).to.match /wakka/ describe 'errors mode extended', -> validate = null errors = null before -> validate = new Validate({ errors: true }) .add('length', 'sa', 1, 256, 'dlen') .add('string', 5, 'dtype') .add('alphaNumericDashUnderscore', 'a!b', 'dstr') it 'should run the tests', -> expect( validate.run() ).to.be.ok it 'should contain errors after run', -> errors = validate.errors expect( errors ).to.be.an 'array' it 'should have a validation error for dtype', -> expect( errors[0] ).to.be.an.instanceOf ValidationError expect( errors[0].message ).to.equal '"dtype" must be a string' it 'should have a second validation error for dstr', -> expect( errors[1] ).to.be.an.instanceOf ValidationError expect( errors[1].message ).to.equal '"dstr" must only contain letters, numbers, dash and underscore [ A-Z a-z 0-9 _ - ]' it 'has the right number of errors', -> expect( errors.length ).to.eql 2 describe 'messages', -> validate = null errors = null before -> validate = new Validate({messages: true}) .add('length', 'sa', 1, 256, 'dlen') .add('string', 5, 'dtype') .add('testing', true, true, 'andtest') .add('alphaNumericDashUnderscore', 'a!b', 'dstr') it 'should run the tests', -> expect( validate.run() ).to.be.ok it 'should run the errors', -> errors = validate.errors expect( errors ).to.be.an 'array' it 'has a validation error', -> expect( errors[0] ).to.equal '"dtype" must be a string' it 'has a validation error', -> expect( errors[1] ).to.equal '"dstr" must only contain letters, numbers, dash and underscore [ A-Z a-z 0-9 _ - ]' it 'has the right number of errors', -> expect( errors.length ).to.eql 2 describe 'results', -> validate = null errors = null before -> validate = new Validate({results: true}) .add('length', 'sa', 1, 256, 'dlen') .add('string', 5, 'dtype') .add('alphaNumericDashUnderscore', 'a!b', 'dstr') it 'should run the tests', -> expect( validate.run() ).to.be.ok it 'should run the errors', -> errors = validate.errors expect( errors ).to.be.an 'array' it 'has a validation error', -> expect( errors[0] ).to.be.an 'array' .and.to.contain 'dtype' it 'has a validation error', -> expect( errors[1] ).to.be.an 'array' .and.to.contain 'dstr' it 'has the right number of errors', -> expect( errors.length ).to.eql 2
169510
Validate = require '../lib/validate' ValidationError = Validate.ValidationError describe 'Unit::Validate', -> describe 'Class', -> describe 'Manage Tests', -> it 'should get a test', -> expect( Validate.getTest('testing') ).to.be.ok it 'should throw on a missing test', -> fn = -> Validate.getTest('testingno') expect( fn ).to.throw Error, /No test named "testingno" available/ it 'should add a new test', -> expect( Validate.addTest('testingtwo', { test: (val)=> val }) ).to.be.ok it 'should run the new test', -> expect( Validate.a('testingtwo', true) ).to.be.true expect( Validate.a('testingtwo', false) ).to.be.false it 'should fail to add the same test', -> fn = -> Validate.addTest('testingtwo', { test: (val)=> val }) expect( fn ).to.be.throw Error, /Test label "testingtwo" already exists/ describe 'Dynamic Tests', -> it 'a string "test" alpha true', -> expect( Validate.string('alpha', 'test') ).to.be.true it 'string "test" alpha true', -> expect( Validate.string('alpha', 'test') ).to.be.true it 'string "test9" alpha true', -> expect( Validate.string('alpha', 'test9c') ).to.be.false it 'a number 3 range 1,5 true', -> expect( Validate.number('range', 3, 1,5) ).to.be.true it 'a number 1 range 3,5 false', -> expect( Validate.number('range', 1, 3,5) ).to.be.false it 'number 1 range 3,5 false', -> expect( Validate.a('range', 1, 3,5) ).to.be.false it 'number 1 between 3,5 false', -> expect( Validate.number('between', 1, 3,5) ).to.be.false it 'number 1 between 1,5 false', -> expect( Validate.a('between', 1, 1,5) ).to.be.false it 'number 2 between 1,5 true', -> expect( Validate.number('between', 2, 1,5) ).to.be.true it 'number 1 between 2,5 true', -> expect( Validate.number('between', 1, 2, 5) ).to.be.false it 'number group throws on missing', -> fn = -> Validate.number('match', 1, 2, 5) expect( fn ).to.throw Error it 'throws number 1 between 2,5 true', -> fn = -> Validate.andThrow('between', 1, 2, 5) expect( fn ).to.throw ValidationError, /Value must be between 2 and 5/ it 'test types buffer via language', -> expect( Validate.language('buffer', new Buffer('')) ).to.be.true it 'test types buffer', -> expect( Validate.a('buffer', new Buffer('')) ).to.be.true it 'test types date', -> expect( Validate.a('date', new Date()) ).to.be.true it 'test types element', -> class Element nodeType: 1 expect( Validate.an('element', new Element()) ).to.be.true it 'test types error', -> expect( Validate.an('error', new Error()) ).to.be.true it 'test types finite', -> expect( Validate.a('finite', 3) ).to.be.true it 'test types function', -> expect( Validate.a('function', new Function()) ).to.be.true it 'test types Map', -> expect( Validate.a('map', new Map()) ).to.be.true it 'test types Nan', -> expect( Validate.a('nan', NaN) ).to.be.true it 'test types number', -> expect( Validate.a('number', 3) ).to.be.true it 'test types object', -> expect( Validate.a('object', {}) ).to.be.true it 'test types plainobject', -> expect( Validate.a('plainobject', {}) ).to.be.true it 'test types regexp', -> expect( Validate.a('regexp', /\w/) ).to.be.true it 'test types safeinteger', -> expect( Validate.a('safeinteger', 5) ).to.be.true it 'test types string', -> expect( Validate.a('string', '') ).to.be.true it 'test types symbol', -> expect( Validate.a('symbol', Symbol.iterator) ).to.be.true it 'test types typedarray', -> expect( Validate.a('typedarray', new Uint8Array) ).to.be.true it 'test types weakmap', -> expect( Validate.a('weakmap', new WeakMap()) ).to.be.true it 'test types weakset', -> expect( Validate.a('weakset', new WeakSet()) ).to.be.true it 'test types nil', -> expect( Validate.a('nil', undefined ) ).to.be.true it 'test types notNil', -> expect( Validate.a('notNil', 5 ) ).to.be.true # Types moved into new test world describe 'Type Tests', -> describe 'Array', -> type_str = 'array' name_str = 'wakka' describe 'Boolean', -> it 'should validate an array', -> expect( Validate.as('array', [], name_str) ).to.be.true it 'should not validate a non array', -> expect( Validate.as('array', 'a', name_str) ).to.be.false describe 'Error', -> it 'should validate an array', -> expect( Validate.toMessage('array', [], name_str) ).to.be.undefined it 'should return msg on non array with name', -> fn = Validate.toMessage('array', '', name_str) expect( fn ).to.equal '"wakka" must be an array' it 'should return generic msg on non array without name', -> fn = Validate.toMessage('array', '') expect( fn ).to.equal 'Value must be an array' describe 'Throw', -> it 'should validate an array', -> expect( Validate.andThrow('array', [], name_str) ).to.be.true it 'should throw on non array with name', -> fn = -> Validate.andThrow('array', '', name_str) expect( fn ).to.throw ValidationError, '"wakka" must be an array' it 'should throw on non array without name', -> fn = -> Validate.andThrow('array', '') expect( fn ).to.throw ValidationError, 'Value must be an array' describe 'Boolean', -> type_str = 'boolean' name_str = '<NAME>' describe 'Boolean', -> it 'should validate an boolean', -> expect( Validate.as('boolean', true, name_str) ).to.be.true it 'should not validate a non boolean', -> expect( Validate.as('boolean', 'a', name_str) ).to.be.false describe 'Message', -> it 'should validate an boolean', -> expect( Validate.toMessage('boolean', false, name_str) ).to.be.undefined it 'should return msg on non boolean with name', -> fn = Validate.toMessage('boolean', '', name_str) expect( fn ).to.equal '"michale" must be a boolean' it 'should return generic msg on non boolean without name', -> fn = Validate.toMessage('boolean', '') expect( fn ).to.equal 'Value must be a boolean' describe 'Throw', -> it 'should validate an boolean', -> expect( Validate.andThrow('boolean', true, name_str) ).to.be.true it 'should throw on non boolean with name', -> fn = -> Validate.andThrow('boolean', '', name_str) expect( fn ).to.throw ValidationError, '"michale" must be a boolean' it 'should throw on non boolean without name', -> fn = -> Validate.andThrow('boolean', '') expect( fn ).to.throw ValidationError, 'Value must be a boolean' describe 'Integer', -> type_str = 'integer' name_str = 'the_int' describe 'Boolean', -> it 'should validate an integer', -> expect( Validate.as('integer', 5, name_str) ).to.be.true it 'should not validate a non integer', -> expect( Validate.as('integer', 5.5, name_str) ).to.be.false it 'should not validate a non integer', -> expect( Validate.as('integer', 'a', name_str) ).to.be.false describe 'Message', -> it 'should validate an integer', -> expect( Validate.toMessage('integer', 7, name_str) ).to.be.undefined it 'should return msg on non integer with name', -> fn = Validate.toMessage('integer', '', name_str) expect( fn ).to.equal '"the_int" must be an integer' it 'should return generic msg on non integer without name', -> fn = Validate.toMessage('integer', '') expect( fn ).to.equal 'Value must be an integer' describe 'Throw', -> it 'should validate an integer', -> expect( Validate.andThrow('integer', 6, name_str) ).to.be.true it 'should throw on non integer with name', -> fn = -> Validate.andThrow('integer', '', name_str) expect( fn ).to.throw ValidationError, '"the_int" must be an integer' it 'should throw on non integer without name', -> fn = -> Validate.andThrow('integer', '') expect( fn ).to.throw ValidationError, 'Value must be an integer' describe 'String', -> type_str = 'string' name_str = 'description' describe 'Boolean', -> it 'should validate an string', -> expect( Validate.as(type_str, 'test', name_str) ).to.be.true it 'should not validate a non string', -> expect( Validate.as(type_str, 5, name_str) ).to.be.false describe 'Message', -> it 'should validate an string', -> expect( Validate.toMessage(type_str, 'test', name_str) ).to.be.undefined it 'should return msg on non string with name', -> fn = Validate.toMessage(type_str, [], name_str) expect( fn ).to.equal '"description" must be a string' it 'should return generic msg on non string without name', -> fn = Validate.toMessage(type_str, true) expect( fn ).to.equal 'Value must be a string' describe 'Throw', -> it 'should validate an string', -> expect( Validate.andThrow('string', 'test', name_str) ).to.be.true it 'should throw on non string with name', -> fn = -> Validate.andThrow('string', 5, name_str) expect( fn ).to.throw ValidationError, '"description" must be a string' it 'should throw on non string without name', -> fn = -> Validate.andThrow('string', {}) expect( fn ).to.throw ValidationError, 'Value must be a string' describe 'Length', -> it 'should return true for the length of string', -> expect( Validate.a('length', 'a', 1, 256, 'thestring') ).to.be.true it 'should return true for the length of string', -> expect( Validate.a('length', 'test', 4, 4, 'thestring') ).to.be.true it 'should return true for above the length of string', -> expect( Validate.a('length', 'test', 3, 5, 'thestring') ).to.be.true it 'should return false for below the length of string', -> expect( Validate.a('length', 'test', 3, 3, 'thestring') ).to.be.false it 'should return false for above the length of string', -> expect( Validate.a('length', 'test', 5, 5, 'thestring') ).to.be.false it 'should return true for only a min', -> expect( Validate.a('length', 'test',4) ).to.be.true it 'should return false for only a min above', -> expect( Validate.a('length', 'test',5) ).to.be.false it 'should return false for only a min below', -> expect( Validate.a('length', 'test',3) ).to.be.false it 'should return error message', -> msg = Validate.toMessage('length', 'test', 1, 5,'thestring') expect( msg ).to.be.undefined it 'should return error message', -> msg = Validate.toMessage('length', 'test', 5, 5,'thestring') expect( msg ).to.be.equal '"thestring" has length 4. Must be 5' it 'should return error message', -> msg = Validate.toMessage('length', 'tes', 4, 5, 'thestring') expect( msg ).to.be.equal '"thestring" has length 3. Must be 4 to 5' it 'should return error', -> res = Validate.toError('length', 'test', 1, 5,'thestring') expect( res ).to.be.undefined it 'should return error', -> err = Validate.toError('length', 'test', 5, 5,'thestring') expect( err ).to.be.instanceOf(ValidationError) expect( err.message ).to.equal '"thestring" has length 4. Must be 5' it 'should throw error', -> fn = -> Validate.andThrow('length', 'test', 1, 5,'thestring') expect( fn ).to.not.throw it 'should throw error', -> fn = -> Validate.andThrow('length', '3es', 4, 5,'thestring') expect( fn ).to.throw ValidationError, '"thestring" has length 3. Must be 4 to 5' describe 'Alpha', -> name_str = "thestring" name_str_msg = "\"#{name_str}\" " error_msg = "must only contain letters [ A-Z a-z ]" it 'should return true alpha', -> expect( Validate.string('alpha', 'ab', 'thestring') ).to.be.true it 'should return true alpha', -> expect( Validate.string('alpha', '59!#$%', 'thestring') ).to.be.false it 'should return true alpha', -> fn = -> Validate.string('integer', '59!#$%', 'thestring') expect( fn ).to.throw Error it 'should return error message', -> msg = Validate.toMessage('alpha', 'ab', 'thestring') expect( msg ).to.be.undefined it 'should return error message', -> msg = Validate.toMessage('alpha', 'a!b', 'thestring') expect( msg ).to.be.equal "#{name_str_msg}#{error_msg}" it 'should return error message', -> msg = Validate.toMessage('alpha', 'a!b') expect( msg ).to.be.equal "Value #{error_msg}" it 'should return error', -> res = Validate.toError('alpha', 'test', 'thestring') expect( res ).to.be.undefined it 'should return error', -> err = Validate.toError('alpha', 'test!', 'thestring') expect( err ).to.be.instanceOf(ValidationError) expect( err.message ).to.equal "#{name_str_msg}#{error_msg}" it 'should not throw error', -> expect( Validate.andThrow('alpha', 'test', 'thestring') ).to.be.true it 'should throw error', -> fn = -> Validate.andThrow('alpha', 'test!', 'thestring') expect( fn ).to.throw ValidationError, "#{name_str_msg}#{error_msg}" describe 'Numeric', -> name_str = "thestring" name_str_msg = "\"#{name_str}\" " error_msg = "must only contain numbers [ 0-9 ]" it 'should return true numeric', -> expect( Validate.string('numeric', '0939393', name_str) ).to.be.true it 'should return true numeric', -> expect( Validate.string('numeric', '59!#$%', name_str) ).to.be.false it 'should return error message', -> msg = Validate.toMessage('numeric', '2323', name_str) expect( msg ).to.be.undefined it 'should return error message', -> msg = Validate.toMessage('numeric', 'a!b', name_str) expect( msg ).to.be.equal "#{name_str_msg}#{error_msg}" it 'should return error message', -> msg = Validate.toMessage('numeric', 'a!b') expect( msg ).to.be.equal "Value #{error_msg}" it 'should return error', -> res = Validate.toError('numeric', '123453', name_str) expect( res ).to.be.undefined it 'should return error', -> err = Validate.toError('numeric', 'aaas', name_str) expect( err ).to.be.instanceOf(ValidationError) expect( err.message ).to.equal "#{name_str_msg}#{error_msg}" it 'should not throw error', -> expect( Validate.andThrow('numeric', '2', name_str) ).to.be.true it 'should throw error', -> fn = -> Validate.andThrow('numeric', 'test!', name_str) expect( fn ).to.throw ValidationError, "#{name_str_msg}#{error_msg}" describe 'alphaNumeric', -> name_str = "thestring" name_str_msg = "\"#{name_str}\" " error_msg = "must only contain letters and numbers [ A-Z a-z 0-9 ]" it 'should return true alpha numeric', -> expect( Validate.string('alphaNumeric', 'ab', name_str) ).to.be.true it 'should return true alpha numeric', -> expect( Validate.string('alphaNumeric', '59!#$%', name_str) ).to.be.false it 'should return error message', -> msg = Validate.toMessage('alphaNumeric', 'ab', name_str) expect( msg ).to.be.undefined it 'should return error message', -> msg = Validate.toMessage('alphaNumeric', 'a!b', name_str) expect( msg ).to.be.equal "#{name_str_msg}#{error_msg}" it 'should return error message', -> msg = Validate.toMessage('alphaNumeric', 'a!b') expect( msg ).to.be.equal "Value #{error_msg}" it 'should return error', -> res = Validate.toError('alphaNumeric', 'test', name_str) expect( res ).to.be.undefined it 'should return error', -> err = Validate.toError('alphaNumeric', 'test!', name_str) expect( err ).to.be.instanceOf(ValidationError) expect( err.message ).to.equal "#{name_str_msg}#{error_msg}" it 'should not throw error', -> expect( Validate.andThrow('alphaNumeric', 'test', name_str) ).to.be.true it 'should throw error', -> fn = -> Validate.andThrow('alphaNumeric', 'test!', name_str) expect( fn ).to.throw ValidationError, "#{name_str_msg}#{error_msg}" describe 'alphaNumericDashUnderscore', -> err_suffix = "must only contain letters, numbers, dash and underscore [ A-Z a-z 0-9 _ - ]" name_str = 'thestring' it 'should return true alpha numeric', -> expect( Validate.string('alphaNumericDashUnderscore', 'ab', name_str) ).to.be.true it 'should return true alpha numeric', -> expect( Validate.string('alphaNumericDashUnderscore', 'a!b', name_str) ).to.be.false it 'should return error message', -> msg = Validate.toMessage('alphaNumericDashUnderscore', 'ab', name_str) expect( msg ).to.be.undefined it 'should return error message', -> msg = Validate.toMessage('alphaNumericDashUnderscore', 'a!b', name_str) expect( msg ).to.be.equal "\"#{name_str}\" #{err_suffix}" it 'should return error', -> res = Validate.toError('alphaNumericDashUnderscore', 'test', name_str) expect( res ).to.be.undefined it 'should return error', -> err = Validate.toError('alphaNumericDashUnderscore', 'test!', name_str) expect( err ).to.be.instanceOf(ValidationError) expect( err.message ).to.equal "\"#{name_str}\" #{err_suffix}" it 'should throw error', -> fn = -> Validate.andThrow('alphaNumericDashUnderscore', 'test', name_str) expect( fn ).to.not.throw it 'should throw error', -> fn = -> Validate.andThrow('alphaNumericDashUnderscore', 'test!', name_str) expect( fn ).to.throw ValidationError, "\"#{name_str}\" #{err_suffix}" describe 'Defined', -> describe 'Boolean', -> it 'should validate a defined variable', -> expect( Validate.as('defined', [], 'somevar') ).to.be.true it 'should not validate a undefined value', -> expect( Validate.as('defined', undefined, 'somevar') ).to.be.false describe 'Message', -> it 'should not return a message for a defined variable', -> expect( Validate.toMessage('defined', 5, 'somevar') ).to.be.undefined it 'should return msg on undefined variable with name', -> fn = Validate.toMessage('defined', undefined, 'somevar') expect( fn ).to.equal '"somevar" must be defined' it 'should return generic msg on non string without name', -> fn = Validate.toMessage('defined', undefined) expect( fn ).to.equal 'Value must be defined' describe 'Throw', -> it 'should not throw on a defined variable', -> expect( Validate.andThrow('defined', 5, 'somevar') ).to.be.true it 'should throw on undefined variable with name', -> fn = -> Validate.andThrow('defined', undefined, 'somevar') expect( fn ).to.throw ValidationError, '"somevar" must be defined' it 'should throw on undefined variable without name', -> fn = -> Validate.andThrow('defined', undefined) expect( fn ).to.throw ValidationError, 'Value must be defined' describe 'Empty', -> describe 'Boolean', -> it 'should validate empty', -> expect( Validate.as('empty', '', 'label') ).to.be.true it 'should validate empty', -> expect( Validate.as('empty', [], 'label') ).to.be.true it 'should validate empty', -> expect( Validate.as('empty', {}, 'label') ).to.be.true it 'should validate empty', -> expect( Validate.as('empty', 7, 'label') ).to.be.true it 'should not validate a non empty', -> expect( Validate.as('empty', 'a', 'label') ).to.be.false describe 'Message', -> it 'should validate empty', -> expect( Validate.toMessage('empty', [], 'label') ).to.be.undefined it 'should return msg on non empty with name', -> fn = Validate.toMessage('empty', 'test', 'label') expect( fn ).to.equal '"label" must be empty' it 'should return generic msg on non empty without name', -> fn = Validate.toMessage('empty', 'test') expect( fn ).to.equal 'Value must be empty' describe 'Throw', -> it 'should validate empty', -> expect( Validate.andThrow('empty', [], 'label') ).to.be.true it 'should throw on non emtpy with name', -> fn = -> Validate.andThrow('empty', 'test', 'label') expect( fn ).to.throw ValidationError, '"label" must be empty' it 'should throw on non empty without name', -> fn = -> Validate.andThrow('empty', 'test') expect( fn ).to.throw ValidationError, 'Value must be empty' describe 'notEmpty', -> describe 'Boolean', -> it 'should validate empty string', -> expect( Validate.as('notEmpty', '', 'label') ).to.be.false it 'should validate empty array', -> expect( Validate.as('notEmpty', [], 'label') ).to.be.false it 'should validate empty object', -> expect( Validate.as('notEmpty', {}, 'label') ).to.be.false it 'should validate empty(?) number', -> expect( Validate.as('notEmpty', 7, 'label') ).to.be.false it 'should validate a non empty string', -> expect( Validate.as('notEmpty', 'a', 'label') ).to.be.true describe 'Message', -> it 'should validate not empty object', -> expect( Validate.toMessage('notEmpty', {a:1}, 'label') ).to.be.undefined it 'should return msg on non empty with name', -> fn = Validate.toMessage('notEmpty', '', 'label') expect( fn ).to.equal '"label" must not be empty' it 'should return generic msg on non empty without name', -> fn = Validate.toMessage('notEmpty', []) expect( fn ).to.equal 'Value must not be empty' describe 'Throw', -> it 'should validate non empty', -> expect( Validate.andThrow('notEmpty', 'iamnotempty', 'label') ).to.be.true it 'should throw on emtpy with name', -> fn = -> Validate.andThrow('notEmpty', {}, 'label') expect( fn ).to.throw ValidationError, '"label" must not be empty' it 'should throw on empty without name', -> fn = -> Validate.andThrow('notEmpty', []) expect( fn ).to.throw ValidationError, 'Value must not be empty' describe 'Undefined', -> type_str = 'undefined' name_str = '<NAME>var' describe 'Boolean', -> it 'should validate undefined', -> expect( Validate.as('undefined', undefined, name_str) ).to.be.true it 'should not validate a defined value', -> expect( Validate.as('undefined', 5, name_str) ).to.be.false describe 'Message', -> it 'should validate an undefined variable', -> expect( Validate.toMessage('undefined', undefined, name_str) ).to.be.undefined it 'should return msg on defined variable with name', -> fn = Validate.toMessage('undefined', [], name_str) expect( fn ).to.equal '"somevar" must be undefined' it 'should return generic msg on non string without name', -> fn = Validate.toMessage('undefined', true) expect( fn ).to.equal 'Value must be undefined' describe 'Throw', -> it 'should validate an undefined variable', -> expect( Validate.andThrow('undefined', undefined, name_str) ).to.be.true it 'should throw on defined variable with name', -> fn = -> Validate.andThrow('undefined', 5, name_str) expect( fn ).to.throw ValidationError, '"somevar" must be undefined' it 'should throw on defined variable without name', -> fn = -> Validate.andThrow('undefined', {}) expect( fn ).to.throw ValidationError, 'Value must be undefined' describe 'between', -> it 'should between', -> expect( Validate.a('between',3,4,5) ).to.be.false expect( Validate.a('between',4,4,5) ).to.be.false expect( Validate.a('between',5,4,5) ).to.be.false expect( Validate.a('between',5,4,6) ).to.be.true describe 'range', -> it 'should range', -> expect( Validate.a('range',3,4,5) ).to.be.false expect( Validate.a('range',4,4,5) ).to.be.true expect( Validate.a('range',5,4,5) ).to.be.true expect( Validate.a('range',5,4,6) ).to.be.true describe 'match', -> it 'should match', -> expect( Validate.a('match','string',/string/) ).to.be.true expect( Validate.a('match','5',/5/) ).to.be.true # ## Instance describe 'Instance', -> describe 'creation', -> it 'should create an instance', -> expect( new Validate() ).to.be.an.instanceOf Validate describe 'properties', -> validate = null beforeEach -> validate = new Validate() it 'should default throw to true', -> expect( validate.throw ).to.be.true it 'should default error mode to false', -> expect( validate.error ).to.be.false it 'should default message mode to false', -> expect( validate.message ).to.be.false it 'should default results mode to false', -> expect( validate.result ).to.be.false it 'should default `mode` to throw', -> expect( validate.mode ).to.equal 'throw' it 'should get errors', -> expect( validate.errors ).to.eql [] it 'should fail to set errors', -> fn = -> validate.errors = ['test'] expect( fn ).to.throw Error, /errors should not be set/ describe 'add', -> validate = null before -> validate = new Validate() it 'should add a test to validate', -> expect( validate.add('type','value','string','wakka') ).to.be.ok it 'should have a test in the array', -> expect( validate._tests.length ).to.equal 1 describe 'run', -> validate = null before -> validate = new Validate() validate.add('string','value','wakka') it 'should run the tests', -> expect( validate.run() ).to.be.ok it 'should run the errors', -> expect( validate.errors ).to.eql [] describe 'throw mode simples', -> validate = null before -> validate = new Validate() validate.add('string', 5, 'wakka') it 'should run the tests', -> fn = -> validate.run() expect( fn ).to.throw ValidationError it 'should run the errors', -> expect( validate.errors ).to.eql [] describe 'throw mode simples with throw option', -> validate = null before -> validate = new Validate({ throw: true }) validate.add('string', 5, 'wakka') it 'should run the tests', -> fn = -> validate.run() expect( fn ).to.throw ValidationError it 'should run the errors', -> expect( validate.errors ).to.eql [] describe 'messages mode simples', -> validate = null before -> validate = new Validate({ messages: true }) validate.add('string', 5, 'wakka') it 'should run the tests', -> expect( validate.run() ).to.be.ok it 'should run the errors', -> expect( validate.errors.length ).to.eql 1 expect( validate.errors[0] ).to.match /wakka/ describe 'errors mode extended', -> validate = null errors = null before -> validate = new Validate({ errors: true }) .add('length', 'sa', 1, 256, 'dlen') .add('string', 5, 'dtype') .add('alphaNumericDashUnderscore', 'a!b', 'dstr') it 'should run the tests', -> expect( validate.run() ).to.be.ok it 'should contain errors after run', -> errors = validate.errors expect( errors ).to.be.an 'array' it 'should have a validation error for dtype', -> expect( errors[0] ).to.be.an.instanceOf ValidationError expect( errors[0].message ).to.equal '"dtype" must be a string' it 'should have a second validation error for dstr', -> expect( errors[1] ).to.be.an.instanceOf ValidationError expect( errors[1].message ).to.equal '"dstr" must only contain letters, numbers, dash and underscore [ A-Z a-z 0-9 _ - ]' it 'has the right number of errors', -> expect( errors.length ).to.eql 2 describe 'messages', -> validate = null errors = null before -> validate = new Validate({messages: true}) .add('length', 'sa', 1, 256, 'dlen') .add('string', 5, 'dtype') .add('testing', true, true, 'andtest') .add('alphaNumericDashUnderscore', 'a!b', 'dstr') it 'should run the tests', -> expect( validate.run() ).to.be.ok it 'should run the errors', -> errors = validate.errors expect( errors ).to.be.an 'array' it 'has a validation error', -> expect( errors[0] ).to.equal '"dtype" must be a string' it 'has a validation error', -> expect( errors[1] ).to.equal '"dstr" must only contain letters, numbers, dash and underscore [ A-Z a-z 0-9 _ - ]' it 'has the right number of errors', -> expect( errors.length ).to.eql 2 describe 'results', -> validate = null errors = null before -> validate = new Validate({results: true}) .add('length', 'sa', 1, 256, 'dlen') .add('string', 5, 'dtype') .add('alphaNumericDashUnderscore', 'a!b', 'dstr') it 'should run the tests', -> expect( validate.run() ).to.be.ok it 'should run the errors', -> errors = validate.errors expect( errors ).to.be.an 'array' it 'has a validation error', -> expect( errors[0] ).to.be.an 'array' .and.to.contain 'dtype' it 'has a validation error', -> expect( errors[1] ).to.be.an 'array' .and.to.contain 'dstr' it 'has the right number of errors', -> expect( errors.length ).to.eql 2
true
Validate = require '../lib/validate' ValidationError = Validate.ValidationError describe 'Unit::Validate', -> describe 'Class', -> describe 'Manage Tests', -> it 'should get a test', -> expect( Validate.getTest('testing') ).to.be.ok it 'should throw on a missing test', -> fn = -> Validate.getTest('testingno') expect( fn ).to.throw Error, /No test named "testingno" available/ it 'should add a new test', -> expect( Validate.addTest('testingtwo', { test: (val)=> val }) ).to.be.ok it 'should run the new test', -> expect( Validate.a('testingtwo', true) ).to.be.true expect( Validate.a('testingtwo', false) ).to.be.false it 'should fail to add the same test', -> fn = -> Validate.addTest('testingtwo', { test: (val)=> val }) expect( fn ).to.be.throw Error, /Test label "testingtwo" already exists/ describe 'Dynamic Tests', -> it 'a string "test" alpha true', -> expect( Validate.string('alpha', 'test') ).to.be.true it 'string "test" alpha true', -> expect( Validate.string('alpha', 'test') ).to.be.true it 'string "test9" alpha true', -> expect( Validate.string('alpha', 'test9c') ).to.be.false it 'a number 3 range 1,5 true', -> expect( Validate.number('range', 3, 1,5) ).to.be.true it 'a number 1 range 3,5 false', -> expect( Validate.number('range', 1, 3,5) ).to.be.false it 'number 1 range 3,5 false', -> expect( Validate.a('range', 1, 3,5) ).to.be.false it 'number 1 between 3,5 false', -> expect( Validate.number('between', 1, 3,5) ).to.be.false it 'number 1 between 1,5 false', -> expect( Validate.a('between', 1, 1,5) ).to.be.false it 'number 2 between 1,5 true', -> expect( Validate.number('between', 2, 1,5) ).to.be.true it 'number 1 between 2,5 true', -> expect( Validate.number('between', 1, 2, 5) ).to.be.false it 'number group throws on missing', -> fn = -> Validate.number('match', 1, 2, 5) expect( fn ).to.throw Error it 'throws number 1 between 2,5 true', -> fn = -> Validate.andThrow('between', 1, 2, 5) expect( fn ).to.throw ValidationError, /Value must be between 2 and 5/ it 'test types buffer via language', -> expect( Validate.language('buffer', new Buffer('')) ).to.be.true it 'test types buffer', -> expect( Validate.a('buffer', new Buffer('')) ).to.be.true it 'test types date', -> expect( Validate.a('date', new Date()) ).to.be.true it 'test types element', -> class Element nodeType: 1 expect( Validate.an('element', new Element()) ).to.be.true it 'test types error', -> expect( Validate.an('error', new Error()) ).to.be.true it 'test types finite', -> expect( Validate.a('finite', 3) ).to.be.true it 'test types function', -> expect( Validate.a('function', new Function()) ).to.be.true it 'test types Map', -> expect( Validate.a('map', new Map()) ).to.be.true it 'test types Nan', -> expect( Validate.a('nan', NaN) ).to.be.true it 'test types number', -> expect( Validate.a('number', 3) ).to.be.true it 'test types object', -> expect( Validate.a('object', {}) ).to.be.true it 'test types plainobject', -> expect( Validate.a('plainobject', {}) ).to.be.true it 'test types regexp', -> expect( Validate.a('regexp', /\w/) ).to.be.true it 'test types safeinteger', -> expect( Validate.a('safeinteger', 5) ).to.be.true it 'test types string', -> expect( Validate.a('string', '') ).to.be.true it 'test types symbol', -> expect( Validate.a('symbol', Symbol.iterator) ).to.be.true it 'test types typedarray', -> expect( Validate.a('typedarray', new Uint8Array) ).to.be.true it 'test types weakmap', -> expect( Validate.a('weakmap', new WeakMap()) ).to.be.true it 'test types weakset', -> expect( Validate.a('weakset', new WeakSet()) ).to.be.true it 'test types nil', -> expect( Validate.a('nil', undefined ) ).to.be.true it 'test types notNil', -> expect( Validate.a('notNil', 5 ) ).to.be.true # Types moved into new test world describe 'Type Tests', -> describe 'Array', -> type_str = 'array' name_str = 'wakka' describe 'Boolean', -> it 'should validate an array', -> expect( Validate.as('array', [], name_str) ).to.be.true it 'should not validate a non array', -> expect( Validate.as('array', 'a', name_str) ).to.be.false describe 'Error', -> it 'should validate an array', -> expect( Validate.toMessage('array', [], name_str) ).to.be.undefined it 'should return msg on non array with name', -> fn = Validate.toMessage('array', '', name_str) expect( fn ).to.equal '"wakka" must be an array' it 'should return generic msg on non array without name', -> fn = Validate.toMessage('array', '') expect( fn ).to.equal 'Value must be an array' describe 'Throw', -> it 'should validate an array', -> expect( Validate.andThrow('array', [], name_str) ).to.be.true it 'should throw on non array with name', -> fn = -> Validate.andThrow('array', '', name_str) expect( fn ).to.throw ValidationError, '"wakka" must be an array' it 'should throw on non array without name', -> fn = -> Validate.andThrow('array', '') expect( fn ).to.throw ValidationError, 'Value must be an array' describe 'Boolean', -> type_str = 'boolean' name_str = 'PI:NAME:<NAME>END_PI' describe 'Boolean', -> it 'should validate an boolean', -> expect( Validate.as('boolean', true, name_str) ).to.be.true it 'should not validate a non boolean', -> expect( Validate.as('boolean', 'a', name_str) ).to.be.false describe 'Message', -> it 'should validate an boolean', -> expect( Validate.toMessage('boolean', false, name_str) ).to.be.undefined it 'should return msg on non boolean with name', -> fn = Validate.toMessage('boolean', '', name_str) expect( fn ).to.equal '"michale" must be a boolean' it 'should return generic msg on non boolean without name', -> fn = Validate.toMessage('boolean', '') expect( fn ).to.equal 'Value must be a boolean' describe 'Throw', -> it 'should validate an boolean', -> expect( Validate.andThrow('boolean', true, name_str) ).to.be.true it 'should throw on non boolean with name', -> fn = -> Validate.andThrow('boolean', '', name_str) expect( fn ).to.throw ValidationError, '"michale" must be a boolean' it 'should throw on non boolean without name', -> fn = -> Validate.andThrow('boolean', '') expect( fn ).to.throw ValidationError, 'Value must be a boolean' describe 'Integer', -> type_str = 'integer' name_str = 'the_int' describe 'Boolean', -> it 'should validate an integer', -> expect( Validate.as('integer', 5, name_str) ).to.be.true it 'should not validate a non integer', -> expect( Validate.as('integer', 5.5, name_str) ).to.be.false it 'should not validate a non integer', -> expect( Validate.as('integer', 'a', name_str) ).to.be.false describe 'Message', -> it 'should validate an integer', -> expect( Validate.toMessage('integer', 7, name_str) ).to.be.undefined it 'should return msg on non integer with name', -> fn = Validate.toMessage('integer', '', name_str) expect( fn ).to.equal '"the_int" must be an integer' it 'should return generic msg on non integer without name', -> fn = Validate.toMessage('integer', '') expect( fn ).to.equal 'Value must be an integer' describe 'Throw', -> it 'should validate an integer', -> expect( Validate.andThrow('integer', 6, name_str) ).to.be.true it 'should throw on non integer with name', -> fn = -> Validate.andThrow('integer', '', name_str) expect( fn ).to.throw ValidationError, '"the_int" must be an integer' it 'should throw on non integer without name', -> fn = -> Validate.andThrow('integer', '') expect( fn ).to.throw ValidationError, 'Value must be an integer' describe 'String', -> type_str = 'string' name_str = 'description' describe 'Boolean', -> it 'should validate an string', -> expect( Validate.as(type_str, 'test', name_str) ).to.be.true it 'should not validate a non string', -> expect( Validate.as(type_str, 5, name_str) ).to.be.false describe 'Message', -> it 'should validate an string', -> expect( Validate.toMessage(type_str, 'test', name_str) ).to.be.undefined it 'should return msg on non string with name', -> fn = Validate.toMessage(type_str, [], name_str) expect( fn ).to.equal '"description" must be a string' it 'should return generic msg on non string without name', -> fn = Validate.toMessage(type_str, true) expect( fn ).to.equal 'Value must be a string' describe 'Throw', -> it 'should validate an string', -> expect( Validate.andThrow('string', 'test', name_str) ).to.be.true it 'should throw on non string with name', -> fn = -> Validate.andThrow('string', 5, name_str) expect( fn ).to.throw ValidationError, '"description" must be a string' it 'should throw on non string without name', -> fn = -> Validate.andThrow('string', {}) expect( fn ).to.throw ValidationError, 'Value must be a string' describe 'Length', -> it 'should return true for the length of string', -> expect( Validate.a('length', 'a', 1, 256, 'thestring') ).to.be.true it 'should return true for the length of string', -> expect( Validate.a('length', 'test', 4, 4, 'thestring') ).to.be.true it 'should return true for above the length of string', -> expect( Validate.a('length', 'test', 3, 5, 'thestring') ).to.be.true it 'should return false for below the length of string', -> expect( Validate.a('length', 'test', 3, 3, 'thestring') ).to.be.false it 'should return false for above the length of string', -> expect( Validate.a('length', 'test', 5, 5, 'thestring') ).to.be.false it 'should return true for only a min', -> expect( Validate.a('length', 'test',4) ).to.be.true it 'should return false for only a min above', -> expect( Validate.a('length', 'test',5) ).to.be.false it 'should return false for only a min below', -> expect( Validate.a('length', 'test',3) ).to.be.false it 'should return error message', -> msg = Validate.toMessage('length', 'test', 1, 5,'thestring') expect( msg ).to.be.undefined it 'should return error message', -> msg = Validate.toMessage('length', 'test', 5, 5,'thestring') expect( msg ).to.be.equal '"thestring" has length 4. Must be 5' it 'should return error message', -> msg = Validate.toMessage('length', 'tes', 4, 5, 'thestring') expect( msg ).to.be.equal '"thestring" has length 3. Must be 4 to 5' it 'should return error', -> res = Validate.toError('length', 'test', 1, 5,'thestring') expect( res ).to.be.undefined it 'should return error', -> err = Validate.toError('length', 'test', 5, 5,'thestring') expect( err ).to.be.instanceOf(ValidationError) expect( err.message ).to.equal '"thestring" has length 4. Must be 5' it 'should throw error', -> fn = -> Validate.andThrow('length', 'test', 1, 5,'thestring') expect( fn ).to.not.throw it 'should throw error', -> fn = -> Validate.andThrow('length', '3es', 4, 5,'thestring') expect( fn ).to.throw ValidationError, '"thestring" has length 3. Must be 4 to 5' describe 'Alpha', -> name_str = "thestring" name_str_msg = "\"#{name_str}\" " error_msg = "must only contain letters [ A-Z a-z ]" it 'should return true alpha', -> expect( Validate.string('alpha', 'ab', 'thestring') ).to.be.true it 'should return true alpha', -> expect( Validate.string('alpha', '59!#$%', 'thestring') ).to.be.false it 'should return true alpha', -> fn = -> Validate.string('integer', '59!#$%', 'thestring') expect( fn ).to.throw Error it 'should return error message', -> msg = Validate.toMessage('alpha', 'ab', 'thestring') expect( msg ).to.be.undefined it 'should return error message', -> msg = Validate.toMessage('alpha', 'a!b', 'thestring') expect( msg ).to.be.equal "#{name_str_msg}#{error_msg}" it 'should return error message', -> msg = Validate.toMessage('alpha', 'a!b') expect( msg ).to.be.equal "Value #{error_msg}" it 'should return error', -> res = Validate.toError('alpha', 'test', 'thestring') expect( res ).to.be.undefined it 'should return error', -> err = Validate.toError('alpha', 'test!', 'thestring') expect( err ).to.be.instanceOf(ValidationError) expect( err.message ).to.equal "#{name_str_msg}#{error_msg}" it 'should not throw error', -> expect( Validate.andThrow('alpha', 'test', 'thestring') ).to.be.true it 'should throw error', -> fn = -> Validate.andThrow('alpha', 'test!', 'thestring') expect( fn ).to.throw ValidationError, "#{name_str_msg}#{error_msg}" describe 'Numeric', -> name_str = "thestring" name_str_msg = "\"#{name_str}\" " error_msg = "must only contain numbers [ 0-9 ]" it 'should return true numeric', -> expect( Validate.string('numeric', '0939393', name_str) ).to.be.true it 'should return true numeric', -> expect( Validate.string('numeric', '59!#$%', name_str) ).to.be.false it 'should return error message', -> msg = Validate.toMessage('numeric', '2323', name_str) expect( msg ).to.be.undefined it 'should return error message', -> msg = Validate.toMessage('numeric', 'a!b', name_str) expect( msg ).to.be.equal "#{name_str_msg}#{error_msg}" it 'should return error message', -> msg = Validate.toMessage('numeric', 'a!b') expect( msg ).to.be.equal "Value #{error_msg}" it 'should return error', -> res = Validate.toError('numeric', '123453', name_str) expect( res ).to.be.undefined it 'should return error', -> err = Validate.toError('numeric', 'aaas', name_str) expect( err ).to.be.instanceOf(ValidationError) expect( err.message ).to.equal "#{name_str_msg}#{error_msg}" it 'should not throw error', -> expect( Validate.andThrow('numeric', '2', name_str) ).to.be.true it 'should throw error', -> fn = -> Validate.andThrow('numeric', 'test!', name_str) expect( fn ).to.throw ValidationError, "#{name_str_msg}#{error_msg}" describe 'alphaNumeric', -> name_str = "thestring" name_str_msg = "\"#{name_str}\" " error_msg = "must only contain letters and numbers [ A-Z a-z 0-9 ]" it 'should return true alpha numeric', -> expect( Validate.string('alphaNumeric', 'ab', name_str) ).to.be.true it 'should return true alpha numeric', -> expect( Validate.string('alphaNumeric', '59!#$%', name_str) ).to.be.false it 'should return error message', -> msg = Validate.toMessage('alphaNumeric', 'ab', name_str) expect( msg ).to.be.undefined it 'should return error message', -> msg = Validate.toMessage('alphaNumeric', 'a!b', name_str) expect( msg ).to.be.equal "#{name_str_msg}#{error_msg}" it 'should return error message', -> msg = Validate.toMessage('alphaNumeric', 'a!b') expect( msg ).to.be.equal "Value #{error_msg}" it 'should return error', -> res = Validate.toError('alphaNumeric', 'test', name_str) expect( res ).to.be.undefined it 'should return error', -> err = Validate.toError('alphaNumeric', 'test!', name_str) expect( err ).to.be.instanceOf(ValidationError) expect( err.message ).to.equal "#{name_str_msg}#{error_msg}" it 'should not throw error', -> expect( Validate.andThrow('alphaNumeric', 'test', name_str) ).to.be.true it 'should throw error', -> fn = -> Validate.andThrow('alphaNumeric', 'test!', name_str) expect( fn ).to.throw ValidationError, "#{name_str_msg}#{error_msg}" describe 'alphaNumericDashUnderscore', -> err_suffix = "must only contain letters, numbers, dash and underscore [ A-Z a-z 0-9 _ - ]" name_str = 'thestring' it 'should return true alpha numeric', -> expect( Validate.string('alphaNumericDashUnderscore', 'ab', name_str) ).to.be.true it 'should return true alpha numeric', -> expect( Validate.string('alphaNumericDashUnderscore', 'a!b', name_str) ).to.be.false it 'should return error message', -> msg = Validate.toMessage('alphaNumericDashUnderscore', 'ab', name_str) expect( msg ).to.be.undefined it 'should return error message', -> msg = Validate.toMessage('alphaNumericDashUnderscore', 'a!b', name_str) expect( msg ).to.be.equal "\"#{name_str}\" #{err_suffix}" it 'should return error', -> res = Validate.toError('alphaNumericDashUnderscore', 'test', name_str) expect( res ).to.be.undefined it 'should return error', -> err = Validate.toError('alphaNumericDashUnderscore', 'test!', name_str) expect( err ).to.be.instanceOf(ValidationError) expect( err.message ).to.equal "\"#{name_str}\" #{err_suffix}" it 'should throw error', -> fn = -> Validate.andThrow('alphaNumericDashUnderscore', 'test', name_str) expect( fn ).to.not.throw it 'should throw error', -> fn = -> Validate.andThrow('alphaNumericDashUnderscore', 'test!', name_str) expect( fn ).to.throw ValidationError, "\"#{name_str}\" #{err_suffix}" describe 'Defined', -> describe 'Boolean', -> it 'should validate a defined variable', -> expect( Validate.as('defined', [], 'somevar') ).to.be.true it 'should not validate a undefined value', -> expect( Validate.as('defined', undefined, 'somevar') ).to.be.false describe 'Message', -> it 'should not return a message for a defined variable', -> expect( Validate.toMessage('defined', 5, 'somevar') ).to.be.undefined it 'should return msg on undefined variable with name', -> fn = Validate.toMessage('defined', undefined, 'somevar') expect( fn ).to.equal '"somevar" must be defined' it 'should return generic msg on non string without name', -> fn = Validate.toMessage('defined', undefined) expect( fn ).to.equal 'Value must be defined' describe 'Throw', -> it 'should not throw on a defined variable', -> expect( Validate.andThrow('defined', 5, 'somevar') ).to.be.true it 'should throw on undefined variable with name', -> fn = -> Validate.andThrow('defined', undefined, 'somevar') expect( fn ).to.throw ValidationError, '"somevar" must be defined' it 'should throw on undefined variable without name', -> fn = -> Validate.andThrow('defined', undefined) expect( fn ).to.throw ValidationError, 'Value must be defined' describe 'Empty', -> describe 'Boolean', -> it 'should validate empty', -> expect( Validate.as('empty', '', 'label') ).to.be.true it 'should validate empty', -> expect( Validate.as('empty', [], 'label') ).to.be.true it 'should validate empty', -> expect( Validate.as('empty', {}, 'label') ).to.be.true it 'should validate empty', -> expect( Validate.as('empty', 7, 'label') ).to.be.true it 'should not validate a non empty', -> expect( Validate.as('empty', 'a', 'label') ).to.be.false describe 'Message', -> it 'should validate empty', -> expect( Validate.toMessage('empty', [], 'label') ).to.be.undefined it 'should return msg on non empty with name', -> fn = Validate.toMessage('empty', 'test', 'label') expect( fn ).to.equal '"label" must be empty' it 'should return generic msg on non empty without name', -> fn = Validate.toMessage('empty', 'test') expect( fn ).to.equal 'Value must be empty' describe 'Throw', -> it 'should validate empty', -> expect( Validate.andThrow('empty', [], 'label') ).to.be.true it 'should throw on non emtpy with name', -> fn = -> Validate.andThrow('empty', 'test', 'label') expect( fn ).to.throw ValidationError, '"label" must be empty' it 'should throw on non empty without name', -> fn = -> Validate.andThrow('empty', 'test') expect( fn ).to.throw ValidationError, 'Value must be empty' describe 'notEmpty', -> describe 'Boolean', -> it 'should validate empty string', -> expect( Validate.as('notEmpty', '', 'label') ).to.be.false it 'should validate empty array', -> expect( Validate.as('notEmpty', [], 'label') ).to.be.false it 'should validate empty object', -> expect( Validate.as('notEmpty', {}, 'label') ).to.be.false it 'should validate empty(?) number', -> expect( Validate.as('notEmpty', 7, 'label') ).to.be.false it 'should validate a non empty string', -> expect( Validate.as('notEmpty', 'a', 'label') ).to.be.true describe 'Message', -> it 'should validate not empty object', -> expect( Validate.toMessage('notEmpty', {a:1}, 'label') ).to.be.undefined it 'should return msg on non empty with name', -> fn = Validate.toMessage('notEmpty', '', 'label') expect( fn ).to.equal '"label" must not be empty' it 'should return generic msg on non empty without name', -> fn = Validate.toMessage('notEmpty', []) expect( fn ).to.equal 'Value must not be empty' describe 'Throw', -> it 'should validate non empty', -> expect( Validate.andThrow('notEmpty', 'iamnotempty', 'label') ).to.be.true it 'should throw on emtpy with name', -> fn = -> Validate.andThrow('notEmpty', {}, 'label') expect( fn ).to.throw ValidationError, '"label" must not be empty' it 'should throw on empty without name', -> fn = -> Validate.andThrow('notEmpty', []) expect( fn ).to.throw ValidationError, 'Value must not be empty' describe 'Undefined', -> type_str = 'undefined' name_str = 'PI:NAME:<NAME>END_PIvar' describe 'Boolean', -> it 'should validate undefined', -> expect( Validate.as('undefined', undefined, name_str) ).to.be.true it 'should not validate a defined value', -> expect( Validate.as('undefined', 5, name_str) ).to.be.false describe 'Message', -> it 'should validate an undefined variable', -> expect( Validate.toMessage('undefined', undefined, name_str) ).to.be.undefined it 'should return msg on defined variable with name', -> fn = Validate.toMessage('undefined', [], name_str) expect( fn ).to.equal '"somevar" must be undefined' it 'should return generic msg on non string without name', -> fn = Validate.toMessage('undefined', true) expect( fn ).to.equal 'Value must be undefined' describe 'Throw', -> it 'should validate an undefined variable', -> expect( Validate.andThrow('undefined', undefined, name_str) ).to.be.true it 'should throw on defined variable with name', -> fn = -> Validate.andThrow('undefined', 5, name_str) expect( fn ).to.throw ValidationError, '"somevar" must be undefined' it 'should throw on defined variable without name', -> fn = -> Validate.andThrow('undefined', {}) expect( fn ).to.throw ValidationError, 'Value must be undefined' describe 'between', -> it 'should between', -> expect( Validate.a('between',3,4,5) ).to.be.false expect( Validate.a('between',4,4,5) ).to.be.false expect( Validate.a('between',5,4,5) ).to.be.false expect( Validate.a('between',5,4,6) ).to.be.true describe 'range', -> it 'should range', -> expect( Validate.a('range',3,4,5) ).to.be.false expect( Validate.a('range',4,4,5) ).to.be.true expect( Validate.a('range',5,4,5) ).to.be.true expect( Validate.a('range',5,4,6) ).to.be.true describe 'match', -> it 'should match', -> expect( Validate.a('match','string',/string/) ).to.be.true expect( Validate.a('match','5',/5/) ).to.be.true # ## Instance describe 'Instance', -> describe 'creation', -> it 'should create an instance', -> expect( new Validate() ).to.be.an.instanceOf Validate describe 'properties', -> validate = null beforeEach -> validate = new Validate() it 'should default throw to true', -> expect( validate.throw ).to.be.true it 'should default error mode to false', -> expect( validate.error ).to.be.false it 'should default message mode to false', -> expect( validate.message ).to.be.false it 'should default results mode to false', -> expect( validate.result ).to.be.false it 'should default `mode` to throw', -> expect( validate.mode ).to.equal 'throw' it 'should get errors', -> expect( validate.errors ).to.eql [] it 'should fail to set errors', -> fn = -> validate.errors = ['test'] expect( fn ).to.throw Error, /errors should not be set/ describe 'add', -> validate = null before -> validate = new Validate() it 'should add a test to validate', -> expect( validate.add('type','value','string','wakka') ).to.be.ok it 'should have a test in the array', -> expect( validate._tests.length ).to.equal 1 describe 'run', -> validate = null before -> validate = new Validate() validate.add('string','value','wakka') it 'should run the tests', -> expect( validate.run() ).to.be.ok it 'should run the errors', -> expect( validate.errors ).to.eql [] describe 'throw mode simples', -> validate = null before -> validate = new Validate() validate.add('string', 5, 'wakka') it 'should run the tests', -> fn = -> validate.run() expect( fn ).to.throw ValidationError it 'should run the errors', -> expect( validate.errors ).to.eql [] describe 'throw mode simples with throw option', -> validate = null before -> validate = new Validate({ throw: true }) validate.add('string', 5, 'wakka') it 'should run the tests', -> fn = -> validate.run() expect( fn ).to.throw ValidationError it 'should run the errors', -> expect( validate.errors ).to.eql [] describe 'messages mode simples', -> validate = null before -> validate = new Validate({ messages: true }) validate.add('string', 5, 'wakka') it 'should run the tests', -> expect( validate.run() ).to.be.ok it 'should run the errors', -> expect( validate.errors.length ).to.eql 1 expect( validate.errors[0] ).to.match /wakka/ describe 'errors mode extended', -> validate = null errors = null before -> validate = new Validate({ errors: true }) .add('length', 'sa', 1, 256, 'dlen') .add('string', 5, 'dtype') .add('alphaNumericDashUnderscore', 'a!b', 'dstr') it 'should run the tests', -> expect( validate.run() ).to.be.ok it 'should contain errors after run', -> errors = validate.errors expect( errors ).to.be.an 'array' it 'should have a validation error for dtype', -> expect( errors[0] ).to.be.an.instanceOf ValidationError expect( errors[0].message ).to.equal '"dtype" must be a string' it 'should have a second validation error for dstr', -> expect( errors[1] ).to.be.an.instanceOf ValidationError expect( errors[1].message ).to.equal '"dstr" must only contain letters, numbers, dash and underscore [ A-Z a-z 0-9 _ - ]' it 'has the right number of errors', -> expect( errors.length ).to.eql 2 describe 'messages', -> validate = null errors = null before -> validate = new Validate({messages: true}) .add('length', 'sa', 1, 256, 'dlen') .add('string', 5, 'dtype') .add('testing', true, true, 'andtest') .add('alphaNumericDashUnderscore', 'a!b', 'dstr') it 'should run the tests', -> expect( validate.run() ).to.be.ok it 'should run the errors', -> errors = validate.errors expect( errors ).to.be.an 'array' it 'has a validation error', -> expect( errors[0] ).to.equal '"dtype" must be a string' it 'has a validation error', -> expect( errors[1] ).to.equal '"dstr" must only contain letters, numbers, dash and underscore [ A-Z a-z 0-9 _ - ]' it 'has the right number of errors', -> expect( errors.length ).to.eql 2 describe 'results', -> validate = null errors = null before -> validate = new Validate({results: true}) .add('length', 'sa', 1, 256, 'dlen') .add('string', 5, 'dtype') .add('alphaNumericDashUnderscore', 'a!b', 'dstr') it 'should run the tests', -> expect( validate.run() ).to.be.ok it 'should run the errors', -> errors = validate.errors expect( errors ).to.be.an 'array' it 'has a validation error', -> expect( errors[0] ).to.be.an 'array' .and.to.contain 'dtype' it 'has a validation error', -> expect( errors[1] ).to.be.an 'array' .and.to.contain 'dstr' it 'has the right number of errors', -> expect( errors.length ).to.eql 2
[ { "context": "rred = Q.defer()\n\n email =\n to: to\n from: 'noreply@carrallychargecoupon.com'\n subject: 'Want a Free Car Charge?'\n text:", "end": 1063, "score": 0.9999191164970398, "start": 1031, "tag": "EMAIL", "value": "noreply@carrallychargecoupon.com" } ]
lib-src/sendgrid-email.coffee
IBM-Cloud/bluemix-car-rally-charge-coupon
0
# Licensed under the Apache License. See footer for details. http = require "http" Q = require "q" cfEnv = require "cf-env" utils = require "./utils" # optionally override the user defined service name for sendgrid with a user defined env variable if process.env.SENDGRID_SERVICE_NAME != undefined and process.env.SENDGRID_SERVICE_NAME != "" SENDGRID_SERVICE_NAME = process.env.SENDGRID_SERVICE_NAME else # default name of the SendGrid service SENDGRID_SERVICE_NAME = "sendgrid" sgService = cfEnv.getService SENDGRID_SERVICE_NAME utils.log "using SendGrid service instance #{sgService.name}" sendgrid = require('sendgrid')(sgService.credentials.username, sgService.credentials.password); #------------------------------------------------------------------------------- # send an email to a customer #------------------------------------------------------------------------------- exports.sendEmail = (to, body) -> utils.log "sendgrid.sendEmail #{to}" deferred = Q.defer() email = to: to from: 'noreply@carrallychargecoupon.com' subject: 'Want a Free Car Charge?' text: body utils.log JSON.stringify(email, undefined , 2) sendgrid.send email, (err, json) -> if err deferred.reject Error "failed to send email to #{to}" else deferred.resolve json deferred.promise #------------------------------------------------------------------------------- # Copyright IBM Corp. 2014 # # 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. #-------------------------------------------------------------------------------
197411
# Licensed under the Apache License. See footer for details. http = require "http" Q = require "q" cfEnv = require "cf-env" utils = require "./utils" # optionally override the user defined service name for sendgrid with a user defined env variable if process.env.SENDGRID_SERVICE_NAME != undefined and process.env.SENDGRID_SERVICE_NAME != "" SENDGRID_SERVICE_NAME = process.env.SENDGRID_SERVICE_NAME else # default name of the SendGrid service SENDGRID_SERVICE_NAME = "sendgrid" sgService = cfEnv.getService SENDGRID_SERVICE_NAME utils.log "using SendGrid service instance #{sgService.name}" sendgrid = require('sendgrid')(sgService.credentials.username, sgService.credentials.password); #------------------------------------------------------------------------------- # send an email to a customer #------------------------------------------------------------------------------- exports.sendEmail = (to, body) -> utils.log "sendgrid.sendEmail #{to}" deferred = Q.defer() email = to: to from: '<EMAIL>' subject: 'Want a Free Car Charge?' text: body utils.log JSON.stringify(email, undefined , 2) sendgrid.send email, (err, json) -> if err deferred.reject Error "failed to send email to #{to}" else deferred.resolve json deferred.promise #------------------------------------------------------------------------------- # Copyright IBM Corp. 2014 # # 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. http = require "http" Q = require "q" cfEnv = require "cf-env" utils = require "./utils" # optionally override the user defined service name for sendgrid with a user defined env variable if process.env.SENDGRID_SERVICE_NAME != undefined and process.env.SENDGRID_SERVICE_NAME != "" SENDGRID_SERVICE_NAME = process.env.SENDGRID_SERVICE_NAME else # default name of the SendGrid service SENDGRID_SERVICE_NAME = "sendgrid" sgService = cfEnv.getService SENDGRID_SERVICE_NAME utils.log "using SendGrid service instance #{sgService.name}" sendgrid = require('sendgrid')(sgService.credentials.username, sgService.credentials.password); #------------------------------------------------------------------------------- # send an email to a customer #------------------------------------------------------------------------------- exports.sendEmail = (to, body) -> utils.log "sendgrid.sendEmail #{to}" deferred = Q.defer() email = to: to from: 'PI:EMAIL:<EMAIL>END_PI' subject: 'Want a Free Car Charge?' text: body utils.log JSON.stringify(email, undefined , 2) sendgrid.send email, (err, json) -> if err deferred.reject Error "failed to send email to #{to}" else deferred.resolve json deferred.promise #------------------------------------------------------------------------------- # Copyright IBM Corp. 2014 # # 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": "client', utils.wrap (done) ->\n json = { name: 'name', email: 'e@mail.com' }\n [res, body] = yield r", "end": 776, "score": 0.95856112241745, "start": 772, "tag": "NAME", "value": "name" }, { "context": "wrap (done) ->\n json = { name: 'name', email: 'e@mail.co...
spec/server/functional/api.spec.coffee
kbespalyi/codecombat
0
User = require '../../../server/models/User' APIClient = require '../../../server/models/APIClient' OAuthProvider = require '../../../server/models/OAuthProvider' utils = require '../utils' nock = require 'nock' request = require '../request' mongoose = require 'mongoose' moment = require 'moment' Prepaid = require '../../../server/models/Prepaid' describe 'POST /api/users', -> url = utils.getURL('/api/users') beforeEach utils.wrap (done) -> yield utils.clearModels([User, APIClient]) @client = new APIClient() @secret = @client.setNewSecret() @auth = { user: @client.id, pass: @secret } yield @client.save() done() it 'creates a user that is marked as having been created by the API client', utils.wrap (done) -> json = { name: 'name', email: 'e@mail.com' } [res, body] = yield request.postAsync({url, json, @auth}) expect(res.statusCode).toBe(201) expect(body.clientCreator).toBe(@client.id) expect(body.name).toBe(json.name) expect(body.email).toBe(json.email) done() describe 'GET /api/users/:handle', -> url = utils.getURL('/api/users') beforeEach utils.wrap (done) -> yield utils.clearModels([User, APIClient]) @client = new APIClient() @secret = @client.setNewSecret() @auth = { user: @client.id, pass: @secret } yield @client.save() json = { name: 'name', email: 'e@mail.com' } [res, body] = yield request.postAsync({url, json, @auth}) @user = yield User.findById(res.body._id) done() it 'returns the user, including stats', utils.wrap (done) -> yield @user.update({$set: {'stats.gamesCompleted':1}}) url = utils.getURL("/api/users/#{@user.id}") [res, body] = yield request.getAsync({url, json: true, @auth}) expect(res.statusCode).toBe(200) expect(body._id).toBe(@user.id) expect(body.name).toBe(@user.get('name')) expect(body.email).toBe(@user.get('email')) expect(body.stats.gamesCompleted).toBe(1) done() describe 'POST /api/users/:handle/o-auth-identities', -> beforeEach utils.wrap (done) -> yield utils.clearModels([User, APIClient]) @client = new APIClient() @secret = @client.setNewSecret() yield @client.save() @auth = { user: @client.id, pass: @secret } url = utils.getURL('/api/users') json = { name: 'name', email: 'e@mail.com' } [res, body] = yield request.postAsync({url, json, @auth}) @user = yield User.findById(res.body._id) @url = utils.getURL("/api/users/#{@user.id}/o-auth-identities") @provider = new OAuthProvider({ lookupUrlTemplate: 'https://oauth.provider/user?t=<%= accessToken %>' tokenUrl: 'https://oauth.provider/oauth2/token' }) @provider.save() @json = { provider: @provider.id, accessToken: '1234' } @providerNock = nock('https://oauth.provider') @providerLookupRequest = @providerNock.get('/user?t=1234') done() it 'adds a new identity to the user if everything checks out', utils.wrap (done) -> @providerLookupRequest.reply(200, {id: 'abcd'}) [res, body] = yield request.postAsync({ @url, @json, @auth }) expect(res.statusCode).toBe(200) expect(res.body.oAuthIdentities.length).toBe(1) expect(res.body.oAuthIdentities[0].id).toBe('abcd') expect(res.body.oAuthIdentities[0].provider).toBe(@provider.id) done() it 'can take a code and do a token lookup', utils.wrap (done) -> @providerNock.get('/oauth2/token').reply(200, {access_token: '1234'}) @providerLookupRequest.reply(200, {id: 'abcd'}) json = { provider: @provider.id, code: 'xyzzy' } [res, body] = yield request.postAsync({ @url, json, @auth }) expect(res.statusCode).toBe(200) expect(res.body.oAuthIdentities.length).toBe(1) done() it 'returns 404 if the user is not found', utils.wrap (done) -> url = utils.getURL("/api/users/dne/o-auth-identities") [res, body] = yield request.postAsync({ url, @json, @auth }) expect(res.statusCode).toBe(404) done() it 'returns 403 if the client did not create the given user', utils.wrap (done) -> user = yield utils.initUser() url = utils.getURL("/api/users/#{user.id}/o-auth-identities") [res, body] = yield request.postAsync({ url, @json, @auth }) expect(res.statusCode).toBe(403) done() it 'returns 422 if "provider" and "accessToken" are not provided', utils.wrap (done) -> json = {} [res, body] = yield request.postAsync({ @url, json, @auth }) expect(res.statusCode).toBe(422) done() it 'returns 404 if the provider is not found', utils.wrap (done) -> json = { provider: new mongoose.Types.ObjectId() + '', accessToken: '1234' } [res, body] = yield request.postAsync({ @url, json, @auth }) expect(res.statusCode).toBe(404) done() it 'returns 422 if the token lookup fails', utils.wrap (done) -> @providerLookupRequest.reply(400, {}) [res, body] = yield request.postAsync({ @url, @json, @auth }) expect(res.statusCode).toBe(422) done() it 'returns 422 if the token lookup does not return an object with an id', utils.wrap (done) -> @providerLookupRequest.reply(200, {id: null}) [res, body] = yield request.postAsync({ @url, @json, @auth }) expect(res.statusCode).toBe(422) done() it 'returns 409 if a user already exists with the given id/provider', utils.wrap (done) -> yield utils.initUser({oAuthIdentities: [{ provider: @provider._id, id: 'abcd'}]}) @providerLookupRequest.reply(200, {id: 'abcd'}) [res, body] = yield request.postAsync({ @url, @json, @auth }) expect(res.statusCode).toBe(409) done() describe 'PUT /api/users/:handle/subscription', -> beforeEach utils.wrap (done) -> yield utils.clearModels([User, APIClient]) yield utils.populateProducts() @client = new APIClient() @secret = @client.setNewSecret() yield @client.save() @auth = { user: @client.id, pass: @secret } url = utils.getURL('/api/users') json = { name: 'name', email: 'e@mail.com' } [res, body] = yield request.postAsync({url, json, @auth}) @user = yield User.findById(res.body._id) @url = utils.getURL("/api/users/#{@user.id}/subscription") @ends = moment().add(12, 'months').toISOString() @json = { @ends } done() it 'provides the user with premium access until the given end date, and creates a prepaid', utils.wrap (done) -> expect(@user.hasSubscription()).toBe(false) t0 = new Date().toISOString() [res, body] = yield request.putAsync({ @url, @json, @auth }) t1 = new Date().toISOString() expect(res.body.subscription.ends).toBe(@ends) expect(res.statusCode).toBe(200) prepaid = yield Prepaid.findOne({'redeemers.userID': @user._id}) expect(prepaid).toBeDefined() expect(prepaid.get('clientCreator').equals(@client._id)).toBe(true) expect(prepaid.get('redeemers')[0].userID.equals(@user._id)).toBe(true) expect(prepaid.get('startDate')).toBeGreaterThan(t0) expect(prepaid.get('startDate')).toBeLessThan(t1) expect(prepaid.get('endDate')).toBe(@ends) user = yield User.findById(@user.id) expect(user.hasSubscription()).toBe(true) done() it 'returns 404 if the user is not found', utils.wrap (done) -> url = utils.getURL('/api/users/dne/subscription') [res, body] = yield request.putAsync({ url, @json, @auth }) expect(res.statusCode).toBe(404) done() it 'returns 403 if the user was not created by the client', utils.wrap (done) -> yield @user.update({$unset: {clientCreator:1}}) [res, body] = yield request.putAsync({ @url, @json, @auth }) expect(res.statusCode).toBe(403) done() it 'returns 422 if ends is not provided or incorrectly formatted', utils.wrap (done) -> json = {} [res, body] = yield request.putAsync({ @url, json, @auth }) expect(res.statusCode).toBe(422) json = { ends: '2014-01-01T00:00:00.00Z'} [res, body] = yield request.putAsync({ @url, json, @auth }) expect(res.statusCode).toBe(422) done() it 'returns 422 if the user already has free premium access', utils.wrap (done) -> yield @user.update({$set: {stripe: {free:true}}}) [res, body] = yield request.putAsync({ @url, @json, @auth }) expect(res.statusCode).toBe(422) done() describe 'when the user has a terminal subscription already', -> it 'returns 422 if the user has access beyond the ends', utils.wrap (done) -> free = moment().add(13, 'months').toISOString() yield @user.update({$set: {stripe: {free}}}) [res, body] = yield request.putAsync({ @url, @json, @auth }) expect(res.statusCode).toBe(422) done() it 'sets the prepaid startDate to the user\'s old terminal subscription end date', utils.wrap (done) -> originalFreeUntil = moment().add(6, 'months').toISOString() yield @user.update({$set: {stripe: {free: originalFreeUntil}}}) [res, body] = yield request.putAsync({ @url, @json, @auth }) expect(res.statusCode).toBe(200) prepaid = yield Prepaid.findOne({'redeemers.userID': @user._id}) expect(prepaid.get('startDate')).toBe(originalFreeUntil) done() it 'sets the prepaid startDate to now if the user\'s subscription ended already', utils.wrap (done) -> originalFreeUntil = moment().subtract(6, 'months').toISOString() yield @user.update({$set: {stripe: {free: originalFreeUntil}}}) t0 = new Date().toISOString() [res, body] = yield request.putAsync({ @url, @json, @auth }) t1 = new Date().toISOString() expect(res.statusCode).toBe(200) prepaid = yield Prepaid.findOne({'redeemers.userID': @user._id}) expect(prepaid.get('startDate')).not.toBe(originalFreeUntil) expect(prepaid.get('startDate')).toBeGreaterThan(t0) expect(prepaid.get('startDate')).toBeLessThan(t1) done() describe 'PUT /api/users/:handle/license', -> beforeEach utils.wrap (done) -> yield utils.clearModels([User, APIClient]) @client = new APIClient() @secret = @client.setNewSecret() yield @client.save() @auth = { user: @client.id, pass: @secret } url = utils.getURL('/api/users') json = { name: 'name', email: 'e@mail.com' } [res, body] = yield request.postAsync({url, json, @auth}) @user = yield User.findById(res.body._id) @url = utils.getURL("/api/users/#{@user.id}/license") @ends = moment().add(12, 'months').toISOString() @json = { @ends } done() it 'provides the user with premium access until the given end date, and creates a prepaid', utils.wrap (done) -> expect(@user.isEnrolled()).toBe(false) t0 = new Date().toISOString() [res, body] = yield request.putAsync({ @url, @json, @auth }) t1 = new Date().toISOString() expect(res.body.license.ends).toBe(@ends) expect(res.statusCode).toBe(200) prepaid = yield Prepaid.findOne({'redeemers.userID': @user._id}) expect(prepaid).toBeDefined() expect(prepaid.get('clientCreator').equals(@client._id)).toBe(true) expect(prepaid.get('redeemers')[0].userID.equals(@user._id)).toBe(true) expect(prepaid.get('startDate')).toBeGreaterThan(t0) expect(prepaid.get('startDate')).toBeLessThan(t1) expect(prepaid.get('type')).toBe('course') expect(prepaid.get('endDate')).toBe(@ends) user = yield User.findById(@user.id) expect(user.isEnrolled()).toBe(true) expect(user.get('role')).toBe('student') done() it 'returns 404 if the user is not found', utils.wrap (done) -> url = utils.getURL('/api/users/dne/license') [res, body] = yield request.putAsync({ url, @json, @auth }) expect(res.statusCode).toBe(404) done() it 'returns 403 if the user was not created by the client', utils.wrap (done) -> yield @user.update({$unset: {clientCreator:1}}) [res, body] = yield request.putAsync({ @url, @json, @auth }) expect(res.statusCode).toBe(403) done() it 'returns 422 if ends is not provided or incorrectly formatted or in the past', utils.wrap (done) -> json = {} [res, body] = yield request.putAsync({ @url, json, @auth }) expect(res.statusCode).toBe(422) json = { ends: '2014-01-01T00:00:00.00Z'} [res, body] = yield request.putAsync({ @url, json, @auth }) expect(res.statusCode).toBe(422) json = { ends: moment().subtract(1, 'day').toISOString() } [res, body] = yield request.putAsync({ @url, json, @auth }) expect(res.statusCode).toBe(422) done() it 'returns 422 if the user is already enrolled', utils.wrap (done) -> yield @user.update({$set: {coursePrepaid:{ _id: new mongoose.Types.ObjectId() endDate: moment().add(1, 'month').toISOString() startDate: moment().subtract(1, 'month').toISOString() }}}) [res, body] = yield request.putAsync({ @url, @json, @auth }) expect(res.statusCode).toBe(422) yield @user.update({$set: {coursePrepaid:{ _id: new mongoose.Types.ObjectId() endDate: moment().subtract(1, 'month').toISOString() startDate: moment().subtract(2, 'months').toISOString() }}}) [res, body] = yield request.putAsync({ @url, @json, @auth }) expect(res.statusCode).toBe(200) done()
51472
User = require '../../../server/models/User' APIClient = require '../../../server/models/APIClient' OAuthProvider = require '../../../server/models/OAuthProvider' utils = require '../utils' nock = require 'nock' request = require '../request' mongoose = require 'mongoose' moment = require 'moment' Prepaid = require '../../../server/models/Prepaid' describe 'POST /api/users', -> url = utils.getURL('/api/users') beforeEach utils.wrap (done) -> yield utils.clearModels([User, APIClient]) @client = new APIClient() @secret = @client.setNewSecret() @auth = { user: @client.id, pass: @secret } yield @client.save() done() it 'creates a user that is marked as having been created by the API client', utils.wrap (done) -> json = { name: '<NAME>', email: '<EMAIL>' } [res, body] = yield request.postAsync({url, json, @auth}) expect(res.statusCode).toBe(201) expect(body.clientCreator).toBe(@client.id) expect(body.name).toBe(json.name) expect(body.email).toBe(json.email) done() describe 'GET /api/users/:handle', -> url = utils.getURL('/api/users') beforeEach utils.wrap (done) -> yield utils.clearModels([User, APIClient]) @client = new APIClient() @secret = @client.setNewSecret() @auth = { user: @client.id, pass: <PASSWORD> } yield @client.save() json = { name: '<NAME>', email: '<EMAIL>' } [res, body] = yield request.postAsync({url, json, @auth}) @user = yield User.findById(res.body._id) done() it 'returns the user, including stats', utils.wrap (done) -> yield @user.update({$set: {'stats.gamesCompleted':1}}) url = utils.getURL("/api/users/#{@user.id}") [res, body] = yield request.getAsync({url, json: true, @auth}) expect(res.statusCode).toBe(200) expect(body._id).toBe(@user.id) expect(body.name).toBe(@user.get('name')) expect(body.email).toBe(@user.get('email')) expect(body.stats.gamesCompleted).toBe(1) done() describe 'POST /api/users/:handle/o-auth-identities', -> beforeEach utils.wrap (done) -> yield utils.clearModels([User, APIClient]) @client = new APIClient() @secret = @client.setNewSecret() yield @client.save() @auth = { user: @client.id, pass: @secret } url = utils.getURL('/api/users') json = { name: 'name', email: '<EMAIL>' } [res, body] = yield request.postAsync({url, json, @auth}) @user = yield User.findById(res.body._id) @url = utils.getURL("/api/users/#{@user.id}/o-auth-identities") @provider = new OAuthProvider({ lookupUrlTemplate: 'https://oauth.provider/user?t=<%= accessToken %>' tokenUrl: 'https://oauth.provider/oauth2/token' }) @provider.save() @json = { provider: @provider.id, accessToken: '<KEY>' } @providerNock = nock('https://oauth.provider') @providerLookupRequest = @providerNock.get('/user?t=1234') done() it 'adds a new identity to the user if everything checks out', utils.wrap (done) -> @providerLookupRequest.reply(200, {id: 'abcd'}) [res, body] = yield request.postAsync({ @url, @json, @auth }) expect(res.statusCode).toBe(200) expect(res.body.oAuthIdentities.length).toBe(1) expect(res.body.oAuthIdentities[0].id).toBe('abcd') expect(res.body.oAuthIdentities[0].provider).toBe(@provider.id) done() it 'can take a code and do a token lookup', utils.wrap (done) -> @providerNock.get('/oauth2/token').reply(200, {access_token: '<KEY>'}) @providerLookupRequest.reply(200, {id: 'abcd'}) json = { provider: @provider.id, code: 'xyzzy' } [res, body] = yield request.postAsync({ @url, json, @auth }) expect(res.statusCode).toBe(200) expect(res.body.oAuthIdentities.length).toBe(1) done() it 'returns 404 if the user is not found', utils.wrap (done) -> url = utils.getURL("/api/users/dne/o-auth-identities") [res, body] = yield request.postAsync({ url, @json, @auth }) expect(res.statusCode).toBe(404) done() it 'returns 403 if the client did not create the given user', utils.wrap (done) -> user = yield utils.initUser() url = utils.getURL("/api/users/#{user.id}/o-auth-identities") [res, body] = yield request.postAsync({ url, @json, @auth }) expect(res.statusCode).toBe(403) done() it 'returns 422 if "provider" and "accessToken" are not provided', utils.wrap (done) -> json = {} [res, body] = yield request.postAsync({ @url, json, @auth }) expect(res.statusCode).toBe(422) done() it 'returns 404 if the provider is not found', utils.wrap (done) -> json = { provider: new mongoose.Types.ObjectId() + '', accessToken: '<KEY>' } [res, body] = yield request.postAsync({ @url, json, @auth }) expect(res.statusCode).toBe(404) done() it 'returns 422 if the token lookup fails', utils.wrap (done) -> @providerLookupRequest.reply(400, {}) [res, body] = yield request.postAsync({ @url, @json, @auth }) expect(res.statusCode).toBe(422) done() it 'returns 422 if the token lookup does not return an object with an id', utils.wrap (done) -> @providerLookupRequest.reply(200, {id: null}) [res, body] = yield request.postAsync({ @url, @json, @auth }) expect(res.statusCode).toBe(422) done() it 'returns 409 if a user already exists with the given id/provider', utils.wrap (done) -> yield utils.initUser({oAuthIdentities: [{ provider: @provider._id, id: 'abcd'}]}) @providerLookupRequest.reply(200, {id: 'abcd'}) [res, body] = yield request.postAsync({ @url, @json, @auth }) expect(res.statusCode).toBe(409) done() describe 'PUT /api/users/:handle/subscription', -> beforeEach utils.wrap (done) -> yield utils.clearModels([User, APIClient]) yield utils.populateProducts() @client = new APIClient() @secret = @client.setNewSecret() yield @client.save() @auth = { user: @client.id, pass: <PASSWORD> } url = utils.getURL('/api/users') json = { name: '<NAME>', email: '<EMAIL>' } [res, body] = yield request.postAsync({url, json, @auth}) @user = yield User.findById(res.body._id) @url = utils.getURL("/api/users/#{@user.id}/subscription") @ends = moment().add(12, 'months').toISOString() @json = { @ends } done() it 'provides the user with premium access until the given end date, and creates a prepaid', utils.wrap (done) -> expect(@user.hasSubscription()).toBe(false) t0 = new Date().toISOString() [res, body] = yield request.putAsync({ @url, @json, @auth }) t1 = new Date().toISOString() expect(res.body.subscription.ends).toBe(@ends) expect(res.statusCode).toBe(200) prepaid = yield Prepaid.findOne({'redeemers.userID': @user._id}) expect(prepaid).toBeDefined() expect(prepaid.get('clientCreator').equals(@client._id)).toBe(true) expect(prepaid.get('redeemers')[0].userID.equals(@user._id)).toBe(true) expect(prepaid.get('startDate')).toBeGreaterThan(t0) expect(prepaid.get('startDate')).toBeLessThan(t1) expect(prepaid.get('endDate')).toBe(@ends) user = yield User.findById(@user.id) expect(user.hasSubscription()).toBe(true) done() it 'returns 404 if the user is not found', utils.wrap (done) -> url = utils.getURL('/api/users/dne/subscription') [res, body] = yield request.putAsync({ url, @json, @auth }) expect(res.statusCode).toBe(404) done() it 'returns 403 if the user was not created by the client', utils.wrap (done) -> yield @user.update({$unset: {clientCreator:1}}) [res, body] = yield request.putAsync({ @url, @json, @auth }) expect(res.statusCode).toBe(403) done() it 'returns 422 if ends is not provided or incorrectly formatted', utils.wrap (done) -> json = {} [res, body] = yield request.putAsync({ @url, json, @auth }) expect(res.statusCode).toBe(422) json = { ends: '2014-01-01T00:00:00.00Z'} [res, body] = yield request.putAsync({ @url, json, @auth }) expect(res.statusCode).toBe(422) done() it 'returns 422 if the user already has free premium access', utils.wrap (done) -> yield @user.update({$set: {stripe: {free:true}}}) [res, body] = yield request.putAsync({ @url, @json, @auth }) expect(res.statusCode).toBe(422) done() describe 'when the user has a terminal subscription already', -> it 'returns 422 if the user has access beyond the ends', utils.wrap (done) -> free = moment().add(13, 'months').toISOString() yield @user.update({$set: {stripe: {free}}}) [res, body] = yield request.putAsync({ @url, @json, @auth }) expect(res.statusCode).toBe(422) done() it 'sets the prepaid startDate to the user\'s old terminal subscription end date', utils.wrap (done) -> originalFreeUntil = moment().add(6, 'months').toISOString() yield @user.update({$set: {stripe: {free: originalFreeUntil}}}) [res, body] = yield request.putAsync({ @url, @json, @auth }) expect(res.statusCode).toBe(200) prepaid = yield Prepaid.findOne({'redeemers.userID': @user._id}) expect(prepaid.get('startDate')).toBe(originalFreeUntil) done() it 'sets the prepaid startDate to now if the user\'s subscription ended already', utils.wrap (done) -> originalFreeUntil = moment().subtract(6, 'months').toISOString() yield @user.update({$set: {stripe: {free: originalFreeUntil}}}) t0 = new Date().toISOString() [res, body] = yield request.putAsync({ @url, @json, @auth }) t1 = new Date().toISOString() expect(res.statusCode).toBe(200) prepaid = yield Prepaid.findOne({'redeemers.userID': @user._id}) expect(prepaid.get('startDate')).not.toBe(originalFreeUntil) expect(prepaid.get('startDate')).toBeGreaterThan(t0) expect(prepaid.get('startDate')).toBeLessThan(t1) done() describe 'PUT /api/users/:handle/license', -> beforeEach utils.wrap (done) -> yield utils.clearModels([User, APIClient]) @client = new APIClient() @secret = @client.setNewSecret() yield @client.save() @auth = { user: @client.id, pass: <PASSWORD> } url = utils.getURL('/api/users') json = { name: 'name', email: '<EMAIL>' } [res, body] = yield request.postAsync({url, json, @auth}) @user = yield User.findById(res.body._id) @url = utils.getURL("/api/users/#{@user.id}/license") @ends = moment().add(12, 'months').toISOString() @json = { @ends } done() it 'provides the user with premium access until the given end date, and creates a prepaid', utils.wrap (done) -> expect(@user.isEnrolled()).toBe(false) t0 = new Date().toISOString() [res, body] = yield request.putAsync({ @url, @json, @auth }) t1 = new Date().toISOString() expect(res.body.license.ends).toBe(@ends) expect(res.statusCode).toBe(200) prepaid = yield Prepaid.findOne({'redeemers.userID': @user._id}) expect(prepaid).toBeDefined() expect(prepaid.get('clientCreator').equals(@client._id)).toBe(true) expect(prepaid.get('redeemers')[0].userID.equals(@user._id)).toBe(true) expect(prepaid.get('startDate')).toBeGreaterThan(t0) expect(prepaid.get('startDate')).toBeLessThan(t1) expect(prepaid.get('type')).toBe('course') expect(prepaid.get('endDate')).toBe(@ends) user = yield User.findById(@user.id) expect(user.isEnrolled()).toBe(true) expect(user.get('role')).toBe('student') done() it 'returns 404 if the user is not found', utils.wrap (done) -> url = utils.getURL('/api/users/dne/license') [res, body] = yield request.putAsync({ url, @json, @auth }) expect(res.statusCode).toBe(404) done() it 'returns 403 if the user was not created by the client', utils.wrap (done) -> yield @user.update({$unset: {clientCreator:1}}) [res, body] = yield request.putAsync({ @url, @json, @auth }) expect(res.statusCode).toBe(403) done() it 'returns 422 if ends is not provided or incorrectly formatted or in the past', utils.wrap (done) -> json = {} [res, body] = yield request.putAsync({ @url, json, @auth }) expect(res.statusCode).toBe(422) json = { ends: '2014-01-01T00:00:00.00Z'} [res, body] = yield request.putAsync({ @url, json, @auth }) expect(res.statusCode).toBe(422) json = { ends: moment().subtract(1, 'day').toISOString() } [res, body] = yield request.putAsync({ @url, json, @auth }) expect(res.statusCode).toBe(422) done() it 'returns 422 if the user is already enrolled', utils.wrap (done) -> yield @user.update({$set: {coursePrepaid:{ _id: new mongoose.Types.ObjectId() endDate: moment().add(1, 'month').toISOString() startDate: moment().subtract(1, 'month').toISOString() }}}) [res, body] = yield request.putAsync({ @url, @json, @auth }) expect(res.statusCode).toBe(422) yield @user.update({$set: {coursePrepaid:{ _id: new mongoose.Types.ObjectId() endDate: moment().subtract(1, 'month').toISOString() startDate: moment().subtract(2, 'months').toISOString() }}}) [res, body] = yield request.putAsync({ @url, @json, @auth }) expect(res.statusCode).toBe(200) done()
true
User = require '../../../server/models/User' APIClient = require '../../../server/models/APIClient' OAuthProvider = require '../../../server/models/OAuthProvider' utils = require '../utils' nock = require 'nock' request = require '../request' mongoose = require 'mongoose' moment = require 'moment' Prepaid = require '../../../server/models/Prepaid' describe 'POST /api/users', -> url = utils.getURL('/api/users') beforeEach utils.wrap (done) -> yield utils.clearModels([User, APIClient]) @client = new APIClient() @secret = @client.setNewSecret() @auth = { user: @client.id, pass: @secret } yield @client.save() done() it 'creates a user that is marked as having been created by the API client', utils.wrap (done) -> json = { name: 'PI:NAME:<NAME>END_PI', email: 'PI:EMAIL:<EMAIL>END_PI' } [res, body] = yield request.postAsync({url, json, @auth}) expect(res.statusCode).toBe(201) expect(body.clientCreator).toBe(@client.id) expect(body.name).toBe(json.name) expect(body.email).toBe(json.email) done() describe 'GET /api/users/:handle', -> url = utils.getURL('/api/users') beforeEach utils.wrap (done) -> yield utils.clearModels([User, APIClient]) @client = new APIClient() @secret = @client.setNewSecret() @auth = { user: @client.id, pass: PI:PASSWORD:<PASSWORD>END_PI } yield @client.save() json = { name: 'PI:NAME:<NAME>END_PI', email: 'PI:EMAIL:<EMAIL>END_PI' } [res, body] = yield request.postAsync({url, json, @auth}) @user = yield User.findById(res.body._id) done() it 'returns the user, including stats', utils.wrap (done) -> yield @user.update({$set: {'stats.gamesCompleted':1}}) url = utils.getURL("/api/users/#{@user.id}") [res, body] = yield request.getAsync({url, json: true, @auth}) expect(res.statusCode).toBe(200) expect(body._id).toBe(@user.id) expect(body.name).toBe(@user.get('name')) expect(body.email).toBe(@user.get('email')) expect(body.stats.gamesCompleted).toBe(1) done() describe 'POST /api/users/:handle/o-auth-identities', -> beforeEach utils.wrap (done) -> yield utils.clearModels([User, APIClient]) @client = new APIClient() @secret = @client.setNewSecret() yield @client.save() @auth = { user: @client.id, pass: @secret } url = utils.getURL('/api/users') json = { name: 'name', email: 'PI:EMAIL:<EMAIL>END_PI' } [res, body] = yield request.postAsync({url, json, @auth}) @user = yield User.findById(res.body._id) @url = utils.getURL("/api/users/#{@user.id}/o-auth-identities") @provider = new OAuthProvider({ lookupUrlTemplate: 'https://oauth.provider/user?t=<%= accessToken %>' tokenUrl: 'https://oauth.provider/oauth2/token' }) @provider.save() @json = { provider: @provider.id, accessToken: 'PI:KEY:<KEY>END_PI' } @providerNock = nock('https://oauth.provider') @providerLookupRequest = @providerNock.get('/user?t=1234') done() it 'adds a new identity to the user if everything checks out', utils.wrap (done) -> @providerLookupRequest.reply(200, {id: 'abcd'}) [res, body] = yield request.postAsync({ @url, @json, @auth }) expect(res.statusCode).toBe(200) expect(res.body.oAuthIdentities.length).toBe(1) expect(res.body.oAuthIdentities[0].id).toBe('abcd') expect(res.body.oAuthIdentities[0].provider).toBe(@provider.id) done() it 'can take a code and do a token lookup', utils.wrap (done) -> @providerNock.get('/oauth2/token').reply(200, {access_token: 'PI:PASSWORD:<KEY>END_PI'}) @providerLookupRequest.reply(200, {id: 'abcd'}) json = { provider: @provider.id, code: 'xyzzy' } [res, body] = yield request.postAsync({ @url, json, @auth }) expect(res.statusCode).toBe(200) expect(res.body.oAuthIdentities.length).toBe(1) done() it 'returns 404 if the user is not found', utils.wrap (done) -> url = utils.getURL("/api/users/dne/o-auth-identities") [res, body] = yield request.postAsync({ url, @json, @auth }) expect(res.statusCode).toBe(404) done() it 'returns 403 if the client did not create the given user', utils.wrap (done) -> user = yield utils.initUser() url = utils.getURL("/api/users/#{user.id}/o-auth-identities") [res, body] = yield request.postAsync({ url, @json, @auth }) expect(res.statusCode).toBe(403) done() it 'returns 422 if "provider" and "accessToken" are not provided', utils.wrap (done) -> json = {} [res, body] = yield request.postAsync({ @url, json, @auth }) expect(res.statusCode).toBe(422) done() it 'returns 404 if the provider is not found', utils.wrap (done) -> json = { provider: new mongoose.Types.ObjectId() + '', accessToken: 'PI:KEY:<KEY>END_PI' } [res, body] = yield request.postAsync({ @url, json, @auth }) expect(res.statusCode).toBe(404) done() it 'returns 422 if the token lookup fails', utils.wrap (done) -> @providerLookupRequest.reply(400, {}) [res, body] = yield request.postAsync({ @url, @json, @auth }) expect(res.statusCode).toBe(422) done() it 'returns 422 if the token lookup does not return an object with an id', utils.wrap (done) -> @providerLookupRequest.reply(200, {id: null}) [res, body] = yield request.postAsync({ @url, @json, @auth }) expect(res.statusCode).toBe(422) done() it 'returns 409 if a user already exists with the given id/provider', utils.wrap (done) -> yield utils.initUser({oAuthIdentities: [{ provider: @provider._id, id: 'abcd'}]}) @providerLookupRequest.reply(200, {id: 'abcd'}) [res, body] = yield request.postAsync({ @url, @json, @auth }) expect(res.statusCode).toBe(409) done() describe 'PUT /api/users/:handle/subscription', -> beforeEach utils.wrap (done) -> yield utils.clearModels([User, APIClient]) yield utils.populateProducts() @client = new APIClient() @secret = @client.setNewSecret() yield @client.save() @auth = { user: @client.id, pass: PI:PASSWORD:<PASSWORD>END_PI } url = utils.getURL('/api/users') json = { name: 'PI:NAME:<NAME>END_PI', email: 'PI:EMAIL:<EMAIL>END_PI' } [res, body] = yield request.postAsync({url, json, @auth}) @user = yield User.findById(res.body._id) @url = utils.getURL("/api/users/#{@user.id}/subscription") @ends = moment().add(12, 'months').toISOString() @json = { @ends } done() it 'provides the user with premium access until the given end date, and creates a prepaid', utils.wrap (done) -> expect(@user.hasSubscription()).toBe(false) t0 = new Date().toISOString() [res, body] = yield request.putAsync({ @url, @json, @auth }) t1 = new Date().toISOString() expect(res.body.subscription.ends).toBe(@ends) expect(res.statusCode).toBe(200) prepaid = yield Prepaid.findOne({'redeemers.userID': @user._id}) expect(prepaid).toBeDefined() expect(prepaid.get('clientCreator').equals(@client._id)).toBe(true) expect(prepaid.get('redeemers')[0].userID.equals(@user._id)).toBe(true) expect(prepaid.get('startDate')).toBeGreaterThan(t0) expect(prepaid.get('startDate')).toBeLessThan(t1) expect(prepaid.get('endDate')).toBe(@ends) user = yield User.findById(@user.id) expect(user.hasSubscription()).toBe(true) done() it 'returns 404 if the user is not found', utils.wrap (done) -> url = utils.getURL('/api/users/dne/subscription') [res, body] = yield request.putAsync({ url, @json, @auth }) expect(res.statusCode).toBe(404) done() it 'returns 403 if the user was not created by the client', utils.wrap (done) -> yield @user.update({$unset: {clientCreator:1}}) [res, body] = yield request.putAsync({ @url, @json, @auth }) expect(res.statusCode).toBe(403) done() it 'returns 422 if ends is not provided or incorrectly formatted', utils.wrap (done) -> json = {} [res, body] = yield request.putAsync({ @url, json, @auth }) expect(res.statusCode).toBe(422) json = { ends: '2014-01-01T00:00:00.00Z'} [res, body] = yield request.putAsync({ @url, json, @auth }) expect(res.statusCode).toBe(422) done() it 'returns 422 if the user already has free premium access', utils.wrap (done) -> yield @user.update({$set: {stripe: {free:true}}}) [res, body] = yield request.putAsync({ @url, @json, @auth }) expect(res.statusCode).toBe(422) done() describe 'when the user has a terminal subscription already', -> it 'returns 422 if the user has access beyond the ends', utils.wrap (done) -> free = moment().add(13, 'months').toISOString() yield @user.update({$set: {stripe: {free}}}) [res, body] = yield request.putAsync({ @url, @json, @auth }) expect(res.statusCode).toBe(422) done() it 'sets the prepaid startDate to the user\'s old terminal subscription end date', utils.wrap (done) -> originalFreeUntil = moment().add(6, 'months').toISOString() yield @user.update({$set: {stripe: {free: originalFreeUntil}}}) [res, body] = yield request.putAsync({ @url, @json, @auth }) expect(res.statusCode).toBe(200) prepaid = yield Prepaid.findOne({'redeemers.userID': @user._id}) expect(prepaid.get('startDate')).toBe(originalFreeUntil) done() it 'sets the prepaid startDate to now if the user\'s subscription ended already', utils.wrap (done) -> originalFreeUntil = moment().subtract(6, 'months').toISOString() yield @user.update({$set: {stripe: {free: originalFreeUntil}}}) t0 = new Date().toISOString() [res, body] = yield request.putAsync({ @url, @json, @auth }) t1 = new Date().toISOString() expect(res.statusCode).toBe(200) prepaid = yield Prepaid.findOne({'redeemers.userID': @user._id}) expect(prepaid.get('startDate')).not.toBe(originalFreeUntil) expect(prepaid.get('startDate')).toBeGreaterThan(t0) expect(prepaid.get('startDate')).toBeLessThan(t1) done() describe 'PUT /api/users/:handle/license', -> beforeEach utils.wrap (done) -> yield utils.clearModels([User, APIClient]) @client = new APIClient() @secret = @client.setNewSecret() yield @client.save() @auth = { user: @client.id, pass: PI:PASSWORD:<PASSWORD>END_PI } url = utils.getURL('/api/users') json = { name: 'name', email: 'PI:EMAIL:<EMAIL>END_PI' } [res, body] = yield request.postAsync({url, json, @auth}) @user = yield User.findById(res.body._id) @url = utils.getURL("/api/users/#{@user.id}/license") @ends = moment().add(12, 'months').toISOString() @json = { @ends } done() it 'provides the user with premium access until the given end date, and creates a prepaid', utils.wrap (done) -> expect(@user.isEnrolled()).toBe(false) t0 = new Date().toISOString() [res, body] = yield request.putAsync({ @url, @json, @auth }) t1 = new Date().toISOString() expect(res.body.license.ends).toBe(@ends) expect(res.statusCode).toBe(200) prepaid = yield Prepaid.findOne({'redeemers.userID': @user._id}) expect(prepaid).toBeDefined() expect(prepaid.get('clientCreator').equals(@client._id)).toBe(true) expect(prepaid.get('redeemers')[0].userID.equals(@user._id)).toBe(true) expect(prepaid.get('startDate')).toBeGreaterThan(t0) expect(prepaid.get('startDate')).toBeLessThan(t1) expect(prepaid.get('type')).toBe('course') expect(prepaid.get('endDate')).toBe(@ends) user = yield User.findById(@user.id) expect(user.isEnrolled()).toBe(true) expect(user.get('role')).toBe('student') done() it 'returns 404 if the user is not found', utils.wrap (done) -> url = utils.getURL('/api/users/dne/license') [res, body] = yield request.putAsync({ url, @json, @auth }) expect(res.statusCode).toBe(404) done() it 'returns 403 if the user was not created by the client', utils.wrap (done) -> yield @user.update({$unset: {clientCreator:1}}) [res, body] = yield request.putAsync({ @url, @json, @auth }) expect(res.statusCode).toBe(403) done() it 'returns 422 if ends is not provided or incorrectly formatted or in the past', utils.wrap (done) -> json = {} [res, body] = yield request.putAsync({ @url, json, @auth }) expect(res.statusCode).toBe(422) json = { ends: '2014-01-01T00:00:00.00Z'} [res, body] = yield request.putAsync({ @url, json, @auth }) expect(res.statusCode).toBe(422) json = { ends: moment().subtract(1, 'day').toISOString() } [res, body] = yield request.putAsync({ @url, json, @auth }) expect(res.statusCode).toBe(422) done() it 'returns 422 if the user is already enrolled', utils.wrap (done) -> yield @user.update({$set: {coursePrepaid:{ _id: new mongoose.Types.ObjectId() endDate: moment().add(1, 'month').toISOString() startDate: moment().subtract(1, 'month').toISOString() }}}) [res, body] = yield request.putAsync({ @url, @json, @auth }) expect(res.statusCode).toBe(422) yield @user.update({$set: {coursePrepaid:{ _id: new mongoose.Types.ObjectId() endDate: moment().subtract(1, 'month').toISOString() startDate: moment().subtract(2, 'months').toISOString() }}}) [res, body] = yield request.putAsync({ @url, @json, @auth }) expect(res.statusCode).toBe(200) done()
[ { "context": "# Copyright 2012 Joshua Carver \n# \n# Licensed under the Apache License, Versio", "end": 30, "score": 0.9998706579208374, "start": 17, "tag": "NAME", "value": "Joshua Carver" } ]
src/coffeescript/charts/base_chart.coffee
jcarver989/raphy-charts
5
# Copyright 2012 Joshua Carver # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. is_element = (o) -> if o.tagName != undefined then true else false class BaseChart constructor: (dom_container, options) -> container = if is_element(dom_container) then dom_container else document.getElementById(dom_container) [@width, @height] = @get_dimensions(container) @r = Raphael(container, @width, @height) @options = options get_dimensions: (container) -> width = parseInt(container.style.width) height = parseInt(container.style.height) [width, height] clear: () -> @r.clear()
18838
# Copyright 2012 <NAME> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. is_element = (o) -> if o.tagName != undefined then true else false class BaseChart constructor: (dom_container, options) -> container = if is_element(dom_container) then dom_container else document.getElementById(dom_container) [@width, @height] = @get_dimensions(container) @r = Raphael(container, @width, @height) @options = options get_dimensions: (container) -> width = parseInt(container.style.width) height = parseInt(container.style.height) [width, height] clear: () -> @r.clear()
true
# Copyright 2012 PI:NAME:<NAME>END_PI # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. is_element = (o) -> if o.tagName != undefined then true else false class BaseChart constructor: (dom_container, options) -> container = if is_element(dom_container) then dom_container else document.getElementById(dom_container) [@width, @height] = @get_dimensions(container) @r = Raphael(container, @width, @height) @options = options get_dimensions: (container) -> width = parseInt(container.style.width) height = parseInt(container.style.height) [width, height] clear: () -> @r.clear()
[ { "context": "### \n\tPantaRhei.js v 0.2.1\n\t\n\t(c) 2012 Federico Weber\n\tdistributed under the MIT license.\n\tfedericowebe", "end": 53, "score": 0.9998787045478821, "start": 39, "tag": "NAME", "value": "Federico Weber" } ]
src/PantaRhei.coffee
SonoIo/PantaRhei
3
### PantaRhei.js v 0.2.1 (c) 2012 Federico Weber distributed under the MIT license. federicoweber](http://federicoweber.com) ### # save a reference to the global object root = this # Define the top-level namespace PantaRhei = {} # require underscore and backbone for testing if (exports?) PantaRhei = exports; _ = require 'underscore' Backbone = require 'backbone' # check for backbone existence in the browser if root.Backbone? Backbone = root.Backbone _ = root._ # if backbone is missing throw an error if Backbone is undefined throw "Please import Backbone to use this library" # Nest top-level namespace into Backbone root.PantaRhei = PantaRhei VERSION = PantaRhei.VERSION = "0.2.1" # ## Flow # # The purpose of a **Flow** is to ease the declaration and execution # of a chain of consecutive tasks. Like preparing the data for a new page. # # The Flow will take care of extecuting the various # workers in the given order. # # It is possible to directly pass to the constructor the queue # If the id is not provided it will generate an uniq one Flow = class PantaRhei.Flow constructor: (@id = _.uniqueId('flow_'), @queue = new Array()) -> @_currentWorker = {} # assign an uniq name ad id to the workers @_naming worker for worker in @queue # return the Flow to enable cascade coding return this # ### Methods # #### use # This method is used to append a new worker in the queue # it will throw an error if the worker is noth properly structured use: (worker) -> if _.isFunction(worker.run) or _.isFunction(worker) @_cacheFlow worker @_naming worker @queue.push worker else throw new Error "Provide a proper worker" # return the Flow to enable cascade coding return this # ### check # This is used to add a test worker on the queue. # It will test the provides key and value pairs against the shared object. # If the test do faile the flow will be interrupted. # As sole parameter it accept an object. check: (valuesToTest)-> worker = new ValueChecker(valuesToTest) @_cacheFlow worker @_naming worker @queue.push worker return this # ### run # This is the method used to actually run the flow # if the @shared object is not provided it create an empty one run: (@shared = {}) -> if @queue.length is 0 throw new Error "The workers queue is empty" else @_paused = false # create a running copy of the queue. This is usefull to allow multiple consecutive run. @_runningQueue = _.clone @queue # reverse the queueu to run everthing int the proper order @_runningQueue.reverse() # fire the run event @trigger('run', @shared) # run the first worker @_next() # return the Flow to enable cascade coding return this # #### Pause # Simply pause the flow pause: -> @_paused = true @trigger('pause', @shared) # return the Flow to enable cascade coding return this # #### Resume # Resume a paused Flow resume: -> @_paused = false @trigger('resume', @shared) @_next() # return the Flow to enable cascade coding return this # #### Terminate # This is used to interrupt the flow at will; it will empty the running queue and throw a **terminate** and a **done** event. terminate: -> @_runningQueue = [] @trigger('terminate', @shared) @_next() # return the Flow to enable cascade coding return this # kill: -> # # return the Flow to enable cascade coding # return this # #### _cacheFlow # this is an internal function to store a reference to the flow into the worker _cacheFlow: (worker) -> worker._flow = this # #### _naming # this is an internal function to an name and an id to the worker to ease debugging # the given name is equal to the worker id _naming: (worker) -> # add the id if it's not provided unless worker.id? if !uniqId? uniqId = _.uniqueId('worker_') worker.id = uniqId # #### _next # this private method is used to actually run the worker # it's also passed as the **next** callback to each worker _next: (error) -> # if an error is passed in fire the error event and pause the flow if error @pause() @trigger('error', error, @_currentWorker.id) else # kill the previous worker if @_currentWorker and _.isFunction @_currentWorker.kill @_currentWorker.kill() # run the worker queue if @_runningQueue.length > 0 @_currentWorker = @_runningQueue.pop() # run the worker if it provide the run method if @_currentWorker and _.isFunction @_currentWorker.run cNext = _.bind(@_next, this) @trigger('step', @shared, @_currentWorker) @_currentWorker.run(@shared, cNext) # run the worker if it's a function else if @_currentWorker and _.isFunction @_currentWorker @trigger('step', @shared, @_currentWorker) cNext = _.bind(@_next, this) @_currentWorker(@shared, cNext) else throw new Error "The #{@_currentWorker.id} cannot be executed" # fire the **complete** event if the queue have been succesfully runned else # TODO: set the app as notBusy @trigger('complete', @shared) # enable events for the Flow _.extend(Flow.prototype, Backbone.Events) # ## Worker # # define the Worker Worker = class PantaRhei.Worker constructor: (@id = _.uniqueId('worker_')) -> # ### Attributes # #### _flow # This is a cached reference to the flow to which the worker belong and it's setted by the Flow _flow: undefined # ### Methods # #### run # Used by the flow to execute the worker. # It's meant to be overridden, if not it will pass an error to the flow # It accept the following mandatory arguments: # # - **shared** object, which purpose is to act as a vehicle of data among the various worker; # - **next** to call next step of the flow run: (@shared, @next) -> # run the next worker @next(new Error('run must be overridden')) # #### kill # This is runned by the Flow before running the next worker # It's meant to be overridden, if not it will throw an error kill: -> throw new ReferenceError "kill must be overridden " _.extend(Worker.prototype, Backbone.Events) # ### Value Checker # This is a special worker that is automatically created by the Flow.check method. # The only required attribute is @valuesToTest object that contains all the key value pairs to test. # If any of the test fail the worker will interrupt the flow class ValueChecker extends Worker constructor: (@valuesToTest, @id = _.uniqueId('valueChecker_')) -> run: (shared, next) -> checkValues = _.chain(@valuesToTest) .pairs() .map( (el)-> if shared[el[0]] is el[1] then true else false ) .value() if _.indexOf(checkValues, false) > -1 @_flow.terminate() else next() kill: -> # --- # Borrowed the Backbone style extend Flow.extend = Worker.extend = Backbone.View.extend
114730
### PantaRhei.js v 0.2.1 (c) 2012 <NAME> distributed under the MIT license. federicoweber](http://federicoweber.com) ### # save a reference to the global object root = this # Define the top-level namespace PantaRhei = {} # require underscore and backbone for testing if (exports?) PantaRhei = exports; _ = require 'underscore' Backbone = require 'backbone' # check for backbone existence in the browser if root.Backbone? Backbone = root.Backbone _ = root._ # if backbone is missing throw an error if Backbone is undefined throw "Please import Backbone to use this library" # Nest top-level namespace into Backbone root.PantaRhei = PantaRhei VERSION = PantaRhei.VERSION = "0.2.1" # ## Flow # # The purpose of a **Flow** is to ease the declaration and execution # of a chain of consecutive tasks. Like preparing the data for a new page. # # The Flow will take care of extecuting the various # workers in the given order. # # It is possible to directly pass to the constructor the queue # If the id is not provided it will generate an uniq one Flow = class PantaRhei.Flow constructor: (@id = _.uniqueId('flow_'), @queue = new Array()) -> @_currentWorker = {} # assign an uniq name ad id to the workers @_naming worker for worker in @queue # return the Flow to enable cascade coding return this # ### Methods # #### use # This method is used to append a new worker in the queue # it will throw an error if the worker is noth properly structured use: (worker) -> if _.isFunction(worker.run) or _.isFunction(worker) @_cacheFlow worker @_naming worker @queue.push worker else throw new Error "Provide a proper worker" # return the Flow to enable cascade coding return this # ### check # This is used to add a test worker on the queue. # It will test the provides key and value pairs against the shared object. # If the test do faile the flow will be interrupted. # As sole parameter it accept an object. check: (valuesToTest)-> worker = new ValueChecker(valuesToTest) @_cacheFlow worker @_naming worker @queue.push worker return this # ### run # This is the method used to actually run the flow # if the @shared object is not provided it create an empty one run: (@shared = {}) -> if @queue.length is 0 throw new Error "The workers queue is empty" else @_paused = false # create a running copy of the queue. This is usefull to allow multiple consecutive run. @_runningQueue = _.clone @queue # reverse the queueu to run everthing int the proper order @_runningQueue.reverse() # fire the run event @trigger('run', @shared) # run the first worker @_next() # return the Flow to enable cascade coding return this # #### Pause # Simply pause the flow pause: -> @_paused = true @trigger('pause', @shared) # return the Flow to enable cascade coding return this # #### Resume # Resume a paused Flow resume: -> @_paused = false @trigger('resume', @shared) @_next() # return the Flow to enable cascade coding return this # #### Terminate # This is used to interrupt the flow at will; it will empty the running queue and throw a **terminate** and a **done** event. terminate: -> @_runningQueue = [] @trigger('terminate', @shared) @_next() # return the Flow to enable cascade coding return this # kill: -> # # return the Flow to enable cascade coding # return this # #### _cacheFlow # this is an internal function to store a reference to the flow into the worker _cacheFlow: (worker) -> worker._flow = this # #### _naming # this is an internal function to an name and an id to the worker to ease debugging # the given name is equal to the worker id _naming: (worker) -> # add the id if it's not provided unless worker.id? if !uniqId? uniqId = _.uniqueId('worker_') worker.id = uniqId # #### _next # this private method is used to actually run the worker # it's also passed as the **next** callback to each worker _next: (error) -> # if an error is passed in fire the error event and pause the flow if error @pause() @trigger('error', error, @_currentWorker.id) else # kill the previous worker if @_currentWorker and _.isFunction @_currentWorker.kill @_currentWorker.kill() # run the worker queue if @_runningQueue.length > 0 @_currentWorker = @_runningQueue.pop() # run the worker if it provide the run method if @_currentWorker and _.isFunction @_currentWorker.run cNext = _.bind(@_next, this) @trigger('step', @shared, @_currentWorker) @_currentWorker.run(@shared, cNext) # run the worker if it's a function else if @_currentWorker and _.isFunction @_currentWorker @trigger('step', @shared, @_currentWorker) cNext = _.bind(@_next, this) @_currentWorker(@shared, cNext) else throw new Error "The #{@_currentWorker.id} cannot be executed" # fire the **complete** event if the queue have been succesfully runned else # TODO: set the app as notBusy @trigger('complete', @shared) # enable events for the Flow _.extend(Flow.prototype, Backbone.Events) # ## Worker # # define the Worker Worker = class PantaRhei.Worker constructor: (@id = _.uniqueId('worker_')) -> # ### Attributes # #### _flow # This is a cached reference to the flow to which the worker belong and it's setted by the Flow _flow: undefined # ### Methods # #### run # Used by the flow to execute the worker. # It's meant to be overridden, if not it will pass an error to the flow # It accept the following mandatory arguments: # # - **shared** object, which purpose is to act as a vehicle of data among the various worker; # - **next** to call next step of the flow run: (@shared, @next) -> # run the next worker @next(new Error('run must be overridden')) # #### kill # This is runned by the Flow before running the next worker # It's meant to be overridden, if not it will throw an error kill: -> throw new ReferenceError "kill must be overridden " _.extend(Worker.prototype, Backbone.Events) # ### Value Checker # This is a special worker that is automatically created by the Flow.check method. # The only required attribute is @valuesToTest object that contains all the key value pairs to test. # If any of the test fail the worker will interrupt the flow class ValueChecker extends Worker constructor: (@valuesToTest, @id = _.uniqueId('valueChecker_')) -> run: (shared, next) -> checkValues = _.chain(@valuesToTest) .pairs() .map( (el)-> if shared[el[0]] is el[1] then true else false ) .value() if _.indexOf(checkValues, false) > -1 @_flow.terminate() else next() kill: -> # --- # Borrowed the Backbone style extend Flow.extend = Worker.extend = Backbone.View.extend
true
### PantaRhei.js v 0.2.1 (c) 2012 PI:NAME:<NAME>END_PI distributed under the MIT license. federicoweber](http://federicoweber.com) ### # save a reference to the global object root = this # Define the top-level namespace PantaRhei = {} # require underscore and backbone for testing if (exports?) PantaRhei = exports; _ = require 'underscore' Backbone = require 'backbone' # check for backbone existence in the browser if root.Backbone? Backbone = root.Backbone _ = root._ # if backbone is missing throw an error if Backbone is undefined throw "Please import Backbone to use this library" # Nest top-level namespace into Backbone root.PantaRhei = PantaRhei VERSION = PantaRhei.VERSION = "0.2.1" # ## Flow # # The purpose of a **Flow** is to ease the declaration and execution # of a chain of consecutive tasks. Like preparing the data for a new page. # # The Flow will take care of extecuting the various # workers in the given order. # # It is possible to directly pass to the constructor the queue # If the id is not provided it will generate an uniq one Flow = class PantaRhei.Flow constructor: (@id = _.uniqueId('flow_'), @queue = new Array()) -> @_currentWorker = {} # assign an uniq name ad id to the workers @_naming worker for worker in @queue # return the Flow to enable cascade coding return this # ### Methods # #### use # This method is used to append a new worker in the queue # it will throw an error if the worker is noth properly structured use: (worker) -> if _.isFunction(worker.run) or _.isFunction(worker) @_cacheFlow worker @_naming worker @queue.push worker else throw new Error "Provide a proper worker" # return the Flow to enable cascade coding return this # ### check # This is used to add a test worker on the queue. # It will test the provides key and value pairs against the shared object. # If the test do faile the flow will be interrupted. # As sole parameter it accept an object. check: (valuesToTest)-> worker = new ValueChecker(valuesToTest) @_cacheFlow worker @_naming worker @queue.push worker return this # ### run # This is the method used to actually run the flow # if the @shared object is not provided it create an empty one run: (@shared = {}) -> if @queue.length is 0 throw new Error "The workers queue is empty" else @_paused = false # create a running copy of the queue. This is usefull to allow multiple consecutive run. @_runningQueue = _.clone @queue # reverse the queueu to run everthing int the proper order @_runningQueue.reverse() # fire the run event @trigger('run', @shared) # run the first worker @_next() # return the Flow to enable cascade coding return this # #### Pause # Simply pause the flow pause: -> @_paused = true @trigger('pause', @shared) # return the Flow to enable cascade coding return this # #### Resume # Resume a paused Flow resume: -> @_paused = false @trigger('resume', @shared) @_next() # return the Flow to enable cascade coding return this # #### Terminate # This is used to interrupt the flow at will; it will empty the running queue and throw a **terminate** and a **done** event. terminate: -> @_runningQueue = [] @trigger('terminate', @shared) @_next() # return the Flow to enable cascade coding return this # kill: -> # # return the Flow to enable cascade coding # return this # #### _cacheFlow # this is an internal function to store a reference to the flow into the worker _cacheFlow: (worker) -> worker._flow = this # #### _naming # this is an internal function to an name and an id to the worker to ease debugging # the given name is equal to the worker id _naming: (worker) -> # add the id if it's not provided unless worker.id? if !uniqId? uniqId = _.uniqueId('worker_') worker.id = uniqId # #### _next # this private method is used to actually run the worker # it's also passed as the **next** callback to each worker _next: (error) -> # if an error is passed in fire the error event and pause the flow if error @pause() @trigger('error', error, @_currentWorker.id) else # kill the previous worker if @_currentWorker and _.isFunction @_currentWorker.kill @_currentWorker.kill() # run the worker queue if @_runningQueue.length > 0 @_currentWorker = @_runningQueue.pop() # run the worker if it provide the run method if @_currentWorker and _.isFunction @_currentWorker.run cNext = _.bind(@_next, this) @trigger('step', @shared, @_currentWorker) @_currentWorker.run(@shared, cNext) # run the worker if it's a function else if @_currentWorker and _.isFunction @_currentWorker @trigger('step', @shared, @_currentWorker) cNext = _.bind(@_next, this) @_currentWorker(@shared, cNext) else throw new Error "The #{@_currentWorker.id} cannot be executed" # fire the **complete** event if the queue have been succesfully runned else # TODO: set the app as notBusy @trigger('complete', @shared) # enable events for the Flow _.extend(Flow.prototype, Backbone.Events) # ## Worker # # define the Worker Worker = class PantaRhei.Worker constructor: (@id = _.uniqueId('worker_')) -> # ### Attributes # #### _flow # This is a cached reference to the flow to which the worker belong and it's setted by the Flow _flow: undefined # ### Methods # #### run # Used by the flow to execute the worker. # It's meant to be overridden, if not it will pass an error to the flow # It accept the following mandatory arguments: # # - **shared** object, which purpose is to act as a vehicle of data among the various worker; # - **next** to call next step of the flow run: (@shared, @next) -> # run the next worker @next(new Error('run must be overridden')) # #### kill # This is runned by the Flow before running the next worker # It's meant to be overridden, if not it will throw an error kill: -> throw new ReferenceError "kill must be overridden " _.extend(Worker.prototype, Backbone.Events) # ### Value Checker # This is a special worker that is automatically created by the Flow.check method. # The only required attribute is @valuesToTest object that contains all the key value pairs to test. # If any of the test fail the worker will interrupt the flow class ValueChecker extends Worker constructor: (@valuesToTest, @id = _.uniqueId('valueChecker_')) -> run: (shared, next) -> checkValues = _.chain(@valuesToTest) .pairs() .map( (el)-> if shared[el[0]] is el[1] then true else false ) .value() if _.indexOf(checkValues, false) > -1 @_flow.terminate() else next() kill: -> # --- # Borrowed the Backbone style extend Flow.extend = Worker.extend = Backbone.View.extend
[ { "context": "coplayer - v0.0.0 - 2015-1-19\n# Copyright (c) 2015 Koki Takahashi\n# Licensed under the MIT license.\n###\n\n((window, ", "end": 90, "score": 0.9998369216918945, "start": 76, "tag": "NAME", "value": "Koki Takahashi" } ]
test/test.coffee
hakatashi/HTML5-niconicoplayer
5
###! videojs-HTML5-niconicoplayer - v0.0.0 - 2015-1-19 # Copyright (c) 2015 Koki Takahashi # Licensed under the MIT license. ### ((window, videojs, Q) -> 'use strict' realIsHtmlSupported = undefined player = undefined Q.module 'videojs-HTML5-niconicoplayer', setup: -> # force HTML support so the tests run in a reasonable # environment under phantomjs realIsHtmlSupported = videojs.Html5.isSupported videojs.Html5.isSupported = -> true # create a video element video = document.createElement('video') document.querySelector('#qunit-fixture').appendChild video # create a video.js player player = videojs(video) # initialize the plugin with the default options player.HTML5Niconicoplayer() teardown: -> videojs.Html5.isSupported = realIsHtmlSupported Q.test 'registers itself', -> Q.ok player.HTML5Niconicoplayer, 'registered the plugin' ) window, window.videojs, window.QUnit
218545
###! videojs-HTML5-niconicoplayer - v0.0.0 - 2015-1-19 # Copyright (c) 2015 <NAME> # Licensed under the MIT license. ### ((window, videojs, Q) -> 'use strict' realIsHtmlSupported = undefined player = undefined Q.module 'videojs-HTML5-niconicoplayer', setup: -> # force HTML support so the tests run in a reasonable # environment under phantomjs realIsHtmlSupported = videojs.Html5.isSupported videojs.Html5.isSupported = -> true # create a video element video = document.createElement('video') document.querySelector('#qunit-fixture').appendChild video # create a video.js player player = videojs(video) # initialize the plugin with the default options player.HTML5Niconicoplayer() teardown: -> videojs.Html5.isSupported = realIsHtmlSupported Q.test 'registers itself', -> Q.ok player.HTML5Niconicoplayer, 'registered the plugin' ) window, window.videojs, window.QUnit
true
###! videojs-HTML5-niconicoplayer - v0.0.0 - 2015-1-19 # Copyright (c) 2015 PI:NAME:<NAME>END_PI # Licensed under the MIT license. ### ((window, videojs, Q) -> 'use strict' realIsHtmlSupported = undefined player = undefined Q.module 'videojs-HTML5-niconicoplayer', setup: -> # force HTML support so the tests run in a reasonable # environment under phantomjs realIsHtmlSupported = videojs.Html5.isSupported videojs.Html5.isSupported = -> true # create a video element video = document.createElement('video') document.querySelector('#qunit-fixture').appendChild video # create a video.js player player = videojs(video) # initialize the plugin with the default options player.HTML5Niconicoplayer() teardown: -> videojs.Html5.isSupported = realIsHtmlSupported Q.test 'registers itself', -> Q.ok player.HTML5Niconicoplayer, 'registered the plugin' ) window, window.videojs, window.QUnit
[ { "context": "e './common'\n\ncommon.setup()\n\n\ncasper.test.begin \"Kyle and Jan crew uniqueness\", (test) ->\n common.wa", "end": 69, "score": 0.998512864112854, "start": 65, "tag": "NAME", "value": "Kyle" }, { "context": "mon'\n\ncommon.setup()\n\n\ncasper.test.begin \"Kyle an...
tests/test_rebel_aces.coffee
strikegun/xwing
0
common = require './common' common.setup() casper.test.begin "Kyle and Jan crew uniqueness", (test) -> common.waitForStartup('#rebel-builder') common.createList('#rebel-builder', [ { ship: 'YT-1300' pilot: 'Chewbacca' upgrades: [ null null "Kyle Katarn" "Jan Ors" null null ] } { ship: 'HWK-290' pilot: 'Rebel Operative' upgrades: [ ] } ]) # Can't add Kyle or Jan in their own ships common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForShipIndex 2} #{common.selectorForPilotDropdown}", 'Kyle Katarn') common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForShipIndex 2} #{common.selectorForPilotDropdown}", 'Jan Ors') common.removeShip('#rebel-builder', 1) common.removeShip('#rebel-builder', 1) common.createList('#rebel-builder', [ { ship: 'HWK-290' pilot: 'Kyle Katarn' upgrades: [ null null null null null ] } { ship: 'HWK-290' pilot: 'Jan Ors' upgrades: [ null null null null null ] } ]) # Can't put Kyle or Jan on Kyle's ship common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex 1, 3}", 'Kyle Katarn') common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex 1, 3}", 'Jan Ors') # Can't put Kyle or Jan on Jan's ship common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex 1, 3}", 'Kyle Katarn') common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex 1, 3}", 'Jan Ors') common.removeShip('#rebel-builder', 1) common.removeShip('#rebel-builder', 1) .run -> test.done() casper.test.begin "A-Wing Test Pilot", (test) -> common.waitForStartup('#rebel-builder') common.createList('#rebel-builder', [ { ship: 'A-Wing' pilot: 'Prototype Pilot' upgrades: [ ] } { ship: 'A-Wing' pilot: 'Green Squadron Pilot' upgrades: [ ] } { ship: 'X-Wing' pilot: 'Red Squadron Pilot' upgrades: [ ] } ]) .then -> # A-Wing only test.assertSelectorHasText "#rebel-builder #{common.selectorForUpgradeIndex 1, 2} .select2-choice", 'No Title', "Prototype Pilot has title field" test.assertSelectorHasText "#rebel-builder #{common.selectorForUpgradeIndex 2, 3} .select2-choice", 'No Title', "Green Squadron Pilot has title field" test.assertDoesntExist "#rebel-builder #{common.selectorForUpgradeIndex 3, 4}", "X-Wings have no titles (yet)" test.assertDoesntExist "#rebel-builder #{common.selectorForUpgradeIndex 2, 5}", "Green Squad doesn't have two elites by default" # Equippable on PS1+ only (no Prototype) common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex 1, 2}", 'A-Wing Test Pilot') common.addUpgrade('#rebel-builder', 2, 3, 'A-Wing Test Pilot') common.assertTotalPoints(test, '#rebel-builder', 59) # Can add two different elites common.addUpgrade('#rebel-builder', 2, 1, 'Adrenaline Rush') common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex 2, 5}", 'Adrenaline Rush') common.addUpgrade('#rebel-builder', 2, 5, 'Deadeye') common.assertTotalPoints(test, '#rebel-builder', 61) # Removing the title removes the elite slot common.removeUpgrade('#rebel-builder', 2, 3) .then -> test.assertDoesntExist "#rebel-builder #{common.selectorForUpgradeIndex 2, 5}", "Green Squad no longer has two elite slots" common.assertTotalPoints(test, '#rebel-builder', 60) common.removeShip('#rebel-builder', 1) common.removeShip('#rebel-builder', 1) common.removeShip('#rebel-builder', 1) .run -> test.done() casper.test.begin "A-Wing Test Pilot (German)", (test) -> common.waitForStartup('#rebel-builder') common.selectLanguage('Deutsch') common.createList('#rebel-builder', [ { ship: 'A-Wing' pilot: 'Testpilot' upgrades: [ ] } { ship: 'A-Wing' pilot: 'Pilot der Grün-Staffel' upgrades: [ ] } { ship: 'X-Wing' pilot: 'Pilot der Rot-Staffel' upgrades: [ ] } ]) .then -> # A-Wing only test.assertSelectorHasText "#rebel-builder #{common.selectorForUpgradeIndex 1, 2} .select2-choice", 'kein Titel', "Prototype Pilot has title field" test.assertSelectorHasText "#rebel-builder #{common.selectorForUpgradeIndex 2, 3} .select2-choice", 'kein Titel', "Green Squadron Pilot has title field" test.assertDoesntExist "#rebel-builder #{common.selectorForUpgradeIndex 3, 4}", "X-Wings have no titles (yet)" test.assertDoesntExist "#rebel-builder #{common.selectorForUpgradeIndex 2, 5}", "Green Squad doesn't have two elites by default" # Equippable on PS1+ only (no Prototype) common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex 1, 2}", 'Erfahrener Testpilot') common.addUpgrade('#rebel-builder', 2, 3, 'Erfahrener Testpilot') common.assertTotalPoints(test, '#rebel-builder', 59) # Can add two different elites common.addUpgrade('#rebel-builder', 2, 1, 'Adrenalinschub') common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex 2, 5}", 'Adrenalinschub') common.addUpgrade('#rebel-builder', 2, 5, 'Meisterschütze') common.assertTotalPoints(test, '#rebel-builder', 61) # Removing the title removes the elite slot common.removeUpgrade('#rebel-builder', 2, 3) .then -> test.assertDoesntExist "#rebel-builder #{common.selectorForUpgradeIndex 2, 5}", "Green Squad no longer has two elite slots" common.assertTotalPoints(test, '#rebel-builder', 60) common.removeShip('#rebel-builder', 1) common.removeShip('#rebel-builder', 1) common.removeShip('#rebel-builder', 1) common.selectLanguage('English') .run -> test.done() casper.test.begin "A-Wing Test Pilot (Spanish)", (test) -> common.waitForStartup('#rebel-builder') common.selectLanguage('Español') common.createList('#rebel-builder', [ { ship: 'Ala-A' pilot: 'Piloto de pruebas' upgrades: [ ] } { ship: 'Ala-A' pilot: 'Piloto del escuadrón verde' upgrades: [ ] } { ship: 'Ala-X' pilot: 'Piloto del escuadrón rojo' upgrades: [ ] } ]) .then -> # A-Wing only test.assertSelectorHasText "#rebel-builder #{common.selectorForUpgradeIndex 1, 2} .select2-choice", 'Sin Título', "Prototype Pilot has title field" test.assertSelectorHasText "#rebel-builder #{common.selectorForUpgradeIndex 2, 3} .select2-choice", 'Sin Título', "Green Squadron Pilot has title field" test.assertDoesntExist "#rebel-builder #{common.selectorForUpgradeIndex 3, 4}", "X-Wings have no titles (yet)" test.assertDoesntExist "#rebel-builder #{common.selectorForUpgradeIndex 2, 5}", "Green Squad doesn't have two elites by default" # Equippable on PS1+ only (no Prototype) common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex 1, 2}", 'Piloto de Ala-A experimental') common.addUpgrade('#rebel-builder', 2, 3, 'Piloto de Ala-A experimental') common.assertTotalPoints(test, '#rebel-builder', 59) # Can add two different elites common.addUpgrade('#rebel-builder', 2, 1, 'Descarga de Adrenalina') common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex 2, 5}", 'Descarga de Adrenalina') common.addUpgrade('#rebel-builder', 2, 5, 'Certero') common.assertTotalPoints(test, '#rebel-builder', 61) # Removing the title removes the elite slot common.removeUpgrade('#rebel-builder', 2, 3) .then -> test.assertDoesntExist "#rebel-builder #{common.selectorForUpgradeIndex 2, 5}", "Green Squad no longer has two elite slots" common.assertTotalPoints(test, '#rebel-builder', 60) common.removeShip('#rebel-builder', 1) common.removeShip('#rebel-builder', 1) common.removeShip('#rebel-builder', 1) common.selectLanguage('English') .run -> test.done() casper.test.begin "Chardaan Refit", (test) -> common.waitForStartup('#rebel-builder') common.createList('#rebel-builder', [ { ship: 'A-Wing' pilot: 'Prototype Pilot' upgrades: [ ] } { ship: 'YT-1300' pilot: 'Lando Calrissian' upgrades: [ ] } { ship: 'Z-95 Headhunter' pilot: 'Bandit Squadron Pilot' upgrades: [ ] } ]) # A-Wing only common.assertNoMatch(test, "#rebel-builder #{common.selectorForUpgradeIndex 2, 2}", 'Chardaan Refit') common.assertNoMatch(test, "#rebel-builder #{common.selectorForUpgradeIndex 3, 1}", 'Chardaan Refit') common.addUpgrade('#rebel-builder', 1, 1, 'Chardaan Refit') # Negative points common.assertTotalPoints(test, '#rebel-builder', 71) common.removeShip('#rebel-builder', 1) common.removeShip('#rebel-builder', 1) common.removeShip('#rebel-builder', 1) # Empire ships shouldn't have it common.openEmpireBuilder() common.createList('#empire-builder', [ { ship: 'TIE Bomber' pilot: 'Gamma Squadron Pilot' upgrades: [ ] } { ship: 'Firespray-31' pilot: 'Bounty Hunter' upgrades: [ ] } { ship: 'TIE Advanced' pilot: 'Tempest Squadron Pilot' upgrades: [ ] } ]) common.assertNoMatch(test, "#empire-builder #{common.selectorForUpgradeIndex 1, 3}", 'Chardaan Refit') common.assertNoMatch(test, "#empire-builder #{common.selectorForUpgradeIndex 1, 4}", 'Chardaan Refit') common.assertNoMatch(test, "#empire-builder #{common.selectorForUpgradeIndex 2, 4}", 'Chardaan Refit') common.assertNoMatch(test, "#empire-builder #{common.selectorForUpgradeIndex 3, 1}", 'Chardaan Refit') common.removeShip('#empire-builder', 1) common.removeShip('#empire-builder', 1) common.removeShip('#empire-builder', 1) .run -> test.done() casper.test.begin "B-Wing/E2", (test) -> common.waitForStartup('#rebel-builder') common.createList('#rebel-builder', [ { ship: 'B-Wing' pilot: 'Blue Squadron Pilot' upgrades: [ ] } { ship: 'X-Wing' pilot: 'Red Squadron Pilot' upgrades: [ ] } ]) # B-Wing only common.assertNoMatch(test, "#rebel-builder #{common.selectorForUpgradeIndex 2, 3}", "B-Wing/E2") .then -> test.assertDoesntExist "#rebel-builder #{common.selectorForUpgradeIndex 1, 6}", "Blue Squad doesn't have crew by default" common.addUpgrade('#rebel-builder', 1, 5, 'B-Wing/E2') common.addUpgrade('#rebel-builder', 1, 6, 'Flight Instructor') common.assertTotalPoints(test, '#rebel-builder', 50) # Removing the modification removes the crew slot common.removeUpgrade('#rebel-builder', 1, 5) .then -> test.assertDoesntExist "#rebel-builder #{common.selectorForUpgradeIndex 1, 6}", "Blue Squad no longer has a crew slot" common.assertTotalPoints(test, '#rebel-builder', 45) common.removeShip('#rebel-builder', 1) common.removeShip('#rebel-builder', 1) .run -> test.done()
74991
common = require './common' common.setup() casper.test.begin "<NAME> and <NAME> crew uniqueness", (test) -> common.waitForStartup('#rebel-builder') common.createList('#rebel-builder', [ { ship: 'YT-1300' pilot: 'Chewbacca' upgrades: [ null null "<NAME>" "<NAME>" null null ] } { ship: 'HWK-290' pilot: 'Rebel Operative' upgrades: [ ] } ]) # Can't add <NAME> or <NAME> in their own ships common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForShipIndex 2} #{common.selectorForPilotDropdown}", '<NAME>') common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForShipIndex 2} #{common.selectorForPilotDropdown}", '<NAME>') common.removeShip('#rebel-builder', 1) common.removeShip('#rebel-builder', 1) common.createList('#rebel-builder', [ { ship: 'HWK-290' pilot: '<NAME>' upgrades: [ null null null null null ] } { ship: 'HWK-290' pilot: '<NAME>' upgrades: [ null null null null null ] } ]) # Can't put <NAME> or <NAME> on <NAME>'s ship common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex 1, 3}", '<NAME>') common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex 1, 3}", '<NAME>') # Can't put <NAME> or <NAME> on <NAME>'s ship common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex 1, 3}", '<NAME>') common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex 1, 3}", '<NAME>') common.removeShip('#rebel-builder', 1) common.removeShip('#rebel-builder', 1) .run -> test.done() casper.test.begin "A-Wing Test Pilot", (test) -> common.waitForStartup('#rebel-builder') common.createList('#rebel-builder', [ { ship: 'A-<NAME>ing' pilot: 'Prototype Pilot' upgrades: [ ] } { ship: 'A-<NAME>ing' pilot: 'Green Squadron Pilot' upgrades: [ ] } { ship: 'X-<NAME>ing' pilot: 'Red Squadron Pilot' upgrades: [ ] } ]) .then -> # A-Wing only test.assertSelectorHasText "#rebel-builder #{common.selectorForUpgradeIndex 1, 2} .select2-choice", 'No Title', "Prototype Pilot has title field" test.assertSelectorHasText "#rebel-builder #{common.selectorForUpgradeIndex 2, 3} .select2-choice", 'No Title', "Green Squadron Pilot has title field" test.assertDoesntExist "#rebel-builder #{common.selectorForUpgradeIndex 3, 4}", "X-Wings have no titles (yet)" test.assertDoesntExist "#rebel-builder #{common.selectorForUpgradeIndex 2, 5}", "Green Squad doesn't have two elites by default" # Equippable on PS1+ only (no Prototype) common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex 1, 2}", 'A-Wing Test Pilot') common.addUpgrade('#rebel-builder', 2, 3, 'A-Wing Test Pilot') common.assertTotalPoints(test, '#rebel-builder', 59) # Can add two different elites common.addUpgrade('#rebel-builder', 2, 1, 'Adrenaline Rush') common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex 2, 5}", 'Adrenaline Rush') common.addUpgrade('#rebel-builder', 2, 5, 'Deadeye') common.assertTotalPoints(test, '#rebel-builder', 61) # Removing the title removes the elite slot common.removeUpgrade('#rebel-builder', 2, 3) .then -> test.assertDoesntExist "#rebel-builder #{common.selectorForUpgradeIndex 2, 5}", "Green Squad no longer has two elite slots" common.assertTotalPoints(test, '#rebel-builder', 60) common.removeShip('#rebel-builder', 1) common.removeShip('#rebel-builder', 1) common.removeShip('#rebel-builder', 1) .run -> test.done() casper.test.begin "A-Wing Test Pilot (German)", (test) -> common.waitForStartup('#rebel-builder') common.selectLanguage('Deutsch') common.createList('#rebel-builder', [ { ship: 'A-Wing' pilot: 'Testpilot' upgrades: [ ] } { ship: 'A-Wing' pilot: 'Pilot der Grün-Staffel' upgrades: [ ] } { ship: 'X-Wing' pilot: 'Pilot der Rot-Staffel' upgrades: [ ] } ]) .then -> # A-Wing only test.assertSelectorHasText "#rebel-builder #{common.selectorForUpgradeIndex 1, 2} .select2-choice", 'kein Titel', "Prototype Pilot has title field" test.assertSelectorHasText "#rebel-builder #{common.selectorForUpgradeIndex 2, 3} .select2-choice", 'kein Titel', "Green Squadron Pilot has title field" test.assertDoesntExist "#rebel-builder #{common.selectorForUpgradeIndex 3, 4}", "X-Wings have no titles (yet)" test.assertDoesntExist "#rebel-builder #{common.selectorForUpgradeIndex 2, 5}", "Green Squad doesn't have two elites by default" # Equippable on PS1+ only (no Prototype) common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex 1, 2}", 'Erfahrener Testpilot') common.addUpgrade('#rebel-builder', 2, 3, 'Erfahrener Testpilot') common.assertTotalPoints(test, '#rebel-builder', 59) # Can add two different elites common.addUpgrade('#rebel-builder', 2, 1, 'Ad<NAME>inschub') common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex 2, 5}", 'Adrenalinschub') common.addUpgrade('#rebel-builder', 2, 5, 'Me<NAME>ch<NAME>ze') common.assertTotalPoints(test, '#rebel-builder', 61) # Removing the title removes the elite slot common.removeUpgrade('#rebel-builder', 2, 3) .then -> test.assertDoesntExist "#rebel-builder #{common.selectorForUpgradeIndex 2, 5}", "Green Squad no longer has two elite slots" common.assertTotalPoints(test, '#rebel-builder', 60) common.removeShip('#rebel-builder', 1) common.removeShip('#rebel-builder', 1) common.removeShip('#rebel-builder', 1) common.selectLanguage('English') .run -> test.done() casper.test.begin "A-Wing Test Pilot (Spanish)", (test) -> common.waitForStartup('#rebel-builder') common.selectLanguage('Español') common.createList('#rebel-builder', [ { ship: 'Ala-A' pilot: 'Piloto de pruebas' upgrades: [ ] } { ship: 'Ala-A' pilot: 'Piloto del escuadrón verde' upgrades: [ ] } { ship: 'Ala-X' pilot: 'Piloto del escuadrón rojo' upgrades: [ ] } ]) .then -> # A-Wing only test.assertSelectorHasText "#rebel-builder #{common.selectorForUpgradeIndex 1, 2} .select2-choice", 'Sin Título', "Prototype Pilot has title field" test.assertSelectorHasText "#rebel-builder #{common.selectorForUpgradeIndex 2, 3} .select2-choice", 'Sin Título', "Green Squadron Pilot has title field" test.assertDoesntExist "#rebel-builder #{common.selectorForUpgradeIndex 3, 4}", "X-Wings have no titles (yet)" test.assertDoesntExist "#rebel-builder #{common.selectorForUpgradeIndex 2, 5}", "Green Squad doesn't have two elites by default" # Equippable on PS1+ only (no Prototype) common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex 1, 2}", 'Piloto de Ala-A experimental') common.addUpgrade('#rebel-builder', 2, 3, 'Piloto de Ala-A experimental') common.assertTotalPoints(test, '#rebel-builder', 59) # Can add two different elites common.addUpgrade('#rebel-builder', 2, 1, 'Descarga de Adrenalina') common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex 2, 5}", 'Descarga de Adrenalina') common.addUpgrade('#rebel-builder', 2, 5, 'Certero') common.assertTotalPoints(test, '#rebel-builder', 61) # Removing the title removes the elite slot common.removeUpgrade('#rebel-builder', 2, 3) .then -> test.assertDoesntExist "#rebel-builder #{common.selectorForUpgradeIndex 2, 5}", "Green Squad no longer has two elite slots" common.assertTotalPoints(test, '#rebel-builder', 60) common.removeShip('#rebel-builder', 1) common.removeShip('#rebel-builder', 1) common.removeShip('#rebel-builder', 1) common.selectLanguage('English') .run -> test.done() casper.test.begin "Chardaan Refit", (test) -> common.waitForStartup('#rebel-builder') common.createList('#rebel-builder', [ { ship: 'A-Wing' pilot: 'Prototype Pilot' upgrades: [ ] } { ship: 'YT-1300' pilot: 'Lando Calrissian' upgrades: [ ] } { ship: 'Z-95 Headhunter' pilot: 'Bandit Squadron Pilot' upgrades: [ ] } ]) # A-Wing only common.assertNoMatch(test, "#rebel-builder #{common.selectorForUpgradeIndex 2, 2}", 'Chardaan Refit') common.assertNoMatch(test, "#rebel-builder #{common.selectorForUpgradeIndex 3, 1}", 'Chardaan Refit') common.addUpgrade('#rebel-builder', 1, 1, 'Chardaan Refit') # Negative points common.assertTotalPoints(test, '#rebel-builder', 71) common.removeShip('#rebel-builder', 1) common.removeShip('#rebel-builder', 1) common.removeShip('#rebel-builder', 1) # Empire ships shouldn't have it common.openEmpireBuilder() common.createList('#empire-builder', [ { ship: 'TIE Bomber' pilot: 'Gamma Squadron Pilot' upgrades: [ ] } { ship: 'Firespray-31' pilot: 'Bounty Hunter' upgrades: [ ] } { ship: 'TIE Advanced' pilot: 'Tempest Squadron Pilot' upgrades: [ ] } ]) common.assertNoMatch(test, "#empire-builder #{common.selectorForUpgradeIndex 1, 3}", 'Chardaan Refit') common.assertNoMatch(test, "#empire-builder #{common.selectorForUpgradeIndex 1, 4}", 'Chardaan Refit') common.assertNoMatch(test, "#empire-builder #{common.selectorForUpgradeIndex 2, 4}", 'Chardaan Refit') common.assertNoMatch(test, "#empire-builder #{common.selectorForUpgradeIndex 3, 1}", 'Chardaan Refit') common.removeShip('#empire-builder', 1) common.removeShip('#empire-builder', 1) common.removeShip('#empire-builder', 1) .run -> test.done() casper.test.begin "B-Wing/E2", (test) -> common.waitForStartup('#rebel-builder') common.createList('#rebel-builder', [ { ship: 'B-Wing' pilot: 'Blue Squadron Pilot' upgrades: [ ] } { ship: 'X-Wing' pilot: 'Red Squadron Pilot' upgrades: [ ] } ]) # B-Wing only common.assertNoMatch(test, "#rebel-builder #{common.selectorForUpgradeIndex 2, 3}", "B-Wing/E2") .then -> test.assertDoesntExist "#rebel-builder #{common.selectorForUpgradeIndex 1, 6}", "Blue Squad doesn't have crew by default" common.addUpgrade('#rebel-builder', 1, 5, 'B-Wing/E2') common.addUpgrade('#rebel-builder', 1, 6, 'Flight Instructor') common.assertTotalPoints(test, '#rebel-builder', 50) # Removing the modification removes the crew slot common.removeUpgrade('#rebel-builder', 1, 5) .then -> test.assertDoesntExist "#rebel-builder #{common.selectorForUpgradeIndex 1, 6}", "Blue Squad no longer has a crew slot" common.assertTotalPoints(test, '#rebel-builder', 45) common.removeShip('#rebel-builder', 1) common.removeShip('#rebel-builder', 1) .run -> test.done()
true
common = require './common' common.setup() casper.test.begin "PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI crew uniqueness", (test) -> common.waitForStartup('#rebel-builder') common.createList('#rebel-builder', [ { ship: 'YT-1300' pilot: 'Chewbacca' upgrades: [ null null "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" null null ] } { ship: 'HWK-290' pilot: 'Rebel Operative' upgrades: [ ] } ]) # Can't add PI:NAME:<NAME>END_PI or PI:NAME:<NAME>END_PI in their own ships common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForShipIndex 2} #{common.selectorForPilotDropdown}", 'PI:NAME:<NAME>END_PI') common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForShipIndex 2} #{common.selectorForPilotDropdown}", 'PI:NAME:<NAME>END_PI') common.removeShip('#rebel-builder', 1) common.removeShip('#rebel-builder', 1) common.createList('#rebel-builder', [ { ship: 'HWK-290' pilot: 'PI:NAME:<NAME>END_PI' upgrades: [ null null null null null ] } { ship: 'HWK-290' pilot: 'PI:NAME:<NAME>END_PI' upgrades: [ null null null null null ] } ]) # Can't put PI:NAME:<NAME>END_PI or PI:NAME:<NAME>END_PI on PI:NAME:<NAME>END_PI's ship common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex 1, 3}", 'PI:NAME:<NAME>END_PI') common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex 1, 3}", 'PI:NAME:<NAME>END_PI') # Can't put PI:NAME:<NAME>END_PI or PI:NAME:<NAME>END_PI on PI:NAME:<NAME>END_PI's ship common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex 1, 3}", 'PI:NAME:<NAME>END_PI') common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex 1, 3}", 'PI:NAME:<NAME>END_PI') common.removeShip('#rebel-builder', 1) common.removeShip('#rebel-builder', 1) .run -> test.done() casper.test.begin "A-Wing Test Pilot", (test) -> common.waitForStartup('#rebel-builder') common.createList('#rebel-builder', [ { ship: 'A-PI:NAME:<NAME>END_PIing' pilot: 'Prototype Pilot' upgrades: [ ] } { ship: 'A-PI:NAME:<NAME>END_PIing' pilot: 'Green Squadron Pilot' upgrades: [ ] } { ship: 'X-PI:NAME:<NAME>END_PIing' pilot: 'Red Squadron Pilot' upgrades: [ ] } ]) .then -> # A-Wing only test.assertSelectorHasText "#rebel-builder #{common.selectorForUpgradeIndex 1, 2} .select2-choice", 'No Title', "Prototype Pilot has title field" test.assertSelectorHasText "#rebel-builder #{common.selectorForUpgradeIndex 2, 3} .select2-choice", 'No Title', "Green Squadron Pilot has title field" test.assertDoesntExist "#rebel-builder #{common.selectorForUpgradeIndex 3, 4}", "X-Wings have no titles (yet)" test.assertDoesntExist "#rebel-builder #{common.selectorForUpgradeIndex 2, 5}", "Green Squad doesn't have two elites by default" # Equippable on PS1+ only (no Prototype) common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex 1, 2}", 'A-Wing Test Pilot') common.addUpgrade('#rebel-builder', 2, 3, 'A-Wing Test Pilot') common.assertTotalPoints(test, '#rebel-builder', 59) # Can add two different elites common.addUpgrade('#rebel-builder', 2, 1, 'Adrenaline Rush') common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex 2, 5}", 'Adrenaline Rush') common.addUpgrade('#rebel-builder', 2, 5, 'Deadeye') common.assertTotalPoints(test, '#rebel-builder', 61) # Removing the title removes the elite slot common.removeUpgrade('#rebel-builder', 2, 3) .then -> test.assertDoesntExist "#rebel-builder #{common.selectorForUpgradeIndex 2, 5}", "Green Squad no longer has two elite slots" common.assertTotalPoints(test, '#rebel-builder', 60) common.removeShip('#rebel-builder', 1) common.removeShip('#rebel-builder', 1) common.removeShip('#rebel-builder', 1) .run -> test.done() casper.test.begin "A-Wing Test Pilot (German)", (test) -> common.waitForStartup('#rebel-builder') common.selectLanguage('Deutsch') common.createList('#rebel-builder', [ { ship: 'A-Wing' pilot: 'Testpilot' upgrades: [ ] } { ship: 'A-Wing' pilot: 'Pilot der Grün-Staffel' upgrades: [ ] } { ship: 'X-Wing' pilot: 'Pilot der Rot-Staffel' upgrades: [ ] } ]) .then -> # A-Wing only test.assertSelectorHasText "#rebel-builder #{common.selectorForUpgradeIndex 1, 2} .select2-choice", 'kein Titel', "Prototype Pilot has title field" test.assertSelectorHasText "#rebel-builder #{common.selectorForUpgradeIndex 2, 3} .select2-choice", 'kein Titel', "Green Squadron Pilot has title field" test.assertDoesntExist "#rebel-builder #{common.selectorForUpgradeIndex 3, 4}", "X-Wings have no titles (yet)" test.assertDoesntExist "#rebel-builder #{common.selectorForUpgradeIndex 2, 5}", "Green Squad doesn't have two elites by default" # Equippable on PS1+ only (no Prototype) common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex 1, 2}", 'Erfahrener Testpilot') common.addUpgrade('#rebel-builder', 2, 3, 'Erfahrener Testpilot') common.assertTotalPoints(test, '#rebel-builder', 59) # Can add two different elites common.addUpgrade('#rebel-builder', 2, 1, 'AdPI:NAME:<NAME>END_PIinschub') common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex 2, 5}", 'Adrenalinschub') common.addUpgrade('#rebel-builder', 2, 5, 'MePI:NAME:<NAME>END_PIchPI:NAME:<NAME>END_PIze') common.assertTotalPoints(test, '#rebel-builder', 61) # Removing the title removes the elite slot common.removeUpgrade('#rebel-builder', 2, 3) .then -> test.assertDoesntExist "#rebel-builder #{common.selectorForUpgradeIndex 2, 5}", "Green Squad no longer has two elite slots" common.assertTotalPoints(test, '#rebel-builder', 60) common.removeShip('#rebel-builder', 1) common.removeShip('#rebel-builder', 1) common.removeShip('#rebel-builder', 1) common.selectLanguage('English') .run -> test.done() casper.test.begin "A-Wing Test Pilot (Spanish)", (test) -> common.waitForStartup('#rebel-builder') common.selectLanguage('Español') common.createList('#rebel-builder', [ { ship: 'Ala-A' pilot: 'Piloto de pruebas' upgrades: [ ] } { ship: 'Ala-A' pilot: 'Piloto del escuadrón verde' upgrades: [ ] } { ship: 'Ala-X' pilot: 'Piloto del escuadrón rojo' upgrades: [ ] } ]) .then -> # A-Wing only test.assertSelectorHasText "#rebel-builder #{common.selectorForUpgradeIndex 1, 2} .select2-choice", 'Sin Título', "Prototype Pilot has title field" test.assertSelectorHasText "#rebel-builder #{common.selectorForUpgradeIndex 2, 3} .select2-choice", 'Sin Título', "Green Squadron Pilot has title field" test.assertDoesntExist "#rebel-builder #{common.selectorForUpgradeIndex 3, 4}", "X-Wings have no titles (yet)" test.assertDoesntExist "#rebel-builder #{common.selectorForUpgradeIndex 2, 5}", "Green Squad doesn't have two elites by default" # Equippable on PS1+ only (no Prototype) common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex 1, 2}", 'Piloto de Ala-A experimental') common.addUpgrade('#rebel-builder', 2, 3, 'Piloto de Ala-A experimental') common.assertTotalPoints(test, '#rebel-builder', 59) # Can add two different elites common.addUpgrade('#rebel-builder', 2, 1, 'Descarga de Adrenalina') common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex 2, 5}", 'Descarga de Adrenalina') common.addUpgrade('#rebel-builder', 2, 5, 'Certero') common.assertTotalPoints(test, '#rebel-builder', 61) # Removing the title removes the elite slot common.removeUpgrade('#rebel-builder', 2, 3) .then -> test.assertDoesntExist "#rebel-builder #{common.selectorForUpgradeIndex 2, 5}", "Green Squad no longer has two elite slots" common.assertTotalPoints(test, '#rebel-builder', 60) common.removeShip('#rebel-builder', 1) common.removeShip('#rebel-builder', 1) common.removeShip('#rebel-builder', 1) common.selectLanguage('English') .run -> test.done() casper.test.begin "Chardaan Refit", (test) -> common.waitForStartup('#rebel-builder') common.createList('#rebel-builder', [ { ship: 'A-Wing' pilot: 'Prototype Pilot' upgrades: [ ] } { ship: 'YT-1300' pilot: 'Lando Calrissian' upgrades: [ ] } { ship: 'Z-95 Headhunter' pilot: 'Bandit Squadron Pilot' upgrades: [ ] } ]) # A-Wing only common.assertNoMatch(test, "#rebel-builder #{common.selectorForUpgradeIndex 2, 2}", 'Chardaan Refit') common.assertNoMatch(test, "#rebel-builder #{common.selectorForUpgradeIndex 3, 1}", 'Chardaan Refit') common.addUpgrade('#rebel-builder', 1, 1, 'Chardaan Refit') # Negative points common.assertTotalPoints(test, '#rebel-builder', 71) common.removeShip('#rebel-builder', 1) common.removeShip('#rebel-builder', 1) common.removeShip('#rebel-builder', 1) # Empire ships shouldn't have it common.openEmpireBuilder() common.createList('#empire-builder', [ { ship: 'TIE Bomber' pilot: 'Gamma Squadron Pilot' upgrades: [ ] } { ship: 'Firespray-31' pilot: 'Bounty Hunter' upgrades: [ ] } { ship: 'TIE Advanced' pilot: 'Tempest Squadron Pilot' upgrades: [ ] } ]) common.assertNoMatch(test, "#empire-builder #{common.selectorForUpgradeIndex 1, 3}", 'Chardaan Refit') common.assertNoMatch(test, "#empire-builder #{common.selectorForUpgradeIndex 1, 4}", 'Chardaan Refit') common.assertNoMatch(test, "#empire-builder #{common.selectorForUpgradeIndex 2, 4}", 'Chardaan Refit') common.assertNoMatch(test, "#empire-builder #{common.selectorForUpgradeIndex 3, 1}", 'Chardaan Refit') common.removeShip('#empire-builder', 1) common.removeShip('#empire-builder', 1) common.removeShip('#empire-builder', 1) .run -> test.done() casper.test.begin "B-Wing/E2", (test) -> common.waitForStartup('#rebel-builder') common.createList('#rebel-builder', [ { ship: 'B-Wing' pilot: 'Blue Squadron Pilot' upgrades: [ ] } { ship: 'X-Wing' pilot: 'Red Squadron Pilot' upgrades: [ ] } ]) # B-Wing only common.assertNoMatch(test, "#rebel-builder #{common.selectorForUpgradeIndex 2, 3}", "B-Wing/E2") .then -> test.assertDoesntExist "#rebel-builder #{common.selectorForUpgradeIndex 1, 6}", "Blue Squad doesn't have crew by default" common.addUpgrade('#rebel-builder', 1, 5, 'B-Wing/E2') common.addUpgrade('#rebel-builder', 1, 6, 'Flight Instructor') common.assertTotalPoints(test, '#rebel-builder', 50) # Removing the modification removes the crew slot common.removeUpgrade('#rebel-builder', 1, 5) .then -> test.assertDoesntExist "#rebel-builder #{common.selectorForUpgradeIndex 1, 6}", "Blue Squad no longer has a crew slot" common.assertTotalPoints(test, '#rebel-builder', 45) common.removeShip('#rebel-builder', 1) common.removeShip('#rebel-builder', 1) .run -> test.done()
[ { "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.9998471140861511, "start": 57, "tag": "NAME", "value": "Mathieu Ledru" } ]
Common/Bin/Data/coffee/Cocos2D/Lang.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. ### cc.Lang = cc.Class.extend( _data: null _lang: null ctor: -> @_data = {} getLang: -> @_lang setLang: (lang) -> @_lang = lang get: (key) -> @_data[key] or key set: (key, value) -> @_data[key] = value addLang: (fileName) -> filePath = cpz.CommonPath + fileName switch @_lang when cc.sys.LANGUAGE_FRENCH then filePath += '-fr' when cc.sys.LANGUAGE_GERMAN then filePath += '-de' when cc.sys.LANGUAGE_ENGLISH then filePath += '-en' else filePath += '-en' dict = cc.loader.getRes filePath + '.json' for key, value of dict @set key, value if value @ ) cc.Lang.s_sharedLang = null cc.Lang.getInstance = -> unless @s_sharedLang @s_sharedLang = new cc.Lang() @s_sharedLang
23179
### 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. ### cc.Lang = cc.Class.extend( _data: null _lang: null ctor: -> @_data = {} getLang: -> @_lang setLang: (lang) -> @_lang = lang get: (key) -> @_data[key] or key set: (key, value) -> @_data[key] = value addLang: (fileName) -> filePath = cpz.CommonPath + fileName switch @_lang when cc.sys.LANGUAGE_FRENCH then filePath += '-fr' when cc.sys.LANGUAGE_GERMAN then filePath += '-de' when cc.sys.LANGUAGE_ENGLISH then filePath += '-en' else filePath += '-en' dict = cc.loader.getRes filePath + '.json' for key, value of dict @set key, value if value @ ) cc.Lang.s_sharedLang = null cc.Lang.getInstance = -> unless @s_sharedLang @s_sharedLang = new cc.Lang() @s_sharedLang
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. ### cc.Lang = cc.Class.extend( _data: null _lang: null ctor: -> @_data = {} getLang: -> @_lang setLang: (lang) -> @_lang = lang get: (key) -> @_data[key] or key set: (key, value) -> @_data[key] = value addLang: (fileName) -> filePath = cpz.CommonPath + fileName switch @_lang when cc.sys.LANGUAGE_FRENCH then filePath += '-fr' when cc.sys.LANGUAGE_GERMAN then filePath += '-de' when cc.sys.LANGUAGE_ENGLISH then filePath += '-en' else filePath += '-en' dict = cc.loader.getRes filePath + '.json' for key, value of dict @set key, value if value @ ) cc.Lang.s_sharedLang = null cc.Lang.getInstance = -> unless @s_sharedLang @s_sharedLang = new cc.Lang() @s_sharedLang
[ { "context": "reate a user\", ->\n\n userObject =\n email: \"test@test.com\"\n password: \"123456\"\n profile:\n ", "end": 153, "score": 0.9999265670776367, "start": 140, "tag": "EMAIL", "value": "test@test.com" }, { "context": "t =\n email: \"test@test....
tests/jasmine/server-disabled/integration/user.spec.coffee
redhead-web/meteor-foodcoop
11
describe "User", -> afterEach -> Meteor.users.remove({}) it "should be able to create a user", -> userObject = email: "test@test.com" password: "123456" profile: name: "Test User" expect -> Accounts.createUser userObject .not.toThrow() it "should automatically get a customer number", -> userObject = email: "test@test.com" password: "123456" profile: name: "Test User" id = Accounts.createUser userObject user = Meteor.users.findOne id expect(user.profile.name).toBe "Test User" expect(user.profile.customerNumber).toBeDefined()
29839
describe "User", -> afterEach -> Meteor.users.remove({}) it "should be able to create a user", -> userObject = email: "<EMAIL>" password: "<PASSWORD>" profile: name: "<NAME>" expect -> Accounts.createUser userObject .not.toThrow() it "should automatically get a customer number", -> userObject = email: "<EMAIL>" password: "<PASSWORD>" profile: name: "<NAME>" id = Accounts.createUser userObject user = Meteor.users.findOne id expect(user.profile.name).toBe "<NAME>" expect(user.profile.customerNumber).toBeDefined()
true
describe "User", -> afterEach -> Meteor.users.remove({}) it "should be able to create a user", -> userObject = email: "PI:EMAIL:<EMAIL>END_PI" password: "PI:PASSWORD:<PASSWORD>END_PI" profile: name: "PI:NAME:<NAME>END_PI" expect -> Accounts.createUser userObject .not.toThrow() it "should automatically get a customer number", -> userObject = email: "PI:EMAIL:<EMAIL>END_PI" password: "PI:PASSWORD:<PASSWORD>END_PI" profile: name: "PI:NAME:<NAME>END_PI" id = Accounts.createUser userObject user = Meteor.users.findOne id expect(user.profile.name).toBe "PI:NAME:<NAME>END_PI" expect(user.profile.customerNumber).toBeDefined()
[ { "context": "derit, enim eiusmod high life accusamus terry richardson ad squid. Nihil anim keffiyeh helvetica, craft be", "end": 834, "score": 0.5751776695251465, "start": 828, "tag": "NAME", "value": "ardson" }, { "context": "he reprehenderit, enim eiusmod high life accusamus terry...
snippets/components-collapse.cson
MdeGOO/atom-bootstrap4
53
'.text.html': # Work only with HTML # TODO: Add Usage form http://v4-alpha.getbootstrap.com/components/collapse/#usage # Collapse 'Collapse - Bootstrap 4': 'prefix': 'coll' 'body': """ <p> <a class="btn btn-primary" data-toggle="collapse" href="#${1:collapseExample}" aria-expanded="false" aria-controls="${1:collapseExample}"> ${2:Link with href} </a> <button class="btn btn-primary" type="button" data-toggle="collapse" data-target="#${1:collapseExample}" aria-expanded="false" aria-controls="${1:collapseExample}"> ${3:Button with data-target} </button> </p> <div class="collapse" id="${1:collapseExample}"> <div class="card card-block"> ${4:Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident.} </div> </div> """ 'Collapse accordion - Bootstrap 4': 'prefix': 'colla' 'body': """ <div id="accordion" role="tablist" aria-multiselectable="true"> <div class="panel panel-default"> <div class="panel-heading" role="tab" id="${3:headingOne}"> <h4 class="panel-title"> <a data-toggle="collapse" data-parent="#accordion" href="#collapseOne" aria-expanded="true" aria-controls="${2:collapseOne}"> ${1:Collapsible Group Item #1} </a> </h4> </div> <div id="${2:collapseOne}" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="${3:headingOne}"> ${3:Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.} </div> </div> <div class="panel panel-default"> <div class="panel-heading" role="tab" id="${3:headingTwo}"> <h4 class="panel-title"> <a class="collapsed" data-toggle="collapse" data-parent="#accordion" href="#collapseTwo" aria-expanded="false" aria-controls="${2:collapseTwo}"> ${1:Collapsible Group Item #2} </a> </h4> </div> <div id="${2:collapseTwo}" class="panel-collapse collapse" role="tabpanel" aria-labelledby="${3:headingTwo}"> ${3:Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.} </div> </div> <div class="panel panel-default"> <div class="panel-heading" role="tab" id="${3:headingThree}"> <h4 class="panel-title"> <a class="collapsed" data-toggle="collapse" data-parent="#accordion" href="#collapseThree" aria-expanded="false" aria-controls="${2:collapseThree}"> ${1:Collapsible Group Item #3} </a> </h4> </div> <div id="${2:collapseThree}" class="panel-collapse collapse" role="tabpanel" aria-labelledby="${3:headingThree}"> ${3:Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.} </div> </div> </div> """
221146
'.text.html': # Work only with HTML # TODO: Add Usage form http://v4-alpha.getbootstrap.com/components/collapse/#usage # Collapse 'Collapse - Bootstrap 4': 'prefix': 'coll' 'body': """ <p> <a class="btn btn-primary" data-toggle="collapse" href="#${1:collapseExample}" aria-expanded="false" aria-controls="${1:collapseExample}"> ${2:Link with href} </a> <button class="btn btn-primary" type="button" data-toggle="collapse" data-target="#${1:collapseExample}" aria-expanded="false" aria-controls="${1:collapseExample}"> ${3:Button with data-target} </button> </p> <div class="collapse" id="${1:collapseExample}"> <div class="card card-block"> ${4:Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry rich<NAME> ad squid. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident.} </div> </div> """ 'Collapse accordion - Bootstrap 4': 'prefix': 'colla' 'body': """ <div id="accordion" role="tablist" aria-multiselectable="true"> <div class="panel panel-default"> <div class="panel-heading" role="tab" id="${3:headingOne}"> <h4 class="panel-title"> <a data-toggle="collapse" data-parent="#accordion" href="#collapseOne" aria-expanded="true" aria-controls="${2:collapseOne}"> ${1:Collapsible Group Item #1} </a> </h4> </div> <div id="${2:collapseOne}" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="${3:headingOne}"> ${3:Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.} </div> </div> <div class="panel panel-default"> <div class="panel-heading" role="tab" id="${3:headingTwo}"> <h4 class="panel-title"> <a class="collapsed" data-toggle="collapse" data-parent="#accordion" href="#collapseTwo" aria-expanded="false" aria-controls="${2:collapseTwo}"> ${1:Collapsible Group Item #2} </a> </h4> </div> <div id="${2:collapseTwo}" class="panel-collapse collapse" role="tabpanel" aria-labelledby="${3:headingTwo}"> ${3:Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.} </div> </div> <div class="panel panel-default"> <div class="panel-heading" role="tab" id="${3:headingThree}"> <h4 class="panel-title"> <a class="collapsed" data-toggle="collapse" data-parent="#accordion" href="#collapseThree" aria-expanded="false" aria-controls="${2:collapseThree}"> ${1:Collapsible Group Item #3} </a> </h4> </div> <div id="${2:collapseThree}" class="panel-collapse collapse" role="tabpanel" aria-labelledby="${3:headingThree}"> ${3:Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus <NAME> <NAME> ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.} </div> </div> </div> """
true
'.text.html': # Work only with HTML # TODO: Add Usage form http://v4-alpha.getbootstrap.com/components/collapse/#usage # Collapse 'Collapse - Bootstrap 4': 'prefix': 'coll' 'body': """ <p> <a class="btn btn-primary" data-toggle="collapse" href="#${1:collapseExample}" aria-expanded="false" aria-controls="${1:collapseExample}"> ${2:Link with href} </a> <button class="btn btn-primary" type="button" data-toggle="collapse" data-target="#${1:collapseExample}" aria-expanded="false" aria-controls="${1:collapseExample}"> ${3:Button with data-target} </button> </p> <div class="collapse" id="${1:collapseExample}"> <div class="card card-block"> ${4:Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richPI:NAME:<NAME>END_PI ad squid. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident.} </div> </div> """ 'Collapse accordion - Bootstrap 4': 'prefix': 'colla' 'body': """ <div id="accordion" role="tablist" aria-multiselectable="true"> <div class="panel panel-default"> <div class="panel-heading" role="tab" id="${3:headingOne}"> <h4 class="panel-title"> <a data-toggle="collapse" data-parent="#accordion" href="#collapseOne" aria-expanded="true" aria-controls="${2:collapseOne}"> ${1:Collapsible Group Item #1} </a> </h4> </div> <div id="${2:collapseOne}" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="${3:headingOne}"> ${3:Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.} </div> </div> <div class="panel panel-default"> <div class="panel-heading" role="tab" id="${3:headingTwo}"> <h4 class="panel-title"> <a class="collapsed" data-toggle="collapse" data-parent="#accordion" href="#collapseTwo" aria-expanded="false" aria-controls="${2:collapseTwo}"> ${1:Collapsible Group Item #2} </a> </h4> </div> <div id="${2:collapseTwo}" class="panel-collapse collapse" role="tabpanel" aria-labelledby="${3:headingTwo}"> ${3:Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.} </div> </div> <div class="panel panel-default"> <div class="panel-heading" role="tab" id="${3:headingThree}"> <h4 class="panel-title"> <a class="collapsed" data-toggle="collapse" data-parent="#accordion" href="#collapseThree" aria-expanded="false" aria-controls="${2:collapseThree}"> ${1:Collapsible Group Item #3} </a> </h4> </div> <div id="${2:collapseThree}" class="panel-collapse collapse" role="tabpanel" aria-labelledby="${3:headingThree}"> ${3:Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.} </div> </div> </div> """
[ { "context": "erty define\n#\n# MIT License\n#\n# Copyright (c) 2015 Dennis Raymondo van der Sluis\n#\n# Permission is hereby granted, free of charge,", "end": 137, "score": 0.9998815059661865, "start": 108, "tag": "NAME", "value": "Dennis Raymondo van der Sluis" } ]
define-prop.coffee
phazelift/define-prop
0
# # define-prop # # Easy and type safe custom object property define # # MIT License # # Copyright (c) 2015 Dennis Raymondo van der Sluis # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # types = require 'types.js' deepFreeze = require 'deep-freeze' defineProp= ( object, key, value, settings... ) -> if not key= types.forceString key defineProp.log 'define-prop: error, invalid or missing key!' return if types.notFunction(object) and (typeof object isnt 'object') defineProp.log 'define-prop: error, invalid or missing object!' return descriptor= enumerable : ~settings.indexOf 'enumerable' if (types.isObject value) and (types.hasFunction value.get, value.set) descriptor.get= types.forceFunction value.get descriptor.set= types.forceFunction value.set else descriptor.value = value descriptor.configurable = ~settings.indexOf 'configurable' descriptor.writable = ~settings.indexOf 'writable' if not descriptor.writable descriptor.value= deepFreeze descriptor.value Object.defineProperty object, key, descriptor return object defineProp.log= console?.log module.exports= defineProp;
217430
# # define-prop # # Easy and type safe custom object property define # # MIT License # # Copyright (c) 2015 <NAME> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # types = require 'types.js' deepFreeze = require 'deep-freeze' defineProp= ( object, key, value, settings... ) -> if not key= types.forceString key defineProp.log 'define-prop: error, invalid or missing key!' return if types.notFunction(object) and (typeof object isnt 'object') defineProp.log 'define-prop: error, invalid or missing object!' return descriptor= enumerable : ~settings.indexOf 'enumerable' if (types.isObject value) and (types.hasFunction value.get, value.set) descriptor.get= types.forceFunction value.get descriptor.set= types.forceFunction value.set else descriptor.value = value descriptor.configurable = ~settings.indexOf 'configurable' descriptor.writable = ~settings.indexOf 'writable' if not descriptor.writable descriptor.value= deepFreeze descriptor.value Object.defineProperty object, key, descriptor return object defineProp.log= console?.log module.exports= defineProp;
true
# # define-prop # # Easy and type safe custom object property define # # MIT License # # Copyright (c) 2015 PI:NAME:<NAME>END_PI # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # types = require 'types.js' deepFreeze = require 'deep-freeze' defineProp= ( object, key, value, settings... ) -> if not key= types.forceString key defineProp.log 'define-prop: error, invalid or missing key!' return if types.notFunction(object) and (typeof object isnt 'object') defineProp.log 'define-prop: error, invalid or missing object!' return descriptor= enumerable : ~settings.indexOf 'enumerable' if (types.isObject value) and (types.hasFunction value.get, value.set) descriptor.get= types.forceFunction value.get descriptor.set= types.forceFunction value.set else descriptor.value = value descriptor.configurable = ~settings.indexOf 'configurable' descriptor.writable = ~settings.indexOf 'writable' if not descriptor.writable descriptor.value= deepFreeze descriptor.value Object.defineProperty object, key, descriptor return object defineProp.log= console?.log module.exports= defineProp;
[ { "context": " editor for taskpaper files:\n# https://github.com/Leftium/todo.taskpaper\n#\n# written by John-Kim Murphy\n#\n#", "end": 153, "score": 0.9882251024246216, "start": 146, "tag": "USERNAME", "value": "Leftium" }, { "context": "//github.com/Leftium/todo.taskpaper\n#\n# wri...
src/coffeeconsole/coffeeconsole.coffee
Leftium/Todo.taskpaper
25
# PhosphorJS widget that hosts a CoffeeScript REPL. # # Part of Todo.taskpaper, an enhanced text editor for taskpaper files: # https://github.com/Leftium/todo.taskpaper # # written by John-Kim Murphy # # Based on: # - https://github.com/phosphorjs/phosphor-codemirror/blob/master/src/index.ts # - https://github.com/larryng/coffeescript-repl/blob/master/coffee/main.coffee import { Widget } from 'phosphor-widget' import { inspect } from 'util' import CoffeeScript from '../../lib/coffee-script.js' import './coffeeconsole.css' escapeHTML = (s) -> s.replace(/&/g,'&amp;') .replace(/</g,'&lt;') .replace(/>/g,'&gt;') class CoffeeREPL DEFAULT_SETTINGS = lastVariable: '_' maxLines: 10000 maxDepth: 2 showHidden: false colorize: true constructor: (@output, @input, @prompt, settings={}) -> @history = [] @historyi = -1 @saved = '' @multiline = false @settings = $.extend({}, DEFAULT_SETTINGS) if localStorage and localStorage.settings for k, v of JSON.parse(localStorage.settings) @settings[k] = v for k, v of settings @settings[k] = v @input.keydown @handleKeypress resetSettings: -> localStorage.clear() saveSettings: -> localStorage.settings = JSON.stringify($.extend({}, @settings)) print: (args...) => s = args.join(' ') or ' ' o = @output[0].innerHTML + s + '\n' @output[0].innerHTML = o.split('\n')[-@settings.maxLines...].join('\n') @prompt[0].scrollIntoView() processSaved: => try compiled = CoffeeScript.compile @saved compiled = compiled[14...-17] value = eval.call window, compiled window[@settings.lastVariable] = value output = inspect value, @settings.showHidden, @settings.maxDepth, @settings.colorize catch e if e.stack output = e.stack # FF doesn't have Error.toString() as the first line of Error.stack # while Chrome does. if output.split('\n')[0] isnt e.toString() output = "#{e.toString()}\n#{e.stack}" # Remove calling stack, which is usually not helpful. output = output.split('\n')[0] else output = e.toString() @saved = '' openSpan = (colorName) -> "<span class=ansi-#{colorName}>" ansi2tag = '1' : openSpan('bold') '3' : openSpan('italic') '4' : openSpan('underline') '7' : openSpan('inverse') '37': openSpan('white') '90': openSpan('grey') '30': openSpan('black') '34': openSpan('blue') '36': openSpan('cyan') '32': openSpan('green') '35': openSpan('magenta') '31': openSpan('red') '33': openSpan('yellow') '22': '</span>' '23': '</span>' '24': '</span>' '27': '</span>' '39': '</span>' for key,value of ansi2tag output = output.replace(///\u001b\[#{key}m///g, value) output = output.replace(/^|\n/g, '$& < ') @print output setPrompt: => s = if @multiline then '------' else 'coffee' @prompt.html "#{s}&gt;&nbsp;" addToHistory: (s) => @history.unshift s @historyi = -1 addToSaved: (s) => @saved += if s[-1...] is '\\' then s[...-1] else s @saved += '\n' @addToHistory s clear: => @output[0].innerHTML = '' undefined handleKeypress: (e) => switch e.which when 13 # Enter e.preventDefault() input = @input.val() @input.val '' @print @prompt.html() + escapeHTML(input) if input window.input = input @addToSaved input if input[-1...] isnt '\\' and not @multiline @processSaved() when 27 # Esc e.preventDefault() input = @input.val() if input and @multiline and @saved input = @input.val() @input.val '' @print @prompt.html() + escapeHTML(input) @addToSaved input @processSaved() else if @multiline and @saved @processSaved() @multiline = not @multiline @setPrompt() when 38 # Up e.preventDefault() if @historyi < @history.length-1 @historyi += 1 @input.val @history[@historyi] when 40 # Down e.preventDefault() if @historyi > 0 @historyi += -1 @input.val @history[@historyi] when 76, 108 # L, l if e.ctrlKey e.preventDefault() @clear() coffeeConsoleHtmlFragment = ''' <div class="container"> <div class="outputdiv"> <pre class="output"></pre> </div> <div class="inputdiv"> <div class="inputl"> <pre class="prompt">coffee&gt;&nbsp;</pre> </div> <div class="inputr"> <textarea class="input" spellcheck="false"></textarea> <div class="inputcopy"></div> </div> </div> </div>''' export class CoffeeConsoleWidget extends Widget constructor: () -> super() @addClass('CoffeeConsoleWidget') @$node = $(@node) # construct div's here @$node.append(coffeeConsoleHtmlFragment) @SAVED_CONSOLE_LOG = console.log @$output = $('.output', @$node) @$input = $('.input', @$node) @$prompt = $('.prompt', @$node) @$inputdiv = $('.inputdiv', @$node) @$inputl = $('.inputl', @$node) @$inputr = $('.inputr', @$node) @$inputcopy = $('.inputcopy', @$node) @init() onResize: (msg) => super() @resizeInput() onAfterAttach: (msg) => super() @resizeInput() @$input.focus() resizeInput: (e) => width = @$inputdiv.width() - @$inputl.width() content = @$input.val() content.replace /\n/g, '<br/>' @$inputcopy.html content @$inputcopy.width width @$input.width width @$input.height @$inputcopy.height() + 2 scrollToBottom: () => @$prompt[0].scrollIntoView() init:() -> # bind other handlers @$input.keydown @scrollToBottom @$input.keyup @resizeInput @$input.change @resizeInput $('.container', @$node).click (e) => if e.clientY > @$input[0].offsetTop @$input.focus() # instantiate our REPL @repl = new CoffeeREPL @$output, @$input, @$prompt # replace console.log console.log = (args...) => @SAVED_CONSOLE_LOG.apply console, args @repl.print args... # log only to CoffeeConsole window.log = (args...) => @repl.print args... # expose repl as $$ window.$$ = @repl # help window.help = => @repl.print """ <strong>Features</strong> <strong>========</strong> + <strong>Esc</strong> toggles multiline mode. + <strong>Up/Down arrow</strong> flips through line history. + <strong>#{$$.settings.lastVariable}</strong> stores the last returned value. + Access the internals of this console through <strong>$$</strong>. + <strong>$$.clear()</strong> clears this console. <strong>Settings</strong> <strong>========</strong> You can modify the behavior of this REPL by altering <strong>$$.settings</strong>: + <strong>lastVariable</strong> (#{@repl.settings.lastVariable}): variable name in which last returned value is stored + <strong>maxLines</strong> (#{@repl.settings.maxLines}): max line count of this console + <strong>maxDepth</strong> (#{@repl.settings.maxDepth}): max depth in which to inspect outputted object + <strong>showHidden</strong> (#{@repl.settings.showHidden}): flag to output hidden (not enumerable) properties of objects + <strong>colorize</strong> (#{@repl.settings.colorize}): flag to colorize output (set to false if REPL is slow) <strong>$$.saveSettings()</strong> will save settings to localStorage. <strong>$$.resetSettings()</strong> will reset settings to default. """ # print header @repl.print """ | CoffeeScript v#{CoffeeScript.VERSION} | <a href="https://github.com/Leftium/todo.taskpaper" target="_blank">https://github.com/Leftium/todo.taskpaper</a> | | Quick Links: | <a href="#WELCOME">#WELCOME</a> - Open sample with quick welcome/tutorial. | <a onclick="dropboxChooser()" >#CHOOSE</a> - Open a file from your Dropbox. | <a href="#NEW" >#NEW</a> - Open a new, blank document. | | help() for features and tips. """
151377
# PhosphorJS widget that hosts a CoffeeScript REPL. # # Part of Todo.taskpaper, an enhanced text editor for taskpaper files: # https://github.com/Leftium/todo.taskpaper # # written by <NAME> # # Based on: # - https://github.com/phosphorjs/phosphor-codemirror/blob/master/src/index.ts # - https://github.com/larryng/coffeescript-repl/blob/master/coffee/main.coffee import { Widget } from 'phosphor-widget' import { inspect } from 'util' import CoffeeScript from '../../lib/coffee-script.js' import './coffeeconsole.css' escapeHTML = (s) -> s.replace(/&/g,'&amp;') .replace(/</g,'&lt;') .replace(/>/g,'&gt;') class CoffeeREPL DEFAULT_SETTINGS = lastVariable: '_' maxLines: 10000 maxDepth: 2 showHidden: false colorize: true constructor: (@output, @input, @prompt, settings={}) -> @history = [] @historyi = -1 @saved = '' @multiline = false @settings = $.extend({}, DEFAULT_SETTINGS) if localStorage and localStorage.settings for k, v of JSON.parse(localStorage.settings) @settings[k] = v for k, v of settings @settings[k] = v @input.keydown @handleKeypress resetSettings: -> localStorage.clear() saveSettings: -> localStorage.settings = JSON.stringify($.extend({}, @settings)) print: (args...) => s = args.join(' ') or ' ' o = @output[0].innerHTML + s + '\n' @output[0].innerHTML = o.split('\n')[-@settings.maxLines...].join('\n') @prompt[0].scrollIntoView() processSaved: => try compiled = CoffeeScript.compile @saved compiled = compiled[14...-17] value = eval.call window, compiled window[@settings.lastVariable] = value output = inspect value, @settings.showHidden, @settings.maxDepth, @settings.colorize catch e if e.stack output = e.stack # FF doesn't have Error.toString() as the first line of Error.stack # while Chrome does. if output.split('\n')[0] isnt e.toString() output = "#{e.toString()}\n#{e.stack}" # Remove calling stack, which is usually not helpful. output = output.split('\n')[0] else output = e.toString() @saved = '' openSpan = (colorName) -> "<span class=ansi-#{colorName}>" ansi2tag = '1' : openSpan('bold') '3' : openSpan('italic') '4' : openSpan('underline') '7' : openSpan('inverse') '37': openSpan('white') '90': openSpan('grey') '30': openSpan('black') '34': openSpan('blue') '36': openSpan('cyan') '32': openSpan('green') '35': openSpan('magenta') '31': openSpan('red') '33': openSpan('yellow') '22': '</span>' '23': '</span>' '24': '</span>' '27': '</span>' '39': '</span>' for key,value of ansi2tag output = output.replace(///\u001b\[#{key}m///g, value) output = output.replace(/^|\n/g, '$& < ') @print output setPrompt: => s = if @multiline then '------' else 'coffee' @prompt.html "#{s}&gt;&nbsp;" addToHistory: (s) => @history.unshift s @historyi = -1 addToSaved: (s) => @saved += if s[-1...] is '\\' then s[...-1] else s @saved += '\n' @addToHistory s clear: => @output[0].innerHTML = '' undefined handleKeypress: (e) => switch e.which when 13 # Enter e.preventDefault() input = @input.val() @input.val '' @print @prompt.html() + escapeHTML(input) if input window.input = input @addToSaved input if input[-1...] isnt '\\' and not @multiline @processSaved() when 27 # Esc e.preventDefault() input = @input.val() if input and @multiline and @saved input = @input.val() @input.val '' @print @prompt.html() + escapeHTML(input) @addToSaved input @processSaved() else if @multiline and @saved @processSaved() @multiline = not @multiline @setPrompt() when 38 # Up e.preventDefault() if @historyi < @history.length-1 @historyi += 1 @input.val @history[@historyi] when 40 # Down e.preventDefault() if @historyi > 0 @historyi += -1 @input.val @history[@historyi] when 76, 108 # L, l if e.ctrlKey e.preventDefault() @clear() coffeeConsoleHtmlFragment = ''' <div class="container"> <div class="outputdiv"> <pre class="output"></pre> </div> <div class="inputdiv"> <div class="inputl"> <pre class="prompt">coffee&gt;&nbsp;</pre> </div> <div class="inputr"> <textarea class="input" spellcheck="false"></textarea> <div class="inputcopy"></div> </div> </div> </div>''' export class CoffeeConsoleWidget extends Widget constructor: () -> super() @addClass('CoffeeConsoleWidget') @$node = $(@node) # construct div's here @$node.append(coffeeConsoleHtmlFragment) @SAVED_CONSOLE_LOG = console.log @$output = $('.output', @$node) @$input = $('.input', @$node) @$prompt = $('.prompt', @$node) @$inputdiv = $('.inputdiv', @$node) @$inputl = $('.inputl', @$node) @$inputr = $('.inputr', @$node) @$inputcopy = $('.inputcopy', @$node) @init() onResize: (msg) => super() @resizeInput() onAfterAttach: (msg) => super() @resizeInput() @$input.focus() resizeInput: (e) => width = @$inputdiv.width() - @$inputl.width() content = @$input.val() content.replace /\n/g, '<br/>' @$inputcopy.html content @$inputcopy.width width @$input.width width @$input.height @$inputcopy.height() + 2 scrollToBottom: () => @$prompt[0].scrollIntoView() init:() -> # bind other handlers @$input.keydown @scrollToBottom @$input.keyup @resizeInput @$input.change @resizeInput $('.container', @$node).click (e) => if e.clientY > @$input[0].offsetTop @$input.focus() # instantiate our REPL @repl = new CoffeeREPL @$output, @$input, @$prompt # replace console.log console.log = (args...) => @SAVED_CONSOLE_LOG.apply console, args @repl.print args... # log only to CoffeeConsole window.log = (args...) => @repl.print args... # expose repl as $$ window.$$ = @repl # help window.help = => @repl.print """ <strong>Features</strong> <strong>========</strong> + <strong>Esc</strong> toggles multiline mode. + <strong>Up/Down arrow</strong> flips through line history. + <strong>#{$$.settings.lastVariable}</strong> stores the last returned value. + Access the internals of this console through <strong>$$</strong>. + <strong>$$.clear()</strong> clears this console. <strong>Settings</strong> <strong>========</strong> You can modify the behavior of this REPL by altering <strong>$$.settings</strong>: + <strong>lastVariable</strong> (#{@repl.settings.lastVariable}): variable name in which last returned value is stored + <strong>maxLines</strong> (#{@repl.settings.maxLines}): max line count of this console + <strong>maxDepth</strong> (#{@repl.settings.maxDepth}): max depth in which to inspect outputted object + <strong>showHidden</strong> (#{@repl.settings.showHidden}): flag to output hidden (not enumerable) properties of objects + <strong>colorize</strong> (#{@repl.settings.colorize}): flag to colorize output (set to false if REPL is slow) <strong>$$.saveSettings()</strong> will save settings to localStorage. <strong>$$.resetSettings()</strong> will reset settings to default. """ # print header @repl.print """ | CoffeeScript v#{CoffeeScript.VERSION} | <a href="https://github.com/Leftium/todo.taskpaper" target="_blank">https://github.com/Leftium/todo.taskpaper</a> | | Quick Links: | <a href="#WELCOME">#WELCOME</a> - Open sample with quick welcome/tutorial. | <a onclick="dropboxChooser()" >#CHOOSE</a> - Open a file from your Dropbox. | <a href="#NEW" >#NEW</a> - Open a new, blank document. | | help() for features and tips. """
true
# PhosphorJS widget that hosts a CoffeeScript REPL. # # Part of Todo.taskpaper, an enhanced text editor for taskpaper files: # https://github.com/Leftium/todo.taskpaper # # written by PI:NAME:<NAME>END_PI # # Based on: # - https://github.com/phosphorjs/phosphor-codemirror/blob/master/src/index.ts # - https://github.com/larryng/coffeescript-repl/blob/master/coffee/main.coffee import { Widget } from 'phosphor-widget' import { inspect } from 'util' import CoffeeScript from '../../lib/coffee-script.js' import './coffeeconsole.css' escapeHTML = (s) -> s.replace(/&/g,'&amp;') .replace(/</g,'&lt;') .replace(/>/g,'&gt;') class CoffeeREPL DEFAULT_SETTINGS = lastVariable: '_' maxLines: 10000 maxDepth: 2 showHidden: false colorize: true constructor: (@output, @input, @prompt, settings={}) -> @history = [] @historyi = -1 @saved = '' @multiline = false @settings = $.extend({}, DEFAULT_SETTINGS) if localStorage and localStorage.settings for k, v of JSON.parse(localStorage.settings) @settings[k] = v for k, v of settings @settings[k] = v @input.keydown @handleKeypress resetSettings: -> localStorage.clear() saveSettings: -> localStorage.settings = JSON.stringify($.extend({}, @settings)) print: (args...) => s = args.join(' ') or ' ' o = @output[0].innerHTML + s + '\n' @output[0].innerHTML = o.split('\n')[-@settings.maxLines...].join('\n') @prompt[0].scrollIntoView() processSaved: => try compiled = CoffeeScript.compile @saved compiled = compiled[14...-17] value = eval.call window, compiled window[@settings.lastVariable] = value output = inspect value, @settings.showHidden, @settings.maxDepth, @settings.colorize catch e if e.stack output = e.stack # FF doesn't have Error.toString() as the first line of Error.stack # while Chrome does. if output.split('\n')[0] isnt e.toString() output = "#{e.toString()}\n#{e.stack}" # Remove calling stack, which is usually not helpful. output = output.split('\n')[0] else output = e.toString() @saved = '' openSpan = (colorName) -> "<span class=ansi-#{colorName}>" ansi2tag = '1' : openSpan('bold') '3' : openSpan('italic') '4' : openSpan('underline') '7' : openSpan('inverse') '37': openSpan('white') '90': openSpan('grey') '30': openSpan('black') '34': openSpan('blue') '36': openSpan('cyan') '32': openSpan('green') '35': openSpan('magenta') '31': openSpan('red') '33': openSpan('yellow') '22': '</span>' '23': '</span>' '24': '</span>' '27': '</span>' '39': '</span>' for key,value of ansi2tag output = output.replace(///\u001b\[#{key}m///g, value) output = output.replace(/^|\n/g, '$& < ') @print output setPrompt: => s = if @multiline then '------' else 'coffee' @prompt.html "#{s}&gt;&nbsp;" addToHistory: (s) => @history.unshift s @historyi = -1 addToSaved: (s) => @saved += if s[-1...] is '\\' then s[...-1] else s @saved += '\n' @addToHistory s clear: => @output[0].innerHTML = '' undefined handleKeypress: (e) => switch e.which when 13 # Enter e.preventDefault() input = @input.val() @input.val '' @print @prompt.html() + escapeHTML(input) if input window.input = input @addToSaved input if input[-1...] isnt '\\' and not @multiline @processSaved() when 27 # Esc e.preventDefault() input = @input.val() if input and @multiline and @saved input = @input.val() @input.val '' @print @prompt.html() + escapeHTML(input) @addToSaved input @processSaved() else if @multiline and @saved @processSaved() @multiline = not @multiline @setPrompt() when 38 # Up e.preventDefault() if @historyi < @history.length-1 @historyi += 1 @input.val @history[@historyi] when 40 # Down e.preventDefault() if @historyi > 0 @historyi += -1 @input.val @history[@historyi] when 76, 108 # L, l if e.ctrlKey e.preventDefault() @clear() coffeeConsoleHtmlFragment = ''' <div class="container"> <div class="outputdiv"> <pre class="output"></pre> </div> <div class="inputdiv"> <div class="inputl"> <pre class="prompt">coffee&gt;&nbsp;</pre> </div> <div class="inputr"> <textarea class="input" spellcheck="false"></textarea> <div class="inputcopy"></div> </div> </div> </div>''' export class CoffeeConsoleWidget extends Widget constructor: () -> super() @addClass('CoffeeConsoleWidget') @$node = $(@node) # construct div's here @$node.append(coffeeConsoleHtmlFragment) @SAVED_CONSOLE_LOG = console.log @$output = $('.output', @$node) @$input = $('.input', @$node) @$prompt = $('.prompt', @$node) @$inputdiv = $('.inputdiv', @$node) @$inputl = $('.inputl', @$node) @$inputr = $('.inputr', @$node) @$inputcopy = $('.inputcopy', @$node) @init() onResize: (msg) => super() @resizeInput() onAfterAttach: (msg) => super() @resizeInput() @$input.focus() resizeInput: (e) => width = @$inputdiv.width() - @$inputl.width() content = @$input.val() content.replace /\n/g, '<br/>' @$inputcopy.html content @$inputcopy.width width @$input.width width @$input.height @$inputcopy.height() + 2 scrollToBottom: () => @$prompt[0].scrollIntoView() init:() -> # bind other handlers @$input.keydown @scrollToBottom @$input.keyup @resizeInput @$input.change @resizeInput $('.container', @$node).click (e) => if e.clientY > @$input[0].offsetTop @$input.focus() # instantiate our REPL @repl = new CoffeeREPL @$output, @$input, @$prompt # replace console.log console.log = (args...) => @SAVED_CONSOLE_LOG.apply console, args @repl.print args... # log only to CoffeeConsole window.log = (args...) => @repl.print args... # expose repl as $$ window.$$ = @repl # help window.help = => @repl.print """ <strong>Features</strong> <strong>========</strong> + <strong>Esc</strong> toggles multiline mode. + <strong>Up/Down arrow</strong> flips through line history. + <strong>#{$$.settings.lastVariable}</strong> stores the last returned value. + Access the internals of this console through <strong>$$</strong>. + <strong>$$.clear()</strong> clears this console. <strong>Settings</strong> <strong>========</strong> You can modify the behavior of this REPL by altering <strong>$$.settings</strong>: + <strong>lastVariable</strong> (#{@repl.settings.lastVariable}): variable name in which last returned value is stored + <strong>maxLines</strong> (#{@repl.settings.maxLines}): max line count of this console + <strong>maxDepth</strong> (#{@repl.settings.maxDepth}): max depth in which to inspect outputted object + <strong>showHidden</strong> (#{@repl.settings.showHidden}): flag to output hidden (not enumerable) properties of objects + <strong>colorize</strong> (#{@repl.settings.colorize}): flag to colorize output (set to false if REPL is slow) <strong>$$.saveSettings()</strong> will save settings to localStorage. <strong>$$.resetSettings()</strong> will reset settings to default. """ # print header @repl.print """ | CoffeeScript v#{CoffeeScript.VERSION} | <a href="https://github.com/Leftium/todo.taskpaper" target="_blank">https://github.com/Leftium/todo.taskpaper</a> | | Quick Links: | <a href="#WELCOME">#WELCOME</a> - Open sample with quick welcome/tutorial. | <a onclick="dropboxChooser()" >#CHOOSE</a> - Open a file from your Dropbox. | <a href="#NEW" >#NEW</a> - Open a new, blank document. | | help() for features and tips. """
[ { "context": "plan more than one month in advance. Maybe two' -- Ivan\";\n txt += \"<p>'In research, keep second guessi", "end": 534, "score": 0.9996944665908813, "start": 530, "tag": "NAME", "value": "Ivan" }, { "context": "<p>'In research, keep second guessing yourself' -- David...
assets/js/example.coffee
rvantonder/site-option-3
0
--- --- # START $(document).ready -> q = 0 $(window).scroll -> if ($(window).scrollTop() + $(window).height()) is $(document).height() q += 1 if q == 4 easter_egg() easter_egg = () -> txt = "<br><br><br><hr/><br><h1>You found the easter egg :)</h1>"; txt += "<p>This is primarily a collection of thoughts and sayings that I've collected over time.</p>"; txt += "<h2>Things people have said that strike a chord with me</h2>"; txt += "<p>'Never plan more than one month in advance. Maybe two' -- Ivan"; txt += "<p>'In research, keep second guessing yourself' -- David"; txt += "<p>'In research, you either have to be the first, or the best' -- Patrice"; txt += "<p>'Dear Rijnard, Never give up on your dreams! Also, remember that smaller dreams are easier to achieve.' -- James Mickens"; txt += "<p>'Don't cut something before making sure the knife is sharp' -- me"; txt += "<p>'If you're not exercising 3 times a week, your priorities are wrong' -- can't remember</p>"; txt += "<p>'Everyone has a plan 'till they get punched in the mouth.' - Mike Tyson"; txt += "<p>'When you're on top there's only one way to go.' - ?</p>"; txt += "<p>'Shoot, if you want bad stuff, watch the news.' - Bob Ross</p>"; txt += "<h2>On \"Success\"</h2>"; txt += "<p>The race is not to the swift,<br> Nor the battle to the strong,<br> Nor bread to the wise,<br> Nor riches to men of understanding,<br> Nor favor to men of skill;<br> But time and chance happen to them all.</p>"; txt += "<img src=images/success.png>"; txt += "<p>Whatever you want to be good at, it's about getting those 10,000 hours in (Malcolm Gladwell). Thats ~1.14 years.</p>"; txt += "<h3>The Pareto Principle</h3>"; txt += "<p>The Pareto principle says that for many events, roughly 80% of the effects come from 20% of the causes.</p>"; txt += "<p>I *think* this applies to research as well. That basically means that, 80% of the significant (publishable?) research that I output, will result from only 20% of the things that I hope are significant. That's both frustrating and optimistic. Time will tell if it holds.</p>"; txt += "<h3>More things I've encountered</h3>"; txt += "<p>Parkinson's law of triviality and the queen with the duck</p>" txt += "<p>Fredkin's paradox and self-referential decisions to avoid the paradox that result in engaging in the same paradox." txt += "<p>Hofstadter's law: \"It always takes longer than you expect, even when you take into account Hofstadter's Law.\"</p>"; txt += "<p>\"It ain't what you don't know that gets you into trouble. It's what you know for sure that just ain't so.\" - Mark Twain</p>"; $("#base").append(txt)
189534
--- --- # START $(document).ready -> q = 0 $(window).scroll -> if ($(window).scrollTop() + $(window).height()) is $(document).height() q += 1 if q == 4 easter_egg() easter_egg = () -> txt = "<br><br><br><hr/><br><h1>You found the easter egg :)</h1>"; txt += "<p>This is primarily a collection of thoughts and sayings that I've collected over time.</p>"; txt += "<h2>Things people have said that strike a chord with me</h2>"; txt += "<p>'Never plan more than one month in advance. Maybe two' -- <NAME>"; txt += "<p>'In research, keep second guessing yourself' -- <NAME>"; txt += "<p>'In research, you either have to be the first, or the best' -- <NAME>"; txt += "<p>'Dear <NAME>, Never give up on your dreams! Also, remember that smaller dreams are easier to achieve.' -- <NAME>"; txt += "<p>'Don't cut something before making sure the knife is sharp' -- me"; txt += "<p>'If you're not exercising 3 times a week, your priorities are wrong' -- can't remember</p>"; txt += "<p>'Everyone has a plan 'till they get punched in the mouth.' - <NAME>"; txt += "<p>'When you're on top there's only one way to go.' - ?</p>"; txt += "<p>'Shoot, if you want bad stuff, watch the news.' - <NAME></p>"; txt += "<h2>On \"Success\"</h2>"; txt += "<p>The race is not to the swift,<br> Nor the battle to the strong,<br> Nor bread to the wise,<br> Nor riches to men of understanding,<br> Nor favor to men of skill;<br> But time and chance happen to them all.</p>"; txt += "<img src=images/success.png>"; txt += "<p>Whatever you want to be good at, it's about getting those 10,000 hours in (Malcolm Gladwell). Thats ~1.14 years.</p>"; txt += "<h3>The Pareto Principle</h3>"; txt += "<p>The Pareto principle says that for many events, roughly 80% of the effects come from 20% of the causes.</p>"; txt += "<p>I *think* this applies to research as well. That basically means that, 80% of the significant (publishable?) research that I output, will result from only 20% of the things that I hope are significant. That's both frustrating and optimistic. Time will tell if it holds.</p>"; txt += "<h3>More things I've encountered</h3>"; txt += "<p>Parkinson's law of triviality and the queen with the duck</p>" txt += "<p><NAME>'s paradox and self-referential decisions to avoid the paradox that result in engaging in the same paradox." txt += "<p>Hofstadter's law: \"It always takes longer than you expect, even when you take into account Hofstadter's Law.\"</p>"; txt += "<p>\"It ain't what you don't know that gets you into trouble. It's what you know for sure that just ain't so.\" - <NAME></p>"; $("#base").append(txt)
true
--- --- # START $(document).ready -> q = 0 $(window).scroll -> if ($(window).scrollTop() + $(window).height()) is $(document).height() q += 1 if q == 4 easter_egg() easter_egg = () -> txt = "<br><br><br><hr/><br><h1>You found the easter egg :)</h1>"; txt += "<p>This is primarily a collection of thoughts and sayings that I've collected over time.</p>"; txt += "<h2>Things people have said that strike a chord with me</h2>"; txt += "<p>'Never plan more than one month in advance. Maybe two' -- PI:NAME:<NAME>END_PI"; txt += "<p>'In research, keep second guessing yourself' -- PI:NAME:<NAME>END_PI"; txt += "<p>'In research, you either have to be the first, or the best' -- PI:NAME:<NAME>END_PI"; txt += "<p>'Dear PI:NAME:<NAME>END_PI, Never give up on your dreams! Also, remember that smaller dreams are easier to achieve.' -- PI:NAME:<NAME>END_PI"; txt += "<p>'Don't cut something before making sure the knife is sharp' -- me"; txt += "<p>'If you're not exercising 3 times a week, your priorities are wrong' -- can't remember</p>"; txt += "<p>'Everyone has a plan 'till they get punched in the mouth.' - PI:NAME:<NAME>END_PI"; txt += "<p>'When you're on top there's only one way to go.' - ?</p>"; txt += "<p>'Shoot, if you want bad stuff, watch the news.' - PI:NAME:<NAME>END_PI</p>"; txt += "<h2>On \"Success\"</h2>"; txt += "<p>The race is not to the swift,<br> Nor the battle to the strong,<br> Nor bread to the wise,<br> Nor riches to men of understanding,<br> Nor favor to men of skill;<br> But time and chance happen to them all.</p>"; txt += "<img src=images/success.png>"; txt += "<p>Whatever you want to be good at, it's about getting those 10,000 hours in (Malcolm Gladwell). Thats ~1.14 years.</p>"; txt += "<h3>The Pareto Principle</h3>"; txt += "<p>The Pareto principle says that for many events, roughly 80% of the effects come from 20% of the causes.</p>"; txt += "<p>I *think* this applies to research as well. That basically means that, 80% of the significant (publishable?) research that I output, will result from only 20% of the things that I hope are significant. That's both frustrating and optimistic. Time will tell if it holds.</p>"; txt += "<h3>More things I've encountered</h3>"; txt += "<p>Parkinson's law of triviality and the queen with the duck</p>" txt += "<p>PI:NAME:<NAME>END_PI's paradox and self-referential decisions to avoid the paradox that result in engaging in the same paradox." txt += "<p>Hofstadter's law: \"It always takes longer than you expect, even when you take into account Hofstadter's Law.\"</p>"; txt += "<p>\"It ain't what you don't know that gets you into trouble. It's what you know for sure that just ain't so.\" - PI:NAME:<NAME>END_PI</p>"; $("#base").append(txt)
[ { "context": "type: 'Admin', owner: fabricate 'profile', name: 'Foo Bar'\n\n sinon.stub Backbone, 'sync'\n .onCall 0", "end": 392, "score": 0.9983142614364624, "start": 385, "tag": "NAME", "value": "Foo Bar" }, { "context": "act-from').text()\n .should.equal 'From:...
src/desktop/components/inquiry_questionnaire/test/views/specialist.coffee
kanaabe/force
1
Q = require 'bluebird-q' benv = require 'benv' sinon = require 'sinon' Backbone = require 'backbone' { fabricate } = require 'antigravity' setup = require './setup' Specialist = benv.requireWithJadeify require.resolve('../../views/specialist'), ['template'] describe 'Specialist', setup -> beforeEach -> @representative = owner_type: 'Admin', owner: fabricate 'profile', name: 'Foo Bar' sinon.stub Backbone, 'sync' .onCall 0 .yieldsTo 'success', [@representative] .returns Q.resolve [@representative] afterEach -> Backbone.sync.restore() describe '#render', -> describe 'user with email and name', -> beforeEach -> @view = new Specialist user: @currentUser artwork: @artwork inquiry: @inquiry state: @state @view.render() it 'loads the representative then renders the template', -> @view.__representatives__.then => Backbone.sync.args[0][1].url .should.containEql '/api/v1/admins/available_representatives' @view.$('h1').text() .should.equal 'Send message to Artsy' @view.$('.scontact-description').text() .should.equal 'Foo Bar, an Artsy Specialist, is available to answer your questions and help you collect through Artsy.' @view.$('input[type="text"][name="name"]') .should.have.lengthOf 0 @view.$('input[type="email"][name="email"]') .should.have.lengthOf 0 @view.$('.scontact-from').text() .should.equal 'From: Craig Spaeth (craigspaeth@gmail.com)' describe 'user without contact details', -> beforeEach -> @loggedOutUser.unset 'name' @loggedOutUser.unset 'email' @view = new Specialist user: @loggedOutUser artwork: @artwork inquiry: @inquiry state: @state @view.render() it 'renders the template', -> @view.$('h1').text() .should.equal 'Send message to Artsy' @view.$('input[type="text"][name="name"]') .should.have.lengthOf 1 @view.$('input[type="email"][name="email"]') .should.have.lengthOf 1 @view.$('.scontact-from').text() .should.be.empty() describe 'next', -> beforeEach -> @state.set 'steps', ['specialist', 'after_specialist'] @loggedOutUser.unset 'name' @loggedOutUser.unset 'email' @view = new Specialist user: @loggedOutUser artwork: @artwork inquiry: @inquiry state: @state @view.render() it 'sets up the inquiry and ensures the user has contact details', -> @view.$('input[name="name"]').val 'Foo Bar' @view.$('input[name="email"]').val 'foo@bar.com' @view.$('textarea[name="message"]').val 'I wish to buy the foo bar' @view.$('button').click() @view.__serialize__.then => # Sets up the inquiry @inquiry.get('message').should.equal 'I wish to buy the foo bar' @inquiry.get('contact_gallery').should.be.false() @inquiry.get('artwork').should.equal @artwork.id # Sets up the user @loggedOutUser.get('name').should.equal 'Foo Bar' @loggedOutUser.get('email').should.equal 'foo@bar.com' Backbone.sync.callCount.should.equal 3 Backbone.sync.args[0][1].url .should.containEql '/api/v1/admins/available_representatives' Backbone.sync.args[1][1].url() .should.containEql "/api/v1/me/anonymous_session/#{@loggedOutUser.id}" Backbone.sync.args[2][1].url() .should.containEql "/api/v1/profile" # Next @view.state.current().should.equal 'after_specialist'
169417
Q = require 'bluebird-q' benv = require 'benv' sinon = require 'sinon' Backbone = require 'backbone' { fabricate } = require 'antigravity' setup = require './setup' Specialist = benv.requireWithJadeify require.resolve('../../views/specialist'), ['template'] describe 'Specialist', setup -> beforeEach -> @representative = owner_type: 'Admin', owner: fabricate 'profile', name: '<NAME>' sinon.stub Backbone, 'sync' .onCall 0 .yieldsTo 'success', [@representative] .returns Q.resolve [@representative] afterEach -> Backbone.sync.restore() describe '#render', -> describe 'user with email and name', -> beforeEach -> @view = new Specialist user: @currentUser artwork: @artwork inquiry: @inquiry state: @state @view.render() it 'loads the representative then renders the template', -> @view.__representatives__.then => Backbone.sync.args[0][1].url .should.containEql '/api/v1/admins/available_representatives' @view.$('h1').text() .should.equal 'Send message to Artsy' @view.$('.scontact-description').text() .should.equal 'Foo Bar, an Artsy Specialist, is available to answer your questions and help you collect through Artsy.' @view.$('input[type="text"][name="name"]') .should.have.lengthOf 0 @view.$('input[type="email"][name="email"]') .should.have.lengthOf 0 @view.$('.scontact-from').text() .should.equal 'From: <NAME> (<EMAIL>)' describe 'user without contact details', -> beforeEach -> @loggedOutUser.unset 'name' @loggedOutUser.unset 'email' @view = new Specialist user: @loggedOutUser artwork: @artwork inquiry: @inquiry state: @state @view.render() it 'renders the template', -> @view.$('h1').text() .should.equal 'Send message to Artsy' @view.$('input[type="text"][name="name"]') .should.have.lengthOf 1 @view.$('input[type="email"][name="email"]') .should.have.lengthOf 1 @view.$('.scontact-from').text() .should.be.empty() describe 'next', -> beforeEach -> @state.set 'steps', ['specialist', 'after_specialist'] @loggedOutUser.unset 'name' @loggedOutUser.unset 'email' @view = new Specialist user: @loggedOutUser artwork: @artwork inquiry: @inquiry state: @state @view.render() it 'sets up the inquiry and ensures the user has contact details', -> @view.$('input[name="name"]').val '<NAME>' @view.$('input[name="email"]').val '<EMAIL>' @view.$('textarea[name="message"]').val 'I wish to buy the foo bar' @view.$('button').click() @view.__serialize__.then => # Sets up the inquiry @inquiry.get('message').should.equal 'I wish to buy the foo bar' @inquiry.get('contact_gallery').should.be.false() @inquiry.get('artwork').should.equal @artwork.id # Sets up the user @loggedOutUser.get('name').should.equal '<NAME>' @loggedOutUser.get('email').should.equal '<EMAIL>' Backbone.sync.callCount.should.equal 3 Backbone.sync.args[0][1].url .should.containEql '/api/v1/admins/available_representatives' Backbone.sync.args[1][1].url() .should.containEql "/api/v1/me/anonymous_session/#{@loggedOutUser.id}" Backbone.sync.args[2][1].url() .should.containEql "/api/v1/profile" # Next @view.state.current().should.equal 'after_specialist'
true
Q = require 'bluebird-q' benv = require 'benv' sinon = require 'sinon' Backbone = require 'backbone' { fabricate } = require 'antigravity' setup = require './setup' Specialist = benv.requireWithJadeify require.resolve('../../views/specialist'), ['template'] describe 'Specialist', setup -> beforeEach -> @representative = owner_type: 'Admin', owner: fabricate 'profile', name: 'PI:NAME:<NAME>END_PI' sinon.stub Backbone, 'sync' .onCall 0 .yieldsTo 'success', [@representative] .returns Q.resolve [@representative] afterEach -> Backbone.sync.restore() describe '#render', -> describe 'user with email and name', -> beforeEach -> @view = new Specialist user: @currentUser artwork: @artwork inquiry: @inquiry state: @state @view.render() it 'loads the representative then renders the template', -> @view.__representatives__.then => Backbone.sync.args[0][1].url .should.containEql '/api/v1/admins/available_representatives' @view.$('h1').text() .should.equal 'Send message to Artsy' @view.$('.scontact-description').text() .should.equal 'Foo Bar, an Artsy Specialist, is available to answer your questions and help you collect through Artsy.' @view.$('input[type="text"][name="name"]') .should.have.lengthOf 0 @view.$('input[type="email"][name="email"]') .should.have.lengthOf 0 @view.$('.scontact-from').text() .should.equal 'From: PI:NAME:<NAME>END_PI (PI:EMAIL:<EMAIL>END_PI)' describe 'user without contact details', -> beforeEach -> @loggedOutUser.unset 'name' @loggedOutUser.unset 'email' @view = new Specialist user: @loggedOutUser artwork: @artwork inquiry: @inquiry state: @state @view.render() it 'renders the template', -> @view.$('h1').text() .should.equal 'Send message to Artsy' @view.$('input[type="text"][name="name"]') .should.have.lengthOf 1 @view.$('input[type="email"][name="email"]') .should.have.lengthOf 1 @view.$('.scontact-from').text() .should.be.empty() describe 'next', -> beforeEach -> @state.set 'steps', ['specialist', 'after_specialist'] @loggedOutUser.unset 'name' @loggedOutUser.unset 'email' @view = new Specialist user: @loggedOutUser artwork: @artwork inquiry: @inquiry state: @state @view.render() it 'sets up the inquiry and ensures the user has contact details', -> @view.$('input[name="name"]').val 'PI:NAME:<NAME>END_PI' @view.$('input[name="email"]').val 'PI:EMAIL:<EMAIL>END_PI' @view.$('textarea[name="message"]').val 'I wish to buy the foo bar' @view.$('button').click() @view.__serialize__.then => # Sets up the inquiry @inquiry.get('message').should.equal 'I wish to buy the foo bar' @inquiry.get('contact_gallery').should.be.false() @inquiry.get('artwork').should.equal @artwork.id # Sets up the user @loggedOutUser.get('name').should.equal 'PI:NAME:<NAME>END_PI' @loggedOutUser.get('email').should.equal 'PI:EMAIL:<EMAIL>END_PI' Backbone.sync.callCount.should.equal 3 Backbone.sync.args[0][1].url .should.containEql '/api/v1/admins/available_representatives' Backbone.sync.args[1][1].url() .should.containEql "/api/v1/me/anonymous_session/#{@loggedOutUser.id}" Backbone.sync.args[2][1].url() .should.containEql "/api/v1/profile" # Next @view.state.current().should.equal 'after_specialist'