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": "[\n {\n type: \"text\"\n id: \"username\"\n floatingLabelText: \"Username\"\n ", "end": 613, "score": 0.999087929725647, "start": 605, "tag": "USERNAME", "value": "username" }, { "context": " id: \"username\"\n float...
src/components/app/pages/user/create_user.coffee
dwetterau/base-node-app
0
React = require 'react' Router = require 'react-router' FormPage = require './form_page' {userCreateRequest} = require '../../actions' Notifier = require '../../utils/notifier' CreateUser = React.createClass mixins: [Router.Navigation] _onSubmit: (fields) -> userCreateRequest(fields).then (response) => @transitionTo response.redirect_url Notifier.info 'Account created!' .catch Notifier.error render: () -> React.createElement FormPage, pageHeader: 'Create an account' action: '/user/create' inputs: [ { type: "text" id: "username" floatingLabelText: "Username" }, { type: "password" id: "password" floatingLabelText: "Password" }, { type: "password" id: "confirm_password" floatingLabelText: "Confirm Password" } ] submitLabel: 'Create account' onSubmit: @_onSubmit module.exports = CreateUser
125407
React = require 'react' Router = require 'react-router' FormPage = require './form_page' {userCreateRequest} = require '../../actions' Notifier = require '../../utils/notifier' CreateUser = React.createClass mixins: [Router.Navigation] _onSubmit: (fields) -> userCreateRequest(fields).then (response) => @transitionTo response.redirect_url Notifier.info 'Account created!' .catch Notifier.error render: () -> React.createElement FormPage, pageHeader: 'Create an account' action: '/user/create' inputs: [ { type: "text" id: "username" floatingLabelText: "Username" }, { type: "<PASSWORD>" id: "<PASSWORD>" floatingLabelText: "<PASSWORD>" }, { type: "<PASSWORD>" id: "<PASSWORD>" floatingLabelText: "<PASSWORD>" } ] submitLabel: 'Create account' onSubmit: @_onSubmit module.exports = CreateUser
true
React = require 'react' Router = require 'react-router' FormPage = require './form_page' {userCreateRequest} = require '../../actions' Notifier = require '../../utils/notifier' CreateUser = React.createClass mixins: [Router.Navigation] _onSubmit: (fields) -> userCreateRequest(fields).then (response) => @transitionTo response.redirect_url Notifier.info 'Account created!' .catch Notifier.error render: () -> React.createElement FormPage, pageHeader: 'Create an account' action: '/user/create' inputs: [ { type: "text" id: "username" floatingLabelText: "Username" }, { type: "PI:PASSWORD:<PASSWORD>END_PI" id: "PI:PASSWORD:<PASSWORD>END_PI" floatingLabelText: "PI:PASSWORD:<PASSWORD>END_PI" }, { type: "PI:PASSWORD:<PASSWORD>END_PI" id: "PI:PASSWORD:<PASSWORD>END_PI" floatingLabelText: "PI:PASSWORD:<PASSWORD>END_PI" } ] submitLabel: 'Create account' onSubmit: @_onSubmit module.exports = CreateUser
[ { "context": " \", 60, 0],\n [\"Project Development Per-Arne Andersen\", 40, 0],\n [\"Project Development Pau", "end": 1034, "score": 0.9998760223388672, "start": 1017, "tag": "NAME", "value": "Per-Arne Andersen" }, { "context": "rsen\", 40, 0],\n ...
GOTHAM/Game/src/scenes/Menu.coffee
perara/gotham
0
###* # THe menu scene is running after the loading scene. Options are to Play Game , # @class Menu # @module Frontend.Scenes # @namespace GothamGame.Scenes # @extends Gotham.Graphics.Scene ### class Menu extends Gotham.Graphics.Scene create: -> that = @ # Create Background @createBackground() # Document Container @documentContainer = new Gotham.Graphics.Container() @addChild @documentContainer # Singleplayer button @buttons = [] @addButton "Play Game", -> GothamGame.Renderer.setScene "World" # Settings button @addButton "Settings", -> Settings = new GothamGame.Controllers.Settings "Settings" that.addObject Settings # About Button ready = true @addButton "Credits", -> if ready ready = false else return # Credits # [0] = Text # [1] = Size # [2] = Delay credits = [ [" Introducing ", 60, 0], ["Project Development Per-Arne Andersen", 40, 0], ["Project Development Paul Richard Lilleland", 40, 0], [" ", 40, 1000], [" Thanks to ", 60, 0], ["Supervisor Christian Auby ", 60, 0], ["Supervisor Sigurd Kristian Brinch", 60, 0], ["Assisting Supervisor Morten Goodwin ", 60, 0], [" ", 40, 1000], [" Special Thanks to ", 60, 0], ["Library Provider PIXI.js Team ", 40, 0], ["Library Provider Howler.js Team ", 40, 0], ["Library Provider Socket.IO Team ", 40, 0], ["Library Provider JQuery Team ", 40, 0], ["Library Provider Sequelize Team ", 40, 0], ["Library Provider TaffyDB Team ", 40, 0], ["Library Provider nHibernate Team ", 40, 0], [" ", 40, 1000], [" Other Technologies ", 60, 0], [" MariaDB ", 60, 0], [" nginx ", 60, 0], [" Google Maps ", 60, 0], [" Node.JS ", 60, 0], ] i = 0 intervalID = setInterval (()-> item = credits[i++] text = new Gotham.Graphics.Text(item[0], {font: "bold #{item[1]}px calibri", stroke: "#000000", strokeThickness: 4, fill: "#ffffff", align: "left", dropShadow: true}); text.anchor = x: 0.5 y: 0.5 text.x = 1920 / 2 text.y = 1080 text.alpha = 0 that.addChild text tween = new Gotham.Tween text tween.delay item[2] tween.to {y: 800, alpha: 1}, 2000 tween.to {y: 300}, 7000 tween.to {y: 200, alpha: 0}, 1300 tween.onComplete ()-> that.removeChild text tween.start() if i >= credits.length ready = true clearInterval intervalID ),1000 # Gotham Button @addButton "Exit", -> window.location.href = "http://gotham.no"; @drawButtons() @setupMusic() setupMusic: () -> sound = Gotham.Preload.fetch("menu_theme", "audio") sound.volume(0.5) sound.loop true sound.play() createBackground: () -> # Game Title @gameTitle = gameTitle = new Gotham.Graphics.Text("Gotham", {font: "bold 100px Orbitron", fill: "#000000", align: "center", stroke: "#FFFFFF", strokeThickness: 4}); gameTitle.x = 1920 / 2 gameTitle.y = 125 gameTitle.anchor = x: 0.5 y: 0.5 originalTitleScale = x: gameTitle.scale.x y: gameTitle.scale.y tween = new Gotham.Tween gameTitle tween.repeat(Infinity) tween.easing Gotham.Tween.Easing.Linear.None tween.to { scale: x: originalTitleScale.x + 0.2 y: originalTitleScale.y + 0.2 }, 10000 tween.to { scale: x: originalTitleScale.x y: originalTitleScale.y }, 10000 tween.start() texture = Gotham.Preload.fetch("menu_background", "image") texture2 = Gotham.Preload.fetch("menu_background2", "image") textures = [texture, texture2] swap = -> next = textures.shift() textures.push next return next sprite = new Gotham.Graphics.Sprite swap() sprite.width = 1920 sprite.height = 1080 sprite.alpha = 1 sprite.anchor = x: 0.5 y: 0.5 sprite.position = x: sprite.width / 2 y: sprite.height / 2 originalScale = x: sprite.scale.x y: sprite.scale.y tween = new Gotham.Tween sprite tween.repeat(Infinity) tween.easing Gotham.Tween.Easing.Linear.None tween.to { scale: x: originalScale.x + 0.8 y: originalScale.y + 0.8 }, 80000 tween.delay(2000) tween.to { alpha: 0 }, 5000 tween.to { scale: x: originalScale.x y: originalScale.y }, 1 tween.func -> sprite.texture = swap() tween.to { alpha: 1 }, 2000 tween.start() @addChild sprite @addChild gameTitle addButton: (text, onClick) -> texture = Gotham.Preload.fetch("menu_button", "image") hoverTexture = Gotham.Preload.fetch("menu_button_hover", "image") # Create a sprite sprite = new Gotham.Graphics.Sprite texture sprite.width = 300 sprite.height = 100 sprite.originalScale = sprite.scale sprite.anchor = x: 0.5 y: 0.5 sprite.interactive = true sprite.buttonMode = true # Create a text object text = new Gotham.Graphics.Text(text, {font: "bold 70px Arial", fill: "#ffffff", align: "center", dropShadow: true }, 0,0) # Ensure anchors are 0 text.anchor = x: 0.5 y: 0.5 # Position the text centered in the sprite text.x = 0 text.y = 0 # Create Events sprite.mouseover = (mouseData) -> @texture = hoverTexture sound = Gotham.Preload.fetch("button_click_1", "audio") sound.volume(0.5) sound.loop(false) sound.play() that = @ sprite.mouseout = (mouseData) -> @texture = texture sprite.click = (mouseData) -> onClick(mouseData) sprite.addChild text @buttons.push(sprite) drawButtons: () -> startX = (1920 / 2) startY = 350 counter = 0 for button in @buttons button.x = startX button.y = startY + (counter * (button.height + 10)) counter++ @addChild button module.exports = Menu
195457
###* # THe menu scene is running after the loading scene. Options are to Play Game , # @class Menu # @module Frontend.Scenes # @namespace GothamGame.Scenes # @extends Gotham.Graphics.Scene ### class Menu extends Gotham.Graphics.Scene create: -> that = @ # Create Background @createBackground() # Document Container @documentContainer = new Gotham.Graphics.Container() @addChild @documentContainer # Singleplayer button @buttons = [] @addButton "Play Game", -> GothamGame.Renderer.setScene "World" # Settings button @addButton "Settings", -> Settings = new GothamGame.Controllers.Settings "Settings" that.addObject Settings # About Button ready = true @addButton "Credits", -> if ready ready = false else return # Credits # [0] = Text # [1] = Size # [2] = Delay credits = [ [" Introducing ", 60, 0], ["Project Development <NAME>", 40, 0], ["Project Development <NAME>", 40, 0], [" ", 40, 1000], [" Thanks to ", 60, 0], ["Supervisor <NAME> ", 60, 0], ["Supervisor <NAME>", 60, 0], ["Assisting Supervisor <NAME> ", 60, 0], [" ", 40, 1000], [" Special Thanks to ", 60, 0], ["Library Provider PIXI.js Team ", 40, 0], ["Library Provider Howler.js Team ", 40, 0], ["Library Provider Socket.IO Team ", 40, 0], ["Library Provider JQuery Team ", 40, 0], ["Library Provider Sequelize Team ", 40, 0], ["Library Provider TaffyDB Team ", 40, 0], ["Library Provider nHibernate Team ", 40, 0], [" ", 40, 1000], [" Other Technologies ", 60, 0], [" MariaDB ", 60, 0], [" nginx ", 60, 0], [" Google Maps ", 60, 0], [" Node.JS ", 60, 0], ] i = 0 intervalID = setInterval (()-> item = credits[i++] text = new Gotham.Graphics.Text(item[0], {font: "bold #{item[1]}px calibri", stroke: "#000000", strokeThickness: 4, fill: "#ffffff", align: "left", dropShadow: true}); text.anchor = x: 0.5 y: 0.5 text.x = 1920 / 2 text.y = 1080 text.alpha = 0 that.addChild text tween = new Gotham.Tween text tween.delay item[2] tween.to {y: 800, alpha: 1}, 2000 tween.to {y: 300}, 7000 tween.to {y: 200, alpha: 0}, 1300 tween.onComplete ()-> that.removeChild text tween.start() if i >= credits.length ready = true clearInterval intervalID ),1000 # Gotham Button @addButton "Exit", -> window.location.href = "http://gotham.no"; @drawButtons() @setupMusic() setupMusic: () -> sound = Gotham.Preload.fetch("menu_theme", "audio") sound.volume(0.5) sound.loop true sound.play() createBackground: () -> # Game Title @gameTitle = gameTitle = new Gotham.Graphics.Text("Gotham", {font: "bold 100px Orbitron", fill: "#000000", align: "center", stroke: "#FFFFFF", strokeThickness: 4}); gameTitle.x = 1920 / 2 gameTitle.y = 125 gameTitle.anchor = x: 0.5 y: 0.5 originalTitleScale = x: gameTitle.scale.x y: gameTitle.scale.y tween = new Gotham.Tween gameTitle tween.repeat(Infinity) tween.easing Gotham.Tween.Easing.Linear.None tween.to { scale: x: originalTitleScale.x + 0.2 y: originalTitleScale.y + 0.2 }, 10000 tween.to { scale: x: originalTitleScale.x y: originalTitleScale.y }, 10000 tween.start() texture = Gotham.Preload.fetch("menu_background", "image") texture2 = Gotham.Preload.fetch("menu_background2", "image") textures = [texture, texture2] swap = -> next = textures.shift() textures.push next return next sprite = new Gotham.Graphics.Sprite swap() sprite.width = 1920 sprite.height = 1080 sprite.alpha = 1 sprite.anchor = x: 0.5 y: 0.5 sprite.position = x: sprite.width / 2 y: sprite.height / 2 originalScale = x: sprite.scale.x y: sprite.scale.y tween = new Gotham.Tween sprite tween.repeat(Infinity) tween.easing Gotham.Tween.Easing.Linear.None tween.to { scale: x: originalScale.x + 0.8 y: originalScale.y + 0.8 }, 80000 tween.delay(2000) tween.to { alpha: 0 }, 5000 tween.to { scale: x: originalScale.x y: originalScale.y }, 1 tween.func -> sprite.texture = swap() tween.to { alpha: 1 }, 2000 tween.start() @addChild sprite @addChild gameTitle addButton: (text, onClick) -> texture = Gotham.Preload.fetch("menu_button", "image") hoverTexture = Gotham.Preload.fetch("menu_button_hover", "image") # Create a sprite sprite = new Gotham.Graphics.Sprite texture sprite.width = 300 sprite.height = 100 sprite.originalScale = sprite.scale sprite.anchor = x: 0.5 y: 0.5 sprite.interactive = true sprite.buttonMode = true # Create a text object text = new Gotham.Graphics.Text(text, {font: "bold 70px Arial", fill: "#ffffff", align: "center", dropShadow: true }, 0,0) # Ensure anchors are 0 text.anchor = x: 0.5 y: 0.5 # Position the text centered in the sprite text.x = 0 text.y = 0 # Create Events sprite.mouseover = (mouseData) -> @texture = hoverTexture sound = Gotham.Preload.fetch("button_click_1", "audio") sound.volume(0.5) sound.loop(false) sound.play() that = @ sprite.mouseout = (mouseData) -> @texture = texture sprite.click = (mouseData) -> onClick(mouseData) sprite.addChild text @buttons.push(sprite) drawButtons: () -> startX = (1920 / 2) startY = 350 counter = 0 for button in @buttons button.x = startX button.y = startY + (counter * (button.height + 10)) counter++ @addChild button module.exports = Menu
true
###* # THe menu scene is running after the loading scene. Options are to Play Game , # @class Menu # @module Frontend.Scenes # @namespace GothamGame.Scenes # @extends Gotham.Graphics.Scene ### class Menu extends Gotham.Graphics.Scene create: -> that = @ # Create Background @createBackground() # Document Container @documentContainer = new Gotham.Graphics.Container() @addChild @documentContainer # Singleplayer button @buttons = [] @addButton "Play Game", -> GothamGame.Renderer.setScene "World" # Settings button @addButton "Settings", -> Settings = new GothamGame.Controllers.Settings "Settings" that.addObject Settings # About Button ready = true @addButton "Credits", -> if ready ready = false else return # Credits # [0] = Text # [1] = Size # [2] = Delay credits = [ [" Introducing ", 60, 0], ["Project Development PI:NAME:<NAME>END_PI", 40, 0], ["Project Development PI:NAME:<NAME>END_PI", 40, 0], [" ", 40, 1000], [" Thanks to ", 60, 0], ["Supervisor PI:NAME:<NAME>END_PI ", 60, 0], ["Supervisor PI:NAME:<NAME>END_PI", 60, 0], ["Assisting Supervisor PI:NAME:<NAME>END_PI ", 60, 0], [" ", 40, 1000], [" Special Thanks to ", 60, 0], ["Library Provider PIXI.js Team ", 40, 0], ["Library Provider Howler.js Team ", 40, 0], ["Library Provider Socket.IO Team ", 40, 0], ["Library Provider JQuery Team ", 40, 0], ["Library Provider Sequelize Team ", 40, 0], ["Library Provider TaffyDB Team ", 40, 0], ["Library Provider nHibernate Team ", 40, 0], [" ", 40, 1000], [" Other Technologies ", 60, 0], [" MariaDB ", 60, 0], [" nginx ", 60, 0], [" Google Maps ", 60, 0], [" Node.JS ", 60, 0], ] i = 0 intervalID = setInterval (()-> item = credits[i++] text = new Gotham.Graphics.Text(item[0], {font: "bold #{item[1]}px calibri", stroke: "#000000", strokeThickness: 4, fill: "#ffffff", align: "left", dropShadow: true}); text.anchor = x: 0.5 y: 0.5 text.x = 1920 / 2 text.y = 1080 text.alpha = 0 that.addChild text tween = new Gotham.Tween text tween.delay item[2] tween.to {y: 800, alpha: 1}, 2000 tween.to {y: 300}, 7000 tween.to {y: 200, alpha: 0}, 1300 tween.onComplete ()-> that.removeChild text tween.start() if i >= credits.length ready = true clearInterval intervalID ),1000 # Gotham Button @addButton "Exit", -> window.location.href = "http://gotham.no"; @drawButtons() @setupMusic() setupMusic: () -> sound = Gotham.Preload.fetch("menu_theme", "audio") sound.volume(0.5) sound.loop true sound.play() createBackground: () -> # Game Title @gameTitle = gameTitle = new Gotham.Graphics.Text("Gotham", {font: "bold 100px Orbitron", fill: "#000000", align: "center", stroke: "#FFFFFF", strokeThickness: 4}); gameTitle.x = 1920 / 2 gameTitle.y = 125 gameTitle.anchor = x: 0.5 y: 0.5 originalTitleScale = x: gameTitle.scale.x y: gameTitle.scale.y tween = new Gotham.Tween gameTitle tween.repeat(Infinity) tween.easing Gotham.Tween.Easing.Linear.None tween.to { scale: x: originalTitleScale.x + 0.2 y: originalTitleScale.y + 0.2 }, 10000 tween.to { scale: x: originalTitleScale.x y: originalTitleScale.y }, 10000 tween.start() texture = Gotham.Preload.fetch("menu_background", "image") texture2 = Gotham.Preload.fetch("menu_background2", "image") textures = [texture, texture2] swap = -> next = textures.shift() textures.push next return next sprite = new Gotham.Graphics.Sprite swap() sprite.width = 1920 sprite.height = 1080 sprite.alpha = 1 sprite.anchor = x: 0.5 y: 0.5 sprite.position = x: sprite.width / 2 y: sprite.height / 2 originalScale = x: sprite.scale.x y: sprite.scale.y tween = new Gotham.Tween sprite tween.repeat(Infinity) tween.easing Gotham.Tween.Easing.Linear.None tween.to { scale: x: originalScale.x + 0.8 y: originalScale.y + 0.8 }, 80000 tween.delay(2000) tween.to { alpha: 0 }, 5000 tween.to { scale: x: originalScale.x y: originalScale.y }, 1 tween.func -> sprite.texture = swap() tween.to { alpha: 1 }, 2000 tween.start() @addChild sprite @addChild gameTitle addButton: (text, onClick) -> texture = Gotham.Preload.fetch("menu_button", "image") hoverTexture = Gotham.Preload.fetch("menu_button_hover", "image") # Create a sprite sprite = new Gotham.Graphics.Sprite texture sprite.width = 300 sprite.height = 100 sprite.originalScale = sprite.scale sprite.anchor = x: 0.5 y: 0.5 sprite.interactive = true sprite.buttonMode = true # Create a text object text = new Gotham.Graphics.Text(text, {font: "bold 70px Arial", fill: "#ffffff", align: "center", dropShadow: true }, 0,0) # Ensure anchors are 0 text.anchor = x: 0.5 y: 0.5 # Position the text centered in the sprite text.x = 0 text.y = 0 # Create Events sprite.mouseover = (mouseData) -> @texture = hoverTexture sound = Gotham.Preload.fetch("button_click_1", "audio") sound.volume(0.5) sound.loop(false) sound.play() that = @ sprite.mouseout = (mouseData) -> @texture = texture sprite.click = (mouseData) -> onClick(mouseData) sprite.addChild text @buttons.push(sprite) drawButtons: () -> startX = (1920 / 2) startY = 350 counter = 0 for button in @buttons button.x = startX button.y = startY + (counter * (button.height + 10)) counter++ @addChild button module.exports = Menu
[ { "context": "e\n\n\t\tif doc.login_password\n\t\t\tdoc.login_password = Steedos.encrypt(doc.login_password, doc.login_name, cryptI", "end": 1797, "score": 0.9474103450775146, "start": 1790, "tag": "PASSWORD", "value": "Steedos" }, { "context": "t.login_password\n\t\t\tmodifier.$set....
creator/packages/steedos-app-portal/models/apps_auth_users.coffee
yicone/steedos-platform
42
db.apps_auth_users = new Meteor.Collection('apps_auth_users') # db.apps_auth_users._simpleSchema = new SimpleSchema Creator.Objects.apps_auth_users = name: "apps_auth_users" label: "域账户" icon: "apps" fields: auth_name: label: "域名称" type: "text" is_name:true required: true user: label: "关联用户" type: "lookup" reference_to: "users" required: true defaultValue: ()-> if Meteor.isClient return Meteor.userId() user_name: label: "用户名称" type: "text" omit: true hidden: true login_name: label: "登录名" type: "text" required: true login_password: label: "登录密码" type: "password" required: true is_encrypted: label: "密码加密" type: "boolean" omit: true list_views: all: label: "所有" filter_scope: "space" columns: ["auth_name", "user_name", "login_name", "modified"] permission_set: user: allowCreate: true allowDelete: true allowEdit: true allowRead: true modifyAllRecords: false viewAllRecords: false admin: allowCreate: true allowDelete: true allowEdit: true allowRead: true modifyAllRecords: true viewAllRecords: true # if Meteor.isClient # db.apps_auth_users._simpleSchema.i18n("apps_auth_users") # db.apps_auth_users.attachSchema(db.apps_auth_users._simpleSchema) if Meteor.isServer cryptIvForAuthUsers = "-auth-user201702" db.apps_auth_users.before.insert (userId, doc) -> if !userId throw new Meteor.Error(400, t("portal_dashboards_error_login_required")); # check space exists space = db.spaces.findOne(doc.space) if !space throw new Meteor.Error(400, t("portal_dashboards_error_space_not_found")); doc.user_name = db.users.findOne(doc.user).name if doc.login_password doc.login_password = Steedos.encrypt(doc.login_password, doc.login_name, cryptIvForAuthUsers); doc.is_encrypted = true doc.created_by = userId doc.created = new Date() doc.modified_by = userId doc.modified = new Date() db.apps_auth_users.before.update (userId, doc, fieldNames, modifier, options) -> if !userId throw new Meteor.Error(400, t("portal_dashboards_error_login_required")); # check space exists space = db.spaces.findOne(doc.space) if !space throw new Meteor.Error(400, t("portal_dashboards_error_space_not_found")); # only seft can edit if space.admins.indexOf(userId) < 0 and userId != doc.user throw new Meteor.Error(400, t("apps_auth_users_error_self_edit_only")); modifier.$set = modifier.$set || {}; modifier.$set.user_name = db.users.findOne(doc.user).name; login_name = doc.login_name if modifier.$set.login_name login_name = modifier.$set.login_name if modifier.$set.login_password modifier.$set.login_password = Steedos.encrypt(modifier.$set.login_password, login_name, cryptIvForAuthUsers); modifier.$set.is_encrypted = true modifier.$set.modified_by = userId; modifier.$set.modified = new Date(); db.apps_auth_users.before.remove (userId, doc) -> if !userId throw new Meteor.Error(400, t("portal_dashboards_error_login_required")); # check space exists space = db.spaces.findOne(doc.space) if !space throw new Meteor.Error(400, t("portal_dashboards_error_space_not_found")); # only seft can remove if space.admins.indexOf(userId) < 0 and userId != doc.user throw new Meteor.Error(400, t("apps_auth_users_error_self_remove_only")); db.apps_auth_users.after.findOne (userId, selector, options, doc)-> if doc?.login_password and doc?.is_encrypted doc.login_password = Steedos.decrypt(doc.login_password, doc.login_name, cryptIvForAuthUsers)
104169
db.apps_auth_users = new Meteor.Collection('apps_auth_users') # db.apps_auth_users._simpleSchema = new SimpleSchema Creator.Objects.apps_auth_users = name: "apps_auth_users" label: "域账户" icon: "apps" fields: auth_name: label: "域名称" type: "text" is_name:true required: true user: label: "关联用户" type: "lookup" reference_to: "users" required: true defaultValue: ()-> if Meteor.isClient return Meteor.userId() user_name: label: "用户名称" type: "text" omit: true hidden: true login_name: label: "登录名" type: "text" required: true login_password: label: "登录密码" type: "password" required: true is_encrypted: label: "密码加密" type: "boolean" omit: true list_views: all: label: "所有" filter_scope: "space" columns: ["auth_name", "user_name", "login_name", "modified"] permission_set: user: allowCreate: true allowDelete: true allowEdit: true allowRead: true modifyAllRecords: false viewAllRecords: false admin: allowCreate: true allowDelete: true allowEdit: true allowRead: true modifyAllRecords: true viewAllRecords: true # if Meteor.isClient # db.apps_auth_users._simpleSchema.i18n("apps_auth_users") # db.apps_auth_users.attachSchema(db.apps_auth_users._simpleSchema) if Meteor.isServer cryptIvForAuthUsers = "-auth-user201702" db.apps_auth_users.before.insert (userId, doc) -> if !userId throw new Meteor.Error(400, t("portal_dashboards_error_login_required")); # check space exists space = db.spaces.findOne(doc.space) if !space throw new Meteor.Error(400, t("portal_dashboards_error_space_not_found")); doc.user_name = db.users.findOne(doc.user).name if doc.login_password doc.login_password = <PASSWORD>.encrypt(doc.login_password, doc.login_name, cryptIvForAuthUsers); doc.is_encrypted = true doc.created_by = userId doc.created = new Date() doc.modified_by = userId doc.modified = new Date() db.apps_auth_users.before.update (userId, doc, fieldNames, modifier, options) -> if !userId throw new Meteor.Error(400, t("portal_dashboards_error_login_required")); # check space exists space = db.spaces.findOne(doc.space) if !space throw new Meteor.Error(400, t("portal_dashboards_error_space_not_found")); # only seft can edit if space.admins.indexOf(userId) < 0 and userId != doc.user throw new Meteor.Error(400, t("apps_auth_users_error_self_edit_only")); modifier.$set = modifier.$set || {}; modifier.$set.user_name = db.users.findOne(doc.user).name; login_name = doc.login_name if modifier.$set.login_name login_name = modifier.$set.login_name if modifier.$set.login_password modifier.$set.login_password = <PASSWORD>.encrypt(modifier.$set.login_password, login_name, cryptIvForAuthUsers); modifier.$set.is_encrypted = true modifier.$set.modified_by = userId; modifier.$set.modified = new Date(); db.apps_auth_users.before.remove (userId, doc) -> if !userId throw new Meteor.Error(400, t("portal_dashboards_error_login_required")); # check space exists space = db.spaces.findOne(doc.space) if !space throw new Meteor.Error(400, t("portal_dashboards_error_space_not_found")); # only seft can remove if space.admins.indexOf(userId) < 0 and userId != doc.user throw new Meteor.Error(400, t("apps_auth_users_error_self_remove_only")); db.apps_auth_users.after.findOne (userId, selector, options, doc)-> if doc?.login_password and doc?.is_encrypted doc.login_password = <PASSWORD>(doc.login_password, doc.login_name, cryptIvForAuthUsers)
true
db.apps_auth_users = new Meteor.Collection('apps_auth_users') # db.apps_auth_users._simpleSchema = new SimpleSchema Creator.Objects.apps_auth_users = name: "apps_auth_users" label: "域账户" icon: "apps" fields: auth_name: label: "域名称" type: "text" is_name:true required: true user: label: "关联用户" type: "lookup" reference_to: "users" required: true defaultValue: ()-> if Meteor.isClient return Meteor.userId() user_name: label: "用户名称" type: "text" omit: true hidden: true login_name: label: "登录名" type: "text" required: true login_password: label: "登录密码" type: "password" required: true is_encrypted: label: "密码加密" type: "boolean" omit: true list_views: all: label: "所有" filter_scope: "space" columns: ["auth_name", "user_name", "login_name", "modified"] permission_set: user: allowCreate: true allowDelete: true allowEdit: true allowRead: true modifyAllRecords: false viewAllRecords: false admin: allowCreate: true allowDelete: true allowEdit: true allowRead: true modifyAllRecords: true viewAllRecords: true # if Meteor.isClient # db.apps_auth_users._simpleSchema.i18n("apps_auth_users") # db.apps_auth_users.attachSchema(db.apps_auth_users._simpleSchema) if Meteor.isServer cryptIvForAuthUsers = "-auth-user201702" db.apps_auth_users.before.insert (userId, doc) -> if !userId throw new Meteor.Error(400, t("portal_dashboards_error_login_required")); # check space exists space = db.spaces.findOne(doc.space) if !space throw new Meteor.Error(400, t("portal_dashboards_error_space_not_found")); doc.user_name = db.users.findOne(doc.user).name if doc.login_password doc.login_password = PI:PASSWORD:<PASSWORD>END_PI.encrypt(doc.login_password, doc.login_name, cryptIvForAuthUsers); doc.is_encrypted = true doc.created_by = userId doc.created = new Date() doc.modified_by = userId doc.modified = new Date() db.apps_auth_users.before.update (userId, doc, fieldNames, modifier, options) -> if !userId throw new Meteor.Error(400, t("portal_dashboards_error_login_required")); # check space exists space = db.spaces.findOne(doc.space) if !space throw new Meteor.Error(400, t("portal_dashboards_error_space_not_found")); # only seft can edit if space.admins.indexOf(userId) < 0 and userId != doc.user throw new Meteor.Error(400, t("apps_auth_users_error_self_edit_only")); modifier.$set = modifier.$set || {}; modifier.$set.user_name = db.users.findOne(doc.user).name; login_name = doc.login_name if modifier.$set.login_name login_name = modifier.$set.login_name if modifier.$set.login_password modifier.$set.login_password = PI:PASSWORD:<PASSWORD>END_PI.encrypt(modifier.$set.login_password, login_name, cryptIvForAuthUsers); modifier.$set.is_encrypted = true modifier.$set.modified_by = userId; modifier.$set.modified = new Date(); db.apps_auth_users.before.remove (userId, doc) -> if !userId throw new Meteor.Error(400, t("portal_dashboards_error_login_required")); # check space exists space = db.spaces.findOne(doc.space) if !space throw new Meteor.Error(400, t("portal_dashboards_error_space_not_found")); # only seft can remove if space.admins.indexOf(userId) < 0 and userId != doc.user throw new Meteor.Error(400, t("apps_auth_users_error_self_remove_only")); db.apps_auth_users.after.findOne (userId, selector, options, doc)-> if doc?.login_password and doc?.is_encrypted doc.login_password = PI:PASSWORD:<PASSWORD>END_PI(doc.login_password, doc.login_name, cryptIvForAuthUsers)
[ { "context": " new Definition('somekey', 'avalue', type: 'Jean-Paul Sartre')\n catch e\n errorRaised = true\n expect", "end": 913, "score": 0.9071397185325623, "start": 899, "tag": "NAME", "value": "an-Paul Sartre" } ]
test/unit/DefinitionTest.coffee
deepdancer/deepdancer
0
{expect, config} = require 'chai' config.includeStack = true Definition = require 'deepdancer/Definition' # coffeelint: disable=cyclomatic_complexity describe 'deepdancer/Definition', -> it 'should correctly validate the type', -> errorRaised = false try definition = new Definition('somekey', 'avalue') catch e errorRaised = true expect(errorRaised).to.be.false expect(definition.type).to.be.equal 'value' errorRaised = false try new Definition('somekey', Error, { type: 'class', arityCheck: false }) catch e errorRaised = true expect(errorRaised).to.be.false errorRaised = false try new Definition('somekey', (-> 'hi'), type: 'factory') catch e errorRaised = true expect(errorRaised).to.be.false errorRaised = false try new Definition('somekey', 'avalue', type: 'Jean-Paul Sartre') catch e errorRaised = true expect(errorRaised).to.be.true it 'should correctly validate the lifespan', -> errorRaised = false try new Definition('somekey', 'avalue', lifespan: 'container') catch e errorRaised = true expect(errorRaised).to.be.false errorRaised = false try new Definition('somekey', 'avalue', lifespan: 'call') catch e errorRaised = true expect(errorRaised).to.be.false errorRaised = false try new Definition('somekey', 'avalue', lifespan: 'callaaaa') catch e errorRaised = true expect(errorRaised).to.be.true it 'should correctly validate the setupCalls', -> correctSetupCall1 = method: 'someMethod' args: [] correctSetupCall2 = method: 'someMethod2' args: [1,2,3] incorrectSetupCall = method: 'someMethod3' ar: [1,2,3] errorRaised = false try new Definition('somekey', 'avalue', { lifespan: 'container', setupCalls: [correctSetupCall1, correctSetupCall2] }) catch e errorRaised = true expect(errorRaised).to.be.false errorRaised = false try new Definition('somekey', 'avalue', { lifespan: 'container' setupCalls: [correctSetupCall1, incorrectSetupCall] }) catch e errorRaised = true expect(errorRaised).to.be.true testDescription = 'should properly load setup type, lifespan, calls and ' + 'dependencies from the values' it testDescription, -> class TestClass @__dependencies: [12] @__type = 'class' @__lifespan = 'call' constructor: (@someValue) -> @port = undefined setPort: (port) => @port = port TestClass.__setupCalls = [{method: 'setPort', args: ['config.port']}] definition = new Definition('testObject', TestClass) expect(definition.type).to.be.equal 'class' expect(definition.lifespan).to.be.equal 'call' expect(definition.dependencies).to.have.length 1 expect(definition.setupCalls).to.have.length 1 it 'should be able to handle arity problems within factories and classes', -> someFactory = (someDependency) -> 'hi' errorRaised = false try new Definition('someFactory', someFactory, type: 'factory') catch errorRaised = true expect(errorRaised).to.be.true # coffeelint: enable=cyclomatic_complexity
159280
{expect, config} = require 'chai' config.includeStack = true Definition = require 'deepdancer/Definition' # coffeelint: disable=cyclomatic_complexity describe 'deepdancer/Definition', -> it 'should correctly validate the type', -> errorRaised = false try definition = new Definition('somekey', 'avalue') catch e errorRaised = true expect(errorRaised).to.be.false expect(definition.type).to.be.equal 'value' errorRaised = false try new Definition('somekey', Error, { type: 'class', arityCheck: false }) catch e errorRaised = true expect(errorRaised).to.be.false errorRaised = false try new Definition('somekey', (-> 'hi'), type: 'factory') catch e errorRaised = true expect(errorRaised).to.be.false errorRaised = false try new Definition('somekey', 'avalue', type: 'Je<NAME>') catch e errorRaised = true expect(errorRaised).to.be.true it 'should correctly validate the lifespan', -> errorRaised = false try new Definition('somekey', 'avalue', lifespan: 'container') catch e errorRaised = true expect(errorRaised).to.be.false errorRaised = false try new Definition('somekey', 'avalue', lifespan: 'call') catch e errorRaised = true expect(errorRaised).to.be.false errorRaised = false try new Definition('somekey', 'avalue', lifespan: 'callaaaa') catch e errorRaised = true expect(errorRaised).to.be.true it 'should correctly validate the setupCalls', -> correctSetupCall1 = method: 'someMethod' args: [] correctSetupCall2 = method: 'someMethod2' args: [1,2,3] incorrectSetupCall = method: 'someMethod3' ar: [1,2,3] errorRaised = false try new Definition('somekey', 'avalue', { lifespan: 'container', setupCalls: [correctSetupCall1, correctSetupCall2] }) catch e errorRaised = true expect(errorRaised).to.be.false errorRaised = false try new Definition('somekey', 'avalue', { lifespan: 'container' setupCalls: [correctSetupCall1, incorrectSetupCall] }) catch e errorRaised = true expect(errorRaised).to.be.true testDescription = 'should properly load setup type, lifespan, calls and ' + 'dependencies from the values' it testDescription, -> class TestClass @__dependencies: [12] @__type = 'class' @__lifespan = 'call' constructor: (@someValue) -> @port = undefined setPort: (port) => @port = port TestClass.__setupCalls = [{method: 'setPort', args: ['config.port']}] definition = new Definition('testObject', TestClass) expect(definition.type).to.be.equal 'class' expect(definition.lifespan).to.be.equal 'call' expect(definition.dependencies).to.have.length 1 expect(definition.setupCalls).to.have.length 1 it 'should be able to handle arity problems within factories and classes', -> someFactory = (someDependency) -> 'hi' errorRaised = false try new Definition('someFactory', someFactory, type: 'factory') catch errorRaised = true expect(errorRaised).to.be.true # coffeelint: enable=cyclomatic_complexity
true
{expect, config} = require 'chai' config.includeStack = true Definition = require 'deepdancer/Definition' # coffeelint: disable=cyclomatic_complexity describe 'deepdancer/Definition', -> it 'should correctly validate the type', -> errorRaised = false try definition = new Definition('somekey', 'avalue') catch e errorRaised = true expect(errorRaised).to.be.false expect(definition.type).to.be.equal 'value' errorRaised = false try new Definition('somekey', Error, { type: 'class', arityCheck: false }) catch e errorRaised = true expect(errorRaised).to.be.false errorRaised = false try new Definition('somekey', (-> 'hi'), type: 'factory') catch e errorRaised = true expect(errorRaised).to.be.false errorRaised = false try new Definition('somekey', 'avalue', type: 'JePI:NAME:<NAME>END_PI') catch e errorRaised = true expect(errorRaised).to.be.true it 'should correctly validate the lifespan', -> errorRaised = false try new Definition('somekey', 'avalue', lifespan: 'container') catch e errorRaised = true expect(errorRaised).to.be.false errorRaised = false try new Definition('somekey', 'avalue', lifespan: 'call') catch e errorRaised = true expect(errorRaised).to.be.false errorRaised = false try new Definition('somekey', 'avalue', lifespan: 'callaaaa') catch e errorRaised = true expect(errorRaised).to.be.true it 'should correctly validate the setupCalls', -> correctSetupCall1 = method: 'someMethod' args: [] correctSetupCall2 = method: 'someMethod2' args: [1,2,3] incorrectSetupCall = method: 'someMethod3' ar: [1,2,3] errorRaised = false try new Definition('somekey', 'avalue', { lifespan: 'container', setupCalls: [correctSetupCall1, correctSetupCall2] }) catch e errorRaised = true expect(errorRaised).to.be.false errorRaised = false try new Definition('somekey', 'avalue', { lifespan: 'container' setupCalls: [correctSetupCall1, incorrectSetupCall] }) catch e errorRaised = true expect(errorRaised).to.be.true testDescription = 'should properly load setup type, lifespan, calls and ' + 'dependencies from the values' it testDescription, -> class TestClass @__dependencies: [12] @__type = 'class' @__lifespan = 'call' constructor: (@someValue) -> @port = undefined setPort: (port) => @port = port TestClass.__setupCalls = [{method: 'setPort', args: ['config.port']}] definition = new Definition('testObject', TestClass) expect(definition.type).to.be.equal 'class' expect(definition.lifespan).to.be.equal 'call' expect(definition.dependencies).to.have.length 1 expect(definition.setupCalls).to.have.length 1 it 'should be able to handle arity problems within factories and classes', -> someFactory = (someDependency) -> 'hi' errorRaised = false try new Definition('someFactory', someFactory, type: 'factory') catch errorRaised = true expect(errorRaised).to.be.true # coffeelint: enable=cyclomatic_complexity
[ { "context": "inject ($httpBackend) ->\n _data =\n name: \"Pascal\"\n awesomeness: 42\n\n $httpBackend.whenGET(", "end": 228, "score": 0.9997192025184631, "start": 222, "tag": "NAME", "value": "Pascal" } ]
test/unit/singleton_resource_spec.coffee
killercup/angular-epicmodel
0
describe "Singleton Resource", -> angular.module 'Stuff', ['EpicModel'] beforeEach module('Stuff') beforeEach addHelpers() # ### Mock Server on `/me` beforeEach inject ($httpBackend) -> _data = name: "Pascal" awesomeness: 42 $httpBackend.whenGET('/me').respond (method, url, data) -> log "GET /me" [200, _data, {}] $httpBackend.whenPUT('/me').respond (method, url, data) -> log "POST /me", data _data = _.extend(data, _data) log "new data", _data [200, _data, {}] # ### Initialize new Collection each time Me = null beforeEach inject (Collection) -> Me = Collection.new "Me", is_singleton: true it 'should fetch an object', (done) -> me = Me.all() me.$promise.then -> expect(me.$resolved).to.eql true expect(me.data).to.be.an('object') expect(me.data).to.contain.keys('name', 'awesomeness') done(null) .then null, (err) -> done new Error JSON.stringify err tick() it "should have a 'loading' flag", (done) -> me = Me.all() expect(me.$loading).to.eql true me.$promise.then -> expect(me.$loading).to.eql false expect(me.$resolved).to.eql true done(null) .then null, (err) -> done new Error JSON.stringify err tick() it 'should update an object', (done) -> oldMe = me = Me.all() me.$promise.then -> oldMe = _.cloneDeep(me) me.data.awesomeness += 1 Me.save(me.data) .then (newMe) -> expect(newMe.awesomeness).to.be.above oldMe.data.awesomeness expect(newMe.name).to.eql oldMe.data.name done(null) .then null, (err) -> done new Error JSON.stringify err tick() it 'should not be able to retrieve a detail resource', -> expect(-> Me.get id: 1).to.throw(Error) it 'should not be able to destroy resource', -> expect(Me.destroy).to.throw(Error) it 'should not be able to create entry', -> expect(Me.create).to.throw(Error)
198714
describe "Singleton Resource", -> angular.module 'Stuff', ['EpicModel'] beforeEach module('Stuff') beforeEach addHelpers() # ### Mock Server on `/me` beforeEach inject ($httpBackend) -> _data = name: "<NAME>" awesomeness: 42 $httpBackend.whenGET('/me').respond (method, url, data) -> log "GET /me" [200, _data, {}] $httpBackend.whenPUT('/me').respond (method, url, data) -> log "POST /me", data _data = _.extend(data, _data) log "new data", _data [200, _data, {}] # ### Initialize new Collection each time Me = null beforeEach inject (Collection) -> Me = Collection.new "Me", is_singleton: true it 'should fetch an object', (done) -> me = Me.all() me.$promise.then -> expect(me.$resolved).to.eql true expect(me.data).to.be.an('object') expect(me.data).to.contain.keys('name', 'awesomeness') done(null) .then null, (err) -> done new Error JSON.stringify err tick() it "should have a 'loading' flag", (done) -> me = Me.all() expect(me.$loading).to.eql true me.$promise.then -> expect(me.$loading).to.eql false expect(me.$resolved).to.eql true done(null) .then null, (err) -> done new Error JSON.stringify err tick() it 'should update an object', (done) -> oldMe = me = Me.all() me.$promise.then -> oldMe = _.cloneDeep(me) me.data.awesomeness += 1 Me.save(me.data) .then (newMe) -> expect(newMe.awesomeness).to.be.above oldMe.data.awesomeness expect(newMe.name).to.eql oldMe.data.name done(null) .then null, (err) -> done new Error JSON.stringify err tick() it 'should not be able to retrieve a detail resource', -> expect(-> Me.get id: 1).to.throw(Error) it 'should not be able to destroy resource', -> expect(Me.destroy).to.throw(Error) it 'should not be able to create entry', -> expect(Me.create).to.throw(Error)
true
describe "Singleton Resource", -> angular.module 'Stuff', ['EpicModel'] beforeEach module('Stuff') beforeEach addHelpers() # ### Mock Server on `/me` beforeEach inject ($httpBackend) -> _data = name: "PI:NAME:<NAME>END_PI" awesomeness: 42 $httpBackend.whenGET('/me').respond (method, url, data) -> log "GET /me" [200, _data, {}] $httpBackend.whenPUT('/me').respond (method, url, data) -> log "POST /me", data _data = _.extend(data, _data) log "new data", _data [200, _data, {}] # ### Initialize new Collection each time Me = null beforeEach inject (Collection) -> Me = Collection.new "Me", is_singleton: true it 'should fetch an object', (done) -> me = Me.all() me.$promise.then -> expect(me.$resolved).to.eql true expect(me.data).to.be.an('object') expect(me.data).to.contain.keys('name', 'awesomeness') done(null) .then null, (err) -> done new Error JSON.stringify err tick() it "should have a 'loading' flag", (done) -> me = Me.all() expect(me.$loading).to.eql true me.$promise.then -> expect(me.$loading).to.eql false expect(me.$resolved).to.eql true done(null) .then null, (err) -> done new Error JSON.stringify err tick() it 'should update an object', (done) -> oldMe = me = Me.all() me.$promise.then -> oldMe = _.cloneDeep(me) me.data.awesomeness += 1 Me.save(me.data) .then (newMe) -> expect(newMe.awesomeness).to.be.above oldMe.data.awesomeness expect(newMe.name).to.eql oldMe.data.name done(null) .then null, (err) -> done new Error JSON.stringify err tick() it 'should not be able to retrieve a detail resource', -> expect(-> Me.get id: 1).to.throw(Error) it 'should not be able to destroy resource', -> expect(Me.destroy).to.throw(Error) it 'should not be able to create entry', -> expect(Me.create).to.throw(Error)
[ { "context": ".io'\n tokens:\n access_token: 'random'\n agentOptions: {}\n\n nock.cleanAl", "end": 3830, "score": 0.872805118560791, "start": 3824, "tag": "KEY", "value": "random" }, { "context": ".io'\n tokens:\n access_token: ...
test/rest/scopeSpec.coffee
camfou/connect-nodejs
0
# Test dependencies cwd = process.cwd() path = require 'path' chai = require 'chai' sinon = require 'sinon' sinonChai = require 'sinon-chai' expect = chai.expect nock = require 'nock' # Assertions chai.use sinonChai chai.should() scopes = require path.join(cwd, 'rest', 'scopes') describe 'REST API Scope Methods', -> describe 'list', -> describe 'with a missing access token', -> {promise,success,failure} = {} beforeEach () -> instance = configuration: issuer: 'https://connect.anvil.io' agentOptions: {} nock.cleanAll() nock(instance.configuration.issuer) .get('/v1/scopes') .reply(200, [{_id: 'uuid'}]) success = sinon.spy() failure = sinon.spy() promise = scopes.list.bind(instance)() .then(success, failure) it 'should return a promise', -> promise.should.be.instanceof Promise it 'should not provide scopes', -> success.should.not.have.been.called it 'should catch an error', -> failure.should.have.been.calledWith sinon.match.instanceOf Error describe 'with a successful response', -> {promise,success,failure} = {} before () -> instance = configuration: issuer: 'https://connect.anvil.io' agentOptions: {} nock.cleanAll() nock(instance.configuration.issuer) .get('/v1/scopes') .reply(200, [{_id: 'uuid'}]) success = sinon.spy() failure = sinon.spy() promise = scopes.list.bind(instance)({ token: 'token' }) .then(success, failure) it 'should return a promise', -> promise.should.be.instanceof Promise it 'should provide the scopes', -> success.should.have.been.calledWith sinon.match [{_id:'uuid'}] it 'should not catch an error', -> failure.should.not.have.been.called describe 'with a failure response', -> {promise,success,failure} = {} before () -> instance = configuration: issuer: 'https://connect.anvil.io' agentOptions: {} nock.cleanAll() nock(instance.configuration.issuer) .get('/v1/scopes') .reply(404, 'Not found') success = sinon.spy() failure = sinon.spy() promise = scopes.list.bind(instance)({ token: 'token' }) .then(success, failure) it 'should return a promise', -> promise.should.be.instanceof Promise it 'should not provide the scopes', -> success.should.not.have.been.called it 'should catch an error', -> failure.should.have.been.called describe 'get', -> describe 'with a missing access token', -> {promise,success,failure} = {} beforeEach () -> instance = configuration: issuer: 'https://connect.anvil.io' agentOptions: {} nock.cleanAll() nock(instance.configuration.issuer) .get('/v1/scopes/uuid') .reply(200, [{_id: 'uuid'}]) success = sinon.spy() failure = sinon.spy() promise = scopes.get.bind(instance)('uuid') .then(success, failure) it 'should return a promise', -> promise.should.be.instanceof Promise it 'should not provide scopes', -> success.should.not.have.been.called it 'should catch an error', -> failure.should.have.been.calledWith sinon.match.instanceOf Error describe 'with a successful response', -> {promise,success,failure} = {} before () -> instance = configuration: issuer: 'https://connect.anvil.io' tokens: access_token: 'random' agentOptions: {} nock.cleanAll() nock(instance.configuration.issuer) .get('/v1/scopes/uuid') .reply(200, {_id: 'uuid'}) success = sinon.spy() failure = sinon.spy() promise = scopes.get.bind(instance)('uuid', { token: 'token' }) .then(success, failure) it 'should return a promise', -> promise.should.be.instanceof Promise it 'should provide the scope', -> success.should.have.been.calledWith sinon.match {_id:'uuid'} it 'should not catch an error', -> failure.should.not.have.been.called describe 'with a failure response', -> {promise,success,failure} = {} before () -> instance = configuration: issuer: 'https://connect.anvil.io' tokens: access_token: 'random' agentOptions: {} nock.cleanAll() nock(instance.configuration.issuer) .get('/v1/scopes/uuid') .reply(404, 'Not found') success = sinon.spy() failure = sinon.spy() promise = scopes.get.bind(instance)('uuid', { token: 'token' }) .then(success, failure) it 'should return a promise', -> promise.should.be.instanceof Promise it 'should not provide the scope', -> success.should.not.have.been.called it 'should catch an error', -> failure.should.have.been.called describe 'create', -> describe 'with a missing access token', -> {promise,success,failure} = {} beforeEach () -> instance = configuration: issuer: 'https://connect.anvil.io' agentOptions: {} nock.cleanAll() nock(instance.configuration.issuer) .post('/v1/scopes') .reply(200, [{_id: 'uuid'}]) success = sinon.spy() failure = sinon.spy() promise = scopes.create.bind(instance)({}) .then(success, failure) it 'should return a promise', -> promise.should.be.instanceof Promise it 'should not provide scope', -> success.should.not.have.been.called it 'should catch an error', -> failure.should.have.been.calledWith sinon.match.instanceOf Error describe 'with a successful response', -> {promise,success,failure} = {} before () -> instance = configuration: issuer: 'https://connect.anvil.io' tokens: access_token: 'random' agentOptions: {} nock.cleanAll() nock(instance.configuration.issuer) .post('/v1/scopes', { redirect_uris: ['https://example.anvil.io'] }) .reply(201, { _id: 'uuid' redirect_uris: ['https://example.anvil.io'] }) success = sinon.spy() failure = sinon.spy() promise = scopes.create.bind(instance)({ redirect_uris: ['https://example.anvil.io'] }, { token: 'token' }).then(success, failure) it 'should return a promise', -> promise.should.be.instanceof Promise it 'should provide the scope', -> success.should.have.been.calledWith sinon.match {_id:'uuid'} it 'should not catch an error', -> failure.should.not.have.been.called describe 'with a failure response', -> {promise,success,failure} = {} before () -> instance = configuration: issuer: 'https://connect.anvil.io' tokens: access_token: 'random' agentOptions: {} nock.cleanAll() nock(instance.configuration.issuer) .post('/v1/scopes', {}) .reply(400, 'Bad request') success = sinon.spy() failure = sinon.spy() promise = scopes.create.bind(instance)({ redirect_uris: ['https://example.anvil.io'] }, { token: 'token' }).then(success, failure) it 'should return a promise', -> promise.should.be.instanceof Promise it 'should not provide the scope', -> success.should.not.have.been.called it 'should catch an error', -> failure.should.have.been.called describe 'update', -> describe 'with a missing access token', -> {promise,success,failure} = {} beforeEach () -> instance = configuration: issuer: 'https://connect.anvil.io' agentOptions: {} nock.cleanAll() nock(instance.configuration.issuer) .patch('/v1/scopes/uuid') .reply(200, {_id: 'uuid'}) success = sinon.spy() failure = sinon.spy() promise = scopes.update.bind(instance)('uuid', {}) .then(success, failure) it 'should return a promise', -> promise.should.be.instanceof Promise it 'should not provide scope', -> success.should.not.have.been.called it 'should catch an error', -> failure.should.have.been.calledWith sinon.match.instanceOf Error describe 'with a successful response', -> {promise,success,failure} = {} before () -> instance = configuration: issuer: 'https://connect.anvil.io' tokens: access_token: 'random' agentOptions: {} nock.cleanAll() nock(instance.configuration.issuer) .patch('/v1/scopes/uuid', { redirect_uris: ['https://example.anvil.io'] }) .reply(200, { _id: 'uuid' redirect_uris: ['https://example.anvil.io'] }) success = sinon.spy() failure = sinon.spy() promise = scopes.update.bind(instance)('uuid', { redirect_uris: ['https://example.anvil.io'] }, { token: 'token' }).then(success, failure) it 'should return a promise', -> promise.should.be.instanceof Promise it 'should provide the scope', -> success.should.have.been.calledWith sinon.match({ redirect_uris: ['https://example.anvil.io'] }) it 'should not catch an error', -> failure.should.not.have.been.called describe 'with a failure response', -> {promise,success,failure} = {} before () -> instance = configuration: issuer: 'https://connect.anvil.io' tokens: access_token: 'random' agentOptions: {} nock.cleanAll() nock(instance.configuration.issuer) .patch('/v1/scopes/uuid', {}) .reply(400, 'Bad request') success = sinon.spy() failure = sinon.spy() promise = scopes.update.bind(instance)('uuid', { redirect_uris: ['https://example.anvil.io'] }, { token: 'token' }).then(success, failure) it 'should return a promise', -> promise.should.be.instanceof Promise it 'should not provide the scope', -> success.should.not.have.been.called it 'should catch an error', -> failure.should.have.been.called describe 'delete', -> describe 'with a missing access token', -> {promise,success,failure} = {} beforeEach () -> instance = configuration: issuer: 'https://connect.anvil.io' agentOptions: {} nock.cleanAll() nock(instance.configuration.issuer) .delete('/v1/scopes/uuid') .reply(401, 'Unauthorized') success = sinon.spy() failure = sinon.spy() promise = scopes.delete.bind(instance)('uuid') .then(success, failure) it 'should return a promise', -> promise.should.be.instanceof Promise it 'should not provide scope', -> success.should.not.have.been.called it 'should catch an error', -> failure.should.have.been.calledWith sinon.match.instanceOf Error describe 'with a successful response', -> {promise,success,failure} = {} before () -> instance = configuration: issuer: 'https://connect.anvil.io' tokens: access_token: 'random' agentOptions: {} nock.cleanAll() nock(instance.configuration.issuer) .delete('/v1/scopes/uuid') .reply(204) success = sinon.spy() failure = sinon.spy() promise = scopes.delete.bind(instance)('uuid', { token: 'token' }) .then(success, failure) it 'should return a promise', -> promise.should.be.instanceof Promise it 'should provide the scope', -> success.should.have.been.called it 'should not catch an error', -> failure.should.not.have.been.called describe 'with a failure response', -> {promise,success,failure} = {} before () -> instance = configuration: issuer: 'https://connect.anvil.io' tokens: access_token: 'random' agentOptions: {} nock.cleanAll() nock(instance.configuration.issuer) .delete('/v1/scopes/uuid') .reply(404, 'Not found') success = sinon.spy() failure = sinon.spy() promise = scopes.delete.bind(instance)('uuid', { token: 'token' }) .then(success, failure) it 'should return a promise', -> promise.should.be.instanceof Promise it 'should not provide the scope', -> success.should.not.have.been.called it 'should catch an error', -> failure.should.have.been.called
86909
# Test dependencies cwd = process.cwd() path = require 'path' chai = require 'chai' sinon = require 'sinon' sinonChai = require 'sinon-chai' expect = chai.expect nock = require 'nock' # Assertions chai.use sinonChai chai.should() scopes = require path.join(cwd, 'rest', 'scopes') describe 'REST API Scope Methods', -> describe 'list', -> describe 'with a missing access token', -> {promise,success,failure} = {} beforeEach () -> instance = configuration: issuer: 'https://connect.anvil.io' agentOptions: {} nock.cleanAll() nock(instance.configuration.issuer) .get('/v1/scopes') .reply(200, [{_id: 'uuid'}]) success = sinon.spy() failure = sinon.spy() promise = scopes.list.bind(instance)() .then(success, failure) it 'should return a promise', -> promise.should.be.instanceof Promise it 'should not provide scopes', -> success.should.not.have.been.called it 'should catch an error', -> failure.should.have.been.calledWith sinon.match.instanceOf Error describe 'with a successful response', -> {promise,success,failure} = {} before () -> instance = configuration: issuer: 'https://connect.anvil.io' agentOptions: {} nock.cleanAll() nock(instance.configuration.issuer) .get('/v1/scopes') .reply(200, [{_id: 'uuid'}]) success = sinon.spy() failure = sinon.spy() promise = scopes.list.bind(instance)({ token: 'token' }) .then(success, failure) it 'should return a promise', -> promise.should.be.instanceof Promise it 'should provide the scopes', -> success.should.have.been.calledWith sinon.match [{_id:'uuid'}] it 'should not catch an error', -> failure.should.not.have.been.called describe 'with a failure response', -> {promise,success,failure} = {} before () -> instance = configuration: issuer: 'https://connect.anvil.io' agentOptions: {} nock.cleanAll() nock(instance.configuration.issuer) .get('/v1/scopes') .reply(404, 'Not found') success = sinon.spy() failure = sinon.spy() promise = scopes.list.bind(instance)({ token: 'token' }) .then(success, failure) it 'should return a promise', -> promise.should.be.instanceof Promise it 'should not provide the scopes', -> success.should.not.have.been.called it 'should catch an error', -> failure.should.have.been.called describe 'get', -> describe 'with a missing access token', -> {promise,success,failure} = {} beforeEach () -> instance = configuration: issuer: 'https://connect.anvil.io' agentOptions: {} nock.cleanAll() nock(instance.configuration.issuer) .get('/v1/scopes/uuid') .reply(200, [{_id: 'uuid'}]) success = sinon.spy() failure = sinon.spy() promise = scopes.get.bind(instance)('uuid') .then(success, failure) it 'should return a promise', -> promise.should.be.instanceof Promise it 'should not provide scopes', -> success.should.not.have.been.called it 'should catch an error', -> failure.should.have.been.calledWith sinon.match.instanceOf Error describe 'with a successful response', -> {promise,success,failure} = {} before () -> instance = configuration: issuer: 'https://connect.anvil.io' tokens: access_token: '<KEY>' agentOptions: {} nock.cleanAll() nock(instance.configuration.issuer) .get('/v1/scopes/uuid') .reply(200, {_id: 'uuid'}) success = sinon.spy() failure = sinon.spy() promise = scopes.get.bind(instance)('uuid', { token: 'token' }) .then(success, failure) it 'should return a promise', -> promise.should.be.instanceof Promise it 'should provide the scope', -> success.should.have.been.calledWith sinon.match {_id:'uuid'} it 'should not catch an error', -> failure.should.not.have.been.called describe 'with a failure response', -> {promise,success,failure} = {} before () -> instance = configuration: issuer: 'https://connect.anvil.io' tokens: access_token: '<KEY>' agentOptions: {} nock.cleanAll() nock(instance.configuration.issuer) .get('/v1/scopes/uuid') .reply(404, 'Not found') success = sinon.spy() failure = sinon.spy() promise = scopes.get.bind(instance)('uuid', { token: 'token' }) .then(success, failure) it 'should return a promise', -> promise.should.be.instanceof Promise it 'should not provide the scope', -> success.should.not.have.been.called it 'should catch an error', -> failure.should.have.been.called describe 'create', -> describe 'with a missing access token', -> {promise,success,failure} = {} beforeEach () -> instance = configuration: issuer: 'https://connect.anvil.io' agentOptions: {} nock.cleanAll() nock(instance.configuration.issuer) .post('/v1/scopes') .reply(200, [{_id: 'uuid'}]) success = sinon.spy() failure = sinon.spy() promise = scopes.create.bind(instance)({}) .then(success, failure) it 'should return a promise', -> promise.should.be.instanceof Promise it 'should not provide scope', -> success.should.not.have.been.called it 'should catch an error', -> failure.should.have.been.calledWith sinon.match.instanceOf Error describe 'with a successful response', -> {promise,success,failure} = {} before () -> instance = configuration: issuer: 'https://connect.anvil.io' tokens: access_token: '<KEY>' agentOptions: {} nock.cleanAll() nock(instance.configuration.issuer) .post('/v1/scopes', { redirect_uris: ['https://example.anvil.io'] }) .reply(201, { _id: 'uuid' redirect_uris: ['https://example.anvil.io'] }) success = sinon.spy() failure = sinon.spy() promise = scopes.create.bind(instance)({ redirect_uris: ['https://example.anvil.io'] }, { token: 'token' }).then(success, failure) it 'should return a promise', -> promise.should.be.instanceof Promise it 'should provide the scope', -> success.should.have.been.calledWith sinon.match {_id:'uuid'} it 'should not catch an error', -> failure.should.not.have.been.called describe 'with a failure response', -> {promise,success,failure} = {} before () -> instance = configuration: issuer: 'https://connect.anvil.io' tokens: access_token: '<KEY>' agentOptions: {} nock.cleanAll() nock(instance.configuration.issuer) .post('/v1/scopes', {}) .reply(400, 'Bad request') success = sinon.spy() failure = sinon.spy() promise = scopes.create.bind(instance)({ redirect_uris: ['https://example.anvil.io'] }, { token: '<KEY>' }).then(success, failure) it 'should return a promise', -> promise.should.be.instanceof Promise it 'should not provide the scope', -> success.should.not.have.been.called it 'should catch an error', -> failure.should.have.been.called describe 'update', -> describe 'with a missing access token', -> {promise,success,failure} = {} beforeEach () -> instance = configuration: issuer: 'https://connect.anvil.io' agentOptions: {} nock.cleanAll() nock(instance.configuration.issuer) .patch('/v1/scopes/uuid') .reply(200, {_id: 'uuid'}) success = sinon.spy() failure = sinon.spy() promise = scopes.update.bind(instance)('uuid', {}) .then(success, failure) it 'should return a promise', -> promise.should.be.instanceof Promise it 'should not provide scope', -> success.should.not.have.been.called it 'should catch an error', -> failure.should.have.been.calledWith sinon.match.instanceOf Error describe 'with a successful response', -> {promise,success,failure} = {} before () -> instance = configuration: issuer: 'https://connect.anvil.io' tokens: access_token: '<KEY>' agentOptions: {} nock.cleanAll() nock(instance.configuration.issuer) .patch('/v1/scopes/uuid', { redirect_uris: ['https://example.anvil.io'] }) .reply(200, { _id: 'uuid' redirect_uris: ['https://example.anvil.io'] }) success = sinon.spy() failure = sinon.spy() promise = scopes.update.bind(instance)('uuid', { redirect_uris: ['https://example.anvil.io'] }, { token: 'token' }).then(success, failure) it 'should return a promise', -> promise.should.be.instanceof Promise it 'should provide the scope', -> success.should.have.been.calledWith sinon.match({ redirect_uris: ['https://example.anvil.io'] }) it 'should not catch an error', -> failure.should.not.have.been.called describe 'with a failure response', -> {promise,success,failure} = {} before () -> instance = configuration: issuer: 'https://connect.anvil.io' tokens: access_token: '<KEY>' agentOptions: {} nock.cleanAll() nock(instance.configuration.issuer) .patch('/v1/scopes/uuid', {}) .reply(400, 'Bad request') success = sinon.spy() failure = sinon.spy() promise = scopes.update.bind(instance)('uuid', { redirect_uris: ['https://example.anvil.io'] }, { token: '<KEY>' }).then(success, failure) it 'should return a promise', -> promise.should.be.instanceof Promise it 'should not provide the scope', -> success.should.not.have.been.called it 'should catch an error', -> failure.should.have.been.called describe 'delete', -> describe 'with a missing access token', -> {promise,success,failure} = {} beforeEach () -> instance = configuration: issuer: 'https://connect.anvil.io' agentOptions: {} nock.cleanAll() nock(instance.configuration.issuer) .delete('/v1/scopes/uuid') .reply(401, 'Unauthorized') success = sinon.spy() failure = sinon.spy() promise = scopes.delete.bind(instance)('uuid') .then(success, failure) it 'should return a promise', -> promise.should.be.instanceof Promise it 'should not provide scope', -> success.should.not.have.been.called it 'should catch an error', -> failure.should.have.been.calledWith sinon.match.instanceOf Error describe 'with a successful response', -> {promise,success,failure} = {} before () -> instance = configuration: issuer: 'https://connect.anvil.io' tokens: access_token: '<KEY>' agentOptions: {} nock.cleanAll() nock(instance.configuration.issuer) .delete('/v1/scopes/uuid') .reply(204) success = sinon.spy() failure = sinon.spy() promise = scopes.delete.bind(instance)('uuid', { token: 'token' }) .then(success, failure) it 'should return a promise', -> promise.should.be.instanceof Promise it 'should provide the scope', -> success.should.have.been.called it 'should not catch an error', -> failure.should.not.have.been.called describe 'with a failure response', -> {promise,success,failure} = {} before () -> instance = configuration: issuer: 'https://connect.anvil.io' tokens: access_token: '<KEY>' agentOptions: {} nock.cleanAll() nock(instance.configuration.issuer) .delete('/v1/scopes/uuid') .reply(404, 'Not found') success = sinon.spy() failure = sinon.spy() promise = scopes.delete.bind(instance)('uuid', { token: 'token' }) .then(success, failure) it 'should return a promise', -> promise.should.be.instanceof Promise it 'should not provide the scope', -> success.should.not.have.been.called it 'should catch an error', -> failure.should.have.been.called
true
# Test dependencies cwd = process.cwd() path = require 'path' chai = require 'chai' sinon = require 'sinon' sinonChai = require 'sinon-chai' expect = chai.expect nock = require 'nock' # Assertions chai.use sinonChai chai.should() scopes = require path.join(cwd, 'rest', 'scopes') describe 'REST API Scope Methods', -> describe 'list', -> describe 'with a missing access token', -> {promise,success,failure} = {} beforeEach () -> instance = configuration: issuer: 'https://connect.anvil.io' agentOptions: {} nock.cleanAll() nock(instance.configuration.issuer) .get('/v1/scopes') .reply(200, [{_id: 'uuid'}]) success = sinon.spy() failure = sinon.spy() promise = scopes.list.bind(instance)() .then(success, failure) it 'should return a promise', -> promise.should.be.instanceof Promise it 'should not provide scopes', -> success.should.not.have.been.called it 'should catch an error', -> failure.should.have.been.calledWith sinon.match.instanceOf Error describe 'with a successful response', -> {promise,success,failure} = {} before () -> instance = configuration: issuer: 'https://connect.anvil.io' agentOptions: {} nock.cleanAll() nock(instance.configuration.issuer) .get('/v1/scopes') .reply(200, [{_id: 'uuid'}]) success = sinon.spy() failure = sinon.spy() promise = scopes.list.bind(instance)({ token: 'token' }) .then(success, failure) it 'should return a promise', -> promise.should.be.instanceof Promise it 'should provide the scopes', -> success.should.have.been.calledWith sinon.match [{_id:'uuid'}] it 'should not catch an error', -> failure.should.not.have.been.called describe 'with a failure response', -> {promise,success,failure} = {} before () -> instance = configuration: issuer: 'https://connect.anvil.io' agentOptions: {} nock.cleanAll() nock(instance.configuration.issuer) .get('/v1/scopes') .reply(404, 'Not found') success = sinon.spy() failure = sinon.spy() promise = scopes.list.bind(instance)({ token: 'token' }) .then(success, failure) it 'should return a promise', -> promise.should.be.instanceof Promise it 'should not provide the scopes', -> success.should.not.have.been.called it 'should catch an error', -> failure.should.have.been.called describe 'get', -> describe 'with a missing access token', -> {promise,success,failure} = {} beforeEach () -> instance = configuration: issuer: 'https://connect.anvil.io' agentOptions: {} nock.cleanAll() nock(instance.configuration.issuer) .get('/v1/scopes/uuid') .reply(200, [{_id: 'uuid'}]) success = sinon.spy() failure = sinon.spy() promise = scopes.get.bind(instance)('uuid') .then(success, failure) it 'should return a promise', -> promise.should.be.instanceof Promise it 'should not provide scopes', -> success.should.not.have.been.called it 'should catch an error', -> failure.should.have.been.calledWith sinon.match.instanceOf Error describe 'with a successful response', -> {promise,success,failure} = {} before () -> instance = configuration: issuer: 'https://connect.anvil.io' tokens: access_token: 'PI:KEY:<KEY>END_PI' agentOptions: {} nock.cleanAll() nock(instance.configuration.issuer) .get('/v1/scopes/uuid') .reply(200, {_id: 'uuid'}) success = sinon.spy() failure = sinon.spy() promise = scopes.get.bind(instance)('uuid', { token: 'token' }) .then(success, failure) it 'should return a promise', -> promise.should.be.instanceof Promise it 'should provide the scope', -> success.should.have.been.calledWith sinon.match {_id:'uuid'} it 'should not catch an error', -> failure.should.not.have.been.called describe 'with a failure response', -> {promise,success,failure} = {} before () -> instance = configuration: issuer: 'https://connect.anvil.io' tokens: access_token: 'PI:KEY:<KEY>END_PI' agentOptions: {} nock.cleanAll() nock(instance.configuration.issuer) .get('/v1/scopes/uuid') .reply(404, 'Not found') success = sinon.spy() failure = sinon.spy() promise = scopes.get.bind(instance)('uuid', { token: 'token' }) .then(success, failure) it 'should return a promise', -> promise.should.be.instanceof Promise it 'should not provide the scope', -> success.should.not.have.been.called it 'should catch an error', -> failure.should.have.been.called describe 'create', -> describe 'with a missing access token', -> {promise,success,failure} = {} beforeEach () -> instance = configuration: issuer: 'https://connect.anvil.io' agentOptions: {} nock.cleanAll() nock(instance.configuration.issuer) .post('/v1/scopes') .reply(200, [{_id: 'uuid'}]) success = sinon.spy() failure = sinon.spy() promise = scopes.create.bind(instance)({}) .then(success, failure) it 'should return a promise', -> promise.should.be.instanceof Promise it 'should not provide scope', -> success.should.not.have.been.called it 'should catch an error', -> failure.should.have.been.calledWith sinon.match.instanceOf Error describe 'with a successful response', -> {promise,success,failure} = {} before () -> instance = configuration: issuer: 'https://connect.anvil.io' tokens: access_token: 'PI:PASSWORD:<KEY>END_PI' agentOptions: {} nock.cleanAll() nock(instance.configuration.issuer) .post('/v1/scopes', { redirect_uris: ['https://example.anvil.io'] }) .reply(201, { _id: 'uuid' redirect_uris: ['https://example.anvil.io'] }) success = sinon.spy() failure = sinon.spy() promise = scopes.create.bind(instance)({ redirect_uris: ['https://example.anvil.io'] }, { token: 'token' }).then(success, failure) it 'should return a promise', -> promise.should.be.instanceof Promise it 'should provide the scope', -> success.should.have.been.calledWith sinon.match {_id:'uuid'} it 'should not catch an error', -> failure.should.not.have.been.called describe 'with a failure response', -> {promise,success,failure} = {} before () -> instance = configuration: issuer: 'https://connect.anvil.io' tokens: access_token: 'PI:KEY:<KEY>END_PI' agentOptions: {} nock.cleanAll() nock(instance.configuration.issuer) .post('/v1/scopes', {}) .reply(400, 'Bad request') success = sinon.spy() failure = sinon.spy() promise = scopes.create.bind(instance)({ redirect_uris: ['https://example.anvil.io'] }, { token: 'PI:KEY:<KEY>END_PI' }).then(success, failure) it 'should return a promise', -> promise.should.be.instanceof Promise it 'should not provide the scope', -> success.should.not.have.been.called it 'should catch an error', -> failure.should.have.been.called describe 'update', -> describe 'with a missing access token', -> {promise,success,failure} = {} beforeEach () -> instance = configuration: issuer: 'https://connect.anvil.io' agentOptions: {} nock.cleanAll() nock(instance.configuration.issuer) .patch('/v1/scopes/uuid') .reply(200, {_id: 'uuid'}) success = sinon.spy() failure = sinon.spy() promise = scopes.update.bind(instance)('uuid', {}) .then(success, failure) it 'should return a promise', -> promise.should.be.instanceof Promise it 'should not provide scope', -> success.should.not.have.been.called it 'should catch an error', -> failure.should.have.been.calledWith sinon.match.instanceOf Error describe 'with a successful response', -> {promise,success,failure} = {} before () -> instance = configuration: issuer: 'https://connect.anvil.io' tokens: access_token: 'PI:KEY:<KEY>END_PI' agentOptions: {} nock.cleanAll() nock(instance.configuration.issuer) .patch('/v1/scopes/uuid', { redirect_uris: ['https://example.anvil.io'] }) .reply(200, { _id: 'uuid' redirect_uris: ['https://example.anvil.io'] }) success = sinon.spy() failure = sinon.spy() promise = scopes.update.bind(instance)('uuid', { redirect_uris: ['https://example.anvil.io'] }, { token: 'token' }).then(success, failure) it 'should return a promise', -> promise.should.be.instanceof Promise it 'should provide the scope', -> success.should.have.been.calledWith sinon.match({ redirect_uris: ['https://example.anvil.io'] }) it 'should not catch an error', -> failure.should.not.have.been.called describe 'with a failure response', -> {promise,success,failure} = {} before () -> instance = configuration: issuer: 'https://connect.anvil.io' tokens: access_token: 'PI:KEY:<KEY>END_PI' agentOptions: {} nock.cleanAll() nock(instance.configuration.issuer) .patch('/v1/scopes/uuid', {}) .reply(400, 'Bad request') success = sinon.spy() failure = sinon.spy() promise = scopes.update.bind(instance)('uuid', { redirect_uris: ['https://example.anvil.io'] }, { token: 'PI:KEY:<KEY>END_PI' }).then(success, failure) it 'should return a promise', -> promise.should.be.instanceof Promise it 'should not provide the scope', -> success.should.not.have.been.called it 'should catch an error', -> failure.should.have.been.called describe 'delete', -> describe 'with a missing access token', -> {promise,success,failure} = {} beforeEach () -> instance = configuration: issuer: 'https://connect.anvil.io' agentOptions: {} nock.cleanAll() nock(instance.configuration.issuer) .delete('/v1/scopes/uuid') .reply(401, 'Unauthorized') success = sinon.spy() failure = sinon.spy() promise = scopes.delete.bind(instance)('uuid') .then(success, failure) it 'should return a promise', -> promise.should.be.instanceof Promise it 'should not provide scope', -> success.should.not.have.been.called it 'should catch an error', -> failure.should.have.been.calledWith sinon.match.instanceOf Error describe 'with a successful response', -> {promise,success,failure} = {} before () -> instance = configuration: issuer: 'https://connect.anvil.io' tokens: access_token: 'PI:KEY:<KEY>END_PI' agentOptions: {} nock.cleanAll() nock(instance.configuration.issuer) .delete('/v1/scopes/uuid') .reply(204) success = sinon.spy() failure = sinon.spy() promise = scopes.delete.bind(instance)('uuid', { token: 'token' }) .then(success, failure) it 'should return a promise', -> promise.should.be.instanceof Promise it 'should provide the scope', -> success.should.have.been.called it 'should not catch an error', -> failure.should.not.have.been.called describe 'with a failure response', -> {promise,success,failure} = {} before () -> instance = configuration: issuer: 'https://connect.anvil.io' tokens: access_token: 'PI:PASSWORD:<KEY>END_PI' agentOptions: {} nock.cleanAll() nock(instance.configuration.issuer) .delete('/v1/scopes/uuid') .reply(404, 'Not found') success = sinon.spy() failure = sinon.spy() promise = scopes.delete.bind(instance)('uuid', { token: 'token' }) .then(success, failure) it 'should return a promise', -> promise.should.be.instanceof Promise it 'should not provide the scope', -> success.should.not.have.been.called it 'should catch an error', -> failure.should.have.been.called
[ { "context": "tion for Backbone.Marionette\n#\n# Copyright (C)2012 Derick Bailey, Muted Solutions, LLC\n# Distributed Under MIT Lic", "end": 108, "score": 0.9998461008071899, "start": 95, "tag": "NAME", "value": "Derick Bailey" }, { "context": "nd Full License Available at:\n# http:/...
client/contacts/categories.coffee
zhangcheng/bbclonemail-meteor
1
# Backbone.BBCloneMail # A reference application for Backbone.Marionette # # Copyright (C)2012 Derick Bailey, Muted Solutions, LLC # Distributed Under MIT License # # Documentation and Full License Available at: # http://github.com/derickbailey/backbone.bbclonemail # http://github.com/derickbailey/backbone.marionette # Contact Categories # -------- # Manage the list of categories, and the interactions with them, # for the contacts app. BBCloneMail.module "ContactsApp.Categories", (Categories, BBCloneMail, Backbone, Marionette, $, _) -> # Categories Views # ---------------- # Displays the hard coded list of contact categories, from # the view template. Categories.ContactCategoriesView = Marionette.ItemView.extend template: "contact-categories-view" events: "click a": "categoryClicked" categoryClicked: (e) -> e.preventDefault() # Public API # ---------- # Show the list of contact categories in the # left hand navigation. Categories.show = -> BBCloneMail.layout.navigation.show new Categories.ContactCategoriesView()
160639
# Backbone.BBCloneMail # A reference application for Backbone.Marionette # # Copyright (C)2012 <NAME>, Muted Solutions, LLC # Distributed Under MIT License # # Documentation and Full License Available at: # http://github.com/derickbailey/backbone.bbclonemail # http://github.com/derickbailey/backbone.marionette # Contact Categories # -------- # Manage the list of categories, and the interactions with them, # for the contacts app. BBCloneMail.module "ContactsApp.Categories", (Categories, BBCloneMail, Backbone, Marionette, $, _) -> # Categories Views # ---------------- # Displays the hard coded list of contact categories, from # the view template. Categories.ContactCategoriesView = Marionette.ItemView.extend template: "contact-categories-view" events: "click a": "categoryClicked" categoryClicked: (e) -> e.preventDefault() # Public API # ---------- # Show the list of contact categories in the # left hand navigation. Categories.show = -> BBCloneMail.layout.navigation.show new Categories.ContactCategoriesView()
true
# Backbone.BBCloneMail # A reference application for Backbone.Marionette # # Copyright (C)2012 PI:NAME:<NAME>END_PI, Muted Solutions, LLC # Distributed Under MIT License # # Documentation and Full License Available at: # http://github.com/derickbailey/backbone.bbclonemail # http://github.com/derickbailey/backbone.marionette # Contact Categories # -------- # Manage the list of categories, and the interactions with them, # for the contacts app. BBCloneMail.module "ContactsApp.Categories", (Categories, BBCloneMail, Backbone, Marionette, $, _) -> # Categories Views # ---------------- # Displays the hard coded list of contact categories, from # the view template. Categories.ContactCategoriesView = Marionette.ItemView.extend template: "contact-categories-view" events: "click a": "categoryClicked" categoryClicked: (e) -> e.preventDefault() # Public API # ---------- # Show the list of contact categories in the # left hand navigation. Categories.show = -> BBCloneMail.layout.navigation.show new Categories.ContactCategoriesView()
[ { "context": " = 'sample message'\n data =\n data_key_1: 'data_value_1'\n extras =\n extras_key_1: 'extras_value_1", "end": 648, "score": 0.9564334154129028, "start": 636, "tag": "KEY", "value": "data_value_1" }, { "context": "value_1'\n extras =\n extras_key_...
test/index-test.coffee
tq1/push-sender
0
require('rootpath')() assert = require('chai').assert sinon = require 'sinon' GcmMessage = require 'test/stubs/gcm/gcm-message-stub' GcmSender = require('test/stubs/gcm/gcm-sender-stub')() ApnsMessage = require 'test/stubs/apns/apns-message-stub' ApnsSender = require('test/stubs/apns/apns-sender-stub')() index = require('src/index') GcmMessage, GcmSender.GcmSender, ApnsMessage, ApnsSender.ApnsSender describe 'Index', -> authorization = null target = null message = null data = null extras = null callback = null gcmSendStub = null before (done) -> message = 'sample message' data = data_key_1: 'data_value_1' extras = extras_key_1: 'extras_value_1' done() it 'should invoke GcmSender for an Android device registered with GCM 3', -> gcmSendStub = sinon.spy() GcmSender.setSendStub gcmSendStub authorization = 'AIzaZSJi04RieGWWElutKRw8lkNBtx8MugwCMhn' target = deviceToken: 'e4uEvCZELP0:APA91bE8Jt75rjHma4p2jwkvVC62pHvjSkxM_ZTY7JkcE3fN67D4uIurEk7Jw78KEcnYtW4GxLE6rdUfSMqL4qIJgbA_zZWSLZ2jus_OdW-QXZfev4RA1r7ln52yQFGvvXVc16pR-BnO' platform: 'android' index.send authorization, target, message, data, extras, callback assert gcmSendStub.calledOnce it 'should invoke GcmSender for an Android device registered with old versions of GCM', -> gcmSendStub = sinon.spy() GcmSender.setSendStub gcmSendStub authorization = 'AIzaZSJi04RieGWWElutKRw8lkNBtx8MugwCMhn' target = 'APA91bFfoi8lPdPlCasG2HaLloQButFvpSeWoMZ1EqFjqcp1qSJyyWBdqxS9Ag2PB7lEza0slA0CT67G7iJCeIDNDBluNGRaoOTAEAk9P6rLlleOtSKye_tiqIzZJoWZD2amt2JJ_Awu' index.send authorization, target, message, data, extras, callback assert gcmSendStub.calledOnce it 'should invoke ApnsSender for an iOS device', -> apnsSendStub = sinon.spy() ApnsSender.setSendStub apnsSendStub 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-----"] target = deviceToken: 'f476e090fd958d351684d9331aad5e6c3c87546ea10247576a76f394ec94b674', platform: 'ios' index.send authorization, target, message, data, extras, callback assert apnsSendStub.calledOnce
163071
require('rootpath')() assert = require('chai').assert sinon = require 'sinon' GcmMessage = require 'test/stubs/gcm/gcm-message-stub' GcmSender = require('test/stubs/gcm/gcm-sender-stub')() ApnsMessage = require 'test/stubs/apns/apns-message-stub' ApnsSender = require('test/stubs/apns/apns-sender-stub')() index = require('src/index') GcmMessage, GcmSender.GcmSender, ApnsMessage, ApnsSender.ApnsSender describe 'Index', -> authorization = null target = null message = null data = null extras = null callback = null gcmSendStub = null before (done) -> message = 'sample message' data = data_key_1: '<KEY>' extras = extras_key_1: 'extras_<KEY>_1' done() it 'should invoke GcmSender for an Android device registered with GCM 3', -> gcmSendStub = sinon.spy() GcmSender.setSendStub gcmSendStub authorization = '<KEY>' target = deviceToken: '<KEY>:<KEY>' platform: 'android' index.send authorization, target, message, data, extras, callback assert gcmSendStub.calledOnce it 'should invoke GcmSender for an Android device registered with old versions of GCM', -> gcmSendStub = sinon.spy() GcmSender.setSendStub gcmSendStub authorization = '<KEY>' target = '<KEY>' index.send authorization, target, message, data, extras, callback assert gcmSendStub.calledOnce it 'should invoke ApnsSender for an iOS device', -> apnsSendStub = sinon.spy() ApnsSender.setSendStub apnsSendStub authorization = ["-----<KEY>", "-----<KEY>"] target = deviceToken: '<KEY>', platform: 'ios' index.send authorization, target, message, data, extras, callback assert apnsSendStub.calledOnce
true
require('rootpath')() assert = require('chai').assert sinon = require 'sinon' GcmMessage = require 'test/stubs/gcm/gcm-message-stub' GcmSender = require('test/stubs/gcm/gcm-sender-stub')() ApnsMessage = require 'test/stubs/apns/apns-message-stub' ApnsSender = require('test/stubs/apns/apns-sender-stub')() index = require('src/index') GcmMessage, GcmSender.GcmSender, ApnsMessage, ApnsSender.ApnsSender describe 'Index', -> authorization = null target = null message = null data = null extras = null callback = null gcmSendStub = null before (done) -> message = 'sample message' data = data_key_1: 'PI:KEY:<KEY>END_PI' extras = extras_key_1: 'extras_PI:KEY:<KEY>END_PI_1' done() it 'should invoke GcmSender for an Android device registered with GCM 3', -> gcmSendStub = sinon.spy() GcmSender.setSendStub gcmSendStub authorization = 'PI:KEY:<KEY>END_PI' target = deviceToken: 'PI:KEY:<KEY>END_PI:PI:KEY:<KEY>END_PI' platform: 'android' index.send authorization, target, message, data, extras, callback assert gcmSendStub.calledOnce it 'should invoke GcmSender for an Android device registered with old versions of GCM', -> gcmSendStub = sinon.spy() GcmSender.setSendStub gcmSendStub authorization = 'PI:KEY:<KEY>END_PI' target = 'PI:KEY:<KEY>END_PI' index.send authorization, target, message, data, extras, callback assert gcmSendStub.calledOnce it 'should invoke ApnsSender for an iOS device', -> apnsSendStub = sinon.spy() ApnsSender.setSendStub apnsSendStub authorization = ["-----PI:KEY:<KEY>END_PI", "-----PI:KEY:<KEY>END_PI"] target = deviceToken: 'PI:KEY:<KEY>END_PI', platform: 'ios' index.send authorization, target, message, data, extras, callback assert apnsSendStub.calledOnce
[ { "context": "me='port']\": \"port\"\n \":input[name='user']\": \"username\"\n \":input[name='password']\": \"password\"\n ", "end": 4597, "score": 0.9923293590545654, "start": 4589, "tag": "USERNAME", "value": "username" }, { "context": "']\": \"username\"\n \":inp...
fmc/fmc-webui/src/main/webapp/app/controllers/add_agent_wizard.coffee
rjakubco/fuse
1
### Copyright 2010 Red Hat, Inc. Red Hat licenses this file to you 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. ### define [ "models/app" "views/jade" "controllers/agents_page" "models/compute_services" "controllers/controls/collection" "controllers/controls/validating_text_input" ], (app, jade, AgentsController, ComputeServices) -> class WizardPage extends FON.TemplateController tagName: "fieldset" validated_controls = [] initialize: -> super @container = @options.container if @options.container @prev = @options.prev if @options.prev @state = @options.state if @options.state @next = @get_next() get_next: -> null sync_state: -> maybe_enable_next: (self) -> valid = true keep_checking = true if self.validated_controls for control in self.validated_controls if !control.validate() && valid valid = false if valid if self.next self.container.enable_next "Next", -> self.on_next() else self.container.enable_next "Finish", -> self.on_finish() else self.container.disable_next() on_back: -> if (@prev) @sync_state() @container.set_page(@prev) false on_next: -> if (@next) @sync_state() @container.set_page(@next) false on_finish: -> @sync_state() false on_render: -> if (@prev) @container.enable_back => @on_back() else @container.disable_back() if (@next) @container.configure_next( "Next" => @on_next() ) else @container.configure_next( "Finish" => @on_finish() ) class RootAgentFilteredList extends FON.CollectionController on_add: (agent) -> if (agent.get("root") && agent.get("alive")) super(agent) class RootAgentSelectControl extends FON.TemplateController tagName: "li" className: "padded" template: jade["agents_page/create_agent_wizard/agent_selector_entry.jade"] template_data: -> @model.toJSON() elements: "input": "input" initialize: -> super @state = @options.state if @options.state on_render: (self) => @input.click (event) => @state.set {selected: @model} if (@state.get("selected") == @model) @input.prop("checked", true) class AddChildAgentPage1 extends WizardPage template: -> jade["agents_page/create_agent_wizard/add_child_agent_page_1.jade"] elements: "ul.inputs-list.agent-selector": "agent_selector" on_finish: -> @sync_state() arguments = providerType: "child" name: @state.get "name" parent: @state.get("selected").id number: @state.get("number") proxyUri: @state.get("proxy") version: @state.get("version").id profiles: @state.get("profiles").join(", ") ensembleServer: @state.get("ensemble_server") jvmOpts: @state.get("jvmopts") resolver: @state.get "resolver" options = success: (data, textStatus, jqXHR) => error: (model, response, options) => app.flash kind: "error" title: "Server Error : " message: "Container creation failed due to #{response.statusText} : \u201c#{response.responseText}\u201d" @model.create arguments, options @container.do_return() false on_render: (self) -> super ul = new RootAgentFilteredList el: @agent_selector collection: @model child_control: (agent) => new RootAgentSelectControl model: agent state: @state ul.render() if (!@state.get("selected")) $(ul.el).find("input[name=root-agent]:first").click() class AddSSHAgentPage1 extends WizardPage template: -> jade["agents_page/create_agent_wizard/add_ssh_agent_page_1.jade"] elements: ":input[name='hostname']": "hostname" ":input[name='port']": "port" ":input[name='user']": "username" ":input[name='password']": "password" "input[name=use-pk-file]": "use_pk_file" "input[name=pk-file]": "pk_file" "a.browse": "browse" initialize: -> super @state.set {port: 22} get_next: -> new AddSSHAgentPage2 model: @model container: @container prev: @ state: @state sync_state: -> pk_file = null pk_file = @pk_file.val() if @use_pk_file.is ":checked" @state.set { hostname: @hostname.val() port: @port.val() username: @username.val() password: @password.val() pk_file: pk_file } on_render: -> super @validated_controls = [] @validated_controls.push new FON.ValidatingTextInput control: @hostname controller: @ validator: (text) -> if !text || text == "" ok: false, msg: "You must specify a valid hostname" else ok: true, msg: "" cb: @maybe_enable_next @validated_controls.push new FON.ValidatingTextInput control: @port controller: @ validator: (text) -> if !text || text == "" ok: false, msg: "You must specify a valid port number" else if isNaN(text) ok: false, msg: "You must specify a valid port number" else ok: true, msg: "" cb: @maybe_enable_next @validated_controls.push new FON.ValidatingTextInput control: @username controller: @ validator: (text) -> if !text || text == "" ok: false, msg: "You must specify a username" else ok: true, msg: "" cb: @maybe_enable_next @validated_controls.push new FON.ValidatingTextInput control: @password controller: @ validator: (text) => if !@use_pk_file.is(":checked") && (!text || text == "") ok: false, msg: "You must specify a password" else ok: true, msg: "" cb: @maybe_enable_next @hostname.bind "DOMNodeInsertedIntoDocument", => @hostname.focus() @maybe_enable_next(@) @use_pk_file.change (event) => if @use_pk_file.is ":checked" @pk_file.prop "disabled", false else @pk_file.prop "disabled", true @pk_file.val "" @maybe_enable_next(@) if @state.get "pk_file" @use_pk_file.attr "checked", true @pk_file.val @state.get "pk_file" @pk_file.prop "disabled", false else @use_pk_file.attr "checked", false @pk_file.prop "disabled", true @hostname.val @state.get "hostname" @port.val @state.get "port" @username.val @state.get "username" @password.val @state.get "password" class AddSSHAgentPage2 extends WizardPage template: -> jade["agents_page/create_agent_wizard/add_ssh_agent_page_2.jade"] elements: ":input[name='path']": "path" ":input[name='retries']": "retries" ":input[name='retry-delay']": "retry_delay" initialize: -> super @state.set retries: 1 retry_delay: 1 sync_state: -> @state.set path: @path.val() retries: @retries.val() retry_delay: @retry_delay.val() on_finish: -> @sync_state() arguments = providerType: "ssh" name: @state.get "name" host: @state.get "hostname" username: @state.get "username" #password: @state.get "password" port: @state.get "port" path: @state.get "path" sshRetries: @state.get "retries" retryDelay: @state.get "retry_delay" number: @state.get "number" proxyUri: @state.get "proxy" version: @state.get("version").id profiles: @state.get("profiles").join(", ") ensembleServer: @state.get "ensemble_server" jvmOpts: @state.get "jvmopts" resolver: @state.get "resolver" if @state.get "pk_file" arguments['privateKeyFile'] = @state.get "pk_file" arguments['passPhrase'] = @state.get "password" else arguments['password'] = @state.get "password" options = success: (data, textStatus, jqXHR) => error: (jqXHR, textStatus, errorThrown) => app.flash kind: "error" title: "Server Error : " message: "Container creation failed due to #{textStatus.statusText} : \u201c#{textStatus.responseText}\u201d" @model.create arguments, options @container.do_return() false on_render: -> super @validated_controls = [] @validated_controls.push new FON.ValidatingTextInput control: @path controller: @ validator: (text) -> if !text || text == "" ok: false, msg: "You must specify a path" else ok: true, msg: "" cb: @maybe_enable_next @validated_controls.push new FON.ValidatingTextInput control: @retries controller: @ validator: (text) -> if !text || text == "" ok: false msg: "You must specify a valid retry count" else if isNaN(text) ok: false msg: "You must specify a valid retry count" else ok: true msg: "" cb: @maybe_enable_next @validated_controls.push new FON.ValidatingTextInput control: @retry_delay controller: @ validator: (text) -> if !text || text == "" ok: false msg: "You must specify a valid retry count" else if isNaN(text) ok: false msg: "You must specify a valid retry count" else ok: true, msg: "" cb: @maybe_enable_next if !@state.get "path" @state.set path: "/home/#{@state.get("username")}" @path.val @state.get "path" @retries.val @state.get "retries" @retry_delay.val @state.get "retry_delay" class AddJCloudsAgentPage1 extends WizardPage template: -> jade["agents_page/create_agent_wizard/add_cloud_agent_page_1.jade"] elements: "select[name=provider]": "provider" ":input[name=instance-type]": "instance_type" ":input[name=type-selection]": "type_selection" "input[name=remember]": "remember_credentials" ":input[name=hardware-id]": "hardware_id" "#hardware-id": "hardware_id_div" initialize: -> super @compute_services = @options.compute_services get_next: -> true on_next: -> type_selection = $(@type_selection).filter(":checked").val() if type_selection == "by-os" if !@by_os_pages @by_os_pages = new AddJCloudsAgentByOSPage model: @model container: @container prev: @ state: @state @next = @by_os_pages else if type_selection == "by-image" if !@by_image_pages @by_image_pages = new AddJCloudsAgentByImagePage model: @model container: @container prev: @ state: @state @next = @by_image_pages super sync_state: -> @state.set provider: @provider.val() instance_type: @instance_type.val() hardware_id: @hardware_id.val() type_selection: $(@type_selection).filter(":checked").val() maybe_show_custom: (event) -> if @instance_type.val() == "Custom" @hardware_id_div.removeClass "hide" else @hardware_id_div.addClass "hide" on_render: -> super @compute_services.each (service) => @provider.append $("<option/>", value: service.id text: service.get "name") @provider.bind "DOMNodeInsertedIntoDocument", => @provider.focus() @maybe_enable_next(@) @instance_type.bind "DOMNodeInsertedIntoDocument", (event) => @maybe_show_custom(event) @instance_type.change (event) => @maybe_show_custom(event) if !@state.get "type_selection" @state.set type_selection: "by-os" selection = @state.get "type_selection" for element in @type_selection el = $(element) el.attr "checked", (el.val() == selection) @provider.val @state.get "provider" @instance_type.val @state.get "instance_type" @hardware_id.val @state.get "hardware_id" poll: -> @compute_services.fetch({op: "update"}) if @compute_services class AddJCloudsAgentByOSPage extends WizardPage template: -> jade["agents_page/create_agent_wizard/add_cloud_agent_by_os_page.jade"] elements: "select[name=os-family]": "os_family" "select[name=os-version]": "os_version" mask: suse: "SUSE" debian: "Debian" centos: "CentOS" rhel: "Red Hat Enterprise Linux" solaris: "Solaris" ubuntu: "Ubuntu" windows: "Windows" initialize: -> super @os_and_versions_map = app.cloud_os_and_versions.toJSON() get_next: -> new AddJCloudsAgentPage3 model: @model container: @container prev: @ state: @state sync_state: -> @state.set os_family: @os_family.val() os_version: @os_version.val() update_os_version: -> @os_version.empty() selected = @os_family.val() versions = @os_and_versions_map[selected] for key, value of versions @os_version.append """<option value="#{value}">#{key}</option>""" on_render: -> super for os of @os_and_versions_map @os_family.append """<option value="#{os}">#{@mask[os]}</option>""" @os_family.change => @update_os_version() if @state.get "os_family" @os_family.val @state.get "os_family" @update_os_version() if @state.get "os_version" @os_version.val @state.get "os_version" class AddJCloudsAgentByImagePage extends WizardPage template: -> jade["agents_page/create_agent_wizard/add_cloud_agent_by_image_page.jade"] elements: ":input[name=image-id]": "image_id" ":input[name=location-id]": "location_id" get_next: -> new AddJCloudsAgentPage3 model: @model container: @container prev: @ state: @state sync_state: -> @state.set image_id: @image_id.val() location_id: @location_id.val() on_render: -> super @validated_controls = [] @validated_controls.push new FON.ValidatingTextInput control: @image_id controller: @ validator: (text) -> if !text || text == "" ok: false, msg: "You must specify what image ID to use for the new nodes" else ok: true, msg: "" cb: @maybe_enable_next if @state.get("provider") == "aws-ec2" @validated_controls.push new FON.ValidatingTextInput control: @location_id controller: @ validator: (text) -> if !text || text == "" ok: false, msg: "You must specify what location to use for the new nodes" else ok: true, msg: "" cb: @maybe_enable_next @image_id.bind "DOMNodeInsertedIntoDocument", => @image_id.focus() @maybe_enable_next(@) @image_id.val @state.get "image_id" @location_id.val @state.get "location_id" class AddJCloudsAgentPage3 extends WizardPage template: -> jade["agents_page/create_agent_wizard/add_cloud_agent_page_3.jade"] elements: ":input[name=user-account]": "user_account" ":input[name=owner]": "owner" ":input[name=group]": "group" ":input[name=disable-admin-access]": "disable_admin_access" sync_state: -> @state.set user_account: @user_account.val() owner: @owner.val() group: @group.val() adminAccess: !@disable_admin_access.is(":checked") on_finish: -> @sync_state() arguments = providerType: "jclouds" name: @state.get "name" providerName: @state.get "provider" #identity: @state.get "identity" #credential: @state.get "credential" user: @state.get "user_account" group: @state.get "group" owner: @state.get "owner" number: @state.get "number" proxyUri: @state.get "proxy" version: @state.get("version").id profiles: @state.get("profiles").join(", ") adminAccess: @state.get "adminAccess" ensembleServer: @state.get "ensemble_server" jvmOpts: @state.get "jvmopts" resolver: @state.get "resolver" arguments.group = "fabric" if !@state.get("group") || @state.get("group") == "" arguments.owner = null if !@state.get("owner") || @state.get("owner") == "" arguments.user = null if !@state.get("user_account") || @state.get("user") == "" if @state.get("instance_type") == "Custom" arguments['hardwareId'] = @state.get "hardware_id" else arguments['instanceType'] = @state.get "instance_type" if @state.get("type_selection") == "by-os" arguments['osFamily'] = @state.get "os_family" arguments['osVersion'] = @state.get "os_version" else arguments['imageId'] = @state.get "image_id" arguments['locationId'] = @state.get "location_id" options = success: (data, textStatus, jqXHR) => error: (jqXHR, textStatus, errorThrown) => app.flash kind: "error" title: "Server Error : " message: "Container creation failed due to : \u201c#{textStatus.responseText}\u201d" @model.create arguments, options @container.do_return() false on_render: -> super @validated_controls = [] @user_account.bind "DOMNodeInsertedIntoDocument", => @user_account.focus() @maybe_enable_next(@) @user_account.val @state.get "user_account" @owner.val @state.get "owner" @group.val @state.get "group" class AgentTypeSelectionPage extends WizardPage template: -> jade["agents_page/create_agent_wizard/create_agent_type_selection.jade"] elements: "li.clouds": "cloud_option" initialize: -> super @compute_services = new ComputeServices @compute_services.fetch() @compute_services.bind "change", @render, @ get_next: -> true on_next: -> @selection = $("input[name=agent-type]:checked").val() if (@selection == "child") if (!@child_agent_pages) @child_agent_pages = new AddChildAgentPage1 model: @model container: @container prev: @ state: @state @next = @child_agent_pages else if (@selection == "ssh") if (!@ssh_agent_pages) @ssh_agent_pages = new AddSSHAgentPage1 model: @model container: @container prev: @ state: @state @next = @ssh_agent_pages else if (@selection == "jclouds") if (!@jclouds_agent_pages) @jclouds_agent_pages = new AddJCloudsAgentPage1 model: @model container: @container prev: @ state: @state compute_services: @compute_services @next = @jclouds_agent_pages super on_render: (self) -> super if @compute_services.length == 0 @cloud_option.css "display", "none" el = $(@el) if (@selection) radio = el.find("input[name=agent-type]").filter("[value=#{@selection}]") radio.prop("checked", true) else radio = el.find("input[name=agent-type]").filter("[value=child]") radio.prop("checked", true) poll: -> @compute_services.fetch op: "update" class AgentProfileConfigPage extends WizardPage template: jade["agents_page/create_agent_wizard/agent_profile_config.jade"] template_data: -> versions: app.versions.models profiles: @profiles initialize: -> super @state.set {version: app.versions.default_version()} elements: "#version": "version_select" ".inputs-list": "profile_list" get_next: -> new AgentTypeSelectionPage model: @model container: @container prev: @ state: @state sync_state: -> checked = $("input:checked") profile_names = [] for profile in checked profile_names.push profile.name @state.set {profiles: profile_names} update_profile_list: -> @profile_list.empty() version = @state.get "version" profile_names = @state.get "profiles" all_profiles = version.get "_profiles" all_profiles = _.difference all_profiles, version.get "abstract_profiles" for profile in all_profiles profile = profile.trim() li = _.template("<li><div class=\"clearfix\" style=\"margin: 0px;\"><label><input type=\"checkbox\" name=\"#{profile}\" value=\"#{profile}\"><span>#{profile}</span></label></div></li>") if profile_names for p in profile_names if profile == p $(":input", li).prop("checked", true) @profile_list.append(li) on_render: -> super @version_select.val(@state.get("version").attributes.id) @version_select.change (event) => for version in app.versions.models if version.id == $("select option:selected").val() @state.set {version: version} @state.unset "profiles" @update_profile_list() @update_profile_list() class AgentConfigurationPage extends WizardPage template: jade["agents_page/create_agent_wizard/standard_agent_details_page.jade"] elements: ":input[name=name]": "name" ":input[name=ensemble-server]": "ensemble_server" ":input[name=use-jvm-opts]": "use_jvm_opts" ":input[name=jvm-opts]": "jvm_opts" ":input[name=proxy]": "proxy" ":input[name=use-proxy]": "use_proxy" ":input[name=number]": "number" "select[name=resolver]": "resolver" initialize: -> super @state.set {number: 1} get_next: -> new AgentProfileConfigPage model: @model container: @container prev: @ state: @state sync_state: -> proxy = null jvmopts = null proxy = @proxy.val() if @use_proxy.is ":checked" jvmopts = @jvm_opts.val() if @use_jvm_opts.is ":checked" ensemble_server = @ensemble_server.is ":checked" @state.set { name: @name.val() ensemble_server: ensemble_server jvmopts: jvmopts proxy: proxy number: @number.val() resolver: @resolver.val() } on_render: -> super @validated_controls = [] @validated_controls.push new FON.ValidatingTextInput control: @name controller: @ validator: (text) -> regex = /^[a-zA-Z0-9_-]*$/ if !text || text == "" ok: false, msg: "You must specify a container name" else if !regex.test(text) ok: false msg: "Name can only contain letters, numbers, \u201c-\u201d, and \u201c_\u201d" else ok: true, msg: "" cb: @maybe_enable_next @validated_controls.push new FON.ValidatingTextInput control: @number controller: @ validator: (text) -> if !text || text == "" ok: false, msg: "You must specify how many containers to create" else if isNaN(text) ok: false, msg: "Count must be a positive integer" else ok: true, msg: "If greater than 1, multiple containers will be created with instance numbers appended to the name" cb: @maybe_enable_next @use_proxy.click (event) => if @use_proxy.is ":checked" @proxy.prop "disabled", false else @proxy.prop "disabled", true @proxy.val("") true @use_jvm_opts.click (event) => if @use_jvm_opts.is ":checked" @jvm_opts.prop "disabled", false else @jvm_opts.prop "disabled", true @jvm_opts.val "" @name.bind "DOMNodeInsertedIntoDocument", => @name.focus() @maybe_enable_next(@) @ensemble_server.prop "checked", @state.get "ensemble_server" if @state.get "jvmopts" @use_jvm_opts.attr("checked", true) @jvm_opts.val @state.get "jvmopts" @jvm_opts.prop "disabled", false else @use_jvm_opts.attr "checked", false @jvm_opts.prop "disabled", true if @state.get "proxy" @use_proxy.attr("checked", true) @proxy.val @state.get "proxy" @proxy.prop "disabled", false else @use_proxy.attr("checked", false) @proxy.prop "disabled", true @number.val @state.get "number" @name.val @state.get "name" @resolver.val @state.get "resolver" class WizardIntro extends WizardPage template: jade["agents_page/create_agent_wizard/create_agent_intro_page.jade"] get_next: -> new AgentConfigurationPage model: @model container: @container prev: @ state: @state class AddAgentWizard extends FON.TemplateController template: jade["common/wizard.jade"] template_data: -> header: "Create Container" elements: ".body": "body" "a.next": "next" "a.back": "back" "a.cancel": "cancel" initialize: -> super @state = new FON.Model @page1 = new AgentConfigurationPage model: @model container: @ state: @state @state.bind "change:page", @refresh_content, @ @do_return = @options.do_return if @options.do_return on_render: (self) -> @cancel.click (event) => @do_return() false if (!@state.get("page")) self.set_page(@page1) do_return: -> disable_next: -> @next.unbind('click') @next.click (event) -> false @next.addClass("disabled") enable_next: (text, handler) -> @configure_next(text, handler) configure_next: (text, handler) -> @next.unbind('click') @next.removeClass("disabled") @next.text(text) if (handler) @next.click (event) -> handler(event) else @next.click (event) -> false enable_back: (handler) -> @back.unbind('click') @back.removeClass("disabled") if (handler) @back.click (event) -> handler(event) else @back.click (event) -> false disable_back: -> @back.unbind('click') @back.click (event) -> false @back.addClass("disabled") clear_handlers: -> @back.unbind('click') @next.unbind('click') @back.click (event) -> false @next.click (event) -> false set_page: (page) -> @state.set {page: page} refresh_content: -> page = @state.get("page") @body.empty() @body.append(page.render().el) poll: -> @model.fetch op: "update" page = @state.get "page" if page && page.poll && _.isFunction(page.poll) page.poll() AddAgentWizard
194027
### Copyright 2010 Red Hat, Inc. Red Hat licenses this file to you 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. ### define [ "models/app" "views/jade" "controllers/agents_page" "models/compute_services" "controllers/controls/collection" "controllers/controls/validating_text_input" ], (app, jade, AgentsController, ComputeServices) -> class WizardPage extends FON.TemplateController tagName: "fieldset" validated_controls = [] initialize: -> super @container = @options.container if @options.container @prev = @options.prev if @options.prev @state = @options.state if @options.state @next = @get_next() get_next: -> null sync_state: -> maybe_enable_next: (self) -> valid = true keep_checking = true if self.validated_controls for control in self.validated_controls if !control.validate() && valid valid = false if valid if self.next self.container.enable_next "Next", -> self.on_next() else self.container.enable_next "Finish", -> self.on_finish() else self.container.disable_next() on_back: -> if (@prev) @sync_state() @container.set_page(@prev) false on_next: -> if (@next) @sync_state() @container.set_page(@next) false on_finish: -> @sync_state() false on_render: -> if (@prev) @container.enable_back => @on_back() else @container.disable_back() if (@next) @container.configure_next( "Next" => @on_next() ) else @container.configure_next( "Finish" => @on_finish() ) class RootAgentFilteredList extends FON.CollectionController on_add: (agent) -> if (agent.get("root") && agent.get("alive")) super(agent) class RootAgentSelectControl extends FON.TemplateController tagName: "li" className: "padded" template: jade["agents_page/create_agent_wizard/agent_selector_entry.jade"] template_data: -> @model.toJSON() elements: "input": "input" initialize: -> super @state = @options.state if @options.state on_render: (self) => @input.click (event) => @state.set {selected: @model} if (@state.get("selected") == @model) @input.prop("checked", true) class AddChildAgentPage1 extends WizardPage template: -> jade["agents_page/create_agent_wizard/add_child_agent_page_1.jade"] elements: "ul.inputs-list.agent-selector": "agent_selector" on_finish: -> @sync_state() arguments = providerType: "child" name: @state.get "name" parent: @state.get("selected").id number: @state.get("number") proxyUri: @state.get("proxy") version: @state.get("version").id profiles: @state.get("profiles").join(", ") ensembleServer: @state.get("ensemble_server") jvmOpts: @state.get("jvmopts") resolver: @state.get "resolver" options = success: (data, textStatus, jqXHR) => error: (model, response, options) => app.flash kind: "error" title: "Server Error : " message: "Container creation failed due to #{response.statusText} : \u201c#{response.responseText}\u201d" @model.create arguments, options @container.do_return() false on_render: (self) -> super ul = new RootAgentFilteredList el: @agent_selector collection: @model child_control: (agent) => new RootAgentSelectControl model: agent state: @state ul.render() if (!@state.get("selected")) $(ul.el).find("input[name=root-agent]:first").click() class AddSSHAgentPage1 extends WizardPage template: -> jade["agents_page/create_agent_wizard/add_ssh_agent_page_1.jade"] elements: ":input[name='hostname']": "hostname" ":input[name='port']": "port" ":input[name='user']": "username" ":input[name='password']": "<PASSWORD>" "input[name=use-pk-file]": "use_pk_file" "input[name=pk-file]": "pk_file" "a.browse": "browse" initialize: -> super @state.set {port: 22} get_next: -> new AddSSHAgentPage2 model: @model container: @container prev: @ state: @state sync_state: -> pk_file = null pk_file = @pk_file.val() if @use_pk_file.is ":checked" @state.set { hostname: @hostname.val() port: @port.val() username: @username.val() password: @password.val() pk_file: pk_file } on_render: -> super @validated_controls = [] @validated_controls.push new FON.ValidatingTextInput control: @hostname controller: @ validator: (text) -> if !text || text == "" ok: false, msg: "You must specify a valid hostname" else ok: true, msg: "" cb: @maybe_enable_next @validated_controls.push new FON.ValidatingTextInput control: @port controller: @ validator: (text) -> if !text || text == "" ok: false, msg: "You must specify a valid port number" else if isNaN(text) ok: false, msg: "You must specify a valid port number" else ok: true, msg: "" cb: @maybe_enable_next @validated_controls.push new FON.ValidatingTextInput control: @username controller: @ validator: (text) -> if !text || text == "" ok: false, msg: "You must specify a username" else ok: true, msg: "" cb: @maybe_enable_next @validated_controls.push new FON.ValidatingTextInput control: @password controller: @ validator: (text) => if !@use_pk_file.is(":checked") && (!text || text == "") ok: false, msg: "You must specify a password" else ok: true, msg: "" cb: @maybe_enable_next @hostname.bind "DOMNodeInsertedIntoDocument", => @hostname.focus() @maybe_enable_next(@) @use_pk_file.change (event) => if @use_pk_file.is ":checked" @pk_file.prop "disabled", false else @pk_file.prop "disabled", true @pk_file.val "" @maybe_enable_next(@) if @state.get "pk_file" @use_pk_file.attr "checked", true @pk_file.val @state.get "pk_file" @pk_file.prop "disabled", false else @use_pk_file.attr "checked", false @pk_file.prop "disabled", true @hostname.val @state.get "hostname" @port.val @state.get "port" @username.val @state.get "username" @password.val @state.get "password" class AddSSHAgentPage2 extends WizardPage template: -> jade["agents_page/create_agent_wizard/add_ssh_agent_page_2.jade"] elements: ":input[name='path']": "path" ":input[name='retries']": "retries" ":input[name='retry-delay']": "retry_delay" initialize: -> super @state.set retries: 1 retry_delay: 1 sync_state: -> @state.set path: @path.val() retries: @retries.val() retry_delay: @retry_delay.val() on_finish: -> @sync_state() arguments = providerType: "ssh" name: @state.get "name" host: @state.get "hostname" username: @state.get "username" #password: <PASSWORD> "<PASSWORD>" port: @state.get "port" path: @state.get "path" sshRetries: @state.get "retries" retryDelay: @state.get "retry_delay" number: @state.get "number" proxyUri: @state.get "proxy" version: @state.get("version").id profiles: @state.get("profiles").join(", ") ensembleServer: @state.get "ensemble_server" jvmOpts: @state.get "jvmopts" resolver: @state.get "resolver" if @state.get "pk_file" arguments['privateKeyFile'] = @state.get "pk_file" arguments['passPhrase'] = <PASSWORD> "password" else arguments['password'] = <PASSWORD> "<PASSWORD>" options = success: (data, textStatus, jqXHR) => error: (jqXHR, textStatus, errorThrown) => app.flash kind: "error" title: "Server Error : " message: "Container creation failed due to #{textStatus.statusText} : \u201c#{textStatus.responseText}\u201d" @model.create arguments, options @container.do_return() false on_render: -> super @validated_controls = [] @validated_controls.push new FON.ValidatingTextInput control: @path controller: @ validator: (text) -> if !text || text == "" ok: false, msg: "You must specify a path" else ok: true, msg: "" cb: @maybe_enable_next @validated_controls.push new FON.ValidatingTextInput control: @retries controller: @ validator: (text) -> if !text || text == "" ok: false msg: "You must specify a valid retry count" else if isNaN(text) ok: false msg: "You must specify a valid retry count" else ok: true msg: "" cb: @maybe_enable_next @validated_controls.push new FON.ValidatingTextInput control: @retry_delay controller: @ validator: (text) -> if !text || text == "" ok: false msg: "You must specify a valid retry count" else if isNaN(text) ok: false msg: "You must specify a valid retry count" else ok: true, msg: "" cb: @maybe_enable_next if !@state.get "path" @state.set path: "/home/#{@state.get("username")}" @path.val @state.get "path" @retries.val @state.get "retries" @retry_delay.val @state.get "retry_delay" class AddJCloudsAgentPage1 extends WizardPage template: -> jade["agents_page/create_agent_wizard/add_cloud_agent_page_1.jade"] elements: "select[name=provider]": "provider" ":input[name=instance-type]": "instance_type" ":input[name=type-selection]": "type_selection" "input[name=remember]": "remember_credentials" ":input[name=hardware-id]": "hardware_id" "#hardware-id": "hardware_id_div" initialize: -> super @compute_services = @options.compute_services get_next: -> true on_next: -> type_selection = $(@type_selection).filter(":checked").val() if type_selection == "by-os" if !@by_os_pages @by_os_pages = new AddJCloudsAgentByOSPage model: @model container: @container prev: @ state: @state @next = @by_os_pages else if type_selection == "by-image" if !@by_image_pages @by_image_pages = new AddJCloudsAgentByImagePage model: @model container: @container prev: @ state: @state @next = @by_image_pages super sync_state: -> @state.set provider: @provider.val() instance_type: @instance_type.val() hardware_id: @hardware_id.val() type_selection: $(@type_selection).filter(":checked").val() maybe_show_custom: (event) -> if @instance_type.val() == "Custom" @hardware_id_div.removeClass "hide" else @hardware_id_div.addClass "hide" on_render: -> super @compute_services.each (service) => @provider.append $("<option/>", value: service.id text: service.get "name") @provider.bind "DOMNodeInsertedIntoDocument", => @provider.focus() @maybe_enable_next(@) @instance_type.bind "DOMNodeInsertedIntoDocument", (event) => @maybe_show_custom(event) @instance_type.change (event) => @maybe_show_custom(event) if !@state.get "type_selection" @state.set type_selection: "by-os" selection = @state.get "type_selection" for element in @type_selection el = $(element) el.attr "checked", (el.val() == selection) @provider.val @state.get "provider" @instance_type.val @state.get "instance_type" @hardware_id.val @state.get "hardware_id" poll: -> @compute_services.fetch({op: "update"}) if @compute_services class AddJCloudsAgentByOSPage extends WizardPage template: -> jade["agents_page/create_agent_wizard/add_cloud_agent_by_os_page.jade"] elements: "select[name=os-family]": "os_family" "select[name=os-version]": "os_version" mask: suse: "SUSE" debian: "Debian" centos: "CentOS" rhel: "Red Hat Enterprise Linux" solaris: "Solaris" ubuntu: "Ubuntu" windows: "Windows" initialize: -> super @os_and_versions_map = app.cloud_os_and_versions.toJSON() get_next: -> new AddJCloudsAgentPage3 model: @model container: @container prev: @ state: @state sync_state: -> @state.set os_family: @os_family.val() os_version: @os_version.val() update_os_version: -> @os_version.empty() selected = @os_family.val() versions = @os_and_versions_map[selected] for key, value of versions @os_version.append """<option value="#{value}">#{key}</option>""" on_render: -> super for os of @os_and_versions_map @os_family.append """<option value="#{os}">#{@mask[os]}</option>""" @os_family.change => @update_os_version() if @state.get "os_family" @os_family.val @state.get "os_family" @update_os_version() if @state.get "os_version" @os_version.val @state.get "os_version" class AddJCloudsAgentByImagePage extends WizardPage template: -> jade["agents_page/create_agent_wizard/add_cloud_agent_by_image_page.jade"] elements: ":input[name=image-id]": "image_id" ":input[name=location-id]": "location_id" get_next: -> new AddJCloudsAgentPage3 model: @model container: @container prev: @ state: @state sync_state: -> @state.set image_id: @image_id.val() location_id: @location_id.val() on_render: -> super @validated_controls = [] @validated_controls.push new FON.ValidatingTextInput control: @image_id controller: @ validator: (text) -> if !text || text == "" ok: false, msg: "You must specify what image ID to use for the new nodes" else ok: true, msg: "" cb: @maybe_enable_next if @state.get("provider") == "aws-ec2" @validated_controls.push new FON.ValidatingTextInput control: @location_id controller: @ validator: (text) -> if !text || text == "" ok: false, msg: "You must specify what location to use for the new nodes" else ok: true, msg: "" cb: @maybe_enable_next @image_id.bind "DOMNodeInsertedIntoDocument", => @image_id.focus() @maybe_enable_next(@) @image_id.val @state.get "image_id" @location_id.val @state.get "location_id" class AddJCloudsAgentPage3 extends WizardPage template: -> jade["agents_page/create_agent_wizard/add_cloud_agent_page_3.jade"] elements: ":input[name=user-account]": "user_account" ":input[name=owner]": "owner" ":input[name=group]": "group" ":input[name=disable-admin-access]": "disable_admin_access" sync_state: -> @state.set user_account: @user_account.val() owner: @owner.val() group: @group.val() adminAccess: !@disable_admin_access.is(":checked") on_finish: -> @sync_state() arguments = providerType: "jclouds" name: @state.get "name" providerName: @state.get "provider" #identity: @state.get "identity" #credential: @state.get "credential" user: @state.get "user_account" group: @state.get "group" owner: @state.get "owner" number: @state.get "number" proxyUri: @state.get "proxy" version: @state.get("version").id profiles: @state.get("profiles").join(", ") adminAccess: @state.get "adminAccess" ensembleServer: @state.get "ensemble_server" jvmOpts: @state.get "jvmopts" resolver: @state.get "resolver" arguments.group = "fabric" if !@state.get("group") || @state.get("group") == "" arguments.owner = null if !@state.get("owner") || @state.get("owner") == "" arguments.user = null if !@state.get("user_account") || @state.get("user") == "" if @state.get("instance_type") == "Custom" arguments['hardwareId'] = @state.get "hardware_id" else arguments['instanceType'] = @state.get "instance_type" if @state.get("type_selection") == "by-os" arguments['osFamily'] = @state.get "os_family" arguments['osVersion'] = @state.get "os_version" else arguments['imageId'] = @state.get "image_id" arguments['locationId'] = @state.get "location_id" options = success: (data, textStatus, jqXHR) => error: (jqXHR, textStatus, errorThrown) => app.flash kind: "error" title: "Server Error : " message: "Container creation failed due to : \u201c#{textStatus.responseText}\u201d" @model.create arguments, options @container.do_return() false on_render: -> super @validated_controls = [] @user_account.bind "DOMNodeInsertedIntoDocument", => @user_account.focus() @maybe_enable_next(@) @user_account.val @state.get "user_account" @owner.val @state.get "owner" @group.val @state.get "group" class AgentTypeSelectionPage extends WizardPage template: -> jade["agents_page/create_agent_wizard/create_agent_type_selection.jade"] elements: "li.clouds": "cloud_option" initialize: -> super @compute_services = new ComputeServices @compute_services.fetch() @compute_services.bind "change", @render, @ get_next: -> true on_next: -> @selection = $("input[name=agent-type]:checked").val() if (@selection == "child") if (!@child_agent_pages) @child_agent_pages = new AddChildAgentPage1 model: @model container: @container prev: @ state: @state @next = @child_agent_pages else if (@selection == "ssh") if (!@ssh_agent_pages) @ssh_agent_pages = new AddSSHAgentPage1 model: @model container: @container prev: @ state: @state @next = @ssh_agent_pages else if (@selection == "jclouds") if (!@jclouds_agent_pages) @jclouds_agent_pages = new AddJCloudsAgentPage1 model: @model container: @container prev: @ state: @state compute_services: @compute_services @next = @jclouds_agent_pages super on_render: (self) -> super if @compute_services.length == 0 @cloud_option.css "display", "none" el = $(@el) if (@selection) radio = el.find("input[name=agent-type]").filter("[value=#{@selection}]") radio.prop("checked", true) else radio = el.find("input[name=agent-type]").filter("[value=child]") radio.prop("checked", true) poll: -> @compute_services.fetch op: "update" class AgentProfileConfigPage extends WizardPage template: jade["agents_page/create_agent_wizard/agent_profile_config.jade"] template_data: -> versions: app.versions.models profiles: @profiles initialize: -> super @state.set {version: app.versions.default_version()} elements: "#version": "version_select" ".inputs-list": "profile_list" get_next: -> new AgentTypeSelectionPage model: @model container: @container prev: @ state: @state sync_state: -> checked = $("input:checked") profile_names = [] for profile in checked profile_names.push profile.name @state.set {profiles: profile_names} update_profile_list: -> @profile_list.empty() version = @state.get "version" profile_names = @state.get "profiles" all_profiles = version.get "_profiles" all_profiles = _.difference all_profiles, version.get "abstract_profiles" for profile in all_profiles profile = profile.trim() li = _.template("<li><div class=\"clearfix\" style=\"margin: 0px;\"><label><input type=\"checkbox\" name=\"#{profile}\" value=\"#{profile}\"><span>#{profile}</span></label></div></li>") if profile_names for p in profile_names if profile == p $(":input", li).prop("checked", true) @profile_list.append(li) on_render: -> super @version_select.val(@state.get("version").attributes.id) @version_select.change (event) => for version in app.versions.models if version.id == $("select option:selected").val() @state.set {version: version} @state.unset "profiles" @update_profile_list() @update_profile_list() class AgentConfigurationPage extends WizardPage template: jade["agents_page/create_agent_wizard/standard_agent_details_page.jade"] elements: ":input[name=name]": "name" ":input[name=ensemble-server]": "ensemble_server" ":input[name=use-jvm-opts]": "use_jvm_opts" ":input[name=jvm-opts]": "jvm_opts" ":input[name=proxy]": "proxy" ":input[name=use-proxy]": "use_proxy" ":input[name=number]": "number" "select[name=resolver]": "resolver" initialize: -> super @state.set {number: 1} get_next: -> new AgentProfileConfigPage model: @model container: @container prev: @ state: @state sync_state: -> proxy = null jvmopts = null proxy = @proxy.val() if @use_proxy.is ":checked" jvmopts = @jvm_opts.val() if @use_jvm_opts.is ":checked" ensemble_server = @ensemble_server.is ":checked" @state.set { name: @name.val() ensemble_server: ensemble_server jvmopts: jvmopts proxy: proxy number: @number.val() resolver: @resolver.val() } on_render: -> super @validated_controls = [] @validated_controls.push new FON.ValidatingTextInput control: @name controller: @ validator: (text) -> regex = /^[a-zA-Z0-9_-]*$/ if !text || text == "" ok: false, msg: "You must specify a container name" else if !regex.test(text) ok: false msg: "Name can only contain letters, numbers, \u201c-\u201d, and \u201c_\u201d" else ok: true, msg: "" cb: @maybe_enable_next @validated_controls.push new FON.ValidatingTextInput control: @number controller: @ validator: (text) -> if !text || text == "" ok: false, msg: "You must specify how many containers to create" else if isNaN(text) ok: false, msg: "Count must be a positive integer" else ok: true, msg: "If greater than 1, multiple containers will be created with instance numbers appended to the name" cb: @maybe_enable_next @use_proxy.click (event) => if @use_proxy.is ":checked" @proxy.prop "disabled", false else @proxy.prop "disabled", true @proxy.val("") true @use_jvm_opts.click (event) => if @use_jvm_opts.is ":checked" @jvm_opts.prop "disabled", false else @jvm_opts.prop "disabled", true @jvm_opts.val "" @name.bind "DOMNodeInsertedIntoDocument", => @name.focus() @maybe_enable_next(@) @ensemble_server.prop "checked", @state.get "ensemble_server" if @state.get "jvmopts" @use_jvm_opts.attr("checked", true) @jvm_opts.val @state.get "jvmopts" @jvm_opts.prop "disabled", false else @use_jvm_opts.attr "checked", false @jvm_opts.prop "disabled", true if @state.get "proxy" @use_proxy.attr("checked", true) @proxy.val @state.get "proxy" @proxy.prop "disabled", false else @use_proxy.attr("checked", false) @proxy.prop "disabled", true @number.val @state.get "number" @name.val @state.get "name" @resolver.val @state.get "resolver" class WizardIntro extends WizardPage template: jade["agents_page/create_agent_wizard/create_agent_intro_page.jade"] get_next: -> new AgentConfigurationPage model: @model container: @container prev: @ state: @state class AddAgentWizard extends FON.TemplateController template: jade["common/wizard.jade"] template_data: -> header: "Create Container" elements: ".body": "body" "a.next": "next" "a.back": "back" "a.cancel": "cancel" initialize: -> super @state = new FON.Model @page1 = new AgentConfigurationPage model: @model container: @ state: @state @state.bind "change:page", @refresh_content, @ @do_return = @options.do_return if @options.do_return on_render: (self) -> @cancel.click (event) => @do_return() false if (!@state.get("page")) self.set_page(@page1) do_return: -> disable_next: -> @next.unbind('click') @next.click (event) -> false @next.addClass("disabled") enable_next: (text, handler) -> @configure_next(text, handler) configure_next: (text, handler) -> @next.unbind('click') @next.removeClass("disabled") @next.text(text) if (handler) @next.click (event) -> handler(event) else @next.click (event) -> false enable_back: (handler) -> @back.unbind('click') @back.removeClass("disabled") if (handler) @back.click (event) -> handler(event) else @back.click (event) -> false disable_back: -> @back.unbind('click') @back.click (event) -> false @back.addClass("disabled") clear_handlers: -> @back.unbind('click') @next.unbind('click') @back.click (event) -> false @next.click (event) -> false set_page: (page) -> @state.set {page: page} refresh_content: -> page = @state.get("page") @body.empty() @body.append(page.render().el) poll: -> @model.fetch op: "update" page = @state.get "page" if page && page.poll && _.isFunction(page.poll) page.poll() AddAgentWizard
true
### Copyright 2010 Red Hat, Inc. Red Hat licenses this file to you 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. ### define [ "models/app" "views/jade" "controllers/agents_page" "models/compute_services" "controllers/controls/collection" "controllers/controls/validating_text_input" ], (app, jade, AgentsController, ComputeServices) -> class WizardPage extends FON.TemplateController tagName: "fieldset" validated_controls = [] initialize: -> super @container = @options.container if @options.container @prev = @options.prev if @options.prev @state = @options.state if @options.state @next = @get_next() get_next: -> null sync_state: -> maybe_enable_next: (self) -> valid = true keep_checking = true if self.validated_controls for control in self.validated_controls if !control.validate() && valid valid = false if valid if self.next self.container.enable_next "Next", -> self.on_next() else self.container.enable_next "Finish", -> self.on_finish() else self.container.disable_next() on_back: -> if (@prev) @sync_state() @container.set_page(@prev) false on_next: -> if (@next) @sync_state() @container.set_page(@next) false on_finish: -> @sync_state() false on_render: -> if (@prev) @container.enable_back => @on_back() else @container.disable_back() if (@next) @container.configure_next( "Next" => @on_next() ) else @container.configure_next( "Finish" => @on_finish() ) class RootAgentFilteredList extends FON.CollectionController on_add: (agent) -> if (agent.get("root") && agent.get("alive")) super(agent) class RootAgentSelectControl extends FON.TemplateController tagName: "li" className: "padded" template: jade["agents_page/create_agent_wizard/agent_selector_entry.jade"] template_data: -> @model.toJSON() elements: "input": "input" initialize: -> super @state = @options.state if @options.state on_render: (self) => @input.click (event) => @state.set {selected: @model} if (@state.get("selected") == @model) @input.prop("checked", true) class AddChildAgentPage1 extends WizardPage template: -> jade["agents_page/create_agent_wizard/add_child_agent_page_1.jade"] elements: "ul.inputs-list.agent-selector": "agent_selector" on_finish: -> @sync_state() arguments = providerType: "child" name: @state.get "name" parent: @state.get("selected").id number: @state.get("number") proxyUri: @state.get("proxy") version: @state.get("version").id profiles: @state.get("profiles").join(", ") ensembleServer: @state.get("ensemble_server") jvmOpts: @state.get("jvmopts") resolver: @state.get "resolver" options = success: (data, textStatus, jqXHR) => error: (model, response, options) => app.flash kind: "error" title: "Server Error : " message: "Container creation failed due to #{response.statusText} : \u201c#{response.responseText}\u201d" @model.create arguments, options @container.do_return() false on_render: (self) -> super ul = new RootAgentFilteredList el: @agent_selector collection: @model child_control: (agent) => new RootAgentSelectControl model: agent state: @state ul.render() if (!@state.get("selected")) $(ul.el).find("input[name=root-agent]:first").click() class AddSSHAgentPage1 extends WizardPage template: -> jade["agents_page/create_agent_wizard/add_ssh_agent_page_1.jade"] elements: ":input[name='hostname']": "hostname" ":input[name='port']": "port" ":input[name='user']": "username" ":input[name='password']": "PI:PASSWORD:<PASSWORD>END_PI" "input[name=use-pk-file]": "use_pk_file" "input[name=pk-file]": "pk_file" "a.browse": "browse" initialize: -> super @state.set {port: 22} get_next: -> new AddSSHAgentPage2 model: @model container: @container prev: @ state: @state sync_state: -> pk_file = null pk_file = @pk_file.val() if @use_pk_file.is ":checked" @state.set { hostname: @hostname.val() port: @port.val() username: @username.val() password: @password.val() pk_file: pk_file } on_render: -> super @validated_controls = [] @validated_controls.push new FON.ValidatingTextInput control: @hostname controller: @ validator: (text) -> if !text || text == "" ok: false, msg: "You must specify a valid hostname" else ok: true, msg: "" cb: @maybe_enable_next @validated_controls.push new FON.ValidatingTextInput control: @port controller: @ validator: (text) -> if !text || text == "" ok: false, msg: "You must specify a valid port number" else if isNaN(text) ok: false, msg: "You must specify a valid port number" else ok: true, msg: "" cb: @maybe_enable_next @validated_controls.push new FON.ValidatingTextInput control: @username controller: @ validator: (text) -> if !text || text == "" ok: false, msg: "You must specify a username" else ok: true, msg: "" cb: @maybe_enable_next @validated_controls.push new FON.ValidatingTextInput control: @password controller: @ validator: (text) => if !@use_pk_file.is(":checked") && (!text || text == "") ok: false, msg: "You must specify a password" else ok: true, msg: "" cb: @maybe_enable_next @hostname.bind "DOMNodeInsertedIntoDocument", => @hostname.focus() @maybe_enable_next(@) @use_pk_file.change (event) => if @use_pk_file.is ":checked" @pk_file.prop "disabled", false else @pk_file.prop "disabled", true @pk_file.val "" @maybe_enable_next(@) if @state.get "pk_file" @use_pk_file.attr "checked", true @pk_file.val @state.get "pk_file" @pk_file.prop "disabled", false else @use_pk_file.attr "checked", false @pk_file.prop "disabled", true @hostname.val @state.get "hostname" @port.val @state.get "port" @username.val @state.get "username" @password.val @state.get "password" class AddSSHAgentPage2 extends WizardPage template: -> jade["agents_page/create_agent_wizard/add_ssh_agent_page_2.jade"] elements: ":input[name='path']": "path" ":input[name='retries']": "retries" ":input[name='retry-delay']": "retry_delay" initialize: -> super @state.set retries: 1 retry_delay: 1 sync_state: -> @state.set path: @path.val() retries: @retries.val() retry_delay: @retry_delay.val() on_finish: -> @sync_state() arguments = providerType: "ssh" name: @state.get "name" host: @state.get "hostname" username: @state.get "username" #password: PI:PASSWORD:<PASSWORD>END_PI "PI:PASSWORD:<PASSWORD>END_PI" port: @state.get "port" path: @state.get "path" sshRetries: @state.get "retries" retryDelay: @state.get "retry_delay" number: @state.get "number" proxyUri: @state.get "proxy" version: @state.get("version").id profiles: @state.get("profiles").join(", ") ensembleServer: @state.get "ensemble_server" jvmOpts: @state.get "jvmopts" resolver: @state.get "resolver" if @state.get "pk_file" arguments['privateKeyFile'] = @state.get "pk_file" arguments['passPhrase'] = PI:PASSWORD:<PASSWORD>END_PI "password" else arguments['password'] = PI:PASSWORD:<PASSWORD>END_PI "PI:PASSWORD:<PASSWORD>END_PI" options = success: (data, textStatus, jqXHR) => error: (jqXHR, textStatus, errorThrown) => app.flash kind: "error" title: "Server Error : " message: "Container creation failed due to #{textStatus.statusText} : \u201c#{textStatus.responseText}\u201d" @model.create arguments, options @container.do_return() false on_render: -> super @validated_controls = [] @validated_controls.push new FON.ValidatingTextInput control: @path controller: @ validator: (text) -> if !text || text == "" ok: false, msg: "You must specify a path" else ok: true, msg: "" cb: @maybe_enable_next @validated_controls.push new FON.ValidatingTextInput control: @retries controller: @ validator: (text) -> if !text || text == "" ok: false msg: "You must specify a valid retry count" else if isNaN(text) ok: false msg: "You must specify a valid retry count" else ok: true msg: "" cb: @maybe_enable_next @validated_controls.push new FON.ValidatingTextInput control: @retry_delay controller: @ validator: (text) -> if !text || text == "" ok: false msg: "You must specify a valid retry count" else if isNaN(text) ok: false msg: "You must specify a valid retry count" else ok: true, msg: "" cb: @maybe_enable_next if !@state.get "path" @state.set path: "/home/#{@state.get("username")}" @path.val @state.get "path" @retries.val @state.get "retries" @retry_delay.val @state.get "retry_delay" class AddJCloudsAgentPage1 extends WizardPage template: -> jade["agents_page/create_agent_wizard/add_cloud_agent_page_1.jade"] elements: "select[name=provider]": "provider" ":input[name=instance-type]": "instance_type" ":input[name=type-selection]": "type_selection" "input[name=remember]": "remember_credentials" ":input[name=hardware-id]": "hardware_id" "#hardware-id": "hardware_id_div" initialize: -> super @compute_services = @options.compute_services get_next: -> true on_next: -> type_selection = $(@type_selection).filter(":checked").val() if type_selection == "by-os" if !@by_os_pages @by_os_pages = new AddJCloudsAgentByOSPage model: @model container: @container prev: @ state: @state @next = @by_os_pages else if type_selection == "by-image" if !@by_image_pages @by_image_pages = new AddJCloudsAgentByImagePage model: @model container: @container prev: @ state: @state @next = @by_image_pages super sync_state: -> @state.set provider: @provider.val() instance_type: @instance_type.val() hardware_id: @hardware_id.val() type_selection: $(@type_selection).filter(":checked").val() maybe_show_custom: (event) -> if @instance_type.val() == "Custom" @hardware_id_div.removeClass "hide" else @hardware_id_div.addClass "hide" on_render: -> super @compute_services.each (service) => @provider.append $("<option/>", value: service.id text: service.get "name") @provider.bind "DOMNodeInsertedIntoDocument", => @provider.focus() @maybe_enable_next(@) @instance_type.bind "DOMNodeInsertedIntoDocument", (event) => @maybe_show_custom(event) @instance_type.change (event) => @maybe_show_custom(event) if !@state.get "type_selection" @state.set type_selection: "by-os" selection = @state.get "type_selection" for element in @type_selection el = $(element) el.attr "checked", (el.val() == selection) @provider.val @state.get "provider" @instance_type.val @state.get "instance_type" @hardware_id.val @state.get "hardware_id" poll: -> @compute_services.fetch({op: "update"}) if @compute_services class AddJCloudsAgentByOSPage extends WizardPage template: -> jade["agents_page/create_agent_wizard/add_cloud_agent_by_os_page.jade"] elements: "select[name=os-family]": "os_family" "select[name=os-version]": "os_version" mask: suse: "SUSE" debian: "Debian" centos: "CentOS" rhel: "Red Hat Enterprise Linux" solaris: "Solaris" ubuntu: "Ubuntu" windows: "Windows" initialize: -> super @os_and_versions_map = app.cloud_os_and_versions.toJSON() get_next: -> new AddJCloudsAgentPage3 model: @model container: @container prev: @ state: @state sync_state: -> @state.set os_family: @os_family.val() os_version: @os_version.val() update_os_version: -> @os_version.empty() selected = @os_family.val() versions = @os_and_versions_map[selected] for key, value of versions @os_version.append """<option value="#{value}">#{key}</option>""" on_render: -> super for os of @os_and_versions_map @os_family.append """<option value="#{os}">#{@mask[os]}</option>""" @os_family.change => @update_os_version() if @state.get "os_family" @os_family.val @state.get "os_family" @update_os_version() if @state.get "os_version" @os_version.val @state.get "os_version" class AddJCloudsAgentByImagePage extends WizardPage template: -> jade["agents_page/create_agent_wizard/add_cloud_agent_by_image_page.jade"] elements: ":input[name=image-id]": "image_id" ":input[name=location-id]": "location_id" get_next: -> new AddJCloudsAgentPage3 model: @model container: @container prev: @ state: @state sync_state: -> @state.set image_id: @image_id.val() location_id: @location_id.val() on_render: -> super @validated_controls = [] @validated_controls.push new FON.ValidatingTextInput control: @image_id controller: @ validator: (text) -> if !text || text == "" ok: false, msg: "You must specify what image ID to use for the new nodes" else ok: true, msg: "" cb: @maybe_enable_next if @state.get("provider") == "aws-ec2" @validated_controls.push new FON.ValidatingTextInput control: @location_id controller: @ validator: (text) -> if !text || text == "" ok: false, msg: "You must specify what location to use for the new nodes" else ok: true, msg: "" cb: @maybe_enable_next @image_id.bind "DOMNodeInsertedIntoDocument", => @image_id.focus() @maybe_enable_next(@) @image_id.val @state.get "image_id" @location_id.val @state.get "location_id" class AddJCloudsAgentPage3 extends WizardPage template: -> jade["agents_page/create_agent_wizard/add_cloud_agent_page_3.jade"] elements: ":input[name=user-account]": "user_account" ":input[name=owner]": "owner" ":input[name=group]": "group" ":input[name=disable-admin-access]": "disable_admin_access" sync_state: -> @state.set user_account: @user_account.val() owner: @owner.val() group: @group.val() adminAccess: !@disable_admin_access.is(":checked") on_finish: -> @sync_state() arguments = providerType: "jclouds" name: @state.get "name" providerName: @state.get "provider" #identity: @state.get "identity" #credential: @state.get "credential" user: @state.get "user_account" group: @state.get "group" owner: @state.get "owner" number: @state.get "number" proxyUri: @state.get "proxy" version: @state.get("version").id profiles: @state.get("profiles").join(", ") adminAccess: @state.get "adminAccess" ensembleServer: @state.get "ensemble_server" jvmOpts: @state.get "jvmopts" resolver: @state.get "resolver" arguments.group = "fabric" if !@state.get("group") || @state.get("group") == "" arguments.owner = null if !@state.get("owner") || @state.get("owner") == "" arguments.user = null if !@state.get("user_account") || @state.get("user") == "" if @state.get("instance_type") == "Custom" arguments['hardwareId'] = @state.get "hardware_id" else arguments['instanceType'] = @state.get "instance_type" if @state.get("type_selection") == "by-os" arguments['osFamily'] = @state.get "os_family" arguments['osVersion'] = @state.get "os_version" else arguments['imageId'] = @state.get "image_id" arguments['locationId'] = @state.get "location_id" options = success: (data, textStatus, jqXHR) => error: (jqXHR, textStatus, errorThrown) => app.flash kind: "error" title: "Server Error : " message: "Container creation failed due to : \u201c#{textStatus.responseText}\u201d" @model.create arguments, options @container.do_return() false on_render: -> super @validated_controls = [] @user_account.bind "DOMNodeInsertedIntoDocument", => @user_account.focus() @maybe_enable_next(@) @user_account.val @state.get "user_account" @owner.val @state.get "owner" @group.val @state.get "group" class AgentTypeSelectionPage extends WizardPage template: -> jade["agents_page/create_agent_wizard/create_agent_type_selection.jade"] elements: "li.clouds": "cloud_option" initialize: -> super @compute_services = new ComputeServices @compute_services.fetch() @compute_services.bind "change", @render, @ get_next: -> true on_next: -> @selection = $("input[name=agent-type]:checked").val() if (@selection == "child") if (!@child_agent_pages) @child_agent_pages = new AddChildAgentPage1 model: @model container: @container prev: @ state: @state @next = @child_agent_pages else if (@selection == "ssh") if (!@ssh_agent_pages) @ssh_agent_pages = new AddSSHAgentPage1 model: @model container: @container prev: @ state: @state @next = @ssh_agent_pages else if (@selection == "jclouds") if (!@jclouds_agent_pages) @jclouds_agent_pages = new AddJCloudsAgentPage1 model: @model container: @container prev: @ state: @state compute_services: @compute_services @next = @jclouds_agent_pages super on_render: (self) -> super if @compute_services.length == 0 @cloud_option.css "display", "none" el = $(@el) if (@selection) radio = el.find("input[name=agent-type]").filter("[value=#{@selection}]") radio.prop("checked", true) else radio = el.find("input[name=agent-type]").filter("[value=child]") radio.prop("checked", true) poll: -> @compute_services.fetch op: "update" class AgentProfileConfigPage extends WizardPage template: jade["agents_page/create_agent_wizard/agent_profile_config.jade"] template_data: -> versions: app.versions.models profiles: @profiles initialize: -> super @state.set {version: app.versions.default_version()} elements: "#version": "version_select" ".inputs-list": "profile_list" get_next: -> new AgentTypeSelectionPage model: @model container: @container prev: @ state: @state sync_state: -> checked = $("input:checked") profile_names = [] for profile in checked profile_names.push profile.name @state.set {profiles: profile_names} update_profile_list: -> @profile_list.empty() version = @state.get "version" profile_names = @state.get "profiles" all_profiles = version.get "_profiles" all_profiles = _.difference all_profiles, version.get "abstract_profiles" for profile in all_profiles profile = profile.trim() li = _.template("<li><div class=\"clearfix\" style=\"margin: 0px;\"><label><input type=\"checkbox\" name=\"#{profile}\" value=\"#{profile}\"><span>#{profile}</span></label></div></li>") if profile_names for p in profile_names if profile == p $(":input", li).prop("checked", true) @profile_list.append(li) on_render: -> super @version_select.val(@state.get("version").attributes.id) @version_select.change (event) => for version in app.versions.models if version.id == $("select option:selected").val() @state.set {version: version} @state.unset "profiles" @update_profile_list() @update_profile_list() class AgentConfigurationPage extends WizardPage template: jade["agents_page/create_agent_wizard/standard_agent_details_page.jade"] elements: ":input[name=name]": "name" ":input[name=ensemble-server]": "ensemble_server" ":input[name=use-jvm-opts]": "use_jvm_opts" ":input[name=jvm-opts]": "jvm_opts" ":input[name=proxy]": "proxy" ":input[name=use-proxy]": "use_proxy" ":input[name=number]": "number" "select[name=resolver]": "resolver" initialize: -> super @state.set {number: 1} get_next: -> new AgentProfileConfigPage model: @model container: @container prev: @ state: @state sync_state: -> proxy = null jvmopts = null proxy = @proxy.val() if @use_proxy.is ":checked" jvmopts = @jvm_opts.val() if @use_jvm_opts.is ":checked" ensemble_server = @ensemble_server.is ":checked" @state.set { name: @name.val() ensemble_server: ensemble_server jvmopts: jvmopts proxy: proxy number: @number.val() resolver: @resolver.val() } on_render: -> super @validated_controls = [] @validated_controls.push new FON.ValidatingTextInput control: @name controller: @ validator: (text) -> regex = /^[a-zA-Z0-9_-]*$/ if !text || text == "" ok: false, msg: "You must specify a container name" else if !regex.test(text) ok: false msg: "Name can only contain letters, numbers, \u201c-\u201d, and \u201c_\u201d" else ok: true, msg: "" cb: @maybe_enable_next @validated_controls.push new FON.ValidatingTextInput control: @number controller: @ validator: (text) -> if !text || text == "" ok: false, msg: "You must specify how many containers to create" else if isNaN(text) ok: false, msg: "Count must be a positive integer" else ok: true, msg: "If greater than 1, multiple containers will be created with instance numbers appended to the name" cb: @maybe_enable_next @use_proxy.click (event) => if @use_proxy.is ":checked" @proxy.prop "disabled", false else @proxy.prop "disabled", true @proxy.val("") true @use_jvm_opts.click (event) => if @use_jvm_opts.is ":checked" @jvm_opts.prop "disabled", false else @jvm_opts.prop "disabled", true @jvm_opts.val "" @name.bind "DOMNodeInsertedIntoDocument", => @name.focus() @maybe_enable_next(@) @ensemble_server.prop "checked", @state.get "ensemble_server" if @state.get "jvmopts" @use_jvm_opts.attr("checked", true) @jvm_opts.val @state.get "jvmopts" @jvm_opts.prop "disabled", false else @use_jvm_opts.attr "checked", false @jvm_opts.prop "disabled", true if @state.get "proxy" @use_proxy.attr("checked", true) @proxy.val @state.get "proxy" @proxy.prop "disabled", false else @use_proxy.attr("checked", false) @proxy.prop "disabled", true @number.val @state.get "number" @name.val @state.get "name" @resolver.val @state.get "resolver" class WizardIntro extends WizardPage template: jade["agents_page/create_agent_wizard/create_agent_intro_page.jade"] get_next: -> new AgentConfigurationPage model: @model container: @container prev: @ state: @state class AddAgentWizard extends FON.TemplateController template: jade["common/wizard.jade"] template_data: -> header: "Create Container" elements: ".body": "body" "a.next": "next" "a.back": "back" "a.cancel": "cancel" initialize: -> super @state = new FON.Model @page1 = new AgentConfigurationPage model: @model container: @ state: @state @state.bind "change:page", @refresh_content, @ @do_return = @options.do_return if @options.do_return on_render: (self) -> @cancel.click (event) => @do_return() false if (!@state.get("page")) self.set_page(@page1) do_return: -> disable_next: -> @next.unbind('click') @next.click (event) -> false @next.addClass("disabled") enable_next: (text, handler) -> @configure_next(text, handler) configure_next: (text, handler) -> @next.unbind('click') @next.removeClass("disabled") @next.text(text) if (handler) @next.click (event) -> handler(event) else @next.click (event) -> false enable_back: (handler) -> @back.unbind('click') @back.removeClass("disabled") if (handler) @back.click (event) -> handler(event) else @back.click (event) -> false disable_back: -> @back.unbind('click') @back.click (event) -> false @back.addClass("disabled") clear_handlers: -> @back.unbind('click') @next.unbind('click') @back.click (event) -> false @next.click (event) -> false set_page: (page) -> @state.set {page: page} refresh_content: -> page = @state.get("page") @body.empty() @body.append(page.render().el) poll: -> @model.fetch op: "update" page = @state.get "page" if page && page.poll && _.isFunction(page.poll) page.poll() AddAgentWizard
[ { "context": "bootstrap/4.1.0/css/bootstrap.min.css\" integrity=\"sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4\" crossorigin=\"anonymous\">'\n @addi", "end": 1409, "score": 0.9993618726730347, "start": 1338, "tag": "KEY", "value": "sha384-9gVQ4dYFww...
lib/atom-html-templates.coffee
Feridum/atom-html-templates
9
{CompositeDisposable} = require 'atom' module.exports = AtomHtmlTemplates = subscriptions: null activate: (state) -> @templateForm = "" @additionalStyles = [] @additionalJs = [] @defaultStyles = '<link rel="stylesheet" href="PATH">' @defaultCharset = '<meta charset="UTF-8">' @defaultTitle = '<title>TITLE</title>' @defaultDescription = '<meta name="description" content="DESCRIPTION">' @defaultAuthor = '<meta name="author" content="AUTHOR">' @defaultLanguage = 'en' # @modalPanel = atom.workspace.addModalPanel(item: @atomHtmlTemplatesView.getElement(), visible: false) # Events subscribed to in atom's system can be easily cleaned up with a CompositeDisposable @subscriptions = new CompositeDisposable # Register command that toggles this view @subscriptions.add atom.commands.add 'atom-workspace', 'atom-html-templates:toggle': => @toggle() deactivate: -> @subscriptions.dispose() addResource: (array) -> indeksS = indeksJ = 0 for i in [0...array.length] by 1 if array[i] == 'bootstrap' @additionalStyles[indeksS++]= '<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">' @additionalJs[indeksJ++] = '<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>' @additionalJs[indeksJ++] = '<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js" integrity="sha384-cs/chFZiN24E4KMATLdqdvsezGxaGsi4hLGOzlXwp5UZB1LY//20VyM2taTB4QvJ" crossorigin="anonymous"></script>' @additionalJs[indeksJ++] = '<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js" integrity="sha384-uefMccjFJAIv6A+rW+L4AHf99KvxDjWSu1z9VI8SKNVmz4sk7buKt/6v9KI65qnm" crossorigin="anonymous"></script>' else if array[i] == 'foundation' @additionalStyles[indeksS++] = '<link href="https://cdnjs.cloudflare.com/ajax/libs/foundation/6.2.0/foundation.min.css" rel="stylesheet">' @additionalJs[indeksJ++] = '<script src="https://cdnjs.cloudflare.com/ajax/libs/foundation/6.2.0/foundation.min.js"></script>' else if array[i] == 'jquery_1.12.1' @additionalJs[indeksJ++] = '<script src="https://code.jquery.com/jquery-1.12.1.min.js"></script>' else if array[i] == 'jquery_2.2.1' @additionalJs[indeksJ++] = '<script src="https://code.jquery.com/jquery-2.2.1.min.js"></script>' else if array[i] == 'fontAwesome' @additionalStyles[indeksS++]= '<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">' else if array[i] == 'mdi' @additionalStyles[indeksS++]= '<link rel="stylesheet" href="https://cdn.materialdesignicons.com/1.4.57/css/materialdesignicons.min.css">' returnAdd: (array) -> scripts = " " for i in [0...array.length] by 1 if array[i] != null||undefined scripts+='\n\t' scripts +=array[i] return scripts toggle: -> defaultGrammarScopeName = "text.html.basic" if editor=atom.workspace.getActiveTextEditor() value = editor.lineTextForScreenRow(editor.getLastScreenRow()) valueArr = value.split "-" if valueArr != null||undefined||"" @addResource(valueArr) console.log(valueArr) console.log(@additionalStyles) if valueArr[0] == "html5" @templateForm = """ <!DOCTYPE html> <html lang="#{@defaultLanguage}"> <head> #{@defaultCharset} #{@defaultTitle} #{@defaultDescription} #{@defaultAuthor} #{@defaultStyles} #{@returnAdd(@additionalStyles)} <!--[if lt IE 9]> <script src = "http://html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> </head> <body> #{@returnAdd(@additionalJs)} </body> </html> """ else if valueArr[0] == "epub" @templateForm= """ <?xml version="1.0" encoding="UTF-8"?> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops" xml:lang="#{@defaultLanguage}" lang="#{@defaultLanguage}"> <head> #{@defaultCharset} #{@defaultTitle} #{@defaultStyles} </head> <body epub:type="TYPE"> </body> </html> """ else @templateForm="There is no such option." editor.setText(@templateForm) editor.setGrammar(atom.grammars.grammarForScopeName(defaultGrammarScopeName)) # Refresh @additionalStyles = [] @additionalJs = []
91828
{CompositeDisposable} = require 'atom' module.exports = AtomHtmlTemplates = subscriptions: null activate: (state) -> @templateForm = "" @additionalStyles = [] @additionalJs = [] @defaultStyles = '<link rel="stylesheet" href="PATH">' @defaultCharset = '<meta charset="UTF-8">' @defaultTitle = '<title>TITLE</title>' @defaultDescription = '<meta name="description" content="DESCRIPTION">' @defaultAuthor = '<meta name="author" content="AUTHOR">' @defaultLanguage = 'en' # @modalPanel = atom.workspace.addModalPanel(item: @atomHtmlTemplatesView.getElement(), visible: false) # Events subscribed to in atom's system can be easily cleaned up with a CompositeDisposable @subscriptions = new CompositeDisposable # Register command that toggles this view @subscriptions.add atom.commands.add 'atom-workspace', 'atom-html-templates:toggle': => @toggle() deactivate: -> @subscriptions.dispose() addResource: (array) -> indeksS = indeksJ = 0 for i in [0...array.length] by 1 if array[i] == 'bootstrap' @additionalStyles[indeksS++]= '<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">' @additionalJs[indeksJ++] = '<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script>' @additionalJs[indeksJ++] = '<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script>' @additionalJs[indeksJ++] = '<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script>' else if array[i] == 'foundation' @additionalStyles[indeksS++] = '<link href="https://cdnjs.cloudflare.com/ajax/libs/foundation/6.2.0/foundation.min.css" rel="stylesheet">' @additionalJs[indeksJ++] = '<script src="https://cdnjs.cloudflare.com/ajax/libs/foundation/6.2.0/foundation.min.js"></script>' else if array[i] == 'jquery_1.12.1' @additionalJs[indeksJ++] = '<script src="https://code.jquery.com/jquery-1.12.1.min.js"></script>' else if array[i] == 'jquery_2.2.1' @additionalJs[indeksJ++] = '<script src="https://code.jquery.com/jquery-2.2.1.min.js"></script>' else if array[i] == 'fontAwesome' @additionalStyles[indeksS++]= '<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">' else if array[i] == 'mdi' @additionalStyles[indeksS++]= '<link rel="stylesheet" href="https://cdn.materialdesignicons.com/1.4.57/css/materialdesignicons.min.css">' returnAdd: (array) -> scripts = " " for i in [0...array.length] by 1 if array[i] != null||undefined scripts+='\n\t' scripts +=array[i] return scripts toggle: -> defaultGrammarScopeName = "text.html.basic" if editor=atom.workspace.getActiveTextEditor() value = editor.lineTextForScreenRow(editor.getLastScreenRow()) valueArr = value.split "-" if valueArr != null||undefined||"" @addResource(valueArr) console.log(valueArr) console.log(@additionalStyles) if valueArr[0] == "html5" @templateForm = """ <!DOCTYPE html> <html lang="#{@defaultLanguage}"> <head> #{@defaultCharset} #{@defaultTitle} #{@defaultDescription} #{@defaultAuthor} #{@defaultStyles} #{@returnAdd(@additionalStyles)} <!--[if lt IE 9]> <script src = "http://html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> </head> <body> #{@returnAdd(@additionalJs)} </body> </html> """ else if valueArr[0] == "epub" @templateForm= """ <?xml version="1.0" encoding="UTF-8"?> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops" xml:lang="#{@defaultLanguage}" lang="#{@defaultLanguage}"> <head> #{@defaultCharset} #{@defaultTitle} #{@defaultStyles} </head> <body epub:type="TYPE"> </body> </html> """ else @templateForm="There is no such option." editor.setText(@templateForm) editor.setGrammar(atom.grammars.grammarForScopeName(defaultGrammarScopeName)) # Refresh @additionalStyles = [] @additionalJs = []
true
{CompositeDisposable} = require 'atom' module.exports = AtomHtmlTemplates = subscriptions: null activate: (state) -> @templateForm = "" @additionalStyles = [] @additionalJs = [] @defaultStyles = '<link rel="stylesheet" href="PATH">' @defaultCharset = '<meta charset="UTF-8">' @defaultTitle = '<title>TITLE</title>' @defaultDescription = '<meta name="description" content="DESCRIPTION">' @defaultAuthor = '<meta name="author" content="AUTHOR">' @defaultLanguage = 'en' # @modalPanel = atom.workspace.addModalPanel(item: @atomHtmlTemplatesView.getElement(), visible: false) # Events subscribed to in atom's system can be easily cleaned up with a CompositeDisposable @subscriptions = new CompositeDisposable # Register command that toggles this view @subscriptions.add atom.commands.add 'atom-workspace', 'atom-html-templates:toggle': => @toggle() deactivate: -> @subscriptions.dispose() addResource: (array) -> indeksS = indeksJ = 0 for i in [0...array.length] by 1 if array[i] == 'bootstrap' @additionalStyles[indeksS++]= '<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="PI:KEY:<KEY>END_PI" crossorigin="anonymous">' @additionalJs[indeksJ++] = '<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="PI:KEY:<KEY>END_PI" crossorigin="anonymous"></script>' @additionalJs[indeksJ++] = '<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js" integrity="PI:KEY:<KEY>END_PI" crossorigin="anonymous"></script>' @additionalJs[indeksJ++] = '<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js" integrity="PI:KEY:<KEY>END_PI" crossorigin="anonymous"></script>' else if array[i] == 'foundation' @additionalStyles[indeksS++] = '<link href="https://cdnjs.cloudflare.com/ajax/libs/foundation/6.2.0/foundation.min.css" rel="stylesheet">' @additionalJs[indeksJ++] = '<script src="https://cdnjs.cloudflare.com/ajax/libs/foundation/6.2.0/foundation.min.js"></script>' else if array[i] == 'jquery_1.12.1' @additionalJs[indeksJ++] = '<script src="https://code.jquery.com/jquery-1.12.1.min.js"></script>' else if array[i] == 'jquery_2.2.1' @additionalJs[indeksJ++] = '<script src="https://code.jquery.com/jquery-2.2.1.min.js"></script>' else if array[i] == 'fontAwesome' @additionalStyles[indeksS++]= '<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">' else if array[i] == 'mdi' @additionalStyles[indeksS++]= '<link rel="stylesheet" href="https://cdn.materialdesignicons.com/1.4.57/css/materialdesignicons.min.css">' returnAdd: (array) -> scripts = " " for i in [0...array.length] by 1 if array[i] != null||undefined scripts+='\n\t' scripts +=array[i] return scripts toggle: -> defaultGrammarScopeName = "text.html.basic" if editor=atom.workspace.getActiveTextEditor() value = editor.lineTextForScreenRow(editor.getLastScreenRow()) valueArr = value.split "-" if valueArr != null||undefined||"" @addResource(valueArr) console.log(valueArr) console.log(@additionalStyles) if valueArr[0] == "html5" @templateForm = """ <!DOCTYPE html> <html lang="#{@defaultLanguage}"> <head> #{@defaultCharset} #{@defaultTitle} #{@defaultDescription} #{@defaultAuthor} #{@defaultStyles} #{@returnAdd(@additionalStyles)} <!--[if lt IE 9]> <script src = "http://html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> </head> <body> #{@returnAdd(@additionalJs)} </body> </html> """ else if valueArr[0] == "epub" @templateForm= """ <?xml version="1.0" encoding="UTF-8"?> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops" xml:lang="#{@defaultLanguage}" lang="#{@defaultLanguage}"> <head> #{@defaultCharset} #{@defaultTitle} #{@defaultStyles} </head> <body epub:type="TYPE"> </body> </html> """ else @templateForm="There is no such option." editor.setText(@templateForm) editor.setGrammar(atom.grammars.grammarForScopeName(defaultGrammarScopeName)) # Refresh @additionalStyles = [] @additionalJs = []
[ { "context": "ns) ->\n default_options = {\n resource_key: \"_id\"\n page_size: 20\n omit: ['__v']\n re", "end": 190, "score": 0.991335391998291, "start": 186, "tag": "KEY", "value": "\"_id" } ]
src/resource.coffee
vforgione/hapi-mongoose-resource
2
_ = require 'lodash' Handler = require './handler' Router = require './router' class Resource constructor: (@model, @path, options) -> default_options = { resource_key: "_id" page_size: 20 omit: ['__v'] rename: { __t: 'type' } } # merge options -> overwrite default options with supplied options @options = {} _.merge(@options, default_options, options) # instantiate a handler @handler = new Handler @model, @path, @options # instantiate a router @router = new Router @path, @handler, @options module.exports = Resource
64439
_ = require 'lodash' Handler = require './handler' Router = require './router' class Resource constructor: (@model, @path, options) -> default_options = { resource_key: <KEY>" page_size: 20 omit: ['__v'] rename: { __t: 'type' } } # merge options -> overwrite default options with supplied options @options = {} _.merge(@options, default_options, options) # instantiate a handler @handler = new Handler @model, @path, @options # instantiate a router @router = new Router @path, @handler, @options module.exports = Resource
true
_ = require 'lodash' Handler = require './handler' Router = require './router' class Resource constructor: (@model, @path, options) -> default_options = { resource_key: PI:KEY:<KEY>END_PI" page_size: 20 omit: ['__v'] rename: { __t: 'type' } } # merge options -> overwrite default options with supplied options @options = {} _.merge(@options, default_options, options) # instantiate a handler @handler = new Handler @model, @path, @options # instantiate a router @router = new Router @path, @handler, @options module.exports = Resource
[ { "context": "ject',\n @projectName,\n 'author:\"John Doe\"',\n 'keywords:foo,bar,baz'\n 'de", "end": 1275, "score": 0.9988045692443848, "start": 1267, "tag": "NAME", "value": "John Doe" } ]
test/helpers/project_helper.coffee
bcmw/neat
1
fs = require 'fs' path = require 'path' eS = fs.existsSync or path.existsSync {exec} = require 'child_process' Neat = require '../../lib/neat' {run} = Neat.require 'utils/commands' {rmSync:rm, ensurePath, touch} = Neat.require 'utils/files' options = {} # stderr: (data)-> print data # stdout: (data)-> print data global.withSourceFile = (file, content, callback) -> dir = file.split('/')[0..-2].join '/' ensurePath dir, (err) -> touch file, content, callback global.withCompiledFile = (file, content, callback) -> dir = file.split('/')[0..-2].join '/' ensurePath dir, (err) -> touch file, content, (err) -> run 'cake', ['build'], (status) -> callback?() global.withProject = (name, desc=null, block, opts) -> if typeof desc is 'function' [block, opts, desc] = [desc, block, opts] describe (desc or "within the generated project #{name}"), -> beforeEach -> @projectName = name @projectPath = "#{TEST_TMP_DIR}/#{name}" global.inProject = (p) -> "#{TEST_TMP_DIR}/#{name}/#{p}" addFileMatchers this process.chdir TEST_TMP_DIR ended = false runs -> args = [ NEAT_BIN, 'generate', 'project', @projectName, 'author:"John Doe"', 'keywords:foo,bar,baz' 'description:"a description"' ] run 'node', args, options, (status) => @status = status process.chdir @projectPath if opts?.init? opts.init -> ended = true else ended = true waitsFor progress(-> ended), 'Timed out on project creation', 5000 afterEach -> process.chdir TEST_ROOT unless opts?.noCleaning rm @projectPath if eS @projectPath block.call(this) global.withBundledProject = (name, desc=null, block, opts) -> if typeof desc is 'function' [block, opts, desc] = [desc, block, opts] opts ||= {} init = opts.init opts.init = (callback) -> args = [ '-s', "#{Neat.neatRoot}/lib", inProject('node_modules/neat') ] ensurePath inProject('node_modules'), -> run 'ln', args, (status) -> if init? init callback else callback?() withProject name, desc, block, opts global.withGitInitialized = (block) -> beforeEach -> process.chdir @projectPath ended = false command = 'cake build; git init; git add .; git commit -am "First commit"; git status' runs -> exec command, (err, stdout, stderr) => # if err? # console.log stderr # else # console.log stdout throw err if err? ended = true waitsFor progress(-> ended), 'Timed out on git init', 5000 block.call(this) global.withPagesInitialized = (block) -> beforeEach -> process.chdir @projectPath ended = false command = "node #{NEAT_BIN} generate github:pages" runs -> exec command, (err, stdout, stderr) => # if err? # console.log stderr # else # console.log stdout throw err if err? ended = true waitsFor progress(-> ended), 'Timed out on pages init', 5000 block.call(this)
219140
fs = require 'fs' path = require 'path' eS = fs.existsSync or path.existsSync {exec} = require 'child_process' Neat = require '../../lib/neat' {run} = Neat.require 'utils/commands' {rmSync:rm, ensurePath, touch} = Neat.require 'utils/files' options = {} # stderr: (data)-> print data # stdout: (data)-> print data global.withSourceFile = (file, content, callback) -> dir = file.split('/')[0..-2].join '/' ensurePath dir, (err) -> touch file, content, callback global.withCompiledFile = (file, content, callback) -> dir = file.split('/')[0..-2].join '/' ensurePath dir, (err) -> touch file, content, (err) -> run 'cake', ['build'], (status) -> callback?() global.withProject = (name, desc=null, block, opts) -> if typeof desc is 'function' [block, opts, desc] = [desc, block, opts] describe (desc or "within the generated project #{name}"), -> beforeEach -> @projectName = name @projectPath = "#{TEST_TMP_DIR}/#{name}" global.inProject = (p) -> "#{TEST_TMP_DIR}/#{name}/#{p}" addFileMatchers this process.chdir TEST_TMP_DIR ended = false runs -> args = [ NEAT_BIN, 'generate', 'project', @projectName, 'author:"<NAME>"', 'keywords:foo,bar,baz' 'description:"a description"' ] run 'node', args, options, (status) => @status = status process.chdir @projectPath if opts?.init? opts.init -> ended = true else ended = true waitsFor progress(-> ended), 'Timed out on project creation', 5000 afterEach -> process.chdir TEST_ROOT unless opts?.noCleaning rm @projectPath if eS @projectPath block.call(this) global.withBundledProject = (name, desc=null, block, opts) -> if typeof desc is 'function' [block, opts, desc] = [desc, block, opts] opts ||= {} init = opts.init opts.init = (callback) -> args = [ '-s', "#{Neat.neatRoot}/lib", inProject('node_modules/neat') ] ensurePath inProject('node_modules'), -> run 'ln', args, (status) -> if init? init callback else callback?() withProject name, desc, block, opts global.withGitInitialized = (block) -> beforeEach -> process.chdir @projectPath ended = false command = 'cake build; git init; git add .; git commit -am "First commit"; git status' runs -> exec command, (err, stdout, stderr) => # if err? # console.log stderr # else # console.log stdout throw err if err? ended = true waitsFor progress(-> ended), 'Timed out on git init', 5000 block.call(this) global.withPagesInitialized = (block) -> beforeEach -> process.chdir @projectPath ended = false command = "node #{NEAT_BIN} generate github:pages" runs -> exec command, (err, stdout, stderr) => # if err? # console.log stderr # else # console.log stdout throw err if err? ended = true waitsFor progress(-> ended), 'Timed out on pages init', 5000 block.call(this)
true
fs = require 'fs' path = require 'path' eS = fs.existsSync or path.existsSync {exec} = require 'child_process' Neat = require '../../lib/neat' {run} = Neat.require 'utils/commands' {rmSync:rm, ensurePath, touch} = Neat.require 'utils/files' options = {} # stderr: (data)-> print data # stdout: (data)-> print data global.withSourceFile = (file, content, callback) -> dir = file.split('/')[0..-2].join '/' ensurePath dir, (err) -> touch file, content, callback global.withCompiledFile = (file, content, callback) -> dir = file.split('/')[0..-2].join '/' ensurePath dir, (err) -> touch file, content, (err) -> run 'cake', ['build'], (status) -> callback?() global.withProject = (name, desc=null, block, opts) -> if typeof desc is 'function' [block, opts, desc] = [desc, block, opts] describe (desc or "within the generated project #{name}"), -> beforeEach -> @projectName = name @projectPath = "#{TEST_TMP_DIR}/#{name}" global.inProject = (p) -> "#{TEST_TMP_DIR}/#{name}/#{p}" addFileMatchers this process.chdir TEST_TMP_DIR ended = false runs -> args = [ NEAT_BIN, 'generate', 'project', @projectName, 'author:"PI:NAME:<NAME>END_PI"', 'keywords:foo,bar,baz' 'description:"a description"' ] run 'node', args, options, (status) => @status = status process.chdir @projectPath if opts?.init? opts.init -> ended = true else ended = true waitsFor progress(-> ended), 'Timed out on project creation', 5000 afterEach -> process.chdir TEST_ROOT unless opts?.noCleaning rm @projectPath if eS @projectPath block.call(this) global.withBundledProject = (name, desc=null, block, opts) -> if typeof desc is 'function' [block, opts, desc] = [desc, block, opts] opts ||= {} init = opts.init opts.init = (callback) -> args = [ '-s', "#{Neat.neatRoot}/lib", inProject('node_modules/neat') ] ensurePath inProject('node_modules'), -> run 'ln', args, (status) -> if init? init callback else callback?() withProject name, desc, block, opts global.withGitInitialized = (block) -> beforeEach -> process.chdir @projectPath ended = false command = 'cake build; git init; git add .; git commit -am "First commit"; git status' runs -> exec command, (err, stdout, stderr) => # if err? # console.log stderr # else # console.log stdout throw err if err? ended = true waitsFor progress(-> ended), 'Timed out on git init', 5000 block.call(this) global.withPagesInitialized = (block) -> beforeEach -> process.chdir @projectPath ended = false command = "node #{NEAT_BIN} generate github:pages" runs -> exec command, (err, stdout, stderr) => # if err? # console.log stderr # else # console.log stdout throw err if err? ended = true waitsFor progress(-> ended), 'Timed out on pages init', 5000 block.call(this)
[ { "context": "*****\n# JSPoint - point coodinate class\n# Coded by Hajime Oh-yake 2013.03.26\n#*************************************", "end": 102, "score": 0.9998896718025208, "start": 88, "tag": "NAME", "value": "Hajime Oh-yake" } ]
JSKit/01_JSPoint.coffee
digitarhythm/codeJS
0
#***************************************** # JSPoint - point coodinate class # Coded by Hajime Oh-yake 2013.03.26 #***************************************** class JSPoint extends JSObject constructor: -> super() @x = 0 @y = 0
76001
#***************************************** # JSPoint - point coodinate class # Coded by <NAME> 2013.03.26 #***************************************** class JSPoint extends JSObject constructor: -> super() @x = 0 @y = 0
true
#***************************************** # JSPoint - point coodinate class # Coded by PI:NAME:<NAME>END_PI 2013.03.26 #***************************************** class JSPoint extends JSObject constructor: -> super() @x = 0 @y = 0
[ { "context": "chosaur.Unit\n # FIXME: document this\n @names: ['parsenote']\n setup: (@objectModel) ->\n @objectModel.set", "end": 86, "score": 0.9148080945014954, "start": 77, "tag": "NAME", "value": "parsenote" } ]
assets/js/units/function/parsenote.coffee
nsyee/patchosaur
3
class Parsenote extends patchosaur.Unit # FIXME: document this @names: ['parsenote'] setup: (@objectModel) -> @objectModel.set numInlets: 1 @objectModel.set numOutlets: 2 @inlets = [@inlet] inlet: (note) => return if not note.type == 'noteOn' {velocity, note} = note @out 1, velocity @out 0, note patchosaur.units.add Parsenote
211856
class Parsenote extends patchosaur.Unit # FIXME: document this @names: ['<NAME>'] setup: (@objectModel) -> @objectModel.set numInlets: 1 @objectModel.set numOutlets: 2 @inlets = [@inlet] inlet: (note) => return if not note.type == 'noteOn' {velocity, note} = note @out 1, velocity @out 0, note patchosaur.units.add Parsenote
true
class Parsenote extends patchosaur.Unit # FIXME: document this @names: ['PI:NAME:<NAME>END_PI'] setup: (@objectModel) -> @objectModel.set numInlets: 1 @objectModel.set numOutlets: 2 @inlets = [@inlet] inlet: (note) => return if not note.type == 'noteOn' {velocity, note} = note @out 1, velocity @out 0, note patchosaur.units.add Parsenote
[ { "context": "->\n bookmarks = [\n {\n name: 'Dicloxacilina 200mg 30'\n retailPrice: 14500\n }", "end": 158, "score": 0.9990901947021484, "start": 145, "tag": "NAME", "value": "Dicloxacilina" } ]
app/assets/js/sell/sell.controller.coffee
cerbatan/CerbatanPOS
0
define(['./module'] (module) -> SellCtrl = ($log, backend, shoppingListsService, $modal) -> bookmarks = [ { name: 'Dicloxacilina 200mg 30' retailPrice: 14500 } { name: 'Second Product' retailPrice: 5600 } { name: 'Second Product' retailPrice: 5600 fraction: name: "Sobre" } { name: 'Second Product' retailPrice: 5600 } { name: 'Second Product' retailPrice: 5600 fraction: name: "Sobre" } { name: 'Second Product' retailPrice: 5600 } { name: 'Second Product' retailPrice: 5600 fraction: name: "Sobre" } ] lastInsertedProduct = null init = () => @selectedProduct = null @bookmarks = bookmarks @shoppingList = shoppingList @deleteProduct = deleteProduct @bookmarkProduct = bookmarkProduct @showProduct = showProduct @price = price @taxes = taxes @totalPrice = totalPrice @searchProducts = searchProducts @selectSearchInput = false @productSelected = productSelected @searchEnterPressed = searchEnterPressed @searchModified = searchModified @charge = charge activate() activate = () => bookmarkProduct = (product) => $log.info "Product bookmarked: #{product.name}" showProduct = (product) => $log.info "Show Product: #{product.name}" shoppingList = () -> shoppingListsService.currentShoppingList().products() price = () -> shoppingListsService.currentShoppingList().price() taxes = () -> shoppingListsService.currentShoppingList().taxes() totalPrice = () -> shoppingListsService.currentShoppingList().totalPrice() searchProducts = (filter) -> backend.listProducts(filter).then( (response) -> response.data ) productSelected = ($item, $model, $label) -> $log.info "Product selected #{$label}, #{$item.sku}, #{@selectedProduct}" addProductToList($item) @selectSearchInput = true deleteProduct = (product) => shoppingListsService.currentShoppingList().remove(product) $log.info "Product deleted: #{product.name}" insertIntoShoppingList = (p) => shoppingListsService.currentShoppingList().insert(p) lastInsertedProduct = p addProductToList = (product) -> backend.getProduct(product.id).then( (response) -> soldProduct = response.data if soldProduct.fractions? and soldProduct.fractions.length > 0 showFractionsSelectionDialog(soldProduct.fractions).result.then( (selectedFraction) => soldProduct.fractions = [selectedFraction] insertIntoShoppingList(soldProduct) -> $log.warn 'Rejected' ) else insertIntoShoppingList(soldProduct) ) showFractionsSelectionDialog = (fractions) -> $modal.open templateUrl: "selectFractionModal.html" controller: 'SelectFractionCtrl' controllerAs: 'selectFractionCtrl' size: 'md' resolve: fractions: () -> fractions searchModified = () => lastInsertedProduct = null @selectSearchInput=false searchEnterPressed = () => insertIntoShoppingList(lastInsertedProduct) unless lastInsertedProduct == null $log.info "Enter pressed #{@selectedProduct.name}" charge = () => list = shoppingListsService.currentShoppingList() unless list.isEmpty() showRegisterPaymentDialog(list.totalPrice()).result.then( (paymentDescription) => $log.info 'Payment Registered' backend.register({items: list.getListBrief(), details: paymentDescription}).then( (response) -> shoppingListsService.clearCurrentShoppingList() $log.info response.data ) -> $log.info 'Payment Cancelled' ) showRegisterPaymentDialog = (payment) -> $modal.open templateUrl: "registerPaymentModal.html" controller: 'RegisterPaymentCtrl' controllerAs: 'paymentCtrl' size: 'md' resolve: payment: () -> payment init() return SellCtrl .$inject = ['$log', 'sellingBackend', 'shoppingListsService', '$uibModal'] SelectFractionCtrl = ($modalInstance, fractions) -> init = () => @fractions = fractions @selected = selected @cancel = cancel @activeIndex = 0 @keyDown = keyDown selected = ($index) => $modalInstance.close @fractions[$index] cancel = -> $modalInstance.dismiss() keyDown = (event) => switch event.keyCode when 40 then arrowDownPressed() when 38 then arrowUpPressed() when 13 then enterPressed() when 27 then cancel() event.stopPropagation() event.preventDefault() arrowDownPressed = => @activeIndex++ if @activeIndex < (@fractions.length - 1) arrowUpPressed = => @activeIndex-- if @activeIndex > 0 enterPressed = => selected(@activeIndex) init() return SelectFractionCtrl .$inject = ['$uibModalInstance', 'fractions'] RegisterPaymentCtrl = ($modalInstance, payment) -> init = () => @payment = payment @tendered = payment @change = change @ok = ok @cancel = cancel change = => change = @tendered - payment if change >= 0 then change else 0 ok = => $modalInstance.close @tendered cancel = -> $modalInstance.dismiss() init() return RegisterPaymentCtrl .$inject = ['$uibModalInstance', 'payment'] module.controller('SellCtrl', SellCtrl) module.controller('SelectFractionCtrl', SelectFractionCtrl) module.controller('SelectFractionCtrl', SelectFractionCtrl) module.controller('RegisterPaymentCtrl', RegisterPaymentCtrl) return )
41197
define(['./module'] (module) -> SellCtrl = ($log, backend, shoppingListsService, $modal) -> bookmarks = [ { name: '<NAME> 200mg 30' retailPrice: 14500 } { name: 'Second Product' retailPrice: 5600 } { name: 'Second Product' retailPrice: 5600 fraction: name: "Sobre" } { name: 'Second Product' retailPrice: 5600 } { name: 'Second Product' retailPrice: 5600 fraction: name: "Sobre" } { name: 'Second Product' retailPrice: 5600 } { name: 'Second Product' retailPrice: 5600 fraction: name: "Sobre" } ] lastInsertedProduct = null init = () => @selectedProduct = null @bookmarks = bookmarks @shoppingList = shoppingList @deleteProduct = deleteProduct @bookmarkProduct = bookmarkProduct @showProduct = showProduct @price = price @taxes = taxes @totalPrice = totalPrice @searchProducts = searchProducts @selectSearchInput = false @productSelected = productSelected @searchEnterPressed = searchEnterPressed @searchModified = searchModified @charge = charge activate() activate = () => bookmarkProduct = (product) => $log.info "Product bookmarked: #{product.name}" showProduct = (product) => $log.info "Show Product: #{product.name}" shoppingList = () -> shoppingListsService.currentShoppingList().products() price = () -> shoppingListsService.currentShoppingList().price() taxes = () -> shoppingListsService.currentShoppingList().taxes() totalPrice = () -> shoppingListsService.currentShoppingList().totalPrice() searchProducts = (filter) -> backend.listProducts(filter).then( (response) -> response.data ) productSelected = ($item, $model, $label) -> $log.info "Product selected #{$label}, #{$item.sku}, #{@selectedProduct}" addProductToList($item) @selectSearchInput = true deleteProduct = (product) => shoppingListsService.currentShoppingList().remove(product) $log.info "Product deleted: #{product.name}" insertIntoShoppingList = (p) => shoppingListsService.currentShoppingList().insert(p) lastInsertedProduct = p addProductToList = (product) -> backend.getProduct(product.id).then( (response) -> soldProduct = response.data if soldProduct.fractions? and soldProduct.fractions.length > 0 showFractionsSelectionDialog(soldProduct.fractions).result.then( (selectedFraction) => soldProduct.fractions = [selectedFraction] insertIntoShoppingList(soldProduct) -> $log.warn 'Rejected' ) else insertIntoShoppingList(soldProduct) ) showFractionsSelectionDialog = (fractions) -> $modal.open templateUrl: "selectFractionModal.html" controller: 'SelectFractionCtrl' controllerAs: 'selectFractionCtrl' size: 'md' resolve: fractions: () -> fractions searchModified = () => lastInsertedProduct = null @selectSearchInput=false searchEnterPressed = () => insertIntoShoppingList(lastInsertedProduct) unless lastInsertedProduct == null $log.info "Enter pressed #{@selectedProduct.name}" charge = () => list = shoppingListsService.currentShoppingList() unless list.isEmpty() showRegisterPaymentDialog(list.totalPrice()).result.then( (paymentDescription) => $log.info 'Payment Registered' backend.register({items: list.getListBrief(), details: paymentDescription}).then( (response) -> shoppingListsService.clearCurrentShoppingList() $log.info response.data ) -> $log.info 'Payment Cancelled' ) showRegisterPaymentDialog = (payment) -> $modal.open templateUrl: "registerPaymentModal.html" controller: 'RegisterPaymentCtrl' controllerAs: 'paymentCtrl' size: 'md' resolve: payment: () -> payment init() return SellCtrl .$inject = ['$log', 'sellingBackend', 'shoppingListsService', '$uibModal'] SelectFractionCtrl = ($modalInstance, fractions) -> init = () => @fractions = fractions @selected = selected @cancel = cancel @activeIndex = 0 @keyDown = keyDown selected = ($index) => $modalInstance.close @fractions[$index] cancel = -> $modalInstance.dismiss() keyDown = (event) => switch event.keyCode when 40 then arrowDownPressed() when 38 then arrowUpPressed() when 13 then enterPressed() when 27 then cancel() event.stopPropagation() event.preventDefault() arrowDownPressed = => @activeIndex++ if @activeIndex < (@fractions.length - 1) arrowUpPressed = => @activeIndex-- if @activeIndex > 0 enterPressed = => selected(@activeIndex) init() return SelectFractionCtrl .$inject = ['$uibModalInstance', 'fractions'] RegisterPaymentCtrl = ($modalInstance, payment) -> init = () => @payment = payment @tendered = payment @change = change @ok = ok @cancel = cancel change = => change = @tendered - payment if change >= 0 then change else 0 ok = => $modalInstance.close @tendered cancel = -> $modalInstance.dismiss() init() return RegisterPaymentCtrl .$inject = ['$uibModalInstance', 'payment'] module.controller('SellCtrl', SellCtrl) module.controller('SelectFractionCtrl', SelectFractionCtrl) module.controller('SelectFractionCtrl', SelectFractionCtrl) module.controller('RegisterPaymentCtrl', RegisterPaymentCtrl) return )
true
define(['./module'] (module) -> SellCtrl = ($log, backend, shoppingListsService, $modal) -> bookmarks = [ { name: 'PI:NAME:<NAME>END_PI 200mg 30' retailPrice: 14500 } { name: 'Second Product' retailPrice: 5600 } { name: 'Second Product' retailPrice: 5600 fraction: name: "Sobre" } { name: 'Second Product' retailPrice: 5600 } { name: 'Second Product' retailPrice: 5600 fraction: name: "Sobre" } { name: 'Second Product' retailPrice: 5600 } { name: 'Second Product' retailPrice: 5600 fraction: name: "Sobre" } ] lastInsertedProduct = null init = () => @selectedProduct = null @bookmarks = bookmarks @shoppingList = shoppingList @deleteProduct = deleteProduct @bookmarkProduct = bookmarkProduct @showProduct = showProduct @price = price @taxes = taxes @totalPrice = totalPrice @searchProducts = searchProducts @selectSearchInput = false @productSelected = productSelected @searchEnterPressed = searchEnterPressed @searchModified = searchModified @charge = charge activate() activate = () => bookmarkProduct = (product) => $log.info "Product bookmarked: #{product.name}" showProduct = (product) => $log.info "Show Product: #{product.name}" shoppingList = () -> shoppingListsService.currentShoppingList().products() price = () -> shoppingListsService.currentShoppingList().price() taxes = () -> shoppingListsService.currentShoppingList().taxes() totalPrice = () -> shoppingListsService.currentShoppingList().totalPrice() searchProducts = (filter) -> backend.listProducts(filter).then( (response) -> response.data ) productSelected = ($item, $model, $label) -> $log.info "Product selected #{$label}, #{$item.sku}, #{@selectedProduct}" addProductToList($item) @selectSearchInput = true deleteProduct = (product) => shoppingListsService.currentShoppingList().remove(product) $log.info "Product deleted: #{product.name}" insertIntoShoppingList = (p) => shoppingListsService.currentShoppingList().insert(p) lastInsertedProduct = p addProductToList = (product) -> backend.getProduct(product.id).then( (response) -> soldProduct = response.data if soldProduct.fractions? and soldProduct.fractions.length > 0 showFractionsSelectionDialog(soldProduct.fractions).result.then( (selectedFraction) => soldProduct.fractions = [selectedFraction] insertIntoShoppingList(soldProduct) -> $log.warn 'Rejected' ) else insertIntoShoppingList(soldProduct) ) showFractionsSelectionDialog = (fractions) -> $modal.open templateUrl: "selectFractionModal.html" controller: 'SelectFractionCtrl' controllerAs: 'selectFractionCtrl' size: 'md' resolve: fractions: () -> fractions searchModified = () => lastInsertedProduct = null @selectSearchInput=false searchEnterPressed = () => insertIntoShoppingList(lastInsertedProduct) unless lastInsertedProduct == null $log.info "Enter pressed #{@selectedProduct.name}" charge = () => list = shoppingListsService.currentShoppingList() unless list.isEmpty() showRegisterPaymentDialog(list.totalPrice()).result.then( (paymentDescription) => $log.info 'Payment Registered' backend.register({items: list.getListBrief(), details: paymentDescription}).then( (response) -> shoppingListsService.clearCurrentShoppingList() $log.info response.data ) -> $log.info 'Payment Cancelled' ) showRegisterPaymentDialog = (payment) -> $modal.open templateUrl: "registerPaymentModal.html" controller: 'RegisterPaymentCtrl' controllerAs: 'paymentCtrl' size: 'md' resolve: payment: () -> payment init() return SellCtrl .$inject = ['$log', 'sellingBackend', 'shoppingListsService', '$uibModal'] SelectFractionCtrl = ($modalInstance, fractions) -> init = () => @fractions = fractions @selected = selected @cancel = cancel @activeIndex = 0 @keyDown = keyDown selected = ($index) => $modalInstance.close @fractions[$index] cancel = -> $modalInstance.dismiss() keyDown = (event) => switch event.keyCode when 40 then arrowDownPressed() when 38 then arrowUpPressed() when 13 then enterPressed() when 27 then cancel() event.stopPropagation() event.preventDefault() arrowDownPressed = => @activeIndex++ if @activeIndex < (@fractions.length - 1) arrowUpPressed = => @activeIndex-- if @activeIndex > 0 enterPressed = => selected(@activeIndex) init() return SelectFractionCtrl .$inject = ['$uibModalInstance', 'fractions'] RegisterPaymentCtrl = ($modalInstance, payment) -> init = () => @payment = payment @tendered = payment @change = change @ok = ok @cancel = cancel change = => change = @tendered - payment if change >= 0 then change else 0 ok = => $modalInstance.close @tendered cancel = -> $modalInstance.dismiss() init() return RegisterPaymentCtrl .$inject = ['$uibModalInstance', 'payment'] module.controller('SellCtrl', SellCtrl) module.controller('SelectFractionCtrl', SelectFractionCtrl) module.controller('SelectFractionCtrl', SelectFractionCtrl) module.controller('RegisterPaymentCtrl', RegisterPaymentCtrl) return )
[ { "context": "m to work with prepending more\n key: \"message-#{id or clientId}\"\n className: z.classKebab {", "end": 2088, "score": 0.8161174654960632, "start": 2088, "tag": "KEY", "value": "" } ]
src/components/message/index.coffee
FreeRoamApp/free-roam
14
z = require 'zorium' _map = require 'lodash/map' _filter = require 'lodash/filter' _truncate = require 'lodash/truncate' _defaults = require 'lodash/defaults' _find = require 'lodash/find' RxBehaviorSubject = require('rxjs/BehaviorSubject').BehaviorSubject Avatar = require '../avatar' ActionMessage = require '../action_message' Author = require '../author' Icon = require '../icon' TripListItem = require '../trip_list_item' FormatService = require '../../services/format' colors = require '../../colors' config = require '../../config' if window? require './index.styl' TITLE_LENGTH = 30 DESCRIPTION_LENGTH = 100 module.exports = class Message constructor: (options) -> {message, @$body, isGrouped, isMe, @model, @isTextareaFocused @router, @group} = options @$avatar = new Avatar() @$author = new Author {@model, @router} @$actionMessage = new ActionMessage {@model, @router, @$body} me = @model.user.getMe() @state = z.state message: message isMe: isMe isGrouped: isGrouped isMeMentioned: me.map (me) -> mentions = message?.body?.match? config.MENTION_REGEX _find mentions, (mention) -> username = mention.replace('@', '').toLowerCase() username and username is me?.username cardInfo: if message?.card?.type is 'trip' @model.trip.getById message?.card.sourceId .map (trip) => if trip {info: trip, $card: new TripListItem {@model, @router, trip}} windowSize: @model.window.getSize() render: ({openProfileDialogFn, isTimeAlignedLeft}) => {isMe, message, cardInfo, isGrouped, isMeMentioned, windowSize} = @state.getValue() {user, groupUser, time, card, id, clientId} = message avatarSize = if windowSize.width > 840 \ then '40px' else '40px' onclick = => unless @isTextareaFocused?.getValue() openProfileDialogFn id, user, groupUser, @group z '.z-message', { # re-use elements in v-dom. doesn't seem to work with prepending more key: "message-#{id or clientId}" className: z.classKebab {isGrouped, isMe, isMeMentioned} }, z '.avatar', { onclick style: width: avatarSize }, if not isGrouped and message?.type isnt 'action' z @$avatar, { user groupUser size: avatarSize bgColor: colors.$grey200 } # z '.level', 1 z '.content', if message?.type is 'action' z @$actionMessage, { user, groupUser, time, isTimeAlignedLeft, onclick } else if not isGrouped z @$author, {user, groupUser, time, isTimeAlignedLeft, onclick} unless message?.type is 'action' or card?.type z '.body', @$body if card?.url z '.card', { onclick: (e) => e?.stopPropagation() @router.openLink card.url }, z '.title', _truncate card.title, {length: TITLE_LENGTH} z '.description', _truncate card.description, { length: DESCRIPTION_LENGTH } else if card?.type [ z '.action', @model.l.get 'message.tripCardAction' # @router.link z 'a.card', { # href: @router.get 'trip', { # id: cardInfo?.info?.id # } # }, z '.custom-card', z cardInfo?.$card ]
47549
z = require 'zorium' _map = require 'lodash/map' _filter = require 'lodash/filter' _truncate = require 'lodash/truncate' _defaults = require 'lodash/defaults' _find = require 'lodash/find' RxBehaviorSubject = require('rxjs/BehaviorSubject').BehaviorSubject Avatar = require '../avatar' ActionMessage = require '../action_message' Author = require '../author' Icon = require '../icon' TripListItem = require '../trip_list_item' FormatService = require '../../services/format' colors = require '../../colors' config = require '../../config' if window? require './index.styl' TITLE_LENGTH = 30 DESCRIPTION_LENGTH = 100 module.exports = class Message constructor: (options) -> {message, @$body, isGrouped, isMe, @model, @isTextareaFocused @router, @group} = options @$avatar = new Avatar() @$author = new Author {@model, @router} @$actionMessage = new ActionMessage {@model, @router, @$body} me = @model.user.getMe() @state = z.state message: message isMe: isMe isGrouped: isGrouped isMeMentioned: me.map (me) -> mentions = message?.body?.match? config.MENTION_REGEX _find mentions, (mention) -> username = mention.replace('@', '').toLowerCase() username and username is me?.username cardInfo: if message?.card?.type is 'trip' @model.trip.getById message?.card.sourceId .map (trip) => if trip {info: trip, $card: new TripListItem {@model, @router, trip}} windowSize: @model.window.getSize() render: ({openProfileDialogFn, isTimeAlignedLeft}) => {isMe, message, cardInfo, isGrouped, isMeMentioned, windowSize} = @state.getValue() {user, groupUser, time, card, id, clientId} = message avatarSize = if windowSize.width > 840 \ then '40px' else '40px' onclick = => unless @isTextareaFocused?.getValue() openProfileDialogFn id, user, groupUser, @group z '.z-message', { # re-use elements in v-dom. doesn't seem to work with prepending more key: "message<KEY>-#{id or clientId}" className: z.classKebab {isGrouped, isMe, isMeMentioned} }, z '.avatar', { onclick style: width: avatarSize }, if not isGrouped and message?.type isnt 'action' z @$avatar, { user groupUser size: avatarSize bgColor: colors.$grey200 } # z '.level', 1 z '.content', if message?.type is 'action' z @$actionMessage, { user, groupUser, time, isTimeAlignedLeft, onclick } else if not isGrouped z @$author, {user, groupUser, time, isTimeAlignedLeft, onclick} unless message?.type is 'action' or card?.type z '.body', @$body if card?.url z '.card', { onclick: (e) => e?.stopPropagation() @router.openLink card.url }, z '.title', _truncate card.title, {length: TITLE_LENGTH} z '.description', _truncate card.description, { length: DESCRIPTION_LENGTH } else if card?.type [ z '.action', @model.l.get 'message.tripCardAction' # @router.link z 'a.card', { # href: @router.get 'trip', { # id: cardInfo?.info?.id # } # }, z '.custom-card', z cardInfo?.$card ]
true
z = require 'zorium' _map = require 'lodash/map' _filter = require 'lodash/filter' _truncate = require 'lodash/truncate' _defaults = require 'lodash/defaults' _find = require 'lodash/find' RxBehaviorSubject = require('rxjs/BehaviorSubject').BehaviorSubject Avatar = require '../avatar' ActionMessage = require '../action_message' Author = require '../author' Icon = require '../icon' TripListItem = require '../trip_list_item' FormatService = require '../../services/format' colors = require '../../colors' config = require '../../config' if window? require './index.styl' TITLE_LENGTH = 30 DESCRIPTION_LENGTH = 100 module.exports = class Message constructor: (options) -> {message, @$body, isGrouped, isMe, @model, @isTextareaFocused @router, @group} = options @$avatar = new Avatar() @$author = new Author {@model, @router} @$actionMessage = new ActionMessage {@model, @router, @$body} me = @model.user.getMe() @state = z.state message: message isMe: isMe isGrouped: isGrouped isMeMentioned: me.map (me) -> mentions = message?.body?.match? config.MENTION_REGEX _find mentions, (mention) -> username = mention.replace('@', '').toLowerCase() username and username is me?.username cardInfo: if message?.card?.type is 'trip' @model.trip.getById message?.card.sourceId .map (trip) => if trip {info: trip, $card: new TripListItem {@model, @router, trip}} windowSize: @model.window.getSize() render: ({openProfileDialogFn, isTimeAlignedLeft}) => {isMe, message, cardInfo, isGrouped, isMeMentioned, windowSize} = @state.getValue() {user, groupUser, time, card, id, clientId} = message avatarSize = if windowSize.width > 840 \ then '40px' else '40px' onclick = => unless @isTextareaFocused?.getValue() openProfileDialogFn id, user, groupUser, @group z '.z-message', { # re-use elements in v-dom. doesn't seem to work with prepending more key: "messagePI:KEY:<KEY>END_PI-#{id or clientId}" className: z.classKebab {isGrouped, isMe, isMeMentioned} }, z '.avatar', { onclick style: width: avatarSize }, if not isGrouped and message?.type isnt 'action' z @$avatar, { user groupUser size: avatarSize bgColor: colors.$grey200 } # z '.level', 1 z '.content', if message?.type is 'action' z @$actionMessage, { user, groupUser, time, isTimeAlignedLeft, onclick } else if not isGrouped z @$author, {user, groupUser, time, isTimeAlignedLeft, onclick} unless message?.type is 'action' or card?.type z '.body', @$body if card?.url z '.card', { onclick: (e) => e?.stopPropagation() @router.openLink card.url }, z '.title', _truncate card.title, {length: TITLE_LENGTH} z '.description', _truncate card.description, { length: DESCRIPTION_LENGTH } else if card?.type [ z '.action', @model.l.get 'message.tripCardAction' # @router.link z 'a.card', { # href: @router.get 'trip', { # id: cardInfo?.info?.id # } # }, z '.custom-card', z cardInfo?.$card ]
[ { "context": "I dont like veggies'.split ' '\n after = 'Joe loves veggies'.split ' '\n @res = @cut be", "end": 3012, "score": 0.9439887404441833, "start": 3009, "tag": "NAME", "value": "Joe" } ]
test/calculate_operations.spec.coffee
hendrathings/htmldiff.js
144
# calculates the differences into a list of edit operations describe 'calculate_operations', -> beforeEach -> @cut = (require '../src/htmldiff.coffee').calculate_operations it 'should be a function', -> (expect @cut).is.a 'function' describe 'Actions', -> describe 'In the middle', -> describe 'Replace', -> beforeEach -> before = 'working on it'.split ' ' after = 'working in it'.split ' ' @res = @cut before, after it 'should result in 3 operations', -> (expect @res.length).to.equal 3 it 'should replace "on"', -> (expect @res[1]).eql action : 'replace' start_in_before: 1 end_in_before : 1 start_in_after : 1 end_in_after : 1 describe 'Insert', -> beforeEach -> before = 'working it'.split ' ' after = 'working on it'.split ' ' @res = @cut before, after it 'should result in 3 operations', -> (expect @res.length).to.equal 3 it 'should show an insert for "on"', -> (expect @res[1]).eql action : 'insert' start_in_before: 1 end_in_before : undefined start_in_after : 1 end_in_after : 1 describe 'More than one word', -> beforeEach -> before = 'working it'.split ' ' after = 'working all up on it'.split ' ' @res = @cut before, after it 'should still have 3 operations', -> (expect @res.length).to.equal 3 it 'should show a big insert', -> (expect @res[1]).eql action : 'insert' start_in_before: 1 end_in_before : undefined start_in_after : 1 end_in_after : 3 describe 'Delete', -> beforeEach -> before = 'this is a lot of text'.split ' ' after = 'this is text'.split ' ' @res = @cut before, after it 'should return 3 operations', -> (expect @res.length).to.equal 3 it 'should show the delete in the middle', -> (expect @res[1]).eql action: 'delete' start_in_before: 2 end_in_before: 4 start_in_after: 2 end_in_after: undefined describe 'Equal', -> beforeEach -> before = 'this is what it sounds like'.split ' ' after = 'this is what it sounds like'.split ' ' @res = @cut before, after it 'should return a single op', -> (expect @res.length).to.equal 1 (expect @res[0]).eql action: 'equal' start_in_before: 0 end_in_before: 5 start_in_after: 0 end_in_after: 5 describe 'At the beginning', -> describe 'Replace', -> beforeEach -> before = 'I dont like veggies'.split ' ' after = 'Joe loves veggies'.split ' ' @res = @cut before, after it 'should return 2 operations', -> (expect @res.length).to.equal 2 it 'should have a replace at the beginning', -> (expect @res[0]).eql action : 'replace' start_in_before: 0 end_in_before : 2 start_in_after : 0 end_in_after : 1 describe 'Insert', -> beforeEach -> before = 'dog'.split ' ' after = 'the shaggy dog'.split ' ' @res = @cut before, after it 'should return 2 operations', -> (expect @res.length).to.equal 2 it 'should have an insert at the beginning', -> (expect @res[0]).eql action : 'insert' start_in_before: 0 end_in_before : undefined start_in_after : 0 end_in_after : 1 describe 'Delete', -> beforeEach -> before = 'awesome dog barks'.split ' ' after = 'dog barks'.split ' ' @res = @cut before, after it 'should return 2 operations', -> (expect @res.length).to.equal 2 it 'should have a delete at the beginning', -> (expect @res[0]).eql action : 'delete' start_in_before: 0 end_in_before : 0 start_in_after : 0 end_in_after : undefined describe 'At the end', -> describe 'Replace', -> beforeEach -> before = 'the dog bit the cat'.split ' ' after = 'the dog bit a bird'.split ' ' @res = @cut before, after it 'should return 2 operations', -> (expect @res.length).to.equal 2 it 'should have a replace at the end', -> (expect @res[1]).eql action : 'replace' start_in_before: 3 end_in_before : 4 start_in_after : 3 end_in_after : 4 describe 'Insert', -> beforeEach -> before = 'this is a dog'.split ' ' after = 'this is a dog that barks'.split ' ' @res = @cut before, after it 'should return 2 operations', -> (expect @res.length).to.equal 2 it 'should have an Insert at the end', -> (expect @res[1]).eql action : 'insert' start_in_before: 4 end_in_before : undefined start_in_after : 4 end_in_after : 5 describe 'Delete', -> beforeEach -> before = 'this is a dog that barks'.split ' ' after = 'this is a dog'.split ' ' @res = @cut before, after it 'should have 2 operations', -> (expect @res.length).to.equal 2 it 'should have a delete at the end', -> (expect @res[1]).eql action : 'delete' start_in_before: 4 end_in_before : 5 start_in_after : 4 end_in_after : undefined describe 'Action Combination', -> describe 'Absorb single-whitespace to make contiguous replace actions', -> beforeEach -> #There are a bunch of replaces, but, because whitespace is #tokenized, they are broken up with equals. We want to combine #them into a contiguous replace operation. before = ['I', ' ', 'am', ' ', 'awesome'] after = ['You', ' ', 'are', ' ', 'great'] @res = @cut before, after it 'should return 1 action', -> (expect @res.length).to.equal 1 it 'should return the correct replace action', -> (expect @res[0]).eql action: 'replace' start_in_before: 0 end_in_before: 4 start_in_after: 0 end_in_after: 4 describe 'but dont absorb non-single-whitespace tokens', -> beforeEach -> before = ['I', ' ', 'am', ' ', 'awesome'] after = ['You', ' ', 'are', ' ', 'great'] @res = @cut before, after it 'should return 3 actions', -> (expect @res.length).to.equal 3 it 'should have a replace first', -> (expect @res[0].action).to.equal 'replace' it 'should have an equal second', -> (expect @res[1].action).to.equal 'equal' it 'should have a replace last', -> (expect @res[2].action).to.equal 'replace'
130168
# calculates the differences into a list of edit operations describe 'calculate_operations', -> beforeEach -> @cut = (require '../src/htmldiff.coffee').calculate_operations it 'should be a function', -> (expect @cut).is.a 'function' describe 'Actions', -> describe 'In the middle', -> describe 'Replace', -> beforeEach -> before = 'working on it'.split ' ' after = 'working in it'.split ' ' @res = @cut before, after it 'should result in 3 operations', -> (expect @res.length).to.equal 3 it 'should replace "on"', -> (expect @res[1]).eql action : 'replace' start_in_before: 1 end_in_before : 1 start_in_after : 1 end_in_after : 1 describe 'Insert', -> beforeEach -> before = 'working it'.split ' ' after = 'working on it'.split ' ' @res = @cut before, after it 'should result in 3 operations', -> (expect @res.length).to.equal 3 it 'should show an insert for "on"', -> (expect @res[1]).eql action : 'insert' start_in_before: 1 end_in_before : undefined start_in_after : 1 end_in_after : 1 describe 'More than one word', -> beforeEach -> before = 'working it'.split ' ' after = 'working all up on it'.split ' ' @res = @cut before, after it 'should still have 3 operations', -> (expect @res.length).to.equal 3 it 'should show a big insert', -> (expect @res[1]).eql action : 'insert' start_in_before: 1 end_in_before : undefined start_in_after : 1 end_in_after : 3 describe 'Delete', -> beforeEach -> before = 'this is a lot of text'.split ' ' after = 'this is text'.split ' ' @res = @cut before, after it 'should return 3 operations', -> (expect @res.length).to.equal 3 it 'should show the delete in the middle', -> (expect @res[1]).eql action: 'delete' start_in_before: 2 end_in_before: 4 start_in_after: 2 end_in_after: undefined describe 'Equal', -> beforeEach -> before = 'this is what it sounds like'.split ' ' after = 'this is what it sounds like'.split ' ' @res = @cut before, after it 'should return a single op', -> (expect @res.length).to.equal 1 (expect @res[0]).eql action: 'equal' start_in_before: 0 end_in_before: 5 start_in_after: 0 end_in_after: 5 describe 'At the beginning', -> describe 'Replace', -> beforeEach -> before = 'I dont like veggies'.split ' ' after = '<NAME> loves veggies'.split ' ' @res = @cut before, after it 'should return 2 operations', -> (expect @res.length).to.equal 2 it 'should have a replace at the beginning', -> (expect @res[0]).eql action : 'replace' start_in_before: 0 end_in_before : 2 start_in_after : 0 end_in_after : 1 describe 'Insert', -> beforeEach -> before = 'dog'.split ' ' after = 'the shaggy dog'.split ' ' @res = @cut before, after it 'should return 2 operations', -> (expect @res.length).to.equal 2 it 'should have an insert at the beginning', -> (expect @res[0]).eql action : 'insert' start_in_before: 0 end_in_before : undefined start_in_after : 0 end_in_after : 1 describe 'Delete', -> beforeEach -> before = 'awesome dog barks'.split ' ' after = 'dog barks'.split ' ' @res = @cut before, after it 'should return 2 operations', -> (expect @res.length).to.equal 2 it 'should have a delete at the beginning', -> (expect @res[0]).eql action : 'delete' start_in_before: 0 end_in_before : 0 start_in_after : 0 end_in_after : undefined describe 'At the end', -> describe 'Replace', -> beforeEach -> before = 'the dog bit the cat'.split ' ' after = 'the dog bit a bird'.split ' ' @res = @cut before, after it 'should return 2 operations', -> (expect @res.length).to.equal 2 it 'should have a replace at the end', -> (expect @res[1]).eql action : 'replace' start_in_before: 3 end_in_before : 4 start_in_after : 3 end_in_after : 4 describe 'Insert', -> beforeEach -> before = 'this is a dog'.split ' ' after = 'this is a dog that barks'.split ' ' @res = @cut before, after it 'should return 2 operations', -> (expect @res.length).to.equal 2 it 'should have an Insert at the end', -> (expect @res[1]).eql action : 'insert' start_in_before: 4 end_in_before : undefined start_in_after : 4 end_in_after : 5 describe 'Delete', -> beforeEach -> before = 'this is a dog that barks'.split ' ' after = 'this is a dog'.split ' ' @res = @cut before, after it 'should have 2 operations', -> (expect @res.length).to.equal 2 it 'should have a delete at the end', -> (expect @res[1]).eql action : 'delete' start_in_before: 4 end_in_before : 5 start_in_after : 4 end_in_after : undefined describe 'Action Combination', -> describe 'Absorb single-whitespace to make contiguous replace actions', -> beforeEach -> #There are a bunch of replaces, but, because whitespace is #tokenized, they are broken up with equals. We want to combine #them into a contiguous replace operation. before = ['I', ' ', 'am', ' ', 'awesome'] after = ['You', ' ', 'are', ' ', 'great'] @res = @cut before, after it 'should return 1 action', -> (expect @res.length).to.equal 1 it 'should return the correct replace action', -> (expect @res[0]).eql action: 'replace' start_in_before: 0 end_in_before: 4 start_in_after: 0 end_in_after: 4 describe 'but dont absorb non-single-whitespace tokens', -> beforeEach -> before = ['I', ' ', 'am', ' ', 'awesome'] after = ['You', ' ', 'are', ' ', 'great'] @res = @cut before, after it 'should return 3 actions', -> (expect @res.length).to.equal 3 it 'should have a replace first', -> (expect @res[0].action).to.equal 'replace' it 'should have an equal second', -> (expect @res[1].action).to.equal 'equal' it 'should have a replace last', -> (expect @res[2].action).to.equal 'replace'
true
# calculates the differences into a list of edit operations describe 'calculate_operations', -> beforeEach -> @cut = (require '../src/htmldiff.coffee').calculate_operations it 'should be a function', -> (expect @cut).is.a 'function' describe 'Actions', -> describe 'In the middle', -> describe 'Replace', -> beforeEach -> before = 'working on it'.split ' ' after = 'working in it'.split ' ' @res = @cut before, after it 'should result in 3 operations', -> (expect @res.length).to.equal 3 it 'should replace "on"', -> (expect @res[1]).eql action : 'replace' start_in_before: 1 end_in_before : 1 start_in_after : 1 end_in_after : 1 describe 'Insert', -> beforeEach -> before = 'working it'.split ' ' after = 'working on it'.split ' ' @res = @cut before, after it 'should result in 3 operations', -> (expect @res.length).to.equal 3 it 'should show an insert for "on"', -> (expect @res[1]).eql action : 'insert' start_in_before: 1 end_in_before : undefined start_in_after : 1 end_in_after : 1 describe 'More than one word', -> beforeEach -> before = 'working it'.split ' ' after = 'working all up on it'.split ' ' @res = @cut before, after it 'should still have 3 operations', -> (expect @res.length).to.equal 3 it 'should show a big insert', -> (expect @res[1]).eql action : 'insert' start_in_before: 1 end_in_before : undefined start_in_after : 1 end_in_after : 3 describe 'Delete', -> beforeEach -> before = 'this is a lot of text'.split ' ' after = 'this is text'.split ' ' @res = @cut before, after it 'should return 3 operations', -> (expect @res.length).to.equal 3 it 'should show the delete in the middle', -> (expect @res[1]).eql action: 'delete' start_in_before: 2 end_in_before: 4 start_in_after: 2 end_in_after: undefined describe 'Equal', -> beforeEach -> before = 'this is what it sounds like'.split ' ' after = 'this is what it sounds like'.split ' ' @res = @cut before, after it 'should return a single op', -> (expect @res.length).to.equal 1 (expect @res[0]).eql action: 'equal' start_in_before: 0 end_in_before: 5 start_in_after: 0 end_in_after: 5 describe 'At the beginning', -> describe 'Replace', -> beforeEach -> before = 'I dont like veggies'.split ' ' after = 'PI:NAME:<NAME>END_PI loves veggies'.split ' ' @res = @cut before, after it 'should return 2 operations', -> (expect @res.length).to.equal 2 it 'should have a replace at the beginning', -> (expect @res[0]).eql action : 'replace' start_in_before: 0 end_in_before : 2 start_in_after : 0 end_in_after : 1 describe 'Insert', -> beforeEach -> before = 'dog'.split ' ' after = 'the shaggy dog'.split ' ' @res = @cut before, after it 'should return 2 operations', -> (expect @res.length).to.equal 2 it 'should have an insert at the beginning', -> (expect @res[0]).eql action : 'insert' start_in_before: 0 end_in_before : undefined start_in_after : 0 end_in_after : 1 describe 'Delete', -> beforeEach -> before = 'awesome dog barks'.split ' ' after = 'dog barks'.split ' ' @res = @cut before, after it 'should return 2 operations', -> (expect @res.length).to.equal 2 it 'should have a delete at the beginning', -> (expect @res[0]).eql action : 'delete' start_in_before: 0 end_in_before : 0 start_in_after : 0 end_in_after : undefined describe 'At the end', -> describe 'Replace', -> beforeEach -> before = 'the dog bit the cat'.split ' ' after = 'the dog bit a bird'.split ' ' @res = @cut before, after it 'should return 2 operations', -> (expect @res.length).to.equal 2 it 'should have a replace at the end', -> (expect @res[1]).eql action : 'replace' start_in_before: 3 end_in_before : 4 start_in_after : 3 end_in_after : 4 describe 'Insert', -> beforeEach -> before = 'this is a dog'.split ' ' after = 'this is a dog that barks'.split ' ' @res = @cut before, after it 'should return 2 operations', -> (expect @res.length).to.equal 2 it 'should have an Insert at the end', -> (expect @res[1]).eql action : 'insert' start_in_before: 4 end_in_before : undefined start_in_after : 4 end_in_after : 5 describe 'Delete', -> beforeEach -> before = 'this is a dog that barks'.split ' ' after = 'this is a dog'.split ' ' @res = @cut before, after it 'should have 2 operations', -> (expect @res.length).to.equal 2 it 'should have a delete at the end', -> (expect @res[1]).eql action : 'delete' start_in_before: 4 end_in_before : 5 start_in_after : 4 end_in_after : undefined describe 'Action Combination', -> describe 'Absorb single-whitespace to make contiguous replace actions', -> beforeEach -> #There are a bunch of replaces, but, because whitespace is #tokenized, they are broken up with equals. We want to combine #them into a contiguous replace operation. before = ['I', ' ', 'am', ' ', 'awesome'] after = ['You', ' ', 'are', ' ', 'great'] @res = @cut before, after it 'should return 1 action', -> (expect @res.length).to.equal 1 it 'should return the correct replace action', -> (expect @res[0]).eql action: 'replace' start_in_before: 0 end_in_before: 4 start_in_after: 0 end_in_after: 4 describe 'but dont absorb non-single-whitespace tokens', -> beforeEach -> before = ['I', ' ', 'am', ' ', 'awesome'] after = ['You', ' ', 'are', ' ', 'great'] @res = @cut before, after it 'should return 3 actions', -> (expect @res.length).to.equal 3 it 'should have a replace first', -> (expect @res[0].action).to.equal 'replace' it 'should have an equal second', -> (expect @res[1].action).to.equal 'equal' it 'should have a replace last', -> (expect @res[2].action).to.equal 'replace'
[ { "context": "###\n# Copyright 2014, 2015, 2016 Simon Lydell\n# X11 (“MIT”) Licensed. (See LICENSE.)\n###\n\ncreat", "end": 45, "score": 0.9998524785041809, "start": 33, "tag": "NAME", "value": "Simon Lydell" } ]
index.coffee
lydell/n-ary-huffman
10
### # Copyright 2014, 2015, 2016 Simon Lydell # X11 (“MIT”) Licensed. (See LICENSE.) ### createTree = (elements, numBranches, options={})-> unless numBranches >= 2 throw new RangeError("`n` must be at least 2") numElements = elements.length # Special cases. if numElements == 0 return new BranchPoint([], 0) if numElements == 1 [element] = elements return new BranchPoint([element], element.weight) unless options.sorted # Sort the elements after their weights, in descending order, so that the # first ones will be the ones with highest weight. This is done on a shallow # copy in order not to modify the original array. elements = elements[..].sort((a, b)-> b.weight - a.weight) # A `numBranches`-ary tree can be formed by `1 + (numBranches - 1) * n` # elements: There is the root of the tree (`1`), and each branch point adds # `numBranches` elements to the total number or elements, but replaces itself # (`numBranches - 1`). `n` is the number of points where the tree branches # (therefore, `n` is an integer). In order to create the tree using # `numElements` elements, we need to find the smallest `n` such that `1 + # (numBranches - 1) * n == numElements + padding`. We need to add `padding` # since `n` is an integer and there might not be an integer `n` that makes # the left-hand side equal to `numElements`. Solving for `padding` gives # `padding = 1 + (numBranches - 1) * n - numElements`. Since `padding >= 0` # (we won’t reduce the number of elements, only add extra dummy ones), it # follows that `n >= (numElements - 1) / (numBranches - 1)`. The smallest # integer `n = numBranchPoints` is then: numBranchPoints = Math.ceil((numElements - 1) / (numBranches - 1)) # The above gives the padding: numPadding = 1 + (numBranches - 1) * numBranchPoints - numElements # All the `numBranchPoints` branch points will be stored in this array instead # of splicing them into the `elements` array. This way we do not need to # search for the correct index to maintain the sort order. This array, and all # other below, are created with the correct length from the beginning for # performance. branchPoints = Array(numBranchPoints) # These indexes will be used instead of pushing, popping, shifting and # unshifting arrays for performance. latestBranchPointIndex = 0 branchPointIndex = 0 elementIndex = numElements - 1 # The first branch point is the only one that can have fewer than # `numBranches` branches. One _could_ add `numPadding` dummy elements, but # this algorithm does not. (Why would that be useful?) if numPadding > 0 numChildren = numBranches - numPadding weight = 0 children = Array(numChildren) childIndex = 0 while childIndex < numChildren element = elements[elementIndex] children[childIndex] = element weight += element.weight elementIndex-- childIndex++ branchPoints[0] = new BranchPoint(children, weight) latestBranchPointIndex = 1 # Create (the rest of) the `numBranchPoints` branch points. nextElement = if elementIndex >= 0 then elements[elementIndex] else null while latestBranchPointIndex < numBranchPoints weight = 0 children = Array(numBranches) childIndex = 0 nextBranchPoint = branchPoints[branchPointIndex] # Put the next `numBranches` smallest weights in the `children` array. while childIndex < numBranches # The smallest weight is either the next element or the next branch point. if not nextElement? or # No elements, only branch points left. (nextBranchPoint? and nextBranchPoint.weight <= nextElement.weight) lowestWeight = nextBranchPoint branchPointIndex++ nextBranchPoint = branchPoints[branchPointIndex] else lowestWeight = nextElement elementIndex-- nextElement = if elementIndex >= 0 then elements[elementIndex] else null children[childIndex] = lowestWeight weight += lowestWeight.weight childIndex++ branchPoints[latestBranchPointIndex] = new BranchPoint(children, weight) latestBranchPointIndex++ root = branchPoints[numBranchPoints - 1] root class BranchPoint constructor: (@children, @weight)-> assignCodeWords: (alphabet, callback, prefix="")-> index = 0 for node in @children by -1 codeWord = prefix + alphabet[index++] if node instanceof BranchPoint node.assignCodeWords(alphabet, callback, codeWord) else callback(node, codeWord) return module.exports = {createTree, BranchPoint}
59427
### # Copyright 2014, 2015, 2016 <NAME> # X11 (“MIT”) Licensed. (See LICENSE.) ### createTree = (elements, numBranches, options={})-> unless numBranches >= 2 throw new RangeError("`n` must be at least 2") numElements = elements.length # Special cases. if numElements == 0 return new BranchPoint([], 0) if numElements == 1 [element] = elements return new BranchPoint([element], element.weight) unless options.sorted # Sort the elements after their weights, in descending order, so that the # first ones will be the ones with highest weight. This is done on a shallow # copy in order not to modify the original array. elements = elements[..].sort((a, b)-> b.weight - a.weight) # A `numBranches`-ary tree can be formed by `1 + (numBranches - 1) * n` # elements: There is the root of the tree (`1`), and each branch point adds # `numBranches` elements to the total number or elements, but replaces itself # (`numBranches - 1`). `n` is the number of points where the tree branches # (therefore, `n` is an integer). In order to create the tree using # `numElements` elements, we need to find the smallest `n` such that `1 + # (numBranches - 1) * n == numElements + padding`. We need to add `padding` # since `n` is an integer and there might not be an integer `n` that makes # the left-hand side equal to `numElements`. Solving for `padding` gives # `padding = 1 + (numBranches - 1) * n - numElements`. Since `padding >= 0` # (we won’t reduce the number of elements, only add extra dummy ones), it # follows that `n >= (numElements - 1) / (numBranches - 1)`. The smallest # integer `n = numBranchPoints` is then: numBranchPoints = Math.ceil((numElements - 1) / (numBranches - 1)) # The above gives the padding: numPadding = 1 + (numBranches - 1) * numBranchPoints - numElements # All the `numBranchPoints` branch points will be stored in this array instead # of splicing them into the `elements` array. This way we do not need to # search for the correct index to maintain the sort order. This array, and all # other below, are created with the correct length from the beginning for # performance. branchPoints = Array(numBranchPoints) # These indexes will be used instead of pushing, popping, shifting and # unshifting arrays for performance. latestBranchPointIndex = 0 branchPointIndex = 0 elementIndex = numElements - 1 # The first branch point is the only one that can have fewer than # `numBranches` branches. One _could_ add `numPadding` dummy elements, but # this algorithm does not. (Why would that be useful?) if numPadding > 0 numChildren = numBranches - numPadding weight = 0 children = Array(numChildren) childIndex = 0 while childIndex < numChildren element = elements[elementIndex] children[childIndex] = element weight += element.weight elementIndex-- childIndex++ branchPoints[0] = new BranchPoint(children, weight) latestBranchPointIndex = 1 # Create (the rest of) the `numBranchPoints` branch points. nextElement = if elementIndex >= 0 then elements[elementIndex] else null while latestBranchPointIndex < numBranchPoints weight = 0 children = Array(numBranches) childIndex = 0 nextBranchPoint = branchPoints[branchPointIndex] # Put the next `numBranches` smallest weights in the `children` array. while childIndex < numBranches # The smallest weight is either the next element or the next branch point. if not nextElement? or # No elements, only branch points left. (nextBranchPoint? and nextBranchPoint.weight <= nextElement.weight) lowestWeight = nextBranchPoint branchPointIndex++ nextBranchPoint = branchPoints[branchPointIndex] else lowestWeight = nextElement elementIndex-- nextElement = if elementIndex >= 0 then elements[elementIndex] else null children[childIndex] = lowestWeight weight += lowestWeight.weight childIndex++ branchPoints[latestBranchPointIndex] = new BranchPoint(children, weight) latestBranchPointIndex++ root = branchPoints[numBranchPoints - 1] root class BranchPoint constructor: (@children, @weight)-> assignCodeWords: (alphabet, callback, prefix="")-> index = 0 for node in @children by -1 codeWord = prefix + alphabet[index++] if node instanceof BranchPoint node.assignCodeWords(alphabet, callback, codeWord) else callback(node, codeWord) return module.exports = {createTree, BranchPoint}
true
### # Copyright 2014, 2015, 2016 PI:NAME:<NAME>END_PI # X11 (“MIT”) Licensed. (See LICENSE.) ### createTree = (elements, numBranches, options={})-> unless numBranches >= 2 throw new RangeError("`n` must be at least 2") numElements = elements.length # Special cases. if numElements == 0 return new BranchPoint([], 0) if numElements == 1 [element] = elements return new BranchPoint([element], element.weight) unless options.sorted # Sort the elements after their weights, in descending order, so that the # first ones will be the ones with highest weight. This is done on a shallow # copy in order not to modify the original array. elements = elements[..].sort((a, b)-> b.weight - a.weight) # A `numBranches`-ary tree can be formed by `1 + (numBranches - 1) * n` # elements: There is the root of the tree (`1`), and each branch point adds # `numBranches` elements to the total number or elements, but replaces itself # (`numBranches - 1`). `n` is the number of points where the tree branches # (therefore, `n` is an integer). In order to create the tree using # `numElements` elements, we need to find the smallest `n` such that `1 + # (numBranches - 1) * n == numElements + padding`. We need to add `padding` # since `n` is an integer and there might not be an integer `n` that makes # the left-hand side equal to `numElements`. Solving for `padding` gives # `padding = 1 + (numBranches - 1) * n - numElements`. Since `padding >= 0` # (we won’t reduce the number of elements, only add extra dummy ones), it # follows that `n >= (numElements - 1) / (numBranches - 1)`. The smallest # integer `n = numBranchPoints` is then: numBranchPoints = Math.ceil((numElements - 1) / (numBranches - 1)) # The above gives the padding: numPadding = 1 + (numBranches - 1) * numBranchPoints - numElements # All the `numBranchPoints` branch points will be stored in this array instead # of splicing them into the `elements` array. This way we do not need to # search for the correct index to maintain the sort order. This array, and all # other below, are created with the correct length from the beginning for # performance. branchPoints = Array(numBranchPoints) # These indexes will be used instead of pushing, popping, shifting and # unshifting arrays for performance. latestBranchPointIndex = 0 branchPointIndex = 0 elementIndex = numElements - 1 # The first branch point is the only one that can have fewer than # `numBranches` branches. One _could_ add `numPadding` dummy elements, but # this algorithm does not. (Why would that be useful?) if numPadding > 0 numChildren = numBranches - numPadding weight = 0 children = Array(numChildren) childIndex = 0 while childIndex < numChildren element = elements[elementIndex] children[childIndex] = element weight += element.weight elementIndex-- childIndex++ branchPoints[0] = new BranchPoint(children, weight) latestBranchPointIndex = 1 # Create (the rest of) the `numBranchPoints` branch points. nextElement = if elementIndex >= 0 then elements[elementIndex] else null while latestBranchPointIndex < numBranchPoints weight = 0 children = Array(numBranches) childIndex = 0 nextBranchPoint = branchPoints[branchPointIndex] # Put the next `numBranches` smallest weights in the `children` array. while childIndex < numBranches # The smallest weight is either the next element or the next branch point. if not nextElement? or # No elements, only branch points left. (nextBranchPoint? and nextBranchPoint.weight <= nextElement.weight) lowestWeight = nextBranchPoint branchPointIndex++ nextBranchPoint = branchPoints[branchPointIndex] else lowestWeight = nextElement elementIndex-- nextElement = if elementIndex >= 0 then elements[elementIndex] else null children[childIndex] = lowestWeight weight += lowestWeight.weight childIndex++ branchPoints[latestBranchPointIndex] = new BranchPoint(children, weight) latestBranchPointIndex++ root = branchPoints[numBranchPoints - 1] root class BranchPoint constructor: (@children, @weight)-> assignCodeWords: (alphabet, callback, prefix="")-> index = 0 for node in @children by -1 codeWord = prefix + alphabet[index++] if node instanceof BranchPoint node.assignCodeWords(alphabet, callback, codeWord) else callback(node, codeWord) return module.exports = {createTree, BranchPoint}
[ { "context": " prefetch: '/api/customers.json'\n valueKey: 'display_name'\n limit: 10\n\n initTypeAhead()\n\n\n # Pickada", "end": 1683, "score": 0.9240889549255371, "start": 1671, "tag": "KEY", "value": "display_name" } ]
app/assets/javascripts/layout.js.coffee
ninech/uberze
19
# ===> Event Listeners $(document).on 'click', '.toggle', (element) -> $('#' + $(this).data('toggle-target')).toggle() $(document).on 'click', '.remote-reveal', (event) -> element = $('#' + $(this).data('reveal-id')) element.find('div.ajax-content').remove() content_element = element.append('<div class="ajax-content"></div>') content_element.find('div.ajax-content').load $(this).data('reveal-url'), => initControls() $.event.trigger("modal:#{$(this).data('reveal-id')}:form-loaded") setTimeout -> $('#time_entry_start_time').focus() , 100 $(document).on 'mouseover', '.has-tip', -> $(this).popover trigger: 'hover' content: $(this).data('tooltip') fadeSpeed: 0 $(document).on 'click', '.time-now', -> target = $('#' + $(this).siblings('label').attr('for')) target.val moment().format('HH:mm') target.trigger 'change' false # ===> Document Ready $ -> # Sortable Tables $('table.sortable').stupidtable "hhmm": (a, b) -> aArray = a.split(':') bArray = b.split(':') aMin = (+aArray[0] * 60) + (+aArray[1]) bMin = (+bArray[0] * 60) + (+bArray[1]) return aMin - bMin $(document) .foundation('reveal', { closeOnBackgroundClick: false, closeOnEsc: false }) .foundation('section') .foundation('topbar') window.initControls = () -> initTimePicker() initDatePicker() window.initTimePicker = () -> # Timepicker $('input.time').timepicker({ dropdown: false, timeFormat: 'HH:mm' }) window.initTypeAhead = () -> $('.typeahead-customer').typeahead name: 'customers' prefetch: '/api/customers.json' valueKey: 'display_name' limit: 10 initTypeAhead() # Pickadate window.initDatePicker = () -> $('input.date').pickadate formatSubmit: 'yyyy-mm-dd' picker_from_element = $('.from_to_date').find('input.from_date') picker_to_element = $('.from_to_date').find('input.to_date') picker_from = $(picker_from_element).pickadate onSet: () -> selected_from_date = moment(@get('select', 'yyyy-mm-dd')) selected_from_date_array = [selected_from_date.year(), selected_from_date.month(), selected_from_date.date()] to_date = moment(picker_to_element.data('pickadate').get('select', 'yyyy-mm-dd')) # set the min value for the to date picker_to_element.data('pickadate').set('min', selected_from_date_array) # set the selected from date as to date, if needed if to_date.isBefore(selected_from_date) and picker_to_element.val().length > 0 picker_to_element.data('pickadate').set('select', selected_from_date_array) picker_to = $(picker_to_element).pickadate onStart: () -> selected_from_date = moment(picker_from_element.pickadate().data('pickadate').get('select', 'yyyy-mm-dd')) selected_from_date_array = [selected_from_date.year(), selected_from_date.month(), selected_from_date.date()] @set 'min', selected_from_date_array # Set initial dates (to isolate Rails' locale from Pickadate locale) $("input[data-month]").each (i, date_input) -> date_input = $(date_input) pickadate = date_input.data('pickadate') if(pickadate) pickadate.set('select', date_input.data('year'),date_input.data('month'),date_input.data('day')) initControls() #$('.touch .navigation li:first-child').click (e) -> # e.stopPropagation() # $('.touch .navigation li:not(:first-child)').toggle() #$(document).click () -> # $('.touch .navigation li:not(:first-child)').hide()
116505
# ===> Event Listeners $(document).on 'click', '.toggle', (element) -> $('#' + $(this).data('toggle-target')).toggle() $(document).on 'click', '.remote-reveal', (event) -> element = $('#' + $(this).data('reveal-id')) element.find('div.ajax-content').remove() content_element = element.append('<div class="ajax-content"></div>') content_element.find('div.ajax-content').load $(this).data('reveal-url'), => initControls() $.event.trigger("modal:#{$(this).data('reveal-id')}:form-loaded") setTimeout -> $('#time_entry_start_time').focus() , 100 $(document).on 'mouseover', '.has-tip', -> $(this).popover trigger: 'hover' content: $(this).data('tooltip') fadeSpeed: 0 $(document).on 'click', '.time-now', -> target = $('#' + $(this).siblings('label').attr('for')) target.val moment().format('HH:mm') target.trigger 'change' false # ===> Document Ready $ -> # Sortable Tables $('table.sortable').stupidtable "hhmm": (a, b) -> aArray = a.split(':') bArray = b.split(':') aMin = (+aArray[0] * 60) + (+aArray[1]) bMin = (+bArray[0] * 60) + (+bArray[1]) return aMin - bMin $(document) .foundation('reveal', { closeOnBackgroundClick: false, closeOnEsc: false }) .foundation('section') .foundation('topbar') window.initControls = () -> initTimePicker() initDatePicker() window.initTimePicker = () -> # Timepicker $('input.time').timepicker({ dropdown: false, timeFormat: 'HH:mm' }) window.initTypeAhead = () -> $('.typeahead-customer').typeahead name: 'customers' prefetch: '/api/customers.json' valueKey: '<KEY>' limit: 10 initTypeAhead() # Pickadate window.initDatePicker = () -> $('input.date').pickadate formatSubmit: 'yyyy-mm-dd' picker_from_element = $('.from_to_date').find('input.from_date') picker_to_element = $('.from_to_date').find('input.to_date') picker_from = $(picker_from_element).pickadate onSet: () -> selected_from_date = moment(@get('select', 'yyyy-mm-dd')) selected_from_date_array = [selected_from_date.year(), selected_from_date.month(), selected_from_date.date()] to_date = moment(picker_to_element.data('pickadate').get('select', 'yyyy-mm-dd')) # set the min value for the to date picker_to_element.data('pickadate').set('min', selected_from_date_array) # set the selected from date as to date, if needed if to_date.isBefore(selected_from_date) and picker_to_element.val().length > 0 picker_to_element.data('pickadate').set('select', selected_from_date_array) picker_to = $(picker_to_element).pickadate onStart: () -> selected_from_date = moment(picker_from_element.pickadate().data('pickadate').get('select', 'yyyy-mm-dd')) selected_from_date_array = [selected_from_date.year(), selected_from_date.month(), selected_from_date.date()] @set 'min', selected_from_date_array # Set initial dates (to isolate Rails' locale from Pickadate locale) $("input[data-month]").each (i, date_input) -> date_input = $(date_input) pickadate = date_input.data('pickadate') if(pickadate) pickadate.set('select', date_input.data('year'),date_input.data('month'),date_input.data('day')) initControls() #$('.touch .navigation li:first-child').click (e) -> # e.stopPropagation() # $('.touch .navigation li:not(:first-child)').toggle() #$(document).click () -> # $('.touch .navigation li:not(:first-child)').hide()
true
# ===> Event Listeners $(document).on 'click', '.toggle', (element) -> $('#' + $(this).data('toggle-target')).toggle() $(document).on 'click', '.remote-reveal', (event) -> element = $('#' + $(this).data('reveal-id')) element.find('div.ajax-content').remove() content_element = element.append('<div class="ajax-content"></div>') content_element.find('div.ajax-content').load $(this).data('reveal-url'), => initControls() $.event.trigger("modal:#{$(this).data('reveal-id')}:form-loaded") setTimeout -> $('#time_entry_start_time').focus() , 100 $(document).on 'mouseover', '.has-tip', -> $(this).popover trigger: 'hover' content: $(this).data('tooltip') fadeSpeed: 0 $(document).on 'click', '.time-now', -> target = $('#' + $(this).siblings('label').attr('for')) target.val moment().format('HH:mm') target.trigger 'change' false # ===> Document Ready $ -> # Sortable Tables $('table.sortable').stupidtable "hhmm": (a, b) -> aArray = a.split(':') bArray = b.split(':') aMin = (+aArray[0] * 60) + (+aArray[1]) bMin = (+bArray[0] * 60) + (+bArray[1]) return aMin - bMin $(document) .foundation('reveal', { closeOnBackgroundClick: false, closeOnEsc: false }) .foundation('section') .foundation('topbar') window.initControls = () -> initTimePicker() initDatePicker() window.initTimePicker = () -> # Timepicker $('input.time').timepicker({ dropdown: false, timeFormat: 'HH:mm' }) window.initTypeAhead = () -> $('.typeahead-customer').typeahead name: 'customers' prefetch: '/api/customers.json' valueKey: 'PI:KEY:<KEY>END_PI' limit: 10 initTypeAhead() # Pickadate window.initDatePicker = () -> $('input.date').pickadate formatSubmit: 'yyyy-mm-dd' picker_from_element = $('.from_to_date').find('input.from_date') picker_to_element = $('.from_to_date').find('input.to_date') picker_from = $(picker_from_element).pickadate onSet: () -> selected_from_date = moment(@get('select', 'yyyy-mm-dd')) selected_from_date_array = [selected_from_date.year(), selected_from_date.month(), selected_from_date.date()] to_date = moment(picker_to_element.data('pickadate').get('select', 'yyyy-mm-dd')) # set the min value for the to date picker_to_element.data('pickadate').set('min', selected_from_date_array) # set the selected from date as to date, if needed if to_date.isBefore(selected_from_date) and picker_to_element.val().length > 0 picker_to_element.data('pickadate').set('select', selected_from_date_array) picker_to = $(picker_to_element).pickadate onStart: () -> selected_from_date = moment(picker_from_element.pickadate().data('pickadate').get('select', 'yyyy-mm-dd')) selected_from_date_array = [selected_from_date.year(), selected_from_date.month(), selected_from_date.date()] @set 'min', selected_from_date_array # Set initial dates (to isolate Rails' locale from Pickadate locale) $("input[data-month]").each (i, date_input) -> date_input = $(date_input) pickadate = date_input.data('pickadate') if(pickadate) pickadate.set('select', date_input.data('year'),date_input.data('month'),date_input.data('day')) initControls() #$('.touch .navigation li:first-child').click (e) -> # e.stopPropagation() # $('.touch .navigation li:not(:first-child)').toggle() #$(document).click () -> # $('.touch .navigation li:not(:first-child)').hide()
[ { "context": "# Copyright 2012 Joyent, Inc. All rights reserved.\n\n#/--- Helpers\nreadNe", "end": 23, "score": 0.7066099643707275, "start": 19, "tag": "NAME", "value": "yent" } ]
deps/npm/node_modules/request/node_modules/http-signature/lib/util.coffee
lxe/io.coffee
0
# Copyright 2012 Joyent, Inc. All rights reserved. #/--- Helpers readNext = (buffer, offset) -> len = ctype.ruint32(buffer, "big", offset) offset += 4 newOffset = offset + len data: buffer.slice(offset, newOffset) offset: newOffset writeInt = (writer, buffer) -> writer.writeByte 0x02 # ASN1.Integer writer.writeLength buffer.length i = 0 while i < buffer.length writer.writeByte buffer[i] i++ writer rsaToPEM = (key) -> buffer = undefined der = undefined exponent = undefined i = undefined modulus = undefined newKey = "" offset = 0 type = undefined tmp = undefined try buffer = new Buffer(key.split(" ")[1], "base64") tmp = readNext(buffer, offset) type = tmp.data.toString() offset = tmp.offset throw new Error("Invalid ssh key type: " + type) if type isnt "ssh-rsa" tmp = readNext(buffer, offset) exponent = tmp.data offset = tmp.offset tmp = readNext(buffer, offset) modulus = tmp.data catch e throw new Error("Invalid ssh key: " + key) # DER is a subset of BER der = new asn1.BerWriter() der.startSequence() der.startSequence() der.writeOID "1.2.840.113549.1.1.1" der.writeNull() der.endSequence() der.startSequence 0x03 # bit string der.writeByte 0x00 # Actual key der.startSequence() writeInt der, modulus writeInt der, exponent der.endSequence() # bit string der.endSequence() der.endSequence() tmp = der.buffer.toString("base64") i = 0 while i < tmp.length newKey += "\n" if (i % 64) is 0 newKey += tmp.charAt(i) i++ newKey += "\n" unless /\\n$/.test(newKey) "-----BEGIN PUBLIC KEY-----" + newKey + "-----END PUBLIC KEY-----\n" dsaToPEM = (key) -> buffer = undefined offset = 0 tmp = undefined der = undefined newKey = "" type = undefined p = undefined q = undefined g = undefined y = undefined try buffer = new Buffer(key.split(" ")[1], "base64") tmp = readNext(buffer, offset) type = tmp.data.toString() offset = tmp.offset # JSSTYLED throw new Error("Invalid ssh key type: " + type) unless /^ssh-ds[as].*/.test(type) tmp = readNext(buffer, offset) p = tmp.data offset = tmp.offset tmp = readNext(buffer, offset) q = tmp.data offset = tmp.offset tmp = readNext(buffer, offset) g = tmp.data offset = tmp.offset tmp = readNext(buffer, offset) y = tmp.data catch e console.log e.stack throw new Error("Invalid ssh key: " + key) # DER is a subset of BER der = new asn1.BerWriter() der.startSequence() der.startSequence() der.writeOID "1.2.840.10040.4.1" der.startSequence() writeInt der, p writeInt der, q writeInt der, g der.endSequence() der.endSequence() der.startSequence 0x03 # bit string der.writeByte 0x00 writeInt der, y der.endSequence() der.endSequence() tmp = der.buffer.toString("base64") i = 0 while i < tmp.length newKey += "\n" if (i % 64) is 0 newKey += tmp.charAt(i) i++ newKey += "\n" unless /\\n$/.test(newKey) "-----BEGIN PUBLIC KEY-----" + newKey + "-----END PUBLIC KEY-----\n" assert = require("assert-plus") crypto = require("crypto") asn1 = require("asn1") ctype = require("ctype") #/--- API module.exports = ###* Converts an OpenSSH public key (rsa only) to a PKCS#8 PEM file. The intent of this module is to interoperate with OpenSSL only, specifically the node crypto module's `verify` method. @param {String} key an OpenSSH public key. @return {String} PEM encoded form of the RSA public key. @throws {TypeError} on bad input. @throws {Error} on invalid ssh key formatted data. ### sshKeyToPEM: sshKeyToPEM = (key) -> assert.string key, "ssh_key" # JSSTYLED return rsaToPEM(key) if /^ssh-rsa.*/.test(key) # JSSTYLED return dsaToPEM(key) if /^ssh-ds[as].*/.test(key) throw new Error("Only RSA and DSA public keys are allowed")return ###* Generates an OpenSSH fingerprint from an ssh public key. @param {String} key an OpenSSH public key. @return {String} key fingerprint. @throws {TypeError} on bad input. @throws {Error} if what you passed doesn't look like an ssh public key. ### fingerprint: fingerprint = (key) -> assert.string key, "ssh_key" pieces = key.split(" ") throw new Error("invalid ssh key") if not pieces or not pieces.length or pieces.length < 2 data = new Buffer(pieces[1], "base64") hash = crypto.createHash("md5") hash.update data digest = hash.digest("hex") fp = "" i = 0 while i < digest.length fp += ":" if i and i % 2 is 0 fp += digest[i] i++ fp
189771
# Copyright 2012 Jo<NAME>, Inc. All rights reserved. #/--- Helpers readNext = (buffer, offset) -> len = ctype.ruint32(buffer, "big", offset) offset += 4 newOffset = offset + len data: buffer.slice(offset, newOffset) offset: newOffset writeInt = (writer, buffer) -> writer.writeByte 0x02 # ASN1.Integer writer.writeLength buffer.length i = 0 while i < buffer.length writer.writeByte buffer[i] i++ writer rsaToPEM = (key) -> buffer = undefined der = undefined exponent = undefined i = undefined modulus = undefined newKey = "" offset = 0 type = undefined tmp = undefined try buffer = new Buffer(key.split(" ")[1], "base64") tmp = readNext(buffer, offset) type = tmp.data.toString() offset = tmp.offset throw new Error("Invalid ssh key type: " + type) if type isnt "ssh-rsa" tmp = readNext(buffer, offset) exponent = tmp.data offset = tmp.offset tmp = readNext(buffer, offset) modulus = tmp.data catch e throw new Error("Invalid ssh key: " + key) # DER is a subset of BER der = new asn1.BerWriter() der.startSequence() der.startSequence() der.writeOID "1.2.840.113549.1.1.1" der.writeNull() der.endSequence() der.startSequence 0x03 # bit string der.writeByte 0x00 # Actual key der.startSequence() writeInt der, modulus writeInt der, exponent der.endSequence() # bit string der.endSequence() der.endSequence() tmp = der.buffer.toString("base64") i = 0 while i < tmp.length newKey += "\n" if (i % 64) is 0 newKey += tmp.charAt(i) i++ newKey += "\n" unless /\\n$/.test(newKey) "-----BEGIN PUBLIC KEY-----" + newKey + "-----END PUBLIC KEY-----\n" dsaToPEM = (key) -> buffer = undefined offset = 0 tmp = undefined der = undefined newKey = "" type = undefined p = undefined q = undefined g = undefined y = undefined try buffer = new Buffer(key.split(" ")[1], "base64") tmp = readNext(buffer, offset) type = tmp.data.toString() offset = tmp.offset # JSSTYLED throw new Error("Invalid ssh key type: " + type) unless /^ssh-ds[as].*/.test(type) tmp = readNext(buffer, offset) p = tmp.data offset = tmp.offset tmp = readNext(buffer, offset) q = tmp.data offset = tmp.offset tmp = readNext(buffer, offset) g = tmp.data offset = tmp.offset tmp = readNext(buffer, offset) y = tmp.data catch e console.log e.stack throw new Error("Invalid ssh key: " + key) # DER is a subset of BER der = new asn1.BerWriter() der.startSequence() der.startSequence() der.writeOID "1.2.840.10040.4.1" der.startSequence() writeInt der, p writeInt der, q writeInt der, g der.endSequence() der.endSequence() der.startSequence 0x03 # bit string der.writeByte 0x00 writeInt der, y der.endSequence() der.endSequence() tmp = der.buffer.toString("base64") i = 0 while i < tmp.length newKey += "\n" if (i % 64) is 0 newKey += tmp.charAt(i) i++ newKey += "\n" unless /\\n$/.test(newKey) "-----BEGIN PUBLIC KEY-----" + newKey + "-----END PUBLIC KEY-----\n" assert = require("assert-plus") crypto = require("crypto") asn1 = require("asn1") ctype = require("ctype") #/--- API module.exports = ###* Converts an OpenSSH public key (rsa only) to a PKCS#8 PEM file. The intent of this module is to interoperate with OpenSSL only, specifically the node crypto module's `verify` method. @param {String} key an OpenSSH public key. @return {String} PEM encoded form of the RSA public key. @throws {TypeError} on bad input. @throws {Error} on invalid ssh key formatted data. ### sshKeyToPEM: sshKeyToPEM = (key) -> assert.string key, "ssh_key" # JSSTYLED return rsaToPEM(key) if /^ssh-rsa.*/.test(key) # JSSTYLED return dsaToPEM(key) if /^ssh-ds[as].*/.test(key) throw new Error("Only RSA and DSA public keys are allowed")return ###* Generates an OpenSSH fingerprint from an ssh public key. @param {String} key an OpenSSH public key. @return {String} key fingerprint. @throws {TypeError} on bad input. @throws {Error} if what you passed doesn't look like an ssh public key. ### fingerprint: fingerprint = (key) -> assert.string key, "ssh_key" pieces = key.split(" ") throw new Error("invalid ssh key") if not pieces or not pieces.length or pieces.length < 2 data = new Buffer(pieces[1], "base64") hash = crypto.createHash("md5") hash.update data digest = hash.digest("hex") fp = "" i = 0 while i < digest.length fp += ":" if i and i % 2 is 0 fp += digest[i] i++ fp
true
# Copyright 2012 JoPI:NAME:<NAME>END_PI, Inc. All rights reserved. #/--- Helpers readNext = (buffer, offset) -> len = ctype.ruint32(buffer, "big", offset) offset += 4 newOffset = offset + len data: buffer.slice(offset, newOffset) offset: newOffset writeInt = (writer, buffer) -> writer.writeByte 0x02 # ASN1.Integer writer.writeLength buffer.length i = 0 while i < buffer.length writer.writeByte buffer[i] i++ writer rsaToPEM = (key) -> buffer = undefined der = undefined exponent = undefined i = undefined modulus = undefined newKey = "" offset = 0 type = undefined tmp = undefined try buffer = new Buffer(key.split(" ")[1], "base64") tmp = readNext(buffer, offset) type = tmp.data.toString() offset = tmp.offset throw new Error("Invalid ssh key type: " + type) if type isnt "ssh-rsa" tmp = readNext(buffer, offset) exponent = tmp.data offset = tmp.offset tmp = readNext(buffer, offset) modulus = tmp.data catch e throw new Error("Invalid ssh key: " + key) # DER is a subset of BER der = new asn1.BerWriter() der.startSequence() der.startSequence() der.writeOID "1.2.840.113549.1.1.1" der.writeNull() der.endSequence() der.startSequence 0x03 # bit string der.writeByte 0x00 # Actual key der.startSequence() writeInt der, modulus writeInt der, exponent der.endSequence() # bit string der.endSequence() der.endSequence() tmp = der.buffer.toString("base64") i = 0 while i < tmp.length newKey += "\n" if (i % 64) is 0 newKey += tmp.charAt(i) i++ newKey += "\n" unless /\\n$/.test(newKey) "-----BEGIN PUBLIC KEY-----" + newKey + "-----END PUBLIC KEY-----\n" dsaToPEM = (key) -> buffer = undefined offset = 0 tmp = undefined der = undefined newKey = "" type = undefined p = undefined q = undefined g = undefined y = undefined try buffer = new Buffer(key.split(" ")[1], "base64") tmp = readNext(buffer, offset) type = tmp.data.toString() offset = tmp.offset # JSSTYLED throw new Error("Invalid ssh key type: " + type) unless /^ssh-ds[as].*/.test(type) tmp = readNext(buffer, offset) p = tmp.data offset = tmp.offset tmp = readNext(buffer, offset) q = tmp.data offset = tmp.offset tmp = readNext(buffer, offset) g = tmp.data offset = tmp.offset tmp = readNext(buffer, offset) y = tmp.data catch e console.log e.stack throw new Error("Invalid ssh key: " + key) # DER is a subset of BER der = new asn1.BerWriter() der.startSequence() der.startSequence() der.writeOID "1.2.840.10040.4.1" der.startSequence() writeInt der, p writeInt der, q writeInt der, g der.endSequence() der.endSequence() der.startSequence 0x03 # bit string der.writeByte 0x00 writeInt der, y der.endSequence() der.endSequence() tmp = der.buffer.toString("base64") i = 0 while i < tmp.length newKey += "\n" if (i % 64) is 0 newKey += tmp.charAt(i) i++ newKey += "\n" unless /\\n$/.test(newKey) "-----BEGIN PUBLIC KEY-----" + newKey + "-----END PUBLIC KEY-----\n" assert = require("assert-plus") crypto = require("crypto") asn1 = require("asn1") ctype = require("ctype") #/--- API module.exports = ###* Converts an OpenSSH public key (rsa only) to a PKCS#8 PEM file. The intent of this module is to interoperate with OpenSSL only, specifically the node crypto module's `verify` method. @param {String} key an OpenSSH public key. @return {String} PEM encoded form of the RSA public key. @throws {TypeError} on bad input. @throws {Error} on invalid ssh key formatted data. ### sshKeyToPEM: sshKeyToPEM = (key) -> assert.string key, "ssh_key" # JSSTYLED return rsaToPEM(key) if /^ssh-rsa.*/.test(key) # JSSTYLED return dsaToPEM(key) if /^ssh-ds[as].*/.test(key) throw new Error("Only RSA and DSA public keys are allowed")return ###* Generates an OpenSSH fingerprint from an ssh public key. @param {String} key an OpenSSH public key. @return {String} key fingerprint. @throws {TypeError} on bad input. @throws {Error} if what you passed doesn't look like an ssh public key. ### fingerprint: fingerprint = (key) -> assert.string key, "ssh_key" pieces = key.split(" ") throw new Error("invalid ssh key") if not pieces or not pieces.length or pieces.length < 2 data = new Buffer(pieces[1], "base64") hash = crypto.createHash("md5") hash.update data digest = hash.digest("hex") fp = "" i = 0 while i < digest.length fp += ":" if i and i % 2 is 0 fp += digest[i] i++ fp
[ { "context": "ng test on filetype.\n # https://github.com/hedefalk/atom-vue/issues/5\n stylus:\n if", "end": 6131, "score": 0.9993734359741211, "start": 6126, "tag": "USERNAME", "value": "hedef" }, { "context": "\n new webpack.BannerPlugin \"📝 Made for Unity3...
webpack.coffee
thelucre/weather
0
### This file exports the webpack configuration object. It is designed to be imported into the app's webpack.config.coffee where it can be hacked if changes are needed. ### # Inspect how webpack is being run minify = '-p' in process.argv # Compiling for production hmr = '--hot' in process.argv # "Hot module replacement" / using webpack-dev-server # Get the port number after the `--port` flag, if it exists, to serve HMR assets port = 8080 # webpack dev server default port = process.argv[process.argv.indexOf('--port')+1] if '--port' in process.argv # Dependencies _ = require 'lodash' webpack = require 'webpack' autoprefixer = require 'autoprefixer' moment = require 'moment' ExtractText = require 'extract-text-webpack-plugin' Notify = require 'webpack-notifier' HtmlWebpackPlugin = require 'html-webpack-plugin' AssetsPlugin = require 'assets-webpack-plugin' DashboardPlugin = require 'webpack-dashboard/plugin' # Read .env file require('dotenv').config() # ############################################################################## # Setup - General config # ############################################################################## config = # Generate source maps. If using HMR, the sourcemap can be cheaper (less # CPU required) and should be inline. Othwerise, generate external, full # sourcemaps. devtool: if hmr then 'inline-cheap-module-eval-source-map' else 'source-map' # Set the dir to look for entry files context: "#{process.cwd()}/assets" # Build one bundle for public site and one for admin. If additional front end # entry points are added, consider using CommonsChunkPlugin to move shared # dependencies out. entry: app: './boot.coffee' # Save the entry points to the public/dist directory. And give any chunks # hashed names when minifying so they can be long term cashed. The entry # JS doesn't need this as it gets unique URLs via PHP. output: path: "#{process.cwd()}/dist" publicPath: if hmr then 'http://localhost:'+port+'/dist/' else '/dist/' filename: '[name].js' chunkFilename: '[id].js' # Setup properties that are set later (With less indentation) module: {} # Configure what shows up in the terminal output stats: children: false # Hides the "extract-text-webpack-plugin" messages assets: true colors: true version: false hash: false timings: true chunks: false chunkModules: false # ############################################################################## # Resolve - Where to find files # ############################################################################## config.resolve = # Look for modules in the vendor directory as well as npm's directory. The # vendor directory is used for third party modules that are committed to the # repo, like things that can't be installed via npm. For example, Modernizr. modules: [config.context, 'node_modules'] # Add coffee to the list of optional extensions extensions: ['.js', '.coffee', '.vue', '.styl'] # Aliases for common libraries alias: velocity: 'velocity-animate' underscore: 'lodash' vue: 'vue/dist/vue' # ############################################################################## # Loaders - File transmogrifying # ############################################################################## config.module.loaders = [ # Coffeescript # { test: /\.coffee$/, loader: 'coffee-loader' } # Jade # # Jade-loader reutrns a function. Apply-loader executes the function so we # get a string back. { test: /\.jade$/, loader: 'apply-loader!jade-loader' } # Haml # { test: /\.haml$/, loader: 'haml-loader' } # HTML # { test: /\.html$/, loader: 'html-loader' } # Fonts # # Not using the url-loader because serving multiple formats of a font would # mean inlining multiple formats that are unncessary for a given user. { test: /\.(eot|ttf|woff|woff2)$/ loader: 'file-loader?name=fonts/[hash:8].[ext]' } # JSON # { test: /\.json$/, loader: 'json-loader' } # CSS # { test: /\.css$/ loader: if hmr then 'style-loader!css-loader?-autoprefixer' else ExtractText.extract 'css-loader?-autoprefixer' } # Stylus # # This also uses the ExtractText to generate a new CSS file, rather # than writing script tags to the DOM. This was required to get the CSS # sourcemaps exporting dependably. Note the "postcss" loader, that is # adding autoprefixer in. { test: /\.styl$/ loader: if hmr then [ 'style-loader' 'css-loader?sourceMap&-autoprefixer' 'postcss-loader' 'stylus-loader?sourceMap' 'prepend-string-loader?string[]=@require "~definitions.styl";' ].join('!') else ExtractText.extract use: [ 'css-loader?sourceMap' 'postcss-loader' 'stylus-loader?sourceMap' 'prepend-string-loader?string[]=@require "~definitions.styl";' ] } # Sass # # Including sass for Decoy support { test: /\.scss$/ loader: if hmr then [ 'style-loader' 'css-loader?sourceMap&-autoprefixer' 'postcss-loader' 'sass-loader?sourceMap' 'import-glob-loader' ].join('!') else ExtractText.extract use: [ 'css-loader?sourceMap' 'postcss-loader' 'sass-loader?sourceMap' 'import-glob-loader' ] } # jQuery plugins # # Make sure jQuery is loaded before Velocity { test: /(velocity)\.js$/, loader: 'imports-loader?$=jquery' } # Vue # { test: /\.vue$/ loader: 'vue-loader' options: loaders: # Support the css precompilers being explicitly defined. This should be # identical to the webpack loaders EXCEPT with postcss removed, because # the Vue loader is doing that automatically. Also, the prepending needs # to be explicity done here because there is no matching test on filetype. # https://github.com/hedefalk/atom-vue/issues/5 stylus: if hmr then [ 'style-loader' 'css-loader?sourceMap&-autoprefixer' 'stylus-loader?sourceMap' 'prepend-string-loader?string[]=@require "~definitions.styl";' ].join('!') else ExtractText.extract use: [ 'css-loader?sourceMap&-autoprefixer' 'stylus-loader?sourceMap' 'prepend-string-loader?string[]=@require "~definitions.styl";' ] } ] # ############################################################################ # Plugins - Register extra functionality # ############################################################################ config.plugins = [ # Required config for ExtractText to tell it what to name css files. Setting # "allChunks" so that CSS referenced in chunked code splits still show up # in here. Otherwise, we would need webpack to DOM insert the styles on # which doesn't play nice with sourcemaps. new ExtractText filename: (if minify then '[name].[hash:8].css' else '[name].css') allChunks: true # Show growl style notifications if not running via HMR. Wit HMR, page updates # automatically, so don't need to watch for compile be done. new Notify alwaysNotify: !hmr # Add add a lil note to the js build new webpack.BannerPlugin "📝 Made for Unity3D by Eric Howard 💾 #{moment().format('M.D.YY')} 👍" # Empty the build directory whenever webpack starts up, but doesn't run on # watch updates. Has the added benefit of clearing out the dist directory # when running the dev server. # new Clean ['public/dist'], { root: process.cwd() } # Output JSON config if the compiled files which is parsed by Laravel to # create script and link tags. new AssetsPlugin filename: 'manifest.json' path: config.output.path prettyPrint: true # Provide common utils to all modules so they don't need to be expliclity # required. new webpack.ProvidePlugin $: 'jquery' jquery: 'jquery' _: 'lodash' Modernizr: 'modernizr' Velocity: 'velocity' # Inject the asset build sources into static pages new HtmlWebpackPlugin template: 'index.ejs' filename: '../index.html' # Make a nice webpack console while developing new DashboardPlugin new webpack.DefinePlugin OPENWEATHER_KEY: JSON.stringify(process.env.OPENWEATHER_KEY || "{{YOUR_OPENWEATHER_KEY}}") ] # Minify only (`webpack -p`) plugins. if minify then config.plugins = config.plugins.concat [ # Turn off warnings during minifcation. They aren't particularly helpfull. new webpack.optimize.UglifyJsPlugin compress: warnings: false # Make small ids new webpack.optimize.OccurenceOrderPlugin() # Try and remove duplicate modules new webpack.optimize.DedupePlugin() ] # ############################################################################## # Export # ############################################################################## module.exports = config
190612
### This file exports the webpack configuration object. It is designed to be imported into the app's webpack.config.coffee where it can be hacked if changes are needed. ### # Inspect how webpack is being run minify = '-p' in process.argv # Compiling for production hmr = '--hot' in process.argv # "Hot module replacement" / using webpack-dev-server # Get the port number after the `--port` flag, if it exists, to serve HMR assets port = 8080 # webpack dev server default port = process.argv[process.argv.indexOf('--port')+1] if '--port' in process.argv # Dependencies _ = require 'lodash' webpack = require 'webpack' autoprefixer = require 'autoprefixer' moment = require 'moment' ExtractText = require 'extract-text-webpack-plugin' Notify = require 'webpack-notifier' HtmlWebpackPlugin = require 'html-webpack-plugin' AssetsPlugin = require 'assets-webpack-plugin' DashboardPlugin = require 'webpack-dashboard/plugin' # Read .env file require('dotenv').config() # ############################################################################## # Setup - General config # ############################################################################## config = # Generate source maps. If using HMR, the sourcemap can be cheaper (less # CPU required) and should be inline. Othwerise, generate external, full # sourcemaps. devtool: if hmr then 'inline-cheap-module-eval-source-map' else 'source-map' # Set the dir to look for entry files context: "#{process.cwd()}/assets" # Build one bundle for public site and one for admin. If additional front end # entry points are added, consider using CommonsChunkPlugin to move shared # dependencies out. entry: app: './boot.coffee' # Save the entry points to the public/dist directory. And give any chunks # hashed names when minifying so they can be long term cashed. The entry # JS doesn't need this as it gets unique URLs via PHP. output: path: "#{process.cwd()}/dist" publicPath: if hmr then 'http://localhost:'+port+'/dist/' else '/dist/' filename: '[name].js' chunkFilename: '[id].js' # Setup properties that are set later (With less indentation) module: {} # Configure what shows up in the terminal output stats: children: false # Hides the "extract-text-webpack-plugin" messages assets: true colors: true version: false hash: false timings: true chunks: false chunkModules: false # ############################################################################## # Resolve - Where to find files # ############################################################################## config.resolve = # Look for modules in the vendor directory as well as npm's directory. The # vendor directory is used for third party modules that are committed to the # repo, like things that can't be installed via npm. For example, Modernizr. modules: [config.context, 'node_modules'] # Add coffee to the list of optional extensions extensions: ['.js', '.coffee', '.vue', '.styl'] # Aliases for common libraries alias: velocity: 'velocity-animate' underscore: 'lodash' vue: 'vue/dist/vue' # ############################################################################## # Loaders - File transmogrifying # ############################################################################## config.module.loaders = [ # Coffeescript # { test: /\.coffee$/, loader: 'coffee-loader' } # Jade # # Jade-loader reutrns a function. Apply-loader executes the function so we # get a string back. { test: /\.jade$/, loader: 'apply-loader!jade-loader' } # Haml # { test: /\.haml$/, loader: 'haml-loader' } # HTML # { test: /\.html$/, loader: 'html-loader' } # Fonts # # Not using the url-loader because serving multiple formats of a font would # mean inlining multiple formats that are unncessary for a given user. { test: /\.(eot|ttf|woff|woff2)$/ loader: 'file-loader?name=fonts/[hash:8].[ext]' } # JSON # { test: /\.json$/, loader: 'json-loader' } # CSS # { test: /\.css$/ loader: if hmr then 'style-loader!css-loader?-autoprefixer' else ExtractText.extract 'css-loader?-autoprefixer' } # Stylus # # This also uses the ExtractText to generate a new CSS file, rather # than writing script tags to the DOM. This was required to get the CSS # sourcemaps exporting dependably. Note the "postcss" loader, that is # adding autoprefixer in. { test: /\.styl$/ loader: if hmr then [ 'style-loader' 'css-loader?sourceMap&-autoprefixer' 'postcss-loader' 'stylus-loader?sourceMap' 'prepend-string-loader?string[]=@require "~definitions.styl";' ].join('!') else ExtractText.extract use: [ 'css-loader?sourceMap' 'postcss-loader' 'stylus-loader?sourceMap' 'prepend-string-loader?string[]=@require "~definitions.styl";' ] } # Sass # # Including sass for Decoy support { test: /\.scss$/ loader: if hmr then [ 'style-loader' 'css-loader?sourceMap&-autoprefixer' 'postcss-loader' 'sass-loader?sourceMap' 'import-glob-loader' ].join('!') else ExtractText.extract use: [ 'css-loader?sourceMap' 'postcss-loader' 'sass-loader?sourceMap' 'import-glob-loader' ] } # jQuery plugins # # Make sure jQuery is loaded before Velocity { test: /(velocity)\.js$/, loader: 'imports-loader?$=jquery' } # Vue # { test: /\.vue$/ loader: 'vue-loader' options: loaders: # Support the css precompilers being explicitly defined. This should be # identical to the webpack loaders EXCEPT with postcss removed, because # the Vue loader is doing that automatically. Also, the prepending needs # to be explicity done here because there is no matching test on filetype. # https://github.com/hedefalk/atom-vue/issues/5 stylus: if hmr then [ 'style-loader' 'css-loader?sourceMap&-autoprefixer' 'stylus-loader?sourceMap' 'prepend-string-loader?string[]=@require "~definitions.styl";' ].join('!') else ExtractText.extract use: [ 'css-loader?sourceMap&-autoprefixer' 'stylus-loader?sourceMap' 'prepend-string-loader?string[]=@require "~definitions.styl";' ] } ] # ############################################################################ # Plugins - Register extra functionality # ############################################################################ config.plugins = [ # Required config for ExtractText to tell it what to name css files. Setting # "allChunks" so that CSS referenced in chunked code splits still show up # in here. Otherwise, we would need webpack to DOM insert the styles on # which doesn't play nice with sourcemaps. new ExtractText filename: (if minify then '[name].[hash:8].css' else '[name].css') allChunks: true # Show growl style notifications if not running via HMR. Wit HMR, page updates # automatically, so don't need to watch for compile be done. new Notify alwaysNotify: !hmr # Add add a lil note to the js build new webpack.BannerPlugin "📝 Made for Unity3D by <NAME> 💾 #{moment().format('M.D.YY')} 👍" # Empty the build directory whenever webpack starts up, but doesn't run on # watch updates. Has the added benefit of clearing out the dist directory # when running the dev server. # new Clean ['public/dist'], { root: process.cwd() } # Output JSON config if the compiled files which is parsed by Laravel to # create script and link tags. new AssetsPlugin filename: 'manifest.json' path: config.output.path prettyPrint: true # Provide common utils to all modules so they don't need to be expliclity # required. new webpack.ProvidePlugin $: 'jquery' jquery: 'jquery' _: 'lodash' Modernizr: 'modernizr' Velocity: 'velocity' # Inject the asset build sources into static pages new HtmlWebpackPlugin template: 'index.ejs' filename: '../index.html' # Make a nice webpack console while developing new DashboardPlugin new webpack.DefinePlugin OPENWEATHER_KEY: JSON.stringify(process.env.OPENWEATHER_KEY || "{{YOUR_OPENWEATHER_KEY}}") ] # Minify only (`webpack -p`) plugins. if minify then config.plugins = config.plugins.concat [ # Turn off warnings during minifcation. They aren't particularly helpfull. new webpack.optimize.UglifyJsPlugin compress: warnings: false # Make small ids new webpack.optimize.OccurenceOrderPlugin() # Try and remove duplicate modules new webpack.optimize.DedupePlugin() ] # ############################################################################## # Export # ############################################################################## module.exports = config
true
### This file exports the webpack configuration object. It is designed to be imported into the app's webpack.config.coffee where it can be hacked if changes are needed. ### # Inspect how webpack is being run minify = '-p' in process.argv # Compiling for production hmr = '--hot' in process.argv # "Hot module replacement" / using webpack-dev-server # Get the port number after the `--port` flag, if it exists, to serve HMR assets port = 8080 # webpack dev server default port = process.argv[process.argv.indexOf('--port')+1] if '--port' in process.argv # Dependencies _ = require 'lodash' webpack = require 'webpack' autoprefixer = require 'autoprefixer' moment = require 'moment' ExtractText = require 'extract-text-webpack-plugin' Notify = require 'webpack-notifier' HtmlWebpackPlugin = require 'html-webpack-plugin' AssetsPlugin = require 'assets-webpack-plugin' DashboardPlugin = require 'webpack-dashboard/plugin' # Read .env file require('dotenv').config() # ############################################################################## # Setup - General config # ############################################################################## config = # Generate source maps. If using HMR, the sourcemap can be cheaper (less # CPU required) and should be inline. Othwerise, generate external, full # sourcemaps. devtool: if hmr then 'inline-cheap-module-eval-source-map' else 'source-map' # Set the dir to look for entry files context: "#{process.cwd()}/assets" # Build one bundle for public site and one for admin. If additional front end # entry points are added, consider using CommonsChunkPlugin to move shared # dependencies out. entry: app: './boot.coffee' # Save the entry points to the public/dist directory. And give any chunks # hashed names when minifying so they can be long term cashed. The entry # JS doesn't need this as it gets unique URLs via PHP. output: path: "#{process.cwd()}/dist" publicPath: if hmr then 'http://localhost:'+port+'/dist/' else '/dist/' filename: '[name].js' chunkFilename: '[id].js' # Setup properties that are set later (With less indentation) module: {} # Configure what shows up in the terminal output stats: children: false # Hides the "extract-text-webpack-plugin" messages assets: true colors: true version: false hash: false timings: true chunks: false chunkModules: false # ############################################################################## # Resolve - Where to find files # ############################################################################## config.resolve = # Look for modules in the vendor directory as well as npm's directory. The # vendor directory is used for third party modules that are committed to the # repo, like things that can't be installed via npm. For example, Modernizr. modules: [config.context, 'node_modules'] # Add coffee to the list of optional extensions extensions: ['.js', '.coffee', '.vue', '.styl'] # Aliases for common libraries alias: velocity: 'velocity-animate' underscore: 'lodash' vue: 'vue/dist/vue' # ############################################################################## # Loaders - File transmogrifying # ############################################################################## config.module.loaders = [ # Coffeescript # { test: /\.coffee$/, loader: 'coffee-loader' } # Jade # # Jade-loader reutrns a function. Apply-loader executes the function so we # get a string back. { test: /\.jade$/, loader: 'apply-loader!jade-loader' } # Haml # { test: /\.haml$/, loader: 'haml-loader' } # HTML # { test: /\.html$/, loader: 'html-loader' } # Fonts # # Not using the url-loader because serving multiple formats of a font would # mean inlining multiple formats that are unncessary for a given user. { test: /\.(eot|ttf|woff|woff2)$/ loader: 'file-loader?name=fonts/[hash:8].[ext]' } # JSON # { test: /\.json$/, loader: 'json-loader' } # CSS # { test: /\.css$/ loader: if hmr then 'style-loader!css-loader?-autoprefixer' else ExtractText.extract 'css-loader?-autoprefixer' } # Stylus # # This also uses the ExtractText to generate a new CSS file, rather # than writing script tags to the DOM. This was required to get the CSS # sourcemaps exporting dependably. Note the "postcss" loader, that is # adding autoprefixer in. { test: /\.styl$/ loader: if hmr then [ 'style-loader' 'css-loader?sourceMap&-autoprefixer' 'postcss-loader' 'stylus-loader?sourceMap' 'prepend-string-loader?string[]=@require "~definitions.styl";' ].join('!') else ExtractText.extract use: [ 'css-loader?sourceMap' 'postcss-loader' 'stylus-loader?sourceMap' 'prepend-string-loader?string[]=@require "~definitions.styl";' ] } # Sass # # Including sass for Decoy support { test: /\.scss$/ loader: if hmr then [ 'style-loader' 'css-loader?sourceMap&-autoprefixer' 'postcss-loader' 'sass-loader?sourceMap' 'import-glob-loader' ].join('!') else ExtractText.extract use: [ 'css-loader?sourceMap' 'postcss-loader' 'sass-loader?sourceMap' 'import-glob-loader' ] } # jQuery plugins # # Make sure jQuery is loaded before Velocity { test: /(velocity)\.js$/, loader: 'imports-loader?$=jquery' } # Vue # { test: /\.vue$/ loader: 'vue-loader' options: loaders: # Support the css precompilers being explicitly defined. This should be # identical to the webpack loaders EXCEPT with postcss removed, because # the Vue loader is doing that automatically. Also, the prepending needs # to be explicity done here because there is no matching test on filetype. # https://github.com/hedefalk/atom-vue/issues/5 stylus: if hmr then [ 'style-loader' 'css-loader?sourceMap&-autoprefixer' 'stylus-loader?sourceMap' 'prepend-string-loader?string[]=@require "~definitions.styl";' ].join('!') else ExtractText.extract use: [ 'css-loader?sourceMap&-autoprefixer' 'stylus-loader?sourceMap' 'prepend-string-loader?string[]=@require "~definitions.styl";' ] } ] # ############################################################################ # Plugins - Register extra functionality # ############################################################################ config.plugins = [ # Required config for ExtractText to tell it what to name css files. Setting # "allChunks" so that CSS referenced in chunked code splits still show up # in here. Otherwise, we would need webpack to DOM insert the styles on # which doesn't play nice with sourcemaps. new ExtractText filename: (if minify then '[name].[hash:8].css' else '[name].css') allChunks: true # Show growl style notifications if not running via HMR. Wit HMR, page updates # automatically, so don't need to watch for compile be done. new Notify alwaysNotify: !hmr # Add add a lil note to the js build new webpack.BannerPlugin "📝 Made for Unity3D by PI:NAME:<NAME>END_PI 💾 #{moment().format('M.D.YY')} 👍" # Empty the build directory whenever webpack starts up, but doesn't run on # watch updates. Has the added benefit of clearing out the dist directory # when running the dev server. # new Clean ['public/dist'], { root: process.cwd() } # Output JSON config if the compiled files which is parsed by Laravel to # create script and link tags. new AssetsPlugin filename: 'manifest.json' path: config.output.path prettyPrint: true # Provide common utils to all modules so they don't need to be expliclity # required. new webpack.ProvidePlugin $: 'jquery' jquery: 'jquery' _: 'lodash' Modernizr: 'modernizr' Velocity: 'velocity' # Inject the asset build sources into static pages new HtmlWebpackPlugin template: 'index.ejs' filename: '../index.html' # Make a nice webpack console while developing new DashboardPlugin new webpack.DefinePlugin OPENWEATHER_KEY: JSON.stringify(process.env.OPENWEATHER_KEY || "{{YOUR_OPENWEATHER_KEY}}") ] # Minify only (`webpack -p`) plugins. if minify then config.plugins = config.plugins.concat [ # Turn off warnings during minifcation. They aren't particularly helpfull. new webpack.optimize.UglifyJsPlugin compress: warnings: false # Make small ids new webpack.optimize.OccurenceOrderPlugin() # Try and remove duplicate modules new webpack.optimize.DedupePlugin() ] # ############################################################################## # Export # ############################################################################## module.exports = config
[ { "context": "\n\n model = memberRepo.save(firstName: 'Shin')\n assert model.mCreatedAt?\n ", "end": 787, "score": 0.999694287776947, "start": 783, "tag": "NAME", "value": "Shin" }, { "context": "\n\n model = memberRepo.save(firstName: 'Shin'...
spec/lib/base-repository.coffee
CureApp/base-domain
37
facade = require('../create-facade').create('domain') Hobby = facade.getModel 'hobby' describe 'BaseRepository', -> describe 'factory', -> it 'is created by the model name', -> repo = facade.createRepository('hobby') HobbyFactory = facade.require('hobby-factory') assert repo.factory instanceof HobbyFactory describe 'save', -> repo = facade.createRepository('hobby') it 'returns instance of Model', -> repo.save(name: 'music').then (model) => assert model instanceof Hobby it 'returns instance of Model with createdAt, updatedAt when configured as such', -> memberRepo = facade.createRepository('member') model = memberRepo.save(firstName: 'Shin') assert model.mCreatedAt? assert model.mUpdatedAt? assert new Date(model.mCreatedAt) instanceof Date assert new Date(model.mUpdatedAt) instanceof Date it 'createdAt stays original', -> memberRepo = facade.createRepository('member') now = new Date() model = memberRepo.save(firstName: 'Shin', mCreatedAt: now) assert model.mCreatedAt? assert.deepEqual model.mCreatedAt, now it 'createdAt is newly set even when model has id', -> memberRepo = facade.createRepository('member') now = new Date() model = memberRepo.save(firstName: 'Shin', id: 'shin') assert model.mCreatedAt? assert new Date(model.mCreatedAt) instanceof Date assert new Date(model.mUpdatedAt) instanceof Date it 'updatedAt changes for each saving', -> memberRepo = facade.createRepository('member') now = new Date() model = memberRepo.save(firstName: 'Shin', mUpdatedAt: now) assert model.mCreatedAt? assert model.mUpdatedAt isnt now it 'returns instance of Model with relation ids', -> memberFactory = facade.createFactory('member') member = memberFactory.createFromObject id: '12' firstName: 'Shin' age: 29 registeredAt: new Date() hobbies: [ { id: 1, name: 'keyboard' } { id: 2, name: 'ingress' } { id: 3, name: 'Shogi' } ] dFactory = facade.createFactory('diary') diary = dFactory.createFromObject title : 'crazy about room335' comment: 'progression of room335 is wonderful' author: member date : new Date() dRepo = facade.createRepository('diary') dRepo.save(diary).then (model) => assert model.memberId is '12' describe 'get', -> repo = facade.createRepository('hobby') it 'returns instance of Model', -> repo.get(1).then (model) => assert model instanceof Hobby describe 'query', -> repo = facade.createRepository('hobby') it 'returns array of models', -> repo.query().then (models) => assert models instanceof Array assert models[0] instanceof Hobby describe 'singleQuery', -> repo = facade.createRepository('hobby') it 'returns instance of Model', -> repo.singleQuery().then (model) => assert model instanceof Hobby describe 'delete', -> repo = facade.createRepository('hobby') it 'returns boolean', -> repo.delete(id: '123').then (isDeleted) => assert isDeleted describe 'update', -> repo = facade.createRepository('hobby') memberRepo = facade.createRepository('member') before -> memberRepo.save(id: '123', firstName: 'shin') repo.save(id: '123', name: 'tennis').then (entity) => @tennis = entity it 'returns instance of Model', -> repo.update('123', name: 'tennis').then (model) => assert model instanceof Hobby it 'returns instance of Model with updatedAt when configured as such', -> model = memberRepo.update('123', firstName: 'Shin') assert new Date(model.mUpdatedAt) instanceof Date describe 'updateProps', -> repo = facade.createRepository('hobby') before -> repo.save(id: 'xyz', name: 'tennis').then (entity) => @tennis = entity it 'returns diff props', -> repo.updateProps(@tennis, { name: 'xxx' }).then (results) => assert.deepEqual results, {} describe 'getDiff', -> repo = facade.createRepository('hobby') before -> repo.save(id: 'primitive-tech', name: 'primitive technology').then (@tech) => it 'returns diff props', -> @tech.name = 'abcde' repo.getDiff(@tech).then (results) => assert.deepEqual results, {name: 'primitive technology'}
69442
facade = require('../create-facade').create('domain') Hobby = facade.getModel 'hobby' describe 'BaseRepository', -> describe 'factory', -> it 'is created by the model name', -> repo = facade.createRepository('hobby') HobbyFactory = facade.require('hobby-factory') assert repo.factory instanceof HobbyFactory describe 'save', -> repo = facade.createRepository('hobby') it 'returns instance of Model', -> repo.save(name: 'music').then (model) => assert model instanceof Hobby it 'returns instance of Model with createdAt, updatedAt when configured as such', -> memberRepo = facade.createRepository('member') model = memberRepo.save(firstName: '<NAME>') assert model.mCreatedAt? assert model.mUpdatedAt? assert new Date(model.mCreatedAt) instanceof Date assert new Date(model.mUpdatedAt) instanceof Date it 'createdAt stays original', -> memberRepo = facade.createRepository('member') now = new Date() model = memberRepo.save(firstName: '<NAME>', mCreatedAt: now) assert model.mCreatedAt? assert.deepEqual model.mCreatedAt, now it 'createdAt is newly set even when model has id', -> memberRepo = facade.createRepository('member') now = new Date() model = memberRepo.save(firstName: '<NAME>', id: 'shin') assert model.mCreatedAt? assert new Date(model.mCreatedAt) instanceof Date assert new Date(model.mUpdatedAt) instanceof Date it 'updatedAt changes for each saving', -> memberRepo = facade.createRepository('member') now = new Date() model = memberRepo.save(firstName: '<NAME>', mUpdatedAt: now) assert model.mCreatedAt? assert model.mUpdatedAt isnt now it 'returns instance of Model with relation ids', -> memberFactory = facade.createFactory('member') member = memberFactory.createFromObject id: '12' firstName: '<NAME>' age: 29 registeredAt: new Date() hobbies: [ { id: 1, name: 'keyboard' } { id: 2, name: 'ingress' } { id: 3, name: '<NAME>' } ] dFactory = facade.createFactory('diary') diary = dFactory.createFromObject title : 'crazy about room335' comment: 'progression of room335 is wonderful' author: member date : new Date() dRepo = facade.createRepository('diary') dRepo.save(diary).then (model) => assert model.memberId is '12' describe 'get', -> repo = facade.createRepository('hobby') it 'returns instance of Model', -> repo.get(1).then (model) => assert model instanceof Hobby describe 'query', -> repo = facade.createRepository('hobby') it 'returns array of models', -> repo.query().then (models) => assert models instanceof Array assert models[0] instanceof Hobby describe 'singleQuery', -> repo = facade.createRepository('hobby') it 'returns instance of Model', -> repo.singleQuery().then (model) => assert model instanceof Hobby describe 'delete', -> repo = facade.createRepository('hobby') it 'returns boolean', -> repo.delete(id: '123').then (isDeleted) => assert isDeleted describe 'update', -> repo = facade.createRepository('hobby') memberRepo = facade.createRepository('member') before -> memberRepo.save(id: '123', firstName: '<NAME>') repo.save(id: '123', name: '<NAME>').then (entity) => @tennis = entity it 'returns instance of Model', -> repo.update('123', name: '<NAME>').then (model) => assert model instanceof Hobby it 'returns instance of Model with updatedAt when configured as such', -> model = memberRepo.update('123', firstName: '<NAME>') assert new Date(model.mUpdatedAt) instanceof Date describe 'updateProps', -> repo = facade.createRepository('hobby') before -> repo.save(id: 'xyz', name: '<NAME>').then (entity) => @tennis = entity it 'returns diff props', -> repo.updateProps(@tennis, { name: 'xxx' }).then (results) => assert.deepEqual results, {} describe 'getDiff', -> repo = facade.createRepository('hobby') before -> repo.save(id: 'primitive-tech', name: 'primitive technology').then (@tech) => it 'returns diff props', -> @tech.name = 'abcde' repo.getDiff(@tech).then (results) => assert.deepEqual results, {name: 'primitive technology'}
true
facade = require('../create-facade').create('domain') Hobby = facade.getModel 'hobby' describe 'BaseRepository', -> describe 'factory', -> it 'is created by the model name', -> repo = facade.createRepository('hobby') HobbyFactory = facade.require('hobby-factory') assert repo.factory instanceof HobbyFactory describe 'save', -> repo = facade.createRepository('hobby') it 'returns instance of Model', -> repo.save(name: 'music').then (model) => assert model instanceof Hobby it 'returns instance of Model with createdAt, updatedAt when configured as such', -> memberRepo = facade.createRepository('member') model = memberRepo.save(firstName: 'PI:NAME:<NAME>END_PI') assert model.mCreatedAt? assert model.mUpdatedAt? assert new Date(model.mCreatedAt) instanceof Date assert new Date(model.mUpdatedAt) instanceof Date it 'createdAt stays original', -> memberRepo = facade.createRepository('member') now = new Date() model = memberRepo.save(firstName: 'PI:NAME:<NAME>END_PI', mCreatedAt: now) assert model.mCreatedAt? assert.deepEqual model.mCreatedAt, now it 'createdAt is newly set even when model has id', -> memberRepo = facade.createRepository('member') now = new Date() model = memberRepo.save(firstName: 'PI:NAME:<NAME>END_PI', id: 'shin') assert model.mCreatedAt? assert new Date(model.mCreatedAt) instanceof Date assert new Date(model.mUpdatedAt) instanceof Date it 'updatedAt changes for each saving', -> memberRepo = facade.createRepository('member') now = new Date() model = memberRepo.save(firstName: 'PI:NAME:<NAME>END_PI', mUpdatedAt: now) assert model.mCreatedAt? assert model.mUpdatedAt isnt now it 'returns instance of Model with relation ids', -> memberFactory = facade.createFactory('member') member = memberFactory.createFromObject id: '12' firstName: 'PI:NAME:<NAME>END_PI' age: 29 registeredAt: new Date() hobbies: [ { id: 1, name: 'keyboard' } { id: 2, name: 'ingress' } { id: 3, name: 'PI:NAME:<NAME>END_PI' } ] dFactory = facade.createFactory('diary') diary = dFactory.createFromObject title : 'crazy about room335' comment: 'progression of room335 is wonderful' author: member date : new Date() dRepo = facade.createRepository('diary') dRepo.save(diary).then (model) => assert model.memberId is '12' describe 'get', -> repo = facade.createRepository('hobby') it 'returns instance of Model', -> repo.get(1).then (model) => assert model instanceof Hobby describe 'query', -> repo = facade.createRepository('hobby') it 'returns array of models', -> repo.query().then (models) => assert models instanceof Array assert models[0] instanceof Hobby describe 'singleQuery', -> repo = facade.createRepository('hobby') it 'returns instance of Model', -> repo.singleQuery().then (model) => assert model instanceof Hobby describe 'delete', -> repo = facade.createRepository('hobby') it 'returns boolean', -> repo.delete(id: '123').then (isDeleted) => assert isDeleted describe 'update', -> repo = facade.createRepository('hobby') memberRepo = facade.createRepository('member') before -> memberRepo.save(id: '123', firstName: 'PI:NAME:<NAME>END_PI') repo.save(id: '123', name: 'PI:NAME:<NAME>END_PI').then (entity) => @tennis = entity it 'returns instance of Model', -> repo.update('123', name: 'PI:NAME:<NAME>END_PI').then (model) => assert model instanceof Hobby it 'returns instance of Model with updatedAt when configured as such', -> model = memberRepo.update('123', firstName: 'PI:NAME:<NAME>END_PI') assert new Date(model.mUpdatedAt) instanceof Date describe 'updateProps', -> repo = facade.createRepository('hobby') before -> repo.save(id: 'xyz', name: 'PI:NAME:<NAME>END_PI').then (entity) => @tennis = entity it 'returns diff props', -> repo.updateProps(@tennis, { name: 'xxx' }).then (results) => assert.deepEqual results, {} describe 'getDiff', -> repo = facade.createRepository('hobby') before -> repo.save(id: 'primitive-tech', name: 'primitive technology').then (@tech) => it 'returns diff props', -> @tech.name = 'abcde' repo.getDiff(@tech).then (results) => assert.deepEqual results, {name: 'primitive technology'}
[ { "context": "'0' + month\n year + '/' + month\n name: user, data: _.sortBy monthCount, (value, month) -> mon", "end": 2030, "score": 0.8813068270683289, "start": 2026, "tag": "NAME", "value": "user" } ]
client/views/home/home.coffee
victerryso/whatsapp
2
root = exports ? this Template.home.helpers total: -> Messages.find(user: $ne: 'You changed').count() firstDate: -> Messages.findOne({}, sort: time: 1).time.toDateString() stats: -> stats = Session.get('stats') if stats then return stats stats = {} charts = {} messages = Messages.find(user: $ne: 'You changed').fetch() grouped = _.groupBy messages, (message) -> message.user _.each grouped, (array, user) -> short = user.replace(/\s.*$/, '').toLowerCase() stats[short] ||= {} stats[short]['user'] = user stats[short]['short'] = user.split(/\s/, '')[0] stats[short]['array'] = array stats[short]['count'] = array.length stats[short]['imageCount'] = _.where(array, text: '<image omitted>').length # Hour Chart categories = _.range(24) series = _.map grouped, (array, user) -> hourCount = _.countBy array, (message) -> message.time.getHours() name: user, data: _.map categories, (hour) -> hourCount[hour] || 0 charts.hourCount = categories: categories, series: series # Day Chart categories = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] series = _.map grouped, (array, user) -> dayCount = _.countBy array, (message) -> message.time.getDay() name: user, data: _.map categories, (day, index) -> dayCount[index] charts.dayCount = categories: categories, series: series # Month Count monthCount = _.countBy messages, (message) -> year = parseInt(message.time.getFullYear()) - 2000 month = parseInt(message.time.getMonth()) + 1 if month < 10 then month = '0' + month year + '/' + month categories = _.keys(monthCount).sort() series = _.map grouped, (array, user) -> monthCount = _.countBy array, (message) -> year = parseInt(message.time.getFullYear()) - 2000 month = parseInt(message.time.getMonth()) + 1 if month < 10 then month = '0' + month year + '/' + month name: user, data: _.sortBy monthCount, (value, month) -> month charts.monthCount = categories: categories, series: series # Store Sessions Session.set('charts', charts) Session.set('stats', _.toArray stats) messageCount: -> stats = Session.get('stats') data = _.map stats, (stat) -> [stat.user, stat.count] chart2d('Messages Sent', data, '0%') imageCount: -> stats = Session.get('stats') data = _.map stats, (stat) -> [stat.user, stat.imageCount] chart2d('Images Sent', data, '50%') hourCount: -> chart = Session.get('charts').hourCount chart3d('column', 'normal', 'Hourly Messages', chart.categories, chart.series) dayCount: -> chart = Session.get('charts').dayCount chart3d('column', null, 'Daily Messages', chart.categories, chart.series) monthCount: -> chart = Session.get('charts').monthCount chart3d('line', null, 'Monthly Messages', chart.categories, chart.series)
178345
root = exports ? this Template.home.helpers total: -> Messages.find(user: $ne: 'You changed').count() firstDate: -> Messages.findOne({}, sort: time: 1).time.toDateString() stats: -> stats = Session.get('stats') if stats then return stats stats = {} charts = {} messages = Messages.find(user: $ne: 'You changed').fetch() grouped = _.groupBy messages, (message) -> message.user _.each grouped, (array, user) -> short = user.replace(/\s.*$/, '').toLowerCase() stats[short] ||= {} stats[short]['user'] = user stats[short]['short'] = user.split(/\s/, '')[0] stats[short]['array'] = array stats[short]['count'] = array.length stats[short]['imageCount'] = _.where(array, text: '<image omitted>').length # Hour Chart categories = _.range(24) series = _.map grouped, (array, user) -> hourCount = _.countBy array, (message) -> message.time.getHours() name: user, data: _.map categories, (hour) -> hourCount[hour] || 0 charts.hourCount = categories: categories, series: series # Day Chart categories = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] series = _.map grouped, (array, user) -> dayCount = _.countBy array, (message) -> message.time.getDay() name: user, data: _.map categories, (day, index) -> dayCount[index] charts.dayCount = categories: categories, series: series # Month Count monthCount = _.countBy messages, (message) -> year = parseInt(message.time.getFullYear()) - 2000 month = parseInt(message.time.getMonth()) + 1 if month < 10 then month = '0' + month year + '/' + month categories = _.keys(monthCount).sort() series = _.map grouped, (array, user) -> monthCount = _.countBy array, (message) -> year = parseInt(message.time.getFullYear()) - 2000 month = parseInt(message.time.getMonth()) + 1 if month < 10 then month = '0' + month year + '/' + month name: <NAME>, data: _.sortBy monthCount, (value, month) -> month charts.monthCount = categories: categories, series: series # Store Sessions Session.set('charts', charts) Session.set('stats', _.toArray stats) messageCount: -> stats = Session.get('stats') data = _.map stats, (stat) -> [stat.user, stat.count] chart2d('Messages Sent', data, '0%') imageCount: -> stats = Session.get('stats') data = _.map stats, (stat) -> [stat.user, stat.imageCount] chart2d('Images Sent', data, '50%') hourCount: -> chart = Session.get('charts').hourCount chart3d('column', 'normal', 'Hourly Messages', chart.categories, chart.series) dayCount: -> chart = Session.get('charts').dayCount chart3d('column', null, 'Daily Messages', chart.categories, chart.series) monthCount: -> chart = Session.get('charts').monthCount chart3d('line', null, 'Monthly Messages', chart.categories, chart.series)
true
root = exports ? this Template.home.helpers total: -> Messages.find(user: $ne: 'You changed').count() firstDate: -> Messages.findOne({}, sort: time: 1).time.toDateString() stats: -> stats = Session.get('stats') if stats then return stats stats = {} charts = {} messages = Messages.find(user: $ne: 'You changed').fetch() grouped = _.groupBy messages, (message) -> message.user _.each grouped, (array, user) -> short = user.replace(/\s.*$/, '').toLowerCase() stats[short] ||= {} stats[short]['user'] = user stats[short]['short'] = user.split(/\s/, '')[0] stats[short]['array'] = array stats[short]['count'] = array.length stats[short]['imageCount'] = _.where(array, text: '<image omitted>').length # Hour Chart categories = _.range(24) series = _.map grouped, (array, user) -> hourCount = _.countBy array, (message) -> message.time.getHours() name: user, data: _.map categories, (hour) -> hourCount[hour] || 0 charts.hourCount = categories: categories, series: series # Day Chart categories = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] series = _.map grouped, (array, user) -> dayCount = _.countBy array, (message) -> message.time.getDay() name: user, data: _.map categories, (day, index) -> dayCount[index] charts.dayCount = categories: categories, series: series # Month Count monthCount = _.countBy messages, (message) -> year = parseInt(message.time.getFullYear()) - 2000 month = parseInt(message.time.getMonth()) + 1 if month < 10 then month = '0' + month year + '/' + month categories = _.keys(monthCount).sort() series = _.map grouped, (array, user) -> monthCount = _.countBy array, (message) -> year = parseInt(message.time.getFullYear()) - 2000 month = parseInt(message.time.getMonth()) + 1 if month < 10 then month = '0' + month year + '/' + month name: PI:NAME:<NAME>END_PI, data: _.sortBy monthCount, (value, month) -> month charts.monthCount = categories: categories, series: series # Store Sessions Session.set('charts', charts) Session.set('stats', _.toArray stats) messageCount: -> stats = Session.get('stats') data = _.map stats, (stat) -> [stat.user, stat.count] chart2d('Messages Sent', data, '0%') imageCount: -> stats = Session.get('stats') data = _.map stats, (stat) -> [stat.user, stat.imageCount] chart2d('Images Sent', data, '50%') hourCount: -> chart = Session.get('charts').hourCount chart3d('column', 'normal', 'Hourly Messages', chart.categories, chart.series) dayCount: -> chart = Session.get('charts').dayCount chart3d('column', null, 'Daily Messages', chart.categories, chart.series) monthCount: -> chart = Session.get('charts').monthCount chart3d('line', null, 'Monthly Messages', chart.categories, chart.series)
[ { "context": "###\n# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>\n# Copyright (C) 2014 Jesús Espino ", "end": 38, "score": 0.9998882412910461, "start": 25, "tag": "NAME", "value": "Andrey Antukh" }, { "context": "###\n# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>\n# Copyright...
public/taiga-front/app/coffee/modules/nav.coffee
mabotech/maboss
0
### # Copyright (C) 2014 Andrey Antukh <niwi@niwi.be> # Copyright (C) 2014 Jesús Espino Garcia <jespinog@gmail.com> # Copyright (C) 2014 David Barragán Merino <bameda@dbarragan.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # File: modules/nav.coffee ### taiga = @.taiga groupBy = @.taiga.groupBy bindOnce = @.taiga.bindOnce timeout = @.taiga.timeout module = angular.module("taigaNavMenu", []) ############################################################################# ## Projects Navigation ############################################################################# class ProjectsNavigationController extends taiga.Controller @.$inject = ["$scope", "$rootScope", "$tgResources", "$tgNavUrls", "$projectUrl"] constructor: (@scope, @rootscope, @rs, @navurls, @projectUrl) -> promise = @.loadInitialData() promise.then null, -> console.log "FAIL" # TODO # Listen when someone wants to reload all the projects @scope.$on "projects:reload", => @.loadInitialData() # Listen when someone has reloaded a project @scope.$on "project:loaded", (ctx, project) => @.loadInitialData() loadInitialData: -> return @rs.projects.list().then (projects) => for project in projects project.url = @projectUrl.get(project) @scope.projects = projects @scope.filteredProjects = projects @scope.filterText = "" return projects newProject: -> @scope.$apply () => @rootscope.$broadcast("projects:create") filterProjects: (text) -> @scope.filteredProjects = _.filter @scope.projects, (project) -> project.name.toLowerCase().indexOf(text) > -1 @scope.filterText = text @rootscope.$broadcast("projects:filtered") module.controller("ProjectsNavigationController", ProjectsNavigationController) ProjectsNavigationDirective = ($rootscope, animationFrame, $timeout, tgLoader, $location, $compile) -> baseTemplate = _.template(""" <h1>Your projects</h1> <form> <fieldset> <input type="text" placeholder="Search in..." class="search-project"/> <a class="icon icon-search"></a> </fieldset> </form> <div class="create-project-button"> <a class="button button-green" href=""> Create project </a> </div> <div class="projects-pagination" tg-projects-pagination> <a class="v-pagination-previous icon icon-arrow-up " href=""></a> <div class="v-pagination-list"> <ul class="projects-list"> </ul> </div> <a class="v-pagination-next icon icon-arrow-bottom" href=""></a> </div> """) # TODO: i18n projectsTemplate = _.template(""" <% _.each(projects, function(project) { %> <li> <a href="<%- project.url %>"> <span class="project-name"><%- project.name %></span> <span class="icon icon-arrow-right"/> </a> </li> <% }) %> """) # TODO: i18n overlay = $(".projects-nav-overlay") loadingStart = 0 hideMenu = () -> if overlay.is(':visible') difftime = new Date().getTime() - loadingStart timeoutValue = 0 if (difftime < 1000) timeoutValue = 1000 - timeoutValue timeout timeoutValue, -> overlay.one 'transitionend', () -> $(document.body) .removeClass("loading-project open-projects-nav closed-projects-nav") .css("overflow-x", "visible") overlay.hide() $(document.body).addClass("closed-projects-nav") tgLoader.disablePreventLoading() link = ($scope, $el, $attrs, $ctrls) -> $ctrl = $ctrls[0] $rootscope.$on("project:loaded", hideMenu) renderProjects = (projects) -> html = projectsTemplate({projects: projects}) $el.find(".projects-list").html(html) $scope.$emit("regenerate:project-pagination") render = (projects) -> $el.html($compile(baseTemplate())($scope)) renderProjects(projects) overlay.on 'click', () -> hideMenu() $(document).on 'keydown', (e) => code = if e.keyCode then e.keyCode else e.which if code == 27 hideMenu() $scope.$on "nav:projects-list:open", -> if !$(document.body).hasClass("open-projects-nav") animationFrame.add () => overlay.show() animationFrame.add( () => $(document.body).css("overflow-x", "hidden") () => $(document.body).toggleClass("open-projects-nav") ) $el.on "click", ".projects-list > li > a", (event) -> # HACK: to solve a problem with the loader when the next url # is equal to the current one target = angular.element(event.currentTarget) nextUrl = target.prop("href") currentUrl = $location.absUrl() if nextUrl == currentUrl hideMenu() return # END HACK $(document.body).addClass('loading-project') tgLoader.preventLoading() loadingStart = new Date().getTime() $el.on "click", ".create-project-button .button", (event) -> event.preventDefault() $ctrl.newProject() $el.on "keyup", ".search-project", (event) -> target = angular.element(event.currentTarget) $ctrl.filterProjects(target.val()) $scope.$on "projects:filtered", -> renderProjects($scope.filteredProjects) $scope.$watch "projects", (projects) -> render(projects) if projects? return { require: ["tgProjectsNav"] controller: ProjectsNavigationController link: link } module.directive("tgProjectsNav", ["$rootScope", "animationFrame", "$timeout", "tgLoader", "$tgLocation", "$compile", ProjectsNavigationDirective]) ############################################################################# ## Project ############################################################################# ProjectMenuDirective = ($log, $compile, $auth, $rootscope, $tgAuth, $location, $navUrls, $config) -> menuEntriesTemplate = _.template(""" <div class="menu-container"> <ul class="main-nav"> <li id="nav-search"> <a href="" title="Search"> <span class="icon icon-search"></span><span class="item">Search</span> </a> </li> <% if (project.is_backlog_activated && project.my_permissions.indexOf("view_us") != -1) { %> <li id="nav-backlog"> <a href="" title="Backlog" tg-nav="project-backlog:project=project.slug"> <span class="icon icon-backlog"></span> <span class="item">Backlog</span> </a> </li> <% } %> <% if (project.is_kanban_activated && project.my_permissions.indexOf("view_us") != -1) { %> <li id="nav-kanban"> <a href="" title="Kanban" tg-nav="project-kanban:project=project.slug"> <span class="icon icon-kanban"></span><span class="item">Kanban</span> </a> </li> <% } %> <% if (project.is_issues_activated && project.my_permissions.indexOf("view_issues") != -1) { %> <li id="nav-issues"> <a href="" title="Issues" tg-nav="project-issues:project=project.slug"> <span class="icon icon-issues"></span><span class="item">Issues</span> </a> </li> <% } %> <% if (project.is_wiki_activated && project.my_permissions.indexOf("view_wiki_pages") != -1) { %> <li id="nav-wiki"> <a href="" title="Wiki" tg-nav="project-wiki:project=project.slug"> <span class="icon icon-wiki"></span> <span class="item">Wiki</span> </a> </li> <% } %> <li id="nav-team"> <a href="" title="Team" tg-nav="project-team:project=project.slug"> <span class="icon icon-team"></span> <span class="item">Team</span> </a> </li> <% if (project.videoconferences) { %> <li id="nav-video"> <a href="<%- project.videoconferenceUrl %>" target="_blank" title="Meet Up"> <span class="icon icon-video"></span> <span class="item">Meet Up</span> </a> </li> <% } %> <% if (project.i_am_owner) { %> <li id="nav-admin"> <a href="" tg-nav="project-admin-home:project=project.slug" title="Admin"> <span class="icon icon-settings"></span> <span class="item">Admin</span> </a> </li> <% } %> </ul> <div class="user"> <div class="user-settings"> <ul class="popover"> <li><a href="" title="User Profile", tg-nav="user-settings-user-profile:project=project.slug">User Profile</a></li> <li><a href="" title="Change Password", tg-nav="user-settings-user-change-password:project=project.slug">Change Password</a></li> <li><a href="" title="Notifications", tg-nav="user-settings-mail-notifications:project=project.slug">Notifications</a></li> <% if (feedbackEnabled) { %> <li><a href="" class="feedback" title="Feedback"">Feedback</a></li> <% } %> <li><a href="" title="Logout" class="logout">Logout</a></li> </ul> <a href="" title="User preferences" class="avatar" id="nav-user-settings"> <img src="<%- user.photo %>" alt="<%- user.full_name_display %>" /> </a> </div> </div> </div> """) mainTemplate = _.template(""" <div class="logo-container logo"> <svg xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 134.2 134.3" version="1.1" preserveAspectRatio="xMidYMid meet"> <style> path { fill:#f5f5f5; opacity:0.7; } </style> <g transform="translate(-307.87667,-465.22863)"> <g class="bottom"> <path transform="matrix(-0.14066483,0.99005727,-0.99005727,0.14066483,0,0)" d="m561.8-506.6 42 0 0 42-42 0z" /> <path transform="matrix(0.14066483,-0.99005727,0.99005727,-0.14066483,0,0)" d="m-645.7 422.6 42 0 0 42-42 0z" /> <path transform="matrix(0.99005727,0.14066483,0.14066483,0.99005727,0,0)" d="m266.6 451.9 42 0 0 42-42 0z" /> <path transform="matrix(-0.99005727,-0.14066483,-0.14066483,-0.99005727,0,0)" d="m-350.6-535.9 42 0 0 42-42 0z" /> </g> <g class="top"> <path transform="matrix(-0.60061118,-0.79954125,0.60061118,-0.79954125,0,0)" d="m-687.1-62.7 42 0 0 42-42 0z" /> <path transform="matrix(-0.79954125,0.60061118,-0.79954125,-0.60061118,0,0)" d="m166.6-719.6 42 0 0 42-42 0z" /> <path transform="matrix(0.60061118,0.79954125,-0.60061118,0.79954125,0,0)" d="m603.1-21.3 42 0 0 42-42 0z" /> <path transform="matrix(0.79954125,-0.60061118,0.79954125,0.60061118,0,0)" d="m-250.7 635.8 42 0 0 42-42 0z" /> <path transform="matrix(0.70710678,0.70710678,-0.70710678,0.70710678,0,0)" d="m630.3 100 22.6 0 0 22.6-22.6 0z" /> </g> </g> </svg> <span class="item">taiga<sup>[beta]</sup></span> </div> <div class="menu-container"></div> """) # If the last page was kanban or backlog and # the new one is the task detail or the us details # this method preserve the last section name. getSectionName = ($el, sectionName, project) -> oldSectionName = $el.find("a.active").parent().attr("id")?.replace("nav-", "") if sectionName == "backlog-kanban" if oldSectionName in ["backlog", "kanban"] sectionName = oldSectionName else if project.is_backlog_activated && !project.is_kanban_activated sectionName = "backlog" else if !project.is_backlog_activated && project.is_kanban_activated sectionName = "kanban" return sectionName renderMainMenu = ($el) -> html = mainTemplate({}) $el.html(html) # WARNING: this code has traces of slighty hacky parts # This rerenders and compiles the navigation when ng-view # content loaded signal is raised using inner scope. renderMenuEntries = ($el, targetScope, project={}) -> container = $el.find(".menu-container") sectionName = getSectionName($el, targetScope.section, project) ctx = { user: $auth.getUser(), project: project, feedbackEnabled: $config.get("feedbackEnabled") } dom = $compile(menuEntriesTemplate(ctx))(targetScope) dom.find("a.active").removeClass("active") dom.find("#nav-#{sectionName} > a").addClass("active") container.replaceWith(dom) videoConferenceUrl = (project) -> if project.videoconferences == "appear-in" baseUrl = "https://appear.in/" else if project.videoconferences == "talky" baseUrl = "https://talky.io/" else return "" if project.videoconferences_salt url = "#{project.slug}-#{project.videoconferences_salt}" else url = "#{project.slug}" return baseUrl + url link = ($scope, $el, $attrs, $ctrl) -> renderMainMenu($el) project = null $el.on "click", ".logo", (event) -> event.preventDefault() target = angular.element(event.currentTarget) $rootscope.$broadcast("nav:projects-list:open") $el.on "click", ".user-settings .avatar", (event) -> event.preventDefault() $el.find(".user-settings .popover").popover().open() $el.on "click", ".logout", (event) -> event.preventDefault() $auth.logout() $scope.$apply -> $location.path($navUrls.resolve("login")) $el.on "click", "#nav-search > a", (event) -> event.preventDefault() $rootscope.$broadcast("search-box:show", project) $el.on "click", ".feedback", (event) -> event.preventDefault() $rootscope.$broadcast("feedback:show") $scope.$on "projects:loaded", (listener) -> $el.addClass("hidden") listener.stopPropagation() $scope.$on "project:loaded", (ctx, newProject) -> project = newProject if $el.hasClass("hidden") $el.removeClass("hidden") project.videoconferenceUrl = videoConferenceUrl(project) renderMenuEntries($el, ctx.targetScope, project) return {link: link} module.directive("tgProjectMenu", ["$log", "$compile", "$tgAuth", "$rootScope", "$tgAuth", "$tgLocation", "$tgNavUrls", "$tgConfig", ProjectMenuDirective])
165467
### # Copyright (C) 2014 <NAME> <<EMAIL>> # Copyright (C) 2014 <NAME> <<EMAIL>> # Copyright (C) 2014 <NAME> <<EMAIL>> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # File: modules/nav.coffee ### taiga = @.taiga groupBy = @.taiga.groupBy bindOnce = @.taiga.bindOnce timeout = @.taiga.timeout module = angular.module("taigaNavMenu", []) ############################################################################# ## Projects Navigation ############################################################################# class ProjectsNavigationController extends taiga.Controller @.$inject = ["$scope", "$rootScope", "$tgResources", "$tgNavUrls", "$projectUrl"] constructor: (@scope, @rootscope, @rs, @navurls, @projectUrl) -> promise = @.loadInitialData() promise.then null, -> console.log "FAIL" # TODO # Listen when someone wants to reload all the projects @scope.$on "projects:reload", => @.loadInitialData() # Listen when someone has reloaded a project @scope.$on "project:loaded", (ctx, project) => @.loadInitialData() loadInitialData: -> return @rs.projects.list().then (projects) => for project in projects project.url = @projectUrl.get(project) @scope.projects = projects @scope.filteredProjects = projects @scope.filterText = "" return projects newProject: -> @scope.$apply () => @rootscope.$broadcast("projects:create") filterProjects: (text) -> @scope.filteredProjects = _.filter @scope.projects, (project) -> project.name.toLowerCase().indexOf(text) > -1 @scope.filterText = text @rootscope.$broadcast("projects:filtered") module.controller("ProjectsNavigationController", ProjectsNavigationController) ProjectsNavigationDirective = ($rootscope, animationFrame, $timeout, tgLoader, $location, $compile) -> baseTemplate = _.template(""" <h1>Your projects</h1> <form> <fieldset> <input type="text" placeholder="Search in..." class="search-project"/> <a class="icon icon-search"></a> </fieldset> </form> <div class="create-project-button"> <a class="button button-green" href=""> Create project </a> </div> <div class="projects-pagination" tg-projects-pagination> <a class="v-pagination-previous icon icon-arrow-up " href=""></a> <div class="v-pagination-list"> <ul class="projects-list"> </ul> </div> <a class="v-pagination-next icon icon-arrow-bottom" href=""></a> </div> """) # TODO: i18n projectsTemplate = _.template(""" <% _.each(projects, function(project) { %> <li> <a href="<%- project.url %>"> <span class="project-name"><%- project.name %></span> <span class="icon icon-arrow-right"/> </a> </li> <% }) %> """) # TODO: i18n overlay = $(".projects-nav-overlay") loadingStart = 0 hideMenu = () -> if overlay.is(':visible') difftime = new Date().getTime() - loadingStart timeoutValue = 0 if (difftime < 1000) timeoutValue = 1000 - timeoutValue timeout timeoutValue, -> overlay.one 'transitionend', () -> $(document.body) .removeClass("loading-project open-projects-nav closed-projects-nav") .css("overflow-x", "visible") overlay.hide() $(document.body).addClass("closed-projects-nav") tgLoader.disablePreventLoading() link = ($scope, $el, $attrs, $ctrls) -> $ctrl = $ctrls[0] $rootscope.$on("project:loaded", hideMenu) renderProjects = (projects) -> html = projectsTemplate({projects: projects}) $el.find(".projects-list").html(html) $scope.$emit("regenerate:project-pagination") render = (projects) -> $el.html($compile(baseTemplate())($scope)) renderProjects(projects) overlay.on 'click', () -> hideMenu() $(document).on 'keydown', (e) => code = if e.keyCode then e.keyCode else e.which if code == 27 hideMenu() $scope.$on "nav:projects-list:open", -> if !$(document.body).hasClass("open-projects-nav") animationFrame.add () => overlay.show() animationFrame.add( () => $(document.body).css("overflow-x", "hidden") () => $(document.body).toggleClass("open-projects-nav") ) $el.on "click", ".projects-list > li > a", (event) -> # HACK: to solve a problem with the loader when the next url # is equal to the current one target = angular.element(event.currentTarget) nextUrl = target.prop("href") currentUrl = $location.absUrl() if nextUrl == currentUrl hideMenu() return # END HACK $(document.body).addClass('loading-project') tgLoader.preventLoading() loadingStart = new Date().getTime() $el.on "click", ".create-project-button .button", (event) -> event.preventDefault() $ctrl.newProject() $el.on "keyup", ".search-project", (event) -> target = angular.element(event.currentTarget) $ctrl.filterProjects(target.val()) $scope.$on "projects:filtered", -> renderProjects($scope.filteredProjects) $scope.$watch "projects", (projects) -> render(projects) if projects? return { require: ["tgProjectsNav"] controller: ProjectsNavigationController link: link } module.directive("tgProjectsNav", ["$rootScope", "animationFrame", "$timeout", "tgLoader", "$tgLocation", "$compile", ProjectsNavigationDirective]) ############################################################################# ## Project ############################################################################# ProjectMenuDirective = ($log, $compile, $auth, $rootscope, $tgAuth, $location, $navUrls, $config) -> menuEntriesTemplate = _.template(""" <div class="menu-container"> <ul class="main-nav"> <li id="nav-search"> <a href="" title="Search"> <span class="icon icon-search"></span><span class="item">Search</span> </a> </li> <% if (project.is_backlog_activated && project.my_permissions.indexOf("view_us") != -1) { %> <li id="nav-backlog"> <a href="" title="Backlog" tg-nav="project-backlog:project=project.slug"> <span class="icon icon-backlog"></span> <span class="item">Backlog</span> </a> </li> <% } %> <% if (project.is_kanban_activated && project.my_permissions.indexOf("view_us") != -1) { %> <li id="nav-kanban"> <a href="" title="Kanban" tg-nav="project-kanban:project=project.slug"> <span class="icon icon-kanban"></span><span class="item">Kanban</span> </a> </li> <% } %> <% if (project.is_issues_activated && project.my_permissions.indexOf("view_issues") != -1) { %> <li id="nav-issues"> <a href="" title="Issues" tg-nav="project-issues:project=project.slug"> <span class="icon icon-issues"></span><span class="item">Issues</span> </a> </li> <% } %> <% if (project.is_wiki_activated && project.my_permissions.indexOf("view_wiki_pages") != -1) { %> <li id="nav-wiki"> <a href="" title="Wiki" tg-nav="project-wiki:project=project.slug"> <span class="icon icon-wiki"></span> <span class="item">Wiki</span> </a> </li> <% } %> <li id="nav-team"> <a href="" title="Team" tg-nav="project-team:project=project.slug"> <span class="icon icon-team"></span> <span class="item">Team</span> </a> </li> <% if (project.videoconferences) { %> <li id="nav-video"> <a href="<%- project.videoconferenceUrl %>" target="_blank" title="Meet Up"> <span class="icon icon-video"></span> <span class="item">Meet Up</span> </a> </li> <% } %> <% if (project.i_am_owner) { %> <li id="nav-admin"> <a href="" tg-nav="project-admin-home:project=project.slug" title="Admin"> <span class="icon icon-settings"></span> <span class="item">Admin</span> </a> </li> <% } %> </ul> <div class="user"> <div class="user-settings"> <ul class="popover"> <li><a href="" title="User Profile", tg-nav="user-settings-user-profile:project=project.slug">User Profile</a></li> <li><a href="" title="Change Password", tg-nav="user-settings-user-change-password:project=project.slug">Change Password</a></li> <li><a href="" title="Notifications", tg-nav="user-settings-mail-notifications:project=project.slug">Notifications</a></li> <% if (feedbackEnabled) { %> <li><a href="" class="feedback" title="Feedback"">Feedback</a></li> <% } %> <li><a href="" title="Logout" class="logout">Logout</a></li> </ul> <a href="" title="User preferences" class="avatar" id="nav-user-settings"> <img src="<%- user.photo %>" alt="<%- user.full_name_display %>" /> </a> </div> </div> </div> """) mainTemplate = _.template(""" <div class="logo-container logo"> <svg xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 134.2 134.3" version="1.1" preserveAspectRatio="xMidYMid meet"> <style> path { fill:#f5f5f5; opacity:0.7; } </style> <g transform="translate(-307.87667,-465.22863)"> <g class="bottom"> <path transform="matrix(-0.14066483,0.99005727,-0.99005727,0.14066483,0,0)" d="m561.8-506.6 42 0 0 42-42 0z" /> <path transform="matrix(0.14066483,-0.99005727,0.99005727,-0.14066483,0,0)" d="m-645.7 422.6 42 0 0 42-42 0z" /> <path transform="matrix(0.99005727,0.14066483,0.14066483,0.99005727,0,0)" d="m266.6 451.9 42 0 0 42-42 0z" /> <path transform="matrix(-0.99005727,-0.14066483,-0.14066483,-0.99005727,0,0)" d="m-350.6-535.9 42 0 0 42-42 0z" /> </g> <g class="top"> <path transform="matrix(-0.60061118,-0.79954125,0.60061118,-0.79954125,0,0)" d="m-687.1-62.7 42 0 0 42-42 0z" /> <path transform="matrix(-0.79954125,0.60061118,-0.79954125,-0.60061118,0,0)" d="m166.6-719.6 42 0 0 42-42 0z" /> <path transform="matrix(0.60061118,0.79954125,-0.60061118,0.79954125,0,0)" d="m603.1-21.3 42 0 0 42-42 0z" /> <path transform="matrix(0.79954125,-0.60061118,0.79954125,0.60061118,0,0)" d="m-250.7 635.8 42 0 0 42-42 0z" /> <path transform="matrix(0.70710678,0.70710678,-0.70710678,0.70710678,0,0)" d="m630.3 100 22.6 0 0 22.6-22.6 0z" /> </g> </g> </svg> <span class="item">taiga<sup>[beta]</sup></span> </div> <div class="menu-container"></div> """) # If the last page was kanban or backlog and # the new one is the task detail or the us details # this method preserve the last section name. getSectionName = ($el, sectionName, project) -> oldSectionName = $el.find("a.active").parent().attr("id")?.replace("nav-", "") if sectionName == "backlog-kanban" if oldSectionName in ["backlog", "kanban"] sectionName = oldSectionName else if project.is_backlog_activated && !project.is_kanban_activated sectionName = "backlog" else if !project.is_backlog_activated && project.is_kanban_activated sectionName = "kanban" return sectionName renderMainMenu = ($el) -> html = mainTemplate({}) $el.html(html) # WARNING: this code has traces of slighty hacky parts # This rerenders and compiles the navigation when ng-view # content loaded signal is raised using inner scope. renderMenuEntries = ($el, targetScope, project={}) -> container = $el.find(".menu-container") sectionName = getSectionName($el, targetScope.section, project) ctx = { user: $auth.getUser(), project: project, feedbackEnabled: $config.get("feedbackEnabled") } dom = $compile(menuEntriesTemplate(ctx))(targetScope) dom.find("a.active").removeClass("active") dom.find("#nav-#{sectionName} > a").addClass("active") container.replaceWith(dom) videoConferenceUrl = (project) -> if project.videoconferences == "appear-in" baseUrl = "https://appear.in/" else if project.videoconferences == "talky" baseUrl = "https://talky.io/" else return "" if project.videoconferences_salt url = "#{project.slug}-#{project.videoconferences_salt}" else url = "#{project.slug}" return baseUrl + url link = ($scope, $el, $attrs, $ctrl) -> renderMainMenu($el) project = null $el.on "click", ".logo", (event) -> event.preventDefault() target = angular.element(event.currentTarget) $rootscope.$broadcast("nav:projects-list:open") $el.on "click", ".user-settings .avatar", (event) -> event.preventDefault() $el.find(".user-settings .popover").popover().open() $el.on "click", ".logout", (event) -> event.preventDefault() $auth.logout() $scope.$apply -> $location.path($navUrls.resolve("login")) $el.on "click", "#nav-search > a", (event) -> event.preventDefault() $rootscope.$broadcast("search-box:show", project) $el.on "click", ".feedback", (event) -> event.preventDefault() $rootscope.$broadcast("feedback:show") $scope.$on "projects:loaded", (listener) -> $el.addClass("hidden") listener.stopPropagation() $scope.$on "project:loaded", (ctx, newProject) -> project = newProject if $el.hasClass("hidden") $el.removeClass("hidden") project.videoconferenceUrl = videoConferenceUrl(project) renderMenuEntries($el, ctx.targetScope, project) return {link: link} module.directive("tgProjectMenu", ["$log", "$compile", "$tgAuth", "$rootScope", "$tgAuth", "$tgLocation", "$tgNavUrls", "$tgConfig", ProjectMenuDirective])
true
### # Copyright (C) 2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # Copyright (C) 2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # Copyright (C) 2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # File: modules/nav.coffee ### taiga = @.taiga groupBy = @.taiga.groupBy bindOnce = @.taiga.bindOnce timeout = @.taiga.timeout module = angular.module("taigaNavMenu", []) ############################################################################# ## Projects Navigation ############################################################################# class ProjectsNavigationController extends taiga.Controller @.$inject = ["$scope", "$rootScope", "$tgResources", "$tgNavUrls", "$projectUrl"] constructor: (@scope, @rootscope, @rs, @navurls, @projectUrl) -> promise = @.loadInitialData() promise.then null, -> console.log "FAIL" # TODO # Listen when someone wants to reload all the projects @scope.$on "projects:reload", => @.loadInitialData() # Listen when someone has reloaded a project @scope.$on "project:loaded", (ctx, project) => @.loadInitialData() loadInitialData: -> return @rs.projects.list().then (projects) => for project in projects project.url = @projectUrl.get(project) @scope.projects = projects @scope.filteredProjects = projects @scope.filterText = "" return projects newProject: -> @scope.$apply () => @rootscope.$broadcast("projects:create") filterProjects: (text) -> @scope.filteredProjects = _.filter @scope.projects, (project) -> project.name.toLowerCase().indexOf(text) > -1 @scope.filterText = text @rootscope.$broadcast("projects:filtered") module.controller("ProjectsNavigationController", ProjectsNavigationController) ProjectsNavigationDirective = ($rootscope, animationFrame, $timeout, tgLoader, $location, $compile) -> baseTemplate = _.template(""" <h1>Your projects</h1> <form> <fieldset> <input type="text" placeholder="Search in..." class="search-project"/> <a class="icon icon-search"></a> </fieldset> </form> <div class="create-project-button"> <a class="button button-green" href=""> Create project </a> </div> <div class="projects-pagination" tg-projects-pagination> <a class="v-pagination-previous icon icon-arrow-up " href=""></a> <div class="v-pagination-list"> <ul class="projects-list"> </ul> </div> <a class="v-pagination-next icon icon-arrow-bottom" href=""></a> </div> """) # TODO: i18n projectsTemplate = _.template(""" <% _.each(projects, function(project) { %> <li> <a href="<%- project.url %>"> <span class="project-name"><%- project.name %></span> <span class="icon icon-arrow-right"/> </a> </li> <% }) %> """) # TODO: i18n overlay = $(".projects-nav-overlay") loadingStart = 0 hideMenu = () -> if overlay.is(':visible') difftime = new Date().getTime() - loadingStart timeoutValue = 0 if (difftime < 1000) timeoutValue = 1000 - timeoutValue timeout timeoutValue, -> overlay.one 'transitionend', () -> $(document.body) .removeClass("loading-project open-projects-nav closed-projects-nav") .css("overflow-x", "visible") overlay.hide() $(document.body).addClass("closed-projects-nav") tgLoader.disablePreventLoading() link = ($scope, $el, $attrs, $ctrls) -> $ctrl = $ctrls[0] $rootscope.$on("project:loaded", hideMenu) renderProjects = (projects) -> html = projectsTemplate({projects: projects}) $el.find(".projects-list").html(html) $scope.$emit("regenerate:project-pagination") render = (projects) -> $el.html($compile(baseTemplate())($scope)) renderProjects(projects) overlay.on 'click', () -> hideMenu() $(document).on 'keydown', (e) => code = if e.keyCode then e.keyCode else e.which if code == 27 hideMenu() $scope.$on "nav:projects-list:open", -> if !$(document.body).hasClass("open-projects-nav") animationFrame.add () => overlay.show() animationFrame.add( () => $(document.body).css("overflow-x", "hidden") () => $(document.body).toggleClass("open-projects-nav") ) $el.on "click", ".projects-list > li > a", (event) -> # HACK: to solve a problem with the loader when the next url # is equal to the current one target = angular.element(event.currentTarget) nextUrl = target.prop("href") currentUrl = $location.absUrl() if nextUrl == currentUrl hideMenu() return # END HACK $(document.body).addClass('loading-project') tgLoader.preventLoading() loadingStart = new Date().getTime() $el.on "click", ".create-project-button .button", (event) -> event.preventDefault() $ctrl.newProject() $el.on "keyup", ".search-project", (event) -> target = angular.element(event.currentTarget) $ctrl.filterProjects(target.val()) $scope.$on "projects:filtered", -> renderProjects($scope.filteredProjects) $scope.$watch "projects", (projects) -> render(projects) if projects? return { require: ["tgProjectsNav"] controller: ProjectsNavigationController link: link } module.directive("tgProjectsNav", ["$rootScope", "animationFrame", "$timeout", "tgLoader", "$tgLocation", "$compile", ProjectsNavigationDirective]) ############################################################################# ## Project ############################################################################# ProjectMenuDirective = ($log, $compile, $auth, $rootscope, $tgAuth, $location, $navUrls, $config) -> menuEntriesTemplate = _.template(""" <div class="menu-container"> <ul class="main-nav"> <li id="nav-search"> <a href="" title="Search"> <span class="icon icon-search"></span><span class="item">Search</span> </a> </li> <% if (project.is_backlog_activated && project.my_permissions.indexOf("view_us") != -1) { %> <li id="nav-backlog"> <a href="" title="Backlog" tg-nav="project-backlog:project=project.slug"> <span class="icon icon-backlog"></span> <span class="item">Backlog</span> </a> </li> <% } %> <% if (project.is_kanban_activated && project.my_permissions.indexOf("view_us") != -1) { %> <li id="nav-kanban"> <a href="" title="Kanban" tg-nav="project-kanban:project=project.slug"> <span class="icon icon-kanban"></span><span class="item">Kanban</span> </a> </li> <% } %> <% if (project.is_issues_activated && project.my_permissions.indexOf("view_issues") != -1) { %> <li id="nav-issues"> <a href="" title="Issues" tg-nav="project-issues:project=project.slug"> <span class="icon icon-issues"></span><span class="item">Issues</span> </a> </li> <% } %> <% if (project.is_wiki_activated && project.my_permissions.indexOf("view_wiki_pages") != -1) { %> <li id="nav-wiki"> <a href="" title="Wiki" tg-nav="project-wiki:project=project.slug"> <span class="icon icon-wiki"></span> <span class="item">Wiki</span> </a> </li> <% } %> <li id="nav-team"> <a href="" title="Team" tg-nav="project-team:project=project.slug"> <span class="icon icon-team"></span> <span class="item">Team</span> </a> </li> <% if (project.videoconferences) { %> <li id="nav-video"> <a href="<%- project.videoconferenceUrl %>" target="_blank" title="Meet Up"> <span class="icon icon-video"></span> <span class="item">Meet Up</span> </a> </li> <% } %> <% if (project.i_am_owner) { %> <li id="nav-admin"> <a href="" tg-nav="project-admin-home:project=project.slug" title="Admin"> <span class="icon icon-settings"></span> <span class="item">Admin</span> </a> </li> <% } %> </ul> <div class="user"> <div class="user-settings"> <ul class="popover"> <li><a href="" title="User Profile", tg-nav="user-settings-user-profile:project=project.slug">User Profile</a></li> <li><a href="" title="Change Password", tg-nav="user-settings-user-change-password:project=project.slug">Change Password</a></li> <li><a href="" title="Notifications", tg-nav="user-settings-mail-notifications:project=project.slug">Notifications</a></li> <% if (feedbackEnabled) { %> <li><a href="" class="feedback" title="Feedback"">Feedback</a></li> <% } %> <li><a href="" title="Logout" class="logout">Logout</a></li> </ul> <a href="" title="User preferences" class="avatar" id="nav-user-settings"> <img src="<%- user.photo %>" alt="<%- user.full_name_display %>" /> </a> </div> </div> </div> """) mainTemplate = _.template(""" <div class="logo-container logo"> <svg xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 134.2 134.3" version="1.1" preserveAspectRatio="xMidYMid meet"> <style> path { fill:#f5f5f5; opacity:0.7; } </style> <g transform="translate(-307.87667,-465.22863)"> <g class="bottom"> <path transform="matrix(-0.14066483,0.99005727,-0.99005727,0.14066483,0,0)" d="m561.8-506.6 42 0 0 42-42 0z" /> <path transform="matrix(0.14066483,-0.99005727,0.99005727,-0.14066483,0,0)" d="m-645.7 422.6 42 0 0 42-42 0z" /> <path transform="matrix(0.99005727,0.14066483,0.14066483,0.99005727,0,0)" d="m266.6 451.9 42 0 0 42-42 0z" /> <path transform="matrix(-0.99005727,-0.14066483,-0.14066483,-0.99005727,0,0)" d="m-350.6-535.9 42 0 0 42-42 0z" /> </g> <g class="top"> <path transform="matrix(-0.60061118,-0.79954125,0.60061118,-0.79954125,0,0)" d="m-687.1-62.7 42 0 0 42-42 0z" /> <path transform="matrix(-0.79954125,0.60061118,-0.79954125,-0.60061118,0,0)" d="m166.6-719.6 42 0 0 42-42 0z" /> <path transform="matrix(0.60061118,0.79954125,-0.60061118,0.79954125,0,0)" d="m603.1-21.3 42 0 0 42-42 0z" /> <path transform="matrix(0.79954125,-0.60061118,0.79954125,0.60061118,0,0)" d="m-250.7 635.8 42 0 0 42-42 0z" /> <path transform="matrix(0.70710678,0.70710678,-0.70710678,0.70710678,0,0)" d="m630.3 100 22.6 0 0 22.6-22.6 0z" /> </g> </g> </svg> <span class="item">taiga<sup>[beta]</sup></span> </div> <div class="menu-container"></div> """) # If the last page was kanban or backlog and # the new one is the task detail or the us details # this method preserve the last section name. getSectionName = ($el, sectionName, project) -> oldSectionName = $el.find("a.active").parent().attr("id")?.replace("nav-", "") if sectionName == "backlog-kanban" if oldSectionName in ["backlog", "kanban"] sectionName = oldSectionName else if project.is_backlog_activated && !project.is_kanban_activated sectionName = "backlog" else if !project.is_backlog_activated && project.is_kanban_activated sectionName = "kanban" return sectionName renderMainMenu = ($el) -> html = mainTemplate({}) $el.html(html) # WARNING: this code has traces of slighty hacky parts # This rerenders and compiles the navigation when ng-view # content loaded signal is raised using inner scope. renderMenuEntries = ($el, targetScope, project={}) -> container = $el.find(".menu-container") sectionName = getSectionName($el, targetScope.section, project) ctx = { user: $auth.getUser(), project: project, feedbackEnabled: $config.get("feedbackEnabled") } dom = $compile(menuEntriesTemplate(ctx))(targetScope) dom.find("a.active").removeClass("active") dom.find("#nav-#{sectionName} > a").addClass("active") container.replaceWith(dom) videoConferenceUrl = (project) -> if project.videoconferences == "appear-in" baseUrl = "https://appear.in/" else if project.videoconferences == "talky" baseUrl = "https://talky.io/" else return "" if project.videoconferences_salt url = "#{project.slug}-#{project.videoconferences_salt}" else url = "#{project.slug}" return baseUrl + url link = ($scope, $el, $attrs, $ctrl) -> renderMainMenu($el) project = null $el.on "click", ".logo", (event) -> event.preventDefault() target = angular.element(event.currentTarget) $rootscope.$broadcast("nav:projects-list:open") $el.on "click", ".user-settings .avatar", (event) -> event.preventDefault() $el.find(".user-settings .popover").popover().open() $el.on "click", ".logout", (event) -> event.preventDefault() $auth.logout() $scope.$apply -> $location.path($navUrls.resolve("login")) $el.on "click", "#nav-search > a", (event) -> event.preventDefault() $rootscope.$broadcast("search-box:show", project) $el.on "click", ".feedback", (event) -> event.preventDefault() $rootscope.$broadcast("feedback:show") $scope.$on "projects:loaded", (listener) -> $el.addClass("hidden") listener.stopPropagation() $scope.$on "project:loaded", (ctx, newProject) -> project = newProject if $el.hasClass("hidden") $el.removeClass("hidden") project.videoconferenceUrl = videoConferenceUrl(project) renderMenuEntries($el, ctx.targetScope, project) return {link: link} module.directive("tgProjectMenu", ["$log", "$compile", "$tgAuth", "$rootScope", "$tgAuth", "$tgLocation", "$tgNavUrls", "$tgConfig", ProjectMenuDirective])
[ { "context": "###\n\nThe Cellular Board for WolfCage.\n\n@author Destin Moulton\n@git https://github.com/destinmoulton/wolfcage\n@l", "end": 61, "score": 0.9998809695243835, "start": 47, "tag": "NAME", "value": "Destin Moulton" }, { "context": ".\n\n@author Destin Moulton\n@git https...
src/Board.coffee
destinmoulton/cagen
0
### The Cellular Board for WolfCage. @author Destin Moulton @git https://github.com/destinmoulton/wolfcage @license MIT Generate a cellular automata board based on a passed rule. ### RuleMatcher = require("./RuleMatcher.coffee") DOM = require("./DOM.coffee") class Board # # Constructor for the Board class. # Initialize the shared variables for the board. # constructor: (BUS)-> @BUS = BUS @_boardNoCellsWide = 0 @_boardNoCellsHigh = 0 @_boardCellWidthPx = 5 @_boardCellHeightPx = 5 @_currentRow = 1 @_rootRowBinary = [] @_currentCells = [] @_RuleMatcher = new RuleMatcher(BUS) @_setupColorChangeEvents() # # Build the board. # Take a binary representation of the root/top row and # then generate the cells. # buildBoard: (rootRowBinary, noCellsWide, noSectionsHigh) -> # Select local jQuery DOM objects @_boardElem = document.getElementById(DOM.getID('BOARD', 'CONTAINER')); @_messageElem = document.getElementById(DOM.getID('BOARD', 'MESSAGE_CONTAINER')); @_rootRowBinary = rootRowBinary @_RuleMatcher.setCurrentRule(@BUS.get('currentruledecimal')) @_boardNoCellsWide = noCellsWide @_boardNoCellsHigh = noSectionsHigh @_boardElem.innerWidth = noCellsWide * @_boardCellWidthPx @_boardElem.innerHeight = noSectionsHigh * @_boardCellHeightPx # Clear the board @_boardElem.innerHtml = "" @_boardElem.style.display = "none" @_currentRow = 1 # Show the generating message @_messageElem.style.display = "block" setTimeout(=> # Generate the rows @_generateRows() @_messageElem.style.display = "none" @_boardElem.style.display = "block" ,500) # # Set the change background/border color events # _setupColorChangeEvents:()-> @BUS.subscribe('change.cell.style.activebackground', (hexColor)=> @_changeCellActiveBackroundColor(hexColor) return ) @BUS.subscribe('change.cell.style.bordercolor', (hexColor)=> @_changeCellBorderColor(hexColor) ) @BUS.subscribe('change.cell.style.inactivebackground', (hexColor)=> @_changeCellInactiveBackgroundColor(hexColor) ) # # Generate the rows in the board # _generateRows:()-> @_buildTopRow() # Start at the 2nd row (the first/root row is already set) for row in [2..@_boardNoCellsHigh] @_currentRow = row @_buildRow(row) # # Add the blocks to a row # _buildRow: (row) -> # Loop over each column in the current row for col in [1..@_boardNoCellsWide] zeroIndex = @_currentCells[row-1][col-1] if zeroIndex is undefined # Wrap to the end of the row # when at the beginning zeroIndex = @_currentCells[row-1][@_boardNoCellsWide] oneIndex = @_currentCells[row-1][col] twoIndex = @_currentCells[row-1][col+1] if twoIndex is undefined # Wrap to the beginning of the row # when the end is reached twoIndex = @_currentCells[row-1][1] # Determine whether the block should be set or not if @_RuleMatcher.match(zeroIndex, oneIndex, twoIndex) is 0 @_getCellHtml(row, col, false) else @_getCellHtml(row, col, true) @_currentRow++ # # Add cells to the root/top row # _buildTopRow: -> # Build the top row from the root row binary # this is defined by the root row editor for col in [1..@_boardNoCellsWide] cell = @_rootRowBinary[col] if cell is 1 @_getCellHtml(@_currentRow, col, true) else @_getCellHtml(@_currentRow, col, false) @_currentRow++ # # Get the cell html # _getCellHtml: (row, col, active)-> # Add the cell state to the current array if !@_currentCells[row] @_currentCells[row] = [] @_currentCells[row][col] = if active then 1 else 0 tmpID = DOM.getPrefix('BOARD','CELL') + @_currentRow + "_" + col tmpLeftPx = (col-1)*@_boardCellWidthPx tmpTopPx = (row-1)*@_boardCellHeightPx tmpCell = document.createElement('div') tmpCell.setAttribute('id', tmpID) tmpCell.style.top = tmpTopPx + "px" tmpCell.style.left = tmpLeftPx + "px" # Inline CSS for the absolute position of the cell tmpClass = DOM.getClass('BOARD', 'CELL_BASE_CLASS') if active tmpCell.style.backgroundColor = @BUS.get('board.cell.style.activeBackgroundColor') tmpClass += " #{ DOM.getClass('BOARD', 'CELL_ACTIVE_CLASS') }" else tmpCell.style.backgroundColor = @BUS.get('board.cell.style.inactiveBackgroundColor') tmpCell.setAttribute('class', "#{tmpClass}") tmpCell.style.borderColor = @BUS.get('board.cell.style.borderColor') @_boardElem.appendChild(tmpCell); # # Change the color of the cells # _changeCellActiveBackroundColor: (hexColor)-> @BUS.set('board.cell.style.activeBackgroundColor', hexColor) cellsElems = document.querySelectorAll('.' + DOM.getClass('BOARD', 'CELL_ACTIVE_CLASS')) for cell in cellsElems cell.style.backgroundColor = hexColor # # Change the border color of the cells # _changeCellBorderColor: (hexColor)-> @BUS.set('board.style.borderColor', hexColor) @BUS.set('board.cell.style.borderColor', hexColor) DOM.elemById('GENERATOR','BOARD').style.borderColor = hexColor cellsElems = DOM.elemsByClass('BOARD', 'CELL_BASE_CLASS') for cell in cellsElems cell.style.borderRightColor = hexColor cell.style.borderBottomColor = hexColor # # Change the background color of the inactive cells # _changeCellInactiveBackgroundColor: (hexColor)-> @BUS.set('board.cell.style.inactiveBackgroundColor', hexColor) cellsElems = document.querySelectorAll('.' + DOM.getClass('BOARD', 'CELL_BASE_CLASS')) for cell in cellsElems if not cell.classList.contains(DOM.getClass('BOARD', 'CELL_ACTIVE_CLASS')) cell.style.backgroundColor = hexColor module.exports = Board
142821
### The Cellular Board for WolfCage. @author <NAME> @git https://github.com/destinmoulton/wolfcage @license MIT Generate a cellular automata board based on a passed rule. ### RuleMatcher = require("./RuleMatcher.coffee") DOM = require("./DOM.coffee") class Board # # Constructor for the Board class. # Initialize the shared variables for the board. # constructor: (BUS)-> @BUS = BUS @_boardNoCellsWide = 0 @_boardNoCellsHigh = 0 @_boardCellWidthPx = 5 @_boardCellHeightPx = 5 @_currentRow = 1 @_rootRowBinary = [] @_currentCells = [] @_RuleMatcher = new RuleMatcher(BUS) @_setupColorChangeEvents() # # Build the board. # Take a binary representation of the root/top row and # then generate the cells. # buildBoard: (rootRowBinary, noCellsWide, noSectionsHigh) -> # Select local jQuery DOM objects @_boardElem = document.getElementById(DOM.getID('BOARD', 'CONTAINER')); @_messageElem = document.getElementById(DOM.getID('BOARD', 'MESSAGE_CONTAINER')); @_rootRowBinary = rootRowBinary @_RuleMatcher.setCurrentRule(@BUS.get('currentruledecimal')) @_boardNoCellsWide = noCellsWide @_boardNoCellsHigh = noSectionsHigh @_boardElem.innerWidth = noCellsWide * @_boardCellWidthPx @_boardElem.innerHeight = noSectionsHigh * @_boardCellHeightPx # Clear the board @_boardElem.innerHtml = "" @_boardElem.style.display = "none" @_currentRow = 1 # Show the generating message @_messageElem.style.display = "block" setTimeout(=> # Generate the rows @_generateRows() @_messageElem.style.display = "none" @_boardElem.style.display = "block" ,500) # # Set the change background/border color events # _setupColorChangeEvents:()-> @BUS.subscribe('change.cell.style.activebackground', (hexColor)=> @_changeCellActiveBackroundColor(hexColor) return ) @BUS.subscribe('change.cell.style.bordercolor', (hexColor)=> @_changeCellBorderColor(hexColor) ) @BUS.subscribe('change.cell.style.inactivebackground', (hexColor)=> @_changeCellInactiveBackgroundColor(hexColor) ) # # Generate the rows in the board # _generateRows:()-> @_buildTopRow() # Start at the 2nd row (the first/root row is already set) for row in [2..@_boardNoCellsHigh] @_currentRow = row @_buildRow(row) # # Add the blocks to a row # _buildRow: (row) -> # Loop over each column in the current row for col in [1..@_boardNoCellsWide] zeroIndex = @_currentCells[row-1][col-1] if zeroIndex is undefined # Wrap to the end of the row # when at the beginning zeroIndex = @_currentCells[row-1][@_boardNoCellsWide] oneIndex = @_currentCells[row-1][col] twoIndex = @_currentCells[row-1][col+1] if twoIndex is undefined # Wrap to the beginning of the row # when the end is reached twoIndex = @_currentCells[row-1][1] # Determine whether the block should be set or not if @_RuleMatcher.match(zeroIndex, oneIndex, twoIndex) is 0 @_getCellHtml(row, col, false) else @_getCellHtml(row, col, true) @_currentRow++ # # Add cells to the root/top row # _buildTopRow: -> # Build the top row from the root row binary # this is defined by the root row editor for col in [1..@_boardNoCellsWide] cell = @_rootRowBinary[col] if cell is 1 @_getCellHtml(@_currentRow, col, true) else @_getCellHtml(@_currentRow, col, false) @_currentRow++ # # Get the cell html # _getCellHtml: (row, col, active)-> # Add the cell state to the current array if !@_currentCells[row] @_currentCells[row] = [] @_currentCells[row][col] = if active then 1 else 0 tmpID = DOM.getPrefix('BOARD','CELL') + @_currentRow + "_" + col tmpLeftPx = (col-1)*@_boardCellWidthPx tmpTopPx = (row-1)*@_boardCellHeightPx tmpCell = document.createElement('div') tmpCell.setAttribute('id', tmpID) tmpCell.style.top = tmpTopPx + "px" tmpCell.style.left = tmpLeftPx + "px" # Inline CSS for the absolute position of the cell tmpClass = DOM.getClass('BOARD', 'CELL_BASE_CLASS') if active tmpCell.style.backgroundColor = @BUS.get('board.cell.style.activeBackgroundColor') tmpClass += " #{ DOM.getClass('BOARD', 'CELL_ACTIVE_CLASS') }" else tmpCell.style.backgroundColor = @BUS.get('board.cell.style.inactiveBackgroundColor') tmpCell.setAttribute('class', "#{tmpClass}") tmpCell.style.borderColor = @BUS.get('board.cell.style.borderColor') @_boardElem.appendChild(tmpCell); # # Change the color of the cells # _changeCellActiveBackroundColor: (hexColor)-> @BUS.set('board.cell.style.activeBackgroundColor', hexColor) cellsElems = document.querySelectorAll('.' + DOM.getClass('BOARD', 'CELL_ACTIVE_CLASS')) for cell in cellsElems cell.style.backgroundColor = hexColor # # Change the border color of the cells # _changeCellBorderColor: (hexColor)-> @BUS.set('board.style.borderColor', hexColor) @BUS.set('board.cell.style.borderColor', hexColor) DOM.elemById('GENERATOR','BOARD').style.borderColor = hexColor cellsElems = DOM.elemsByClass('BOARD', 'CELL_BASE_CLASS') for cell in cellsElems cell.style.borderRightColor = hexColor cell.style.borderBottomColor = hexColor # # Change the background color of the inactive cells # _changeCellInactiveBackgroundColor: (hexColor)-> @BUS.set('board.cell.style.inactiveBackgroundColor', hexColor) cellsElems = document.querySelectorAll('.' + DOM.getClass('BOARD', 'CELL_BASE_CLASS')) for cell in cellsElems if not cell.classList.contains(DOM.getClass('BOARD', 'CELL_ACTIVE_CLASS')) cell.style.backgroundColor = hexColor module.exports = Board
true
### The Cellular Board for WolfCage. @author PI:NAME:<NAME>END_PI @git https://github.com/destinmoulton/wolfcage @license MIT Generate a cellular automata board based on a passed rule. ### RuleMatcher = require("./RuleMatcher.coffee") DOM = require("./DOM.coffee") class Board # # Constructor for the Board class. # Initialize the shared variables for the board. # constructor: (BUS)-> @BUS = BUS @_boardNoCellsWide = 0 @_boardNoCellsHigh = 0 @_boardCellWidthPx = 5 @_boardCellHeightPx = 5 @_currentRow = 1 @_rootRowBinary = [] @_currentCells = [] @_RuleMatcher = new RuleMatcher(BUS) @_setupColorChangeEvents() # # Build the board. # Take a binary representation of the root/top row and # then generate the cells. # buildBoard: (rootRowBinary, noCellsWide, noSectionsHigh) -> # Select local jQuery DOM objects @_boardElem = document.getElementById(DOM.getID('BOARD', 'CONTAINER')); @_messageElem = document.getElementById(DOM.getID('BOARD', 'MESSAGE_CONTAINER')); @_rootRowBinary = rootRowBinary @_RuleMatcher.setCurrentRule(@BUS.get('currentruledecimal')) @_boardNoCellsWide = noCellsWide @_boardNoCellsHigh = noSectionsHigh @_boardElem.innerWidth = noCellsWide * @_boardCellWidthPx @_boardElem.innerHeight = noSectionsHigh * @_boardCellHeightPx # Clear the board @_boardElem.innerHtml = "" @_boardElem.style.display = "none" @_currentRow = 1 # Show the generating message @_messageElem.style.display = "block" setTimeout(=> # Generate the rows @_generateRows() @_messageElem.style.display = "none" @_boardElem.style.display = "block" ,500) # # Set the change background/border color events # _setupColorChangeEvents:()-> @BUS.subscribe('change.cell.style.activebackground', (hexColor)=> @_changeCellActiveBackroundColor(hexColor) return ) @BUS.subscribe('change.cell.style.bordercolor', (hexColor)=> @_changeCellBorderColor(hexColor) ) @BUS.subscribe('change.cell.style.inactivebackground', (hexColor)=> @_changeCellInactiveBackgroundColor(hexColor) ) # # Generate the rows in the board # _generateRows:()-> @_buildTopRow() # Start at the 2nd row (the first/root row is already set) for row in [2..@_boardNoCellsHigh] @_currentRow = row @_buildRow(row) # # Add the blocks to a row # _buildRow: (row) -> # Loop over each column in the current row for col in [1..@_boardNoCellsWide] zeroIndex = @_currentCells[row-1][col-1] if zeroIndex is undefined # Wrap to the end of the row # when at the beginning zeroIndex = @_currentCells[row-1][@_boardNoCellsWide] oneIndex = @_currentCells[row-1][col] twoIndex = @_currentCells[row-1][col+1] if twoIndex is undefined # Wrap to the beginning of the row # when the end is reached twoIndex = @_currentCells[row-1][1] # Determine whether the block should be set or not if @_RuleMatcher.match(zeroIndex, oneIndex, twoIndex) is 0 @_getCellHtml(row, col, false) else @_getCellHtml(row, col, true) @_currentRow++ # # Add cells to the root/top row # _buildTopRow: -> # Build the top row from the root row binary # this is defined by the root row editor for col in [1..@_boardNoCellsWide] cell = @_rootRowBinary[col] if cell is 1 @_getCellHtml(@_currentRow, col, true) else @_getCellHtml(@_currentRow, col, false) @_currentRow++ # # Get the cell html # _getCellHtml: (row, col, active)-> # Add the cell state to the current array if !@_currentCells[row] @_currentCells[row] = [] @_currentCells[row][col] = if active then 1 else 0 tmpID = DOM.getPrefix('BOARD','CELL') + @_currentRow + "_" + col tmpLeftPx = (col-1)*@_boardCellWidthPx tmpTopPx = (row-1)*@_boardCellHeightPx tmpCell = document.createElement('div') tmpCell.setAttribute('id', tmpID) tmpCell.style.top = tmpTopPx + "px" tmpCell.style.left = tmpLeftPx + "px" # Inline CSS for the absolute position of the cell tmpClass = DOM.getClass('BOARD', 'CELL_BASE_CLASS') if active tmpCell.style.backgroundColor = @BUS.get('board.cell.style.activeBackgroundColor') tmpClass += " #{ DOM.getClass('BOARD', 'CELL_ACTIVE_CLASS') }" else tmpCell.style.backgroundColor = @BUS.get('board.cell.style.inactiveBackgroundColor') tmpCell.setAttribute('class', "#{tmpClass}") tmpCell.style.borderColor = @BUS.get('board.cell.style.borderColor') @_boardElem.appendChild(tmpCell); # # Change the color of the cells # _changeCellActiveBackroundColor: (hexColor)-> @BUS.set('board.cell.style.activeBackgroundColor', hexColor) cellsElems = document.querySelectorAll('.' + DOM.getClass('BOARD', 'CELL_ACTIVE_CLASS')) for cell in cellsElems cell.style.backgroundColor = hexColor # # Change the border color of the cells # _changeCellBorderColor: (hexColor)-> @BUS.set('board.style.borderColor', hexColor) @BUS.set('board.cell.style.borderColor', hexColor) DOM.elemById('GENERATOR','BOARD').style.borderColor = hexColor cellsElems = DOM.elemsByClass('BOARD', 'CELL_BASE_CLASS') for cell in cellsElems cell.style.borderRightColor = hexColor cell.style.borderBottomColor = hexColor # # Change the background color of the inactive cells # _changeCellInactiveBackgroundColor: (hexColor)-> @BUS.set('board.cell.style.inactiveBackgroundColor', hexColor) cellsElems = document.querySelectorAll('.' + DOM.getClass('BOARD', 'CELL_BASE_CLASS')) for cell in cellsElems if not cell.classList.contains(DOM.getClass('BOARD', 'CELL_ACTIVE_CLASS')) cell.style.backgroundColor = hexColor module.exports = Board
[ { "context": "\n \n getIdJob = (cb) =>\n indexIdKey = ['ids', name]\n @master.get(indexIdKey, cb)\n\n getIdCb =", "end": 1916, "score": 0.9491921067237854, "start": 1906, "tag": "KEY", "value": "ids', name" }, { "context": " id = @db.next(0)\n indexIdRever...
src/local/revision.coffee
tarruda/archdb
5
{AsyncEmitter, Uid, JobQueue, UidGenerator, ObjectRef} = require('../util') {DbError} = require('../errors') {AvlTree} = require('../avl') {LocalDomain, LocalHistoryDomain} = require('./domain') class LocalRevision extends AsyncEmitter constructor: (db, dbStorage, masterRef, @suffix) -> errorCb = (err) => @emit('error', err) historyCb = (err, tree) => if err then return @emit('error', err) @hist = tree super() @db = db @dbStorage = dbStorage @originalMasterRef = masterRef @uidGenerator = new UidGenerator(suffix) # this id is used mainly to filter out history entries created after # this revision when executing the merge algorithm @id = @uidGenerator.generate() @queue = new JobQueue() @queue.on('error', errorCb) @treeCache = {} @master = new AvlTree(dbStorage, masterRef, 0) @hist = new IndexProxy(HISTORY, @master, dbStorage, @queue, historyCb) domain: (name) -> if name[0] == '$' # special domain if name == HISTORY return @historyDomain() if match = HOOK_DOMAIN_PATTERN.exec(name) domain = match[3] name = "$on-#{match[1]}-#{match[2]}" return @hooksDomain(name, domain) throw new DbError("Invalid special domain '#{name}'") return @simpleDomain(name) historyDomain: -> rv = new LocalHistoryDomain(@dbStorage, @queue, @hist, @master) committedCb = => rv.tree = @hist @once('committed', committedCb) return rv simpleDomain: (name) -> indexIdKey = indexIdReverseKey = null cacheEntry = @treeCache[name] or @treeCache[name] = tree: new IndexProxy(name, @master, @dbStorage, @queue, treeCb) id: null name: name tree = cacheEntry.tree rv = new LocalDomain(name, @db, @dbStorage, @queue, tree, @hist, @uidGenerator) getIdJob = (cb) => indexIdKey = ['ids', name] @master.get(indexIdKey, cb) getIdCb = (err, id) => if err then return @emit('error', err) if not id id = @db.next(0) indexIdReverseKey = ['names', id] @queue.add(null, setIdJob) @queue.add(null, setIdReverseJob) cacheEntry.id = id rv.id = id setIdJob = (cb) => @master.set(indexIdKey, cacheEntry.id, cb) setIdReverseJob = (cb) => @master.set(indexIdReverseKey, name, cb) treeCb = (err, tree) => if err then return @emit('error', err) cacheEntry.tree = tree committedCb = => rv.tree = @treeCache[name].tree @once('committed', committedCb) if not cacheEntry.id then @queue.add(getIdCb, getIdJob) rv.id = cacheEntry.id return rv commit: (cb) -> job = (mergeCb) => @db.merge(this, mergeCb) mergeCb = (err, refMap, hist, master) => if err then return cb(err) for own k, v of refMap @treeCache[k] = v @hist = hist @master = master @originalMasterRef = master.getRootRef() @id = @uidGenerator.generate() @emit('committed') cb(null) @queue.add(mergeCb, job) class IndexProxy constructor: (name, master, dbStorage, queue, cb) -> jobCb = (nextJob) => cb = nextJob master.get(['refs', name], getCb) getCb = (err, refCount) => if err then return cb(err) if refCount @tree = new AvlTree(dbStorage, refCount[0], refCount[1]) else @tree = new AvlTree(dbStorage, null, null) if @pending @pending.add(cb, proxyJob) @pending.frozen = false return @pending.run() cb(null, @tree) proxyJob = (cb) => # only after all pending proxy invocations are handled we let # the transaction queue continue processing cb(null, @tree) @tree = null @pending = null queue.add(cb, jobCb) get: (key, cb) -> dcb = (tree, cb) => tree.get(key, cb) @delegate(cb, dcb) set: (key, value, cb) -> dcb = (tree, cb) => tree.set(key, value, cb) @delegate(cb, dcb) del: (key, cb) -> dcb = (tree, cb) => tree.del(key, cb) @delegate(cb, dcb) getCount: -> @tree.getCount() inOrder: (minKey, cb) -> dcb = (tree, cb) => tree.inOrder(minKey, cb) @delegate(cb, dcb) revInOrder: (maxKey, cb) -> dcb = (tree, cb) => tree.revInOrder(maxKey, cb) @delegate(cb, dcb) commit: (releaseCache, cb) -> dcb = (tree, cb) => tree.commit(releaseCache, cb) @delegate(cb, dcb) getRootRef: -> @tree.getRootRef() getOriginalRootRef: -> @tree.getOriginalRootRef() setOriginalRootRef: (ref) -> @tree.setOriginalRootRef(ref) modified: -> @tree.modified() delegate: (cb, fn) -> jobCb = (cb) => fn(@tree, cb) if @tree return fn(@tree, cb) if not @pending @pending = new JobQueue(true) @pending.add(cb, jobCb) module.exports = LocalRevision
148726
{AsyncEmitter, Uid, JobQueue, UidGenerator, ObjectRef} = require('../util') {DbError} = require('../errors') {AvlTree} = require('../avl') {LocalDomain, LocalHistoryDomain} = require('./domain') class LocalRevision extends AsyncEmitter constructor: (db, dbStorage, masterRef, @suffix) -> errorCb = (err) => @emit('error', err) historyCb = (err, tree) => if err then return @emit('error', err) @hist = tree super() @db = db @dbStorage = dbStorage @originalMasterRef = masterRef @uidGenerator = new UidGenerator(suffix) # this id is used mainly to filter out history entries created after # this revision when executing the merge algorithm @id = @uidGenerator.generate() @queue = new JobQueue() @queue.on('error', errorCb) @treeCache = {} @master = new AvlTree(dbStorage, masterRef, 0) @hist = new IndexProxy(HISTORY, @master, dbStorage, @queue, historyCb) domain: (name) -> if name[0] == '$' # special domain if name == HISTORY return @historyDomain() if match = HOOK_DOMAIN_PATTERN.exec(name) domain = match[3] name = "$on-#{match[1]}-#{match[2]}" return @hooksDomain(name, domain) throw new DbError("Invalid special domain '#{name}'") return @simpleDomain(name) historyDomain: -> rv = new LocalHistoryDomain(@dbStorage, @queue, @hist, @master) committedCb = => rv.tree = @hist @once('committed', committedCb) return rv simpleDomain: (name) -> indexIdKey = indexIdReverseKey = null cacheEntry = @treeCache[name] or @treeCache[name] = tree: new IndexProxy(name, @master, @dbStorage, @queue, treeCb) id: null name: name tree = cacheEntry.tree rv = new LocalDomain(name, @db, @dbStorage, @queue, tree, @hist, @uidGenerator) getIdJob = (cb) => indexIdKey = ['<KEY>] @master.get(indexIdKey, cb) getIdCb = (err, id) => if err then return @emit('error', err) if not id id = @db.next(0) indexIdReverseKey = ['<KEY>] @queue.add(null, setIdJob) @queue.add(null, setIdReverseJob) cacheEntry.id = id rv.id = id setIdJob = (cb) => @master.set(indexIdKey, cacheEntry.id, cb) setIdReverseJob = (cb) => @master.set(indexIdReverseKey, name, cb) treeCb = (err, tree) => if err then return @emit('error', err) cacheEntry.tree = tree committedCb = => rv.tree = @treeCache[name].tree @once('committed', committedCb) if not cacheEntry.id then @queue.add(getIdCb, getIdJob) rv.id = cacheEntry.id return rv commit: (cb) -> job = (mergeCb) => @db.merge(this, mergeCb) mergeCb = (err, refMap, hist, master) => if err then return cb(err) for own k, v of refMap @treeCache[k] = v @hist = hist @master = master @originalMasterRef = master.getRootRef() @id = @uidGenerator.generate() @emit('committed') cb(null) @queue.add(mergeCb, job) class IndexProxy constructor: (name, master, dbStorage, queue, cb) -> jobCb = (nextJob) => cb = nextJob master.get(['refs', name], getCb) getCb = (err, refCount) => if err then return cb(err) if refCount @tree = new AvlTree(dbStorage, refCount[0], refCount[1]) else @tree = new AvlTree(dbStorage, null, null) if @pending @pending.add(cb, proxyJob) @pending.frozen = false return @pending.run() cb(null, @tree) proxyJob = (cb) => # only after all pending proxy invocations are handled we let # the transaction queue continue processing cb(null, @tree) @tree = null @pending = null queue.add(cb, jobCb) get: (key, cb) -> dcb = (tree, cb) => tree.get(key, cb) @delegate(cb, dcb) set: (key, value, cb) -> dcb = (tree, cb) => tree.set(key, value, cb) @delegate(cb, dcb) del: (key, cb) -> dcb = (tree, cb) => tree.del(key, cb) @delegate(cb, dcb) getCount: -> @tree.getCount() inOrder: (minKey, cb) -> dcb = (tree, cb) => tree.inOrder(minKey, cb) @delegate(cb, dcb) revInOrder: (maxKey, cb) -> dcb = (tree, cb) => tree.revInOrder(maxKey, cb) @delegate(cb, dcb) commit: (releaseCache, cb) -> dcb = (tree, cb) => tree.commit(releaseCache, cb) @delegate(cb, dcb) getRootRef: -> @tree.getRootRef() getOriginalRootRef: -> @tree.getOriginalRootRef() setOriginalRootRef: (ref) -> @tree.setOriginalRootRef(ref) modified: -> @tree.modified() delegate: (cb, fn) -> jobCb = (cb) => fn(@tree, cb) if @tree return fn(@tree, cb) if not @pending @pending = new JobQueue(true) @pending.add(cb, jobCb) module.exports = LocalRevision
true
{AsyncEmitter, Uid, JobQueue, UidGenerator, ObjectRef} = require('../util') {DbError} = require('../errors') {AvlTree} = require('../avl') {LocalDomain, LocalHistoryDomain} = require('./domain') class LocalRevision extends AsyncEmitter constructor: (db, dbStorage, masterRef, @suffix) -> errorCb = (err) => @emit('error', err) historyCb = (err, tree) => if err then return @emit('error', err) @hist = tree super() @db = db @dbStorage = dbStorage @originalMasterRef = masterRef @uidGenerator = new UidGenerator(suffix) # this id is used mainly to filter out history entries created after # this revision when executing the merge algorithm @id = @uidGenerator.generate() @queue = new JobQueue() @queue.on('error', errorCb) @treeCache = {} @master = new AvlTree(dbStorage, masterRef, 0) @hist = new IndexProxy(HISTORY, @master, dbStorage, @queue, historyCb) domain: (name) -> if name[0] == '$' # special domain if name == HISTORY return @historyDomain() if match = HOOK_DOMAIN_PATTERN.exec(name) domain = match[3] name = "$on-#{match[1]}-#{match[2]}" return @hooksDomain(name, domain) throw new DbError("Invalid special domain '#{name}'") return @simpleDomain(name) historyDomain: -> rv = new LocalHistoryDomain(@dbStorage, @queue, @hist, @master) committedCb = => rv.tree = @hist @once('committed', committedCb) return rv simpleDomain: (name) -> indexIdKey = indexIdReverseKey = null cacheEntry = @treeCache[name] or @treeCache[name] = tree: new IndexProxy(name, @master, @dbStorage, @queue, treeCb) id: null name: name tree = cacheEntry.tree rv = new LocalDomain(name, @db, @dbStorage, @queue, tree, @hist, @uidGenerator) getIdJob = (cb) => indexIdKey = ['PI:KEY:<KEY>END_PI] @master.get(indexIdKey, cb) getIdCb = (err, id) => if err then return @emit('error', err) if not id id = @db.next(0) indexIdReverseKey = ['PI:KEY:<KEY>END_PI] @queue.add(null, setIdJob) @queue.add(null, setIdReverseJob) cacheEntry.id = id rv.id = id setIdJob = (cb) => @master.set(indexIdKey, cacheEntry.id, cb) setIdReverseJob = (cb) => @master.set(indexIdReverseKey, name, cb) treeCb = (err, tree) => if err then return @emit('error', err) cacheEntry.tree = tree committedCb = => rv.tree = @treeCache[name].tree @once('committed', committedCb) if not cacheEntry.id then @queue.add(getIdCb, getIdJob) rv.id = cacheEntry.id return rv commit: (cb) -> job = (mergeCb) => @db.merge(this, mergeCb) mergeCb = (err, refMap, hist, master) => if err then return cb(err) for own k, v of refMap @treeCache[k] = v @hist = hist @master = master @originalMasterRef = master.getRootRef() @id = @uidGenerator.generate() @emit('committed') cb(null) @queue.add(mergeCb, job) class IndexProxy constructor: (name, master, dbStorage, queue, cb) -> jobCb = (nextJob) => cb = nextJob master.get(['refs', name], getCb) getCb = (err, refCount) => if err then return cb(err) if refCount @tree = new AvlTree(dbStorage, refCount[0], refCount[1]) else @tree = new AvlTree(dbStorage, null, null) if @pending @pending.add(cb, proxyJob) @pending.frozen = false return @pending.run() cb(null, @tree) proxyJob = (cb) => # only after all pending proxy invocations are handled we let # the transaction queue continue processing cb(null, @tree) @tree = null @pending = null queue.add(cb, jobCb) get: (key, cb) -> dcb = (tree, cb) => tree.get(key, cb) @delegate(cb, dcb) set: (key, value, cb) -> dcb = (tree, cb) => tree.set(key, value, cb) @delegate(cb, dcb) del: (key, cb) -> dcb = (tree, cb) => tree.del(key, cb) @delegate(cb, dcb) getCount: -> @tree.getCount() inOrder: (minKey, cb) -> dcb = (tree, cb) => tree.inOrder(minKey, cb) @delegate(cb, dcb) revInOrder: (maxKey, cb) -> dcb = (tree, cb) => tree.revInOrder(maxKey, cb) @delegate(cb, dcb) commit: (releaseCache, cb) -> dcb = (tree, cb) => tree.commit(releaseCache, cb) @delegate(cb, dcb) getRootRef: -> @tree.getRootRef() getOriginalRootRef: -> @tree.getOriginalRootRef() setOriginalRootRef: (ref) -> @tree.setOriginalRootRef(ref) modified: -> @tree.modified() delegate: (cb, fn) -> jobCb = (cb) => fn(@tree, cb) if @tree return fn(@tree, cb) if not @pending @pending = new JobQueue(true) @pending.add(cb, jobCb) module.exports = LocalRevision
[ { "context": "#\n#/*!\n# * node-uglifier\n# * Copyright (c) 2014 Zsolt Szabo Istvan\n# * MIT Licensed\n# *\n# */\n#\n\nfsExtra = require('f", "end": 66, "score": 0.9998596906661987, "start": 48, "tag": "NAME", "value": "Zsolt Szabo Istvan" } ]
src/libs/packageUtils.coffee
BenHall/node-uglifier
185
# #/*! # * node-uglifier # * Copyright (c) 2014 Zsolt Szabo Istvan # * MIT Licensed # * # */ # fsExtra = require('fs-extra'); fs = require('fs'); UglifyJS = require('uglify-js-harmony') path = require('path') _ = require('underscore') packageUtils = module.exports # Check if `module` is a native module (like `net` or `tty`). packageUtils.isNative = (module)-> try return require.resolve(module) == module; catch err return false; packageUtils.readFile = (pathAbs, encoding = 'utf8')-> options = {encoding} return fs.readFileSync(pathAbs, options) packageUtils.getAst = (code)-> return UglifyJS.parse(code) #absolulte file path packageUtils.getMatchingFiles = (rootPath, dirAndFileArray)-> r = [] rootDir = if fs.lstatSync(rootPath).isDirectory() then path.resolve(rootPath) else path.dirname(path.resolve(rootPath)) for dirOrFile in dirAndFileArray destination = path.resolve(rootDir, dirOrFile) try filestats = fs.lstatSync(destination) catch me #probably missing extension, file not found filestats = null if filestats and filestats.isDirectory() #we have directory fs.readdirSync(destination).reduce(((prev, curr)-> prev.push(path.join(destination, curr));return prev), r) else if path.extname(destination) == "" fileName = path.basename(destination) fs.readdirSync(path.dirname(destination)).filter((fileNameLoc)-> fileNameLoc.indexOf(fileName) != -1).reduce(((prev, curr)-> prev.push(path.join(destination, curr)); return prev), r) else r.push(destination) return r packageUtils.getIfNonNativeNotFilteredNonNpm = (fileAbs, filters, possibleExtensions)-> #if path can be resolved and it is file than it is non native, non npm r = null if path.extname(fileAbs) == "" existingExtensions = possibleExtensions.filter((ext)->return fs.existsSync(fileAbs + "." + ext)) if existingExtensions.length > 1 then throw new Error(" multiple matching extensions problem for " + fileAbs) r = if existingExtensions.length == 1 then fileAbs + "." + existingExtensions[0] else null else r = if fs.existsSync(fileAbs) then fileAbs else null if r if filters.filter((fFile)->return path.normalize(fFile) == path.normalize(r)).length > 0 r = null; console.log(fileAbs + " was filtered ") return r packageUtils.walkExpressions=(astNode,parentNode,depth)-> if depth>5 then return null if astNode.name=="require" return parentNode?.args || astNode.args else if astNode.expression? return packageUtils.walkExpressions(astNode.expression,astNode,depth+1) #assume no directory is native module #returns the file path of modules if file exists #if no extension specified first existing possibleExtensions is used packageUtils.getRequireStatements = (ast, file, possibleExtensions = ["js", "coffee"], packNodeModules = false)-> r = [] fileDir = path.dirname(file) handleRequireNode = (text, args)-> pathOfModuleRaw = args[0].value if !pathOfModuleRaw? then throw new Error("probably dynamic") #has / or \ in the string hasPathInIt = (!_.isEmpty(pathOfModuleRaw.match("/")) || !_.isEmpty(pathOfModuleRaw.match(/\\/))) if hasPathInIt #it is not a module, do nothing else if packNodeModules #find node_module directory, than main in package json if no index.js found pathOfModuleRaw=require.resolve(pathOfModuleRaw) else #it is module and not packed return false pathOfModuleLoc = path.resolve(fileDir, pathOfModuleRaw) try pathOfModuleLocStats =fs.lstatSync(pathOfModuleLoc) catch me; if (pathOfModuleLocStats and pathOfModuleLocStats.isDirectory()) pathOfModuleLoc=path.resolve(pathOfModuleLoc, "index") #if path can be resolved and it is file than it is non native, non npm pathOfModule = packageUtils.getIfNonNativeNotFilteredNonNpm(pathOfModuleLoc, [], possibleExtensions) rs = {text, path: pathOfModule} if pathOfModule r.push(rs) ast.walk(new UglifyJS.TreeWalker( (node)-> if (node instanceof UglifyJS.AST_Call) && (node.start.value == 'require' || (node.start.value == 'new' and node.expression.print_to_string() == "require")) text = node.print_to_string({beautify: false}) # console.log(text) #expression argument takes precedence over the first argument of require requireArgs = node?.expression?.args walkedArgs=packageUtils.walkExpressions(node,null,1) if _.isEmpty(requireArgs) requireArgs = node.args try # if args.length != 1 then # throw new Error ("in file: " + file + " require supposed to have 1 argument: " + text) if requireArgs.length != 1 or !handleRequireNode(text, requireArgs) and !_.isEmpty(walkedArgs) text2="require('#{walkedArgs[0].value}')" handleRequireNode(text2, walkedArgs) catch me console.log("Warning!:") console.log("unhandled require type in file: " + file + " the problematic statement: " + text + " probably something fancy going on! " + " the error: " + me.message) return true else if (node instanceof UglifyJS.AST_Call) && (node.start.value == 'new' and node.expression.start.value == "(" and node.expression.print_to_string().indexOf("require") != -1) args = node.expression.args text = "require" + "('" + args[0].value + "')" # console.log(text) handleRequireNode(text, args) console.log("second " + text) return true else return ) ) return r strEscapeMap = { '\b': '\\b', '\f': '\\f', '\n': '\\n', '\r': '\\r', '\t': '\\t', }; packageUtils.hexifyString = (str)-> r = "" if !str.length > 0 then return r for i in [0..str.length - 1] char = str[i]; if (strEscapeMap[char]) r += r[char]; else if ('\\' == char) r += '\\' + str[++i] else r += '\\x' + str.charCodeAt(i).toString(16); return r; packageUtils.deHexifyString = (str)-> return str.toString() packageUtils.getSourceHexified = (ast)-> hexify = (node)-> if (node instanceof UglifyJS.AST_String) text = node.getValue() hex = packageUtils.hexifyString(text); obj = _.extend({}, node); obj.value = hex return new UglifyJS.AST_String(obj); else return transformer = new UglifyJS.TreeTransformer(null, hexify); stream = new UglifyJS.OutputStream; stream.print_string = (str)-> return this.print('"' + str + '"') ast = ast.transform(transformer); ast.print(stream); return stream.toString() #packageUtils.replaceAll=(find, replace, str)-> # return str.replace(new RegExp(find, 'g'), replace); packageUtils.replaceRequireStatement = (textIn, orig, replacement)-> text = textIn isReplaced = false text = text.replace(orig, (token)-> (isReplaced = true;return replacement)) if !isReplaced withTheOtherQuotation = orig if withTheOtherQuotation.indexOf("'") != -1 withTheOtherQuotation = withTheOtherQuotation.replace(/[']/ig, '"') else withTheOtherQuotation = withTheOtherQuotation.replace(/["]/ig, "'") text = text.replace(withTheOtherQuotation, (token)-> (isReplaced = true;return replacement)) if !isReplaced throw new Error(orig + " was not replaced with " + replacement) return text packageUtils.countWords = (sentence)-> index = {} words = sentence .replace(/[.,?!;()"'-]/g, " ") .replace(/\s+/g, " ") .toLowerCase() .split(" "); words.forEach((word)-> if (!(index.hasOwnProperty(word))) index[word] = 0; index[word]++; ) return index # console.log([text,path.resolve(fileDir,pathOfModule),packageUtils.isNative(pathOfModule)].join(" | ")) #print_to_string({ beautify: false }).replace(/-/g, "_") AST_Assign node.left,right # return true; no descend
75678
# #/*! # * node-uglifier # * Copyright (c) 2014 <NAME> # * MIT Licensed # * # */ # fsExtra = require('fs-extra'); fs = require('fs'); UglifyJS = require('uglify-js-harmony') path = require('path') _ = require('underscore') packageUtils = module.exports # Check if `module` is a native module (like `net` or `tty`). packageUtils.isNative = (module)-> try return require.resolve(module) == module; catch err return false; packageUtils.readFile = (pathAbs, encoding = 'utf8')-> options = {encoding} return fs.readFileSync(pathAbs, options) packageUtils.getAst = (code)-> return UglifyJS.parse(code) #absolulte file path packageUtils.getMatchingFiles = (rootPath, dirAndFileArray)-> r = [] rootDir = if fs.lstatSync(rootPath).isDirectory() then path.resolve(rootPath) else path.dirname(path.resolve(rootPath)) for dirOrFile in dirAndFileArray destination = path.resolve(rootDir, dirOrFile) try filestats = fs.lstatSync(destination) catch me #probably missing extension, file not found filestats = null if filestats and filestats.isDirectory() #we have directory fs.readdirSync(destination).reduce(((prev, curr)-> prev.push(path.join(destination, curr));return prev), r) else if path.extname(destination) == "" fileName = path.basename(destination) fs.readdirSync(path.dirname(destination)).filter((fileNameLoc)-> fileNameLoc.indexOf(fileName) != -1).reduce(((prev, curr)-> prev.push(path.join(destination, curr)); return prev), r) else r.push(destination) return r packageUtils.getIfNonNativeNotFilteredNonNpm = (fileAbs, filters, possibleExtensions)-> #if path can be resolved and it is file than it is non native, non npm r = null if path.extname(fileAbs) == "" existingExtensions = possibleExtensions.filter((ext)->return fs.existsSync(fileAbs + "." + ext)) if existingExtensions.length > 1 then throw new Error(" multiple matching extensions problem for " + fileAbs) r = if existingExtensions.length == 1 then fileAbs + "." + existingExtensions[0] else null else r = if fs.existsSync(fileAbs) then fileAbs else null if r if filters.filter((fFile)->return path.normalize(fFile) == path.normalize(r)).length > 0 r = null; console.log(fileAbs + " was filtered ") return r packageUtils.walkExpressions=(astNode,parentNode,depth)-> if depth>5 then return null if astNode.name=="require" return parentNode?.args || astNode.args else if astNode.expression? return packageUtils.walkExpressions(astNode.expression,astNode,depth+1) #assume no directory is native module #returns the file path of modules if file exists #if no extension specified first existing possibleExtensions is used packageUtils.getRequireStatements = (ast, file, possibleExtensions = ["js", "coffee"], packNodeModules = false)-> r = [] fileDir = path.dirname(file) handleRequireNode = (text, args)-> pathOfModuleRaw = args[0].value if !pathOfModuleRaw? then throw new Error("probably dynamic") #has / or \ in the string hasPathInIt = (!_.isEmpty(pathOfModuleRaw.match("/")) || !_.isEmpty(pathOfModuleRaw.match(/\\/))) if hasPathInIt #it is not a module, do nothing else if packNodeModules #find node_module directory, than main in package json if no index.js found pathOfModuleRaw=require.resolve(pathOfModuleRaw) else #it is module and not packed return false pathOfModuleLoc = path.resolve(fileDir, pathOfModuleRaw) try pathOfModuleLocStats =fs.lstatSync(pathOfModuleLoc) catch me; if (pathOfModuleLocStats and pathOfModuleLocStats.isDirectory()) pathOfModuleLoc=path.resolve(pathOfModuleLoc, "index") #if path can be resolved and it is file than it is non native, non npm pathOfModule = packageUtils.getIfNonNativeNotFilteredNonNpm(pathOfModuleLoc, [], possibleExtensions) rs = {text, path: pathOfModule} if pathOfModule r.push(rs) ast.walk(new UglifyJS.TreeWalker( (node)-> if (node instanceof UglifyJS.AST_Call) && (node.start.value == 'require' || (node.start.value == 'new' and node.expression.print_to_string() == "require")) text = node.print_to_string({beautify: false}) # console.log(text) #expression argument takes precedence over the first argument of require requireArgs = node?.expression?.args walkedArgs=packageUtils.walkExpressions(node,null,1) if _.isEmpty(requireArgs) requireArgs = node.args try # if args.length != 1 then # throw new Error ("in file: " + file + " require supposed to have 1 argument: " + text) if requireArgs.length != 1 or !handleRequireNode(text, requireArgs) and !_.isEmpty(walkedArgs) text2="require('#{walkedArgs[0].value}')" handleRequireNode(text2, walkedArgs) catch me console.log("Warning!:") console.log("unhandled require type in file: " + file + " the problematic statement: " + text + " probably something fancy going on! " + " the error: " + me.message) return true else if (node instanceof UglifyJS.AST_Call) && (node.start.value == 'new' and node.expression.start.value == "(" and node.expression.print_to_string().indexOf("require") != -1) args = node.expression.args text = "require" + "('" + args[0].value + "')" # console.log(text) handleRequireNode(text, args) console.log("second " + text) return true else return ) ) return r strEscapeMap = { '\b': '\\b', '\f': '\\f', '\n': '\\n', '\r': '\\r', '\t': '\\t', }; packageUtils.hexifyString = (str)-> r = "" if !str.length > 0 then return r for i in [0..str.length - 1] char = str[i]; if (strEscapeMap[char]) r += r[char]; else if ('\\' == char) r += '\\' + str[++i] else r += '\\x' + str.charCodeAt(i).toString(16); return r; packageUtils.deHexifyString = (str)-> return str.toString() packageUtils.getSourceHexified = (ast)-> hexify = (node)-> if (node instanceof UglifyJS.AST_String) text = node.getValue() hex = packageUtils.hexifyString(text); obj = _.extend({}, node); obj.value = hex return new UglifyJS.AST_String(obj); else return transformer = new UglifyJS.TreeTransformer(null, hexify); stream = new UglifyJS.OutputStream; stream.print_string = (str)-> return this.print('"' + str + '"') ast = ast.transform(transformer); ast.print(stream); return stream.toString() #packageUtils.replaceAll=(find, replace, str)-> # return str.replace(new RegExp(find, 'g'), replace); packageUtils.replaceRequireStatement = (textIn, orig, replacement)-> text = textIn isReplaced = false text = text.replace(orig, (token)-> (isReplaced = true;return replacement)) if !isReplaced withTheOtherQuotation = orig if withTheOtherQuotation.indexOf("'") != -1 withTheOtherQuotation = withTheOtherQuotation.replace(/[']/ig, '"') else withTheOtherQuotation = withTheOtherQuotation.replace(/["]/ig, "'") text = text.replace(withTheOtherQuotation, (token)-> (isReplaced = true;return replacement)) if !isReplaced throw new Error(orig + " was not replaced with " + replacement) return text packageUtils.countWords = (sentence)-> index = {} words = sentence .replace(/[.,?!;()"'-]/g, " ") .replace(/\s+/g, " ") .toLowerCase() .split(" "); words.forEach((word)-> if (!(index.hasOwnProperty(word))) index[word] = 0; index[word]++; ) return index # console.log([text,path.resolve(fileDir,pathOfModule),packageUtils.isNative(pathOfModule)].join(" | ")) #print_to_string({ beautify: false }).replace(/-/g, "_") AST_Assign node.left,right # return true; no descend
true
# #/*! # * node-uglifier # * Copyright (c) 2014 PI:NAME:<NAME>END_PI # * MIT Licensed # * # */ # fsExtra = require('fs-extra'); fs = require('fs'); UglifyJS = require('uglify-js-harmony') path = require('path') _ = require('underscore') packageUtils = module.exports # Check if `module` is a native module (like `net` or `tty`). packageUtils.isNative = (module)-> try return require.resolve(module) == module; catch err return false; packageUtils.readFile = (pathAbs, encoding = 'utf8')-> options = {encoding} return fs.readFileSync(pathAbs, options) packageUtils.getAst = (code)-> return UglifyJS.parse(code) #absolulte file path packageUtils.getMatchingFiles = (rootPath, dirAndFileArray)-> r = [] rootDir = if fs.lstatSync(rootPath).isDirectory() then path.resolve(rootPath) else path.dirname(path.resolve(rootPath)) for dirOrFile in dirAndFileArray destination = path.resolve(rootDir, dirOrFile) try filestats = fs.lstatSync(destination) catch me #probably missing extension, file not found filestats = null if filestats and filestats.isDirectory() #we have directory fs.readdirSync(destination).reduce(((prev, curr)-> prev.push(path.join(destination, curr));return prev), r) else if path.extname(destination) == "" fileName = path.basename(destination) fs.readdirSync(path.dirname(destination)).filter((fileNameLoc)-> fileNameLoc.indexOf(fileName) != -1).reduce(((prev, curr)-> prev.push(path.join(destination, curr)); return prev), r) else r.push(destination) return r packageUtils.getIfNonNativeNotFilteredNonNpm = (fileAbs, filters, possibleExtensions)-> #if path can be resolved and it is file than it is non native, non npm r = null if path.extname(fileAbs) == "" existingExtensions = possibleExtensions.filter((ext)->return fs.existsSync(fileAbs + "." + ext)) if existingExtensions.length > 1 then throw new Error(" multiple matching extensions problem for " + fileAbs) r = if existingExtensions.length == 1 then fileAbs + "." + existingExtensions[0] else null else r = if fs.existsSync(fileAbs) then fileAbs else null if r if filters.filter((fFile)->return path.normalize(fFile) == path.normalize(r)).length > 0 r = null; console.log(fileAbs + " was filtered ") return r packageUtils.walkExpressions=(astNode,parentNode,depth)-> if depth>5 then return null if astNode.name=="require" return parentNode?.args || astNode.args else if astNode.expression? return packageUtils.walkExpressions(astNode.expression,astNode,depth+1) #assume no directory is native module #returns the file path of modules if file exists #if no extension specified first existing possibleExtensions is used packageUtils.getRequireStatements = (ast, file, possibleExtensions = ["js", "coffee"], packNodeModules = false)-> r = [] fileDir = path.dirname(file) handleRequireNode = (text, args)-> pathOfModuleRaw = args[0].value if !pathOfModuleRaw? then throw new Error("probably dynamic") #has / or \ in the string hasPathInIt = (!_.isEmpty(pathOfModuleRaw.match("/")) || !_.isEmpty(pathOfModuleRaw.match(/\\/))) if hasPathInIt #it is not a module, do nothing else if packNodeModules #find node_module directory, than main in package json if no index.js found pathOfModuleRaw=require.resolve(pathOfModuleRaw) else #it is module and not packed return false pathOfModuleLoc = path.resolve(fileDir, pathOfModuleRaw) try pathOfModuleLocStats =fs.lstatSync(pathOfModuleLoc) catch me; if (pathOfModuleLocStats and pathOfModuleLocStats.isDirectory()) pathOfModuleLoc=path.resolve(pathOfModuleLoc, "index") #if path can be resolved and it is file than it is non native, non npm pathOfModule = packageUtils.getIfNonNativeNotFilteredNonNpm(pathOfModuleLoc, [], possibleExtensions) rs = {text, path: pathOfModule} if pathOfModule r.push(rs) ast.walk(new UglifyJS.TreeWalker( (node)-> if (node instanceof UglifyJS.AST_Call) && (node.start.value == 'require' || (node.start.value == 'new' and node.expression.print_to_string() == "require")) text = node.print_to_string({beautify: false}) # console.log(text) #expression argument takes precedence over the first argument of require requireArgs = node?.expression?.args walkedArgs=packageUtils.walkExpressions(node,null,1) if _.isEmpty(requireArgs) requireArgs = node.args try # if args.length != 1 then # throw new Error ("in file: " + file + " require supposed to have 1 argument: " + text) if requireArgs.length != 1 or !handleRequireNode(text, requireArgs) and !_.isEmpty(walkedArgs) text2="require('#{walkedArgs[0].value}')" handleRequireNode(text2, walkedArgs) catch me console.log("Warning!:") console.log("unhandled require type in file: " + file + " the problematic statement: " + text + " probably something fancy going on! " + " the error: " + me.message) return true else if (node instanceof UglifyJS.AST_Call) && (node.start.value == 'new' and node.expression.start.value == "(" and node.expression.print_to_string().indexOf("require") != -1) args = node.expression.args text = "require" + "('" + args[0].value + "')" # console.log(text) handleRequireNode(text, args) console.log("second " + text) return true else return ) ) return r strEscapeMap = { '\b': '\\b', '\f': '\\f', '\n': '\\n', '\r': '\\r', '\t': '\\t', }; packageUtils.hexifyString = (str)-> r = "" if !str.length > 0 then return r for i in [0..str.length - 1] char = str[i]; if (strEscapeMap[char]) r += r[char]; else if ('\\' == char) r += '\\' + str[++i] else r += '\\x' + str.charCodeAt(i).toString(16); return r; packageUtils.deHexifyString = (str)-> return str.toString() packageUtils.getSourceHexified = (ast)-> hexify = (node)-> if (node instanceof UglifyJS.AST_String) text = node.getValue() hex = packageUtils.hexifyString(text); obj = _.extend({}, node); obj.value = hex return new UglifyJS.AST_String(obj); else return transformer = new UglifyJS.TreeTransformer(null, hexify); stream = new UglifyJS.OutputStream; stream.print_string = (str)-> return this.print('"' + str + '"') ast = ast.transform(transformer); ast.print(stream); return stream.toString() #packageUtils.replaceAll=(find, replace, str)-> # return str.replace(new RegExp(find, 'g'), replace); packageUtils.replaceRequireStatement = (textIn, orig, replacement)-> text = textIn isReplaced = false text = text.replace(orig, (token)-> (isReplaced = true;return replacement)) if !isReplaced withTheOtherQuotation = orig if withTheOtherQuotation.indexOf("'") != -1 withTheOtherQuotation = withTheOtherQuotation.replace(/[']/ig, '"') else withTheOtherQuotation = withTheOtherQuotation.replace(/["]/ig, "'") text = text.replace(withTheOtherQuotation, (token)-> (isReplaced = true;return replacement)) if !isReplaced throw new Error(orig + " was not replaced with " + replacement) return text packageUtils.countWords = (sentence)-> index = {} words = sentence .replace(/[.,?!;()"'-]/g, " ") .replace(/\s+/g, " ") .toLowerCase() .split(" "); words.forEach((word)-> if (!(index.hasOwnProperty(word))) index[word] = 0; index[word]++; ) return index # console.log([text,path.resolve(fileDir,pathOfModule),packageUtils.isNative(pathOfModule)].join(" | ")) #print_to_string({ beautify: false }).replace(/-/g, "_") AST_Assign node.left,right # return true; no descend
[ { "context": "ow(\"Argument must be a number. https://github.com/mojotech/pioneer/blob/master/docs/list.md#at\")\n\n @When /^", "end": 1826, "score": 0.9995712637901306, "start": 1818, "tag": "USERNAME", "value": "mojotech" }, { "context": ".toUpperCase()\n })\n .should.eventu...
test/integration/steps/list_steps.coffee
piretmadrus/newPioneer
203
_ = require('lodash') expect = require('chai').expect module.exports = -> @Given /^I should see "([^"]*)" items in a list$/, (count) -> new @Widgets.List().items() .should.eventually.have.length(count) @Given /^I should get the identity "([^"]*)" for the item with a super-hero class$/, (identity)-> new @Widgets.List().items().then (items)-> for item in items item.getIdentity?() .should.eventually.equal(identity) @Given /^I should see "([^"]*)" in position "([^"]*)" of the list$/, (content, position) -> new @Widgets.List().at(+position-1) .then (item) -> item.find() .then (elm) -> elm.getText() .should.eventually.equal(content) @Given /^I should see html "([^"]*)" in position "([^"]*)" of the list$/, (content, position) -> new @Widgets.List().at(+position-1) .then (item) -> item.getHtml() .should.eventually.equal(content) @When /^I filter by "([^"]*)" I should see "([^"]*)" element$/, (string, count) -> new @Widgets.List().filterBy(string) .should.eventually.have.length(count) @Then /^I should see the following list:$/, (table) -> new @Widgets.List().toArray() .should.eventually.eql(_.flatten(table.raw())) @Then /^I should see stuff$/, (table) -> new @Widgets.List().toHtml() @When /^I find with "([^"]*)" I should see "([^"]*)"$/, (string, content) -> new @Widgets.List().findBy(string) .then (item) -> item.getHtml() .should.eventually.eql(content) @When /^I call length I should receive (\d+)$/, (expectedLength) -> new @Widgets.List().length() .should.eventually.eql(+expectedLength) @When /^I call at with a string I should get an error$/, -> expect( => new @Widgets.List().at("0") ) .to.throw("Argument must be a number. https://github.com/mojotech/pioneer/blob/master/docs/list.md#at") @When /^I find the "([^"]*)" within "([^"]*)" I should see (\d+) items$/, (itemSelector, root, count) -> new @Widgets.List({ root: root itemSelector: itemSelector }).items().should.eventually.have.length(+count) @When /^I find the "([^"]*)" child "([^"]*)" within "([^"]*)" and then I read the "([^"]*)" I should see "([^"]*)"$/, (index, itemSelector, root, childSelector, value) -> new @Widgets.List({ root: root itemSelector: itemSelector }) .at(+index-1) .then (child) -> child.read(childSelector).should.eventually.eql(value) @When /^I read at the "([^"]*)" index of ul I should see "([^"]*)"$/, (index, expected) -> new @Widgets.List() .readAt(+index-1) .should.eventually.eql(expected) @When /^I read at the "([^"]*)" child "([^"]*)" within "([^"]*)" inside "([^"]*)" I should see "([^"]*)"$/, (index, itemSelector, root, childSelector, expected) -> new @Widgets.List({ root: root itemSelector: itemSelector }) .readAt({ index: +index-1, selector: childSelector }) .should.eventually.eql(expected) @When /^I click on the "([^"]*)" child of "([^"]*)" I should read "([^"]*)"$/, (index, rootSelector, expected) -> _this = this new @Widgets.List({ root: rootSelector }) .at(index - 1) .then (item) -> item.click() .then -> new _this.Widget({ root: '#onSubmit' }) .read() .should.eventually.eql(expected) @When /^I click at the "([^"]*)" index of "([^"]*)" I should read "([^"]*)"$/, (index, selector, expected) -> _this = this new @Widgets.List({ root: selector }) .clickAt(index - 1) .then -> new _this.Widget({ root: '#onSubmit' }) .read() .should.eventually.eql(expected) @When /^I click at the "([^"]*)" index with selector "([^"]*)" I should read "([^"]*)"$/, (index, selector, expected) -> _this = this new @Widgets.List() .clickAt({ index: index - 1, selector: selector }) .then -> new _this.Widget({ root: '#onSubmit' }) .read() .should.eventually.eql(expected) @Given /^I should be able to read and transform a list item at an index$/, -> new @Widgets.List() .readAt({ index: 4, transformer: (val) -> val.toUpperCase() }) .should.eventually.eql("JOHN CRICHTON") @Given /^I should be able to read with a subselector and transform an item at an index$/, -> new @Widgets.List() .readAt({ index: 4, selector: "p", transformer: (val) -> val.toUpperCase() }) .should.eventually.eql("JOHN CRICHTON") @When /^I click on each item in the list$/, -> new @Widgets.List({root: "ul.click-list"}).clickEach() @Then /^I should see that each list item was clicked$/, -> new @Widgets.List({root: "ul.click-list"}).map((item) -> item.read() ).should.eventually.eql(["clicked", "clicked", "clicked"]) @Given /^I can invoke click on each widget in the list$/, -> new @Widgets.List({root: "ul.click-list"}).invoke('click') @Given /^I can invoke click on each widget in the list with a method$/, -> new @Widgets.List({root: "ul.click-list"}).invoke(@Widget::click) @Given /^I can invoke read on each widget in the list with a transformer and selector$/, -> new @Widgets.List({ root: ".nested", itemSelector: "span" }) .invoke({ method: "read", arguments: [{ transformer: (val) -> return val.toUpperCase() selector: "p" }] }).should.eventually.eql(["ORC", "HUMAN", "PROTOSS"]) @Given /^I can check the visibility on a list's items$/, -> new @Widgets.List({ root: ".nested", itemSelector: "span" }) .map (w) -> w.isVisible() .should.eventually .eql([true, true, true])
51216
_ = require('lodash') expect = require('chai').expect module.exports = -> @Given /^I should see "([^"]*)" items in a list$/, (count) -> new @Widgets.List().items() .should.eventually.have.length(count) @Given /^I should get the identity "([^"]*)" for the item with a super-hero class$/, (identity)-> new @Widgets.List().items().then (items)-> for item in items item.getIdentity?() .should.eventually.equal(identity) @Given /^I should see "([^"]*)" in position "([^"]*)" of the list$/, (content, position) -> new @Widgets.List().at(+position-1) .then (item) -> item.find() .then (elm) -> elm.getText() .should.eventually.equal(content) @Given /^I should see html "([^"]*)" in position "([^"]*)" of the list$/, (content, position) -> new @Widgets.List().at(+position-1) .then (item) -> item.getHtml() .should.eventually.equal(content) @When /^I filter by "([^"]*)" I should see "([^"]*)" element$/, (string, count) -> new @Widgets.List().filterBy(string) .should.eventually.have.length(count) @Then /^I should see the following list:$/, (table) -> new @Widgets.List().toArray() .should.eventually.eql(_.flatten(table.raw())) @Then /^I should see stuff$/, (table) -> new @Widgets.List().toHtml() @When /^I find with "([^"]*)" I should see "([^"]*)"$/, (string, content) -> new @Widgets.List().findBy(string) .then (item) -> item.getHtml() .should.eventually.eql(content) @When /^I call length I should receive (\d+)$/, (expectedLength) -> new @Widgets.List().length() .should.eventually.eql(+expectedLength) @When /^I call at with a string I should get an error$/, -> expect( => new @Widgets.List().at("0") ) .to.throw("Argument must be a number. https://github.com/mojotech/pioneer/blob/master/docs/list.md#at") @When /^I find the "([^"]*)" within "([^"]*)" I should see (\d+) items$/, (itemSelector, root, count) -> new @Widgets.List({ root: root itemSelector: itemSelector }).items().should.eventually.have.length(+count) @When /^I find the "([^"]*)" child "([^"]*)" within "([^"]*)" and then I read the "([^"]*)" I should see "([^"]*)"$/, (index, itemSelector, root, childSelector, value) -> new @Widgets.List({ root: root itemSelector: itemSelector }) .at(+index-1) .then (child) -> child.read(childSelector).should.eventually.eql(value) @When /^I read at the "([^"]*)" index of ul I should see "([^"]*)"$/, (index, expected) -> new @Widgets.List() .readAt(+index-1) .should.eventually.eql(expected) @When /^I read at the "([^"]*)" child "([^"]*)" within "([^"]*)" inside "([^"]*)" I should see "([^"]*)"$/, (index, itemSelector, root, childSelector, expected) -> new @Widgets.List({ root: root itemSelector: itemSelector }) .readAt({ index: +index-1, selector: childSelector }) .should.eventually.eql(expected) @When /^I click on the "([^"]*)" child of "([^"]*)" I should read "([^"]*)"$/, (index, rootSelector, expected) -> _this = this new @Widgets.List({ root: rootSelector }) .at(index - 1) .then (item) -> item.click() .then -> new _this.Widget({ root: '#onSubmit' }) .read() .should.eventually.eql(expected) @When /^I click at the "([^"]*)" index of "([^"]*)" I should read "([^"]*)"$/, (index, selector, expected) -> _this = this new @Widgets.List({ root: selector }) .clickAt(index - 1) .then -> new _this.Widget({ root: '#onSubmit' }) .read() .should.eventually.eql(expected) @When /^I click at the "([^"]*)" index with selector "([^"]*)" I should read "([^"]*)"$/, (index, selector, expected) -> _this = this new @Widgets.List() .clickAt({ index: index - 1, selector: selector }) .then -> new _this.Widget({ root: '#onSubmit' }) .read() .should.eventually.eql(expected) @Given /^I should be able to read and transform a list item at an index$/, -> new @Widgets.List() .readAt({ index: 4, transformer: (val) -> val.toUpperCase() }) .should.eventually.eql("<NAME>") @Given /^I should be able to read with a subselector and transform an item at an index$/, -> new @Widgets.List() .readAt({ index: 4, selector: "p", transformer: (val) -> val.toUpperCase() }) .should.eventually.eql("<NAME>") @When /^I click on each item in the list$/, -> new @Widgets.List({root: "ul.click-list"}).clickEach() @Then /^I should see that each list item was clicked$/, -> new @Widgets.List({root: "ul.click-list"}).map((item) -> item.read() ).should.eventually.eql(["clicked", "clicked", "clicked"]) @Given /^I can invoke click on each widget in the list$/, -> new @Widgets.List({root: "ul.click-list"}).invoke('click') @Given /^I can invoke click on each widget in the list with a method$/, -> new @Widgets.List({root: "ul.click-list"}).invoke(@Widget::click) @Given /^I can invoke read on each widget in the list with a transformer and selector$/, -> new @Widgets.List({ root: ".nested", itemSelector: "span" }) .invoke({ method: "read", arguments: [{ transformer: (val) -> return val.toUpperCase() selector: "p" }] }).should.eventually.eql(["ORC", "HUMAN", "PROTOSS"]) @Given /^I can check the visibility on a list's items$/, -> new @Widgets.List({ root: ".nested", itemSelector: "span" }) .map (w) -> w.isVisible() .should.eventually .eql([true, true, true])
true
_ = require('lodash') expect = require('chai').expect module.exports = -> @Given /^I should see "([^"]*)" items in a list$/, (count) -> new @Widgets.List().items() .should.eventually.have.length(count) @Given /^I should get the identity "([^"]*)" for the item with a super-hero class$/, (identity)-> new @Widgets.List().items().then (items)-> for item in items item.getIdentity?() .should.eventually.equal(identity) @Given /^I should see "([^"]*)" in position "([^"]*)" of the list$/, (content, position) -> new @Widgets.List().at(+position-1) .then (item) -> item.find() .then (elm) -> elm.getText() .should.eventually.equal(content) @Given /^I should see html "([^"]*)" in position "([^"]*)" of the list$/, (content, position) -> new @Widgets.List().at(+position-1) .then (item) -> item.getHtml() .should.eventually.equal(content) @When /^I filter by "([^"]*)" I should see "([^"]*)" element$/, (string, count) -> new @Widgets.List().filterBy(string) .should.eventually.have.length(count) @Then /^I should see the following list:$/, (table) -> new @Widgets.List().toArray() .should.eventually.eql(_.flatten(table.raw())) @Then /^I should see stuff$/, (table) -> new @Widgets.List().toHtml() @When /^I find with "([^"]*)" I should see "([^"]*)"$/, (string, content) -> new @Widgets.List().findBy(string) .then (item) -> item.getHtml() .should.eventually.eql(content) @When /^I call length I should receive (\d+)$/, (expectedLength) -> new @Widgets.List().length() .should.eventually.eql(+expectedLength) @When /^I call at with a string I should get an error$/, -> expect( => new @Widgets.List().at("0") ) .to.throw("Argument must be a number. https://github.com/mojotech/pioneer/blob/master/docs/list.md#at") @When /^I find the "([^"]*)" within "([^"]*)" I should see (\d+) items$/, (itemSelector, root, count) -> new @Widgets.List({ root: root itemSelector: itemSelector }).items().should.eventually.have.length(+count) @When /^I find the "([^"]*)" child "([^"]*)" within "([^"]*)" and then I read the "([^"]*)" I should see "([^"]*)"$/, (index, itemSelector, root, childSelector, value) -> new @Widgets.List({ root: root itemSelector: itemSelector }) .at(+index-1) .then (child) -> child.read(childSelector).should.eventually.eql(value) @When /^I read at the "([^"]*)" index of ul I should see "([^"]*)"$/, (index, expected) -> new @Widgets.List() .readAt(+index-1) .should.eventually.eql(expected) @When /^I read at the "([^"]*)" child "([^"]*)" within "([^"]*)" inside "([^"]*)" I should see "([^"]*)"$/, (index, itemSelector, root, childSelector, expected) -> new @Widgets.List({ root: root itemSelector: itemSelector }) .readAt({ index: +index-1, selector: childSelector }) .should.eventually.eql(expected) @When /^I click on the "([^"]*)" child of "([^"]*)" I should read "([^"]*)"$/, (index, rootSelector, expected) -> _this = this new @Widgets.List({ root: rootSelector }) .at(index - 1) .then (item) -> item.click() .then -> new _this.Widget({ root: '#onSubmit' }) .read() .should.eventually.eql(expected) @When /^I click at the "([^"]*)" index of "([^"]*)" I should read "([^"]*)"$/, (index, selector, expected) -> _this = this new @Widgets.List({ root: selector }) .clickAt(index - 1) .then -> new _this.Widget({ root: '#onSubmit' }) .read() .should.eventually.eql(expected) @When /^I click at the "([^"]*)" index with selector "([^"]*)" I should read "([^"]*)"$/, (index, selector, expected) -> _this = this new @Widgets.List() .clickAt({ index: index - 1, selector: selector }) .then -> new _this.Widget({ root: '#onSubmit' }) .read() .should.eventually.eql(expected) @Given /^I should be able to read and transform a list item at an index$/, -> new @Widgets.List() .readAt({ index: 4, transformer: (val) -> val.toUpperCase() }) .should.eventually.eql("PI:NAME:<NAME>END_PI") @Given /^I should be able to read with a subselector and transform an item at an index$/, -> new @Widgets.List() .readAt({ index: 4, selector: "p", transformer: (val) -> val.toUpperCase() }) .should.eventually.eql("PI:NAME:<NAME>END_PI") @When /^I click on each item in the list$/, -> new @Widgets.List({root: "ul.click-list"}).clickEach() @Then /^I should see that each list item was clicked$/, -> new @Widgets.List({root: "ul.click-list"}).map((item) -> item.read() ).should.eventually.eql(["clicked", "clicked", "clicked"]) @Given /^I can invoke click on each widget in the list$/, -> new @Widgets.List({root: "ul.click-list"}).invoke('click') @Given /^I can invoke click on each widget in the list with a method$/, -> new @Widgets.List({root: "ul.click-list"}).invoke(@Widget::click) @Given /^I can invoke read on each widget in the list with a transformer and selector$/, -> new @Widgets.List({ root: ".nested", itemSelector: "span" }) .invoke({ method: "read", arguments: [{ transformer: (val) -> return val.toUpperCase() selector: "p" }] }).should.eventually.eql(["ORC", "HUMAN", "PROTOSS"]) @Given /^I can check the visibility on a list's items$/, -> new @Widgets.List({ root: ".nested", itemSelector: "span" }) .map (w) -> w.isVisible() .should.eventually .eql([true, true, true])
[ { "context": "m)\n continue unless contact.email\n key = contact.toString().trim().toLowerCase()\n continue if seen[key]\n seen[key] = tru", "end": 6634, "score": 0.990612268447876, "start": 6595, "tag": "KEY", "value": "contact.toString().trim().toLowerCase()" }, { ...
app/src/flux/models/message.coffee
immershy/nodemail
0
_ = require 'underscore' moment = require 'moment' File = require './file' Utils = require './utils' Event = require './event' Category = require './category' Contact = require './contact' Attributes = require '../attributes' AccountStore = require '../stores/account-store' ModelWithMetadata = require './model-with-metadata' ### Public: The Message model represents a Message object served by the Nylas Platform API. For more information about Messages on the Nylas Platform, read the [Messages API Documentation](https://nylas.com/docs/api#messages) Messages are a sub-object of threads. The content of a message is immutable (with the exception being drafts). Nylas does not support operations such as move or delete on individual messages; those operations should be performed on the message’s thread. All messages are part of a thread, even if that thread has only one message. ## Attributes `to`: {AttributeCollection} A collection of {Contact} objects `cc`: {AttributeCollection} A collection of {Contact} objects `bcc`: {AttributeCollection} A collection of {Contact} objects `from`: {AttributeCollection} A collection of {Contact} objects. `replyTo`: {AttributeCollection} A collection of {Contact} objects. `date`: {AttributeDateTime} When the message was delivered. Queryable. `subject`: {AttributeString} The subject of the thread. Queryable. `snippet`: {AttributeString} A short, 140-character plain-text summary of the message body. `unread`: {AttributeBoolean} True if the message is unread. Queryable. `starred`: {AttributeBoolean} True if the message is starred. Queryable. `draft`: {AttributeBoolean} True if the message is a draft. Queryable. `version`: {AttributeNumber} The version number of the message. Message versions are used for drafts, and increment when attributes are changed. `files`: {AttributeCollection} A set of {File} models representing the attachments on this thread. `body`: {AttributeJoinedData} The HTML body of the message. You must specifically request this attribute when querying for a Message using the {{AttributeJoinedData::include}} method. `pristine`: {AttributeBoolean} True if the message is a draft which has not been edited since it was created. `threadId`: {AttributeString} The ID of the Message's parent {Thread}. Queryable. `replyToMessageId`: {AttributeString} The ID of a {Message} that this message is in reply to. This class also inherits attributes from {Model} Section: Models ### class Message extends ModelWithMetadata @attributes: _.extend {}, ModelWithMetadata.attributes, 'to': Attributes.Collection modelKey: 'to' itemClass: Contact 'cc': Attributes.Collection modelKey: 'cc' itemClass: Contact 'bcc': Attributes.Collection modelKey: 'bcc' itemClass: Contact 'from': Attributes.Collection modelKey: 'from' itemClass: Contact 'replyTo': Attributes.Collection modelKey: 'replyTo' jsonKey: 'reply_to' itemClass: Contact 'date': Attributes.DateTime queryable: true modelKey: 'date' 'body': Attributes.JoinedData modelTable: 'MessageBody' modelKey: 'body' 'files': Attributes.Collection modelKey: 'files' itemClass: File 'uploads': Attributes.Object queryable: false modelKey: 'uploads' 'unread': Attributes.Boolean queryable: true modelKey: 'unread' 'events': Attributes.Collection modelKey: 'events' itemClass: Event 'starred': Attributes.Boolean queryable: true modelKey: 'starred' 'snippet': Attributes.String modelKey: 'snippet' 'threadId': Attributes.ServerId queryable: true modelKey: 'threadId' jsonKey: 'thread_id' 'subject': Attributes.String modelKey: 'subject' 'draft': Attributes.Boolean modelKey: 'draft' jsonKey: 'draft' queryable: true 'pristine': Attributes.Boolean modelKey: 'pristine' jsonKey: 'pristine' queryable: false 'version': Attributes.Number modelKey: 'version' queryable: true 'replyToMessageId': Attributes.ServerId modelKey: 'replyToMessageId' jsonKey: 'reply_to_message_id' 'categories': Attributes.Collection modelKey: 'categories' itemClass: Category @naturalSortOrder: -> Message.attributes.date.ascending() @additionalSQLiteConfig: setup: -> [ # For thread view 'CREATE INDEX IF NOT EXISTS MessageListThreadIndex ON Message(thread_id, date ASC)', # For draft lookups 'CREATE UNIQUE INDEX IF NOT EXISTS MessageDraftIndex ON Message(client_id)', # Partial indexes for draft 'CREATE INDEX IF NOT EXISTS MessageListDraftIndex ON Message(account_id, date DESC) WHERE draft = 1', 'CREATE INDEX IF NOT EXISTS MessageListUnifiedDraftIndex ON Message(date DESC) WHERE draft = 1', # MessageBody lookups 'CREATE UNIQUE INDEX IF NOT EXISTS MessageBodyIndex ON MessageBody(id)' ] constructor: -> super @subject ||= "" @to ||= [] @cc ||= [] @bcc ||= [] @from ||= [] @replyTo ||= [] @files ||= [] @uploads ||= [] @events ||= [] @categories ||= [] @ toJSON: (options) -> json = super(options) json.file_ids = @fileIds() json.object = 'draft' if @draft json.event_id = @events[0].serverId if (@events and @events.length) json fromJSON: (json={}) -> super (json) # Only change the `draft` bit if the incoming json has an `object` # property. Because of `DraftChangeSet`, it's common for incoming json # to be an empty hash. In this case we want to leave the pre-existing # draft bit alone. if json.object? @draft = (json.object is 'draft') if json['folder'] @categories = @constructor.attributes.categories.fromJSON([json['folder']]) else if json['labels'] @categories = @constructor.attributes.categories.fromJSON(json['labels']) for attr in ['to', 'from', 'cc', 'bcc', 'files', 'categories'] values = @[attr] continue unless values and values instanceof Array item.accountId = @accountId for item in values return @ canReplyAll: -> {to, cc} = @participantsForReplyAll() to.length > 1 or cc.length > 0 # Public: Returns a set of uniqued message participants by combining the # `to`, `cc`, and `from` fields. participants: -> seen = {} all = [] for contact in [].concat(@to, @cc, @from) continue unless contact.email key = contact.toString().trim().toLowerCase() continue if seen[key] seen[key] = true all.push(contact) all # Public: Returns a hash with `to` and `cc` keys for authoring a new draft in # "reply all" to this message. This method takes into account whether the # message is from the current user, and also looks at the replyTo field. participantsForReplyAll: -> excludedFroms = @from.map (c) -> Utils.toEquivalentEmailForm(c.email) excludeMeAndFroms = (cc) -> _.reject cc, (p) -> p.isMe() or _.contains(excludedFroms, Utils.toEquivalentEmailForm(p.email)) to = null cc = null if @isFromMe() to = @to cc = excludeMeAndFroms(@cc) else if @replyTo.length to = @replyTo else to = @from cc = excludeMeAndFroms([].concat(@to, @cc)) to = _.uniq to, (p) -> Utils.toEquivalentEmailForm(p.email) cc = _.uniq cc, (p) -> Utils.toEquivalentEmailForm(p.email) {to, cc} # Public: Returns a hash with `to` and `cc` keys for authoring a new draft in # "reply" to this message. This method takes into account whether the # message is from the current user, and also looks at the replyTo field. participantsForReply: -> to = [] cc = [] if @isFromMe() to = @to else if @replyTo.length to = @replyTo else to = @from to = _.uniq to, (p) -> Utils.toEquivalentEmailForm(p.email) {to, cc} # Public: Returns an {Array} of {File} IDs fileIds: -> _.map @files, (file) -> file.id # Public: Returns true if this message is from the current user's email # address. In the future, this method will take into account all of the # user's email addresses and accounts. isFromMe: -> @from[0]?.isMe() # Public: Returns a plaintext version of the message body using Chromium's # DOMParser. Use with care. plainTextBody: -> if (@body ? "").trim().length is 0 then return "" (new DOMParser()).parseFromString(@body, "text/html").body.innerText fromContact: -> @from?[0] ? new Contact(name: 'Unknown', email: 'Unknown') # Public: Returns the standard attribution line for this message, # localized for the current user. # ie "On Dec. 12th, 2015 at 4:00PM, Ben Gotow wrote:" replyAttributionLine: -> "On #{@formattedDate()}, #{@fromContact().toString()} wrote:" formattedDate: -> moment(@date).format("MMM D YYYY, [at] h:mm a") module.exports = Message
6098
_ = require 'underscore' moment = require 'moment' File = require './file' Utils = require './utils' Event = require './event' Category = require './category' Contact = require './contact' Attributes = require '../attributes' AccountStore = require '../stores/account-store' ModelWithMetadata = require './model-with-metadata' ### Public: The Message model represents a Message object served by the Nylas Platform API. For more information about Messages on the Nylas Platform, read the [Messages API Documentation](https://nylas.com/docs/api#messages) Messages are a sub-object of threads. The content of a message is immutable (with the exception being drafts). Nylas does not support operations such as move or delete on individual messages; those operations should be performed on the message’s thread. All messages are part of a thread, even if that thread has only one message. ## Attributes `to`: {AttributeCollection} A collection of {Contact} objects `cc`: {AttributeCollection} A collection of {Contact} objects `bcc`: {AttributeCollection} A collection of {Contact} objects `from`: {AttributeCollection} A collection of {Contact} objects. `replyTo`: {AttributeCollection} A collection of {Contact} objects. `date`: {AttributeDateTime} When the message was delivered. Queryable. `subject`: {AttributeString} The subject of the thread. Queryable. `snippet`: {AttributeString} A short, 140-character plain-text summary of the message body. `unread`: {AttributeBoolean} True if the message is unread. Queryable. `starred`: {AttributeBoolean} True if the message is starred. Queryable. `draft`: {AttributeBoolean} True if the message is a draft. Queryable. `version`: {AttributeNumber} The version number of the message. Message versions are used for drafts, and increment when attributes are changed. `files`: {AttributeCollection} A set of {File} models representing the attachments on this thread. `body`: {AttributeJoinedData} The HTML body of the message. You must specifically request this attribute when querying for a Message using the {{AttributeJoinedData::include}} method. `pristine`: {AttributeBoolean} True if the message is a draft which has not been edited since it was created. `threadId`: {AttributeString} The ID of the Message's parent {Thread}. Queryable. `replyToMessageId`: {AttributeString} The ID of a {Message} that this message is in reply to. This class also inherits attributes from {Model} Section: Models ### class Message extends ModelWithMetadata @attributes: _.extend {}, ModelWithMetadata.attributes, 'to': Attributes.Collection modelKey: 'to' itemClass: Contact 'cc': Attributes.Collection modelKey: 'cc' itemClass: Contact 'bcc': Attributes.Collection modelKey: 'bcc' itemClass: Contact 'from': Attributes.Collection modelKey: 'from' itemClass: Contact 'replyTo': Attributes.Collection modelKey: 'replyTo' jsonKey: 'reply_to' itemClass: Contact 'date': Attributes.DateTime queryable: true modelKey: 'date' 'body': Attributes.JoinedData modelTable: 'MessageBody' modelKey: 'body' 'files': Attributes.Collection modelKey: 'files' itemClass: File 'uploads': Attributes.Object queryable: false modelKey: 'uploads' 'unread': Attributes.Boolean queryable: true modelKey: 'unread' 'events': Attributes.Collection modelKey: 'events' itemClass: Event 'starred': Attributes.Boolean queryable: true modelKey: 'starred' 'snippet': Attributes.String modelKey: 'snippet' 'threadId': Attributes.ServerId queryable: true modelKey: 'threadId' jsonKey: 'thread_id' 'subject': Attributes.String modelKey: 'subject' 'draft': Attributes.Boolean modelKey: 'draft' jsonKey: 'draft' queryable: true 'pristine': Attributes.Boolean modelKey: 'pristine' jsonKey: 'pristine' queryable: false 'version': Attributes.Number modelKey: 'version' queryable: true 'replyToMessageId': Attributes.ServerId modelKey: 'replyToMessageId' jsonKey: 'reply_to_message_id' 'categories': Attributes.Collection modelKey: 'categories' itemClass: Category @naturalSortOrder: -> Message.attributes.date.ascending() @additionalSQLiteConfig: setup: -> [ # For thread view 'CREATE INDEX IF NOT EXISTS MessageListThreadIndex ON Message(thread_id, date ASC)', # For draft lookups 'CREATE UNIQUE INDEX IF NOT EXISTS MessageDraftIndex ON Message(client_id)', # Partial indexes for draft 'CREATE INDEX IF NOT EXISTS MessageListDraftIndex ON Message(account_id, date DESC) WHERE draft = 1', 'CREATE INDEX IF NOT EXISTS MessageListUnifiedDraftIndex ON Message(date DESC) WHERE draft = 1', # MessageBody lookups 'CREATE UNIQUE INDEX IF NOT EXISTS MessageBodyIndex ON MessageBody(id)' ] constructor: -> super @subject ||= "" @to ||= [] @cc ||= [] @bcc ||= [] @from ||= [] @replyTo ||= [] @files ||= [] @uploads ||= [] @events ||= [] @categories ||= [] @ toJSON: (options) -> json = super(options) json.file_ids = @fileIds() json.object = 'draft' if @draft json.event_id = @events[0].serverId if (@events and @events.length) json fromJSON: (json={}) -> super (json) # Only change the `draft` bit if the incoming json has an `object` # property. Because of `DraftChangeSet`, it's common for incoming json # to be an empty hash. In this case we want to leave the pre-existing # draft bit alone. if json.object? @draft = (json.object is 'draft') if json['folder'] @categories = @constructor.attributes.categories.fromJSON([json['folder']]) else if json['labels'] @categories = @constructor.attributes.categories.fromJSON(json['labels']) for attr in ['to', 'from', 'cc', 'bcc', 'files', 'categories'] values = @[attr] continue unless values and values instanceof Array item.accountId = @accountId for item in values return @ canReplyAll: -> {to, cc} = @participantsForReplyAll() to.length > 1 or cc.length > 0 # Public: Returns a set of uniqued message participants by combining the # `to`, `cc`, and `from` fields. participants: -> seen = {} all = [] for contact in [].concat(@to, @cc, @from) continue unless contact.email key = <KEY> continue if seen[key] seen[key] = true all.push(contact) all # Public: Returns a hash with `to` and `cc` keys for authoring a new draft in # "reply all" to this message. This method takes into account whether the # message is from the current user, and also looks at the replyTo field. participantsForReplyAll: -> excludedFroms = @from.map (c) -> Utils.toEquivalentEmailForm(c.email) excludeMeAndFroms = (cc) -> _.reject cc, (p) -> p.isMe() or _.contains(excludedFroms, Utils.toEquivalentEmailForm(p.email)) to = null cc = null if @isFromMe() to = @to cc = excludeMeAndFroms(@cc) else if @replyTo.length to = @replyTo else to = @from cc = excludeMeAndFroms([].concat(@to, @cc)) to = _.uniq to, (p) -> Utils.toEquivalentEmailForm(p.email) cc = _.uniq cc, (p) -> Utils.toEquivalentEmailForm(p.email) {to, cc} # Public: Returns a hash with `to` and `cc` keys for authoring a new draft in # "reply" to this message. This method takes into account whether the # message is from the current user, and also looks at the replyTo field. participantsForReply: -> to = [] cc = [] if @isFromMe() to = @to else if @replyTo.length to = @replyTo else to = @from to = _.uniq to, (p) -> Utils.toEquivalentEmailForm(p.email) {to, cc} # Public: Returns an {Array} of {File} IDs fileIds: -> _.map @files, (file) -> file.id # Public: Returns true if this message is from the current user's email # address. In the future, this method will take into account all of the # user's email addresses and accounts. isFromMe: -> @from[0]?.isMe() # Public: Returns a plaintext version of the message body using Chromium's # DOMParser. Use with care. plainTextBody: -> if (@body ? "").trim().length is 0 then return "" (new DOMParser()).parseFromString(@body, "text/html").body.innerText fromContact: -> @from?[0] ? new Contact(name: 'Unknown', email: 'Unknown') # Public: Returns the standard attribution line for this message, # localized for the current user. # ie "On Dec. 12th, 2015 at 4:00PM, <NAME> wrote:" replyAttributionLine: -> "On #{@formattedDate()}, #{@fromContact().toString()} wrote:" formattedDate: -> moment(@date).format("MMM D YYYY, [at] h:mm a") module.exports = Message
true
_ = require 'underscore' moment = require 'moment' File = require './file' Utils = require './utils' Event = require './event' Category = require './category' Contact = require './contact' Attributes = require '../attributes' AccountStore = require '../stores/account-store' ModelWithMetadata = require './model-with-metadata' ### Public: The Message model represents a Message object served by the Nylas Platform API. For more information about Messages on the Nylas Platform, read the [Messages API Documentation](https://nylas.com/docs/api#messages) Messages are a sub-object of threads. The content of a message is immutable (with the exception being drafts). Nylas does not support operations such as move or delete on individual messages; those operations should be performed on the message’s thread. All messages are part of a thread, even if that thread has only one message. ## Attributes `to`: {AttributeCollection} A collection of {Contact} objects `cc`: {AttributeCollection} A collection of {Contact} objects `bcc`: {AttributeCollection} A collection of {Contact} objects `from`: {AttributeCollection} A collection of {Contact} objects. `replyTo`: {AttributeCollection} A collection of {Contact} objects. `date`: {AttributeDateTime} When the message was delivered. Queryable. `subject`: {AttributeString} The subject of the thread. Queryable. `snippet`: {AttributeString} A short, 140-character plain-text summary of the message body. `unread`: {AttributeBoolean} True if the message is unread. Queryable. `starred`: {AttributeBoolean} True if the message is starred. Queryable. `draft`: {AttributeBoolean} True if the message is a draft. Queryable. `version`: {AttributeNumber} The version number of the message. Message versions are used for drafts, and increment when attributes are changed. `files`: {AttributeCollection} A set of {File} models representing the attachments on this thread. `body`: {AttributeJoinedData} The HTML body of the message. You must specifically request this attribute when querying for a Message using the {{AttributeJoinedData::include}} method. `pristine`: {AttributeBoolean} True if the message is a draft which has not been edited since it was created. `threadId`: {AttributeString} The ID of the Message's parent {Thread}. Queryable. `replyToMessageId`: {AttributeString} The ID of a {Message} that this message is in reply to. This class also inherits attributes from {Model} Section: Models ### class Message extends ModelWithMetadata @attributes: _.extend {}, ModelWithMetadata.attributes, 'to': Attributes.Collection modelKey: 'to' itemClass: Contact 'cc': Attributes.Collection modelKey: 'cc' itemClass: Contact 'bcc': Attributes.Collection modelKey: 'bcc' itemClass: Contact 'from': Attributes.Collection modelKey: 'from' itemClass: Contact 'replyTo': Attributes.Collection modelKey: 'replyTo' jsonKey: 'reply_to' itemClass: Contact 'date': Attributes.DateTime queryable: true modelKey: 'date' 'body': Attributes.JoinedData modelTable: 'MessageBody' modelKey: 'body' 'files': Attributes.Collection modelKey: 'files' itemClass: File 'uploads': Attributes.Object queryable: false modelKey: 'uploads' 'unread': Attributes.Boolean queryable: true modelKey: 'unread' 'events': Attributes.Collection modelKey: 'events' itemClass: Event 'starred': Attributes.Boolean queryable: true modelKey: 'starred' 'snippet': Attributes.String modelKey: 'snippet' 'threadId': Attributes.ServerId queryable: true modelKey: 'threadId' jsonKey: 'thread_id' 'subject': Attributes.String modelKey: 'subject' 'draft': Attributes.Boolean modelKey: 'draft' jsonKey: 'draft' queryable: true 'pristine': Attributes.Boolean modelKey: 'pristine' jsonKey: 'pristine' queryable: false 'version': Attributes.Number modelKey: 'version' queryable: true 'replyToMessageId': Attributes.ServerId modelKey: 'replyToMessageId' jsonKey: 'reply_to_message_id' 'categories': Attributes.Collection modelKey: 'categories' itemClass: Category @naturalSortOrder: -> Message.attributes.date.ascending() @additionalSQLiteConfig: setup: -> [ # For thread view 'CREATE INDEX IF NOT EXISTS MessageListThreadIndex ON Message(thread_id, date ASC)', # For draft lookups 'CREATE UNIQUE INDEX IF NOT EXISTS MessageDraftIndex ON Message(client_id)', # Partial indexes for draft 'CREATE INDEX IF NOT EXISTS MessageListDraftIndex ON Message(account_id, date DESC) WHERE draft = 1', 'CREATE INDEX IF NOT EXISTS MessageListUnifiedDraftIndex ON Message(date DESC) WHERE draft = 1', # MessageBody lookups 'CREATE UNIQUE INDEX IF NOT EXISTS MessageBodyIndex ON MessageBody(id)' ] constructor: -> super @subject ||= "" @to ||= [] @cc ||= [] @bcc ||= [] @from ||= [] @replyTo ||= [] @files ||= [] @uploads ||= [] @events ||= [] @categories ||= [] @ toJSON: (options) -> json = super(options) json.file_ids = @fileIds() json.object = 'draft' if @draft json.event_id = @events[0].serverId if (@events and @events.length) json fromJSON: (json={}) -> super (json) # Only change the `draft` bit if the incoming json has an `object` # property. Because of `DraftChangeSet`, it's common for incoming json # to be an empty hash. In this case we want to leave the pre-existing # draft bit alone. if json.object? @draft = (json.object is 'draft') if json['folder'] @categories = @constructor.attributes.categories.fromJSON([json['folder']]) else if json['labels'] @categories = @constructor.attributes.categories.fromJSON(json['labels']) for attr in ['to', 'from', 'cc', 'bcc', 'files', 'categories'] values = @[attr] continue unless values and values instanceof Array item.accountId = @accountId for item in values return @ canReplyAll: -> {to, cc} = @participantsForReplyAll() to.length > 1 or cc.length > 0 # Public: Returns a set of uniqued message participants by combining the # `to`, `cc`, and `from` fields. participants: -> seen = {} all = [] for contact in [].concat(@to, @cc, @from) continue unless contact.email key = PI:KEY:<KEY>END_PI continue if seen[key] seen[key] = true all.push(contact) all # Public: Returns a hash with `to` and `cc` keys for authoring a new draft in # "reply all" to this message. This method takes into account whether the # message is from the current user, and also looks at the replyTo field. participantsForReplyAll: -> excludedFroms = @from.map (c) -> Utils.toEquivalentEmailForm(c.email) excludeMeAndFroms = (cc) -> _.reject cc, (p) -> p.isMe() or _.contains(excludedFroms, Utils.toEquivalentEmailForm(p.email)) to = null cc = null if @isFromMe() to = @to cc = excludeMeAndFroms(@cc) else if @replyTo.length to = @replyTo else to = @from cc = excludeMeAndFroms([].concat(@to, @cc)) to = _.uniq to, (p) -> Utils.toEquivalentEmailForm(p.email) cc = _.uniq cc, (p) -> Utils.toEquivalentEmailForm(p.email) {to, cc} # Public: Returns a hash with `to` and `cc` keys for authoring a new draft in # "reply" to this message. This method takes into account whether the # message is from the current user, and also looks at the replyTo field. participantsForReply: -> to = [] cc = [] if @isFromMe() to = @to else if @replyTo.length to = @replyTo else to = @from to = _.uniq to, (p) -> Utils.toEquivalentEmailForm(p.email) {to, cc} # Public: Returns an {Array} of {File} IDs fileIds: -> _.map @files, (file) -> file.id # Public: Returns true if this message is from the current user's email # address. In the future, this method will take into account all of the # user's email addresses and accounts. isFromMe: -> @from[0]?.isMe() # Public: Returns a plaintext version of the message body using Chromium's # DOMParser. Use with care. plainTextBody: -> if (@body ? "").trim().length is 0 then return "" (new DOMParser()).parseFromString(@body, "text/html").body.innerText fromContact: -> @from?[0] ? new Contact(name: 'Unknown', email: 'Unknown') # Public: Returns the standard attribution line for this message, # localized for the current user. # ie "On Dec. 12th, 2015 at 4:00PM, PI:NAME:<NAME>END_PI wrote:" replyAttributionLine: -> "On #{@formattedDate()}, #{@fromContact().toString()} wrote:" formattedDate: -> moment(@date).format("MMM D YYYY, [at] h:mm a") module.exports = Message
[ { "context": "World!\n ============\n Author Name, <author@domain.foo>\n\n you can write text http://example.com[w", "end": 406, "score": 0.9999143481254578, "start": 389, "tag": "EMAIL", "value": "author@domain.foo" }, { "context": " ____\n\n another quot...
test/mocha/element/code.coffee
alinex/node-report
1
### eslint-env node, mocha ### test = require '../test' async = require 'async' Report = require '../../../src' before (cb) -> Report.init cb describe "code", -> describe "examples", -> @timeout 30000 it "should make example for asciidoc", (cb) -> test.markdown 'code/asciidoc', """ ``` asciidoc Hello, World! ============ Author Name, <author@domain.foo> you can write text http://example.com[with links], optionally using an explicit link:http://example.com[link prefix]. * single quotes around a phrase place 'emphasis' ** alternatively, you can put underlines around a phrase to add _emphasis_ * astericks around a phrase make the text *bold* * pluses around a phrase make it +monospaced+ * `smart' quotes using a leading backtick and trailing single quote ** use two of each for double ``smart'' quotes - escape characters are supported - you can escape a quote inside emphasized text like 'here\'s johnny!' term:: definition another term:: another definition // this is just a comment Let's make a break. ''' //// we'll be right with you after this brief interruption. //// == We're back! Want to see a image::images/tiger.png[Tiger]? .Nested highlighting ++++ <this_is inline="xml"></this_is> ++++ ____ asciidoc is so powerful. ____ another quote: [quote, Sir Arthur Conan Doyle, The Adventures of Sherlock Holmes] ____ When you have eliminated all which is impossible, then whatever remains, however improbable, must be the truth. ____ Getting Literal --------------- want to get literal? prefix a line with a space. .... I'll join that party, too. .... . one thing (yeah!) . two thing `i can write code`, and `more` wipee! NOTE: AsciiDoc is quite cool, you should try it. ``` """, null, true, cb it "should make example for bash", (cb) -> test.markdown 'code/bash', """ ``` bash #!/bin/bash ###### CONFIG ACCEPTED_HOSTS="/root/.hag_accepted.conf" BE_VERBOSE=false if [ "$UID" -ne 0 ] then echo "Superuser rights required" exit 2 fi genApacheConf(){ echo -e "# Host ${HOME_DIR}$1/$2 :" } ``` """, null, true, cb it "should make example for coffeescript", (cb) -> test.markdown 'code/coffeescript', """ ``` coffee grade = (student, period=(if b? then 7 else 6)) -> if student.excellentWork "A+" else if student.okayStuff if student.triedHard then "B" else "B-" else "C" class Animal extends Being constructor: (@name) -> move: (meters) -> alert @name + " moved \#{meters}m." ``` """, null, true, cb it "should make example for c++", (cb) -> test.markdown 'code/cpp', """ ``` cpp #include <iostream> int main(int argc, char *argv[]) { /* An annoying "Hello World" example */ for (auto i = 0; i < 0xFFFF; i++) cout << "Hello, World!" << endl; char c = '\\n'; unordered_map <string, vector<string> > m; m["key"] = "\\\\\\\\"; // this is an error return -2e3 + 12l; } ``` """, null, true, cb it "should make example for c#", (cb) -> test.markdown 'code/csharp', """ ``` csharp using System; #pragma warning disable 414, 3021 /// <summary>Main task</summary> async Task<int, int> AccessTheWebAsync() { Console.WriteLine("Hello, World!"); string urlContents = await getStringTask; return urlContents.Length; } ``` """, null, true, cb it "should make example for css", (cb) -> test.markdown 'code/css', """ ``` css @font-face { font-family: Chunkfive; src: url('Chunkfive.otf'); } body, .usertext { color: #F0F0F0; background: #600; font-family: Chunkfive, sans; } @import url(print.css); @media print { a[href^=http]::after { content: attr(href) } } ``` """, null, true, cb it "should make example for diff", (cb) -> test.markdown 'code/diff', """ ``` diff Index: languages/ini.js =================================================================== --- languages/ini.js (revision 199) +++ languages/ini.js (revision 200) @@ -1,8 +1,7 @@ hljs.LANGUAGES.ini = { case_insensitive: true, - defaultMode: - { + defaultMode: { contains: ['comment', 'title', 'setting'], illegal: '[^\\\\s]' }, *** /path/to/original timestamp --- /path/to/new timestamp *************** *** 1,3 **** --- 1,9 ---- + This is an important + notice! It should + therefore be located at + the beginning of this + document! ! compress the size of the ! changes. It is important to spell ``` """, null, true, cb it "should make example for go", (cb) -> test.markdown 'code/go', """ ``` go package main import "fmt" func main() { ch := make(chan float64) ch <- 1.0e10 // magic number x, ok := <- ch defer fmt.Println(`exitting now\\`) go println(len("hello world!")) return } ``` """, null, true, cb it "should make example for groovy", (cb) -> test.markdown 'code/groovy', """ ```` groovy #!/usr/bin/env groovy package model import groovy.transform.CompileStatic import java.util.List as MyList trait Distributable { void distribute(String version) {} } @CompileStatic class Distribution implements Distributable { double number = 1234.234 / 567 def otherNumber = 3 / 4 boolean archivable = condition ?: true def ternary = a ? b : c String name = "Guillaume" Closure description = null List<DownloadPackage> packages = [] String regex = ~/.*foo.*/ String multi = ''' multi line string ''' + ""\" now with double quotes and ${gstring} ""\" + $/ even with dollar slashy strings /$ /** * description method * @param cl the closure */ void description(Closure cl) { this.description = cl } void version(String name, Closure versionSpec) { def closure = { println "hi" } as Runnable MyList ml = [1, 2, [a: 1, b:2,c :3]] for (ch in "name") {} // single line comment DownloadPackage pkg = new DownloadPackage(version: name) check that: true label: def clone = versionSpec.rehydrate(pkg, pkg, pkg) /* now clone() in a multiline comment */ clone() packages.add(pkg) assert 4 / 2 == 2 } } ```` """, null, true, cb it "should make example for handlebars", (cb) -> test.markdown 'code/handlebars', """ ``` handlebars <div class="entry"> {{!-- only show if author exists --}} {{#if author}} <h1>{{firstName}} {{lastName}}</h1> {{/if}} </div> ``` """, null, true, cb it "should make example for http", (cb) -> test.markdown 'code/http', """ ``` http POST /task?id=1 HTTP/1.1 Host: example.org Content-Type: application/json; charset=utf-8 Content-Length: 137 { "status": "ok", "extended": true, "results": [ {"value": 0, "type": "int64"}, {"value": 1.0e+3, "type": "decimal"} ] } ``` """, null, true, cb it "should make example for ini", (cb) -> test.markdown 'code/ini', """ ``` ini ; boilerplate [package] name = "some_name" authors = ["Author"] description = "This is \ a description" [[lib]] name = ${NAME} default = True auto = no counter = 1_000 ``` """, null, true, cb it "should make example for java", (cb) -> test.markdown 'code/java', """ ``` java /** * @author John Smith <john.smith@example.com> */ package l2f.gameserver.model; public abstract class L2Char extends L2Object { public static final Short ERROR = 0x0001; public void moveTo(int x, int y, int z) { _ai = null; log("Should not be called"); if (1 > 5) { // wtf!? return; } } } ``` """, null, true, cb it "should make example for javascript", (cb) -> test.markdown 'code/javascript', """ ``` javascript function $initHighlight(block, cls) { try { if (cls.search(/\\bno\-highlight\\b/) != -1) return process(block, true, 0x0F) + ` class="${cls}"`; } catch (e) { /* handle exception */ } for (var i = 0 / 2; i < classes.length; i++) { if (checkCondition(classes[i]) === undefined) console.log('undefined'); } } export $initHighlight; ``` """, null, true, cb it "should make example for json", (cb) -> test.markdown 'code/json', """ ``` json [ { "title": "apples", "count": [12000, 20000], "description": {"text": "...", "sensitive": false} }, { "title": "oranges", "count": [17500, null], "description": {"text": "...", "sensitive": false} } ] ``` """, null, true, cb it "should make example for less", (cb) -> test.markdown 'code/less', """ ``` less @import "fruits"; @rhythm: 1.5em; @media screen and (min-resolution: 2dppx) { body {font-size: 125%} } section > .foo + #bar:hover [href*="less"] { margin: @rhythm 0 0 @rhythm; padding: calc(5% + 20px); background: #f00ba7 url(http://placehold.alpha-centauri/42.png) no-repeat; background-image: linear-gradient(-135deg, wheat, fuchsia) !important ; background-blend-mode: multiply; } @font-face { font-family: /* ? */ 'Omega'; src: url('../fonts/omega-webfont.woff?v=2.0.2'); } .icon-baz::before { display: inline-block; font-family: "Omega", Alpha, sans-serif; content: "\\f085"; color: rgba(98, 76 /* or 54 */, 231, .75); } ``` """, null, true, cb it "should make example for lisp", (cb) -> test.markdown 'code/lisp', """ ``` lisp #!/usr/bin/env csi (defun prompt-for-cd () "Prompts for CD" (prompt-read "Title" 1.53 1 2/4 1.7 1.7e0 2.9E-4 +42 -7 #b001 #b001/100 #o777 #O777 #xabc55 #c(0 -5.6)) (prompt-read "Artist" &rest) (or (parse-integer (prompt-read "Rating") :junk-allowed t) 0) (if x (format t "yes") (format t "no" nil) ;and here comment ) ;; second line comment '(+ 1 2) (defvar *lines*) ; list of all lines (position-if-not #'sys::whitespacep line :start beg)) (quote (privet 1 2 3)) '(hello world) (* 5 7) (1 2 34 5) (:use "aaaa") (let ((x 10) (y 20)) (print (+ x y)) ) ``` """, null, true, cb it "should make example for lua", (cb) -> test.markdown 'code/lua', """ ``` lua --[[ Simple signal/slot implementation ]] local signal_mt = { __index = { register = table.insert } } function signal_mt.__index:emit(... --[[ Comment in params ]]) for _, slot in ipairs(self) do slot(self, ...) end end local function create_signal() return setmetatable({}, signal_mt) end -- Signal test local signal = create_signal() signal:register(function(signal, ...) print(...) end) signal:emit('Answer to Life, the Universe, and Everything:', 42) --[==[ [=[ [[ Nested ]] multi-line ]=] comment ]==] [==[ Nested [=[ multi-line [[ string ]] ]=] ]==] ``` """, null, true, cb it "should make example for makefile", (cb) -> test.markdown 'code/makefile', """ ``` makefile # Makefile BUILDDIR = _build EXTRAS ?= $(BUILDDIR)/extras .PHONY: main clean main: @echo "Building main facility..." build_main $(BUILDDIR) clean: rm -rf $(BUILDDIR)/* ``` """, null, true, cb it "should make example for markdown", (cb) -> test.markdown 'code/markdown', """ ``` markdown # hello world you can write text [with links](http://example.com) inline or [link references][1]. * one _thing_ has *em*phasis * two __things__ are **bold** [1]: http://example.com --- hello world =========== <this_is inline="xml"></this_is> > markdown is so cool so are code segments 1. one thing (yeah!) 2. two thing `i can write code`, and `more` wipee! ``` """, null, true, cb it "should make example for perl", (cb) -> test.markdown 'code/perl', """ ``` perl # loads object sub load { my $flds = $c->db_load($id,@_) || do { Carp::carp "Can`t load (class: $c, id: $id): '$!'"; return undef }; my $o = $c->_perl_new(); $id12 = $id / 24 / 3600; $o->{'ID'} = $id12 + 123; #$o->{'SHCUT'} = $flds->{'SHCUT'}; my $p = $o->props; my $vt; $string =~ m/^sought_text$/; $items = split //, 'abc'; $string //= "bar"; for my $key (keys %$p) { if(${$vt.'::property'}) { $o->{$key . '_real'} = $flds->{$key}; tie $o->{$key}, 'CMSBuilder::Property', $o, $key; } } $o->save if delete $o->{'_save_after_load'}; # GH-117 my $g = glob("/usr/bin/*"); return $o; } __DATA__ @@ layouts/default.html.ep <!DOCTYPE html> <html> <head><title><%= title %></title></head> <body><%= content %></body> </html> __END__ =head1 NAME POD till the end of file ``` """, null, true, cb it "should make example for php", (cb) -> test.markdown 'code/php', """ ``` php require_once 'Zend/Uri/Http.php'; namespace Location\\Web; interface Factory { static function _factory(); } abstract class URI extends BaseURI implements Factory { abstract function test(); public static $st1 = 1; const ME = "Yo"; var $list = NULL; private $var; /** * Returns a URI * * @return URI */ static public function _factory($stats = array(), $uri = 'http') { echo __METHOD__; $uri = explode(':', $uri, 0b10); $schemeSpecific = isset($uri[1]) ? $uri[1] : ''; $desc = 'Multi line description'; // Security check if (!ctype_alnum($scheme)) { throw new Zend_Uri_Exception('Illegal scheme'); } $this->var = 0 - self::$st; $this->list = list(Array("1"=> 2, 2=>self::ME, 3 => \\Location\\Web\\URI::class)); return [ 'uri' => $uri, 'value' => null, ]; } } echo URI::ME . URI::$st1; __halt_compiler () ; datahere datahere datahere */ datahere ``` """, null, true, cb it "should make example for python", (cb) -> test.markdown 'code/python', """ ``` python @requires_authorization def somefunc(param1='', param2=0): r'''A docstring''' if param1 > param2: # interesting print 'Gre\\'ater' return (param2 - param1 + 1 + 0b10l) or None class SomeClass: pass >>> message = '''interpreter ... prompt''' ``` """, null, true, cb it "should make example for ruby", (cb) -> test.markdown 'code/ruby', """ ``` ruby # The Greeter class class Greeter def initialize(name) @name = name.capitalize end def salute puts "Hello #{@name}!" end end g = Greeter.new("world") g.salute ``` """, null, true, cb it "should make example for scala", (cb) -> test.markdown 'code/scala', """ ``` scala /** * A person has a name and an age. */ case class Person(name: String, age: Int) abstract class Vertical extends CaseJeu case class Haut(a: Int) extends Vertical case class Bas(name: String, b: Double) extends Vertical sealed trait Ior[+A, +B] case class Left[A](a: A) extends Ior[A, Nothing] case class Right[B](b: B) extends Ior[Nothing, B] case class Both[A, B](a: A, b: B) extends Ior[A, B] trait Functor[F[_]] { def map[A, B](fa: F[A], f: A => B): F[B] } // beware Int.MinValue def absoluteValue(n: Int): Int = if (n < 0) -n else n def interp(n: Int): String = s"there are $n ${color} balloons.\\n" type ξ[A] = (A, A) trait Hist { lhs => def ⊕(rhs: Hist): Hist } def gsum[A: Ring](as: Seq[A]): A = as.foldLeft(Ring[A].zero)(_ + _) val actions: List[Symbol] = 'init :: 'read :: 'write :: 'close :: Nil trait Cake { type T; type Q val things: Seq[T] abstract class Spindler def spindle(s: Spindler, ts: Seq[T], reversed: Boolean = false): Seq[Q] } val colors = Map( "red" -> 0xFF0000, "turquoise" -> 0x00FFFF, "black" -> 0x000000, "orange" -> 0xFF8040, "brown" -> 0x804000) lazy val ns = for { x <- 0 until 100 y <- 0 until 100 } yield (x + y) * 33.33 ``` """, null, true, cb it "should make example for scheme", (cb) -> test.markdown 'code/scheme', """ ``` scheme ;; Calculation of Hofstadter's male and female sequences as a list of pairs (define (hofstadter-male-female n) (letrec ((female (lambda (n) (if (= n 0) 1 (- n (male (female (- n 1))))))) (male (lambda (n) (if (= n 0) 0 (- n (female (male (- n 1)))))))) (let loop ((i 0)) (if (> i n) '() (cons (cons (female i) (male i)) (loop (+ i 1))))))) (hofstadter-male-female 8) (define (find-first func lst) (call-with-current-continuation (lambda (return-immediately) (for-each (lambda (x) (if (func x) (return-immediately x))) lst) #f))) ``` """, null, true, cb it "should make example for shell", (cb) -> test.markdown 'code/shell', """ ``` shell $ echo $EDITOR vim $ git checkout master Switched to branch 'master' Your branch is up-to-date with 'origin/master'. $ git push Everything up-to-date $ echo 'All > done!' All done! ``` """, null, true, cb it "should make example for sql", (cb) -> test.markdown 'code/sql', """ ``` sql CREATE TABLE "topic" ( "id" serial NOT NULL PRIMARY KEY, "forum_id" integer NOT NULL, "subject" varchar(255) NOT NULL ); ALTER TABLE "topic" ADD CONSTRAINT forum_id FOREIGN KEY ("forum_id") REFERENCES "forum" ("id"); -- Initials insert into "topic" ("forum_id", "subject") values (2, 'D''artagnian'); ``` """, null, true, cb it "should make example for stylus", (cb) -> test.markdown 'code/stylus', """ ``` stylus @import "nib" // variables $green = #008000 $green_dark = darken($green, 10) // mixin/function container() max-width 980px // mixin/function with parameters buttonBG($color = green) if $color == green background-color #008000 else if $color == red background-color #B22222 button buttonBG(red) #content, .content font Tahoma, Chunkfive, sans-serif background url('hatch.png') color #F0F0F0 !important width 100% ``` """, null, true, cb it "should make example for tex", (cb) -> test.markdown 'code/tex', """ ``` tex \\documentclass{article} \\usepackage[koi8-r]{inputenc} \\hoffset=0pt \\voffset=.3em \\tolerance=400 \\newcommand{\\eTiX}{\\TeX} \\begin{document} \\section*{Highlight.js} \\begin{table}[c|c] $\\frac 12\\, + \\, \\frac 1{x^3}\\text{Hello \\! world}$ & \\textbf{Goodbye\\~ world} \\\\\\eTiX $ \\pi=400 $ \\end{table} Ch\\'erie, \\c{c}a ne me pla\\^\\i t pas! % comment \\b G\\"otterd\\"ammerung~45\\%=34. $$ \\int\\limits_{0}^{\\pi}\\frac{4}{x-7}=3 $$ \\end{document} ``` """, null, true, cb it "should make example for typescript", (cb) -> test.markdown 'code/typescript', """ ``` typescript class MyClass { public static myValue: string; constructor(init: string) { this.myValue = init; } } import fs = require("fs"); module MyModule { export interface MyInterface extends Other { myProperty: any; } } declare magicNumber number; myArray.forEach(() => { }); // fat arrow syntax ``` """, null, true, cb it "should make example for xml", (cb) -> test.markdown 'code/xml', """ ``` xml <!DOCTYPE html> <title>Title</title> <style>body {width: 500px;}</style> <script type="application/javascript"> function $init() {return true;} </script> <body> <p checked class="title" id='title'>Title</p> <!-- here goes the rest of the page --> </body> ``` """, null, true, cb it "should make example for yaml", (cb) -> test.markdown 'code/yaml', """ ``` yaml --- # comment string_1: "Bar" string_2: 'bar' string_3: bar inline_keys_ignored: sompath/name/file.jpg keywords_in_yaml: - true - false - TRUE - FALSE - 21 - 21.0 - !!str 123 "quoted_key": &foobar bar: foo foo: "foo": bar reference: *foobar multiline_1: | Multiline String multiline_2: > Multiline String multiline_3: " Multiline string " ansible_variables: "foo {{variable}}" array_nested: - a - b: 1 c: 2 - b - comment ``` """, null, true, cb describe "api", -> it "should create code text section", (cb) -> # create report report = new Report() report.code 'text = \'foo\';', 'js' # check it test.report null, report, [ {type: 'document', nesting: 1} {type: 'code', nesting: 1, language: 'javascript'} {type: 'text', content: 'text = \'foo\';'} {type: 'code', nesting: -1} {type: 'document', nesting: -1} ], [ {format: 'md', text: '``` javascript\ntext = \'foo\';\n```'} {format: 'text', re: /foo/} {format: 'html', re: /<pre class=\"language javascript\">.*?<code>text = <span class=\"hljs-string\">\'foo\'<\/span>;<\/code><\/pre>/} {format: 'man', text: '.P\n.RS 2\n.nf\ntext = \'foo\';\n.fi\n.RE'} ], cb it "should create in multiple steps", (cb) -> # create report report = new Report() report.code true, 'js' report.text 'text = \'foo\';' report.code false # check it test.report null, report, [ {type: 'document', nesting: 1} {type: 'code', nesting: 1, language: 'javascript'} {type: 'text', content: 'text = \'foo\';'} {type: 'code', nesting: -1} {type: 'document', nesting: -1} ], [ {format: 'md', text: '``` javascript\ntext = \'foo\';\n```'} {format: 'text', re: /foo/} {format: 'html', re: /<pre class=\"language javascript\">.*?<code>text = <span class=\"hljs-string\">\'foo\'<\/span>;<\/code><\/pre>/} {format: 'man', text: '.P\n.RS 2\n.nf\ntext = \'foo\';\n.fi\n.RE'} ], cb
147090
### eslint-env node, mocha ### test = require '../test' async = require 'async' Report = require '../../../src' before (cb) -> Report.init cb describe "code", -> describe "examples", -> @timeout 30000 it "should make example for asciidoc", (cb) -> test.markdown 'code/asciidoc', """ ``` asciidoc Hello, World! ============ Author Name, <<EMAIL>> you can write text http://example.com[with links], optionally using an explicit link:http://example.com[link prefix]. * single quotes around a phrase place 'emphasis' ** alternatively, you can put underlines around a phrase to add _emphasis_ * astericks around a phrase make the text *bold* * pluses around a phrase make it +monospaced+ * `smart' quotes using a leading backtick and trailing single quote ** use two of each for double ``smart'' quotes - escape characters are supported - you can escape a quote inside emphasized text like 'here\'s johnny!' term:: definition another term:: another definition // this is just a comment Let's make a break. ''' //// we'll be right with you after this brief interruption. //// == We're back! Want to see a image::images/tiger.png[Tiger]? .Nested highlighting ++++ <this_is inline="xml"></this_is> ++++ ____ asciidoc is so powerful. ____ another quote: [quote, Sir <NAME>, The Adventures of Sherlock Holmes] ____ When you have eliminated all which is impossible, then whatever remains, however improbable, must be the truth. ____ Getting Literal --------------- want to get literal? prefix a line with a space. .... I'll join that party, too. .... . one thing (yeah!) . two thing `i can write code`, and `more` wipee! NOTE: AsciiDoc is quite cool, you should try it. ``` """, null, true, cb it "should make example for bash", (cb) -> test.markdown 'code/bash', """ ``` bash #!/bin/bash ###### CONFIG ACCEPTED_HOSTS="/root/.hag_accepted.conf" BE_VERBOSE=false if [ "$UID" -ne 0 ] then echo "Superuser rights required" exit 2 fi genApacheConf(){ echo -e "# Host ${HOME_DIR}$1/$2 :" } ``` """, null, true, cb it "should make example for coffeescript", (cb) -> test.markdown 'code/coffeescript', """ ``` coffee grade = (student, period=(if b? then 7 else 6)) -> if student.excellentWork "A+" else if student.okayStuff if student.triedHard then "B" else "B-" else "C" class Animal extends Being constructor: (@name) -> move: (meters) -> alert @name + " moved \#{meters}m." ``` """, null, true, cb it "should make example for c++", (cb) -> test.markdown 'code/cpp', """ ``` cpp #include <iostream> int main(int argc, char *argv[]) { /* An annoying "Hello World" example */ for (auto i = 0; i < 0xFFFF; i++) cout << "Hello, World!" << endl; char c = '\\n'; unordered_map <string, vector<string> > m; m["key"] = "\\\\<KEY>\\\\"; // this is an error return -2e3 + 12l; } ``` """, null, true, cb it "should make example for c#", (cb) -> test.markdown 'code/csharp', """ ``` csharp using System; #pragma warning disable 414, 3021 /// <summary>Main task</summary> async Task<int, int> AccessTheWebAsync() { Console.WriteLine("Hello, World!"); string urlContents = await getStringTask; return urlContents.Length; } ``` """, null, true, cb it "should make example for css", (cb) -> test.markdown 'code/css', """ ``` css @font-face { font-family: Chunkfive; src: url('Chunkfive.otf'); } body, .usertext { color: #F0F0F0; background: #600; font-family: Chunkfive, sans; } @import url(print.css); @media print { a[href^=http]::after { content: attr(href) } } ``` """, null, true, cb it "should make example for diff", (cb) -> test.markdown 'code/diff', """ ``` diff Index: languages/ini.js =================================================================== --- languages/ini.js (revision 199) +++ languages/ini.js (revision 200) @@ -1,8 +1,7 @@ hljs.LANGUAGES.ini = { case_insensitive: true, - defaultMode: - { + defaultMode: { contains: ['comment', 'title', 'setting'], illegal: '[^\\\\s]' }, *** /path/to/original timestamp --- /path/to/new timestamp *************** *** 1,3 **** --- 1,9 ---- + This is an important + notice! It should + therefore be located at + the beginning of this + document! ! compress the size of the ! changes. It is important to spell ``` """, null, true, cb it "should make example for go", (cb) -> test.markdown 'code/go', """ ``` go package main import "fmt" func main() { ch := make(chan float64) ch <- 1.0e10 // magic number x, ok := <- ch defer fmt.Println(`exitting now\\`) go println(len("hello world!")) return } ``` """, null, true, cb it "should make example for groovy", (cb) -> test.markdown 'code/groovy', """ ```` groovy #!/usr/bin/env groovy package model import groovy.transform.CompileStatic import java.util.List as MyList trait Distributable { void distribute(String version) {} } @CompileStatic class Distribution implements Distributable { double number = 1234.234 / 567 def otherNumber = 3 / 4 boolean archivable = condition ?: true def ternary = a ? b : c String name = "<NAME>" Closure description = null List<DownloadPackage> packages = [] String regex = ~/.*foo.*/ String multi = ''' multi line string ''' + ""\" now with double quotes and ${gstring} ""\" + $/ even with dollar slashy strings /$ /** * description method * @param cl the closure */ void description(Closure cl) { this.description = cl } void version(String name, Closure versionSpec) { def closure = { println "hi" } as Runnable MyList ml = [1, 2, [a: 1, b:2,c :3]] for (ch in "name") {} // single line comment DownloadPackage pkg = new DownloadPackage(version: name) check that: true label: def clone = versionSpec.rehydrate(pkg, pkg, pkg) /* now clone() in a multiline comment */ clone() packages.add(pkg) assert 4 / 2 == 2 } } ```` """, null, true, cb it "should make example for handlebars", (cb) -> test.markdown 'code/handlebars', """ ``` handlebars <div class="entry"> {{!-- only show if author exists --}} {{#if author}} <h1>{{firstName}} {{lastName}}</h1> {{/if}} </div> ``` """, null, true, cb it "should make example for http", (cb) -> test.markdown 'code/http', """ ``` http POST /task?id=1 HTTP/1.1 Host: example.org Content-Type: application/json; charset=utf-8 Content-Length: 137 { "status": "ok", "extended": true, "results": [ {"value": 0, "type": "int64"}, {"value": 1.0e+3, "type": "decimal"} ] } ``` """, null, true, cb it "should make example for ini", (cb) -> test.markdown 'code/ini', """ ``` ini ; boilerplate [package] name = "some_name" authors = ["Author"] description = "This is \ a description" [[lib]] name = ${NAME} default = True auto = no counter = 1_000 ``` """, null, true, cb it "should make example for java", (cb) -> test.markdown 'code/java', """ ``` java /** * @author <NAME> <<EMAIL>> */ package l2f.gameserver.model; public abstract class L2Char extends L2Object { public static final Short ERROR = 0x0001; public void moveTo(int x, int y, int z) { _ai = null; log("Should not be called"); if (1 > 5) { // wtf!? return; } } } ``` """, null, true, cb it "should make example for javascript", (cb) -> test.markdown 'code/javascript', """ ``` javascript function $initHighlight(block, cls) { try { if (cls.search(/\\bno\-highlight\\b/) != -1) return process(block, true, 0x0F) + ` class="${cls}"`; } catch (e) { /* handle exception */ } for (var i = 0 / 2; i < classes.length; i++) { if (checkCondition(classes[i]) === undefined) console.log('undefined'); } } export $initHighlight; ``` """, null, true, cb it "should make example for json", (cb) -> test.markdown 'code/json', """ ``` json [ { "title": "apples", "count": [12000, 20000], "description": {"text": "...", "sensitive": false} }, { "title": "oranges", "count": [17500, null], "description": {"text": "...", "sensitive": false} } ] ``` """, null, true, cb it "should make example for less", (cb) -> test.markdown 'code/less', """ ``` less @import "fruits"; @rhythm: 1.5em; @media screen and (min-resolution: 2dppx) { body {font-size: 125%} } section > .foo + #bar:hover [href*="less"] { margin: @rhythm 0 0 @rhythm; padding: calc(5% + 20px); background: #f00ba7 url(http://placehold.alpha-centauri/42.png) no-repeat; background-image: linear-gradient(-135deg, wheat, fuchsia) !important ; background-blend-mode: multiply; } @font-face { font-family: /* ? */ 'Omega'; src: url('../fonts/omega-webfont.woff?v=2.0.2'); } .icon-baz::before { display: inline-block; font-family: "Omega", Alpha, sans-serif; content: "\\f085"; color: rgba(98, 76 /* or 54 */, 231, .75); } ``` """, null, true, cb it "should make example for lisp", (cb) -> test.markdown 'code/lisp', """ ``` lisp #!/usr/bin/env csi (defun prompt-for-cd () "Prompts for CD" (prompt-read "Title" 1.53 1 2/4 1.7 1.7e0 2.9E-4 +42 -7 #b001 #b001/100 #o777 #O777 #xabc55 #c(0 -5.6)) (prompt-read "Artist" &rest) (or (parse-integer (prompt-read "Rating") :junk-allowed t) 0) (if x (format t "yes") (format t "no" nil) ;and here comment ) ;; second line comment '(+ 1 2) (defvar *lines*) ; list of all lines (position-if-not #'sys::whitespacep line :start beg)) (quote (privet 1 2 3)) '(hello world) (* 5 7) (1 2 34 5) (:use "aaaa") (let ((x 10) (y 20)) (print (+ x y)) ) ``` """, null, true, cb it "should make example for lua", (cb) -> test.markdown 'code/lua', """ ``` lua --[[ Simple signal/slot implementation ]] local signal_mt = { __index = { register = table.insert } } function signal_mt.__index:emit(... --[[ Comment in params ]]) for _, slot in ipairs(self) do slot(self, ...) end end local function create_signal() return setmetatable({}, signal_mt) end -- Signal test local signal = create_signal() signal:register(function(signal, ...) print(...) end) signal:emit('Answer to Life, the Universe, and Everything:', 42) --[==[ [=[ [[ Nested ]] multi-line ]=] comment ]==] [==[ Nested [=[ multi-line [[ string ]] ]=] ]==] ``` """, null, true, cb it "should make example for makefile", (cb) -> test.markdown 'code/makefile', """ ``` makefile # Makefile BUILDDIR = _build EXTRAS ?= $(BUILDDIR)/extras .PHONY: main clean main: @echo "Building main facility..." build_main $(BUILDDIR) clean: rm -rf $(BUILDDIR)/* ``` """, null, true, cb it "should make example for markdown", (cb) -> test.markdown 'code/markdown', """ ``` markdown # hello world you can write text [with links](http://example.com) inline or [link references][1]. * one _thing_ has *em*phasis * two __things__ are **bold** [1]: http://example.com --- hello world =========== <this_is inline="xml"></this_is> > markdown is so cool so are code segments 1. one thing (yeah!) 2. two thing `i can write code`, and `more` wipee! ``` """, null, true, cb it "should make example for perl", (cb) -> test.markdown 'code/perl', """ ``` perl # loads object sub load { my $flds = $c->db_load($id,@_) || do { Carp::carp "Can`t load (class: $c, id: $id): '$!'"; return undef }; my $o = $c->_perl_new(); $id12 = $id / 24 / 3600; $o->{'ID'} = $id12 + 123; #$o->{'SHCUT'} = $flds->{'SHCUT'}; my $p = $o->props; my $vt; $string =~ m/^sought_text$/; $items = split //, 'abc'; $string //= "bar"; for my $key (keys %$p) { if(${$vt.'::property'}) { $o->{$key . '_real'} = $flds->{$key}; tie $o->{$key}, 'CMSBuilder::Property', $o, $key; } } $o->save if delete $o->{'_save_after_load'}; # GH-117 my $g = glob("/usr/bin/*"); return $o; } __DATA__ @@ layouts/default.html.ep <!DOCTYPE html> <html> <head><title><%= title %></title></head> <body><%= content %></body> </html> __END__ =head1 NAME POD till the end of file ``` """, null, true, cb it "should make example for php", (cb) -> test.markdown 'code/php', """ ``` php require_once 'Zend/Uri/Http.php'; namespace Location\\Web; interface Factory { static function _factory(); } abstract class URI extends BaseURI implements Factory { abstract function test(); public static $st1 = 1; const ME = "Yo"; var $list = NULL; private $var; /** * Returns a URI * * @return URI */ static public function _factory($stats = array(), $uri = 'http') { echo __METHOD__; $uri = explode(':', $uri, 0b10); $schemeSpecific = isset($uri[1]) ? $uri[1] : ''; $desc = 'Multi line description'; // Security check if (!ctype_alnum($scheme)) { throw new Zend_Uri_Exception('Illegal scheme'); } $this->var = 0 - self::$st; $this->list = list(Array("1"=> 2, 2=>self::ME, 3 => \\Location\\Web\\URI::class)); return [ 'uri' => $uri, 'value' => null, ]; } } echo URI::ME . URI::$st1; __halt_compiler () ; datahere datahere datahere */ datahere ``` """, null, true, cb it "should make example for python", (cb) -> test.markdown 'code/python', """ ``` python @requires_authorization def somefunc(param1='', param2=0): r'''A docstring''' if param1 > param2: # interesting print 'Gre\\'ater' return (param2 - param1 + 1 + 0b10l) or None class SomeClass: pass >>> message = '''interpreter ... prompt''' ``` """, null, true, cb it "should make example for ruby", (cb) -> test.markdown 'code/ruby', """ ``` ruby # The Greeter class class Greeter def initialize(name) @name = name.capitalize end def salute puts "Hello #{@name}!" end end g = Greeter.new("world") g.salute ``` """, null, true, cb it "should make example for scala", (cb) -> test.markdown 'code/scala', """ ``` scala /** * A person has a name and an age. */ case class Person(name: String, age: Int) abstract class Vertical extends CaseJeu case class Haut(a: Int) extends Vertical case class Bas(name: String, b: Double) extends Vertical sealed trait Ior[+A, +B] case class Left[A](a: A) extends Ior[A, Nothing] case class Right[B](b: B) extends Ior[Nothing, B] case class Both[A, B](a: A, b: B) extends Ior[A, B] trait Functor[F[_]] { def map[A, B](fa: F[A], f: A => B): F[B] } // beware Int.MinValue def absoluteValue(n: Int): Int = if (n < 0) -n else n def interp(n: Int): String = s"there are $n ${color} balloons.\\n" type ξ[A] = (A, A) trait Hist { lhs => def ⊕(rhs: Hist): Hist } def gsum[A: Ring](as: Seq[A]): A = as.foldLeft(Ring[A].zero)(_ + _) val actions: List[Symbol] = 'init :: 'read :: 'write :: 'close :: Nil trait Cake { type T; type Q val things: Seq[T] abstract class Spindler def spindle(s: Spindler, ts: Seq[T], reversed: Boolean = false): Seq[Q] } val colors = Map( "red" -> 0xFF0000, "turquoise" -> 0x00FFFF, "black" -> 0x000000, "orange" -> 0xFF8040, "brown" -> 0x804000) lazy val ns = for { x <- 0 until 100 y <- 0 until 100 } yield (x + y) * 33.33 ``` """, null, true, cb it "should make example for scheme", (cb) -> test.markdown 'code/scheme', """ ``` scheme ;; Calculation of Hofstadter's male and female sequences as a list of pairs (define (hofstadter-male-female n) (letrec ((female (lambda (n) (if (= n 0) 1 (- n (male (female (- n 1))))))) (male (lambda (n) (if (= n 0) 0 (- n (female (male (- n 1)))))))) (let loop ((i 0)) (if (> i n) '() (cons (cons (female i) (male i)) (loop (+ i 1))))))) (hofstadter-male-female 8) (define (find-first func lst) (call-with-current-continuation (lambda (return-immediately) (for-each (lambda (x) (if (func x) (return-immediately x))) lst) #f))) ``` """, null, true, cb it "should make example for shell", (cb) -> test.markdown 'code/shell', """ ``` shell $ echo $EDITOR vim $ git checkout master Switched to branch 'master' Your branch is up-to-date with 'origin/master'. $ git push Everything up-to-date $ echo 'All > done!' All done! ``` """, null, true, cb it "should make example for sql", (cb) -> test.markdown 'code/sql', """ ``` sql CREATE TABLE "topic" ( "id" serial NOT NULL PRIMARY KEY, "forum_id" integer NOT NULL, "subject" varchar(255) NOT NULL ); ALTER TABLE "topic" ADD CONSTRAINT forum_id FOREIGN KEY ("forum_id") REFERENCES "forum" ("id"); -- Initials insert into "topic" ("forum_id", "subject") values (2, 'D''artagnian'); ``` """, null, true, cb it "should make example for stylus", (cb) -> test.markdown 'code/stylus', """ ``` stylus @import "nib" // variables $green = #008000 $green_dark = darken($green, 10) // mixin/function container() max-width 980px // mixin/function with parameters buttonBG($color = green) if $color == green background-color #008000 else if $color == red background-color #B22222 button buttonBG(red) #content, .content font Tahoma, Chunkfive, sans-serif background url('hatch.png') color #F0F0F0 !important width 100% ``` """, null, true, cb it "should make example for tex", (cb) -> test.markdown 'code/tex', """ ``` tex \\documentclass{article} \\usepackage[koi8-r]{inputenc} \\hoffset=0pt \\voffset=.3em \\tolerance=400 \\newcommand{\\eTiX}{\\TeX} \\begin{document} \\section*{Highlight.js} \\begin{table}[c|c] $\\frac 12\\, + \\, \\frac 1{x^3}\\text{Hello \\! world}$ & \\textbf{Goodbye\\~ world} \\\\\\eTiX $ \\pi=400 $ \\end{table} Ch\\'erie, \\c{c}a ne me pla\\^\\i t pas! % comment \\b G\\"otterd\\"ammerung~45\\%=34. $$ \\int\\limits_{0}^{\\pi}\\frac{4}{x-7}=3 $$ \\end{document} ``` """, null, true, cb it "should make example for typescript", (cb) -> test.markdown 'code/typescript', """ ``` typescript class MyClass { public static myValue: string; constructor(init: string) { this.myValue = init; } } import fs = require("fs"); module MyModule { export interface MyInterface extends Other { myProperty: any; } } declare magicNumber number; myArray.forEach(() => { }); // fat arrow syntax ``` """, null, true, cb it "should make example for xml", (cb) -> test.markdown 'code/xml', """ ``` xml <!DOCTYPE html> <title>Title</title> <style>body {width: 500px;}</style> <script type="application/javascript"> function $init() {return true;} </script> <body> <p checked class="title" id='title'>Title</p> <!-- here goes the rest of the page --> </body> ``` """, null, true, cb it "should make example for yaml", (cb) -> test.markdown 'code/yaml', """ ``` yaml --- # comment string_1: "Bar" string_2: 'bar' string_3: bar inline_keys_ignored: <KEY> keywords_in_yaml: - true - false - TRUE - FALSE - 21 - 21.0 - !!str 123 "quoted_key": &foobar bar: foo foo: "foo": bar reference: *foobar multiline_1: | Multiline String multiline_2: > Multiline String multiline_3: " Multiline string " ansible_variables: "foo {{variable}}" array_nested: - a - b: 1 c: 2 - b - comment ``` """, null, true, cb describe "api", -> it "should create code text section", (cb) -> # create report report = new Report() report.code 'text = \'foo\';', 'js' # check it test.report null, report, [ {type: 'document', nesting: 1} {type: 'code', nesting: 1, language: 'javascript'} {type: 'text', content: 'text = \'foo\';'} {type: 'code', nesting: -1} {type: 'document', nesting: -1} ], [ {format: 'md', text: '``` javascript\ntext = \'foo\';\n```'} {format: 'text', re: /foo/} {format: 'html', re: /<pre class=\"language javascript\">.*?<code>text = <span class=\"hljs-string\">\'foo\'<\/span>;<\/code><\/pre>/} {format: 'man', text: '.P\n.RS 2\n.nf\ntext = \'foo\';\n.fi\n.RE'} ], cb it "should create in multiple steps", (cb) -> # create report report = new Report() report.code true, 'js' report.text 'text = \'foo\';' report.code false # check it test.report null, report, [ {type: 'document', nesting: 1} {type: 'code', nesting: 1, language: 'javascript'} {type: 'text', content: 'text = \'foo\';'} {type: 'code', nesting: -1} {type: 'document', nesting: -1} ], [ {format: 'md', text: '``` javascript\ntext = \'foo\';\n```'} {format: 'text', re: /foo/} {format: 'html', re: /<pre class=\"language javascript\">.*?<code>text = <span class=\"hljs-string\">\'foo\'<\/span>;<\/code><\/pre>/} {format: 'man', text: '.P\n.RS 2\n.nf\ntext = \'foo\';\n.fi\n.RE'} ], cb
true
### eslint-env node, mocha ### test = require '../test' async = require 'async' Report = require '../../../src' before (cb) -> Report.init cb describe "code", -> describe "examples", -> @timeout 30000 it "should make example for asciidoc", (cb) -> test.markdown 'code/asciidoc', """ ``` asciidoc Hello, World! ============ Author Name, <PI:EMAIL:<EMAIL>END_PI> you can write text http://example.com[with links], optionally using an explicit link:http://example.com[link prefix]. * single quotes around a phrase place 'emphasis' ** alternatively, you can put underlines around a phrase to add _emphasis_ * astericks around a phrase make the text *bold* * pluses around a phrase make it +monospaced+ * `smart' quotes using a leading backtick and trailing single quote ** use two of each for double ``smart'' quotes - escape characters are supported - you can escape a quote inside emphasized text like 'here\'s johnny!' term:: definition another term:: another definition // this is just a comment Let's make a break. ''' //// we'll be right with you after this brief interruption. //// == We're back! Want to see a image::images/tiger.png[Tiger]? .Nested highlighting ++++ <this_is inline="xml"></this_is> ++++ ____ asciidoc is so powerful. ____ another quote: [quote, Sir PI:NAME:<NAME>END_PI, The Adventures of Sherlock Holmes] ____ When you have eliminated all which is impossible, then whatever remains, however improbable, must be the truth. ____ Getting Literal --------------- want to get literal? prefix a line with a space. .... I'll join that party, too. .... . one thing (yeah!) . two thing `i can write code`, and `more` wipee! NOTE: AsciiDoc is quite cool, you should try it. ``` """, null, true, cb it "should make example for bash", (cb) -> test.markdown 'code/bash', """ ``` bash #!/bin/bash ###### CONFIG ACCEPTED_HOSTS="/root/.hag_accepted.conf" BE_VERBOSE=false if [ "$UID" -ne 0 ] then echo "Superuser rights required" exit 2 fi genApacheConf(){ echo -e "# Host ${HOME_DIR}$1/$2 :" } ``` """, null, true, cb it "should make example for coffeescript", (cb) -> test.markdown 'code/coffeescript', """ ``` coffee grade = (student, period=(if b? then 7 else 6)) -> if student.excellentWork "A+" else if student.okayStuff if student.triedHard then "B" else "B-" else "C" class Animal extends Being constructor: (@name) -> move: (meters) -> alert @name + " moved \#{meters}m." ``` """, null, true, cb it "should make example for c++", (cb) -> test.markdown 'code/cpp', """ ``` cpp #include <iostream> int main(int argc, char *argv[]) { /* An annoying "Hello World" example */ for (auto i = 0; i < 0xFFFF; i++) cout << "Hello, World!" << endl; char c = '\\n'; unordered_map <string, vector<string> > m; m["key"] = "\\\\PI:KEY:<KEY>END_PI\\\\"; // this is an error return -2e3 + 12l; } ``` """, null, true, cb it "should make example for c#", (cb) -> test.markdown 'code/csharp', """ ``` csharp using System; #pragma warning disable 414, 3021 /// <summary>Main task</summary> async Task<int, int> AccessTheWebAsync() { Console.WriteLine("Hello, World!"); string urlContents = await getStringTask; return urlContents.Length; } ``` """, null, true, cb it "should make example for css", (cb) -> test.markdown 'code/css', """ ``` css @font-face { font-family: Chunkfive; src: url('Chunkfive.otf'); } body, .usertext { color: #F0F0F0; background: #600; font-family: Chunkfive, sans; } @import url(print.css); @media print { a[href^=http]::after { content: attr(href) } } ``` """, null, true, cb it "should make example for diff", (cb) -> test.markdown 'code/diff', """ ``` diff Index: languages/ini.js =================================================================== --- languages/ini.js (revision 199) +++ languages/ini.js (revision 200) @@ -1,8 +1,7 @@ hljs.LANGUAGES.ini = { case_insensitive: true, - defaultMode: - { + defaultMode: { contains: ['comment', 'title', 'setting'], illegal: '[^\\\\s]' }, *** /path/to/original timestamp --- /path/to/new timestamp *************** *** 1,3 **** --- 1,9 ---- + This is an important + notice! It should + therefore be located at + the beginning of this + document! ! compress the size of the ! changes. It is important to spell ``` """, null, true, cb it "should make example for go", (cb) -> test.markdown 'code/go', """ ``` go package main import "fmt" func main() { ch := make(chan float64) ch <- 1.0e10 // magic number x, ok := <- ch defer fmt.Println(`exitting now\\`) go println(len("hello world!")) return } ``` """, null, true, cb it "should make example for groovy", (cb) -> test.markdown 'code/groovy', """ ```` groovy #!/usr/bin/env groovy package model import groovy.transform.CompileStatic import java.util.List as MyList trait Distributable { void distribute(String version) {} } @CompileStatic class Distribution implements Distributable { double number = 1234.234 / 567 def otherNumber = 3 / 4 boolean archivable = condition ?: true def ternary = a ? b : c String name = "PI:NAME:<NAME>END_PI" Closure description = null List<DownloadPackage> packages = [] String regex = ~/.*foo.*/ String multi = ''' multi line string ''' + ""\" now with double quotes and ${gstring} ""\" + $/ even with dollar slashy strings /$ /** * description method * @param cl the closure */ void description(Closure cl) { this.description = cl } void version(String name, Closure versionSpec) { def closure = { println "hi" } as Runnable MyList ml = [1, 2, [a: 1, b:2,c :3]] for (ch in "name") {} // single line comment DownloadPackage pkg = new DownloadPackage(version: name) check that: true label: def clone = versionSpec.rehydrate(pkg, pkg, pkg) /* now clone() in a multiline comment */ clone() packages.add(pkg) assert 4 / 2 == 2 } } ```` """, null, true, cb it "should make example for handlebars", (cb) -> test.markdown 'code/handlebars', """ ``` handlebars <div class="entry"> {{!-- only show if author exists --}} {{#if author}} <h1>{{firstName}} {{lastName}}</h1> {{/if}} </div> ``` """, null, true, cb it "should make example for http", (cb) -> test.markdown 'code/http', """ ``` http POST /task?id=1 HTTP/1.1 Host: example.org Content-Type: application/json; charset=utf-8 Content-Length: 137 { "status": "ok", "extended": true, "results": [ {"value": 0, "type": "int64"}, {"value": 1.0e+3, "type": "decimal"} ] } ``` """, null, true, cb it "should make example for ini", (cb) -> test.markdown 'code/ini', """ ``` ini ; boilerplate [package] name = "some_name" authors = ["Author"] description = "This is \ a description" [[lib]] name = ${NAME} default = True auto = no counter = 1_000 ``` """, null, true, cb it "should make example for java", (cb) -> test.markdown 'code/java', """ ``` java /** * @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> */ package l2f.gameserver.model; public abstract class L2Char extends L2Object { public static final Short ERROR = 0x0001; public void moveTo(int x, int y, int z) { _ai = null; log("Should not be called"); if (1 > 5) { // wtf!? return; } } } ``` """, null, true, cb it "should make example for javascript", (cb) -> test.markdown 'code/javascript', """ ``` javascript function $initHighlight(block, cls) { try { if (cls.search(/\\bno\-highlight\\b/) != -1) return process(block, true, 0x0F) + ` class="${cls}"`; } catch (e) { /* handle exception */ } for (var i = 0 / 2; i < classes.length; i++) { if (checkCondition(classes[i]) === undefined) console.log('undefined'); } } export $initHighlight; ``` """, null, true, cb it "should make example for json", (cb) -> test.markdown 'code/json', """ ``` json [ { "title": "apples", "count": [12000, 20000], "description": {"text": "...", "sensitive": false} }, { "title": "oranges", "count": [17500, null], "description": {"text": "...", "sensitive": false} } ] ``` """, null, true, cb it "should make example for less", (cb) -> test.markdown 'code/less', """ ``` less @import "fruits"; @rhythm: 1.5em; @media screen and (min-resolution: 2dppx) { body {font-size: 125%} } section > .foo + #bar:hover [href*="less"] { margin: @rhythm 0 0 @rhythm; padding: calc(5% + 20px); background: #f00ba7 url(http://placehold.alpha-centauri/42.png) no-repeat; background-image: linear-gradient(-135deg, wheat, fuchsia) !important ; background-blend-mode: multiply; } @font-face { font-family: /* ? */ 'Omega'; src: url('../fonts/omega-webfont.woff?v=2.0.2'); } .icon-baz::before { display: inline-block; font-family: "Omega", Alpha, sans-serif; content: "\\f085"; color: rgba(98, 76 /* or 54 */, 231, .75); } ``` """, null, true, cb it "should make example for lisp", (cb) -> test.markdown 'code/lisp', """ ``` lisp #!/usr/bin/env csi (defun prompt-for-cd () "Prompts for CD" (prompt-read "Title" 1.53 1 2/4 1.7 1.7e0 2.9E-4 +42 -7 #b001 #b001/100 #o777 #O777 #xabc55 #c(0 -5.6)) (prompt-read "Artist" &rest) (or (parse-integer (prompt-read "Rating") :junk-allowed t) 0) (if x (format t "yes") (format t "no" nil) ;and here comment ) ;; second line comment '(+ 1 2) (defvar *lines*) ; list of all lines (position-if-not #'sys::whitespacep line :start beg)) (quote (privet 1 2 3)) '(hello world) (* 5 7) (1 2 34 5) (:use "aaaa") (let ((x 10) (y 20)) (print (+ x y)) ) ``` """, null, true, cb it "should make example for lua", (cb) -> test.markdown 'code/lua', """ ``` lua --[[ Simple signal/slot implementation ]] local signal_mt = { __index = { register = table.insert } } function signal_mt.__index:emit(... --[[ Comment in params ]]) for _, slot in ipairs(self) do slot(self, ...) end end local function create_signal() return setmetatable({}, signal_mt) end -- Signal test local signal = create_signal() signal:register(function(signal, ...) print(...) end) signal:emit('Answer to Life, the Universe, and Everything:', 42) --[==[ [=[ [[ Nested ]] multi-line ]=] comment ]==] [==[ Nested [=[ multi-line [[ string ]] ]=] ]==] ``` """, null, true, cb it "should make example for makefile", (cb) -> test.markdown 'code/makefile', """ ``` makefile # Makefile BUILDDIR = _build EXTRAS ?= $(BUILDDIR)/extras .PHONY: main clean main: @echo "Building main facility..." build_main $(BUILDDIR) clean: rm -rf $(BUILDDIR)/* ``` """, null, true, cb it "should make example for markdown", (cb) -> test.markdown 'code/markdown', """ ``` markdown # hello world you can write text [with links](http://example.com) inline or [link references][1]. * one _thing_ has *em*phasis * two __things__ are **bold** [1]: http://example.com --- hello world =========== <this_is inline="xml"></this_is> > markdown is so cool so are code segments 1. one thing (yeah!) 2. two thing `i can write code`, and `more` wipee! ``` """, null, true, cb it "should make example for perl", (cb) -> test.markdown 'code/perl', """ ``` perl # loads object sub load { my $flds = $c->db_load($id,@_) || do { Carp::carp "Can`t load (class: $c, id: $id): '$!'"; return undef }; my $o = $c->_perl_new(); $id12 = $id / 24 / 3600; $o->{'ID'} = $id12 + 123; #$o->{'SHCUT'} = $flds->{'SHCUT'}; my $p = $o->props; my $vt; $string =~ m/^sought_text$/; $items = split //, 'abc'; $string //= "bar"; for my $key (keys %$p) { if(${$vt.'::property'}) { $o->{$key . '_real'} = $flds->{$key}; tie $o->{$key}, 'CMSBuilder::Property', $o, $key; } } $o->save if delete $o->{'_save_after_load'}; # GH-117 my $g = glob("/usr/bin/*"); return $o; } __DATA__ @@ layouts/default.html.ep <!DOCTYPE html> <html> <head><title><%= title %></title></head> <body><%= content %></body> </html> __END__ =head1 NAME POD till the end of file ``` """, null, true, cb it "should make example for php", (cb) -> test.markdown 'code/php', """ ``` php require_once 'Zend/Uri/Http.php'; namespace Location\\Web; interface Factory { static function _factory(); } abstract class URI extends BaseURI implements Factory { abstract function test(); public static $st1 = 1; const ME = "Yo"; var $list = NULL; private $var; /** * Returns a URI * * @return URI */ static public function _factory($stats = array(), $uri = 'http') { echo __METHOD__; $uri = explode(':', $uri, 0b10); $schemeSpecific = isset($uri[1]) ? $uri[1] : ''; $desc = 'Multi line description'; // Security check if (!ctype_alnum($scheme)) { throw new Zend_Uri_Exception('Illegal scheme'); } $this->var = 0 - self::$st; $this->list = list(Array("1"=> 2, 2=>self::ME, 3 => \\Location\\Web\\URI::class)); return [ 'uri' => $uri, 'value' => null, ]; } } echo URI::ME . URI::$st1; __halt_compiler () ; datahere datahere datahere */ datahere ``` """, null, true, cb it "should make example for python", (cb) -> test.markdown 'code/python', """ ``` python @requires_authorization def somefunc(param1='', param2=0): r'''A docstring''' if param1 > param2: # interesting print 'Gre\\'ater' return (param2 - param1 + 1 + 0b10l) or None class SomeClass: pass >>> message = '''interpreter ... prompt''' ``` """, null, true, cb it "should make example for ruby", (cb) -> test.markdown 'code/ruby', """ ``` ruby # The Greeter class class Greeter def initialize(name) @name = name.capitalize end def salute puts "Hello #{@name}!" end end g = Greeter.new("world") g.salute ``` """, null, true, cb it "should make example for scala", (cb) -> test.markdown 'code/scala', """ ``` scala /** * A person has a name and an age. */ case class Person(name: String, age: Int) abstract class Vertical extends CaseJeu case class Haut(a: Int) extends Vertical case class Bas(name: String, b: Double) extends Vertical sealed trait Ior[+A, +B] case class Left[A](a: A) extends Ior[A, Nothing] case class Right[B](b: B) extends Ior[Nothing, B] case class Both[A, B](a: A, b: B) extends Ior[A, B] trait Functor[F[_]] { def map[A, B](fa: F[A], f: A => B): F[B] } // beware Int.MinValue def absoluteValue(n: Int): Int = if (n < 0) -n else n def interp(n: Int): String = s"there are $n ${color} balloons.\\n" type ξ[A] = (A, A) trait Hist { lhs => def ⊕(rhs: Hist): Hist } def gsum[A: Ring](as: Seq[A]): A = as.foldLeft(Ring[A].zero)(_ + _) val actions: List[Symbol] = 'init :: 'read :: 'write :: 'close :: Nil trait Cake { type T; type Q val things: Seq[T] abstract class Spindler def spindle(s: Spindler, ts: Seq[T], reversed: Boolean = false): Seq[Q] } val colors = Map( "red" -> 0xFF0000, "turquoise" -> 0x00FFFF, "black" -> 0x000000, "orange" -> 0xFF8040, "brown" -> 0x804000) lazy val ns = for { x <- 0 until 100 y <- 0 until 100 } yield (x + y) * 33.33 ``` """, null, true, cb it "should make example for scheme", (cb) -> test.markdown 'code/scheme', """ ``` scheme ;; Calculation of Hofstadter's male and female sequences as a list of pairs (define (hofstadter-male-female n) (letrec ((female (lambda (n) (if (= n 0) 1 (- n (male (female (- n 1))))))) (male (lambda (n) (if (= n 0) 0 (- n (female (male (- n 1)))))))) (let loop ((i 0)) (if (> i n) '() (cons (cons (female i) (male i)) (loop (+ i 1))))))) (hofstadter-male-female 8) (define (find-first func lst) (call-with-current-continuation (lambda (return-immediately) (for-each (lambda (x) (if (func x) (return-immediately x))) lst) #f))) ``` """, null, true, cb it "should make example for shell", (cb) -> test.markdown 'code/shell', """ ``` shell $ echo $EDITOR vim $ git checkout master Switched to branch 'master' Your branch is up-to-date with 'origin/master'. $ git push Everything up-to-date $ echo 'All > done!' All done! ``` """, null, true, cb it "should make example for sql", (cb) -> test.markdown 'code/sql', """ ``` sql CREATE TABLE "topic" ( "id" serial NOT NULL PRIMARY KEY, "forum_id" integer NOT NULL, "subject" varchar(255) NOT NULL ); ALTER TABLE "topic" ADD CONSTRAINT forum_id FOREIGN KEY ("forum_id") REFERENCES "forum" ("id"); -- Initials insert into "topic" ("forum_id", "subject") values (2, 'D''artagnian'); ``` """, null, true, cb it "should make example for stylus", (cb) -> test.markdown 'code/stylus', """ ``` stylus @import "nib" // variables $green = #008000 $green_dark = darken($green, 10) // mixin/function container() max-width 980px // mixin/function with parameters buttonBG($color = green) if $color == green background-color #008000 else if $color == red background-color #B22222 button buttonBG(red) #content, .content font Tahoma, Chunkfive, sans-serif background url('hatch.png') color #F0F0F0 !important width 100% ``` """, null, true, cb it "should make example for tex", (cb) -> test.markdown 'code/tex', """ ``` tex \\documentclass{article} \\usepackage[koi8-r]{inputenc} \\hoffset=0pt \\voffset=.3em \\tolerance=400 \\newcommand{\\eTiX}{\\TeX} \\begin{document} \\section*{Highlight.js} \\begin{table}[c|c] $\\frac 12\\, + \\, \\frac 1{x^3}\\text{Hello \\! world}$ & \\textbf{Goodbye\\~ world} \\\\\\eTiX $ \\pi=400 $ \\end{table} Ch\\'erie, \\c{c}a ne me pla\\^\\i t pas! % comment \\b G\\"otterd\\"ammerung~45\\%=34. $$ \\int\\limits_{0}^{\\pi}\\frac{4}{x-7}=3 $$ \\end{document} ``` """, null, true, cb it "should make example for typescript", (cb) -> test.markdown 'code/typescript', """ ``` typescript class MyClass { public static myValue: string; constructor(init: string) { this.myValue = init; } } import fs = require("fs"); module MyModule { export interface MyInterface extends Other { myProperty: any; } } declare magicNumber number; myArray.forEach(() => { }); // fat arrow syntax ``` """, null, true, cb it "should make example for xml", (cb) -> test.markdown 'code/xml', """ ``` xml <!DOCTYPE html> <title>Title</title> <style>body {width: 500px;}</style> <script type="application/javascript"> function $init() {return true;} </script> <body> <p checked class="title" id='title'>Title</p> <!-- here goes the rest of the page --> </body> ``` """, null, true, cb it "should make example for yaml", (cb) -> test.markdown 'code/yaml', """ ``` yaml --- # comment string_1: "Bar" string_2: 'bar' string_3: bar inline_keys_ignored: PI:KEY:<KEY>END_PI keywords_in_yaml: - true - false - TRUE - FALSE - 21 - 21.0 - !!str 123 "quoted_key": &foobar bar: foo foo: "foo": bar reference: *foobar multiline_1: | Multiline String multiline_2: > Multiline String multiline_3: " Multiline string " ansible_variables: "foo {{variable}}" array_nested: - a - b: 1 c: 2 - b - comment ``` """, null, true, cb describe "api", -> it "should create code text section", (cb) -> # create report report = new Report() report.code 'text = \'foo\';', 'js' # check it test.report null, report, [ {type: 'document', nesting: 1} {type: 'code', nesting: 1, language: 'javascript'} {type: 'text', content: 'text = \'foo\';'} {type: 'code', nesting: -1} {type: 'document', nesting: -1} ], [ {format: 'md', text: '``` javascript\ntext = \'foo\';\n```'} {format: 'text', re: /foo/} {format: 'html', re: /<pre class=\"language javascript\">.*?<code>text = <span class=\"hljs-string\">\'foo\'<\/span>;<\/code><\/pre>/} {format: 'man', text: '.P\n.RS 2\n.nf\ntext = \'foo\';\n.fi\n.RE'} ], cb it "should create in multiple steps", (cb) -> # create report report = new Report() report.code true, 'js' report.text 'text = \'foo\';' report.code false # check it test.report null, report, [ {type: 'document', nesting: 1} {type: 'code', nesting: 1, language: 'javascript'} {type: 'text', content: 'text = \'foo\';'} {type: 'code', nesting: -1} {type: 'document', nesting: -1} ], [ {format: 'md', text: '``` javascript\ntext = \'foo\';\n```'} {format: 'text', re: /foo/} {format: 'html', re: /<pre class=\"language javascript\">.*?<code>text = <span class=\"hljs-string\">\'foo\'<\/span>;<\/code><\/pre>/} {format: 'man', text: '.P\n.RS 2\n.nf\ntext = \'foo\';\n.fi\n.RE'} ], cb
[ { "context": "---\n---\n\n### Ben Scott # 2015-10-26 # Viewer ###\n\n'use strict'\n\n### Cons", "end": 22, "score": 0.9997074007987976, "start": 13, "tag": "NAME", "value": "Ben Scott" } ]
js/lib/viewer.coffee
evan-erdos/evan-erdos.github.io
1
--- --- ### Ben Scott # 2015-10-26 # Viewer ### 'use strict' ### Constants & Aliases ### {abs,floor,random,sqrt} = Math T = THREE ### DOM ### dir = "/js/assets/" # directory divID = "CoffeeCode" # id of parent container = null # parent in document ### WebGL ### loader = new T.JSONLoader() objectLoader = new T.ObjectLoader() objLoader = new T.OBJLoader() textureLoader = new T.TextureLoader() ### `Viewer` # # This is the program entrypoint, and it initializes all of the # [Three.js][] objects. # - `@scene`: An object representing everything in the # environment, including `camera`s, 3D models, etc. # - `@camera`: The main rendering viewpoint, typically uses # perspective rather than orthogonal rendering. # - `@renderer`: ... I'll... get back to you about exactly # what it is that this one does! ### class Viewer constructor: (@filename,@distance = 1) -> @scene = new T.Scene() @camera = new T.PerspectiveCamera( 75,768/512,1,65536) @renderer = new T.WebGLRenderer { antialias: true, alpha: true } @renderer.setSize(768,512) @renderer.setClearColor(0x0,0) @ambient = new T.AmbientLight(0x404040) @scene.add @ambient @light = new T.DirectionalLight(0xEFEFED,1) @light.position.set(512,512,512) @model = { mesh: null material: null albedo: null normal: null specular: null } @model.material = @createMaterial( @model.albedo @model.normal @model.specular) @scene.add @light @import3D(@filename) @init() init: -> @initDOM() @initControls() @camera.position.z = @distance @render() initDOM: -> container = document.getElementById(divID) container.appendChild(@renderer.domElement) initControls: -> @controls = new T.OrbitControls( @camera,@renderer.domElement) @controls.userZoom = false ### `Viewer.render` # # This needs to be a bound function, and is the callback # used by `requestAnimationFrame`, which does a bunch of # stuff, e.g., calling render at the proper framerate. ### render: => requestAnimationFrame(@render) @controls.update() @renderer.render(@scene,@camera) ### `Viewer.import3D` # # This needs to be a bound function, and is the callback # used by the `JSONLoader` to initialize geometry from # the provided filename. ### import3D: (filename) => textureLoader.load( "#{dir}#{filename}-albedo.png" (texture) => @model.albedo = texture texture.needsUpdate = true) textureLoader.load( "#{dir}#{filename}-normal.jpg" (texture) => @model.normal = texture @loadModel(filename) texture.needsUpdate = true) #textureLoader.load( # "#{dir}#{filename}-specular.png" # (texture) => # @model.specular = texture # texture.needsUpdate = true) loadModel: (filename) => objLoader.load( "#{dir}#{filename}.obj" (object) => object.traverse (child) => return unless (child instanceof T.Mesh) #@model.mesh = child #@model.mesh.material = new T.MeshPhongMaterial { # color: 0xFFFFFF # specular: 0xAAAAAA # shininess: 10 # map: @model.albedo } mat = new T.MeshPhongMaterial { color: 0xFFFFFF specular: 0xAAAAAA shininess: 10 map: @model.albedo specularMap: @model.specular normalMap: @model.normal normalScale: new T.Vector2(0.8,0.8) } mesh = new T.Mesh(child.geometry, mat) console.log mesh #@model.mesh.material.map = @model.albedo #@model.mesh.material.normalMap = @model.normal #child.material = @createMaterial( # @model.albedo # @model.normal # @model.specular) #@model. mesh.scale.set(100,100,100) @renderer.render(@scene,@camera) @scene.add mesh) createMaterial: (albedo, normal, specular) => new T.MeshPhongMaterial { color: 0xFFFFFF specular: 0xAAAAAA shininess: 10 map: albedo specularMap: specular normalMap: normal normalScale: new T.Vector2(0.8,0.8) } ### `@createViewer` # # This is a global function, callable from other scripts, and # will be used with another script on the page to load an # arbitrary 3D model into a basic scene. ### @createViewer = (filename, distance=1) => new Viewer(filename,distance)
102965
--- --- ### <NAME> # 2015-10-26 # Viewer ### 'use strict' ### Constants & Aliases ### {abs,floor,random,sqrt} = Math T = THREE ### DOM ### dir = "/js/assets/" # directory divID = "CoffeeCode" # id of parent container = null # parent in document ### WebGL ### loader = new T.JSONLoader() objectLoader = new T.ObjectLoader() objLoader = new T.OBJLoader() textureLoader = new T.TextureLoader() ### `Viewer` # # This is the program entrypoint, and it initializes all of the # [Three.js][] objects. # - `@scene`: An object representing everything in the # environment, including `camera`s, 3D models, etc. # - `@camera`: The main rendering viewpoint, typically uses # perspective rather than orthogonal rendering. # - `@renderer`: ... I'll... get back to you about exactly # what it is that this one does! ### class Viewer constructor: (@filename,@distance = 1) -> @scene = new T.Scene() @camera = new T.PerspectiveCamera( 75,768/512,1,65536) @renderer = new T.WebGLRenderer { antialias: true, alpha: true } @renderer.setSize(768,512) @renderer.setClearColor(0x0,0) @ambient = new T.AmbientLight(0x404040) @scene.add @ambient @light = new T.DirectionalLight(0xEFEFED,1) @light.position.set(512,512,512) @model = { mesh: null material: null albedo: null normal: null specular: null } @model.material = @createMaterial( @model.albedo @model.normal @model.specular) @scene.add @light @import3D(@filename) @init() init: -> @initDOM() @initControls() @camera.position.z = @distance @render() initDOM: -> container = document.getElementById(divID) container.appendChild(@renderer.domElement) initControls: -> @controls = new T.OrbitControls( @camera,@renderer.domElement) @controls.userZoom = false ### `Viewer.render` # # This needs to be a bound function, and is the callback # used by `requestAnimationFrame`, which does a bunch of # stuff, e.g., calling render at the proper framerate. ### render: => requestAnimationFrame(@render) @controls.update() @renderer.render(@scene,@camera) ### `Viewer.import3D` # # This needs to be a bound function, and is the callback # used by the `JSONLoader` to initialize geometry from # the provided filename. ### import3D: (filename) => textureLoader.load( "#{dir}#{filename}-albedo.png" (texture) => @model.albedo = texture texture.needsUpdate = true) textureLoader.load( "#{dir}#{filename}-normal.jpg" (texture) => @model.normal = texture @loadModel(filename) texture.needsUpdate = true) #textureLoader.load( # "#{dir}#{filename}-specular.png" # (texture) => # @model.specular = texture # texture.needsUpdate = true) loadModel: (filename) => objLoader.load( "#{dir}#{filename}.obj" (object) => object.traverse (child) => return unless (child instanceof T.Mesh) #@model.mesh = child #@model.mesh.material = new T.MeshPhongMaterial { # color: 0xFFFFFF # specular: 0xAAAAAA # shininess: 10 # map: @model.albedo } mat = new T.MeshPhongMaterial { color: 0xFFFFFF specular: 0xAAAAAA shininess: 10 map: @model.albedo specularMap: @model.specular normalMap: @model.normal normalScale: new T.Vector2(0.8,0.8) } mesh = new T.Mesh(child.geometry, mat) console.log mesh #@model.mesh.material.map = @model.albedo #@model.mesh.material.normalMap = @model.normal #child.material = @createMaterial( # @model.albedo # @model.normal # @model.specular) #@model. mesh.scale.set(100,100,100) @renderer.render(@scene,@camera) @scene.add mesh) createMaterial: (albedo, normal, specular) => new T.MeshPhongMaterial { color: 0xFFFFFF specular: 0xAAAAAA shininess: 10 map: albedo specularMap: specular normalMap: normal normalScale: new T.Vector2(0.8,0.8) } ### `@createViewer` # # This is a global function, callable from other scripts, and # will be used with another script on the page to load an # arbitrary 3D model into a basic scene. ### @createViewer = (filename, distance=1) => new Viewer(filename,distance)
true
--- --- ### PI:NAME:<NAME>END_PI # 2015-10-26 # Viewer ### 'use strict' ### Constants & Aliases ### {abs,floor,random,sqrt} = Math T = THREE ### DOM ### dir = "/js/assets/" # directory divID = "CoffeeCode" # id of parent container = null # parent in document ### WebGL ### loader = new T.JSONLoader() objectLoader = new T.ObjectLoader() objLoader = new T.OBJLoader() textureLoader = new T.TextureLoader() ### `Viewer` # # This is the program entrypoint, and it initializes all of the # [Three.js][] objects. # - `@scene`: An object representing everything in the # environment, including `camera`s, 3D models, etc. # - `@camera`: The main rendering viewpoint, typically uses # perspective rather than orthogonal rendering. # - `@renderer`: ... I'll... get back to you about exactly # what it is that this one does! ### class Viewer constructor: (@filename,@distance = 1) -> @scene = new T.Scene() @camera = new T.PerspectiveCamera( 75,768/512,1,65536) @renderer = new T.WebGLRenderer { antialias: true, alpha: true } @renderer.setSize(768,512) @renderer.setClearColor(0x0,0) @ambient = new T.AmbientLight(0x404040) @scene.add @ambient @light = new T.DirectionalLight(0xEFEFED,1) @light.position.set(512,512,512) @model = { mesh: null material: null albedo: null normal: null specular: null } @model.material = @createMaterial( @model.albedo @model.normal @model.specular) @scene.add @light @import3D(@filename) @init() init: -> @initDOM() @initControls() @camera.position.z = @distance @render() initDOM: -> container = document.getElementById(divID) container.appendChild(@renderer.domElement) initControls: -> @controls = new T.OrbitControls( @camera,@renderer.domElement) @controls.userZoom = false ### `Viewer.render` # # This needs to be a bound function, and is the callback # used by `requestAnimationFrame`, which does a bunch of # stuff, e.g., calling render at the proper framerate. ### render: => requestAnimationFrame(@render) @controls.update() @renderer.render(@scene,@camera) ### `Viewer.import3D` # # This needs to be a bound function, and is the callback # used by the `JSONLoader` to initialize geometry from # the provided filename. ### import3D: (filename) => textureLoader.load( "#{dir}#{filename}-albedo.png" (texture) => @model.albedo = texture texture.needsUpdate = true) textureLoader.load( "#{dir}#{filename}-normal.jpg" (texture) => @model.normal = texture @loadModel(filename) texture.needsUpdate = true) #textureLoader.load( # "#{dir}#{filename}-specular.png" # (texture) => # @model.specular = texture # texture.needsUpdate = true) loadModel: (filename) => objLoader.load( "#{dir}#{filename}.obj" (object) => object.traverse (child) => return unless (child instanceof T.Mesh) #@model.mesh = child #@model.mesh.material = new T.MeshPhongMaterial { # color: 0xFFFFFF # specular: 0xAAAAAA # shininess: 10 # map: @model.albedo } mat = new T.MeshPhongMaterial { color: 0xFFFFFF specular: 0xAAAAAA shininess: 10 map: @model.albedo specularMap: @model.specular normalMap: @model.normal normalScale: new T.Vector2(0.8,0.8) } mesh = new T.Mesh(child.geometry, mat) console.log mesh #@model.mesh.material.map = @model.albedo #@model.mesh.material.normalMap = @model.normal #child.material = @createMaterial( # @model.albedo # @model.normal # @model.specular) #@model. mesh.scale.set(100,100,100) @renderer.render(@scene,@camera) @scene.add mesh) createMaterial: (albedo, normal, specular) => new T.MeshPhongMaterial { color: 0xFFFFFF specular: 0xAAAAAA shininess: 10 map: albedo specularMap: specular normalMap: normal normalScale: new T.Vector2(0.8,0.8) } ### `@createViewer` # # This is a global function, callable from other scripts, and # will be used with another script on the page to load an # arbitrary 3D model into a basic scene. ### @createViewer = (filename, distance=1) => new Viewer(filename,distance)
[ { "context": "eader\n header: (key, val) ->\n key = key.toLowerCase()\n @$headers[key] = val\n @\n\n\n # ", "end": 1563, "score": 0.8335217833518982, "start": 1552, "tag": "KEY", "value": "toLowerCase" } ]
src/response.coffee
SegmentFault/node-tiny-http
16
Cookie = require 'cookie' Status = require 'statuses' Zlib = require 'zlib' Stream = require 'stream' # make a monkey patch for original response object patchOriginalResponse = (res) -> originalWrite = res.write res.bytes = 0 res.write = (args...) -> buf = args[0] @bytes += buf.length originalWrite.apply @, args class Response constructor: (@res, req, @options) -> @$statusCode = 200 @$headers = 'content-type': 'text/html; charset=utf-8' @$cookies = [] @$startTime = Date.now() @$stream = null @$content = null @responded = no if @options.compression acceptEncoding = req.headers['accept-encoding'] if acceptEncoding? if acceptEncoding.match /\bdeflate\b/ @$stream = Zlib.createDeflate() @$headers['content-encoding'] = 'deflate' else if acceptEncoding.match /\bgzip\b/ @$stream = Zlib.createGzip() @$headers['content-encoding'] = 'gzip' @$stream = new Stream.PassThrough if not @$stream? patchOriginalResponse @res # set content content: (val) -> @$content = val @ # set status code status: (code) -> @$statusCode = Status code @ # set cookie cookie: (key, val, options) -> @$cookies.push Cookie.serialize key, val, options @ # set header header: (key, val) -> key = key.toLowerCase() @$headers[key] = val @ # set finish finish: (@finish) -> @res.on 'finish', => @finish.call @, @res.statusCode, @res.bytes, Date.now() - @$startTime # respond respond: -> @res.statusCode = @$statusCode @res.statusMessage = Status[@$statusCode] for key, val of @$headers key = key.replace /(^|-)([a-z])/g, (m, a, b) -> a + b.toUpperCase() @res.setHeader key, val @res.setHeader 'Set-Cookie', @$cookies if @$cookies.length > 0 @$stream.pipe @res if @$content instanceof Stream.Readable @$content.pipe @$stream else @$stream.end @$content module.exports = Response
55089
Cookie = require 'cookie' Status = require 'statuses' Zlib = require 'zlib' Stream = require 'stream' # make a monkey patch for original response object patchOriginalResponse = (res) -> originalWrite = res.write res.bytes = 0 res.write = (args...) -> buf = args[0] @bytes += buf.length originalWrite.apply @, args class Response constructor: (@res, req, @options) -> @$statusCode = 200 @$headers = 'content-type': 'text/html; charset=utf-8' @$cookies = [] @$startTime = Date.now() @$stream = null @$content = null @responded = no if @options.compression acceptEncoding = req.headers['accept-encoding'] if acceptEncoding? if acceptEncoding.match /\bdeflate\b/ @$stream = Zlib.createDeflate() @$headers['content-encoding'] = 'deflate' else if acceptEncoding.match /\bgzip\b/ @$stream = Zlib.createGzip() @$headers['content-encoding'] = 'gzip' @$stream = new Stream.PassThrough if not @$stream? patchOriginalResponse @res # set content content: (val) -> @$content = val @ # set status code status: (code) -> @$statusCode = Status code @ # set cookie cookie: (key, val, options) -> @$cookies.push Cookie.serialize key, val, options @ # set header header: (key, val) -> key = key.<KEY>() @$headers[key] = val @ # set finish finish: (@finish) -> @res.on 'finish', => @finish.call @, @res.statusCode, @res.bytes, Date.now() - @$startTime # respond respond: -> @res.statusCode = @$statusCode @res.statusMessage = Status[@$statusCode] for key, val of @$headers key = key.replace /(^|-)([a-z])/g, (m, a, b) -> a + b.toUpperCase() @res.setHeader key, val @res.setHeader 'Set-Cookie', @$cookies if @$cookies.length > 0 @$stream.pipe @res if @$content instanceof Stream.Readable @$content.pipe @$stream else @$stream.end @$content module.exports = Response
true
Cookie = require 'cookie' Status = require 'statuses' Zlib = require 'zlib' Stream = require 'stream' # make a monkey patch for original response object patchOriginalResponse = (res) -> originalWrite = res.write res.bytes = 0 res.write = (args...) -> buf = args[0] @bytes += buf.length originalWrite.apply @, args class Response constructor: (@res, req, @options) -> @$statusCode = 200 @$headers = 'content-type': 'text/html; charset=utf-8' @$cookies = [] @$startTime = Date.now() @$stream = null @$content = null @responded = no if @options.compression acceptEncoding = req.headers['accept-encoding'] if acceptEncoding? if acceptEncoding.match /\bdeflate\b/ @$stream = Zlib.createDeflate() @$headers['content-encoding'] = 'deflate' else if acceptEncoding.match /\bgzip\b/ @$stream = Zlib.createGzip() @$headers['content-encoding'] = 'gzip' @$stream = new Stream.PassThrough if not @$stream? patchOriginalResponse @res # set content content: (val) -> @$content = val @ # set status code status: (code) -> @$statusCode = Status code @ # set cookie cookie: (key, val, options) -> @$cookies.push Cookie.serialize key, val, options @ # set header header: (key, val) -> key = key.PI:KEY:<KEY>END_PI() @$headers[key] = val @ # set finish finish: (@finish) -> @res.on 'finish', => @finish.call @, @res.statusCode, @res.bytes, Date.now() - @$startTime # respond respond: -> @res.statusCode = @$statusCode @res.statusMessage = Status[@$statusCode] for key, val of @$headers key = key.replace /(^|-)([a-z])/g, (m, a, b) -> a + b.toUpperCase() @res.setHeader key, val @res.setHeader 'Set-Cookie', @$cookies if @$cookies.length > 0 @$stream.pipe @res if @$content instanceof Stream.Readable @$content.pipe @$stream else @$stream.end @$content module.exports = Response
[ { "context": "### ^\nBSD 3-Clause License\n\nCopyright (c) 2017, Stephan Jorek\nAll rights reserved.\n\nRedistribution and use in s", "end": 61, "score": 0.9998332262039185, "start": 48, "tag": "NAME", "value": "Stephan Jorek" } ]
src/Grammar.coffee
sjorek/goatee-script.js
0
### ^ BSD 3-Clause License Copyright (c) 2017, Stephan Jorek 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. * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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. ### {Parser} = require 'jison' Notator = require './Notator' Scope = require './Scope' { isString, isFunction } = require './Utility' ### # # Grammar … # ----------- # # … is always useful. ### ###* # ------------- # Implements the `goatee-script` grammar definitions. # # @class Grammar # @namepace GoateeScript ### class Grammar ###* # ------------- # Loads the our **Grammar** # # @method load # @param {String} [filename] # @return {Parser} # @static ### Grammar.load = (filename = './grammar/jison.coffee', scope = {}, notator = Notator)-> scope.goatee = new Scope() unless scope.goatee? grammar = require filename #console.log 'load', grammar, 'from', filename grammar = grammar(scope, notator) if isFunction grammar grammar.yy.goatee = scope.goatee grammar ###* # ------------- # Initializes our **Grammar** # # @method create # @param {String|Object} grammar filepath or object # @return {Grammar} # @static ### Grammar.create = (grammar = null, scope = {}, notator = Notator)-> if grammar is null or isString grammar grammar = Grammar.load(grammar, scope, notator) #console.log 'create', grammar grammar = new Grammar grammar ###* # ------------- # Create and return the parsers source code wrapped into a closure, still # keeping the value of `this`. # # @method generateParser # @param {Function} [generator] # @param {String} [comment] # @param {String} [prefix] # @param {String} [suffix] # @return {String} # @static ### Grammar.generateParser = (parser = null, comment = ''' /* Goatee Script Parser */ ''', prefix = ''' (function() { ''', suffix = ''' ; parser.yy.goatee = new (require("./Scope")); }).call(this); ''') -> if parser is null or isString parser parser = Grammar.createParser parser [comment, prefix, parser.generate(), suffix].join '' ###* # ------------- # Initializes the **Parser** with our **Grammar** # # @method createParser # @param {Grammar} [grammar] # @param {Function|Boolean} [log] # @return {Parser} # @static ### Grammar.createParser = (grammar = null, log = null) -> if grammar is null or isString grammar grammar = Grammar.create grammar # console.log 'createParser', grammar parser = new Parser grammar.grammar parser.yy.goatee = grammar.grammar.yy.goatee if log? Grammar.addLoggingToLexer(parser, if log is true then null else log) parser ###* # ------------- # Adds logging to the parser's lexer # # @method addLoggingToLexer # @param {Parser} [grammar] # @param {Function} [log] # @return {Parser} # @static ### Grammar.addLoggingToLexer = (parser, \ log = (a...) -> console.log.apply(console, a))-> lexer = parser.lexer lex = lexer.lex set = lexer.setInput lexer.lex = (args...) -> log 'lex', [lexer.match, lexer.matched] lex.apply lexer, args lexer.setInput = (args...) -> log 'set', args set.apply lexer, args parser ###* # ------------- # @property filename # @type {String} ### filename: null ###* # ------------- # @property grammar # @type {Object} ### grammar: null ###* # ------------- # Use the default jison-lexer # # @constructor ### constructor: (@grammar) -> # console.log @grammar @tokenize(@grammar) unless @grammar.tokens? ###* # ------------- # Now that we have our **Grammar.bnf** and our **Grammar.operators**, so # we can create our **Jison.Parser**. We do this by processing all of our # rules, recording all terminals (every symbol which does not appear as the # name of a rule above) as "tokens". # # @method tokenize # @param {Object|Grammar} grammar # @return {String} ### tokenize: (grammar) -> {bnf, startSymbol, operators} = grammar tokens = [] known = {} tokenizer = (name, alternatives) -> for alt in alternatives for token in alt[0].split ' ' tokens.push token if not bnf[token]? and not known[token]? known[token] = true alt[1] = "#{alt[1]}" if name is startSymbol alt for own name, alternatives of bnf bnf[name] = tokenizer(name, alternatives) grammar.known = known grammar.tokens = tokens.join ' ' ###* # ------------- # Returns an object containing parser's exportable grammar as references. # # @method toObject # @return {Object} # @private ### toObject : () -> out = startSymbol: @grammar.startSymbol bnf: @grammar.bnf lex: @grammar.lex operators: @grammar.operators tokens: @grammar.tokens yy: {} out.filename = @filename if @filename? out ###* # ------------- # Export the parsers exportable grammar as json string. # # @method toString # @param {Function|null} [replacer] # @param {Boolean|String|null} [indent] # @return {String} ### toJSONString : (replacer = null, indent = null) -> if indent? if indent is true indent = ' ' else if indent is false indent = null JSON.stringify @toObject(), replacer, indent ###* # ------------- # Export the parsers exportable grammar as json object (deep clone). # # @method toJSON # @param {Function|null} [replacer] # @return {Object} ### toJSON : (replacer = null) -> JSON.parse @toJSONString(replacer) module.exports = Grammar
38257
### ^ BSD 3-Clause License Copyright (c) 2017, <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. * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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. ### {Parser} = require 'jison' Notator = require './Notator' Scope = require './Scope' { isString, isFunction } = require './Utility' ### # # Grammar … # ----------- # # … is always useful. ### ###* # ------------- # Implements the `goatee-script` grammar definitions. # # @class Grammar # @namepace GoateeScript ### class Grammar ###* # ------------- # Loads the our **Grammar** # # @method load # @param {String} [filename] # @return {Parser} # @static ### Grammar.load = (filename = './grammar/jison.coffee', scope = {}, notator = Notator)-> scope.goatee = new Scope() unless scope.goatee? grammar = require filename #console.log 'load', grammar, 'from', filename grammar = grammar(scope, notator) if isFunction grammar grammar.yy.goatee = scope.goatee grammar ###* # ------------- # Initializes our **Grammar** # # @method create # @param {String|Object} grammar filepath or object # @return {Grammar} # @static ### Grammar.create = (grammar = null, scope = {}, notator = Notator)-> if grammar is null or isString grammar grammar = Grammar.load(grammar, scope, notator) #console.log 'create', grammar grammar = new Grammar grammar ###* # ------------- # Create and return the parsers source code wrapped into a closure, still # keeping the value of `this`. # # @method generateParser # @param {Function} [generator] # @param {String} [comment] # @param {String} [prefix] # @param {String} [suffix] # @return {String} # @static ### Grammar.generateParser = (parser = null, comment = ''' /* Goatee Script Parser */ ''', prefix = ''' (function() { ''', suffix = ''' ; parser.yy.goatee = new (require("./Scope")); }).call(this); ''') -> if parser is null or isString parser parser = Grammar.createParser parser [comment, prefix, parser.generate(), suffix].join '' ###* # ------------- # Initializes the **Parser** with our **Grammar** # # @method createParser # @param {Grammar} [grammar] # @param {Function|Boolean} [log] # @return {Parser} # @static ### Grammar.createParser = (grammar = null, log = null) -> if grammar is null or isString grammar grammar = Grammar.create grammar # console.log 'createParser', grammar parser = new Parser grammar.grammar parser.yy.goatee = grammar.grammar.yy.goatee if log? Grammar.addLoggingToLexer(parser, if log is true then null else log) parser ###* # ------------- # Adds logging to the parser's lexer # # @method addLoggingToLexer # @param {Parser} [grammar] # @param {Function} [log] # @return {Parser} # @static ### Grammar.addLoggingToLexer = (parser, \ log = (a...) -> console.log.apply(console, a))-> lexer = parser.lexer lex = lexer.lex set = lexer.setInput lexer.lex = (args...) -> log 'lex', [lexer.match, lexer.matched] lex.apply lexer, args lexer.setInput = (args...) -> log 'set', args set.apply lexer, args parser ###* # ------------- # @property filename # @type {String} ### filename: null ###* # ------------- # @property grammar # @type {Object} ### grammar: null ###* # ------------- # Use the default jison-lexer # # @constructor ### constructor: (@grammar) -> # console.log @grammar @tokenize(@grammar) unless @grammar.tokens? ###* # ------------- # Now that we have our **Grammar.bnf** and our **Grammar.operators**, so # we can create our **Jison.Parser**. We do this by processing all of our # rules, recording all terminals (every symbol which does not appear as the # name of a rule above) as "tokens". # # @method tokenize # @param {Object|Grammar} grammar # @return {String} ### tokenize: (grammar) -> {bnf, startSymbol, operators} = grammar tokens = [] known = {} tokenizer = (name, alternatives) -> for alt in alternatives for token in alt[0].split ' ' tokens.push token if not bnf[token]? and not known[token]? known[token] = true alt[1] = "#{alt[1]}" if name is startSymbol alt for own name, alternatives of bnf bnf[name] = tokenizer(name, alternatives) grammar.known = known grammar.tokens = tokens.join ' ' ###* # ------------- # Returns an object containing parser's exportable grammar as references. # # @method toObject # @return {Object} # @private ### toObject : () -> out = startSymbol: @grammar.startSymbol bnf: @grammar.bnf lex: @grammar.lex operators: @grammar.operators tokens: @grammar.tokens yy: {} out.filename = @filename if @filename? out ###* # ------------- # Export the parsers exportable grammar as json string. # # @method toString # @param {Function|null} [replacer] # @param {Boolean|String|null} [indent] # @return {String} ### toJSONString : (replacer = null, indent = null) -> if indent? if indent is true indent = ' ' else if indent is false indent = null JSON.stringify @toObject(), replacer, indent ###* # ------------- # Export the parsers exportable grammar as json object (deep clone). # # @method toJSON # @param {Function|null} [replacer] # @return {Object} ### toJSON : (replacer = null) -> JSON.parse @toJSONString(replacer) module.exports = Grammar
true
### ^ BSD 3-Clause License Copyright (c) 2017, 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. * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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. ### {Parser} = require 'jison' Notator = require './Notator' Scope = require './Scope' { isString, isFunction } = require './Utility' ### # # Grammar … # ----------- # # … is always useful. ### ###* # ------------- # Implements the `goatee-script` grammar definitions. # # @class Grammar # @namepace GoateeScript ### class Grammar ###* # ------------- # Loads the our **Grammar** # # @method load # @param {String} [filename] # @return {Parser} # @static ### Grammar.load = (filename = './grammar/jison.coffee', scope = {}, notator = Notator)-> scope.goatee = new Scope() unless scope.goatee? grammar = require filename #console.log 'load', grammar, 'from', filename grammar = grammar(scope, notator) if isFunction grammar grammar.yy.goatee = scope.goatee grammar ###* # ------------- # Initializes our **Grammar** # # @method create # @param {String|Object} grammar filepath or object # @return {Grammar} # @static ### Grammar.create = (grammar = null, scope = {}, notator = Notator)-> if grammar is null or isString grammar grammar = Grammar.load(grammar, scope, notator) #console.log 'create', grammar grammar = new Grammar grammar ###* # ------------- # Create and return the parsers source code wrapped into a closure, still # keeping the value of `this`. # # @method generateParser # @param {Function} [generator] # @param {String} [comment] # @param {String} [prefix] # @param {String} [suffix] # @return {String} # @static ### Grammar.generateParser = (parser = null, comment = ''' /* Goatee Script Parser */ ''', prefix = ''' (function() { ''', suffix = ''' ; parser.yy.goatee = new (require("./Scope")); }).call(this); ''') -> if parser is null or isString parser parser = Grammar.createParser parser [comment, prefix, parser.generate(), suffix].join '' ###* # ------------- # Initializes the **Parser** with our **Grammar** # # @method createParser # @param {Grammar} [grammar] # @param {Function|Boolean} [log] # @return {Parser} # @static ### Grammar.createParser = (grammar = null, log = null) -> if grammar is null or isString grammar grammar = Grammar.create grammar # console.log 'createParser', grammar parser = new Parser grammar.grammar parser.yy.goatee = grammar.grammar.yy.goatee if log? Grammar.addLoggingToLexer(parser, if log is true then null else log) parser ###* # ------------- # Adds logging to the parser's lexer # # @method addLoggingToLexer # @param {Parser} [grammar] # @param {Function} [log] # @return {Parser} # @static ### Grammar.addLoggingToLexer = (parser, \ log = (a...) -> console.log.apply(console, a))-> lexer = parser.lexer lex = lexer.lex set = lexer.setInput lexer.lex = (args...) -> log 'lex', [lexer.match, lexer.matched] lex.apply lexer, args lexer.setInput = (args...) -> log 'set', args set.apply lexer, args parser ###* # ------------- # @property filename # @type {String} ### filename: null ###* # ------------- # @property grammar # @type {Object} ### grammar: null ###* # ------------- # Use the default jison-lexer # # @constructor ### constructor: (@grammar) -> # console.log @grammar @tokenize(@grammar) unless @grammar.tokens? ###* # ------------- # Now that we have our **Grammar.bnf** and our **Grammar.operators**, so # we can create our **Jison.Parser**. We do this by processing all of our # rules, recording all terminals (every symbol which does not appear as the # name of a rule above) as "tokens". # # @method tokenize # @param {Object|Grammar} grammar # @return {String} ### tokenize: (grammar) -> {bnf, startSymbol, operators} = grammar tokens = [] known = {} tokenizer = (name, alternatives) -> for alt in alternatives for token in alt[0].split ' ' tokens.push token if not bnf[token]? and not known[token]? known[token] = true alt[1] = "#{alt[1]}" if name is startSymbol alt for own name, alternatives of bnf bnf[name] = tokenizer(name, alternatives) grammar.known = known grammar.tokens = tokens.join ' ' ###* # ------------- # Returns an object containing parser's exportable grammar as references. # # @method toObject # @return {Object} # @private ### toObject : () -> out = startSymbol: @grammar.startSymbol bnf: @grammar.bnf lex: @grammar.lex operators: @grammar.operators tokens: @grammar.tokens yy: {} out.filename = @filename if @filename? out ###* # ------------- # Export the parsers exportable grammar as json string. # # @method toString # @param {Function|null} [replacer] # @param {Boolean|String|null} [indent] # @return {String} ### toJSONString : (replacer = null, indent = null) -> if indent? if indent is true indent = ' ' else if indent is false indent = null JSON.stringify @toObject(), replacer, indent ###* # ------------- # Export the parsers exportable grammar as json object (deep clone). # # @method toJSON # @param {Function|null} [replacer] # @return {Object} ### toJSON : (replacer = null) -> JSON.parse @toJSONString(replacer) module.exports = Grammar
[ { "context": " bencodedString = 'd3:agei100e4:infod5:email13:dude@dude.com6:numberi2488081446ee4:name8:the dudee'\n expec", "end": 1459, "score": 0.9923046827316284, "start": 1445, "tag": "EMAIL", "value": "dude@dude.com6" }, { "context": "e8:the dudee'\n expected = { ag...
test/decode_spec.coffee
benjreinhart/bencode-js
32
{ decode } = require '../' { expect } = require 'chai' describe 'decoding', -> describe 'strings', -> it 'with a basic value returns the string', -> expect(decode '10:helloworld').to.equal 'helloworld' it 'with a colon in them returns the correct string', -> expect(decode '12:0.0.0.0:3000').to.equal '0.0.0.0:3000' describe 'integers', -> it 'is the integer between i and e', -> expect(decode 'i42e').to.equal 42 it 'allows negative numbers', -> expect(decode 'i-42e').to.equal -42 it 'allows zeros', -> expect(decode 'i0e').to.equal 0 describe 'lists', -> it 'creates a list with strings and integers', -> expect(decode 'l5:helloi42ee').to.eql ['hello', 42] it 'creates a list with nested lists of strings and integers', -> expect(decode 'l5:helloi42eli-1ei0ei1ei2ei3e4:fouree').to.eql ['hello', 42, [-1, 0, 1, 2, 3, 'four']] it 'has no problem with multiple empty lists or objects', -> expect(decode 'lllleeee').to.eql [[[[]]]] expect(decode 'llelelelleee').to.eql [[], [], [], [[]]] expect(decode 'ldededee').to.eql [{}, {}, {}] describe 'dictionaries', -> it 'creates an object with strings and integers', -> expect(decode 'd3:agei100e4:name8:the dudee').to.eql { age: 100, name: 'the dude' } it 'creates an object with nested objects of strings and integers', -> bencodedString = 'd3:agei100e4:infod5:email13:dude@dude.com6:numberi2488081446ee4:name8:the dudee' expected = { age: 100, name: 'the dude', info: { email: 'dude@dude.com', number: 2488081446 } } expect(decode bencodedString).to.eql expected it 'has no problem with an empty object', -> expect(decode 'de').to.eql {} describe 'lists and dictionaries', -> it 'creates an object with a list of objects', -> bencodedString = 'd9:locationsld7:address10:484 streeted7:address10:828 streeteee' expected = { locations: [{ address: '484 street' }, { address: '828 street' } ]} expect(decode bencodedString).to.eql expected it 'has no problem when there are multiple "e"s in a row', -> bencodedString = 'lld9:favoritesleeei500ee' expected = [[{ favorites: [] }], 500] expect(decode bencodedString).to.eql expected
97486
{ decode } = require '../' { expect } = require 'chai' describe 'decoding', -> describe 'strings', -> it 'with a basic value returns the string', -> expect(decode '10:helloworld').to.equal 'helloworld' it 'with a colon in them returns the correct string', -> expect(decode '12:0.0.0.0:3000').to.equal '0.0.0.0:3000' describe 'integers', -> it 'is the integer between i and e', -> expect(decode 'i42e').to.equal 42 it 'allows negative numbers', -> expect(decode 'i-42e').to.equal -42 it 'allows zeros', -> expect(decode 'i0e').to.equal 0 describe 'lists', -> it 'creates a list with strings and integers', -> expect(decode 'l5:helloi42ee').to.eql ['hello', 42] it 'creates a list with nested lists of strings and integers', -> expect(decode 'l5:helloi42eli-1ei0ei1ei2ei3e4:fouree').to.eql ['hello', 42, [-1, 0, 1, 2, 3, 'four']] it 'has no problem with multiple empty lists or objects', -> expect(decode 'lllleeee').to.eql [[[[]]]] expect(decode 'llelelelleee').to.eql [[], [], [], [[]]] expect(decode 'ldededee').to.eql [{}, {}, {}] describe 'dictionaries', -> it 'creates an object with strings and integers', -> expect(decode 'd3:agei100e4:name8:the dudee').to.eql { age: 100, name: 'the dude' } it 'creates an object with nested objects of strings and integers', -> bencodedString = 'd3:agei100e4:infod5:email13:<EMAIL>:numberi2488081446ee4:name8:the dudee' expected = { age: 100, name: '<NAME>', info: { email: '<EMAIL>', number: 2488081446 } } expect(decode bencodedString).to.eql expected it 'has no problem with an empty object', -> expect(decode 'de').to.eql {} describe 'lists and dictionaries', -> it 'creates an object with a list of objects', -> bencodedString = 'd9:locationsld7:address10:484 streeted7:address10:828 streeteee' expected = { locations: [{ address: '484 street' }, { address: '828 street' } ]} expect(decode bencodedString).to.eql expected it 'has no problem when there are multiple "e"s in a row', -> bencodedString = 'lld9:favoritesleeei500ee' expected = [[{ favorites: [] }], 500] expect(decode bencodedString).to.eql expected
true
{ decode } = require '../' { expect } = require 'chai' describe 'decoding', -> describe 'strings', -> it 'with a basic value returns the string', -> expect(decode '10:helloworld').to.equal 'helloworld' it 'with a colon in them returns the correct string', -> expect(decode '12:0.0.0.0:3000').to.equal '0.0.0.0:3000' describe 'integers', -> it 'is the integer between i and e', -> expect(decode 'i42e').to.equal 42 it 'allows negative numbers', -> expect(decode 'i-42e').to.equal -42 it 'allows zeros', -> expect(decode 'i0e').to.equal 0 describe 'lists', -> it 'creates a list with strings and integers', -> expect(decode 'l5:helloi42ee').to.eql ['hello', 42] it 'creates a list with nested lists of strings and integers', -> expect(decode 'l5:helloi42eli-1ei0ei1ei2ei3e4:fouree').to.eql ['hello', 42, [-1, 0, 1, 2, 3, 'four']] it 'has no problem with multiple empty lists or objects', -> expect(decode 'lllleeee').to.eql [[[[]]]] expect(decode 'llelelelleee').to.eql [[], [], [], [[]]] expect(decode 'ldededee').to.eql [{}, {}, {}] describe 'dictionaries', -> it 'creates an object with strings and integers', -> expect(decode 'd3:agei100e4:name8:the dudee').to.eql { age: 100, name: 'the dude' } it 'creates an object with nested objects of strings and integers', -> bencodedString = 'd3:agei100e4:infod5:email13:PI:EMAIL:<EMAIL>END_PI:numberi2488081446ee4:name8:the dudee' expected = { age: 100, name: 'PI:NAME:<NAME>END_PI', info: { email: 'PI:EMAIL:<EMAIL>END_PI', number: 2488081446 } } expect(decode bencodedString).to.eql expected it 'has no problem with an empty object', -> expect(decode 'de').to.eql {} describe 'lists and dictionaries', -> it 'creates an object with a list of objects', -> bencodedString = 'd9:locationsld7:address10:484 streeted7:address10:828 streeteee' expected = { locations: [{ address: '484 street' }, { address: '828 street' } ]} expect(decode bencodedString).to.eql expected it 'has no problem when there are multiple "e"s in a row', -> bencodedString = 'lld9:favoritesleeei500ee' expected = [[{ favorites: [] }], 500] expect(decode bencodedString).to.eql expected
[ { "context": "n created', ->\n user = new User {\n name: 'Luiz Freneda'\n email: 'lfreneda@gmail.com'\n property", "end": 213, "score": 0.9998654127120972, "start": 201, "tag": "NAME", "value": "Luiz Freneda" }, { "context": "w User {\n name: 'Luiz Freneda'\n ...
test/app/users/models/user.spec.coffee
lfreneda/restify-api-design
0
User = require './../../../../src/app/models/users/user' expect = require('chai').expect describe 'User Model', -> it 'User should be sanitized when created', -> user = new User { name: 'Luiz Freneda' email: 'lfreneda@gmail.com' propertyShouldBeRemoved: 32 } expect(JSON.stringify(user)).to.equal '{"name":"Luiz Freneda","email":"lfreneda@gmail.com"}'
217535
User = require './../../../../src/app/models/users/user' expect = require('chai').expect describe 'User Model', -> it 'User should be sanitized when created', -> user = new User { name: '<NAME>' email: '<EMAIL>' propertyShouldBeRemoved: 32 } expect(JSON.stringify(user)).to.equal '{"name":"<NAME>","email":"<EMAIL>"}'
true
User = require './../../../../src/app/models/users/user' expect = require('chai').expect describe 'User Model', -> it 'User should be sanitized when created', -> user = new User { name: 'PI:NAME:<NAME>END_PI' email: 'PI:EMAIL:<EMAIL>END_PI' propertyShouldBeRemoved: 32 } expect(JSON.stringify(user)).to.equal '{"name":"PI:NAME:<NAME>END_PI","email":"PI:EMAIL:<EMAIL>END_PI"}'
[ { "context": " # turn on stats\n\n model = new Contact({name: 'Ringo', number: '555-555-5556'})\n view_model = kb.vi", "end": 972, "score": 0.9997791051864624, "start": 967, "tag": "NAME", "value": "Ringo" }, { "context": ")\n\n # get\n assert.equal(view_model.name(), 'Ri...
test/spec/core/view-model.tests.coffee
metacommunications/knockback
0
assert = assert or require?('chai').assert describe 'view-model @quick @view-model', -> kb = window?.kb; try kb or= require?('knockback') catch; try kb or= require?('../../../knockback') {_, ko, $} = kb it 'TEST DEPENDENCY MISSING', (done) -> assert.ok(!!ko, 'ko') assert.ok(!!_, '_') assert.ok(!!kb.Model, 'kb.Model') assert.ok(!!kb.Collection, 'kb.Collection') assert.ok(!!kb, 'kb') done() Contact = if kb.Parse then kb.Model.extend('Contact', { defaults: {name: '', number: 0, date: new Date()} }) else kb.Model.extend({ defaults: {name: '', number: 0, date: new Date()} }) Contacts = kb.Collection.extend({model: Contact}) class TestViewModel extends kb.ViewModel constructor: -> super @test = ko.observable('hello') value = @test() value = @name() it '1. Standard use case: read and write', (done) -> kb.statistics = new kb.Statistics() # turn on stats model = new Contact({name: 'Ringo', number: '555-555-5556'}) view_model = kb.viewModel(model) # get assert.equal(view_model.name(), 'Ringo', "Interesting name") assert.equal(view_model.number(), '555-555-5556', "Not so interesting number") # set from the view model view_model.number('9222-222-222') assert.equal(model.get('number'), '9222-222-222', "Number was changed") assert.equal(view_model.number(), '9222-222-222', "Number was changed") # set from the model model.set({name: 'Starr', number: 'XXX-XXX-XXXX'}) assert.equal(view_model.name(), 'Starr', "Name changed") assert.equal(view_model.number(), 'XXX-XXX-XXXX', "Number was changed") # and cleanup after yourself when you are done. kb.release(view_model) assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done() it '2. Using Coffeescript classes', (done) -> kb.statistics = new kb.Statistics() # turn on stats class ContactViewModelCustom extends kb.ViewModel constructor: (model) -> super(model, {internals: ['name', 'number']}) @name = ko.computed(=> return "First: #{@_name()}") model = new Contact({name: 'Ringo', number: '555-555-5556'}) view_model = new ContactViewModelCustom(model) # get assert.equal(view_model._name(), 'Ringo', "Interesting name") assert.equal(view_model.name(), 'First: Ringo', "Interesting name") # set from the model model.set({name: 'Starr'}) assert.equal(view_model._name(), 'Starr', "Name changed") assert.equal(view_model.name(), 'First: Starr', "Name changed") # set from the generated attribute view_model._name('Ringo') assert.equal(view_model._name(), 'Ringo', "Interesting name") assert.equal(view_model.name(), 'First: Ringo', "Interesting name") # and cleanup after yourself when you are done. kb.release(view_model) assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done() it '3. Using simple Javascript classes', (done) -> kb.statistics = new kb.Statistics() # turn on stats ContactViewModelCustom = (model) -> view_model = kb.viewModel(model) view_model.formatted_name = kb.observable(model, {key:'name', read: -> return "First: #{model.get('name')}" }) view_model.formatted_number = kb.observable(model, { key:'number' read: -> return "#: #{model.get('number')}" write: (value) -> model.set({number: value.substring(3)}) }, view_model) return view_model model = new Contact({name: 'Ringo', number: '555-555-5556'}) view_model = new ContactViewModelCustom(model) # get assert.equal(view_model.name(), 'Ringo', "Interesting name") assert.equal(view_model.formatted_name(), 'First: Ringo', "Interesting name") assert.equal(view_model.number(), '555-555-5556', "Not so interesting number") assert.equal(view_model.formatted_number(), '#: 555-555-5556', "Not so interesting number") # set from the view model view_model.formatted_number('#: 9222-222-222') assert.equal(model.get('number'), '9222-222-222', "Number was changed") assert.equal(view_model.number(), '9222-222-222', "Number was changed") assert.equal(view_model.formatted_number(), '#: 9222-222-222', "Number was changed") # set from the model model.set({name: 'Starr', number: 'XXX-XXX-XXXX'}) assert.equal(view_model.name(), 'Starr', "Name changed") assert.equal(view_model.formatted_name(), 'First: Starr', "Name changed") assert.equal(view_model.number(), 'XXX-XXX-XXXX', "Number was changed") assert.equal(view_model.formatted_number(), '#: XXX-XXX-XXXX', "Number was changed") # and cleanup after yourself when you are done. kb.release(view_model) assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done() it '4. requires', (done) -> kb.statistics = new kb.Statistics() # turn on stats class ContactViewModelFullName extends kb.ViewModel constructor: (model) -> super(model, {requires: ['first', 'last']}) @full_name = ko.computed(=> "Last: #{@last()}, First: #{@first()}") model = new kb.Model() view_model = new ContactViewModelFullName(model) assert.equal(view_model.full_name(), 'Last: null, First: null', "full name is good") model.set({first: 'Ringo', last: 'Starr'}) assert.equal(view_model.full_name(), 'Last: Starr, First: Ringo', "full name is good") model.set({first: 'Bongo'}) assert.equal(view_model.full_name(), 'Last: Starr, First: Bongo', "full name is good") # clean up kb.release(view_model) class ContactViewModelFullName2 extends kb.ViewModel constructor: (model) -> super(model, {requires: 'first'}) @last = kb.observable(model, 'last') @full_name = ko.computed(=> "Last: #{@last()}, First: #{@first()}") model = new kb.Model() view_model = new ContactViewModelFullName2(model) assert.equal(view_model.full_name(), 'Last: null, First: null', "full name is good") model.set({first: 'Ringo', last: 'Starr'}) assert.equal(view_model.full_name(), 'Last: Starr, First: Ringo', "full name is good") model.set({first: 'Bongo'}) assert.equal(view_model.full_name(), 'Last: Starr, First: Bongo', "full name is good") # clean up kb.release(view_model) assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done() it '5. reference counting and custom __destroy (Coffeescript inheritance)', (done) -> kb.statistics = new kb.Statistics() # turn on stats class ContactViewModelFullName extends kb.ViewModel constructor: (model) -> super(model, {requires: ['first', 'last']}) @is_destroyed = false # monkey patch reference counting @ref_count = 1 @super_destroy = @destroy; @destroy = null @is_destroyed = false retain: -> @ref_count++ refCount: -> return @ref_count release: -> --@ref_count throw new Error 'ref count is corrupt' if @ref_count < 0 return if @ref_count @is_destroyed = true @super_destroy() model = new kb.Model({first: "Hello"}) view_model = new ContactViewModelFullName(model) assert.equal(view_model.first(), "Hello", "Hello exists") view_model.retain() assert.equal(view_model.refCount(), 2, "ref count 2") assert.equal(view_model.is_destroyed, false, "not destroyed") view_model.release() assert.equal(view_model.refCount(), 1, "ref count 1") assert.equal(view_model.is_destroyed, false, "not destroyed") kb.release(view_model) assert.equal(view_model.refCount(), 0, "ref count 0") assert.equal(view_model.is_destroyed, true, "is destroyed using overridden destroy function") assert.ok(!view_model.first, "Hello doesn't exist anymore") assert.throw((->view_model.release()), Error, "ref count is corrupt") assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done() it '6. reference counting and custom __destroy (Javascript inheritance)', (done) -> kb.statistics = new kb.Statistics() # turn on stats ContactViewModelFullName = kb.ViewModel.extend({ constructor: (model) -> kb.ViewModel.prototype.constructor.call(this, model, {requires: ['first', 'last']}) # monkey patch reference counting @ref_count = 1 @super_destroy = @destroy; @destroy = null @is_destroyed = false retain: -> @ref_count++ refCount: -> return @ref_count release: -> --@ref_count throw new Error "ref count is corrupt" if @ref_count < 0 return if @ref_count @is_destroyed = true @super_destroy() }) model = new kb.Model({first: "Hello"}) view_model = new ContactViewModelFullName(model) assert.equal(view_model.first(), "Hello", "Hello exists") view_model.retain() assert.equal(view_model.refCount(), 2, "ref count 2") assert.equal(view_model.is_destroyed, false, "not destroyed") view_model.release() assert.equal(view_model.refCount(), 1, "ref count 1") assert.equal(view_model.is_destroyed, false, "not destroyed") kb.release(view_model) assert.equal(view_model.refCount(), 0, "ref count 0") assert.equal(view_model.is_destroyed, true, "is destroyed using overridden destroy function") assert.ok(!view_model.first, "Hello doesn't exist anymore") assert.throw((->view_model.release()), Error, "ref count is corrupt") assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done() it '7. Nested custom view models', (done) -> kb.statistics = new kb.Statistics() # turn on stats class ContactViewModelDate extends kb.ViewModel constructor: (model, options) -> super(model, _.extend({requires: ['date']}, options)) john_birthdate = new Date(1940, 10, 9) john = new Contact({name: 'John', date: new Date(john_birthdate.valueOf())}) paul_birthdate = new Date(1942, 6, 18) paul = new Contact({name: 'Paul', date: new Date(paul_birthdate.valueOf())}) george_birthdate = new Date(1943, 2, 25) george = new Contact({name: 'George', date: new Date(george_birthdate.valueOf())}) ringo_birthdate = new Date(1940, 7, 7) ringo = new Contact({name: 'Ringo', date: new Date(ringo_birthdate.valueOf())}) major_duo = new kb.Collection([john, paul]) minor_duo = new kb.Collection([george, ringo]) nested_model = new kb.Model({ john: john paul: paul george: george ringo: ringo major_duo1: major_duo major_duo2: major_duo major_duo3: major_duo minor_duo1: minor_duo minor_duo2: minor_duo minor_duo3: minor_duo }) nested_view_model = kb.viewModel(nested_model, { factories: john: ContactViewModelDate george: {create: (model, options) -> return new ContactViewModelDate(model, options)} 'major_duo1.models': ContactViewModelDate 'major_duo2.models': {create: (model, options) -> return new ContactViewModelDate(model, options)} 'major_duo3.models': {models_only: true} 'minor_duo1.models': kb.ViewModel 'minor_duo2.models': {create: (model, options) -> return new kb.ViewModel(model, options)} }) validateContactViewModel = (view_model, name, birthdate) -> model = kb.utils.wrappedModel(view_model) assert.equal(view_model.name(), name, "#{name}: Name matches") # set from the view model view_model.date(new Date(1963, 11, 10)) current_date = model.get('date') assert.equal(current_date.getFullYear(), 1963, "#{name}: year is good") assert.equal(current_date.getMonth(), 11, "#{name}: month is good") assert.equal(current_date.getDate(), 10, "#{name}: day is good") assert.equal(view_model.date().getFullYear(), 1963, "#{name}: year is good") assert.equal(view_model.date().getMonth(), 11, "#{name}: month is good") assert.equal(view_model.date().getDate(), 10, "#{name}: day is good") model.set({date: new Date(birthdate.valueOf())}) # restore birthdate # set from the model view_model.date(new Date(1940, 10, 10)) current_date = model.get('date') assert.equal(current_date.getFullYear(), 1940, "#{name}: year is good") assert.equal(current_date.getMonth(), 10, "#{name}: month is good") assert.equal(current_date.getDate(), 10, "#{name}: day is good") assert.equal(view_model.date().getFullYear(), 1940, "#{name}: year is good") assert.equal(view_model.date().getMonth(), 10, "#{name}: month is good") assert.equal(view_model.date().getDate(), 10, "#{name}: day is good") model.set({date: new Date(birthdate.valueOf())}) # restore birthdate validateGenericViewModel = (view_model, name, birthdate) -> assert.equal(view_model.name(), name, "#{name}: Name matches") assert.equal(view_model.date().valueOf(), birthdate.valueOf(), "#{name}: Birthdate matches") validateModel = (model, name, birthdate) -> assert.equal(model.get('name'), name, "#{name}: Name matches") assert.equal(model.get('date').valueOf(), birthdate.valueOf(), "#{name}: Birthdate matches") # models validateContactViewModel(nested_view_model.john(), 'John', john_birthdate) validateGenericViewModel(nested_view_model.paul(), 'Paul', paul_birthdate) validateContactViewModel(nested_view_model.george(), 'George', george_birthdate) validateGenericViewModel(nested_view_model.ringo(), 'Ringo', ringo_birthdate) # colllections validateContactViewModel(nested_view_model.major_duo1()[0], 'John', john_birthdate) validateContactViewModel(nested_view_model.major_duo1()[1], 'Paul', paul_birthdate) validateContactViewModel(nested_view_model.major_duo2()[0], 'John', john_birthdate) validateContactViewModel(nested_view_model.major_duo2()[1], 'Paul', paul_birthdate) validateModel(nested_view_model.major_duo3()[0], 'John', john_birthdate) validateModel(nested_view_model.major_duo3()[1], 'Paul', paul_birthdate) validateGenericViewModel(nested_view_model.minor_duo1()[0], 'George', george_birthdate) validateGenericViewModel(nested_view_model.minor_duo1()[1], 'Ringo', ringo_birthdate) validateGenericViewModel(nested_view_model.minor_duo2()[0], 'George', george_birthdate) validateGenericViewModel(nested_view_model.minor_duo2()[1], 'Ringo', ringo_birthdate) validateGenericViewModel(nested_view_model.minor_duo3()[0], 'George', george_birthdate) validateGenericViewModel(nested_view_model.minor_duo3()[1], 'Ringo', ringo_birthdate) # and cleanup after yourself when you are done. kb.release(nested_view_model) assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done() it '8. Changing attribute types', (done) -> kb.statistics = new kb.Statistics() # turn on stats model = new kb.Model({reused: null}) view_model = kb.viewModel(model) assert.equal(kb.utils.valueType(view_model.reused), kb.TYPE_SIMPLE, 'reused is kb.TYPE_SIMPLE') model.set({reused: new kb.Model()}) assert.equal(kb.utils.valueType(view_model.reused), kb.TYPE_MODEL, 'reused is kb.TYPE_MODEL') model.set({reused: new kb.Collection()}) assert.equal(kb.utils.valueType(view_model.reused), kb.TYPE_COLLECTION, 'reused is kb.TYPE_COLLECTION') model.set({reused: null}) assert.equal(kb.utils.valueType(view_model.reused), kb.TYPE_COLLECTION, 'reused is retains type of kb.TYPE_COLLECTION') # clean up kb.release(view_model) # add custom mapping view_model = kb.viewModel(model, {factories: reused: (obj, options) -> return if obj instanceof kb.Collection then kb.collectionObservable(obj, options) else kb.viewModel(obj, options) }) assert.equal(kb.utils.valueType(view_model.reused), kb.TYPE_MODEL, 'reused is kb.TYPE_MODEL') model.set({reused: new kb.Model()}) assert.equal(kb.utils.valueType(view_model.reused), kb.TYPE_MODEL, 'reused is kb.TYPE_MODEL') model.set({reused: new kb.Collection()}) assert.equal(kb.utils.valueType(view_model.reused), kb.TYPE_COLLECTION, 'reused is kb.TYPE_COLLECTION') model.set({reused: null}) assert.equal(kb.utils.valueType(view_model.reused), kb.TYPE_COLLECTION, 'reused retains type of kb.TYPE_COLLECTION') # clean up kb.release(view_model) assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done() it '9. Shared Options', (done) -> kb.statistics = new kb.Statistics() # turn on stats model1 = new kb.Model({id: 1, name: 'Bob'}) model2 = new kb.Model({id: 1, name: 'Bob'}) model3 = new kb.Model({id: 1, name: 'Bob'}) view_model1 = kb.viewModel(model1) view_model2 = kb.viewModel(model2) view_model3 = kb.viewModel(model3, view_model1.shareOptions()) assert.ok((view_model1.name isnt view_model2.name) and (view_model1.name() is view_model2.name()), 'not sharing') assert.ok((view_model1.name isnt view_model3.name) and (view_model1.name() is view_model3.name()), 'sharing') kb.release([view_model1, view_model2, view_model3]) assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done() it '10. Options', (done) -> kb.statistics = new kb.Statistics() # turn on stats # keys - array view_model = kb.viewModel(new kb.Model({name: 'Bob'}), keys: ['name', 'date']) assert.equal(view_model.name(), 'Bob', 'keys: Bob') assert.ok(view_model.date, 'keys: date') assert.equal(view_model.date(), null, 'keys: date fn') kb.release(view_model) # keys - no array view_model = kb.viewModel(new kb.Model({name: 'Bob'}), keys: 'date') assert.ok(view_model.date, 'keys: date') assert.equal(view_model.date(), null, 'keys: date fn') kb.release(view_model) # keys - object view_model = kb.viewModel(new kb.Model({name: 'Bob'}), keys: {name: {}, date: {}}) assert.equal(view_model.name(), 'Bob', 'keys: Bob') assert.ok(view_model.date, 'keys: date') assert.equal(view_model.date(), null, 'keys: date fn') kb.release(view_model) # excludes view_model = kb.viewModel(new kb.Model({name: 'Bob', date: new Date()}), excludes: ['date']) assert.equal(view_model.name(), 'Bob', 'excludes: Bob') assert.ok(not view_model.date, 'excludes: date') kb.release(view_model) # excludes - no array view_model = kb.viewModel(new kb.Model({name: 'Bob', date: new Date()}), excludes: 'date') assert.equal(view_model.name(), 'Bob', 'excludes: Bob') assert.ok(not view_model.date, 'excludes: date') kb.release(view_model) # requires view_model = kb.viewModel(new kb.Model(), requires: ['name']) assert.equal(view_model.name(), null, 'requires: name') assert.ok(not view_model.date, 'requires: date') kb.release(view_model) # requires - no array view_model = kb.viewModel(new kb.Model(), requires: 'name') assert.equal(view_model.name(), null, 'requires: name') assert.ok(not view_model.date, 'requires: date') kb.release(view_model) # internals view_model = kb.viewModel(new kb.Model(), internals: ['name']) assert.equal(view_model._name(), null, 'internals: name') assert.ok(not view_model.date, 'internals: date') kb.release(view_model) # internals - no array view_model = kb.viewModel(new kb.Model(), internals: 'name') assert.equal(view_model._name(), null, 'internals: name') assert.ok(not view_model.date, 'internals: date') kb.release(view_model) # mappings view_model = kb.viewModel(new kb.Model(), mappings: {name: {}}) assert.equal(view_model.name(), null, 'mappings: name') assert.ok(not view_model.date, 'mappings: date') kb.release(view_model) assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done() it '11. array attributes', (done) -> model = new kb.Model text: ["heading.get these rewards"] widget: ["sign_up", "rewards"] model_data: reward: top_rewards: properties: ["title", "description", "num_points"] query: type: "active" limit: 6 view_model = kb.viewModel model assert.ok(_.isEqual(view_model.text(), ["heading.get these rewards"]), 'text observable matches') assert.ok(_.isEqual(view_model.widget(), ["sign_up", "rewards"]), 'widget observable matches') assert.ok(_.isEqual(view_model.model_data().reward.top_rewards.properties, ["title", "description", "num_points"]), 'model_data observable matches') done() it '12. model change is observable', (done) -> kb.statistics = new kb.Statistics() # turn on stats model = new kb.Model({id: 1, name: 'Bob'}) view_model = kb.viewModel(model) count = 0 ko.computed(-> view_model.model(); count++) view_model.model(null) view_model.model(model) assert.equal(count, 3, "model change was observed") kb.release(view_model) assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done() it '13. model replacement', (done) -> kb.statistics = new kb.Statistics() model_opts = attributes: prop: 1 defaults: prop: 1 Model = if kb.Parse then kb.Model.extend('Model', model_opts) else kb.Model.extend(model_opts) model1 = new Model view_model = kb.viewModel(model1) assert.equal(view_model.prop(), 1, "sanity check") model2 = new Model({ prop: 2 }) assert.equal(model2.get('prop'), 2, "sanity check 2") view_model.model(model2) assert.equal(model2.get('prop'), 2, "switched in model shouldn't inherit values from previous model") assert.equal(view_model.prop(), 2, "view model should have the value of the switched in model") kb.release(view_model) assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done() it '14. model replacement with select', (done) -> return done() unless $ kb.statistics = new kb.Statistics() model_opts = attributes: prop: 1 defaults: prop: 1 Model = if kb.Parse then kb.Model.extend('Model', model_opts) else kb.Model.extend(model_opts) model1 = new Model view_model = kb.viewModel(model1) el = $(''' <div id="the_template1"> <select data-bind="value: prop"> <option value="" selected>---</option> <option value="1">1</option> <option value="2">2</option> </select> </div>''') $('body').append(el) widget = el.find('select') assert.equal(widget.val(), "", "select should be empty to start with") ko.applyBindings(view_model, el.get(0)) assert.equal(widget.val(), "1", "select should be equal to the model after bindings applied") model2 = new Model({prop : 2}) assert.equal(model2.get('prop'), 2, "sanity check 2") view_model.model(model2) assert.equal(widget.val(), 2, "model sets the select") assert.equal(model2.get('prop'), 2, "switched in model shouldn't inherit values from previous model") assert.equal(view_model.model(), model2, "view_model.model should be the same as the new model") assert.equal(view_model.prop(), 2, "view model should have the value of the switched in model") el.remove() kb.release(view_model) assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done() it '16. model replacement with input', (done) -> return done() unless $ kb.statistics = new kb.Statistics() model_opts = attributes: prop: 1 defaults: prop: 1 Model = if kb.Parse then kb.Model.extend('Model', model_opts) else kb.Model.extend(model_opts) model1 = new Model view_model = kb.viewModel(model1) el = $(''' <div id="the_template1"> <input data-bind="value: prop" /> </div>''') $('body').append(el) widget = el.find('input') assert.equal(widget.val(), "", "input should be empty to start with") ko.applyBindings(view_model, el.get(0)) assert.equal(widget.val(), "1", "input should be equal to the model after bindings applied") model2 = new Model({prop : 2}) assert.equal(model2.get('prop'), 2, "sanity check 2") view_model.model(model2) assert.equal(widget.val(), 2, "model sets the select") assert.equal(model2.get('prop'), 2, "switched in model shouldn't inherit values from previous model") assert.equal(view_model.model(), model2, "view_model.model should be the same as the new model") assert.equal(view_model.prop(), 2, "view model should have the value of the switched in model") el.remove() kb.release(view_model) assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done() it '17. model replacement with multiple selects and weird backbone bug', (done) -> return done() unless $ kb.statistics = new kb.Statistics() default_attrs = prop1 : "p1-wrong" prop2 : "p2-wrong" model_opts = attributes: default_attrs defaults: default_attrs Model = if kb.Parse then kb.Model.extend('Model', model_opts) else kb.Model.extend(model_opts) model1 = new Model view_model = kb.viewModel(model1) el = $(''' <div id="the_template1"> <select id="prop1" data-bind="value: prop1"> <option value="p1-wrong" selected>WRONG</option> <option value="p1-right">RIGHT</option> </select> <select id="prop2" data-bind="value: prop2"> <option value="p2-wrong" selected>WRONG</option> <option value="p2-right">RIGHT</option> </select> </div>''') $('body').append(el) widget1 = el.find('#prop1') widget2 = el.find('#prop2') assert.equal(widget1.val(), "p1-wrong", "select should be first value to start with") assert.equal(widget2.val(), "p2-wrong", "select should be first value to start with") ko.applyBindings(view_model, el.get(0)) assert.equal(widget1.val(), "p1-wrong", "select should be equal to the model after bindings applied") assert.equal(widget2.val(), "p2-wrong", "select should be equal to the model after bindings applied") model2 = new Model( DUMMY : "" prop1 : "p1-right" prop2 : "p2-right" ) assert.equal(model2.get('prop1'), 'p1-right', "sanity check 2") assert.equal(model2.get('prop2'), 'p2-right', "sanity check 3") view_model.model(model2) assert.equal(widget1.val(), 'p1-right', "model sets the select") assert.equal(widget2.val(), 'p2-right', "model sets the select") assert.equal(model2.get('prop1'), 'p1-right', "switched in model shouldn't inherit values from previous model") assert.equal(model2.get('prop2'), 'p2-right', "switched in model shouldn't inherit values from previous model") assert.equal(view_model.model(), model2, "view_model.model should be the same as the new model") assert.equal(view_model.prop1(), 'p1-right', "view model should have the value of the switched in model") assert.equal(view_model.prop2(), 'p2-right', "view model should have the value of the switched in model") el.remove() kb.release(view_model) assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done() it '18. can merge unique options', (done) -> options = internals: ['internal1'] keys: ['key1'] factories: {models: ->} options: requires: 'require2' keys: ['key2'] excludes: 'exclude2' options: excludes: ['exclude3'] factories: {'collection.models': ->} collapsed_options = kb.utils.collapseOptions(options) assert.deepEqual(collapsed_options.internals, ['internal1']) assert.deepEqual(collapsed_options.keys, ['key1', 'key2']) assert.deepEqual(_.keys(collapsed_options.factories), ['models', 'collection.models']) assert.deepEqual(collapsed_options.excludes, ['exclude2', 'exclude3']) done() it '19. can merge non-unique options', (done) -> factoryOverride = -> factory = -> options = internals: ['internal1'] keys: ['key1'] factories: {models: factory} options: requires: 'require1' keys: ['key1'] excludes: 'exclude1' options: excludes: ['exclude1'] factories: {models: factoryOverride} collapsed_options = kb.utils.collapseOptions(options) assert.deepEqual(collapsed_options.internals, ['internal1']) assert.deepEqual(collapsed_options.keys, ['key1']) assert.deepEqual(_.keys(collapsed_options.factories), ['models']) assert.equal(collapsed_options.factories.models, factoryOverride, 'selected overidden factory') assert.notEqual(collapsed_options.factories.models, factory, 'did not select original factory') assert.deepEqual(collapsed_options.excludes, ['exclude1']) done() it '20. can merge keys as object', (done) -> options = keys: {name: {key: 'name'}} options: keys: {thing: {key: 'thing'}} collapsed_options = kb.utils.collapseOptions(options) assert.deepEqual(collapsed_options.keys, {name: {key: 'name'}, thing: {key: 'thing'}}) options = keys: 'name' options: keys: {thing: {key: 'thing'}} collapsed_options = kb.utils.collapseOptions(options) assert.deepEqual(collapsed_options.keys, {name: {key: 'name'}, thing: {key: 'thing'}}) options = keys: ['name'] options: keys: {thing: {key: 'thing'}} collapsed_options = kb.utils.collapseOptions(options) assert.deepEqual(collapsed_options.keys, {name: {key: 'name'}, thing: {key: 'thing'}}) options = keys: {name: {key: 'name'}} options: keys: 'thing' collapsed_options = kb.utils.collapseOptions(options) assert.deepEqual(collapsed_options.keys, {name: {key: 'name'}, thing: {key: 'thing'}}) options = keys: {name: {key: 'name'}} options: keys: ['thing'] collapsed_options = kb.utils.collapseOptions(options) assert.deepEqual(collapsed_options.keys, {name: {key: 'name'}, thing: {key: 'thing'}}) done() it '21. view model changes do not cause dependencies inside ko.computed', (done) -> kb.statistics = new kb.Statistics() # turn on stats view_model = new TestViewModel(new kb.Model({id: 1, name: 'Initial'})) model = view_model.model() count_manual = 0 ko.computed -> view_model.model(new kb.Model({id: 10, name: 'Manual'})) # should not depend count_manual++ count_set_existing = 0 ko.computed -> model.set({name: 'Existing'}) # should not depend count_set_existing++ count_set_new = 0 ko.computed -> model.set({new_attribute: 'New'}) # should not depend count_set_new++ count_set_model = 0 ko.computed -> model.set({model: new kb.Model({name: 'NestedModel'})}) # should not depend count_set_model++ count_set_collection = 0 ko.computed -> model.set({collection: new kb.Collection([{name: 'NestedModel'}])}) # should not depend count_set_collection++ observable_count = 0 ko.computed -> view_model.model() # should depend observable_count++ assert.equal(count_manual, 1, 'count_manual'); assert.equal(count_set_existing, 1, 'count_set_existing'); assert.equal(count_set_new, 1, 'count_set_new'); assert.equal(count_set_model, 1, 'count_set_model'); assert.equal(count_set_collection, 1, 'count_set_collection'); assert.equal(observable_count, 1, 'observable_count') view_model.model(new kb.Model({id: 10, name: 'Manual'})) model.set({name: 'Existing'}) model.set({new_attribute: 'New'}) model.set({model: new kb.Model({name: 'NestedModel'})}) model.set({collection: new kb.Collection([{name: 'NestedModel'}])}) assert.equal(count_manual, 1, 'count_manual'); assert.equal(count_set_existing, 1, 'count_set_existing'); assert.equal(count_set_new, 1, 'count_set_new'); assert.equal(count_set_model, 1, 'count_set_model'); assert.equal(count_set_collection, 1, 'count_set_collection'); assert.equal(observable_count, 2, 'observable_count') model = view_model.model() model.set({name: 'Bob2'}) assert.equal(view_model.name(), 'Bob2') view_model.test('world') assert.equal(view_model.test(), 'world') assert.equal(count_manual, 1, 'count_manual'); assert.equal(count_set_existing, 1, 'count_set_existing'); assert.equal(count_set_new, 1, 'count_set_new'); assert.equal(count_set_model, 1, 'count_set_model'); assert.equal(count_set_collection, 1, 'count_set_collection'); assert.equal(observable_count, 2, 'observable_count') kb.release(view_model) assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done() it '22. statics and static defaults keyword', (done) -> kb.statistics = new kb.Statistics() # turn on stats view_model = kb.viewModel( new kb.Model({id: 1, name: 'Initial', date: new Date()}), {statics: ['name', 'author', 'description', 'tags'], static_defaults: {author: '(none)', description: null}} ) assert.ok(view_model.name and !ko.isObservable(view_model.name), 'name: non-observable') assert.equal(view_model.name, 'Initial', 'name: value is correct') assert.equal(ko.utils.unwrapObservable(view_model.name), 'Initial', 'name: unwrapped value is correct') assert.ok(view_model.date and ko.isObservable(view_model.date), 'date: observable') assert.equal(view_model.date(), view_model.model().get('date'), 'date: value is correct') assert.equal(ko.utils.unwrapObservable(view_model.date), view_model.model().get('date'), 'date: unwrapped value is correct') assert.ok(view_model.author and !ko.isObservable(view_model.author), 'author: non-observable') assert.equal(view_model.author, '(none)', 'author: value is correct') assert.equal(ko.utils.unwrapObservable(view_model.author), '(none)', 'author: unwrapped value is correct') assert.ok(!view_model.description and !ko.isObservable(view_model.description), 'description: non-observable') assert.equal(view_model.description, null, 'description: value is correct') assert.equal(ko.utils.unwrapObservable(view_model.description), null, 'description: unwrapped value is correct') assert.ok(_.isUndefined(view_model.tags), 'tags: not created') kb.release(view_model) assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done() it '23. Issue 94', (done) -> kb.statistics = new kb.Statistics() # turn on stats # ECOSYSTEM return done() if kb.Parse Child = kb.Model.extend() Parent = kb.Model.extend({ defaults: { child: new Child({name: "SingleChild"}), children: new kb.Collection([new Child({name: "Child1"}), new Child({name: "Child2"})], {model: Child}) } }) ChildViewModel = (model) -> assert.ok(!!model, 'model is null?') view_model = kb.viewModel(model) view_model.nameComputed = ko.computed => ret = "no name function!" ret = "Hello, " + view_model.name() if view_model.name return ret return view_model ParentViewModel = (model) -> view_model = kb.viewModel(model, { factories: { 'children.models': ChildViewModel, 'child': ChildViewModel } }) view_model.nameComputed = ko.computed => return "Hello, " + view_model.name() return view_model parent_view_model = new ParentViewModel(new Parent({name: "TestParent"})) kb.release(parent_view_model) assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done() # https://github.com/kmalakoff/knockback/issues/82 it '24. Issue 82 - createObservables', (done) -> kb.statistics = new kb.Statistics() # turn on stats children = new kb.Collection([ new kb.Model({name:"Charles"}), new kb.Model({name:"Eve"}) ]) parent = new kb.Model({name: "Bob", children: children}) subFactory = (model) -> subVm = new kb.ViewModel(model) subVm.cid = ko.computed -> return model.cid return subVm; vm = new kb.ViewModel(parent, {excludes : ['children'], factories: {'children.models': subFactory}}) assert.ok(_.isUndefined(vm.children)) vm.children = kb.observable(parent, 'children', vm.shareOptions()) assert.ok(vm.children()[0].cid()) kb.release(vm) assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done() # https://github.com/kmalakoff/knockback/issues/121 it '25. Issue 121', (done) -> kb.statistics = new kb.Statistics() # turn on stats view_model = kb.viewModel(model1 = new kb.Model()) model1.set({propB: 'val2'}) assert.equal view_model.propB(), 'val2' model1.set({propA: 'val1', propB: 'val2.2'}) assert.equal view_model.propA(), 'val1' assert.equal view_model.propB(), 'val2.2' kb.release(view_model) assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done()
20598
assert = assert or require?('chai').assert describe 'view-model @quick @view-model', -> kb = window?.kb; try kb or= require?('knockback') catch; try kb or= require?('../../../knockback') {_, ko, $} = kb it 'TEST DEPENDENCY MISSING', (done) -> assert.ok(!!ko, 'ko') assert.ok(!!_, '_') assert.ok(!!kb.Model, 'kb.Model') assert.ok(!!kb.Collection, 'kb.Collection') assert.ok(!!kb, 'kb') done() Contact = if kb.Parse then kb.Model.extend('Contact', { defaults: {name: '', number: 0, date: new Date()} }) else kb.Model.extend({ defaults: {name: '', number: 0, date: new Date()} }) Contacts = kb.Collection.extend({model: Contact}) class TestViewModel extends kb.ViewModel constructor: -> super @test = ko.observable('hello') value = @test() value = @name() it '1. Standard use case: read and write', (done) -> kb.statistics = new kb.Statistics() # turn on stats model = new Contact({name: '<NAME>', number: '555-555-5556'}) view_model = kb.viewModel(model) # get assert.equal(view_model.name(), '<NAME>', "Interesting name") assert.equal(view_model.number(), '555-555-5556', "Not so interesting number") # set from the view model view_model.number('9222-222-222') assert.equal(model.get('number'), '9222-222-222', "Number was changed") assert.equal(view_model.number(), '9222-222-222', "Number was changed") # set from the model model.set({name: '<NAME>', number: 'XXX-XXX-XXXX'}) assert.equal(view_model.name(), '<NAME>', "Name changed") assert.equal(view_model.number(), 'XXX-XXX-XXXX', "Number was changed") # and cleanup after yourself when you are done. kb.release(view_model) assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done() it '2. Using Coffeescript classes', (done) -> kb.statistics = new kb.Statistics() # turn on stats class ContactViewModelCustom extends kb.ViewModel constructor: (model) -> super(model, {internals: ['name', 'number']}) @name = ko.computed(=> return "First: #{@_name()}") model = new Contact({name: '<NAME>', number: '555-555-5556'}) view_model = new ContactViewModelCustom(model) # get assert.equal(view_model._name(), '<NAME>', "Interesting name") assert.equal(view_model.name(), 'First: <NAME>', "Interesting name") # set from the model model.set({name: '<NAME>'}) assert.equal(view_model._name(), '<NAME>', "Name changed") assert.equal(view_model.name(), 'First: <NAME>', "Name changed") # set from the generated attribute view_model._name('<NAME>') assert.equal(view_model._name(), '<NAME>', "Interesting name") assert.equal(view_model.name(), 'First: <NAME>', "Interesting name") # and cleanup after yourself when you are done. kb.release(view_model) assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done() it '3. Using simple Javascript classes', (done) -> kb.statistics = new kb.Statistics() # turn on stats ContactViewModelCustom = (model) -> view_model = kb.viewModel(model) view_model.formatted_name = kb.observable(model, {key:'name', read: -> return "First: #{model.get('name')}" }) view_model.formatted_number = kb.observable(model, { key:'number' read: -> return "#: #{model.get('number')}" write: (value) -> model.set({number: value.substring(3)}) }, view_model) return view_model model = new Contact({name: '<NAME>', number: '555-555-5556'}) view_model = new ContactViewModelCustom(model) # get assert.equal(view_model.name(), '<NAME>', "Interesting name") assert.equal(view_model.formatted_name(), 'First: <NAME>', "Interesting name") assert.equal(view_model.number(), '555-555-5556', "Not so interesting number") assert.equal(view_model.formatted_number(), '#: 555-555-5556', "Not so interesting number") # set from the view model view_model.formatted_number('#: 9222-222-222') assert.equal(model.get('number'), '9222-222-222', "Number was changed") assert.equal(view_model.number(), '9222-222-222', "Number was changed") assert.equal(view_model.formatted_number(), '#: 9222-222-222', "Number was changed") # set from the model model.set({name: '<NAME>', number: 'XXX-XXX-XXXX'}) assert.equal(view_model.name(), '<NAME>', "Name changed") assert.equal(view_model.formatted_name(), 'First: <NAME>', "Name changed") assert.equal(view_model.number(), 'XXX-XXX-XXXX', "Number was changed") assert.equal(view_model.formatted_number(), '#: XXX-XXX-XXXX', "Number was changed") # and cleanup after yourself when you are done. kb.release(view_model) assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done() it '4. requires', (done) -> kb.statistics = new kb.Statistics() # turn on stats class ContactViewModelFullName extends kb.ViewModel constructor: (model) -> super(model, {requires: ['first', 'last']}) @full_name = ko.computed(=> "Last: #{@last()}, First: #{@first()}") model = new kb.Model() view_model = new ContactViewModelFullName(model) assert.equal(view_model.full_name(), 'Last: null, First: null', "full name is good") model.set({first: '<NAME>', last: '<NAME>'}) assert.equal(view_model.full_name(), 'Last: <NAME>, First: Ringo', "full name is good") model.set({first: 'Bongo'}) assert.equal(view_model.full_name(), 'Last: <NAME>, First: Bongo', "full name is good") # clean up kb.release(view_model) class ContactViewModelFullName2 extends kb.ViewModel constructor: (model) -> super(model, {requires: 'first'}) @last = kb.observable(model, 'last') @full_name = ko.computed(=> "Last: #{@last()}, First: #{@first()}") model = new kb.Model() view_model = new ContactViewModelFullName2(model) assert.equal(view_model.full_name(), 'Last: null, First: null', "full name is good") model.set({first: '<NAME>', last: '<NAME>'}) assert.equal(view_model.full_name(), 'Last: <NAME>, First: Ring<NAME>', "full name is good") model.set({first: 'Bongo'}) assert.equal(view_model.full_name(), 'Last: <NAME>, First: Bongo', "full name is good") # clean up kb.release(view_model) assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done() it '5. reference counting and custom __destroy (Coffeescript inheritance)', (done) -> kb.statistics = new kb.Statistics() # turn on stats class ContactViewModelFullName extends kb.ViewModel constructor: (model) -> super(model, {requires: ['first', 'last']}) @is_destroyed = false # monkey patch reference counting @ref_count = 1 @super_destroy = @destroy; @destroy = null @is_destroyed = false retain: -> @ref_count++ refCount: -> return @ref_count release: -> --@ref_count throw new Error 'ref count is corrupt' if @ref_count < 0 return if @ref_count @is_destroyed = true @super_destroy() model = new kb.Model({first: "<NAME>"}) view_model = new ContactViewModelFullName(model) assert.equal(view_model.first(), "Hello", "Hello exists") view_model.retain() assert.equal(view_model.refCount(), 2, "ref count 2") assert.equal(view_model.is_destroyed, false, "not destroyed") view_model.release() assert.equal(view_model.refCount(), 1, "ref count 1") assert.equal(view_model.is_destroyed, false, "not destroyed") kb.release(view_model) assert.equal(view_model.refCount(), 0, "ref count 0") assert.equal(view_model.is_destroyed, true, "is destroyed using overridden destroy function") assert.ok(!view_model.first, "Hello doesn't exist anymore") assert.throw((->view_model.release()), Error, "ref count is corrupt") assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done() it '6. reference counting and custom __destroy (Javascript inheritance)', (done) -> kb.statistics = new kb.Statistics() # turn on stats ContactViewModelFullName = kb.ViewModel.extend({ constructor: (model) -> kb.ViewModel.prototype.constructor.call(this, model, {requires: ['first', 'last']}) # monkey patch reference counting @ref_count = 1 @super_destroy = @destroy; @destroy = null @is_destroyed = false retain: -> @ref_count++ refCount: -> return @ref_count release: -> --@ref_count throw new Error "ref count is corrupt" if @ref_count < 0 return if @ref_count @is_destroyed = true @super_destroy() }) model = new kb.Model({first: "<NAME>"}) view_model = new ContactViewModelFullName(model) assert.equal(view_model.first(), "Hello", "Hello exists") view_model.retain() assert.equal(view_model.refCount(), 2, "ref count 2") assert.equal(view_model.is_destroyed, false, "not destroyed") view_model.release() assert.equal(view_model.refCount(), 1, "ref count 1") assert.equal(view_model.is_destroyed, false, "not destroyed") kb.release(view_model) assert.equal(view_model.refCount(), 0, "ref count 0") assert.equal(view_model.is_destroyed, true, "is destroyed using overridden destroy function") assert.ok(!view_model.first, "Hello doesn't exist anymore") assert.throw((->view_model.release()), Error, "ref count is corrupt") assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done() it '7. Nested custom view models', (done) -> kb.statistics = new kb.Statistics() # turn on stats class ContactViewModelDate extends kb.ViewModel constructor: (model, options) -> super(model, _.extend({requires: ['date']}, options)) john_birthdate = new Date(1940, 10, 9) john = new Contact({name: '<NAME>', date: new Date(john_birthdate.valueOf())}) paul_birthdate = new Date(1942, 6, 18) paul = new Contact({name: '<NAME>', date: new Date(paul_birthdate.valueOf())}) george_birthdate = new Date(1943, 2, 25) george = new Contact({name: '<NAME>', date: new Date(george_birthdate.valueOf())}) ringo_birthdate = new Date(1940, 7, 7) ringo = new Contact({name: '<NAME>', date: new Date(ringo_birthdate.valueOf())}) major_duo = new kb.Collection([<NAME>, <NAME>]) minor_duo = new kb.Collection([george, ringo]) nested_model = new kb.Model({ <NAME>: <NAME> <NAME>: <NAME> george: george ringo: ringo major_duo1: major_duo major_duo2: major_duo major_duo3: major_duo minor_duo1: minor_duo minor_duo2: minor_duo minor_duo3: minor_duo }) nested_view_model = kb.viewModel(nested_model, { factories: <NAME> <NAME>: ContactViewModelDate <NAME>orge: {create: (model, options) -> return new ContactViewModelDate(model, options)} 'major_duo1.models': ContactViewModelDate 'major_duo2.models': {create: (model, options) -> return new ContactViewModelDate(model, options)} 'major_duo3.models': {models_only: true} 'minor_duo1.models': kb.ViewModel 'minor_duo2.models': {create: (model, options) -> return new kb.ViewModel(model, options)} }) validateContactViewModel = (view_model, name, birthdate) -> model = kb.utils.wrappedModel(view_model) assert.equal(view_model.name(), name, "#{name}: Name matches") # set from the view model view_model.date(new Date(1963, 11, 10)) current_date = model.get('date') assert.equal(current_date.getFullYear(), 1963, "#{name}: year is good") assert.equal(current_date.getMonth(), 11, "#{name}: month is good") assert.equal(current_date.getDate(), 10, "#{name}: day is good") assert.equal(view_model.date().getFullYear(), 1963, "#{name}: year is good") assert.equal(view_model.date().getMonth(), 11, "#{name}: month is good") assert.equal(view_model.date().getDate(), 10, "#{name}: day is good") model.set({date: new Date(birthdate.valueOf())}) # restore birthdate # set from the model view_model.date(new Date(1940, 10, 10)) current_date = model.get('date') assert.equal(current_date.getFullYear(), 1940, "#{name}: year is good") assert.equal(current_date.getMonth(), 10, "#{name}: month is good") assert.equal(current_date.getDate(), 10, "#{name}: day is good") assert.equal(view_model.date().getFullYear(), 1940, "#{name}: year is good") assert.equal(view_model.date().getMonth(), 10, "#{name}: month is good") assert.equal(view_model.date().getDate(), 10, "#{name}: day is good") model.set({date: new Date(birthdate.valueOf())}) # restore birthdate validateGenericViewModel = (view_model, name, birthdate) -> assert.equal(view_model.name(), name, "#{name}: Name matches") assert.equal(view_model.date().valueOf(), birthdate.valueOf(), "#{name}: Birthdate matches") validateModel = (model, name, birthdate) -> assert.equal(model.get('name'), name, "#{name}: Name matches") assert.equal(model.get('date').valueOf(), birthdate.valueOf(), "#{name}: Birthdate matches") # models validateContactViewModel(nested_view_model.john(), '<NAME>', john_birthdate) validateGenericViewModel(nested_view_model.paul(), '<NAME>', paul_birthdate) validateContactViewModel(nested_view_model.george(), '<NAME>', george_birthdate) validateGenericViewModel(nested_view_model.ringo(), '<NAME>', ringo_birthdate) # colllections validateContactViewModel(nested_view_model.major_duo1()[0], '<NAME>', john_birthdate) validateContactViewModel(nested_view_model.major_duo1()[1], '<NAME>', paul_birthdate) validateContactViewModel(nested_view_model.major_duo2()[0], '<NAME>', john_birthdate) validateContactViewModel(nested_view_model.major_duo2()[1], '<NAME>', paul_birthdate) validateModel(nested_view_model.major_duo3()[0], '<NAME>', john_birthdate) validateModel(nested_view_model.major_duo3()[1], '<NAME>', paul_birthdate) validateGenericViewModel(nested_view_model.minor_duo1()[0], '<NAME>', george_birthdate) validateGenericViewModel(nested_view_model.minor_duo1()[1], '<NAME>', ringo_birthdate) validateGenericViewModel(nested_view_model.minor_duo2()[0], '<NAME>', george_birthdate) validateGenericViewModel(nested_view_model.minor_duo2()[1], '<NAME>', ringo_birthdate) validateGenericViewModel(nested_view_model.minor_duo3()[0], '<NAME>', george_birthdate) validateGenericViewModel(nested_view_model.minor_duo3()[1], '<NAME>', ringo_birthdate) # and cleanup after yourself when you are done. kb.release(nested_view_model) assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done() it '8. Changing attribute types', (done) -> kb.statistics = new kb.Statistics() # turn on stats model = new kb.Model({reused: null}) view_model = kb.viewModel(model) assert.equal(kb.utils.valueType(view_model.reused), kb.TYPE_SIMPLE, 'reused is kb.TYPE_SIMPLE') model.set({reused: new kb.Model()}) assert.equal(kb.utils.valueType(view_model.reused), kb.TYPE_MODEL, 'reused is kb.TYPE_MODEL') model.set({reused: new kb.Collection()}) assert.equal(kb.utils.valueType(view_model.reused), kb.TYPE_COLLECTION, 'reused is kb.TYPE_COLLECTION') model.set({reused: null}) assert.equal(kb.utils.valueType(view_model.reused), kb.TYPE_COLLECTION, 'reused is retains type of kb.TYPE_COLLECTION') # clean up kb.release(view_model) # add custom mapping view_model = kb.viewModel(model, {factories: reused: (obj, options) -> return if obj instanceof kb.Collection then kb.collectionObservable(obj, options) else kb.viewModel(obj, options) }) assert.equal(kb.utils.valueType(view_model.reused), kb.TYPE_MODEL, 'reused is kb.TYPE_MODEL') model.set({reused: new kb.Model()}) assert.equal(kb.utils.valueType(view_model.reused), kb.TYPE_MODEL, 'reused is kb.TYPE_MODEL') model.set({reused: new kb.Collection()}) assert.equal(kb.utils.valueType(view_model.reused), kb.TYPE_COLLECTION, 'reused is kb.TYPE_COLLECTION') model.set({reused: null}) assert.equal(kb.utils.valueType(view_model.reused), kb.TYPE_COLLECTION, 'reused retains type of kb.TYPE_COLLECTION') # clean up kb.release(view_model) assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done() it '9. Shared Options', (done) -> kb.statistics = new kb.Statistics() # turn on stats model1 = new kb.Model({id: 1, name: '<NAME>'}) model2 = new kb.Model({id: 1, name: '<NAME>'}) model3 = new kb.Model({id: 1, name: '<NAME>'}) view_model1 = kb.viewModel(model1) view_model2 = kb.viewModel(model2) view_model3 = kb.viewModel(model3, view_model1.shareOptions()) assert.ok((view_model1.name isnt view_model2.name) and (view_model1.name() is view_model2.name()), 'not sharing') assert.ok((view_model1.name isnt view_model3.name) and (view_model1.name() is view_model3.name()), 'sharing') kb.release([view_model1, view_model2, view_model3]) assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done() it '10. Options', (done) -> kb.statistics = new kb.Statistics() # turn on stats # keys - array view_model = kb.viewModel(new kb.Model({name: '<NAME>'}), keys: ['name', 'date']) assert.equal(view_model.name(), '<NAME>', 'keys: <NAME>') assert.ok(view_model.date, 'keys: date') assert.equal(view_model.date(), null, 'keys: date fn') kb.release(view_model) # keys - no array view_model = kb.viewModel(new kb.Model({name: '<NAME>'}), keys: 'date') assert.ok(view_model.date, 'keys: date') assert.equal(view_model.date(), null, 'keys: date fn') kb.release(view_model) # keys - object view_model = kb.viewModel(new kb.Model({name: '<NAME>'}), keys: {name: {}, date: {}}) assert.equal(view_model.name(), '<NAME>', 'keys: Bob') assert.ok(view_model.date, 'keys: date') assert.equal(view_model.date(), null, 'keys: date fn') kb.release(view_model) # excludes view_model = kb.viewModel(new kb.Model({name: '<NAME>', date: new Date()}), excludes: ['date']) assert.equal(view_model.name(), '<NAME>', 'excludes: Bob') assert.ok(not view_model.date, 'excludes: date') kb.release(view_model) # excludes - no array view_model = kb.viewModel(new kb.Model({name: '<NAME>', date: new Date()}), excludes: 'date') assert.equal(view_model.name(), '<NAME>', 'excludes: Bob') assert.ok(not view_model.date, 'excludes: date') kb.release(view_model) # requires view_model = kb.viewModel(new kb.Model(), requires: ['name']) assert.equal(view_model.name(), null, 'requires: name') assert.ok(not view_model.date, 'requires: date') kb.release(view_model) # requires - no array view_model = kb.viewModel(new kb.Model(), requires: 'name') assert.equal(view_model.name(), null, 'requires: name') assert.ok(not view_model.date, 'requires: date') kb.release(view_model) # internals view_model = kb.viewModel(new kb.Model(), internals: ['name']) assert.equal(view_model._name(), null, 'internals: name') assert.ok(not view_model.date, 'internals: date') kb.release(view_model) # internals - no array view_model = kb.viewModel(new kb.Model(), internals: 'name') assert.equal(view_model._name(), null, 'internals: name') assert.ok(not view_model.date, 'internals: date') kb.release(view_model) # mappings view_model = kb.viewModel(new kb.Model(), mappings: {name: {}}) assert.equal(view_model.name(), null, 'mappings: name') assert.ok(not view_model.date, 'mappings: date') kb.release(view_model) assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done() it '11. array attributes', (done) -> model = new kb.Model text: ["heading.get these rewards"] widget: ["sign_up", "rewards"] model_data: reward: top_rewards: properties: ["title", "description", "num_points"] query: type: "active" limit: 6 view_model = kb.viewModel model assert.ok(_.isEqual(view_model.text(), ["heading.get these rewards"]), 'text observable matches') assert.ok(_.isEqual(view_model.widget(), ["sign_up", "rewards"]), 'widget observable matches') assert.ok(_.isEqual(view_model.model_data().reward.top_rewards.properties, ["title", "description", "num_points"]), 'model_data observable matches') done() it '12. model change is observable', (done) -> kb.statistics = new kb.Statistics() # turn on stats model = new kb.Model({id: 1, name: '<NAME>'}) view_model = kb.viewModel(model) count = 0 ko.computed(-> view_model.model(); count++) view_model.model(null) view_model.model(model) assert.equal(count, 3, "model change was observed") kb.release(view_model) assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done() it '13. model replacement', (done) -> kb.statistics = new kb.Statistics() model_opts = attributes: prop: 1 defaults: prop: 1 Model = if kb.Parse then kb.Model.extend('Model', model_opts) else kb.Model.extend(model_opts) model1 = new Model view_model = kb.viewModel(model1) assert.equal(view_model.prop(), 1, "sanity check") model2 = new Model({ prop: 2 }) assert.equal(model2.get('prop'), 2, "sanity check 2") view_model.model(model2) assert.equal(model2.get('prop'), 2, "switched in model shouldn't inherit values from previous model") assert.equal(view_model.prop(), 2, "view model should have the value of the switched in model") kb.release(view_model) assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done() it '14. model replacement with select', (done) -> return done() unless $ kb.statistics = new kb.Statistics() model_opts = attributes: prop: 1 defaults: prop: 1 Model = if kb.Parse then kb.Model.extend('Model', model_opts) else kb.Model.extend(model_opts) model1 = new Model view_model = kb.viewModel(model1) el = $(''' <div id="the_template1"> <select data-bind="value: prop"> <option value="" selected>---</option> <option value="1">1</option> <option value="2">2</option> </select> </div>''') $('body').append(el) widget = el.find('select') assert.equal(widget.val(), "", "select should be empty to start with") ko.applyBindings(view_model, el.get(0)) assert.equal(widget.val(), "1", "select should be equal to the model after bindings applied") model2 = new Model({prop : 2}) assert.equal(model2.get('prop'), 2, "sanity check 2") view_model.model(model2) assert.equal(widget.val(), 2, "model sets the select") assert.equal(model2.get('prop'), 2, "switched in model shouldn't inherit values from previous model") assert.equal(view_model.model(), model2, "view_model.model should be the same as the new model") assert.equal(view_model.prop(), 2, "view model should have the value of the switched in model") el.remove() kb.release(view_model) assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done() it '16. model replacement with input', (done) -> return done() unless $ kb.statistics = new kb.Statistics() model_opts = attributes: prop: 1 defaults: prop: 1 Model = if kb.Parse then kb.Model.extend('Model', model_opts) else kb.Model.extend(model_opts) model1 = new Model view_model = kb.viewModel(model1) el = $(''' <div id="the_template1"> <input data-bind="value: prop" /> </div>''') $('body').append(el) widget = el.find('input') assert.equal(widget.val(), "", "input should be empty to start with") ko.applyBindings(view_model, el.get(0)) assert.equal(widget.val(), "1", "input should be equal to the model after bindings applied") model2 = new Model({prop : 2}) assert.equal(model2.get('prop'), 2, "sanity check 2") view_model.model(model2) assert.equal(widget.val(), 2, "model sets the select") assert.equal(model2.get('prop'), 2, "switched in model shouldn't inherit values from previous model") assert.equal(view_model.model(), model2, "view_model.model should be the same as the new model") assert.equal(view_model.prop(), 2, "view model should have the value of the switched in model") el.remove() kb.release(view_model) assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done() it '17. model replacement with multiple selects and weird backbone bug', (done) -> return done() unless $ kb.statistics = new kb.Statistics() default_attrs = prop1 : "p1-wrong" prop2 : "p2-wrong" model_opts = attributes: default_attrs defaults: default_attrs Model = if kb.Parse then kb.Model.extend('Model', model_opts) else kb.Model.extend(model_opts) model1 = new Model view_model = kb.viewModel(model1) el = $(''' <div id="the_template1"> <select id="prop1" data-bind="value: prop1"> <option value="p1-wrong" selected>WRONG</option> <option value="p1-right">RIGHT</option> </select> <select id="prop2" data-bind="value: prop2"> <option value="p2-wrong" selected>WRONG</option> <option value="p2-right">RIGHT</option> </select> </div>''') $('body').append(el) widget1 = el.find('#prop1') widget2 = el.find('#prop2') assert.equal(widget1.val(), "p1-wrong", "select should be first value to start with") assert.equal(widget2.val(), "p2-wrong", "select should be first value to start with") ko.applyBindings(view_model, el.get(0)) assert.equal(widget1.val(), "p1-wrong", "select should be equal to the model after bindings applied") assert.equal(widget2.val(), "p2-wrong", "select should be equal to the model after bindings applied") model2 = new Model( DUMMY : "" prop1 : "p1-right" prop2 : "p2-right" ) assert.equal(model2.get('prop1'), 'p1-right', "sanity check 2") assert.equal(model2.get('prop2'), 'p2-right', "sanity check 3") view_model.model(model2) assert.equal(widget1.val(), 'p1-right', "model sets the select") assert.equal(widget2.val(), 'p2-right', "model sets the select") assert.equal(model2.get('prop1'), 'p1-right', "switched in model shouldn't inherit values from previous model") assert.equal(model2.get('prop2'), 'p2-right', "switched in model shouldn't inherit values from previous model") assert.equal(view_model.model(), model2, "view_model.model should be the same as the new model") assert.equal(view_model.prop1(), 'p1-right', "view model should have the value of the switched in model") assert.equal(view_model.prop2(), 'p2-right', "view model should have the value of the switched in model") el.remove() kb.release(view_model) assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done() it '18. can merge unique options', (done) -> options = internals: ['internal1'] keys: ['key1'] factories: {models: ->} options: requires: 'require2' keys: ['key2'] excludes: 'exclude2' options: excludes: ['exclude3'] factories: {'collection.models': ->} collapsed_options = kb.utils.collapseOptions(options) assert.deepEqual(collapsed_options.internals, ['internal1']) assert.deepEqual(collapsed_options.keys, ['key1', 'key2']) assert.deepEqual(_.keys(collapsed_options.factories), ['models', 'collection.models']) assert.deepEqual(collapsed_options.excludes, ['exclude2', 'exclude3']) done() it '19. can merge non-unique options', (done) -> factoryOverride = -> factory = -> options = internals: ['internal1'] keys: ['key1'] factories: {models: factory} options: requires: 'require1' keys: ['key1'] excludes: 'exclude1' options: excludes: ['exclude1'] factories: {models: factoryOverride} collapsed_options = kb.utils.collapseOptions(options) assert.deepEqual(collapsed_options.internals, ['internal1']) assert.deepEqual(collapsed_options.keys, ['key1']) assert.deepEqual(_.keys(collapsed_options.factories), ['models']) assert.equal(collapsed_options.factories.models, factoryOverride, 'selected overidden factory') assert.notEqual(collapsed_options.factories.models, factory, 'did not select original factory') assert.deepEqual(collapsed_options.excludes, ['exclude1']) done() it '20. can merge keys as object', (done) -> options = keys: {name: {key: 'name'}} options: keys: {thing: {key: 'thing'}} collapsed_options = kb.utils.collapseOptions(options) assert.deepEqual(collapsed_options.keys, {name: {key: 'name'}, thing: {key: 'thing'}}) options = keys: 'name' options: keys: {thing: {key: 'thing'}} collapsed_options = kb.utils.collapseOptions(options) assert.deepEqual(collapsed_options.keys, {name: {key: 'name'}, thing: {key: 'thing'}}) options = keys: ['name'] options: keys: {thing: {key: 'thing'}} collapsed_options = kb.utils.collapseOptions(options) assert.deepEqual(collapsed_options.keys, {name: {key: 'name'}, thing: {key: 'thing'}}) options = keys: {name: {key: 'name'}} options: keys: 'thing' collapsed_options = kb.utils.collapseOptions(options) assert.deepEqual(collapsed_options.keys, {name: {key: 'name'}, thing: {key: 'thing'}}) options = keys: {name: {key: 'name'}} options: keys: ['thing'] collapsed_options = kb.utils.collapseOptions(options) assert.deepEqual(collapsed_options.keys, {name: {key: 'name'}, thing: {key: 'thing'}}) done() it '21. view model changes do not cause dependencies inside ko.computed', (done) -> kb.statistics = new kb.Statistics() # turn on stats view_model = new TestViewModel(new kb.Model({id: 1, name: 'Initial'})) model = view_model.model() count_manual = 0 ko.computed -> view_model.model(new kb.Model({id: 10, name: 'Manual'})) # should not depend count_manual++ count_set_existing = 0 ko.computed -> model.set({name: 'Existing'}) # should not depend count_set_existing++ count_set_new = 0 ko.computed -> model.set({new_attribute: 'New'}) # should not depend count_set_new++ count_set_model = 0 ko.computed -> model.set({model: new kb.Model({name: 'NestedModel'})}) # should not depend count_set_model++ count_set_collection = 0 ko.computed -> model.set({collection: new kb.Collection([{name: 'NestedModel'}])}) # should not depend count_set_collection++ observable_count = 0 ko.computed -> view_model.model() # should depend observable_count++ assert.equal(count_manual, 1, 'count_manual'); assert.equal(count_set_existing, 1, 'count_set_existing'); assert.equal(count_set_new, 1, 'count_set_new'); assert.equal(count_set_model, 1, 'count_set_model'); assert.equal(count_set_collection, 1, 'count_set_collection'); assert.equal(observable_count, 1, 'observable_count') view_model.model(new kb.Model({id: 10, name: 'Manual'})) model.set({name: 'Existing'}) model.set({new_attribute: 'New'}) model.set({model: new kb.Model({name: 'NestedModel'})}) model.set({collection: new kb.Collection([{name: 'NestedModel'}])}) assert.equal(count_manual, 1, 'count_manual'); assert.equal(count_set_existing, 1, 'count_set_existing'); assert.equal(count_set_new, 1, 'count_set_new'); assert.equal(count_set_model, 1, 'count_set_model'); assert.equal(count_set_collection, 1, 'count_set_collection'); assert.equal(observable_count, 2, 'observable_count') model = view_model.model() model.set({name: '<NAME>'}) assert.equal(view_model.name(), '<NAME>') view_model.test('world') assert.equal(view_model.test(), 'world') assert.equal(count_manual, 1, 'count_manual'); assert.equal(count_set_existing, 1, 'count_set_existing'); assert.equal(count_set_new, 1, 'count_set_new'); assert.equal(count_set_model, 1, 'count_set_model'); assert.equal(count_set_collection, 1, 'count_set_collection'); assert.equal(observable_count, 2, 'observable_count') kb.release(view_model) assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done() it '22. statics and static defaults keyword', (done) -> kb.statistics = new kb.Statistics() # turn on stats view_model = kb.viewModel( new kb.Model({id: 1, name: 'Initial', date: new Date()}), {statics: ['name', 'author', 'description', 'tags'], static_defaults: {author: '(none)', description: null}} ) assert.ok(view_model.name and !ko.isObservable(view_model.name), 'name: non-observable') assert.equal(view_model.name, 'Initial', 'name: value is correct') assert.equal(ko.utils.unwrapObservable(view_model.name), 'Initial', 'name: unwrapped value is correct') assert.ok(view_model.date and ko.isObservable(view_model.date), 'date: observable') assert.equal(view_model.date(), view_model.model().get('date'), 'date: value is correct') assert.equal(ko.utils.unwrapObservable(view_model.date), view_model.model().get('date'), 'date: unwrapped value is correct') assert.ok(view_model.author and !ko.isObservable(view_model.author), 'author: non-observable') assert.equal(view_model.author, '(none)', 'author: value is correct') assert.equal(ko.utils.unwrapObservable(view_model.author), '(none)', 'author: unwrapped value is correct') assert.ok(!view_model.description and !ko.isObservable(view_model.description), 'description: non-observable') assert.equal(view_model.description, null, 'description: value is correct') assert.equal(ko.utils.unwrapObservable(view_model.description), null, 'description: unwrapped value is correct') assert.ok(_.isUndefined(view_model.tags), 'tags: not created') kb.release(view_model) assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done() it '23. Issue 94', (done) -> kb.statistics = new kb.Statistics() # turn on stats # ECOSYSTEM return done() if kb.Parse Child = kb.Model.extend() Parent = kb.Model.extend({ defaults: { child: new Child({name: "SingleChild"}), children: new kb.Collection([new Child({name: "Child1"}), new Child({name: "Child2"})], {model: Child}) } }) ChildViewModel = (model) -> assert.ok(!!model, 'model is null?') view_model = kb.viewModel(model) view_model.nameComputed = ko.computed => ret = "no name function!" ret = "Hello, " + view_model.name() if view_model.name return ret return view_model ParentViewModel = (model) -> view_model = kb.viewModel(model, { factories: { 'children.models': ChildViewModel, 'child': ChildViewModel } }) view_model.nameComputed = ko.computed => return "Hello, " + view_model.name() return view_model parent_view_model = new ParentViewModel(new Parent({name: "<NAME>"})) kb.release(parent_view_model) assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done() # https://github.com/kmalakoff/knockback/issues/82 it '24. Issue 82 - createObservables', (done) -> kb.statistics = new kb.Statistics() # turn on stats children = new kb.Collection([ new kb.Model({name:"<NAME>"}), new kb.Model({name:"<NAME>"}) ]) parent = new kb.Model({name: "<NAME>", children: children}) subFactory = (model) -> subVm = new kb.ViewModel(model) subVm.cid = ko.computed -> return model.cid return subVm; vm = new kb.ViewModel(parent, {excludes : ['children'], factories: {'children.models': subFactory}}) assert.ok(_.isUndefined(vm.children)) vm.children = kb.observable(parent, 'children', vm.shareOptions()) assert.ok(vm.children()[0].cid()) kb.release(vm) assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done() # https://github.com/kmalakoff/knockback/issues/121 it '25. Issue 121', (done) -> kb.statistics = new kb.Statistics() # turn on stats view_model = kb.viewModel(model1 = new kb.Model()) model1.set({propB: 'val2'}) assert.equal view_model.propB(), 'val2' model1.set({propA: 'val1', propB: 'val2.2'}) assert.equal view_model.propA(), 'val1' assert.equal view_model.propB(), 'val2.2' kb.release(view_model) assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done()
true
assert = assert or require?('chai').assert describe 'view-model @quick @view-model', -> kb = window?.kb; try kb or= require?('knockback') catch; try kb or= require?('../../../knockback') {_, ko, $} = kb it 'TEST DEPENDENCY MISSING', (done) -> assert.ok(!!ko, 'ko') assert.ok(!!_, '_') assert.ok(!!kb.Model, 'kb.Model') assert.ok(!!kb.Collection, 'kb.Collection') assert.ok(!!kb, 'kb') done() Contact = if kb.Parse then kb.Model.extend('Contact', { defaults: {name: '', number: 0, date: new Date()} }) else kb.Model.extend({ defaults: {name: '', number: 0, date: new Date()} }) Contacts = kb.Collection.extend({model: Contact}) class TestViewModel extends kb.ViewModel constructor: -> super @test = ko.observable('hello') value = @test() value = @name() it '1. Standard use case: read and write', (done) -> kb.statistics = new kb.Statistics() # turn on stats model = new Contact({name: 'PI:NAME:<NAME>END_PI', number: '555-555-5556'}) view_model = kb.viewModel(model) # get assert.equal(view_model.name(), 'PI:NAME:<NAME>END_PI', "Interesting name") assert.equal(view_model.number(), '555-555-5556', "Not so interesting number") # set from the view model view_model.number('9222-222-222') assert.equal(model.get('number'), '9222-222-222', "Number was changed") assert.equal(view_model.number(), '9222-222-222', "Number was changed") # set from the model model.set({name: 'PI:NAME:<NAME>END_PI', number: 'XXX-XXX-XXXX'}) assert.equal(view_model.name(), 'PI:NAME:<NAME>END_PI', "Name changed") assert.equal(view_model.number(), 'XXX-XXX-XXXX', "Number was changed") # and cleanup after yourself when you are done. kb.release(view_model) assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done() it '2. Using Coffeescript classes', (done) -> kb.statistics = new kb.Statistics() # turn on stats class ContactViewModelCustom extends kb.ViewModel constructor: (model) -> super(model, {internals: ['name', 'number']}) @name = ko.computed(=> return "First: #{@_name()}") model = new Contact({name: 'PI:NAME:<NAME>END_PI', number: '555-555-5556'}) view_model = new ContactViewModelCustom(model) # get assert.equal(view_model._name(), 'PI:NAME:<NAME>END_PI', "Interesting name") assert.equal(view_model.name(), 'First: PI:NAME:<NAME>END_PI', "Interesting name") # set from the model model.set({name: 'PI:NAME:<NAME>END_PI'}) assert.equal(view_model._name(), 'PI:NAME:<NAME>END_PI', "Name changed") assert.equal(view_model.name(), 'First: PI:NAME:<NAME>END_PI', "Name changed") # set from the generated attribute view_model._name('PI:NAME:<NAME>END_PI') assert.equal(view_model._name(), 'PI:NAME:<NAME>END_PI', "Interesting name") assert.equal(view_model.name(), 'First: PI:NAME:<NAME>END_PI', "Interesting name") # and cleanup after yourself when you are done. kb.release(view_model) assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done() it '3. Using simple Javascript classes', (done) -> kb.statistics = new kb.Statistics() # turn on stats ContactViewModelCustom = (model) -> view_model = kb.viewModel(model) view_model.formatted_name = kb.observable(model, {key:'name', read: -> return "First: #{model.get('name')}" }) view_model.formatted_number = kb.observable(model, { key:'number' read: -> return "#: #{model.get('number')}" write: (value) -> model.set({number: value.substring(3)}) }, view_model) return view_model model = new Contact({name: 'PI:NAME:<NAME>END_PI', number: '555-555-5556'}) view_model = new ContactViewModelCustom(model) # get assert.equal(view_model.name(), 'PI:NAME:<NAME>END_PI', "Interesting name") assert.equal(view_model.formatted_name(), 'First: PI:NAME:<NAME>END_PI', "Interesting name") assert.equal(view_model.number(), '555-555-5556', "Not so interesting number") assert.equal(view_model.formatted_number(), '#: 555-555-5556', "Not so interesting number") # set from the view model view_model.formatted_number('#: 9222-222-222') assert.equal(model.get('number'), '9222-222-222', "Number was changed") assert.equal(view_model.number(), '9222-222-222', "Number was changed") assert.equal(view_model.formatted_number(), '#: 9222-222-222', "Number was changed") # set from the model model.set({name: 'PI:NAME:<NAME>END_PI', number: 'XXX-XXX-XXXX'}) assert.equal(view_model.name(), 'PI:NAME:<NAME>END_PI', "Name changed") assert.equal(view_model.formatted_name(), 'First: PI:NAME:<NAME>END_PI', "Name changed") assert.equal(view_model.number(), 'XXX-XXX-XXXX', "Number was changed") assert.equal(view_model.formatted_number(), '#: XXX-XXX-XXXX', "Number was changed") # and cleanup after yourself when you are done. kb.release(view_model) assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done() it '4. requires', (done) -> kb.statistics = new kb.Statistics() # turn on stats class ContactViewModelFullName extends kb.ViewModel constructor: (model) -> super(model, {requires: ['first', 'last']}) @full_name = ko.computed(=> "Last: #{@last()}, First: #{@first()}") model = new kb.Model() view_model = new ContactViewModelFullName(model) assert.equal(view_model.full_name(), 'Last: null, First: null', "full name is good") model.set({first: 'PI:NAME:<NAME>END_PI', last: 'PI:NAME:<NAME>END_PI'}) assert.equal(view_model.full_name(), 'Last: PI:NAME:<NAME>END_PI, First: Ringo', "full name is good") model.set({first: 'Bongo'}) assert.equal(view_model.full_name(), 'Last: PI:NAME:<NAME>END_PI, First: Bongo', "full name is good") # clean up kb.release(view_model) class ContactViewModelFullName2 extends kb.ViewModel constructor: (model) -> super(model, {requires: 'first'}) @last = kb.observable(model, 'last') @full_name = ko.computed(=> "Last: #{@last()}, First: #{@first()}") model = new kb.Model() view_model = new ContactViewModelFullName2(model) assert.equal(view_model.full_name(), 'Last: null, First: null', "full name is good") model.set({first: 'PI:NAME:<NAME>END_PI', last: 'PI:NAME:<NAME>END_PI'}) assert.equal(view_model.full_name(), 'Last: PI:NAME:<NAME>END_PI, First: RingPI:NAME:<NAME>END_PI', "full name is good") model.set({first: 'Bongo'}) assert.equal(view_model.full_name(), 'Last: PI:NAME:<NAME>END_PI, First: Bongo', "full name is good") # clean up kb.release(view_model) assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done() it '5. reference counting and custom __destroy (Coffeescript inheritance)', (done) -> kb.statistics = new kb.Statistics() # turn on stats class ContactViewModelFullName extends kb.ViewModel constructor: (model) -> super(model, {requires: ['first', 'last']}) @is_destroyed = false # monkey patch reference counting @ref_count = 1 @super_destroy = @destroy; @destroy = null @is_destroyed = false retain: -> @ref_count++ refCount: -> return @ref_count release: -> --@ref_count throw new Error 'ref count is corrupt' if @ref_count < 0 return if @ref_count @is_destroyed = true @super_destroy() model = new kb.Model({first: "PI:NAME:<NAME>END_PI"}) view_model = new ContactViewModelFullName(model) assert.equal(view_model.first(), "Hello", "Hello exists") view_model.retain() assert.equal(view_model.refCount(), 2, "ref count 2") assert.equal(view_model.is_destroyed, false, "not destroyed") view_model.release() assert.equal(view_model.refCount(), 1, "ref count 1") assert.equal(view_model.is_destroyed, false, "not destroyed") kb.release(view_model) assert.equal(view_model.refCount(), 0, "ref count 0") assert.equal(view_model.is_destroyed, true, "is destroyed using overridden destroy function") assert.ok(!view_model.first, "Hello doesn't exist anymore") assert.throw((->view_model.release()), Error, "ref count is corrupt") assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done() it '6. reference counting and custom __destroy (Javascript inheritance)', (done) -> kb.statistics = new kb.Statistics() # turn on stats ContactViewModelFullName = kb.ViewModel.extend({ constructor: (model) -> kb.ViewModel.prototype.constructor.call(this, model, {requires: ['first', 'last']}) # monkey patch reference counting @ref_count = 1 @super_destroy = @destroy; @destroy = null @is_destroyed = false retain: -> @ref_count++ refCount: -> return @ref_count release: -> --@ref_count throw new Error "ref count is corrupt" if @ref_count < 0 return if @ref_count @is_destroyed = true @super_destroy() }) model = new kb.Model({first: "PI:NAME:<NAME>END_PI"}) view_model = new ContactViewModelFullName(model) assert.equal(view_model.first(), "Hello", "Hello exists") view_model.retain() assert.equal(view_model.refCount(), 2, "ref count 2") assert.equal(view_model.is_destroyed, false, "not destroyed") view_model.release() assert.equal(view_model.refCount(), 1, "ref count 1") assert.equal(view_model.is_destroyed, false, "not destroyed") kb.release(view_model) assert.equal(view_model.refCount(), 0, "ref count 0") assert.equal(view_model.is_destroyed, true, "is destroyed using overridden destroy function") assert.ok(!view_model.first, "Hello doesn't exist anymore") assert.throw((->view_model.release()), Error, "ref count is corrupt") assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done() it '7. Nested custom view models', (done) -> kb.statistics = new kb.Statistics() # turn on stats class ContactViewModelDate extends kb.ViewModel constructor: (model, options) -> super(model, _.extend({requires: ['date']}, options)) john_birthdate = new Date(1940, 10, 9) john = new Contact({name: 'PI:NAME:<NAME>END_PI', date: new Date(john_birthdate.valueOf())}) paul_birthdate = new Date(1942, 6, 18) paul = new Contact({name: 'PI:NAME:<NAME>END_PI', date: new Date(paul_birthdate.valueOf())}) george_birthdate = new Date(1943, 2, 25) george = new Contact({name: 'PI:NAME:<NAME>END_PI', date: new Date(george_birthdate.valueOf())}) ringo_birthdate = new Date(1940, 7, 7) ringo = new Contact({name: 'PI:NAME:<NAME>END_PI', date: new Date(ringo_birthdate.valueOf())}) major_duo = new kb.Collection([PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI]) minor_duo = new kb.Collection([george, ringo]) nested_model = new kb.Model({ PI:NAME:<NAME>END_PI: PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI: PI:NAME:<NAME>END_PI george: george ringo: ringo major_duo1: major_duo major_duo2: major_duo major_duo3: major_duo minor_duo1: minor_duo minor_duo2: minor_duo minor_duo3: minor_duo }) nested_view_model = kb.viewModel(nested_model, { factories: PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI: ContactViewModelDate PI:NAME:<NAME>END_PIorge: {create: (model, options) -> return new ContactViewModelDate(model, options)} 'major_duo1.models': ContactViewModelDate 'major_duo2.models': {create: (model, options) -> return new ContactViewModelDate(model, options)} 'major_duo3.models': {models_only: true} 'minor_duo1.models': kb.ViewModel 'minor_duo2.models': {create: (model, options) -> return new kb.ViewModel(model, options)} }) validateContactViewModel = (view_model, name, birthdate) -> model = kb.utils.wrappedModel(view_model) assert.equal(view_model.name(), name, "#{name}: Name matches") # set from the view model view_model.date(new Date(1963, 11, 10)) current_date = model.get('date') assert.equal(current_date.getFullYear(), 1963, "#{name}: year is good") assert.equal(current_date.getMonth(), 11, "#{name}: month is good") assert.equal(current_date.getDate(), 10, "#{name}: day is good") assert.equal(view_model.date().getFullYear(), 1963, "#{name}: year is good") assert.equal(view_model.date().getMonth(), 11, "#{name}: month is good") assert.equal(view_model.date().getDate(), 10, "#{name}: day is good") model.set({date: new Date(birthdate.valueOf())}) # restore birthdate # set from the model view_model.date(new Date(1940, 10, 10)) current_date = model.get('date') assert.equal(current_date.getFullYear(), 1940, "#{name}: year is good") assert.equal(current_date.getMonth(), 10, "#{name}: month is good") assert.equal(current_date.getDate(), 10, "#{name}: day is good") assert.equal(view_model.date().getFullYear(), 1940, "#{name}: year is good") assert.equal(view_model.date().getMonth(), 10, "#{name}: month is good") assert.equal(view_model.date().getDate(), 10, "#{name}: day is good") model.set({date: new Date(birthdate.valueOf())}) # restore birthdate validateGenericViewModel = (view_model, name, birthdate) -> assert.equal(view_model.name(), name, "#{name}: Name matches") assert.equal(view_model.date().valueOf(), birthdate.valueOf(), "#{name}: Birthdate matches") validateModel = (model, name, birthdate) -> assert.equal(model.get('name'), name, "#{name}: Name matches") assert.equal(model.get('date').valueOf(), birthdate.valueOf(), "#{name}: Birthdate matches") # models validateContactViewModel(nested_view_model.john(), 'PI:NAME:<NAME>END_PI', john_birthdate) validateGenericViewModel(nested_view_model.paul(), 'PI:NAME:<NAME>END_PI', paul_birthdate) validateContactViewModel(nested_view_model.george(), 'PI:NAME:<NAME>END_PI', george_birthdate) validateGenericViewModel(nested_view_model.ringo(), 'PI:NAME:<NAME>END_PI', ringo_birthdate) # colllections validateContactViewModel(nested_view_model.major_duo1()[0], 'PI:NAME:<NAME>END_PI', john_birthdate) validateContactViewModel(nested_view_model.major_duo1()[1], 'PI:NAME:<NAME>END_PI', paul_birthdate) validateContactViewModel(nested_view_model.major_duo2()[0], 'PI:NAME:<NAME>END_PI', john_birthdate) validateContactViewModel(nested_view_model.major_duo2()[1], 'PI:NAME:<NAME>END_PI', paul_birthdate) validateModel(nested_view_model.major_duo3()[0], 'PI:NAME:<NAME>END_PI', john_birthdate) validateModel(nested_view_model.major_duo3()[1], 'PI:NAME:<NAME>END_PI', paul_birthdate) validateGenericViewModel(nested_view_model.minor_duo1()[0], 'PI:NAME:<NAME>END_PI', george_birthdate) validateGenericViewModel(nested_view_model.minor_duo1()[1], 'PI:NAME:<NAME>END_PI', ringo_birthdate) validateGenericViewModel(nested_view_model.minor_duo2()[0], 'PI:NAME:<NAME>END_PI', george_birthdate) validateGenericViewModel(nested_view_model.minor_duo2()[1], 'PI:NAME:<NAME>END_PI', ringo_birthdate) validateGenericViewModel(nested_view_model.minor_duo3()[0], 'PI:NAME:<NAME>END_PI', george_birthdate) validateGenericViewModel(nested_view_model.minor_duo3()[1], 'PI:NAME:<NAME>END_PI', ringo_birthdate) # and cleanup after yourself when you are done. kb.release(nested_view_model) assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done() it '8. Changing attribute types', (done) -> kb.statistics = new kb.Statistics() # turn on stats model = new kb.Model({reused: null}) view_model = kb.viewModel(model) assert.equal(kb.utils.valueType(view_model.reused), kb.TYPE_SIMPLE, 'reused is kb.TYPE_SIMPLE') model.set({reused: new kb.Model()}) assert.equal(kb.utils.valueType(view_model.reused), kb.TYPE_MODEL, 'reused is kb.TYPE_MODEL') model.set({reused: new kb.Collection()}) assert.equal(kb.utils.valueType(view_model.reused), kb.TYPE_COLLECTION, 'reused is kb.TYPE_COLLECTION') model.set({reused: null}) assert.equal(kb.utils.valueType(view_model.reused), kb.TYPE_COLLECTION, 'reused is retains type of kb.TYPE_COLLECTION') # clean up kb.release(view_model) # add custom mapping view_model = kb.viewModel(model, {factories: reused: (obj, options) -> return if obj instanceof kb.Collection then kb.collectionObservable(obj, options) else kb.viewModel(obj, options) }) assert.equal(kb.utils.valueType(view_model.reused), kb.TYPE_MODEL, 'reused is kb.TYPE_MODEL') model.set({reused: new kb.Model()}) assert.equal(kb.utils.valueType(view_model.reused), kb.TYPE_MODEL, 'reused is kb.TYPE_MODEL') model.set({reused: new kb.Collection()}) assert.equal(kb.utils.valueType(view_model.reused), kb.TYPE_COLLECTION, 'reused is kb.TYPE_COLLECTION') model.set({reused: null}) assert.equal(kb.utils.valueType(view_model.reused), kb.TYPE_COLLECTION, 'reused retains type of kb.TYPE_COLLECTION') # clean up kb.release(view_model) assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done() it '9. Shared Options', (done) -> kb.statistics = new kb.Statistics() # turn on stats model1 = new kb.Model({id: 1, name: 'PI:NAME:<NAME>END_PI'}) model2 = new kb.Model({id: 1, name: 'PI:NAME:<NAME>END_PI'}) model3 = new kb.Model({id: 1, name: 'PI:NAME:<NAME>END_PI'}) view_model1 = kb.viewModel(model1) view_model2 = kb.viewModel(model2) view_model3 = kb.viewModel(model3, view_model1.shareOptions()) assert.ok((view_model1.name isnt view_model2.name) and (view_model1.name() is view_model2.name()), 'not sharing') assert.ok((view_model1.name isnt view_model3.name) and (view_model1.name() is view_model3.name()), 'sharing') kb.release([view_model1, view_model2, view_model3]) assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done() it '10. Options', (done) -> kb.statistics = new kb.Statistics() # turn on stats # keys - array view_model = kb.viewModel(new kb.Model({name: 'PI:NAME:<NAME>END_PI'}), keys: ['name', 'date']) assert.equal(view_model.name(), 'PI:NAME:<NAME>END_PI', 'keys: PI:NAME:<NAME>END_PI') assert.ok(view_model.date, 'keys: date') assert.equal(view_model.date(), null, 'keys: date fn') kb.release(view_model) # keys - no array view_model = kb.viewModel(new kb.Model({name: 'PI:NAME:<NAME>END_PI'}), keys: 'date') assert.ok(view_model.date, 'keys: date') assert.equal(view_model.date(), null, 'keys: date fn') kb.release(view_model) # keys - object view_model = kb.viewModel(new kb.Model({name: 'PI:NAME:<NAME>END_PI'}), keys: {name: {}, date: {}}) assert.equal(view_model.name(), 'PI:NAME:<NAME>END_PI', 'keys: Bob') assert.ok(view_model.date, 'keys: date') assert.equal(view_model.date(), null, 'keys: date fn') kb.release(view_model) # excludes view_model = kb.viewModel(new kb.Model({name: 'PI:NAME:<NAME>END_PI', date: new Date()}), excludes: ['date']) assert.equal(view_model.name(), 'PI:NAME:<NAME>END_PI', 'excludes: Bob') assert.ok(not view_model.date, 'excludes: date') kb.release(view_model) # excludes - no array view_model = kb.viewModel(new kb.Model({name: 'PI:NAME:<NAME>END_PI', date: new Date()}), excludes: 'date') assert.equal(view_model.name(), 'PI:NAME:<NAME>END_PI', 'excludes: Bob') assert.ok(not view_model.date, 'excludes: date') kb.release(view_model) # requires view_model = kb.viewModel(new kb.Model(), requires: ['name']) assert.equal(view_model.name(), null, 'requires: name') assert.ok(not view_model.date, 'requires: date') kb.release(view_model) # requires - no array view_model = kb.viewModel(new kb.Model(), requires: 'name') assert.equal(view_model.name(), null, 'requires: name') assert.ok(not view_model.date, 'requires: date') kb.release(view_model) # internals view_model = kb.viewModel(new kb.Model(), internals: ['name']) assert.equal(view_model._name(), null, 'internals: name') assert.ok(not view_model.date, 'internals: date') kb.release(view_model) # internals - no array view_model = kb.viewModel(new kb.Model(), internals: 'name') assert.equal(view_model._name(), null, 'internals: name') assert.ok(not view_model.date, 'internals: date') kb.release(view_model) # mappings view_model = kb.viewModel(new kb.Model(), mappings: {name: {}}) assert.equal(view_model.name(), null, 'mappings: name') assert.ok(not view_model.date, 'mappings: date') kb.release(view_model) assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done() it '11. array attributes', (done) -> model = new kb.Model text: ["heading.get these rewards"] widget: ["sign_up", "rewards"] model_data: reward: top_rewards: properties: ["title", "description", "num_points"] query: type: "active" limit: 6 view_model = kb.viewModel model assert.ok(_.isEqual(view_model.text(), ["heading.get these rewards"]), 'text observable matches') assert.ok(_.isEqual(view_model.widget(), ["sign_up", "rewards"]), 'widget observable matches') assert.ok(_.isEqual(view_model.model_data().reward.top_rewards.properties, ["title", "description", "num_points"]), 'model_data observable matches') done() it '12. model change is observable', (done) -> kb.statistics = new kb.Statistics() # turn on stats model = new kb.Model({id: 1, name: 'PI:NAME:<NAME>END_PI'}) view_model = kb.viewModel(model) count = 0 ko.computed(-> view_model.model(); count++) view_model.model(null) view_model.model(model) assert.equal(count, 3, "model change was observed") kb.release(view_model) assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done() it '13. model replacement', (done) -> kb.statistics = new kb.Statistics() model_opts = attributes: prop: 1 defaults: prop: 1 Model = if kb.Parse then kb.Model.extend('Model', model_opts) else kb.Model.extend(model_opts) model1 = new Model view_model = kb.viewModel(model1) assert.equal(view_model.prop(), 1, "sanity check") model2 = new Model({ prop: 2 }) assert.equal(model2.get('prop'), 2, "sanity check 2") view_model.model(model2) assert.equal(model2.get('prop'), 2, "switched in model shouldn't inherit values from previous model") assert.equal(view_model.prop(), 2, "view model should have the value of the switched in model") kb.release(view_model) assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done() it '14. model replacement with select', (done) -> return done() unless $ kb.statistics = new kb.Statistics() model_opts = attributes: prop: 1 defaults: prop: 1 Model = if kb.Parse then kb.Model.extend('Model', model_opts) else kb.Model.extend(model_opts) model1 = new Model view_model = kb.viewModel(model1) el = $(''' <div id="the_template1"> <select data-bind="value: prop"> <option value="" selected>---</option> <option value="1">1</option> <option value="2">2</option> </select> </div>''') $('body').append(el) widget = el.find('select') assert.equal(widget.val(), "", "select should be empty to start with") ko.applyBindings(view_model, el.get(0)) assert.equal(widget.val(), "1", "select should be equal to the model after bindings applied") model2 = new Model({prop : 2}) assert.equal(model2.get('prop'), 2, "sanity check 2") view_model.model(model2) assert.equal(widget.val(), 2, "model sets the select") assert.equal(model2.get('prop'), 2, "switched in model shouldn't inherit values from previous model") assert.equal(view_model.model(), model2, "view_model.model should be the same as the new model") assert.equal(view_model.prop(), 2, "view model should have the value of the switched in model") el.remove() kb.release(view_model) assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done() it '16. model replacement with input', (done) -> return done() unless $ kb.statistics = new kb.Statistics() model_opts = attributes: prop: 1 defaults: prop: 1 Model = if kb.Parse then kb.Model.extend('Model', model_opts) else kb.Model.extend(model_opts) model1 = new Model view_model = kb.viewModel(model1) el = $(''' <div id="the_template1"> <input data-bind="value: prop" /> </div>''') $('body').append(el) widget = el.find('input') assert.equal(widget.val(), "", "input should be empty to start with") ko.applyBindings(view_model, el.get(0)) assert.equal(widget.val(), "1", "input should be equal to the model after bindings applied") model2 = new Model({prop : 2}) assert.equal(model2.get('prop'), 2, "sanity check 2") view_model.model(model2) assert.equal(widget.val(), 2, "model sets the select") assert.equal(model2.get('prop'), 2, "switched in model shouldn't inherit values from previous model") assert.equal(view_model.model(), model2, "view_model.model should be the same as the new model") assert.equal(view_model.prop(), 2, "view model should have the value of the switched in model") el.remove() kb.release(view_model) assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done() it '17. model replacement with multiple selects and weird backbone bug', (done) -> return done() unless $ kb.statistics = new kb.Statistics() default_attrs = prop1 : "p1-wrong" prop2 : "p2-wrong" model_opts = attributes: default_attrs defaults: default_attrs Model = if kb.Parse then kb.Model.extend('Model', model_opts) else kb.Model.extend(model_opts) model1 = new Model view_model = kb.viewModel(model1) el = $(''' <div id="the_template1"> <select id="prop1" data-bind="value: prop1"> <option value="p1-wrong" selected>WRONG</option> <option value="p1-right">RIGHT</option> </select> <select id="prop2" data-bind="value: prop2"> <option value="p2-wrong" selected>WRONG</option> <option value="p2-right">RIGHT</option> </select> </div>''') $('body').append(el) widget1 = el.find('#prop1') widget2 = el.find('#prop2') assert.equal(widget1.val(), "p1-wrong", "select should be first value to start with") assert.equal(widget2.val(), "p2-wrong", "select should be first value to start with") ko.applyBindings(view_model, el.get(0)) assert.equal(widget1.val(), "p1-wrong", "select should be equal to the model after bindings applied") assert.equal(widget2.val(), "p2-wrong", "select should be equal to the model after bindings applied") model2 = new Model( DUMMY : "" prop1 : "p1-right" prop2 : "p2-right" ) assert.equal(model2.get('prop1'), 'p1-right', "sanity check 2") assert.equal(model2.get('prop2'), 'p2-right', "sanity check 3") view_model.model(model2) assert.equal(widget1.val(), 'p1-right', "model sets the select") assert.equal(widget2.val(), 'p2-right', "model sets the select") assert.equal(model2.get('prop1'), 'p1-right', "switched in model shouldn't inherit values from previous model") assert.equal(model2.get('prop2'), 'p2-right', "switched in model shouldn't inherit values from previous model") assert.equal(view_model.model(), model2, "view_model.model should be the same as the new model") assert.equal(view_model.prop1(), 'p1-right', "view model should have the value of the switched in model") assert.equal(view_model.prop2(), 'p2-right', "view model should have the value of the switched in model") el.remove() kb.release(view_model) assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done() it '18. can merge unique options', (done) -> options = internals: ['internal1'] keys: ['key1'] factories: {models: ->} options: requires: 'require2' keys: ['key2'] excludes: 'exclude2' options: excludes: ['exclude3'] factories: {'collection.models': ->} collapsed_options = kb.utils.collapseOptions(options) assert.deepEqual(collapsed_options.internals, ['internal1']) assert.deepEqual(collapsed_options.keys, ['key1', 'key2']) assert.deepEqual(_.keys(collapsed_options.factories), ['models', 'collection.models']) assert.deepEqual(collapsed_options.excludes, ['exclude2', 'exclude3']) done() it '19. can merge non-unique options', (done) -> factoryOverride = -> factory = -> options = internals: ['internal1'] keys: ['key1'] factories: {models: factory} options: requires: 'require1' keys: ['key1'] excludes: 'exclude1' options: excludes: ['exclude1'] factories: {models: factoryOverride} collapsed_options = kb.utils.collapseOptions(options) assert.deepEqual(collapsed_options.internals, ['internal1']) assert.deepEqual(collapsed_options.keys, ['key1']) assert.deepEqual(_.keys(collapsed_options.factories), ['models']) assert.equal(collapsed_options.factories.models, factoryOverride, 'selected overidden factory') assert.notEqual(collapsed_options.factories.models, factory, 'did not select original factory') assert.deepEqual(collapsed_options.excludes, ['exclude1']) done() it '20. can merge keys as object', (done) -> options = keys: {name: {key: 'name'}} options: keys: {thing: {key: 'thing'}} collapsed_options = kb.utils.collapseOptions(options) assert.deepEqual(collapsed_options.keys, {name: {key: 'name'}, thing: {key: 'thing'}}) options = keys: 'name' options: keys: {thing: {key: 'thing'}} collapsed_options = kb.utils.collapseOptions(options) assert.deepEqual(collapsed_options.keys, {name: {key: 'name'}, thing: {key: 'thing'}}) options = keys: ['name'] options: keys: {thing: {key: 'thing'}} collapsed_options = kb.utils.collapseOptions(options) assert.deepEqual(collapsed_options.keys, {name: {key: 'name'}, thing: {key: 'thing'}}) options = keys: {name: {key: 'name'}} options: keys: 'thing' collapsed_options = kb.utils.collapseOptions(options) assert.deepEqual(collapsed_options.keys, {name: {key: 'name'}, thing: {key: 'thing'}}) options = keys: {name: {key: 'name'}} options: keys: ['thing'] collapsed_options = kb.utils.collapseOptions(options) assert.deepEqual(collapsed_options.keys, {name: {key: 'name'}, thing: {key: 'thing'}}) done() it '21. view model changes do not cause dependencies inside ko.computed', (done) -> kb.statistics = new kb.Statistics() # turn on stats view_model = new TestViewModel(new kb.Model({id: 1, name: 'Initial'})) model = view_model.model() count_manual = 0 ko.computed -> view_model.model(new kb.Model({id: 10, name: 'Manual'})) # should not depend count_manual++ count_set_existing = 0 ko.computed -> model.set({name: 'Existing'}) # should not depend count_set_existing++ count_set_new = 0 ko.computed -> model.set({new_attribute: 'New'}) # should not depend count_set_new++ count_set_model = 0 ko.computed -> model.set({model: new kb.Model({name: 'NestedModel'})}) # should not depend count_set_model++ count_set_collection = 0 ko.computed -> model.set({collection: new kb.Collection([{name: 'NestedModel'}])}) # should not depend count_set_collection++ observable_count = 0 ko.computed -> view_model.model() # should depend observable_count++ assert.equal(count_manual, 1, 'count_manual'); assert.equal(count_set_existing, 1, 'count_set_existing'); assert.equal(count_set_new, 1, 'count_set_new'); assert.equal(count_set_model, 1, 'count_set_model'); assert.equal(count_set_collection, 1, 'count_set_collection'); assert.equal(observable_count, 1, 'observable_count') view_model.model(new kb.Model({id: 10, name: 'Manual'})) model.set({name: 'Existing'}) model.set({new_attribute: 'New'}) model.set({model: new kb.Model({name: 'NestedModel'})}) model.set({collection: new kb.Collection([{name: 'NestedModel'}])}) assert.equal(count_manual, 1, 'count_manual'); assert.equal(count_set_existing, 1, 'count_set_existing'); assert.equal(count_set_new, 1, 'count_set_new'); assert.equal(count_set_model, 1, 'count_set_model'); assert.equal(count_set_collection, 1, 'count_set_collection'); assert.equal(observable_count, 2, 'observable_count') model = view_model.model() model.set({name: 'PI:NAME:<NAME>END_PI'}) assert.equal(view_model.name(), 'PI:NAME:<NAME>END_PI') view_model.test('world') assert.equal(view_model.test(), 'world') assert.equal(count_manual, 1, 'count_manual'); assert.equal(count_set_existing, 1, 'count_set_existing'); assert.equal(count_set_new, 1, 'count_set_new'); assert.equal(count_set_model, 1, 'count_set_model'); assert.equal(count_set_collection, 1, 'count_set_collection'); assert.equal(observable_count, 2, 'observable_count') kb.release(view_model) assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done() it '22. statics and static defaults keyword', (done) -> kb.statistics = new kb.Statistics() # turn on stats view_model = kb.viewModel( new kb.Model({id: 1, name: 'Initial', date: new Date()}), {statics: ['name', 'author', 'description', 'tags'], static_defaults: {author: '(none)', description: null}} ) assert.ok(view_model.name and !ko.isObservable(view_model.name), 'name: non-observable') assert.equal(view_model.name, 'Initial', 'name: value is correct') assert.equal(ko.utils.unwrapObservable(view_model.name), 'Initial', 'name: unwrapped value is correct') assert.ok(view_model.date and ko.isObservable(view_model.date), 'date: observable') assert.equal(view_model.date(), view_model.model().get('date'), 'date: value is correct') assert.equal(ko.utils.unwrapObservable(view_model.date), view_model.model().get('date'), 'date: unwrapped value is correct') assert.ok(view_model.author and !ko.isObservable(view_model.author), 'author: non-observable') assert.equal(view_model.author, '(none)', 'author: value is correct') assert.equal(ko.utils.unwrapObservable(view_model.author), '(none)', 'author: unwrapped value is correct') assert.ok(!view_model.description and !ko.isObservable(view_model.description), 'description: non-observable') assert.equal(view_model.description, null, 'description: value is correct') assert.equal(ko.utils.unwrapObservable(view_model.description), null, 'description: unwrapped value is correct') assert.ok(_.isUndefined(view_model.tags), 'tags: not created') kb.release(view_model) assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done() it '23. Issue 94', (done) -> kb.statistics = new kb.Statistics() # turn on stats # ECOSYSTEM return done() if kb.Parse Child = kb.Model.extend() Parent = kb.Model.extend({ defaults: { child: new Child({name: "SingleChild"}), children: new kb.Collection([new Child({name: "Child1"}), new Child({name: "Child2"})], {model: Child}) } }) ChildViewModel = (model) -> assert.ok(!!model, 'model is null?') view_model = kb.viewModel(model) view_model.nameComputed = ko.computed => ret = "no name function!" ret = "Hello, " + view_model.name() if view_model.name return ret return view_model ParentViewModel = (model) -> view_model = kb.viewModel(model, { factories: { 'children.models': ChildViewModel, 'child': ChildViewModel } }) view_model.nameComputed = ko.computed => return "Hello, " + view_model.name() return view_model parent_view_model = new ParentViewModel(new Parent({name: "PI:NAME:<NAME>END_PI"})) kb.release(parent_view_model) assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done() # https://github.com/kmalakoff/knockback/issues/82 it '24. Issue 82 - createObservables', (done) -> kb.statistics = new kb.Statistics() # turn on stats children = new kb.Collection([ new kb.Model({name:"PI:NAME:<NAME>END_PI"}), new kb.Model({name:"PI:NAME:<NAME>END_PI"}) ]) parent = new kb.Model({name: "PI:NAME:<NAME>END_PI", children: children}) subFactory = (model) -> subVm = new kb.ViewModel(model) subVm.cid = ko.computed -> return model.cid return subVm; vm = new kb.ViewModel(parent, {excludes : ['children'], factories: {'children.models': subFactory}}) assert.ok(_.isUndefined(vm.children)) vm.children = kb.observable(parent, 'children', vm.shareOptions()) assert.ok(vm.children()[0].cid()) kb.release(vm) assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done() # https://github.com/kmalakoff/knockback/issues/121 it '25. Issue 121', (done) -> kb.statistics = new kb.Statistics() # turn on stats view_model = kb.viewModel(model1 = new kb.Model()) model1.set({propB: 'val2'}) assert.equal view_model.propB(), 'val2' model1.set({propA: 'val1', propB: 'val2.2'}) assert.equal view_model.propA(), 'val1' assert.equal view_model.propB(), 'val2.2' kb.release(view_model) assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done()
[ { "context": " auth:\n user: req.body.username\n pass: req.body.password\n\n # Update password only if not empty.\n if (not", "end": 780, "score": 0.999180018901825, "start": 763, "tag": "PASSWORD", "value": "req.body.password" } ]
adminApp.coffee
madnite1/devnote
11
wiki = require './lib/wiki' mailer = require './lib/mailer' config = require './lib/config' _ = require 'underscore' __ = (require './lib/i18n').__ exports.mailconf = (req, res) -> options = (config.get 'mail') or {} options.ssl = options.secureConnection options.tls = !options.ignoreTLS if options.auth options.username = options.auth.user res.render 'admin/mailconf.jade', options: options title: 'Mail Configuration' exports.postMailconf = (req, res) -> originOptions = config.get 'mail' newOptions = from: req.body.from host: req.body.host secureConnection: req.body.ssl port: req.body.port ignoreTLS: not req.body.tls authMethod: req.body.authMethod auth: user: req.body.username pass: req.body.password # Update password only if not empty. if (not newOptions.auth.pass) and originOptions and originOptions.auth newOptions.auth.pass = originOptions.auth.pass config.set 'mail', newOptions res.redirect '/' exports.mail = (req, res) -> res.render 'admin/mail.jade', notConfigured: !(config.get 'mail') title: 'Mail' to: req.query.to urls: mailConf: '/admin/mailconf' exports.postMail = (req, res) -> mailer.send to: req.body.to, subject: req.body.subject text: req.body.body res.redirect '/admin/mail'
202939
wiki = require './lib/wiki' mailer = require './lib/mailer' config = require './lib/config' _ = require 'underscore' __ = (require './lib/i18n').__ exports.mailconf = (req, res) -> options = (config.get 'mail') or {} options.ssl = options.secureConnection options.tls = !options.ignoreTLS if options.auth options.username = options.auth.user res.render 'admin/mailconf.jade', options: options title: 'Mail Configuration' exports.postMailconf = (req, res) -> originOptions = config.get 'mail' newOptions = from: req.body.from host: req.body.host secureConnection: req.body.ssl port: req.body.port ignoreTLS: not req.body.tls authMethod: req.body.authMethod auth: user: req.body.username pass: <PASSWORD> # Update password only if not empty. if (not newOptions.auth.pass) and originOptions and originOptions.auth newOptions.auth.pass = originOptions.auth.pass config.set 'mail', newOptions res.redirect '/' exports.mail = (req, res) -> res.render 'admin/mail.jade', notConfigured: !(config.get 'mail') title: 'Mail' to: req.query.to urls: mailConf: '/admin/mailconf' exports.postMail = (req, res) -> mailer.send to: req.body.to, subject: req.body.subject text: req.body.body res.redirect '/admin/mail'
true
wiki = require './lib/wiki' mailer = require './lib/mailer' config = require './lib/config' _ = require 'underscore' __ = (require './lib/i18n').__ exports.mailconf = (req, res) -> options = (config.get 'mail') or {} options.ssl = options.secureConnection options.tls = !options.ignoreTLS if options.auth options.username = options.auth.user res.render 'admin/mailconf.jade', options: options title: 'Mail Configuration' exports.postMailconf = (req, res) -> originOptions = config.get 'mail' newOptions = from: req.body.from host: req.body.host secureConnection: req.body.ssl port: req.body.port ignoreTLS: not req.body.tls authMethod: req.body.authMethod auth: user: req.body.username pass: PI:PASSWORD:<PASSWORD>END_PI # Update password only if not empty. if (not newOptions.auth.pass) and originOptions and originOptions.auth newOptions.auth.pass = originOptions.auth.pass config.set 'mail', newOptions res.redirect '/' exports.mail = (req, res) -> res.render 'admin/mail.jade', notConfigured: !(config.get 'mail') title: 'Mail' to: req.query.to urls: mailConf: '/admin/mailconf' exports.postMail = (req, res) -> mailer.send to: req.body.to, subject: req.body.subject text: req.body.body res.redirect '/admin/mail'
[ { "context": "= sinon.stub console, 'error'\n\n message = 'Test message'\n exercise = -> errorReporter.repo", "end": 4378, "score": 0.6503401398658752, "start": 4374, "tag": "NAME", "value": "Test" } ]
spec/error-reporter.coffee
gss/error-reporter
4
if window? ErrorReporter = require 'error-reporter' else ErrorReporter = require '../lib/error-reporter' chai = require 'chai' sinon = require 'sinon' {expect} = chai describe 'Error reporter', -> describe 'creating an instance', -> context 'without source code', -> it 'should throw an error', -> exercise = -> new ErrorReporter expect(exercise).to.throw Error, 'Source code not provided' context 'with source code that is not a string', -> it 'should throw an error', -> exercise = -> new ErrorReporter({}) expect(exercise).to.throw TypeError, 'Source code must be a string' context 'with source code that is a string', -> it 'should create an instance', -> expect(new ErrorReporter('')).to.be.an.instanceof ErrorReporter describe 'reporting an error', -> describe 'with a message', -> context 'not provided', -> it 'should throw an error', -> errorReporter = new ErrorReporter 'a' exercise = -> errorReporter.reportError null, 1, 1 expect(exercise).to.throw Error, 'Message not provided' context 'that is not a string', -> it 'should throw an error', -> errorReporter = new ErrorReporter 'a' exercise = -> errorReporter.reportError {}, 1, 1 expect(exercise).to.throw TypeError, 'Message must be a string' context 'that is empty', -> it 'should throw an error', -> errorReporter = new ErrorReporter 'a' exercise = -> errorReporter.reportError '', 1, 1 expect(exercise).to.throw Error, 'Message must not be empty' describe 'with a line number', -> context 'not provided', -> it 'should throw an error', -> errorReporter = new ErrorReporter 'a' exercise = -> errorReporter.reportError 'Test message', null, 1 expect(exercise).to.throw Error, 'Line number not provided' context 'that is not a number', -> it 'should throw an error', -> errorReporter = new ErrorReporter 'a' exercise = -> errorReporter.reportError 'Test message', {}, 1 expect(exercise).to.throw TypeError, 'Line number must be a number' context 'that is invalid', -> it 'should throw an error', -> errorReporter = new ErrorReporter 'a' exercise = -> errorReporter.reportError 'Test message', 0, 1 expect(exercise).to.throw RangeError, 'Line number is invalid' context 'that is out of range', -> it 'should throw an error', -> errorReporter = new ErrorReporter 'a' exercise = -> errorReporter.reportError 'Test message', 2, 1 expect(exercise).to.throw RangeError, 'Line number is out of range' describe 'with a column number', -> context 'not provided', -> it 'should throw an error', -> errorReporter = new ErrorReporter 'a' exercise = -> errorReporter.reportError 'Test message', 1, null expect(exercise).to.throw Error, 'Column number not provided' context 'that is not a number', -> it 'should throw an error', -> errorReporter = new ErrorReporter 'a' exercise = -> errorReporter.reportError 'Test message', 1, {} expect(exercise).to.throw TypeError, 'Column number must be a number' context 'that is invalid', -> it 'should throw an error', -> errorReporter = new ErrorReporter 'a' exercise = -> errorReporter.reportError 'Test message', 1, 0 expect(exercise).to.throw RangeError, 'Column number is invalid' context 'that is out of range', -> it 'should throw an error', -> errorReporter = new ErrorReporter 'a' exercise = -> errorReporter.reportError 'Test message', 1, 2 expect(exercise).to.throw RangeError, 'Column number is out of range' context 'with valid parameters', -> it 'should output an error in the console', -> errorReporter = new ErrorReporter 'a' stub = sinon.stub console, 'error' try errorReporter.reportError 'Test message', 1, 1 expect(stub.calledOnce).to.be.true stub.restore() it 'should throw an error', -> errorReporter = new ErrorReporter 'a' stub = sinon.stub console, 'error' message = 'Test message' exercise = -> errorReporter.reportError message, 1, 1 expect(exercise).to.throw Error, message stub.restore() describe 'with source code', -> context 'that does not have the previous or next line', -> it 'should provide the current line as context', -> sourceCode = 'a' errorReporter = new ErrorReporter sourceCode stub = sinon.stub console, 'error' message = 'Test error message' lineNumber = 1 columnNumber = 1 try errorReporter.reportError message, lineNumber, columnNumber contextualErrorFixture = [ "Error on line #{lineNumber}, column #{columnNumber}: #{message}" '' '1 : a' '^ : ^' ].join '\n' contextualError = stub.firstCall.args[0] stub.restore() expect(contextualError).to.equal contextualErrorFixture context 'that does not have the previous line', -> it 'should provide the current and next line as context', -> sourceCode = 'ab'.split('').join '\n' errorReporter = new ErrorReporter sourceCode stub = sinon.stub console, 'error' message = 'Test error message' lineNumber = 1 columnNumber = 1 try errorReporter.reportError message, lineNumber, columnNumber contextualErrorFixture = [ "Error on line #{lineNumber}, column #{columnNumber}: #{message}" '' '1 : a' '^ : ^' '2 : b' ].join '\n' contextualError = stub.firstCall.args[0] stub.restore() expect(contextualError).to.equal contextualErrorFixture context 'that does not have the next line', -> it 'should provide the previous and current line as context', -> sourceCode = 'ab'.split('').join '\n' errorReporter = new ErrorReporter sourceCode stub = sinon.stub console, 'error' message = 'Test error message' lineNumber = 2 columnNumber = 1 try errorReporter.reportError message, lineNumber, columnNumber contextualErrorFixture = [ "Error on line #{lineNumber}, column #{columnNumber}: #{message}" '' '1 : a' '2 : b' '^ : ^' ].join '\n' contextualError = stub.firstCall.args[0] stub.restore() expect(contextualError).to.equal contextualErrorFixture context 'that has the previous and next line', -> it 'should provide the previous, current, and next line as context', -> sourceCode = 'abc'.split('').join '\n' errorReporter = new ErrorReporter sourceCode stub = sinon.stub console, 'error' message = 'Test error message' lineNumber = 2 columnNumber = 1 try errorReporter.reportError message, lineNumber, columnNumber contextualErrorFixture = [ "Error on line #{lineNumber}, column #{columnNumber}: #{message}" '' '1 : a' '2 : b' '^ : ^' '3 : c' ].join '\n' contextualError = stub.firstCall.args[0] stub.restore() expect(contextualError).to.equal contextualErrorFixture describe 'when formatting', -> context 'with line numbers of different length', -> it 'should pad the gutter values correctly', -> sourceCode = 'abcdefghij'.split('').join '\n' errorReporter = new ErrorReporter sourceCode stub = sinon.stub console, 'error' message = 'Test error message' lineNumber = 9 columnNumber = 1 try errorReporter.reportError message, lineNumber, columnNumber contextualErrorFixture = [ "Error on line #{lineNumber}, column #{columnNumber}: #{message}" '' ' 8 : h' ' 9 : i' ' ^ : ^' '10 : j' ].join '\n' contextualError = stub.firstCall.args[0] stub.restore() expect(contextualError).to.equal contextualErrorFixture
75301
if window? ErrorReporter = require 'error-reporter' else ErrorReporter = require '../lib/error-reporter' chai = require 'chai' sinon = require 'sinon' {expect} = chai describe 'Error reporter', -> describe 'creating an instance', -> context 'without source code', -> it 'should throw an error', -> exercise = -> new ErrorReporter expect(exercise).to.throw Error, 'Source code not provided' context 'with source code that is not a string', -> it 'should throw an error', -> exercise = -> new ErrorReporter({}) expect(exercise).to.throw TypeError, 'Source code must be a string' context 'with source code that is a string', -> it 'should create an instance', -> expect(new ErrorReporter('')).to.be.an.instanceof ErrorReporter describe 'reporting an error', -> describe 'with a message', -> context 'not provided', -> it 'should throw an error', -> errorReporter = new ErrorReporter 'a' exercise = -> errorReporter.reportError null, 1, 1 expect(exercise).to.throw Error, 'Message not provided' context 'that is not a string', -> it 'should throw an error', -> errorReporter = new ErrorReporter 'a' exercise = -> errorReporter.reportError {}, 1, 1 expect(exercise).to.throw TypeError, 'Message must be a string' context 'that is empty', -> it 'should throw an error', -> errorReporter = new ErrorReporter 'a' exercise = -> errorReporter.reportError '', 1, 1 expect(exercise).to.throw Error, 'Message must not be empty' describe 'with a line number', -> context 'not provided', -> it 'should throw an error', -> errorReporter = new ErrorReporter 'a' exercise = -> errorReporter.reportError 'Test message', null, 1 expect(exercise).to.throw Error, 'Line number not provided' context 'that is not a number', -> it 'should throw an error', -> errorReporter = new ErrorReporter 'a' exercise = -> errorReporter.reportError 'Test message', {}, 1 expect(exercise).to.throw TypeError, 'Line number must be a number' context 'that is invalid', -> it 'should throw an error', -> errorReporter = new ErrorReporter 'a' exercise = -> errorReporter.reportError 'Test message', 0, 1 expect(exercise).to.throw RangeError, 'Line number is invalid' context 'that is out of range', -> it 'should throw an error', -> errorReporter = new ErrorReporter 'a' exercise = -> errorReporter.reportError 'Test message', 2, 1 expect(exercise).to.throw RangeError, 'Line number is out of range' describe 'with a column number', -> context 'not provided', -> it 'should throw an error', -> errorReporter = new ErrorReporter 'a' exercise = -> errorReporter.reportError 'Test message', 1, null expect(exercise).to.throw Error, 'Column number not provided' context 'that is not a number', -> it 'should throw an error', -> errorReporter = new ErrorReporter 'a' exercise = -> errorReporter.reportError 'Test message', 1, {} expect(exercise).to.throw TypeError, 'Column number must be a number' context 'that is invalid', -> it 'should throw an error', -> errorReporter = new ErrorReporter 'a' exercise = -> errorReporter.reportError 'Test message', 1, 0 expect(exercise).to.throw RangeError, 'Column number is invalid' context 'that is out of range', -> it 'should throw an error', -> errorReporter = new ErrorReporter 'a' exercise = -> errorReporter.reportError 'Test message', 1, 2 expect(exercise).to.throw RangeError, 'Column number is out of range' context 'with valid parameters', -> it 'should output an error in the console', -> errorReporter = new ErrorReporter 'a' stub = sinon.stub console, 'error' try errorReporter.reportError 'Test message', 1, 1 expect(stub.calledOnce).to.be.true stub.restore() it 'should throw an error', -> errorReporter = new ErrorReporter 'a' stub = sinon.stub console, 'error' message = '<NAME> message' exercise = -> errorReporter.reportError message, 1, 1 expect(exercise).to.throw Error, message stub.restore() describe 'with source code', -> context 'that does not have the previous or next line', -> it 'should provide the current line as context', -> sourceCode = 'a' errorReporter = new ErrorReporter sourceCode stub = sinon.stub console, 'error' message = 'Test error message' lineNumber = 1 columnNumber = 1 try errorReporter.reportError message, lineNumber, columnNumber contextualErrorFixture = [ "Error on line #{lineNumber}, column #{columnNumber}: #{message}" '' '1 : a' '^ : ^' ].join '\n' contextualError = stub.firstCall.args[0] stub.restore() expect(contextualError).to.equal contextualErrorFixture context 'that does not have the previous line', -> it 'should provide the current and next line as context', -> sourceCode = 'ab'.split('').join '\n' errorReporter = new ErrorReporter sourceCode stub = sinon.stub console, 'error' message = 'Test error message' lineNumber = 1 columnNumber = 1 try errorReporter.reportError message, lineNumber, columnNumber contextualErrorFixture = [ "Error on line #{lineNumber}, column #{columnNumber}: #{message}" '' '1 : a' '^ : ^' '2 : b' ].join '\n' contextualError = stub.firstCall.args[0] stub.restore() expect(contextualError).to.equal contextualErrorFixture context 'that does not have the next line', -> it 'should provide the previous and current line as context', -> sourceCode = 'ab'.split('').join '\n' errorReporter = new ErrorReporter sourceCode stub = sinon.stub console, 'error' message = 'Test error message' lineNumber = 2 columnNumber = 1 try errorReporter.reportError message, lineNumber, columnNumber contextualErrorFixture = [ "Error on line #{lineNumber}, column #{columnNumber}: #{message}" '' '1 : a' '2 : b' '^ : ^' ].join '\n' contextualError = stub.firstCall.args[0] stub.restore() expect(contextualError).to.equal contextualErrorFixture context 'that has the previous and next line', -> it 'should provide the previous, current, and next line as context', -> sourceCode = 'abc'.split('').join '\n' errorReporter = new ErrorReporter sourceCode stub = sinon.stub console, 'error' message = 'Test error message' lineNumber = 2 columnNumber = 1 try errorReporter.reportError message, lineNumber, columnNumber contextualErrorFixture = [ "Error on line #{lineNumber}, column #{columnNumber}: #{message}" '' '1 : a' '2 : b' '^ : ^' '3 : c' ].join '\n' contextualError = stub.firstCall.args[0] stub.restore() expect(contextualError).to.equal contextualErrorFixture describe 'when formatting', -> context 'with line numbers of different length', -> it 'should pad the gutter values correctly', -> sourceCode = 'abcdefghij'.split('').join '\n' errorReporter = new ErrorReporter sourceCode stub = sinon.stub console, 'error' message = 'Test error message' lineNumber = 9 columnNumber = 1 try errorReporter.reportError message, lineNumber, columnNumber contextualErrorFixture = [ "Error on line #{lineNumber}, column #{columnNumber}: #{message}" '' ' 8 : h' ' 9 : i' ' ^ : ^' '10 : j' ].join '\n' contextualError = stub.firstCall.args[0] stub.restore() expect(contextualError).to.equal contextualErrorFixture
true
if window? ErrorReporter = require 'error-reporter' else ErrorReporter = require '../lib/error-reporter' chai = require 'chai' sinon = require 'sinon' {expect} = chai describe 'Error reporter', -> describe 'creating an instance', -> context 'without source code', -> it 'should throw an error', -> exercise = -> new ErrorReporter expect(exercise).to.throw Error, 'Source code not provided' context 'with source code that is not a string', -> it 'should throw an error', -> exercise = -> new ErrorReporter({}) expect(exercise).to.throw TypeError, 'Source code must be a string' context 'with source code that is a string', -> it 'should create an instance', -> expect(new ErrorReporter('')).to.be.an.instanceof ErrorReporter describe 'reporting an error', -> describe 'with a message', -> context 'not provided', -> it 'should throw an error', -> errorReporter = new ErrorReporter 'a' exercise = -> errorReporter.reportError null, 1, 1 expect(exercise).to.throw Error, 'Message not provided' context 'that is not a string', -> it 'should throw an error', -> errorReporter = new ErrorReporter 'a' exercise = -> errorReporter.reportError {}, 1, 1 expect(exercise).to.throw TypeError, 'Message must be a string' context 'that is empty', -> it 'should throw an error', -> errorReporter = new ErrorReporter 'a' exercise = -> errorReporter.reportError '', 1, 1 expect(exercise).to.throw Error, 'Message must not be empty' describe 'with a line number', -> context 'not provided', -> it 'should throw an error', -> errorReporter = new ErrorReporter 'a' exercise = -> errorReporter.reportError 'Test message', null, 1 expect(exercise).to.throw Error, 'Line number not provided' context 'that is not a number', -> it 'should throw an error', -> errorReporter = new ErrorReporter 'a' exercise = -> errorReporter.reportError 'Test message', {}, 1 expect(exercise).to.throw TypeError, 'Line number must be a number' context 'that is invalid', -> it 'should throw an error', -> errorReporter = new ErrorReporter 'a' exercise = -> errorReporter.reportError 'Test message', 0, 1 expect(exercise).to.throw RangeError, 'Line number is invalid' context 'that is out of range', -> it 'should throw an error', -> errorReporter = new ErrorReporter 'a' exercise = -> errorReporter.reportError 'Test message', 2, 1 expect(exercise).to.throw RangeError, 'Line number is out of range' describe 'with a column number', -> context 'not provided', -> it 'should throw an error', -> errorReporter = new ErrorReporter 'a' exercise = -> errorReporter.reportError 'Test message', 1, null expect(exercise).to.throw Error, 'Column number not provided' context 'that is not a number', -> it 'should throw an error', -> errorReporter = new ErrorReporter 'a' exercise = -> errorReporter.reportError 'Test message', 1, {} expect(exercise).to.throw TypeError, 'Column number must be a number' context 'that is invalid', -> it 'should throw an error', -> errorReporter = new ErrorReporter 'a' exercise = -> errorReporter.reportError 'Test message', 1, 0 expect(exercise).to.throw RangeError, 'Column number is invalid' context 'that is out of range', -> it 'should throw an error', -> errorReporter = new ErrorReporter 'a' exercise = -> errorReporter.reportError 'Test message', 1, 2 expect(exercise).to.throw RangeError, 'Column number is out of range' context 'with valid parameters', -> it 'should output an error in the console', -> errorReporter = new ErrorReporter 'a' stub = sinon.stub console, 'error' try errorReporter.reportError 'Test message', 1, 1 expect(stub.calledOnce).to.be.true stub.restore() it 'should throw an error', -> errorReporter = new ErrorReporter 'a' stub = sinon.stub console, 'error' message = 'PI:NAME:<NAME>END_PI message' exercise = -> errorReporter.reportError message, 1, 1 expect(exercise).to.throw Error, message stub.restore() describe 'with source code', -> context 'that does not have the previous or next line', -> it 'should provide the current line as context', -> sourceCode = 'a' errorReporter = new ErrorReporter sourceCode stub = sinon.stub console, 'error' message = 'Test error message' lineNumber = 1 columnNumber = 1 try errorReporter.reportError message, lineNumber, columnNumber contextualErrorFixture = [ "Error on line #{lineNumber}, column #{columnNumber}: #{message}" '' '1 : a' '^ : ^' ].join '\n' contextualError = stub.firstCall.args[0] stub.restore() expect(contextualError).to.equal contextualErrorFixture context 'that does not have the previous line', -> it 'should provide the current and next line as context', -> sourceCode = 'ab'.split('').join '\n' errorReporter = new ErrorReporter sourceCode stub = sinon.stub console, 'error' message = 'Test error message' lineNumber = 1 columnNumber = 1 try errorReporter.reportError message, lineNumber, columnNumber contextualErrorFixture = [ "Error on line #{lineNumber}, column #{columnNumber}: #{message}" '' '1 : a' '^ : ^' '2 : b' ].join '\n' contextualError = stub.firstCall.args[0] stub.restore() expect(contextualError).to.equal contextualErrorFixture context 'that does not have the next line', -> it 'should provide the previous and current line as context', -> sourceCode = 'ab'.split('').join '\n' errorReporter = new ErrorReporter sourceCode stub = sinon.stub console, 'error' message = 'Test error message' lineNumber = 2 columnNumber = 1 try errorReporter.reportError message, lineNumber, columnNumber contextualErrorFixture = [ "Error on line #{lineNumber}, column #{columnNumber}: #{message}" '' '1 : a' '2 : b' '^ : ^' ].join '\n' contextualError = stub.firstCall.args[0] stub.restore() expect(contextualError).to.equal contextualErrorFixture context 'that has the previous and next line', -> it 'should provide the previous, current, and next line as context', -> sourceCode = 'abc'.split('').join '\n' errorReporter = new ErrorReporter sourceCode stub = sinon.stub console, 'error' message = 'Test error message' lineNumber = 2 columnNumber = 1 try errorReporter.reportError message, lineNumber, columnNumber contextualErrorFixture = [ "Error on line #{lineNumber}, column #{columnNumber}: #{message}" '' '1 : a' '2 : b' '^ : ^' '3 : c' ].join '\n' contextualError = stub.firstCall.args[0] stub.restore() expect(contextualError).to.equal contextualErrorFixture describe 'when formatting', -> context 'with line numbers of different length', -> it 'should pad the gutter values correctly', -> sourceCode = 'abcdefghij'.split('').join '\n' errorReporter = new ErrorReporter sourceCode stub = sinon.stub console, 'error' message = 'Test error message' lineNumber = 9 columnNumber = 1 try errorReporter.reportError message, lineNumber, columnNumber contextualErrorFixture = [ "Error on line #{lineNumber}, column #{columnNumber}: #{message}" '' ' 8 : h' ' 9 : i' ' ^ : ^' '10 : j' ].join '\n' contextualError = stub.firstCall.args[0] stub.restore() expect(contextualError).to.equal contextualErrorFixture
[ { "context": " + tell me a poem\n - There once was a man named Tim,\\\\s\n ^ who never quite learned how to swim.\\\\s", "end": 3021, "score": 0.9996440410614014, "start": 3018, "tag": "NAME", "value": "Tim" }, { "context": "ply(\"Tell me a poem.\", \"There once was a man named...
test/test-replies.coffee
rundexter/rivescript-js
1
TestCase = require("./test-base") ################################################################################ # Reply Tests ################################################################################ exports.test_previous = (test) -> bot = new TestCase(test, """ ! sub who's = who is ! sub it's = it is ! sub didn't = did not + knock knock - Who's there? + * % who is there - <sentence> who? + * % * who - Haha! <sentence>! + ask me a question - How many arms do I have? + [*] # [*] % how many arms do i have * <star> == 2 => Yes! - No! + * % how many arms do i have - That isn't a number. + * - I don't know. """) bot.reply("knock knock", "Who's there?") bot.reply("Canoe", "Canoe who?") bot.reply("Canoe help me with my homework?", "Haha! Canoe help me with my homework!") bot.reply("hello", "I don't know.") bot.reply("Ask me a question", "How many arms do I have?") bot.reply("1", "No!") bot.reply("Ask me a question", "How many arms do I have?") bot.reply("2", "Yes!") bot.reply("Ask me a question", "How many arms do I have?") bot.reply("lol", "That isn't a number.") test.done() exports.test_random = (test) -> bot = new TestCase(test, """ + test random response - One. - Two. + test random tag - This sentence has a random {random}word|bit{/random}. """) bot.replyRandom("test random response", ["One.", "Two."]) bot.replyRandom("test random tag", [ "This sentence has a random word.", "This sentence has a random bit.", ]) test.done() exports.test_unrandom = (test) -> bot = new TestCase(test, """ + test random response - One. - Two. - Two. - Two. - Two. - Two. - Two. - Two. - Two. - Two. + test random tag - Pick {random}1|2|2|2|2|2|2|2|2|2|2{/random} """, {"forceFirst": true}) # Yeah, this is ugly and imperfect, but there isn't a good way to test a pool of answers right now. bot.reply("test random response", "One.") bot.reply("test random response", "One.") bot.reply("test random response", "One.") bot.reply("test random response", "One.") bot.reply("test random response", "One.") bot.reply("test random response", "One.") bot.reply("test random response", "One.") bot.reply("test random response", "One.") bot.reply("test random response", "One.") bot.reply("test random response", "One.") bot.reply("test random tag", "Pick 1") bot.reply("test random tag", "Pick 1") bot.reply("test random tag", "Pick 1") bot.reply("test random tag", "Pick 1") bot.reply("test random tag", "Pick 1") bot.reply("test random tag", "Pick 1") bot.reply("test random tag", "Pick 1") bot.reply("test random tag", "Pick 1") bot.reply("test random tag", "Pick 1") bot.reply("test random tag", "Pick 1") test.done() exports.test_continuations = (test) -> bot = new TestCase(test, """ + tell me a poem - There once was a man named Tim,\\s ^ who never quite learned how to swim.\\s ^ He fell off a dock, and sank like a rock,\\s ^ and that was the end of him. """) bot.reply("Tell me a poem.", "There once was a man named Tim, who never quite learned how to swim. He fell off a dock, and sank like a rock, and that was the end of him.") test.done() exports.test_redirects = (test) -> bot = new TestCase(test, """ + hello - Hi there! + hey @ hello // Test the {@} tag with and without spaces. + hi there - {@hello} + howdy - {@ hello} + hola - {@ hello } """) bot.reply("hello", "Hi there!") bot.reply("hey", "Hi there!") bot.reply("hi there", "Hi there!") bot.reply("howdy", "Hi there!") bot.reply("hola", "Hi there!") test.done() exports.test_conditionals = (test) -> bot = new TestCase(test, """ + i am # years old - <set age=<star>>OK. + what can i do * <get age> == undefined => I don't know. * <get age> > 25 => Anything you want. * <get age> == 25 => Rent a car for cheap. * <get age> >= 21 => Drink. * <get age> >= 18 => Vote. * <get age> < 18 => Not much of anything. + am i your master * <get master> == true => Yes. - No. """) age_q = "What can I do?" bot.reply(age_q, "I don't know.") ages = '16' : "Not much of anything." '18' : "Vote." '20' : "Vote." '22' : "Drink." '24' : "Drink." '25' : "Rent a car for cheap." '27' : "Anything you want." for age of ages if (!ages.hasOwnProperty(age)) continue bot.reply("I am " + age + " years old.", "OK.") bot.reply(age_q, ages[age]) bot.reply("Am I your master?", "No.") bot.rs.setUservar(bot.username, "master", "true") bot.reply("Am I your master?", "Yes.") test.done() exports.test_embedded_tags = (test) -> bot = new TestCase(test, """ + my name is * * <get name> != undefined => <set oldname=<get name>>I thought\\s ^ your name was <get oldname>? ^ <set name=<formal>> - <set name=<formal>>OK. + what is my name - Your name is <get name>, right? + html test - <set name=<b>Name</b>>This has some non-RS <em>tags</em> in it. """) bot.reply("What is my name?", "Your name is undefined, right?") bot.reply("My name is Alice.", "OK.") bot.reply("My name is Bob.", "I thought your name was Alice?") bot.reply("What is my name?", "Your name is Bob, right?") bot.reply("HTML Test", "This has some non-RS <em>tags</em> in it.") test.done() exports.test_set_uservars = (test) -> bot = new TestCase(test, """ + what is my name - Your name is <get name>. + how old am i - You are <get age>. """) bot.rs.setUservars(bot.username, { "name": "Aiden", "age": 5, }) bot.reply("What is my name?", "Your name is Aiden.") bot.reply("How old am I?", "You are 5.") test.done() exports.test_questionmark = (test) -> bot = new TestCase(test, """ + google * - <a href="https://www.google.com/search?q=<star>">Results are here</a> """) bot.reply("google coffeescript", '<a href="https://www.google.com/search?q=coffeescript">Results are here</a>' ) test.done() exports.test_reply_arrays = (test) -> bot = new TestCase(test, """ ! array greek = alpha beta gamma ! array test = testing trying ! array format = <uppercase>|<lowercase>|<formal>|<sentence> + test random array - Testing (@greek) array. + test two random arrays - {formal}(@test){/formal} another (@greek) array. + test nonexistant array - This (@array) does not exist. + test more arrays - I'm (@test) more (@greek) (@arrays). + test weird syntax - This (@ greek) shouldn't work, and neither should this @test. + random format * - (@format) """) bot.replyRandom("test random array", [ "Testing alpha array.", "Testing beta array.", "Testing gamma array.", ]) bot.replyRandom("test two random arrays", [ "Testing another alpha array.", "Testing another beta array.", "Testing another gamma array.", "Trying another alpha array.", "Trying another beta array.", "Trying another gamma array.", ]) bot.reply("test nonexistant array", "This (@array) does not exist.") bot.replyRandom("test more arrays", [ "I'm testing more alpha (@arrays).", "I'm testing more beta (@arrays).", "I'm testing more gamma (@arrays).", "I'm trying more alpha (@arrays).", "I'm trying more beta (@arrays).", "I'm trying more gamma (@arrays)." ]) bot.reply("test weird syntax", "This (@ greek) shouldn't work, and neither should this @test.") bot.replyRandom("random format hello world", [ "HELLO WORLD", "hello world", "Hello World", "Hello world", ]) test.done() exports.test_raw = (test) -> bot = new TestCase(test, ''' > object test javascript return 'OH NO'; < object + rawget - OK <raw><get foo></raw> DONE + rawtopic - OK <raw>{topic=foo}</raw> DONE + rawcall - OK <raw><call>test</call></raw> DONE + multiraw - <raw><call>test</call></raw> <call>test</call> <raw>^two()</raw> ...DONE? <raw>{@ok}</raw>! ''') bot.reply('rawget', 'OK <get foo> DONE') bot.reply('rawtopic', 'OK {topic=foo} DONE') bot.reply('rawcall', 'OK <call>test</call> DONE') bot.reply('multiraw', '<call>test</call> OH NO ^two() ...DONE? {@ok}!') test.done() exports.test_replace_recursion = (test) -> bot = new TestCase(test, ''' + * - {@a}{@b} ''') bot.reply('go', "#{bot.rs.errors.deepRecursion}") test.done()
223370
TestCase = require("./test-base") ################################################################################ # Reply Tests ################################################################################ exports.test_previous = (test) -> bot = new TestCase(test, """ ! sub who's = who is ! sub it's = it is ! sub didn't = did not + knock knock - Who's there? + * % who is there - <sentence> who? + * % * who - Haha! <sentence>! + ask me a question - How many arms do I have? + [*] # [*] % how many arms do i have * <star> == 2 => Yes! - No! + * % how many arms do i have - That isn't a number. + * - I don't know. """) bot.reply("knock knock", "Who's there?") bot.reply("Canoe", "Canoe who?") bot.reply("Canoe help me with my homework?", "Haha! Canoe help me with my homework!") bot.reply("hello", "I don't know.") bot.reply("Ask me a question", "How many arms do I have?") bot.reply("1", "No!") bot.reply("Ask me a question", "How many arms do I have?") bot.reply("2", "Yes!") bot.reply("Ask me a question", "How many arms do I have?") bot.reply("lol", "That isn't a number.") test.done() exports.test_random = (test) -> bot = new TestCase(test, """ + test random response - One. - Two. + test random tag - This sentence has a random {random}word|bit{/random}. """) bot.replyRandom("test random response", ["One.", "Two."]) bot.replyRandom("test random tag", [ "This sentence has a random word.", "This sentence has a random bit.", ]) test.done() exports.test_unrandom = (test) -> bot = new TestCase(test, """ + test random response - One. - Two. - Two. - Two. - Two. - Two. - Two. - Two. - Two. - Two. + test random tag - Pick {random}1|2|2|2|2|2|2|2|2|2|2{/random} """, {"forceFirst": true}) # Yeah, this is ugly and imperfect, but there isn't a good way to test a pool of answers right now. bot.reply("test random response", "One.") bot.reply("test random response", "One.") bot.reply("test random response", "One.") bot.reply("test random response", "One.") bot.reply("test random response", "One.") bot.reply("test random response", "One.") bot.reply("test random response", "One.") bot.reply("test random response", "One.") bot.reply("test random response", "One.") bot.reply("test random response", "One.") bot.reply("test random tag", "Pick 1") bot.reply("test random tag", "Pick 1") bot.reply("test random tag", "Pick 1") bot.reply("test random tag", "Pick 1") bot.reply("test random tag", "Pick 1") bot.reply("test random tag", "Pick 1") bot.reply("test random tag", "Pick 1") bot.reply("test random tag", "Pick 1") bot.reply("test random tag", "Pick 1") bot.reply("test random tag", "Pick 1") test.done() exports.test_continuations = (test) -> bot = new TestCase(test, """ + tell me a poem - There once was a man named <NAME>,\\s ^ who never quite learned how to swim.\\s ^ He fell off a dock, and sank like a rock,\\s ^ and that was the end of him. """) bot.reply("Tell me a poem.", "There once was a man named <NAME>, who never quite learned how to swim. He fell off a dock, and sank like a rock, and that was the end of him.") test.done() exports.test_redirects = (test) -> bot = new TestCase(test, """ + hello - Hi there! + hey @ hello // Test the {@} tag with and without spaces. + hi there - {@hello} + howdy - {@ hello} + hola - {@ hello } """) bot.reply("hello", "Hi there!") bot.reply("hey", "Hi there!") bot.reply("hi there", "Hi there!") bot.reply("howdy", "Hi there!") bot.reply("hola", "Hi there!") test.done() exports.test_conditionals = (test) -> bot = new TestCase(test, """ + i am # years old - <set age=<star>>OK. + what can i do * <get age> == undefined => I don't know. * <get age> > 25 => Anything you want. * <get age> == 25 => Rent a car for cheap. * <get age> >= 21 => Drink. * <get age> >= 18 => Vote. * <get age> < 18 => Not much of anything. + am i your master * <get master> == true => Yes. - No. """) age_q = "What can I do?" bot.reply(age_q, "I don't know.") ages = '16' : "Not much of anything." '18' : "Vote." '20' : "Vote." '22' : "Drink." '24' : "Drink." '25' : "Rent a car for cheap." '27' : "Anything you want." for age of ages if (!ages.hasOwnProperty(age)) continue bot.reply("I am " + age + " years old.", "OK.") bot.reply(age_q, ages[age]) bot.reply("Am I your master?", "No.") bot.rs.setUservar(bot.username, "master", "true") bot.reply("Am I your master?", "Yes.") test.done() exports.test_embedded_tags = (test) -> bot = new TestCase(test, """ + my name is * * <get name> != undefined => <set oldname=<get name>>I thought\\s ^ your name was <get oldname>? ^ <set name=<formal>> - <set name=<formal>>OK. + what is my name - Your name is <get name>, right? + html test - <set name=<b>Name</b>>This has some non-RS <em>tags</em> in it. """) bot.reply("What is my name?", "Your name is undefined, right?") bot.reply("My name is <NAME>.", "OK.") bot.reply("My name is <NAME>.", "I thought your name was <NAME>?") bot.reply("What is my name?", "Your name is <NAME>, right?") bot.reply("HTML Test", "This has some non-RS <em>tags</em> in it.") test.done() exports.test_set_uservars = (test) -> bot = new TestCase(test, """ + what is my name - Your name is <get name>. + how old am i - You are <get age>. """) bot.rs.setUservars(bot.username, { "name": "<NAME>", "age": 5, }) bot.reply("What is my name?", "Your name is <NAME>.") bot.reply("How old am I?", "You are 5.") test.done() exports.test_questionmark = (test) -> bot = new TestCase(test, """ + google * - <a href="https://www.google.com/search?q=<star>">Results are here</a> """) bot.reply("google coffeescript", '<a href="https://www.google.com/search?q=coffeescript">Results are here</a>' ) test.done() exports.test_reply_arrays = (test) -> bot = new TestCase(test, """ ! array greek = alpha beta gamma ! array test = testing trying ! array format = <uppercase>|<lowercase>|<formal>|<sentence> + test random array - Testing (@greek) array. + test two random arrays - {formal}(@test){/formal} another (@greek) array. + test nonexistant array - This (@array) does not exist. + test more arrays - I'm (@test) more (@greek) (@arrays). + test weird syntax - This (@ greek) shouldn't work, and neither should this @test. + random format * - (@format) """) bot.replyRandom("test random array", [ "Testing alpha array.", "Testing beta array.", "Testing gamma array.", ]) bot.replyRandom("test two random arrays", [ "Testing another alpha array.", "Testing another beta array.", "Testing another gamma array.", "Trying another alpha array.", "Trying another beta array.", "Trying another gamma array.", ]) bot.reply("test nonexistant array", "This (@array) does not exist.") bot.replyRandom("test more arrays", [ "I'm testing more alpha (@arrays).", "I'm testing more beta (@arrays).", "I'm testing more gamma (@arrays).", "I'm trying more alpha (@arrays).", "I'm trying more beta (@arrays).", "I'm trying more gamma (@arrays)." ]) bot.reply("test weird syntax", "This (@ greek) shouldn't work, and neither should this @test.") bot.replyRandom("random format hello world", [ "HELLO WORLD", "hello world", "Hello World", "Hello world", ]) test.done() exports.test_raw = (test) -> bot = new TestCase(test, ''' > object test javascript return 'OH NO'; < object + rawget - OK <raw><get foo></raw> DONE + rawtopic - OK <raw>{topic=foo}</raw> DONE + rawcall - OK <raw><call>test</call></raw> DONE + multiraw - <raw><call>test</call></raw> <call>test</call> <raw>^two()</raw> ...DONE? <raw>{@ok}</raw>! ''') bot.reply('rawget', 'OK <get foo> DONE') bot.reply('rawtopic', 'OK {topic=foo} DONE') bot.reply('rawcall', 'OK <call>test</call> DONE') bot.reply('multiraw', '<call>test</call> OH NO ^two() ...DONE? {@ok}!') test.done() exports.test_replace_recursion = (test) -> bot = new TestCase(test, ''' + * - {@a}{@b} ''') bot.reply('go', "#{bot.rs.errors.deepRecursion}") test.done()
true
TestCase = require("./test-base") ################################################################################ # Reply Tests ################################################################################ exports.test_previous = (test) -> bot = new TestCase(test, """ ! sub who's = who is ! sub it's = it is ! sub didn't = did not + knock knock - Who's there? + * % who is there - <sentence> who? + * % * who - Haha! <sentence>! + ask me a question - How many arms do I have? + [*] # [*] % how many arms do i have * <star> == 2 => Yes! - No! + * % how many arms do i have - That isn't a number. + * - I don't know. """) bot.reply("knock knock", "Who's there?") bot.reply("Canoe", "Canoe who?") bot.reply("Canoe help me with my homework?", "Haha! Canoe help me with my homework!") bot.reply("hello", "I don't know.") bot.reply("Ask me a question", "How many arms do I have?") bot.reply("1", "No!") bot.reply("Ask me a question", "How many arms do I have?") bot.reply("2", "Yes!") bot.reply("Ask me a question", "How many arms do I have?") bot.reply("lol", "That isn't a number.") test.done() exports.test_random = (test) -> bot = new TestCase(test, """ + test random response - One. - Two. + test random tag - This sentence has a random {random}word|bit{/random}. """) bot.replyRandom("test random response", ["One.", "Two."]) bot.replyRandom("test random tag", [ "This sentence has a random word.", "This sentence has a random bit.", ]) test.done() exports.test_unrandom = (test) -> bot = new TestCase(test, """ + test random response - One. - Two. - Two. - Two. - Two. - Two. - Two. - Two. - Two. - Two. + test random tag - Pick {random}1|2|2|2|2|2|2|2|2|2|2{/random} """, {"forceFirst": true}) # Yeah, this is ugly and imperfect, but there isn't a good way to test a pool of answers right now. bot.reply("test random response", "One.") bot.reply("test random response", "One.") bot.reply("test random response", "One.") bot.reply("test random response", "One.") bot.reply("test random response", "One.") bot.reply("test random response", "One.") bot.reply("test random response", "One.") bot.reply("test random response", "One.") bot.reply("test random response", "One.") bot.reply("test random response", "One.") bot.reply("test random tag", "Pick 1") bot.reply("test random tag", "Pick 1") bot.reply("test random tag", "Pick 1") bot.reply("test random tag", "Pick 1") bot.reply("test random tag", "Pick 1") bot.reply("test random tag", "Pick 1") bot.reply("test random tag", "Pick 1") bot.reply("test random tag", "Pick 1") bot.reply("test random tag", "Pick 1") bot.reply("test random tag", "Pick 1") test.done() exports.test_continuations = (test) -> bot = new TestCase(test, """ + tell me a poem - There once was a man named PI:NAME:<NAME>END_PI,\\s ^ who never quite learned how to swim.\\s ^ He fell off a dock, and sank like a rock,\\s ^ and that was the end of him. """) bot.reply("Tell me a poem.", "There once was a man named PI:NAME:<NAME>END_PI, who never quite learned how to swim. He fell off a dock, and sank like a rock, and that was the end of him.") test.done() exports.test_redirects = (test) -> bot = new TestCase(test, """ + hello - Hi there! + hey @ hello // Test the {@} tag with and without spaces. + hi there - {@hello} + howdy - {@ hello} + hola - {@ hello } """) bot.reply("hello", "Hi there!") bot.reply("hey", "Hi there!") bot.reply("hi there", "Hi there!") bot.reply("howdy", "Hi there!") bot.reply("hola", "Hi there!") test.done() exports.test_conditionals = (test) -> bot = new TestCase(test, """ + i am # years old - <set age=<star>>OK. + what can i do * <get age> == undefined => I don't know. * <get age> > 25 => Anything you want. * <get age> == 25 => Rent a car for cheap. * <get age> >= 21 => Drink. * <get age> >= 18 => Vote. * <get age> < 18 => Not much of anything. + am i your master * <get master> == true => Yes. - No. """) age_q = "What can I do?" bot.reply(age_q, "I don't know.") ages = '16' : "Not much of anything." '18' : "Vote." '20' : "Vote." '22' : "Drink." '24' : "Drink." '25' : "Rent a car for cheap." '27' : "Anything you want." for age of ages if (!ages.hasOwnProperty(age)) continue bot.reply("I am " + age + " years old.", "OK.") bot.reply(age_q, ages[age]) bot.reply("Am I your master?", "No.") bot.rs.setUservar(bot.username, "master", "true") bot.reply("Am I your master?", "Yes.") test.done() exports.test_embedded_tags = (test) -> bot = new TestCase(test, """ + my name is * * <get name> != undefined => <set oldname=<get name>>I thought\\s ^ your name was <get oldname>? ^ <set name=<formal>> - <set name=<formal>>OK. + what is my name - Your name is <get name>, right? + html test - <set name=<b>Name</b>>This has some non-RS <em>tags</em> in it. """) bot.reply("What is my name?", "Your name is undefined, right?") bot.reply("My name is PI:NAME:<NAME>END_PI.", "OK.") bot.reply("My name is PI:NAME:<NAME>END_PI.", "I thought your name was PI:NAME:<NAME>END_PI?") bot.reply("What is my name?", "Your name is PI:NAME:<NAME>END_PI, right?") bot.reply("HTML Test", "This has some non-RS <em>tags</em> in it.") test.done() exports.test_set_uservars = (test) -> bot = new TestCase(test, """ + what is my name - Your name is <get name>. + how old am i - You are <get age>. """) bot.rs.setUservars(bot.username, { "name": "PI:NAME:<NAME>END_PI", "age": 5, }) bot.reply("What is my name?", "Your name is PI:NAME:<NAME>END_PI.") bot.reply("How old am I?", "You are 5.") test.done() exports.test_questionmark = (test) -> bot = new TestCase(test, """ + google * - <a href="https://www.google.com/search?q=<star>">Results are here</a> """) bot.reply("google coffeescript", '<a href="https://www.google.com/search?q=coffeescript">Results are here</a>' ) test.done() exports.test_reply_arrays = (test) -> bot = new TestCase(test, """ ! array greek = alpha beta gamma ! array test = testing trying ! array format = <uppercase>|<lowercase>|<formal>|<sentence> + test random array - Testing (@greek) array. + test two random arrays - {formal}(@test){/formal} another (@greek) array. + test nonexistant array - This (@array) does not exist. + test more arrays - I'm (@test) more (@greek) (@arrays). + test weird syntax - This (@ greek) shouldn't work, and neither should this @test. + random format * - (@format) """) bot.replyRandom("test random array", [ "Testing alpha array.", "Testing beta array.", "Testing gamma array.", ]) bot.replyRandom("test two random arrays", [ "Testing another alpha array.", "Testing another beta array.", "Testing another gamma array.", "Trying another alpha array.", "Trying another beta array.", "Trying another gamma array.", ]) bot.reply("test nonexistant array", "This (@array) does not exist.") bot.replyRandom("test more arrays", [ "I'm testing more alpha (@arrays).", "I'm testing more beta (@arrays).", "I'm testing more gamma (@arrays).", "I'm trying more alpha (@arrays).", "I'm trying more beta (@arrays).", "I'm trying more gamma (@arrays)." ]) bot.reply("test weird syntax", "This (@ greek) shouldn't work, and neither should this @test.") bot.replyRandom("random format hello world", [ "HELLO WORLD", "hello world", "Hello World", "Hello world", ]) test.done() exports.test_raw = (test) -> bot = new TestCase(test, ''' > object test javascript return 'OH NO'; < object + rawget - OK <raw><get foo></raw> DONE + rawtopic - OK <raw>{topic=foo}</raw> DONE + rawcall - OK <raw><call>test</call></raw> DONE + multiraw - <raw><call>test</call></raw> <call>test</call> <raw>^two()</raw> ...DONE? <raw>{@ok}</raw>! ''') bot.reply('rawget', 'OK <get foo> DONE') bot.reply('rawtopic', 'OK {topic=foo} DONE') bot.reply('rawcall', 'OK <call>test</call> DONE') bot.reply('multiraw', '<call>test</call> OH NO ^two() ...DONE? {@ok}!') test.done() exports.test_replace_recursion = (test) -> bot = new TestCase(test, ''' + * - {@a}{@b} ''') bot.reply('go', "#{bot.rs.errors.deepRecursion}") test.done()
[ { "context": " _.extend {}, @props, @state,\n key: \"layout-precontent-#{key}\"\n Content\n key: @props.curre", "end": 1579, "score": 0.8022708892822266, "start": 1556, "tag": "KEY", "value": "layout-precontent-#{key" }, { "context": "-#{key}\"\n ...
src/components/layout.coffee
brianshaler/kerplunk-dashboard-skin
0
_ = require 'lodash' React = require 'react' {DOM} = React module.exports = React.createFactory React.createClass getInitialState: -> navActive: false componentWillReceiveProps: (newProps) -> if newProps.currentUrl != @props.currentUrl @setState navActive: false toggleNav: (e) -> e.preventDefault() @setState navActive: !@state.navActive render: -> getComponent = (componentPath) => Component = @props.getComponent componentPath (obj) => Component _.extend {}, @props, obj url = @props.currentUrl #window.location.pathname wrapperClasses = [ 'wrapper' 'row-offcanvas' 'row-offcanvas-left' 'relative' ] if @state.navActive wrapperClasses.push 'active' Header = getComponent @props.globals.public.headerComponent Nav = getComponent @props.globals.public.navComponent Content = getComponent @props.contentComponent LoadingComponent = getComponent @props.globals.public.loadingComponent DOM.div className: 'dashboard-container fixed skin-black' , Header toggleNav: @toggleNav DOM.div className: wrapperClasses.join ' ' , DOM.div className: 'nav-container' , Nav() DOM.aside className: 'right-side' , _.map (@props.globals.public.layout?.preContent ? []), (componentPath, key) => Component = getComponent componentPath Component _.extend {}, @props, @state, key: "layout-precontent-#{key}" Content key: @props.currentUrl
181165
_ = require 'lodash' React = require 'react' {DOM} = React module.exports = React.createFactory React.createClass getInitialState: -> navActive: false componentWillReceiveProps: (newProps) -> if newProps.currentUrl != @props.currentUrl @setState navActive: false toggleNav: (e) -> e.preventDefault() @setState navActive: !@state.navActive render: -> getComponent = (componentPath) => Component = @props.getComponent componentPath (obj) => Component _.extend {}, @props, obj url = @props.currentUrl #window.location.pathname wrapperClasses = [ 'wrapper' 'row-offcanvas' 'row-offcanvas-left' 'relative' ] if @state.navActive wrapperClasses.push 'active' Header = getComponent @props.globals.public.headerComponent Nav = getComponent @props.globals.public.navComponent Content = getComponent @props.contentComponent LoadingComponent = getComponent @props.globals.public.loadingComponent DOM.div className: 'dashboard-container fixed skin-black' , Header toggleNav: @toggleNav DOM.div className: wrapperClasses.join ' ' , DOM.div className: 'nav-container' , Nav() DOM.aside className: 'right-side' , _.map (@props.globals.public.layout?.preContent ? []), (componentPath, key) => Component = getComponent componentPath Component _.extend {}, @props, @state, key: "<KEY>}" Content key: @props.<KEY>
true
_ = require 'lodash' React = require 'react' {DOM} = React module.exports = React.createFactory React.createClass getInitialState: -> navActive: false componentWillReceiveProps: (newProps) -> if newProps.currentUrl != @props.currentUrl @setState navActive: false toggleNav: (e) -> e.preventDefault() @setState navActive: !@state.navActive render: -> getComponent = (componentPath) => Component = @props.getComponent componentPath (obj) => Component _.extend {}, @props, obj url = @props.currentUrl #window.location.pathname wrapperClasses = [ 'wrapper' 'row-offcanvas' 'row-offcanvas-left' 'relative' ] if @state.navActive wrapperClasses.push 'active' Header = getComponent @props.globals.public.headerComponent Nav = getComponent @props.globals.public.navComponent Content = getComponent @props.contentComponent LoadingComponent = getComponent @props.globals.public.loadingComponent DOM.div className: 'dashboard-container fixed skin-black' , Header toggleNav: @toggleNav DOM.div className: wrapperClasses.join ' ' , DOM.div className: 'nav-container' , Nav() DOM.aside className: 'right-side' , _.map (@props.globals.public.layout?.preContent ? []), (componentPath, key) => Component = getComponent componentPath Component _.extend {}, @props, @state, key: "PI:KEY:<KEY>END_PI}" Content key: @props.PI:KEY:<KEY>END_PI
[ { "context": "l', ->\n div '.wave-participant-name', h(@name)\n div '.wave-participant-email', h(@em", "end": 475, "score": 0.9990376830101013, "start": 470, "tag": "USERNAME", "value": "@name" }, { "context": "name)\n div '.wave-participant-email', h...
src/client/popup/user_popup/template.coffee
LaPingvino/rizzoma
88
ck = window.CoffeeKup BrowserSupport = require('../../utils/browser_support') {getOtherUrl} = require('../../utils/url') userComnonPopupTmpl = -> div '.js-user-popup-menu-top-block.user-popup-menu-top-block', '' userTopPopupTmpl = -> div -> div '.wave-participant-avatar.avatar', {style:"background-image: url(#{h(@fixedAvatar || @avatar)})"}, h(@initials)# -> div '.wave-participant-name-email', -> div '.wave-participant-name', h(@name) div '.wave-participant-email', h(@email) if @skypeId skypeId = h(@skypeId) a '.skype-call-link', {href: "skype:#{skypeId}?call", title: "Call Skype", target: 'skype-call-iframe'}, -> text skypeId # the icon is from Font Awesome by Dave Gandy - http://fontawesome.io img '.skype-status-ico', {src: "/s/img/skype/skype.black.svg"} div '.js-user-popup-menu-remove-block.user-popup-menu-remove-block', '' div '.clearer', '' exports.renderUserComnonPopup = ck.compile(userComnonPopupTmpl) renderUserTopPopup = ck.compile(userTopPopupTmpl) if BrowserSupport.isMozilla() # В firefox, начиная с 19-й версии есть баг: если одна и та же картинка на странице приводится к разным размера # background-size'ом, то firefox потребляет очень много процессорного времени. Изменим url картинки так, чтобы # адрес был разным, но картинка - той же orgRenderUserTopPopup = renderUserTopPopup renderUserTopPopup = (params={}) -> params.fixedAvatar = getOtherUrl(params.avatar) orgRenderUserTopPopup(params) exports.renderUserTopPopup = renderUserTopPopup
141550
ck = window.CoffeeKup BrowserSupport = require('../../utils/browser_support') {getOtherUrl} = require('../../utils/url') userComnonPopupTmpl = -> div '.js-user-popup-menu-top-block.user-popup-menu-top-block', '' userTopPopupTmpl = -> div -> div '.wave-participant-avatar.avatar', {style:"background-image: url(#{h(@fixedAvatar || @avatar)})"}, h(@initials)# -> div '.wave-participant-name-email', -> div '.wave-participant-name', h(@name) div '.wave-participant-email', h(@email) if @skypeId skypeId = h(@skypeId) a '.skype-call-link', {href: "skype:#{skypeId}?call", title: "Call Skype", target: 'skype-call-iframe'}, -> text skypeId # the icon is from Font Awesome by <NAME> - http://fontawesome.io img '.skype-status-ico', {src: "/s/img/skype/skype.black.svg"} div '.js-user-popup-menu-remove-block.user-popup-menu-remove-block', '' div '.clearer', '' exports.renderUserComnonPopup = ck.compile(userComnonPopupTmpl) renderUserTopPopup = ck.compile(userTopPopupTmpl) if BrowserSupport.isMozilla() # В firefox, начиная с 19-й версии есть баг: если одна и та же картинка на странице приводится к разным размера # background-size'ом, то firefox потребляет очень много процессорного времени. Изменим url картинки так, чтобы # адрес был разным, но картинка - той же orgRenderUserTopPopup = renderUserTopPopup renderUserTopPopup = (params={}) -> params.fixedAvatar = getOtherUrl(params.avatar) orgRenderUserTopPopup(params) exports.renderUserTopPopup = renderUserTopPopup
true
ck = window.CoffeeKup BrowserSupport = require('../../utils/browser_support') {getOtherUrl} = require('../../utils/url') userComnonPopupTmpl = -> div '.js-user-popup-menu-top-block.user-popup-menu-top-block', '' userTopPopupTmpl = -> div -> div '.wave-participant-avatar.avatar', {style:"background-image: url(#{h(@fixedAvatar || @avatar)})"}, h(@initials)# -> div '.wave-participant-name-email', -> div '.wave-participant-name', h(@name) div '.wave-participant-email', h(@email) if @skypeId skypeId = h(@skypeId) a '.skype-call-link', {href: "skype:#{skypeId}?call", title: "Call Skype", target: 'skype-call-iframe'}, -> text skypeId # the icon is from Font Awesome by PI:NAME:<NAME>END_PI - http://fontawesome.io img '.skype-status-ico', {src: "/s/img/skype/skype.black.svg"} div '.js-user-popup-menu-remove-block.user-popup-menu-remove-block', '' div '.clearer', '' exports.renderUserComnonPopup = ck.compile(userComnonPopupTmpl) renderUserTopPopup = ck.compile(userTopPopupTmpl) if BrowserSupport.isMozilla() # В firefox, начиная с 19-й версии есть баг: если одна и та же картинка на странице приводится к разным размера # background-size'ом, то firefox потребляет очень много процессорного времени. Изменим url картинки так, чтобы # адрес был разным, но картинка - той же orgRenderUserTopPopup = renderUserTopPopup renderUserTopPopup = (params={}) -> params.fixedAvatar = getOtherUrl(params.avatar) orgRenderUserTopPopup(params) exports.renderUserTopPopup = renderUserTopPopup
[ { "context": ": 'linode01'\n ip: '1.2.3.4'\n user: 'root'\n ssh_key: 'overcast.key'\n ssh_port", "end": 255, "score": 0.9863992929458618, "start": 251, "tag": "USERNAME", "value": "root" }, { "context": " 'notlinode'\n ip: '2.3.4.5'\n user: '...
test/unit/linode.spec.coffee
skmezanul/overcast
238
cli = require('../../modules/cli') utils = require('../../modules/utils') api = require('../../modules/providers/linode') MOCK_CLUSTERS = { default: { instances: { linode01: { name: 'linode01' ip: '1.2.3.4' user: 'root' ssh_key: 'overcast.key' ssh_port: 22 linode: { id: 1234567 name: 'linode01' distribution: 'Ubuntu' status: 1 datacenter_id: 3 disk: 49152 ram: 2048 ip: '1.2.3.4' } } notlinode: { name: 'notlinode' ip: '2.3.4.5' user: 'root' ssh_key: 'overcast.key' ssh_port: 22 } } } } describe 'linode', -> beforeEach -> spyOn(utils, 'getClusters').andReturn(MOCK_CLUSTERS) spyOn(utils, 'die') spyOn(utils, 'red') spyOn(utils, 'grey') spyOn(utils, 'success') spyOn(utils, 'dieWithList') spyOn(utils, 'waitForBoot') spyOn(cli, 'missingArgument') describe 'boot', -> it 'should fail if instance is missing', -> cli.execute('linode boot') expect(cli.missingArgument).toHaveBeenCalled() it 'should fail if instance does not exist', -> cli.execute('linode boot missing') expect(utils.dieWithList).toHaveBeenCalled() it 'should fail if instance is not an Linode instance', -> cli.execute('linode boot notlinode') expect(utils.die).toHaveBeenCalled() it 'should otherwise boot the instance', -> spyOn(api, 'boot').andCallFake (instance, callback) -> callback() cli.execute('linode boot linode01') expect(utils.success).toHaveBeenCalledWith('Instance "linode01" booted.') describe 'create', -> it 'should fail if instance is missing', -> cli.execute('linode create') expect(cli.missingArgument).toHaveBeenCalled() it 'should fail if instance already exists', -> cli.execute('linode create linode01') expect(utils.die).toHaveBeenCalledWith('Instance "linode01" already exists.') describe 'valid inputs', -> beforeEach -> spyOn(api, 'create').andCallFake (args, callback) -> response = { name: 'linode02' ip: '2.3.4.5' user: 'root' ssh_key: 'overcast.key' ssh_port: 22 linode: { id: 1234567 name: 'linode02' distribution: 'Ubuntu' status: 1 datacenter_id: 3 disk: 49152 ram: 2048 ip: '2.3.4.5' } } callback(response) spyOn(utils, 'saveInstanceToCluster') it 'should handle defaults', -> cli.execute('linode create linode02') expect(utils.grey).toHaveBeenCalledWith('Creating new instance "linode02" on Linode...') expect(utils.success).toHaveBeenCalledWith('Instance "linode02" (2.3.4.5) saved.') describe 'destroy', -> it 'should fail if instance is missing', -> cli.execute('linode destroy') expect(cli.missingArgument).toHaveBeenCalled() it 'should fail if instance does not exist', -> cli.execute('linode destroy missing') expect(utils.dieWithList).toHaveBeenCalled() it 'should fail if instance is not an Linode instance', -> cli.execute('linode destroy notlinode --force') expect(utils.die).toHaveBeenCalled() it 'should otherwise destroy the instance', -> spyOn(api, 'destroy').andCallFake (instance, callback) -> callback() spyOn(utils, 'deleteInstance') cli.execute('linode destroy linode01 --force') expect(utils.success).toHaveBeenCalledWith('Instance "linode01" destroyed.') describe 'images', -> describe 'instances', -> describe 'kernels', -> describe 'reboot', -> it 'should fail if instance is missing', -> cli.execute('linode reboot') expect(cli.missingArgument).toHaveBeenCalled() it 'should fail if instance does not exist', -> cli.execute('linode reboot missing') expect(utils.dieWithList).toHaveBeenCalled() it 'should fail if instance is not an Linode instance', -> cli.execute('linode reboot notlinode') expect(utils.die).toHaveBeenCalled() it 'should otherwise reboot the instance', -> spyOn(api, 'reboot').andCallFake (instance, callback) -> callback() cli.execute('linode reboot linode01') expect(utils.success).toHaveBeenCalledWith('Instance "linode01" rebooted.') describe 'regions', -> describe 'resize', -> it 'should fail if instance is missing', -> cli.execute('linode resize') expect(cli.missingArgument).toHaveBeenCalled() it 'should fail if size is missing', -> cli.execute('linode resize linode01') expect(cli.missingArgument).toHaveBeenCalled() it 'should fail if instance does not exist', -> cli.execute('linode resize missing 4096 --skip-boot') expect(utils.dieWithList).toHaveBeenCalled() it 'should fail if instance is not an Linode instance', -> cli.execute('linode resize notlinode 4096 --skip-boot') expect(utils.die).toHaveBeenCalled() it 'should otherwise resize the instance', -> spyOn(api, 'resize').andCallFake (instance, size, callback) -> callback() spyOn(api, 'updateInstanceMetadata').andCallFake (instance, callback) -> callback() cli.execute('linode resize linode01 4096 --skip-boot') expect(utils.success).toHaveBeenCalledWith('Instance "linode01" resized.') describe 'shutdown', -> it 'should fail if instance is missing', -> cli.execute('linode shutdown') expect(cli.missingArgument).toHaveBeenCalled() it 'should fail if instance does not exist', -> cli.execute('linode shutdown missing') expect(utils.dieWithList).toHaveBeenCalled() it 'should fail if instance is not an Linode instance', -> cli.execute('linode shutdown notlinode') expect(utils.die).toHaveBeenCalled() it 'should otherwise shutdown the instance', -> spyOn(api, 'shutdown').andCallFake (instance, callback) -> callback() cli.execute('linode shutdown linode01') expect(utils.success).toHaveBeenCalledWith('Instance "linode01" has been shut down.') describe 'sizes', -> describe 'sync', -> it 'should fail if instance is missing', -> cli.execute('linode sync') expect(cli.missingArgument).toHaveBeenCalled() it 'should fail if instance does not exist', -> cli.execute('linode sync missing') expect(utils.dieWithList).toHaveBeenCalled() it 'should fail if instance is not an Linode instance', -> cli.execute('linode sync notlinode') expect(utils.die).toHaveBeenCalled() it 'should otherwise sync the instance metadata', -> spyOn(api, 'sync').andCallFake (instance, callback) -> callback() cli.execute('linode sync linode01') expect(utils.success).toHaveBeenCalledWith('Metadata for "linode01" updated.')
25557
cli = require('../../modules/cli') utils = require('../../modules/utils') api = require('../../modules/providers/linode') MOCK_CLUSTERS = { default: { instances: { linode01: { name: 'linode01' ip: '1.2.3.4' user: 'root' ssh_key: 'overcast.key' ssh_port: 22 linode: { id: 1234567 name: 'linode01' distribution: 'Ubuntu' status: 1 datacenter_id: 3 disk: 49152 ram: 2048 ip: '1.2.3.4' } } notlinode: { name: 'notlinode' ip: '2.3.4.5' user: 'root' ssh_key: 'overcast.key' ssh_port: 22 } } } } describe 'linode', -> beforeEach -> spyOn(utils, 'getClusters').andReturn(MOCK_CLUSTERS) spyOn(utils, 'die') spyOn(utils, 'red') spyOn(utils, 'grey') spyOn(utils, 'success') spyOn(utils, 'dieWithList') spyOn(utils, 'waitForBoot') spyOn(cli, 'missingArgument') describe 'boot', -> it 'should fail if instance is missing', -> cli.execute('linode boot') expect(cli.missingArgument).toHaveBeenCalled() it 'should fail if instance does not exist', -> cli.execute('linode boot missing') expect(utils.dieWithList).toHaveBeenCalled() it 'should fail if instance is not an Linode instance', -> cli.execute('linode boot notlinode') expect(utils.die).toHaveBeenCalled() it 'should otherwise boot the instance', -> spyOn(api, 'boot').andCallFake (instance, callback) -> callback() cli.execute('linode boot linode01') expect(utils.success).toHaveBeenCalledWith('Instance "linode01" booted.') describe 'create', -> it 'should fail if instance is missing', -> cli.execute('linode create') expect(cli.missingArgument).toHaveBeenCalled() it 'should fail if instance already exists', -> cli.execute('linode create linode01') expect(utils.die).toHaveBeenCalledWith('Instance "linode01" already exists.') describe 'valid inputs', -> beforeEach -> spyOn(api, 'create').andCallFake (args, callback) -> response = { name: 'linode02' ip: '2.3.4.5' user: 'root' ssh_key: '<KEY>' ssh_port: 22 linode: { id: 1234567 name: 'linode02' distribution: 'Ubuntu' status: 1 datacenter_id: 3 disk: 49152 ram: 2048 ip: '2.3.4.5' } } callback(response) spyOn(utils, 'saveInstanceToCluster') it 'should handle defaults', -> cli.execute('linode create linode02') expect(utils.grey).toHaveBeenCalledWith('Creating new instance "linode02" on Linode...') expect(utils.success).toHaveBeenCalledWith('Instance "linode02" (2.3.4.5) saved.') describe 'destroy', -> it 'should fail if instance is missing', -> cli.execute('linode destroy') expect(cli.missingArgument).toHaveBeenCalled() it 'should fail if instance does not exist', -> cli.execute('linode destroy missing') expect(utils.dieWithList).toHaveBeenCalled() it 'should fail if instance is not an Linode instance', -> cli.execute('linode destroy notlinode --force') expect(utils.die).toHaveBeenCalled() it 'should otherwise destroy the instance', -> spyOn(api, 'destroy').andCallFake (instance, callback) -> callback() spyOn(utils, 'deleteInstance') cli.execute('linode destroy linode01 --force') expect(utils.success).toHaveBeenCalledWith('Instance "linode01" destroyed.') describe 'images', -> describe 'instances', -> describe 'kernels', -> describe 'reboot', -> it 'should fail if instance is missing', -> cli.execute('linode reboot') expect(cli.missingArgument).toHaveBeenCalled() it 'should fail if instance does not exist', -> cli.execute('linode reboot missing') expect(utils.dieWithList).toHaveBeenCalled() it 'should fail if instance is not an Linode instance', -> cli.execute('linode reboot notlinode') expect(utils.die).toHaveBeenCalled() it 'should otherwise reboot the instance', -> spyOn(api, 'reboot').andCallFake (instance, callback) -> callback() cli.execute('linode reboot linode01') expect(utils.success).toHaveBeenCalledWith('Instance "linode01" rebooted.') describe 'regions', -> describe 'resize', -> it 'should fail if instance is missing', -> cli.execute('linode resize') expect(cli.missingArgument).toHaveBeenCalled() it 'should fail if size is missing', -> cli.execute('linode resize linode01') expect(cli.missingArgument).toHaveBeenCalled() it 'should fail if instance does not exist', -> cli.execute('linode resize missing 4096 --skip-boot') expect(utils.dieWithList).toHaveBeenCalled() it 'should fail if instance is not an Linode instance', -> cli.execute('linode resize notlinode 4096 --skip-boot') expect(utils.die).toHaveBeenCalled() it 'should otherwise resize the instance', -> spyOn(api, 'resize').andCallFake (instance, size, callback) -> callback() spyOn(api, 'updateInstanceMetadata').andCallFake (instance, callback) -> callback() cli.execute('linode resize linode01 4096 --skip-boot') expect(utils.success).toHaveBeenCalledWith('Instance "linode01" resized.') describe 'shutdown', -> it 'should fail if instance is missing', -> cli.execute('linode shutdown') expect(cli.missingArgument).toHaveBeenCalled() it 'should fail if instance does not exist', -> cli.execute('linode shutdown missing') expect(utils.dieWithList).toHaveBeenCalled() it 'should fail if instance is not an Linode instance', -> cli.execute('linode shutdown notlinode') expect(utils.die).toHaveBeenCalled() it 'should otherwise shutdown the instance', -> spyOn(api, 'shutdown').andCallFake (instance, callback) -> callback() cli.execute('linode shutdown linode01') expect(utils.success).toHaveBeenCalledWith('Instance "linode01" has been shut down.') describe 'sizes', -> describe 'sync', -> it 'should fail if instance is missing', -> cli.execute('linode sync') expect(cli.missingArgument).toHaveBeenCalled() it 'should fail if instance does not exist', -> cli.execute('linode sync missing') expect(utils.dieWithList).toHaveBeenCalled() it 'should fail if instance is not an Linode instance', -> cli.execute('linode sync notlinode') expect(utils.die).toHaveBeenCalled() it 'should otherwise sync the instance metadata', -> spyOn(api, 'sync').andCallFake (instance, callback) -> callback() cli.execute('linode sync linode01') expect(utils.success).toHaveBeenCalledWith('Metadata for "linode01" updated.')
true
cli = require('../../modules/cli') utils = require('../../modules/utils') api = require('../../modules/providers/linode') MOCK_CLUSTERS = { default: { instances: { linode01: { name: 'linode01' ip: '1.2.3.4' user: 'root' ssh_key: 'overcast.key' ssh_port: 22 linode: { id: 1234567 name: 'linode01' distribution: 'Ubuntu' status: 1 datacenter_id: 3 disk: 49152 ram: 2048 ip: '1.2.3.4' } } notlinode: { name: 'notlinode' ip: '2.3.4.5' user: 'root' ssh_key: 'overcast.key' ssh_port: 22 } } } } describe 'linode', -> beforeEach -> spyOn(utils, 'getClusters').andReturn(MOCK_CLUSTERS) spyOn(utils, 'die') spyOn(utils, 'red') spyOn(utils, 'grey') spyOn(utils, 'success') spyOn(utils, 'dieWithList') spyOn(utils, 'waitForBoot') spyOn(cli, 'missingArgument') describe 'boot', -> it 'should fail if instance is missing', -> cli.execute('linode boot') expect(cli.missingArgument).toHaveBeenCalled() it 'should fail if instance does not exist', -> cli.execute('linode boot missing') expect(utils.dieWithList).toHaveBeenCalled() it 'should fail if instance is not an Linode instance', -> cli.execute('linode boot notlinode') expect(utils.die).toHaveBeenCalled() it 'should otherwise boot the instance', -> spyOn(api, 'boot').andCallFake (instance, callback) -> callback() cli.execute('linode boot linode01') expect(utils.success).toHaveBeenCalledWith('Instance "linode01" booted.') describe 'create', -> it 'should fail if instance is missing', -> cli.execute('linode create') expect(cli.missingArgument).toHaveBeenCalled() it 'should fail if instance already exists', -> cli.execute('linode create linode01') expect(utils.die).toHaveBeenCalledWith('Instance "linode01" already exists.') describe 'valid inputs', -> beforeEach -> spyOn(api, 'create').andCallFake (args, callback) -> response = { name: 'linode02' ip: '2.3.4.5' user: 'root' ssh_key: 'PI:KEY:<KEY>END_PI' ssh_port: 22 linode: { id: 1234567 name: 'linode02' distribution: 'Ubuntu' status: 1 datacenter_id: 3 disk: 49152 ram: 2048 ip: '2.3.4.5' } } callback(response) spyOn(utils, 'saveInstanceToCluster') it 'should handle defaults', -> cli.execute('linode create linode02') expect(utils.grey).toHaveBeenCalledWith('Creating new instance "linode02" on Linode...') expect(utils.success).toHaveBeenCalledWith('Instance "linode02" (2.3.4.5) saved.') describe 'destroy', -> it 'should fail if instance is missing', -> cli.execute('linode destroy') expect(cli.missingArgument).toHaveBeenCalled() it 'should fail if instance does not exist', -> cli.execute('linode destroy missing') expect(utils.dieWithList).toHaveBeenCalled() it 'should fail if instance is not an Linode instance', -> cli.execute('linode destroy notlinode --force') expect(utils.die).toHaveBeenCalled() it 'should otherwise destroy the instance', -> spyOn(api, 'destroy').andCallFake (instance, callback) -> callback() spyOn(utils, 'deleteInstance') cli.execute('linode destroy linode01 --force') expect(utils.success).toHaveBeenCalledWith('Instance "linode01" destroyed.') describe 'images', -> describe 'instances', -> describe 'kernels', -> describe 'reboot', -> it 'should fail if instance is missing', -> cli.execute('linode reboot') expect(cli.missingArgument).toHaveBeenCalled() it 'should fail if instance does not exist', -> cli.execute('linode reboot missing') expect(utils.dieWithList).toHaveBeenCalled() it 'should fail if instance is not an Linode instance', -> cli.execute('linode reboot notlinode') expect(utils.die).toHaveBeenCalled() it 'should otherwise reboot the instance', -> spyOn(api, 'reboot').andCallFake (instance, callback) -> callback() cli.execute('linode reboot linode01') expect(utils.success).toHaveBeenCalledWith('Instance "linode01" rebooted.') describe 'regions', -> describe 'resize', -> it 'should fail if instance is missing', -> cli.execute('linode resize') expect(cli.missingArgument).toHaveBeenCalled() it 'should fail if size is missing', -> cli.execute('linode resize linode01') expect(cli.missingArgument).toHaveBeenCalled() it 'should fail if instance does not exist', -> cli.execute('linode resize missing 4096 --skip-boot') expect(utils.dieWithList).toHaveBeenCalled() it 'should fail if instance is not an Linode instance', -> cli.execute('linode resize notlinode 4096 --skip-boot') expect(utils.die).toHaveBeenCalled() it 'should otherwise resize the instance', -> spyOn(api, 'resize').andCallFake (instance, size, callback) -> callback() spyOn(api, 'updateInstanceMetadata').andCallFake (instance, callback) -> callback() cli.execute('linode resize linode01 4096 --skip-boot') expect(utils.success).toHaveBeenCalledWith('Instance "linode01" resized.') describe 'shutdown', -> it 'should fail if instance is missing', -> cli.execute('linode shutdown') expect(cli.missingArgument).toHaveBeenCalled() it 'should fail if instance does not exist', -> cli.execute('linode shutdown missing') expect(utils.dieWithList).toHaveBeenCalled() it 'should fail if instance is not an Linode instance', -> cli.execute('linode shutdown notlinode') expect(utils.die).toHaveBeenCalled() it 'should otherwise shutdown the instance', -> spyOn(api, 'shutdown').andCallFake (instance, callback) -> callback() cli.execute('linode shutdown linode01') expect(utils.success).toHaveBeenCalledWith('Instance "linode01" has been shut down.') describe 'sizes', -> describe 'sync', -> it 'should fail if instance is missing', -> cli.execute('linode sync') expect(cli.missingArgument).toHaveBeenCalled() it 'should fail if instance does not exist', -> cli.execute('linode sync missing') expect(utils.dieWithList).toHaveBeenCalled() it 'should fail if instance is not an Linode instance', -> cli.execute('linode sync notlinode') expect(utils.die).toHaveBeenCalled() it 'should otherwise sync the instance metadata', -> spyOn(api, 'sync').andCallFake (instance, callback) -> callback() cli.execute('linode sync linode01') expect(utils.success).toHaveBeenCalledWith('Metadata for "linode01" updated.')
[ { "context": "(weight, size, box, viewBox, translate) ->\n key = \"#{weight}-#{size}\"\n\n gulp.task key, ['sketch'], ->\n gulp\n .", "end": 2225, "score": 0.9949328303337097, "start": 2206, "tag": "KEY", "value": "\"#{weight}-#{size}\"" } ]
gulpfile.coffee
trello/iconathon
260
gulp = require 'gulp' gutil = require 'gulp-util' rename = require 'gulp-rename' sketch = require 'gulp-sketch' svgmin = require 'gulp-svgmin' cheerio = require 'gulp-cheerio' convert = require 'gulp-rsvg' iconfont = require 'gulp-iconfont' shell = require 'gulp-shell' consolidate = require 'gulp-consolidate' jsoneditor = require 'gulp-json-editor' jsonminify = require 'gulp-jsonminify' less = require 'gulp-less' LessPluginAutoPrefix = require 'less-plugin-autoprefix' minifyCSS = require 'gulp-minify-css' minifyHTML = require 'gulp-minify-html' fs = require 'fs' path = require 'path' _ = require 'lodash' # https://github.com/svg/svgo/tree/master/plugins # We use these plugins for all our svg optimizing. svgoPluginOpts = [ { removeViewBox: false } { removeDesc: true } { removeTitle: true } { removeRasterImages: true } { cleanupNumericValues: false } ] # This is the distance between the edge of the glyph and the edge of the file. # For instance, for 16pt18box, the glyph will be 16x16 points, and have a # 1 point margin on all sides. # If you want to add more sizes, you can follow the same format, but be sure to # add to the tasks at the bottom. sizes = { '16pt18box': { size: 16, box: 18 } '20pt24box': { size: 20, box: 24 } '30pt32box': { size: 30, box: 32 } } # This is the thickness of the line in the icon. weights = [ '100' '500' ] getUnits = (size, box) -> # Hard dependancy on 1920 x 1920 SVGs… boxDelta = box - size boundingUnits = ((1920 / size) * boxDelta) viewBoxValue = 1920 + boundingUnits viewBox = "0 0 #{viewBoxValue} #{viewBoxValue}" translateDiff = boundingUnits / 2 translate = "translate(#{translateDiff} #{translateDiff})" # Points don't make sense for web screens, but these outputs are primarily # for android. box = "#{box}pt" return { box, viewBox, translate } # Export from Sketch. This will export all the weights, so long as they are # artboards. gulp.task 'sketch', -> gulp .src ['./src/sketch/*.sketch'] .pipe sketch export: 'artboards' formats: 'svg' .pipe gulp.dest './build/exports/' # Tasks for individual sizes. gulpSizeTask = (weight, size, box, viewBox, translate) -> key = "#{weight}-#{size}" gulp.task key, ['sketch'], -> gulp .src ["./build/exports/#{weight}/*.svg"] .pipe cheerio({ run: ($, file, done) -> $('svg') .attr({ 'height': box, 'width': box }) .attr({ 'viewBox': viewBox }) $('svg > g').attr({ 'transform': translate }) done() # SVG is XML so this turns out to be pretty important. # The output is mangled without it. parserOptions: { xmlMode: true } }) .pipe svgmin plugins: svgoPluginOpts .pipe rename prefix: 'ic_' suffix: "_#{weight}_#{size}" # Sure, you could use these SVGs for any platform, but we have Android in # mind here. .pipe gulp.dest("./build/weights/#{weight}/#{size}/android") # iOS uses PDFs. .pipe cheerio({ # For iOS PDFs, use a pixel value. It will get converted to pixels # anyway. run: ($, file, done) -> pxBox = box.replace("pt", "px") $('svg') .attr({ 'height': pxBox, 'width': pxBox }) done() parserOptions: { xmlMode: true } }) .pipe convert({format: 'pdf'}) .pipe gulp.dest("./build/weights/#{weight}/#{size}/ios") # For each weight, export for various sizes. for weight in weights do (weight) -> paths = { sketchFiles: ["./src/sketch/#{weight}/*.sketch"] exportSvgs: ["./build/exports/#{weight}/*.svg"] } # Now, the various sizes… for size, value of sizes # getUnits does all the math for the defined size and bounding box, then # adds a gulp task for each. units = getUnits(value.size, value.box) gulpSizeTask(weight, size, units.box, units.viewBox, units.translate) # We also want the full SVGs without modified height, width, or margin. gulp.task "#{weight}-full", ["sketch"], -> gulp .src paths.exportSvgs .pipe svgmin plugins: svgoPluginOpts .pipe gulp.dest("./build/weights/#{weight}/full/") # Build the icon font. We mainly use this for rudimentary testing and use # Icomoon for production. gulp.task "#{weight}-font", ["sketch"], -> gulp .src paths.exportSvgs .pipe svgmin plugins: svgoPluginOpts .pipe iconfont fontName: "trellicons-#{weight}" fixedWidth: true centerHorizontally: true .on 'codepoints', (codepoints, options) -> # Outputs a CSS file with the right characters. templateData = { glyphs: codepoints className: 'icon' weight: weight fontName: options.fontName } gulp .src './src/demo/templates/icon-css-points.tmpl' .pipe consolidate 'lodash', templateData .pipe rename 'icon-points.less' .pipe gulp.dest "./build/weights/#{weight}/fonts" .pipe gulp.dest "./build/weights/#{weight}/fonts" gulp.task 'demo', ['500-font'], -> # we need the font task to be finished before building the CSS. autoprefix = new LessPluginAutoPrefix browsers: [ "last 3 Chrome versions", "last 3 Firefox versions" ] # Styles gulp .src './src/demo/styles/entry/app.less', base: path.join(__dirname, '/src/demo/styles/') .pipe less paths: [ path.join(__dirname, '/src/demo/styles/'), './build/' ] plugins: [ autoprefix ] .on 'error', (err) -> gutil.log(err) this.emit('end') .pipe rename 'app.css' .pipe gulp.dest './build/demo/' .pipe minifyCSS() .pipe rename 'app.min.css' .pipe gulp.dest './build/demo/' # HTML gulp .src './src/demo/templates/demo.html' .pipe minifyHTML() .pipe gulp.dest './build/demo/' # Read the Sketch file names to get data for the demo. fs.readdir "./src/sketch/", (err, files) -> # Get the icon names. iconNames = [] for icon in files iconNames.push icon.replace(/\.[^/.]+$/, "") iconNames = _.compact iconNames # Get the sizes. sizeData = [] for key, value of sizes sizeData.push key gulp .src "./src/demo/templates/data.json" .pipe jsoneditor icons: iconNames sizes: sizeData weights: weights .pipe jsonminify() .pipe gulp.dest './build/demo' gulp.task 'watch', -> gulp.watch './src/demo/**/*', ['demo'] gulp.watch './src/sketch/**/*.sketch', [ '100-16pt18box', '100-20pt24box', '100-30pt32box', '100-full', '100-font', '500-16pt18box', '500-20pt24box', '500-30pt32box', '500-full', '500-font', 'demo' ] gulp.task 'default', [ 'watch', '100-16pt18box', '100-20pt24box', '100-30pt32box', '100-full', '100-font', '500-16pt18box', '500-20pt24box', '500-30pt32box', '500-full', '500-font', 'demo' ]
103124
gulp = require 'gulp' gutil = require 'gulp-util' rename = require 'gulp-rename' sketch = require 'gulp-sketch' svgmin = require 'gulp-svgmin' cheerio = require 'gulp-cheerio' convert = require 'gulp-rsvg' iconfont = require 'gulp-iconfont' shell = require 'gulp-shell' consolidate = require 'gulp-consolidate' jsoneditor = require 'gulp-json-editor' jsonminify = require 'gulp-jsonminify' less = require 'gulp-less' LessPluginAutoPrefix = require 'less-plugin-autoprefix' minifyCSS = require 'gulp-minify-css' minifyHTML = require 'gulp-minify-html' fs = require 'fs' path = require 'path' _ = require 'lodash' # https://github.com/svg/svgo/tree/master/plugins # We use these plugins for all our svg optimizing. svgoPluginOpts = [ { removeViewBox: false } { removeDesc: true } { removeTitle: true } { removeRasterImages: true } { cleanupNumericValues: false } ] # This is the distance between the edge of the glyph and the edge of the file. # For instance, for 16pt18box, the glyph will be 16x16 points, and have a # 1 point margin on all sides. # If you want to add more sizes, you can follow the same format, but be sure to # add to the tasks at the bottom. sizes = { '16pt18box': { size: 16, box: 18 } '20pt24box': { size: 20, box: 24 } '30pt32box': { size: 30, box: 32 } } # This is the thickness of the line in the icon. weights = [ '100' '500' ] getUnits = (size, box) -> # Hard dependancy on 1920 x 1920 SVGs… boxDelta = box - size boundingUnits = ((1920 / size) * boxDelta) viewBoxValue = 1920 + boundingUnits viewBox = "0 0 #{viewBoxValue} #{viewBoxValue}" translateDiff = boundingUnits / 2 translate = "translate(#{translateDiff} #{translateDiff})" # Points don't make sense for web screens, but these outputs are primarily # for android. box = "#{box}pt" return { box, viewBox, translate } # Export from Sketch. This will export all the weights, so long as they are # artboards. gulp.task 'sketch', -> gulp .src ['./src/sketch/*.sketch'] .pipe sketch export: 'artboards' formats: 'svg' .pipe gulp.dest './build/exports/' # Tasks for individual sizes. gulpSizeTask = (weight, size, box, viewBox, translate) -> key = <KEY> gulp.task key, ['sketch'], -> gulp .src ["./build/exports/#{weight}/*.svg"] .pipe cheerio({ run: ($, file, done) -> $('svg') .attr({ 'height': box, 'width': box }) .attr({ 'viewBox': viewBox }) $('svg > g').attr({ 'transform': translate }) done() # SVG is XML so this turns out to be pretty important. # The output is mangled without it. parserOptions: { xmlMode: true } }) .pipe svgmin plugins: svgoPluginOpts .pipe rename prefix: 'ic_' suffix: "_#{weight}_#{size}" # Sure, you could use these SVGs for any platform, but we have Android in # mind here. .pipe gulp.dest("./build/weights/#{weight}/#{size}/android") # iOS uses PDFs. .pipe cheerio({ # For iOS PDFs, use a pixel value. It will get converted to pixels # anyway. run: ($, file, done) -> pxBox = box.replace("pt", "px") $('svg') .attr({ 'height': pxBox, 'width': pxBox }) done() parserOptions: { xmlMode: true } }) .pipe convert({format: 'pdf'}) .pipe gulp.dest("./build/weights/#{weight}/#{size}/ios") # For each weight, export for various sizes. for weight in weights do (weight) -> paths = { sketchFiles: ["./src/sketch/#{weight}/*.sketch"] exportSvgs: ["./build/exports/#{weight}/*.svg"] } # Now, the various sizes… for size, value of sizes # getUnits does all the math for the defined size and bounding box, then # adds a gulp task for each. units = getUnits(value.size, value.box) gulpSizeTask(weight, size, units.box, units.viewBox, units.translate) # We also want the full SVGs without modified height, width, or margin. gulp.task "#{weight}-full", ["sketch"], -> gulp .src paths.exportSvgs .pipe svgmin plugins: svgoPluginOpts .pipe gulp.dest("./build/weights/#{weight}/full/") # Build the icon font. We mainly use this for rudimentary testing and use # Icomoon for production. gulp.task "#{weight}-font", ["sketch"], -> gulp .src paths.exportSvgs .pipe svgmin plugins: svgoPluginOpts .pipe iconfont fontName: "trellicons-#{weight}" fixedWidth: true centerHorizontally: true .on 'codepoints', (codepoints, options) -> # Outputs a CSS file with the right characters. templateData = { glyphs: codepoints className: 'icon' weight: weight fontName: options.fontName } gulp .src './src/demo/templates/icon-css-points.tmpl' .pipe consolidate 'lodash', templateData .pipe rename 'icon-points.less' .pipe gulp.dest "./build/weights/#{weight}/fonts" .pipe gulp.dest "./build/weights/#{weight}/fonts" gulp.task 'demo', ['500-font'], -> # we need the font task to be finished before building the CSS. autoprefix = new LessPluginAutoPrefix browsers: [ "last 3 Chrome versions", "last 3 Firefox versions" ] # Styles gulp .src './src/demo/styles/entry/app.less', base: path.join(__dirname, '/src/demo/styles/') .pipe less paths: [ path.join(__dirname, '/src/demo/styles/'), './build/' ] plugins: [ autoprefix ] .on 'error', (err) -> gutil.log(err) this.emit('end') .pipe rename 'app.css' .pipe gulp.dest './build/demo/' .pipe minifyCSS() .pipe rename 'app.min.css' .pipe gulp.dest './build/demo/' # HTML gulp .src './src/demo/templates/demo.html' .pipe minifyHTML() .pipe gulp.dest './build/demo/' # Read the Sketch file names to get data for the demo. fs.readdir "./src/sketch/", (err, files) -> # Get the icon names. iconNames = [] for icon in files iconNames.push icon.replace(/\.[^/.]+$/, "") iconNames = _.compact iconNames # Get the sizes. sizeData = [] for key, value of sizes sizeData.push key gulp .src "./src/demo/templates/data.json" .pipe jsoneditor icons: iconNames sizes: sizeData weights: weights .pipe jsonminify() .pipe gulp.dest './build/demo' gulp.task 'watch', -> gulp.watch './src/demo/**/*', ['demo'] gulp.watch './src/sketch/**/*.sketch', [ '100-16pt18box', '100-20pt24box', '100-30pt32box', '100-full', '100-font', '500-16pt18box', '500-20pt24box', '500-30pt32box', '500-full', '500-font', 'demo' ] gulp.task 'default', [ 'watch', '100-16pt18box', '100-20pt24box', '100-30pt32box', '100-full', '100-font', '500-16pt18box', '500-20pt24box', '500-30pt32box', '500-full', '500-font', 'demo' ]
true
gulp = require 'gulp' gutil = require 'gulp-util' rename = require 'gulp-rename' sketch = require 'gulp-sketch' svgmin = require 'gulp-svgmin' cheerio = require 'gulp-cheerio' convert = require 'gulp-rsvg' iconfont = require 'gulp-iconfont' shell = require 'gulp-shell' consolidate = require 'gulp-consolidate' jsoneditor = require 'gulp-json-editor' jsonminify = require 'gulp-jsonminify' less = require 'gulp-less' LessPluginAutoPrefix = require 'less-plugin-autoprefix' minifyCSS = require 'gulp-minify-css' minifyHTML = require 'gulp-minify-html' fs = require 'fs' path = require 'path' _ = require 'lodash' # https://github.com/svg/svgo/tree/master/plugins # We use these plugins for all our svg optimizing. svgoPluginOpts = [ { removeViewBox: false } { removeDesc: true } { removeTitle: true } { removeRasterImages: true } { cleanupNumericValues: false } ] # This is the distance between the edge of the glyph and the edge of the file. # For instance, for 16pt18box, the glyph will be 16x16 points, and have a # 1 point margin on all sides. # If you want to add more sizes, you can follow the same format, but be sure to # add to the tasks at the bottom. sizes = { '16pt18box': { size: 16, box: 18 } '20pt24box': { size: 20, box: 24 } '30pt32box': { size: 30, box: 32 } } # This is the thickness of the line in the icon. weights = [ '100' '500' ] getUnits = (size, box) -> # Hard dependancy on 1920 x 1920 SVGs… boxDelta = box - size boundingUnits = ((1920 / size) * boxDelta) viewBoxValue = 1920 + boundingUnits viewBox = "0 0 #{viewBoxValue} #{viewBoxValue}" translateDiff = boundingUnits / 2 translate = "translate(#{translateDiff} #{translateDiff})" # Points don't make sense for web screens, but these outputs are primarily # for android. box = "#{box}pt" return { box, viewBox, translate } # Export from Sketch. This will export all the weights, so long as they are # artboards. gulp.task 'sketch', -> gulp .src ['./src/sketch/*.sketch'] .pipe sketch export: 'artboards' formats: 'svg' .pipe gulp.dest './build/exports/' # Tasks for individual sizes. gulpSizeTask = (weight, size, box, viewBox, translate) -> key = PI:KEY:<KEY>END_PI gulp.task key, ['sketch'], -> gulp .src ["./build/exports/#{weight}/*.svg"] .pipe cheerio({ run: ($, file, done) -> $('svg') .attr({ 'height': box, 'width': box }) .attr({ 'viewBox': viewBox }) $('svg > g').attr({ 'transform': translate }) done() # SVG is XML so this turns out to be pretty important. # The output is mangled without it. parserOptions: { xmlMode: true } }) .pipe svgmin plugins: svgoPluginOpts .pipe rename prefix: 'ic_' suffix: "_#{weight}_#{size}" # Sure, you could use these SVGs for any platform, but we have Android in # mind here. .pipe gulp.dest("./build/weights/#{weight}/#{size}/android") # iOS uses PDFs. .pipe cheerio({ # For iOS PDFs, use a pixel value. It will get converted to pixels # anyway. run: ($, file, done) -> pxBox = box.replace("pt", "px") $('svg') .attr({ 'height': pxBox, 'width': pxBox }) done() parserOptions: { xmlMode: true } }) .pipe convert({format: 'pdf'}) .pipe gulp.dest("./build/weights/#{weight}/#{size}/ios") # For each weight, export for various sizes. for weight in weights do (weight) -> paths = { sketchFiles: ["./src/sketch/#{weight}/*.sketch"] exportSvgs: ["./build/exports/#{weight}/*.svg"] } # Now, the various sizes… for size, value of sizes # getUnits does all the math for the defined size and bounding box, then # adds a gulp task for each. units = getUnits(value.size, value.box) gulpSizeTask(weight, size, units.box, units.viewBox, units.translate) # We also want the full SVGs without modified height, width, or margin. gulp.task "#{weight}-full", ["sketch"], -> gulp .src paths.exportSvgs .pipe svgmin plugins: svgoPluginOpts .pipe gulp.dest("./build/weights/#{weight}/full/") # Build the icon font. We mainly use this for rudimentary testing and use # Icomoon for production. gulp.task "#{weight}-font", ["sketch"], -> gulp .src paths.exportSvgs .pipe svgmin plugins: svgoPluginOpts .pipe iconfont fontName: "trellicons-#{weight}" fixedWidth: true centerHorizontally: true .on 'codepoints', (codepoints, options) -> # Outputs a CSS file with the right characters. templateData = { glyphs: codepoints className: 'icon' weight: weight fontName: options.fontName } gulp .src './src/demo/templates/icon-css-points.tmpl' .pipe consolidate 'lodash', templateData .pipe rename 'icon-points.less' .pipe gulp.dest "./build/weights/#{weight}/fonts" .pipe gulp.dest "./build/weights/#{weight}/fonts" gulp.task 'demo', ['500-font'], -> # we need the font task to be finished before building the CSS. autoprefix = new LessPluginAutoPrefix browsers: [ "last 3 Chrome versions", "last 3 Firefox versions" ] # Styles gulp .src './src/demo/styles/entry/app.less', base: path.join(__dirname, '/src/demo/styles/') .pipe less paths: [ path.join(__dirname, '/src/demo/styles/'), './build/' ] plugins: [ autoprefix ] .on 'error', (err) -> gutil.log(err) this.emit('end') .pipe rename 'app.css' .pipe gulp.dest './build/demo/' .pipe minifyCSS() .pipe rename 'app.min.css' .pipe gulp.dest './build/demo/' # HTML gulp .src './src/demo/templates/demo.html' .pipe minifyHTML() .pipe gulp.dest './build/demo/' # Read the Sketch file names to get data for the demo. fs.readdir "./src/sketch/", (err, files) -> # Get the icon names. iconNames = [] for icon in files iconNames.push icon.replace(/\.[^/.]+$/, "") iconNames = _.compact iconNames # Get the sizes. sizeData = [] for key, value of sizes sizeData.push key gulp .src "./src/demo/templates/data.json" .pipe jsoneditor icons: iconNames sizes: sizeData weights: weights .pipe jsonminify() .pipe gulp.dest './build/demo' gulp.task 'watch', -> gulp.watch './src/demo/**/*', ['demo'] gulp.watch './src/sketch/**/*.sketch', [ '100-16pt18box', '100-20pt24box', '100-30pt32box', '100-full', '100-font', '500-16pt18box', '500-20pt24box', '500-30pt32box', '500-full', '500-font', 'demo' ] gulp.task 'default', [ 'watch', '100-16pt18box', '100-20pt24box', '100-30pt32box', '100-full', '100-font', '500-16pt18box', '500-20pt24box', '500-30pt32box', '500-full', '500-font', 'demo' ]
[ { "context": "= ValidationModes.KEYCARD\n validationKey = (\"0#{char}\" for char in validationKey.split('')).join('') \n el", "end": 3412, "score": 0.8865558505058289, "start": 3399, "tag": "KEY", "value": "0#{char}\" for" }, { "context": "dationKey = (\"0#{char}\" for char i...
app/src/dongle/transaction.coffee
doged/ledger-wallet-doged-chrome
1
ValidationModes = PIN: 0x01 KEYCARD: 0x02 SECURE_SCREEN: 0x03 Errors = @ledger.errors Amount = ledger.Amount @ledger.dongle ?= {} ### @example Usage amount = ledger.Amount.fromBtc("1.234") fee = ledger.Amount.fromBtc("0.0001") recipientAddress = "1DR6p2UVfu1m6mCU8hyvh5r6ix3dJEPMX7" ledger.dongle.Transaction.createAndPrepareTransaction(amount, fees, recipientAddress, inputsAccounts, changeAccount).then (tx) => console.log("Prepared tx :", tx) ### class ledger.dongle.Transaction # @ValidationModes: ValidationModes # @DEFAULT_FEES: Amount.fromBtc(0.00005) # @property [ledger.Amount] amount: undefined # @property [ledger.Amount] fees: @DEFAULT_FEES # @property [String] recipientAddress: undefined # @property [Array<Object>] inputs: undefined # @property [String] changePath: undefined # @property [String] hash: undefined # @property [Boolean] _isValidated: no # @property [Object] _resumeData: undefined # @property [Integer] _validationMode: undefined # @property [Array<Object>] _btInputs: undefined # @property [Array<Object>] _btcAssociatedKeyPath: undefined # @property [Object] _transaction: undefined # @param [ledger.dongle.Dongle] dongle # @param [ledger.Amount] amount # @param [ledger.Amount] fees # @param [String] recipientAddress constructor: (@dongle, @amount, @fees, @recipientAddress) -> # @return [Boolean] isValidated: () -> @_isValidated # @return [String] getSignedTransaction: () -> @_transaction # @return [Integer] getValidationMode: () -> @_validationMode # @return [ledger.Amount] getAmount: () -> @amount # @return [String] getRecipientAddress: () -> @receiverAddress # @param [String] hash setHash: (hash) -> @hash = hash # @param [Array<Object>] inputs # @param [String] changePath # @param [Function] callback # @return [CompletionClosure] prepare: (@inputs, @changePath, callback=undefined) -> if not @amount? or not @fees? or not @recipientAddress? throw new ledger.StandardError('Transaction must me initialized before preparation') completion = new CompletionClosure(callback) try @_btInputs = [] @_btcAssociatedKeyPath = [] for input in inputs splitTransaction = @dongle.splitTransaction(input) @_btInputs.push [splitTransaction, input.output_index] @_btcAssociatedKeyPath.push input.paths[0] catch err completion.failure(new ledger.StandardError(Errors.UnknowError, err)) @dongle.createPaymentTransaction(@_btInputs, @_btcAssociatedKeyPath, @changePath, @recipientAddress, @amount, @fees) .then (@_resumeData) => @_validationMode = @_resumeData.authorizationRequired completion.success() .fail (error) => completion.failure(new ledger.StandardError(Errors.SignatureError)) .done() completion.readonly() # @param [String] validationKey 4 chars ASCII encoded # @param [Function] callback # @return [CompletionClosure] validate: (validationKey, callback=undefined) -> if not @_resumeData? or not @_validationMode? throw new ledger.StandardError('Transaction must me prepared before validation') completion = new CompletionClosure(callback) # Convert ASCII encoded validationKey to HEX encoded validationKey if @_validationMode == ValidationModes.KEYCARD validationKey = ("0#{char}" for char in validationKey.split('')).join('') else validationKey = (validationKey.charCodeAt(i).toString(16) for i in [0...validationKey.length]).join('') @dongle.createPaymentTransaction( @_btInputs, @_btcAssociatedKeyPath, @changePath, @recipientAddress, @amount, @fees, undefined, # Default lockTime undefined, # Default sigHash validationKey, resumeData ) .then (@_transaction) => @_isValidated = yes _.defer => completion.success() .fail (error) => _.defer => completion.failure(new ledger.StandardError(Errors.SignatureError, error)) .done() completion.readonly() # Retrieve information that need to be confirmed by the user. # @return [Object] # @option [Integer] validationMode # @option [Object, undefined] amount # @option [String] text # @option [Array<Integer>] indexes # @option [Object] recipientsAddress # @option [String] text # @option [Array<Integer>] indexes # @option [String] validationCharacters # @option [Boolean] needsAmountValidation getValidationDetails: -> details = validationMode: @_validationMode recipientsAddress: text: @recipientAddress indexes: @_resumeData.indexesKeyCard.match(/../g) validationCharacters: (@recipientAddress[index] for index in @_resumeData.indexesKeyCard.match(/../g)) needsAmountValidation: false # ~> 1.4.13 need validation on amount if @dongle.getIntFirmwareVersion() < @dongle.Firmware.V1_4_13 stringifiedAmount = @amount.toString() stringifiedAmount = _.str.lpad(stringifiedAmount, 9, '0') # Split amount in integer and decimal parts integerPart = stringifiedAmount.substr(0, stringifiedAmount.length - 8) decimalPart = stringifiedAmount.substr(stringifiedAmount.length - 8) # Prepend to validationCharacters first digit of integer part, # and 3 first digit of decimal part only if not empty. amountChars = [integerPart.charAt(integerPart.length - 1)] if decimalPart isnt "00000000" amountChars.concat decimalPart.substring(0,3).split('') details.validationCharacters = amountChars.concat(details.validationCharacters) # Compute amount indexes firstIdx = integerPart.length - 1 lastIdx = if decimalPart is "00000000" then firstIdx else firstIdx+3 detail.amount = text: stringifiedAmount indexes: [firstIdx..lastIdx] details.needsAmountValidation = true return details # @param [ledger.Amount] amount # @param [ledger.Amount] fees # @param [String] recipientAddress # @param [Array] inputsAccounts # @param [?] changeAccount # @param [Function] callback # @return [CompletionClosure] @createAndPrepareTransaction: (amount, fees, recipientAddress, inputsAccounts, changeAccount, callback=undefined) -> completion = new CompletionClosure(callback) inputsAccounts = [inputsAccounts] unless _.isArray inputsAccounts inputsPaths = _.flatten(inputsAccount.getHDWalletAccount().getAllAddressesPaths() for inputsAccount in inputsAccounts) changePath = changeAccount.getHDWalletAccount().getCurrentChangeAddressPath() requiredAmount = amount.add(fees) l "Required amount", requiredAmount.toString() transaction = new ledger.dongle.Transaction(ledger.app.dongle, amount, fees, recipientAddress) ledger.api.UnspentOutputsRestClient.instance.getUnspentOutputsFromPaths inputsPath, (outputs, error) -> return completion.error(Errors.NetworkError, error) if error? # Collect each valid outputs and sort them by desired priority validOutputs = _.chain(outputs) .filter((output) -> output.paths.length > 0) .sortBy((output) -> -output['confirmations']) .value() l "Valid outputs :", validOutputs return completion.error(Errors.NotEnoughFunds) if validOutputs.length == 0 # For each valid outputs we try to get its raw transaction. finalOutputs = [] collectedAmount = new Amount() hadNetworkFailure = no _.async.each validOutputs, (output, done, hasNext) => ledger.api.TransactionsRestClient.instance.getRawTransaction output.transaction_hash, (rawTransaction, error) -> if error? hadNetworkFailure = yes return done() output.raw = rawTransaction finalOutputs.push(output) collectedAmount = collectedAmount.add(output.value) l "Required amount :", requiredAmount.toString(), ", Collected amount :", collectedAmount.toString(), "has next ?", hasNext if collectedAmount.gte(requiredAmount) # We have reached our required amount. It's time to prepare the transaction transaction.prepare(finalOutputs, changePath) .then => completion.success(transaction) .fail (error) => completion.failure(error) else if hasNext is true # Continue to collect funds done() else if hadNetworkFailure completion.error(Errors.NetworkError) else completion.error(Errors.NotEnoughFunds) completion.readonly()
195805
ValidationModes = PIN: 0x01 KEYCARD: 0x02 SECURE_SCREEN: 0x03 Errors = @ledger.errors Amount = ledger.Amount @ledger.dongle ?= {} ### @example Usage amount = ledger.Amount.fromBtc("1.234") fee = ledger.Amount.fromBtc("0.0001") recipientAddress = "1DR6p2UVfu1m6mCU8hyvh5r6ix3dJEPMX7" ledger.dongle.Transaction.createAndPrepareTransaction(amount, fees, recipientAddress, inputsAccounts, changeAccount).then (tx) => console.log("Prepared tx :", tx) ### class ledger.dongle.Transaction # @ValidationModes: ValidationModes # @DEFAULT_FEES: Amount.fromBtc(0.00005) # @property [ledger.Amount] amount: undefined # @property [ledger.Amount] fees: @DEFAULT_FEES # @property [String] recipientAddress: undefined # @property [Array<Object>] inputs: undefined # @property [String] changePath: undefined # @property [String] hash: undefined # @property [Boolean] _isValidated: no # @property [Object] _resumeData: undefined # @property [Integer] _validationMode: undefined # @property [Array<Object>] _btInputs: undefined # @property [Array<Object>] _btcAssociatedKeyPath: undefined # @property [Object] _transaction: undefined # @param [ledger.dongle.Dongle] dongle # @param [ledger.Amount] amount # @param [ledger.Amount] fees # @param [String] recipientAddress constructor: (@dongle, @amount, @fees, @recipientAddress) -> # @return [Boolean] isValidated: () -> @_isValidated # @return [String] getSignedTransaction: () -> @_transaction # @return [Integer] getValidationMode: () -> @_validationMode # @return [ledger.Amount] getAmount: () -> @amount # @return [String] getRecipientAddress: () -> @receiverAddress # @param [String] hash setHash: (hash) -> @hash = hash # @param [Array<Object>] inputs # @param [String] changePath # @param [Function] callback # @return [CompletionClosure] prepare: (@inputs, @changePath, callback=undefined) -> if not @amount? or not @fees? or not @recipientAddress? throw new ledger.StandardError('Transaction must me initialized before preparation') completion = new CompletionClosure(callback) try @_btInputs = [] @_btcAssociatedKeyPath = [] for input in inputs splitTransaction = @dongle.splitTransaction(input) @_btInputs.push [splitTransaction, input.output_index] @_btcAssociatedKeyPath.push input.paths[0] catch err completion.failure(new ledger.StandardError(Errors.UnknowError, err)) @dongle.createPaymentTransaction(@_btInputs, @_btcAssociatedKeyPath, @changePath, @recipientAddress, @amount, @fees) .then (@_resumeData) => @_validationMode = @_resumeData.authorizationRequired completion.success() .fail (error) => completion.failure(new ledger.StandardError(Errors.SignatureError)) .done() completion.readonly() # @param [String] validationKey 4 chars ASCII encoded # @param [Function] callback # @return [CompletionClosure] validate: (validationKey, callback=undefined) -> if not @_resumeData? or not @_validationMode? throw new ledger.StandardError('Transaction must me prepared before validation') completion = new CompletionClosure(callback) # Convert ASCII encoded validationKey to HEX encoded validationKey if @_validationMode == ValidationModes.KEYCARD validationKey = ("<KEY> char in validationKey.<KEY>('')).<KEY> else validationKey = (validationKey.charCodeAt(i).<KEY>(16) for i in [0...validationKey.length]).<KEY>('') @dongle.createPaymentTransaction( @_btInputs, @_btcAssociatedKeyPath, @changePath, @recipientAddress, @amount, @fees, undefined, # Default lockTime undefined, # Default sigHash validationKey, resumeData ) .then (@_transaction) => @_isValidated = yes _.defer => completion.success() .fail (error) => _.defer => completion.failure(new ledger.StandardError(Errors.SignatureError, error)) .done() completion.readonly() # Retrieve information that need to be confirmed by the user. # @return [Object] # @option [Integer] validationMode # @option [Object, undefined] amount # @option [String] text # @option [Array<Integer>] indexes # @option [Object] recipientsAddress # @option [String] text # @option [Array<Integer>] indexes # @option [String] validationCharacters # @option [Boolean] needsAmountValidation getValidationDetails: -> details = validationMode: @_validationMode recipientsAddress: text: @recipientAddress indexes: @_resumeData.indexesKeyCard.match(/../g) validationCharacters: (@recipientAddress[index] for index in @_resumeData.indexesKeyCard.match(/../g)) needsAmountValidation: false # ~> 1.4.13 need validation on amount if @dongle.getIntFirmwareVersion() < @dongle.Firmware.V1_4_13 stringifiedAmount = @amount.toString() stringifiedAmount = _.str.lpad(stringifiedAmount, 9, '0') # Split amount in integer and decimal parts integerPart = stringifiedAmount.substr(0, stringifiedAmount.length - 8) decimalPart = stringifiedAmount.substr(stringifiedAmount.length - 8) # Prepend to validationCharacters first digit of integer part, # and 3 first digit of decimal part only if not empty. amountChars = [integerPart.charAt(integerPart.length - 1)] if decimalPart isnt "00000000" amountChars.concat decimalPart.substring(0,3).split('') details.validationCharacters = amountChars.concat(details.validationCharacters) # Compute amount indexes firstIdx = integerPart.length - 1 lastIdx = if decimalPart is "00000000" then firstIdx else firstIdx+3 detail.amount = text: stringifiedAmount indexes: [firstIdx..lastIdx] details.needsAmountValidation = true return details # @param [ledger.Amount] amount # @param [ledger.Amount] fees # @param [String] recipientAddress # @param [Array] inputsAccounts # @param [?] changeAccount # @param [Function] callback # @return [CompletionClosure] @createAndPrepareTransaction: (amount, fees, recipientAddress, inputsAccounts, changeAccount, callback=undefined) -> completion = new CompletionClosure(callback) inputsAccounts = [inputsAccounts] unless _.isArray inputsAccounts inputsPaths = _.flatten(inputsAccount.getHDWalletAccount().getAllAddressesPaths() for inputsAccount in inputsAccounts) changePath = changeAccount.getHDWalletAccount().getCurrentChangeAddressPath() requiredAmount = amount.add(fees) l "Required amount", requiredAmount.toString() transaction = new ledger.dongle.Transaction(ledger.app.dongle, amount, fees, recipientAddress) ledger.api.UnspentOutputsRestClient.instance.getUnspentOutputsFromPaths inputsPath, (outputs, error) -> return completion.error(Errors.NetworkError, error) if error? # Collect each valid outputs and sort them by desired priority validOutputs = _.chain(outputs) .filter((output) -> output.paths.length > 0) .sortBy((output) -> -output['confirmations']) .value() l "Valid outputs :", validOutputs return completion.error(Errors.NotEnoughFunds) if validOutputs.length == 0 # For each valid outputs we try to get its raw transaction. finalOutputs = [] collectedAmount = new Amount() hadNetworkFailure = no _.async.each validOutputs, (output, done, hasNext) => ledger.api.TransactionsRestClient.instance.getRawTransaction output.transaction_hash, (rawTransaction, error) -> if error? hadNetworkFailure = yes return done() output.raw = rawTransaction finalOutputs.push(output) collectedAmount = collectedAmount.add(output.value) l "Required amount :", requiredAmount.toString(), ", Collected amount :", collectedAmount.toString(), "has next ?", hasNext if collectedAmount.gte(requiredAmount) # We have reached our required amount. It's time to prepare the transaction transaction.prepare(finalOutputs, changePath) .then => completion.success(transaction) .fail (error) => completion.failure(error) else if hasNext is true # Continue to collect funds done() else if hadNetworkFailure completion.error(Errors.NetworkError) else completion.error(Errors.NotEnoughFunds) completion.readonly()
true
ValidationModes = PIN: 0x01 KEYCARD: 0x02 SECURE_SCREEN: 0x03 Errors = @ledger.errors Amount = ledger.Amount @ledger.dongle ?= {} ### @example Usage amount = ledger.Amount.fromBtc("1.234") fee = ledger.Amount.fromBtc("0.0001") recipientAddress = "1DR6p2UVfu1m6mCU8hyvh5r6ix3dJEPMX7" ledger.dongle.Transaction.createAndPrepareTransaction(amount, fees, recipientAddress, inputsAccounts, changeAccount).then (tx) => console.log("Prepared tx :", tx) ### class ledger.dongle.Transaction # @ValidationModes: ValidationModes # @DEFAULT_FEES: Amount.fromBtc(0.00005) # @property [ledger.Amount] amount: undefined # @property [ledger.Amount] fees: @DEFAULT_FEES # @property [String] recipientAddress: undefined # @property [Array<Object>] inputs: undefined # @property [String] changePath: undefined # @property [String] hash: undefined # @property [Boolean] _isValidated: no # @property [Object] _resumeData: undefined # @property [Integer] _validationMode: undefined # @property [Array<Object>] _btInputs: undefined # @property [Array<Object>] _btcAssociatedKeyPath: undefined # @property [Object] _transaction: undefined # @param [ledger.dongle.Dongle] dongle # @param [ledger.Amount] amount # @param [ledger.Amount] fees # @param [String] recipientAddress constructor: (@dongle, @amount, @fees, @recipientAddress) -> # @return [Boolean] isValidated: () -> @_isValidated # @return [String] getSignedTransaction: () -> @_transaction # @return [Integer] getValidationMode: () -> @_validationMode # @return [ledger.Amount] getAmount: () -> @amount # @return [String] getRecipientAddress: () -> @receiverAddress # @param [String] hash setHash: (hash) -> @hash = hash # @param [Array<Object>] inputs # @param [String] changePath # @param [Function] callback # @return [CompletionClosure] prepare: (@inputs, @changePath, callback=undefined) -> if not @amount? or not @fees? or not @recipientAddress? throw new ledger.StandardError('Transaction must me initialized before preparation') completion = new CompletionClosure(callback) try @_btInputs = [] @_btcAssociatedKeyPath = [] for input in inputs splitTransaction = @dongle.splitTransaction(input) @_btInputs.push [splitTransaction, input.output_index] @_btcAssociatedKeyPath.push input.paths[0] catch err completion.failure(new ledger.StandardError(Errors.UnknowError, err)) @dongle.createPaymentTransaction(@_btInputs, @_btcAssociatedKeyPath, @changePath, @recipientAddress, @amount, @fees) .then (@_resumeData) => @_validationMode = @_resumeData.authorizationRequired completion.success() .fail (error) => completion.failure(new ledger.StandardError(Errors.SignatureError)) .done() completion.readonly() # @param [String] validationKey 4 chars ASCII encoded # @param [Function] callback # @return [CompletionClosure] validate: (validationKey, callback=undefined) -> if not @_resumeData? or not @_validationMode? throw new ledger.StandardError('Transaction must me prepared before validation') completion = new CompletionClosure(callback) # Convert ASCII encoded validationKey to HEX encoded validationKey if @_validationMode == ValidationModes.KEYCARD validationKey = ("PI:KEY:<KEY>END_PI char in validationKey.PI:KEY:<KEY>END_PI('')).PI:KEY:<KEY>END_PI else validationKey = (validationKey.charCodeAt(i).PI:KEY:<KEY>END_PI(16) for i in [0...validationKey.length]).PI:KEY:<KEY>END_PI('') @dongle.createPaymentTransaction( @_btInputs, @_btcAssociatedKeyPath, @changePath, @recipientAddress, @amount, @fees, undefined, # Default lockTime undefined, # Default sigHash validationKey, resumeData ) .then (@_transaction) => @_isValidated = yes _.defer => completion.success() .fail (error) => _.defer => completion.failure(new ledger.StandardError(Errors.SignatureError, error)) .done() completion.readonly() # Retrieve information that need to be confirmed by the user. # @return [Object] # @option [Integer] validationMode # @option [Object, undefined] amount # @option [String] text # @option [Array<Integer>] indexes # @option [Object] recipientsAddress # @option [String] text # @option [Array<Integer>] indexes # @option [String] validationCharacters # @option [Boolean] needsAmountValidation getValidationDetails: -> details = validationMode: @_validationMode recipientsAddress: text: @recipientAddress indexes: @_resumeData.indexesKeyCard.match(/../g) validationCharacters: (@recipientAddress[index] for index in @_resumeData.indexesKeyCard.match(/../g)) needsAmountValidation: false # ~> 1.4.13 need validation on amount if @dongle.getIntFirmwareVersion() < @dongle.Firmware.V1_4_13 stringifiedAmount = @amount.toString() stringifiedAmount = _.str.lpad(stringifiedAmount, 9, '0') # Split amount in integer and decimal parts integerPart = stringifiedAmount.substr(0, stringifiedAmount.length - 8) decimalPart = stringifiedAmount.substr(stringifiedAmount.length - 8) # Prepend to validationCharacters first digit of integer part, # and 3 first digit of decimal part only if not empty. amountChars = [integerPart.charAt(integerPart.length - 1)] if decimalPart isnt "00000000" amountChars.concat decimalPart.substring(0,3).split('') details.validationCharacters = amountChars.concat(details.validationCharacters) # Compute amount indexes firstIdx = integerPart.length - 1 lastIdx = if decimalPart is "00000000" then firstIdx else firstIdx+3 detail.amount = text: stringifiedAmount indexes: [firstIdx..lastIdx] details.needsAmountValidation = true return details # @param [ledger.Amount] amount # @param [ledger.Amount] fees # @param [String] recipientAddress # @param [Array] inputsAccounts # @param [?] changeAccount # @param [Function] callback # @return [CompletionClosure] @createAndPrepareTransaction: (amount, fees, recipientAddress, inputsAccounts, changeAccount, callback=undefined) -> completion = new CompletionClosure(callback) inputsAccounts = [inputsAccounts] unless _.isArray inputsAccounts inputsPaths = _.flatten(inputsAccount.getHDWalletAccount().getAllAddressesPaths() for inputsAccount in inputsAccounts) changePath = changeAccount.getHDWalletAccount().getCurrentChangeAddressPath() requiredAmount = amount.add(fees) l "Required amount", requiredAmount.toString() transaction = new ledger.dongle.Transaction(ledger.app.dongle, amount, fees, recipientAddress) ledger.api.UnspentOutputsRestClient.instance.getUnspentOutputsFromPaths inputsPath, (outputs, error) -> return completion.error(Errors.NetworkError, error) if error? # Collect each valid outputs and sort them by desired priority validOutputs = _.chain(outputs) .filter((output) -> output.paths.length > 0) .sortBy((output) -> -output['confirmations']) .value() l "Valid outputs :", validOutputs return completion.error(Errors.NotEnoughFunds) if validOutputs.length == 0 # For each valid outputs we try to get its raw transaction. finalOutputs = [] collectedAmount = new Amount() hadNetworkFailure = no _.async.each validOutputs, (output, done, hasNext) => ledger.api.TransactionsRestClient.instance.getRawTransaction output.transaction_hash, (rawTransaction, error) -> if error? hadNetworkFailure = yes return done() output.raw = rawTransaction finalOutputs.push(output) collectedAmount = collectedAmount.add(output.value) l "Required amount :", requiredAmount.toString(), ", Collected amount :", collectedAmount.toString(), "has next ?", hasNext if collectedAmount.gte(requiredAmount) # We have reached our required amount. It's time to prepare the transaction transaction.prepare(finalOutputs, changePath) .then => completion.success(transaction) .fail (error) => completion.failure(error) else if hasNext is true # Continue to collect funds done() else if hadNetworkFailure completion.error(Errors.NetworkError) else completion.error(Errors.NotEnoughFunds) completion.readonly()
[ { "context": "id'\n\t\t@newUser = _id: 'mock-new-user-id', email: 'new-user-email@foo.bar'\n\t\t@subscription =\n\t\t\t_id: 'mock-subscription-id'", "end": 813, "score": 0.9965658187866211, "start": 791, "tag": "EMAIL", "value": "new-user-email@foo.bar" }, { "context": "\t@users = [\...
test/unit/coffee/UserMembership/UserMembershipControllerTests.coffee
shyoshyo/web-sharelatex
1
sinon = require('sinon') assertCalledWith = sinon.assert.calledWith assertNotCalled = sinon.assert.notCalled chai = require('chai') should = chai.should() assert = chai.assert expect = require('chai').expect modulePath = "../../../../app/js/Features/UserMembership/UserMembershipController.js" SandboxedModule = require('sandboxed-module') MockRequest = require "../helpers/MockRequest" MockResponse = require "../helpers/MockResponse" EntityConfigs = require("../../../../app/js/Features/UserMembership/UserMembershipEntityConfigs") Errors = require("../../../../app/js/Features/Errors/Errors") describe "UserMembershipController", -> beforeEach -> @req = new MockRequest() @req.params.id = 'mock-entity-id' @user = _id: 'mock-user-id' @newUser = _id: 'mock-new-user-id', email: 'new-user-email@foo.bar' @subscription = _id: 'mock-subscription-id' fetchV1Data: (callback) => callback(null, @subscription) @institution = _id: 'mock-institution-id' v1Id: 123 fetchV1Data: (callback) => institution = Object.assign({}, @institution) institution.name = 'Test Institution Name' callback(null, institution) @users = [ { _id: 'mock-member-id-1', email: 'mock-email-1@foo.com' } { _id: 'mock-member-id-2', email: 'mock-email-2@foo.com' } ] @AuthenticationController = getSessionUser: sinon.stub().returns(@user) getLoggedInUserId: sinon.stub().returns(@user._id) @UserMembershipHandler = getEntity: sinon.stub().yields(null, @subscription) createEntity: sinon.stub().yields(null, @institution) getUsers: sinon.stub().yields(null, @users) addUser: sinon.stub().yields(null, @newUser) removeUser: sinon.stub().yields(null) @UserMembershipController = SandboxedModule.require modulePath, requires: '../Authentication/AuthenticationController': @AuthenticationController './UserMembershipHandler': @UserMembershipHandler '../Errors/Errors': Errors "logger-sharelatex": log: -> err: -> describe 'index', -> beforeEach -> @req.entity = @subscription @req.entityConfig = EntityConfigs.group it 'get users', (done) -> @UserMembershipController.index @req, render: () => sinon.assert.calledWithMatch( @UserMembershipHandler.getUsers, @subscription, modelName: 'Subscription', ) done() it 'render group view', (done) -> @UserMembershipController.index @req, render: (viewPath, viewParams) => expect(viewPath).to.equal 'user_membership/index' expect(viewParams.users).to.deep.equal @users expect(viewParams.groupSize).to.equal @subscription.membersLimit expect(viewParams.translations.title).to.equal 'group_account' expect(viewParams.paths.addMember).to.equal "/manage/groups/#{@subscription._id}/invites" done() it 'render group managers view', (done) -> @req.entityConfig = EntityConfigs.groupManagers @UserMembershipController.index @req, render: (viewPath, viewParams) => expect(viewPath).to.equal 'user_membership/index' expect(viewParams.groupSize).to.equal undefined expect(viewParams.translations.title).to.equal 'group_account' expect(viewParams.translations.subtitle).to.equal 'managers_management' expect(viewParams.paths.exportMembers).to.be.undefined done() it 'render institution view', (done) -> @req.entity = @institution @req.entityConfig = EntityConfigs.institution @UserMembershipController.index @req, render: (viewPath, viewParams) => expect(viewPath).to.equal 'user_membership/index' expect(viewParams.name).to.equal 'Test Institution Name' expect(viewParams.groupSize).to.equal undefined expect(viewParams.translations.title).to.equal 'institution_account' expect(viewParams.paths.exportMembers).to.be.undefined done() describe 'add', -> beforeEach -> @req.body.email = @newUser.email @req.entity = @subscription @req.entityConfig = EntityConfigs.groupManagers it 'add user', (done) -> @UserMembershipController.add @req, json: () => sinon.assert.calledWithMatch( @UserMembershipHandler.addUser, @subscription, modelName: 'Subscription', @newUser.email ) done() it 'return user object', (done) -> @UserMembershipController.add @req, json: (payload) => payload.user.should.equal @newUser done() it 'handle readOnly entity', (done) -> @req.entityConfig = EntityConfigs.group @UserMembershipController.add @req, null, (error) => expect(error).to.extist expect(error).to.be.an.instanceof(Errors.NotFoundError) done() it 'handle user already added', (done) -> @UserMembershipHandler.addUser.yields(alreadyAdded: true) @UserMembershipController.add @req, status: () => json: (payload) => expect(payload.error.code).to.equal 'user_already_added' done() it 'handle user not found', (done) -> @UserMembershipHandler.addUser.yields(userNotFound: true) @UserMembershipController.add @req, status: () => json: (payload) => expect(payload.error.code).to.equal 'user_not_found' done() it 'handle invalid email', (done) -> @req.body.email = 'not_valid_email' @UserMembershipController.add @req, status: () => json: (payload) => expect(payload.error.code).to.equal 'invalid_email' done() describe 'remove', -> beforeEach -> @req.params.userId = @newUser._id @req.entity = @subscription @req.entityConfig = EntityConfigs.groupManagers it 'remove user', (done) -> @UserMembershipController.remove @req, send: () => sinon.assert.calledWithMatch( @UserMembershipHandler.removeUser, @subscription, modelName: 'Subscription', @newUser._id ) done() it 'handle readOnly entity', (done) -> @req.entityConfig = EntityConfigs.group @UserMembershipController.remove @req, null, (error) => expect(error).to.extist expect(error).to.be.an.instanceof(Errors.NotFoundError) done() it 'prevent self removal', (done) -> @req.params.userId = @user._id @UserMembershipController.remove @req, status: () => json: (payload) => expect(payload.error.code).to.equal 'managers_cannot_remove_self' done() it 'prevent admin removal', (done) -> @UserMembershipHandler.removeUser.yields(isAdmin: true) @UserMembershipController.remove @req, status: () => json: (payload) => expect(payload.error.code).to.equal 'managers_cannot_remove_admin' done() describe "exportCsv", -> beforeEach -> @req.entity = @subscription @req.entityConfig = EntityConfigs.groupManagers @res = new MockResponse() @res.contentType = sinon.stub() @res.header = sinon.stub() @res.send = sinon.stub() @UserMembershipController.exportCsv @req, @res it 'get users', -> sinon.assert.calledWithMatch( @UserMembershipHandler.getUsers, @subscription, modelName: 'Subscription', ) it "should set the correct content type on the request", -> assertCalledWith(@res.contentType, "text/csv") it "should name the exported csv file", -> assertCalledWith( @res.header "Content-Disposition", "attachment; filename=Group.csv" ) it "should export the correct csv", -> assertCalledWith(@res.send, "mock-email-1@foo.com\nmock-email-2@foo.com\n") describe 'new', -> beforeEach -> @req.params.name = 'publisher' @req.params.id = 'abc' it 'renders view', (done) -> @UserMembershipController.new @req, render: (viewPath, data) => expect(data.entityName).to.eq 'publisher' expect(data.entityId).to.eq 'abc' done() describe 'create', -> beforeEach -> @req.params.name = 'institution' @req.params.id = 123 it 'creates institution', (done) -> @UserMembershipController.create @req, redirect: (path) => expect(path).to.eq EntityConfigs['institution'].pathsFor(123).index sinon.assert.calledWithMatch( @UserMembershipHandler.createEntity, 123, modelName: 'Institution', ) done() it 'checks canCreate', (done) -> @req.params.name = 'group' @UserMembershipController.create @req, null, (error) => expect(error).to.extist expect(error).to.be.an.instanceof(Errors.NotFoundError) sinon.assert.notCalled(@UserMembershipHandler.createEntity) done()
225085
sinon = require('sinon') assertCalledWith = sinon.assert.calledWith assertNotCalled = sinon.assert.notCalled chai = require('chai') should = chai.should() assert = chai.assert expect = require('chai').expect modulePath = "../../../../app/js/Features/UserMembership/UserMembershipController.js" SandboxedModule = require('sandboxed-module') MockRequest = require "../helpers/MockRequest" MockResponse = require "../helpers/MockResponse" EntityConfigs = require("../../../../app/js/Features/UserMembership/UserMembershipEntityConfigs") Errors = require("../../../../app/js/Features/Errors/Errors") describe "UserMembershipController", -> beforeEach -> @req = new MockRequest() @req.params.id = 'mock-entity-id' @user = _id: 'mock-user-id' @newUser = _id: 'mock-new-user-id', email: '<EMAIL>' @subscription = _id: 'mock-subscription-id' fetchV1Data: (callback) => callback(null, @subscription) @institution = _id: 'mock-institution-id' v1Id: 123 fetchV1Data: (callback) => institution = Object.assign({}, @institution) institution.name = 'Test Institution Name' callback(null, institution) @users = [ { _id: 'mock-member-id-1', email: '<EMAIL>' } { _id: 'mock-member-id-2', email: '<EMAIL>' } ] @AuthenticationController = getSessionUser: sinon.stub().returns(@user) getLoggedInUserId: sinon.stub().returns(@user._id) @UserMembershipHandler = getEntity: sinon.stub().yields(null, @subscription) createEntity: sinon.stub().yields(null, @institution) getUsers: sinon.stub().yields(null, @users) addUser: sinon.stub().yields(null, @newUser) removeUser: sinon.stub().yields(null) @UserMembershipController = SandboxedModule.require modulePath, requires: '../Authentication/AuthenticationController': @AuthenticationController './UserMembershipHandler': @UserMembershipHandler '../Errors/Errors': Errors "logger-sharelatex": log: -> err: -> describe 'index', -> beforeEach -> @req.entity = @subscription @req.entityConfig = EntityConfigs.group it 'get users', (done) -> @UserMembershipController.index @req, render: () => sinon.assert.calledWithMatch( @UserMembershipHandler.getUsers, @subscription, modelName: 'Subscription', ) done() it 'render group view', (done) -> @UserMembershipController.index @req, render: (viewPath, viewParams) => expect(viewPath).to.equal 'user_membership/index' expect(viewParams.users).to.deep.equal @users expect(viewParams.groupSize).to.equal @subscription.membersLimit expect(viewParams.translations.title).to.equal 'group_account' expect(viewParams.paths.addMember).to.equal "/manage/groups/#{@subscription._id}/invites" done() it 'render group managers view', (done) -> @req.entityConfig = EntityConfigs.groupManagers @UserMembershipController.index @req, render: (viewPath, viewParams) => expect(viewPath).to.equal 'user_membership/index' expect(viewParams.groupSize).to.equal undefined expect(viewParams.translations.title).to.equal 'group_account' expect(viewParams.translations.subtitle).to.equal 'managers_management' expect(viewParams.paths.exportMembers).to.be.undefined done() it 'render institution view', (done) -> @req.entity = @institution @req.entityConfig = EntityConfigs.institution @UserMembershipController.index @req, render: (viewPath, viewParams) => expect(viewPath).to.equal 'user_membership/index' expect(viewParams.name).to.equal 'Test Institution Name' expect(viewParams.groupSize).to.equal undefined expect(viewParams.translations.title).to.equal 'institution_account' expect(viewParams.paths.exportMembers).to.be.undefined done() describe 'add', -> beforeEach -> @req.body.email = @newUser.email @req.entity = @subscription @req.entityConfig = EntityConfigs.groupManagers it 'add user', (done) -> @UserMembershipController.add @req, json: () => sinon.assert.calledWithMatch( @UserMembershipHandler.addUser, @subscription, modelName: 'Subscription', @newUser.email ) done() it 'return user object', (done) -> @UserMembershipController.add @req, json: (payload) => payload.user.should.equal @newUser done() it 'handle readOnly entity', (done) -> @req.entityConfig = EntityConfigs.group @UserMembershipController.add @req, null, (error) => expect(error).to.extist expect(error).to.be.an.instanceof(Errors.NotFoundError) done() it 'handle user already added', (done) -> @UserMembershipHandler.addUser.yields(alreadyAdded: true) @UserMembershipController.add @req, status: () => json: (payload) => expect(payload.error.code).to.equal 'user_already_added' done() it 'handle user not found', (done) -> @UserMembershipHandler.addUser.yields(userNotFound: true) @UserMembershipController.add @req, status: () => json: (payload) => expect(payload.error.code).to.equal 'user_not_found' done() it 'handle invalid email', (done) -> @req.body.email = 'not_valid_email' @UserMembershipController.add @req, status: () => json: (payload) => expect(payload.error.code).to.equal 'invalid_email' done() describe 'remove', -> beforeEach -> @req.params.userId = @newUser._id @req.entity = @subscription @req.entityConfig = EntityConfigs.groupManagers it 'remove user', (done) -> @UserMembershipController.remove @req, send: () => sinon.assert.calledWithMatch( @UserMembershipHandler.removeUser, @subscription, modelName: 'Subscription', @newUser._id ) done() it 'handle readOnly entity', (done) -> @req.entityConfig = EntityConfigs.group @UserMembershipController.remove @req, null, (error) => expect(error).to.extist expect(error).to.be.an.instanceof(Errors.NotFoundError) done() it 'prevent self removal', (done) -> @req.params.userId = @user._id @UserMembershipController.remove @req, status: () => json: (payload) => expect(payload.error.code).to.equal 'managers_cannot_remove_self' done() it 'prevent admin removal', (done) -> @UserMembershipHandler.removeUser.yields(isAdmin: true) @UserMembershipController.remove @req, status: () => json: (payload) => expect(payload.error.code).to.equal 'managers_cannot_remove_admin' done() describe "exportCsv", -> beforeEach -> @req.entity = @subscription @req.entityConfig = EntityConfigs.groupManagers @res = new MockResponse() @res.contentType = sinon.stub() @res.header = sinon.stub() @res.send = sinon.stub() @UserMembershipController.exportCsv @req, @res it 'get users', -> sinon.assert.calledWithMatch( @UserMembershipHandler.getUsers, @subscription, modelName: 'Subscription', ) it "should set the correct content type on the request", -> assertCalledWith(@res.contentType, "text/csv") it "should name the exported csv file", -> assertCalledWith( @res.header "Content-Disposition", "attachment; filename=Group.csv" ) it "should export the correct csv", -> assertCalledWith(@res.send, "<EMAIL>\nmock-email-2@foo.com\n") describe 'new', -> beforeEach -> @req.params.name = 'publisher' @req.params.id = 'abc' it 'renders view', (done) -> @UserMembershipController.new @req, render: (viewPath, data) => expect(data.entityName).to.eq 'publisher' expect(data.entityId).to.eq 'abc' done() describe 'create', -> beforeEach -> @req.params.name = 'institution' @req.params.id = 123 it 'creates institution', (done) -> @UserMembershipController.create @req, redirect: (path) => expect(path).to.eq EntityConfigs['institution'].pathsFor(123).index sinon.assert.calledWithMatch( @UserMembershipHandler.createEntity, 123, modelName: 'Institution', ) done() it 'checks canCreate', (done) -> @req.params.name = 'group' @UserMembershipController.create @req, null, (error) => expect(error).to.extist expect(error).to.be.an.instanceof(Errors.NotFoundError) sinon.assert.notCalled(@UserMembershipHandler.createEntity) done()
true
sinon = require('sinon') assertCalledWith = sinon.assert.calledWith assertNotCalled = sinon.assert.notCalled chai = require('chai') should = chai.should() assert = chai.assert expect = require('chai').expect modulePath = "../../../../app/js/Features/UserMembership/UserMembershipController.js" SandboxedModule = require('sandboxed-module') MockRequest = require "../helpers/MockRequest" MockResponse = require "../helpers/MockResponse" EntityConfigs = require("../../../../app/js/Features/UserMembership/UserMembershipEntityConfigs") Errors = require("../../../../app/js/Features/Errors/Errors") describe "UserMembershipController", -> beforeEach -> @req = new MockRequest() @req.params.id = 'mock-entity-id' @user = _id: 'mock-user-id' @newUser = _id: 'mock-new-user-id', email: 'PI:EMAIL:<EMAIL>END_PI' @subscription = _id: 'mock-subscription-id' fetchV1Data: (callback) => callback(null, @subscription) @institution = _id: 'mock-institution-id' v1Id: 123 fetchV1Data: (callback) => institution = Object.assign({}, @institution) institution.name = 'Test Institution Name' callback(null, institution) @users = [ { _id: 'mock-member-id-1', email: 'PI:EMAIL:<EMAIL>END_PI' } { _id: 'mock-member-id-2', email: 'PI:EMAIL:<EMAIL>END_PI' } ] @AuthenticationController = getSessionUser: sinon.stub().returns(@user) getLoggedInUserId: sinon.stub().returns(@user._id) @UserMembershipHandler = getEntity: sinon.stub().yields(null, @subscription) createEntity: sinon.stub().yields(null, @institution) getUsers: sinon.stub().yields(null, @users) addUser: sinon.stub().yields(null, @newUser) removeUser: sinon.stub().yields(null) @UserMembershipController = SandboxedModule.require modulePath, requires: '../Authentication/AuthenticationController': @AuthenticationController './UserMembershipHandler': @UserMembershipHandler '../Errors/Errors': Errors "logger-sharelatex": log: -> err: -> describe 'index', -> beforeEach -> @req.entity = @subscription @req.entityConfig = EntityConfigs.group it 'get users', (done) -> @UserMembershipController.index @req, render: () => sinon.assert.calledWithMatch( @UserMembershipHandler.getUsers, @subscription, modelName: 'Subscription', ) done() it 'render group view', (done) -> @UserMembershipController.index @req, render: (viewPath, viewParams) => expect(viewPath).to.equal 'user_membership/index' expect(viewParams.users).to.deep.equal @users expect(viewParams.groupSize).to.equal @subscription.membersLimit expect(viewParams.translations.title).to.equal 'group_account' expect(viewParams.paths.addMember).to.equal "/manage/groups/#{@subscription._id}/invites" done() it 'render group managers view', (done) -> @req.entityConfig = EntityConfigs.groupManagers @UserMembershipController.index @req, render: (viewPath, viewParams) => expect(viewPath).to.equal 'user_membership/index' expect(viewParams.groupSize).to.equal undefined expect(viewParams.translations.title).to.equal 'group_account' expect(viewParams.translations.subtitle).to.equal 'managers_management' expect(viewParams.paths.exportMembers).to.be.undefined done() it 'render institution view', (done) -> @req.entity = @institution @req.entityConfig = EntityConfigs.institution @UserMembershipController.index @req, render: (viewPath, viewParams) => expect(viewPath).to.equal 'user_membership/index' expect(viewParams.name).to.equal 'Test Institution Name' expect(viewParams.groupSize).to.equal undefined expect(viewParams.translations.title).to.equal 'institution_account' expect(viewParams.paths.exportMembers).to.be.undefined done() describe 'add', -> beforeEach -> @req.body.email = @newUser.email @req.entity = @subscription @req.entityConfig = EntityConfigs.groupManagers it 'add user', (done) -> @UserMembershipController.add @req, json: () => sinon.assert.calledWithMatch( @UserMembershipHandler.addUser, @subscription, modelName: 'Subscription', @newUser.email ) done() it 'return user object', (done) -> @UserMembershipController.add @req, json: (payload) => payload.user.should.equal @newUser done() it 'handle readOnly entity', (done) -> @req.entityConfig = EntityConfigs.group @UserMembershipController.add @req, null, (error) => expect(error).to.extist expect(error).to.be.an.instanceof(Errors.NotFoundError) done() it 'handle user already added', (done) -> @UserMembershipHandler.addUser.yields(alreadyAdded: true) @UserMembershipController.add @req, status: () => json: (payload) => expect(payload.error.code).to.equal 'user_already_added' done() it 'handle user not found', (done) -> @UserMembershipHandler.addUser.yields(userNotFound: true) @UserMembershipController.add @req, status: () => json: (payload) => expect(payload.error.code).to.equal 'user_not_found' done() it 'handle invalid email', (done) -> @req.body.email = 'not_valid_email' @UserMembershipController.add @req, status: () => json: (payload) => expect(payload.error.code).to.equal 'invalid_email' done() describe 'remove', -> beforeEach -> @req.params.userId = @newUser._id @req.entity = @subscription @req.entityConfig = EntityConfigs.groupManagers it 'remove user', (done) -> @UserMembershipController.remove @req, send: () => sinon.assert.calledWithMatch( @UserMembershipHandler.removeUser, @subscription, modelName: 'Subscription', @newUser._id ) done() it 'handle readOnly entity', (done) -> @req.entityConfig = EntityConfigs.group @UserMembershipController.remove @req, null, (error) => expect(error).to.extist expect(error).to.be.an.instanceof(Errors.NotFoundError) done() it 'prevent self removal', (done) -> @req.params.userId = @user._id @UserMembershipController.remove @req, status: () => json: (payload) => expect(payload.error.code).to.equal 'managers_cannot_remove_self' done() it 'prevent admin removal', (done) -> @UserMembershipHandler.removeUser.yields(isAdmin: true) @UserMembershipController.remove @req, status: () => json: (payload) => expect(payload.error.code).to.equal 'managers_cannot_remove_admin' done() describe "exportCsv", -> beforeEach -> @req.entity = @subscription @req.entityConfig = EntityConfigs.groupManagers @res = new MockResponse() @res.contentType = sinon.stub() @res.header = sinon.stub() @res.send = sinon.stub() @UserMembershipController.exportCsv @req, @res it 'get users', -> sinon.assert.calledWithMatch( @UserMembershipHandler.getUsers, @subscription, modelName: 'Subscription', ) it "should set the correct content type on the request", -> assertCalledWith(@res.contentType, "text/csv") it "should name the exported csv file", -> assertCalledWith( @res.header "Content-Disposition", "attachment; filename=Group.csv" ) it "should export the correct csv", -> assertCalledWith(@res.send, "PI:EMAIL:<EMAIL>END_PI\nmock-email-2@foo.com\n") describe 'new', -> beforeEach -> @req.params.name = 'publisher' @req.params.id = 'abc' it 'renders view', (done) -> @UserMembershipController.new @req, render: (viewPath, data) => expect(data.entityName).to.eq 'publisher' expect(data.entityId).to.eq 'abc' done() describe 'create', -> beforeEach -> @req.params.name = 'institution' @req.params.id = 123 it 'creates institution', (done) -> @UserMembershipController.create @req, redirect: (path) => expect(path).to.eq EntityConfigs['institution'].pathsFor(123).index sinon.assert.calledWithMatch( @UserMembershipHandler.createEntity, 123, modelName: 'Institution', ) done() it 'checks canCreate', (done) -> @req.params.name = 'group' @UserMembershipController.create @req, null, (error) => expect(error).to.extist expect(error).to.be.an.instanceof(Errors.NotFoundError) sinon.assert.notCalled(@UserMembershipHandler.createEntity) done()
[ { "context": "ame=\"user\"]', {\n display_key: (d) ->\n \"#{d.name} (#{d.email})\"\n })\n usertypeahead.on 'typeahead:se", "end": 386, "score": 0.7532309293746948, "start": 379, "tag": "KEY", "value": "name} (" }, { "context": " display_key: (d) ->\n \"#{d.name} (#{d...
app/assets/javascripts/manager/users.js.coffee
gina-alaska/gina-catalog
0
# Place all the behaviors and hooks related to the matching controller here. # All this logic will automatically be available in application.js. # You can use CoffeeScript in this file: http://coffeescript.org/ $(document).on 'ready turbolinks:load', -> usertypeahead = new TypeAheadField('[data-behavior="typeahead"][data-name="user"]', { display_key: (d) -> "#{d.name} (#{d.email})" }) usertypeahead.on 'typeahead:selected', (e, suggestion, dataset) -> window.location = "/manager/permissions/new?user_id=#{suggestion.id}"
18402
# Place all the behaviors and hooks related to the matching controller here. # All this logic will automatically be available in application.js. # You can use CoffeeScript in this file: http://coffeescript.org/ $(document).on 'ready turbolinks:load', -> usertypeahead = new TypeAheadField('[data-behavior="typeahead"][data-name="user"]', { display_key: (d) -> "#{d.<KEY>#{d.email<KEY>})" }) usertypeahead.on 'typeahead:selected', (e, suggestion, dataset) -> window.location = "/manager/permissions/new?user_id=#{suggestion.id}"
true
# Place all the behaviors and hooks related to the matching controller here. # All this logic will automatically be available in application.js. # You can use CoffeeScript in this file: http://coffeescript.org/ $(document).on 'ready turbolinks:load', -> usertypeahead = new TypeAheadField('[data-behavior="typeahead"][data-name="user"]', { display_key: (d) -> "#{d.PI:KEY:<KEY>END_PI#{d.emailPI:KEY:<KEY>END_PI})" }) usertypeahead.on 'typeahead:selected', (e, suggestion, dataset) -> window.location = "/manager/permissions/new?user_id=#{suggestion.id}"
[ { "context": "key: 'example-paragraph'\n\npatterns: [\n\n # Matches example paragraph.\n #", "end": 23, "score": 0.6171474456787109, "start": 14, "tag": "KEY", "value": "paragraph" } ]
grammars/repositories/blocks/example-grammar.cson
andrewcarver/atom-language-asciidoc
45
key: 'example-paragraph' patterns: [ # Matches example paragraph. # # Examples: # # [example] # ==== # A multi-line example. # ==== # # or # # [example] # -- # A multi-line example. # -- # # or # # [example] # A example paragraph # name: 'markup.block.example.asciidoc' begin: '(?=(?>(?:^\\[(example)((?:,|#|\\.|%)[^\\]]+)*\\]$)))' patterns: [ match: '^\\[(example)((?:,|#|\\.|%)([^,\\]]+))*\\]$' captures: 0: patterns: [ include: '#block-attribute-inner' ] , include: '#block-title' , comment: 'example block' begin: '^(={4,})$' patterns: [ include: '$self' ] end: '^(\\1)$' , comment: 'open block' begin: '^(-{2})$' patterns: [ include: '$self' ] end: '^(\\1)$' , include: '#inlines' ] end: '((?<=--|====)$|^\\p{Blank}*$)' , # Matches example block # # Examples # # ==== # A multi-line example. # # Notice it's a delimited block. # ==== # name: 'markup.block.example.asciidoc' begin: '^(={4,})$' patterns: [ include: '$self' ] end: '^(\\1)$' ]
2828
key: 'example-<KEY>' patterns: [ # Matches example paragraph. # # Examples: # # [example] # ==== # A multi-line example. # ==== # # or # # [example] # -- # A multi-line example. # -- # # or # # [example] # A example paragraph # name: 'markup.block.example.asciidoc' begin: '(?=(?>(?:^\\[(example)((?:,|#|\\.|%)[^\\]]+)*\\]$)))' patterns: [ match: '^\\[(example)((?:,|#|\\.|%)([^,\\]]+))*\\]$' captures: 0: patterns: [ include: '#block-attribute-inner' ] , include: '#block-title' , comment: 'example block' begin: '^(={4,})$' patterns: [ include: '$self' ] end: '^(\\1)$' , comment: 'open block' begin: '^(-{2})$' patterns: [ include: '$self' ] end: '^(\\1)$' , include: '#inlines' ] end: '((?<=--|====)$|^\\p{Blank}*$)' , # Matches example block # # Examples # # ==== # A multi-line example. # # Notice it's a delimited block. # ==== # name: 'markup.block.example.asciidoc' begin: '^(={4,})$' patterns: [ include: '$self' ] end: '^(\\1)$' ]
true
key: 'example-PI:KEY:<KEY>END_PI' patterns: [ # Matches example paragraph. # # Examples: # # [example] # ==== # A multi-line example. # ==== # # or # # [example] # -- # A multi-line example. # -- # # or # # [example] # A example paragraph # name: 'markup.block.example.asciidoc' begin: '(?=(?>(?:^\\[(example)((?:,|#|\\.|%)[^\\]]+)*\\]$)))' patterns: [ match: '^\\[(example)((?:,|#|\\.|%)([^,\\]]+))*\\]$' captures: 0: patterns: [ include: '#block-attribute-inner' ] , include: '#block-title' , comment: 'example block' begin: '^(={4,})$' patterns: [ include: '$self' ] end: '^(\\1)$' , comment: 'open block' begin: '^(-{2})$' patterns: [ include: '$self' ] end: '^(\\1)$' , include: '#inlines' ] end: '((?<=--|====)$|^\\p{Blank}*$)' , # Matches example block # # Examples # # ==== # A multi-line example. # # Notice it's a delimited block. # ==== # name: 'markup.block.example.asciidoc' begin: '^(={4,})$' patterns: [ include: '$self' ] end: '^(\\1)$' ]
[ { "context": "============================\n# Copyright 2011-2014 Asyraf Abdul Rahman\n# Licensed under MIT\n# ==========================", "end": 222, "score": 0.9998759031295776, "start": 203, "tag": "NAME", "value": "Asyraf Abdul Rahman" } ]
app/assets/javascripts/sidebar.coffee
harley/rainbow
0
### ======================================================================== # Bootstrap: sidebar.js v0.1 # ======================================================================== # Copyright 2011-2014 Asyraf Abdul Rahman # Licensed under MIT # ======================================================================== ### +(($) -> 'use strict' # SIDEBAR PUBLIC CLASS DEFINITION # ================================ Sidebar = (element, options) -> @$element = $(element) @options = $.extend({}, Sidebar.DEFAULTS, options) @transitioning = null if @options.parent @$parent = $(@options.parent) if @options.toggle @toggle() return Sidebar.DEFAULTS = toggle: true Sidebar::show = -> if @transitioning or @$element.hasClass('sidebar-open') return startEvent = $.Event('show.bs.sidebar') @$element.trigger startEvent if startEvent.isDefaultPrevented() return @$element.addClass 'sidebar-open' @transitioning = 1 complete = -> @$element @transitioning = 0 @$element.trigger 'shown.bs.sidebar' return if !$.support.transition return complete.call(this) @$element.one($.support.transition.end, $.proxy(complete, this)).emulateTransitionEnd 400 return Sidebar::hide = -> if @transitioning or !@$element.hasClass('sidebar-open') return startEvent = $.Event('hide.bs.sidebar') @$element.trigger startEvent if startEvent.isDefaultPrevented() return @$element.removeClass 'sidebar-open' @transitioning = 1 complete = -> @transitioning = 0 @$element.trigger 'hidden.bs.sidebar' return if !$.support.transition return complete.call(this) @$element.one($.support.transition.end, $.proxy(complete, this)).emulateTransitionEnd 400 return Sidebar::toggle = -> @[if @$element.hasClass('sidebar-open') then 'hide' else 'show']() return old = $.fn.sidebar $.fn.sidebar = (option) -> @each -> $this = $(this) data = $this.data('bs.sidebar') options = $.extend({}, Sidebar.DEFAULTS, $this.data(), typeof options == 'object' and option) if !data and options.toggle and option == 'show' option = !option if !data $this.data 'bs.sidebar', data = new Sidebar(this, options) if typeof option == 'string' data[option]() return $.fn.sidebar.Constructor = Sidebar $.fn.collapse.noConflict = -> $.fn.sidebar = old this $(document).on 'click.bs.sidebar.data-api', '[data-toggle="sidebar"]', (e) -> $this = $(this) href = undefined target = $this.attr('data-target') or e.preventDefault() or (href = $this.attr('href')) and href.replace(/.*(?=#[^\s]+$)/, '') $target = $(target) data = $target.data('bs.sidebar') option = if data then 'toggle' else $this.data() $target.sidebar option return $('html').on 'click.bs.sidebar.autohide', (event) -> $this = $(event.target) isButtonOrSidebar = $this.is('.sidebar, [data-toggle="sidebar"]') or $this.parents('.sidebar, [data-toggle="sidebar"]').length if isButtonOrSidebar return else $target = $('.sidebar') $target.each (i, trgt) -> $trgt = $(trgt) if $trgt.data('bs.sidebar') and $trgt.hasClass('sidebar-open') $trgt.sidebar 'hide' return return return )(jQuery)
24960
### ======================================================================== # Bootstrap: sidebar.js v0.1 # ======================================================================== # Copyright 2011-2014 <NAME> # Licensed under MIT # ======================================================================== ### +(($) -> 'use strict' # SIDEBAR PUBLIC CLASS DEFINITION # ================================ Sidebar = (element, options) -> @$element = $(element) @options = $.extend({}, Sidebar.DEFAULTS, options) @transitioning = null if @options.parent @$parent = $(@options.parent) if @options.toggle @toggle() return Sidebar.DEFAULTS = toggle: true Sidebar::show = -> if @transitioning or @$element.hasClass('sidebar-open') return startEvent = $.Event('show.bs.sidebar') @$element.trigger startEvent if startEvent.isDefaultPrevented() return @$element.addClass 'sidebar-open' @transitioning = 1 complete = -> @$element @transitioning = 0 @$element.trigger 'shown.bs.sidebar' return if !$.support.transition return complete.call(this) @$element.one($.support.transition.end, $.proxy(complete, this)).emulateTransitionEnd 400 return Sidebar::hide = -> if @transitioning or !@$element.hasClass('sidebar-open') return startEvent = $.Event('hide.bs.sidebar') @$element.trigger startEvent if startEvent.isDefaultPrevented() return @$element.removeClass 'sidebar-open' @transitioning = 1 complete = -> @transitioning = 0 @$element.trigger 'hidden.bs.sidebar' return if !$.support.transition return complete.call(this) @$element.one($.support.transition.end, $.proxy(complete, this)).emulateTransitionEnd 400 return Sidebar::toggle = -> @[if @$element.hasClass('sidebar-open') then 'hide' else 'show']() return old = $.fn.sidebar $.fn.sidebar = (option) -> @each -> $this = $(this) data = $this.data('bs.sidebar') options = $.extend({}, Sidebar.DEFAULTS, $this.data(), typeof options == 'object' and option) if !data and options.toggle and option == 'show' option = !option if !data $this.data 'bs.sidebar', data = new Sidebar(this, options) if typeof option == 'string' data[option]() return $.fn.sidebar.Constructor = Sidebar $.fn.collapse.noConflict = -> $.fn.sidebar = old this $(document).on 'click.bs.sidebar.data-api', '[data-toggle="sidebar"]', (e) -> $this = $(this) href = undefined target = $this.attr('data-target') or e.preventDefault() or (href = $this.attr('href')) and href.replace(/.*(?=#[^\s]+$)/, '') $target = $(target) data = $target.data('bs.sidebar') option = if data then 'toggle' else $this.data() $target.sidebar option return $('html').on 'click.bs.sidebar.autohide', (event) -> $this = $(event.target) isButtonOrSidebar = $this.is('.sidebar, [data-toggle="sidebar"]') or $this.parents('.sidebar, [data-toggle="sidebar"]').length if isButtonOrSidebar return else $target = $('.sidebar') $target.each (i, trgt) -> $trgt = $(trgt) if $trgt.data('bs.sidebar') and $trgt.hasClass('sidebar-open') $trgt.sidebar 'hide' return return return )(jQuery)
true
### ======================================================================== # Bootstrap: sidebar.js v0.1 # ======================================================================== # Copyright 2011-2014 PI:NAME:<NAME>END_PI # Licensed under MIT # ======================================================================== ### +(($) -> 'use strict' # SIDEBAR PUBLIC CLASS DEFINITION # ================================ Sidebar = (element, options) -> @$element = $(element) @options = $.extend({}, Sidebar.DEFAULTS, options) @transitioning = null if @options.parent @$parent = $(@options.parent) if @options.toggle @toggle() return Sidebar.DEFAULTS = toggle: true Sidebar::show = -> if @transitioning or @$element.hasClass('sidebar-open') return startEvent = $.Event('show.bs.sidebar') @$element.trigger startEvent if startEvent.isDefaultPrevented() return @$element.addClass 'sidebar-open' @transitioning = 1 complete = -> @$element @transitioning = 0 @$element.trigger 'shown.bs.sidebar' return if !$.support.transition return complete.call(this) @$element.one($.support.transition.end, $.proxy(complete, this)).emulateTransitionEnd 400 return Sidebar::hide = -> if @transitioning or !@$element.hasClass('sidebar-open') return startEvent = $.Event('hide.bs.sidebar') @$element.trigger startEvent if startEvent.isDefaultPrevented() return @$element.removeClass 'sidebar-open' @transitioning = 1 complete = -> @transitioning = 0 @$element.trigger 'hidden.bs.sidebar' return if !$.support.transition return complete.call(this) @$element.one($.support.transition.end, $.proxy(complete, this)).emulateTransitionEnd 400 return Sidebar::toggle = -> @[if @$element.hasClass('sidebar-open') then 'hide' else 'show']() return old = $.fn.sidebar $.fn.sidebar = (option) -> @each -> $this = $(this) data = $this.data('bs.sidebar') options = $.extend({}, Sidebar.DEFAULTS, $this.data(), typeof options == 'object' and option) if !data and options.toggle and option == 'show' option = !option if !data $this.data 'bs.sidebar', data = new Sidebar(this, options) if typeof option == 'string' data[option]() return $.fn.sidebar.Constructor = Sidebar $.fn.collapse.noConflict = -> $.fn.sidebar = old this $(document).on 'click.bs.sidebar.data-api', '[data-toggle="sidebar"]', (e) -> $this = $(this) href = undefined target = $this.attr('data-target') or e.preventDefault() or (href = $this.attr('href')) and href.replace(/.*(?=#[^\s]+$)/, '') $target = $(target) data = $target.data('bs.sidebar') option = if data then 'toggle' else $this.data() $target.sidebar option return $('html').on 'click.bs.sidebar.autohide', (event) -> $this = $(event.target) isButtonOrSidebar = $this.is('.sidebar, [data-toggle="sidebar"]') or $this.parents('.sidebar, [data-toggle="sidebar"]').length if isButtonOrSidebar return else $target = $('.sidebar') $target.each (i, trgt) -> $trgt = $(trgt) if $trgt.data('bs.sidebar') and $trgt.hasClass('sidebar-open') $trgt.sidebar 'hide' return return return )(jQuery)
[ { "context": "pan class='person' up-data='{ \"age\": 18, \"name\": \"Bob\" }'>Bob</span>\n <span class='person' up-data", "end": 3214, "score": 0.9995779395103455, "start": 3211, "tag": "NAME", "value": "Bob" }, { "context": "s='person' up-data='{ \"age\": 18, \"name\": \"Bob\" ...
lib/assets/javascripts/unpoly/event.coffee
pfw/unpoly
0
###** Events ====== This module contains functions to [emit](/up.emit) and [observe](/up.on) DOM events. While the browser also has built-in functions to work with events, you will find Unpoly's functions to be very concise and feature-rich. ## Events emitted by Unpoly Most Unpoly features emit events that are prefixed with `up:`. Unpoly's own events are documented in their respective modules, for example: | Event | Module | |-----------------------|--------------------| | `up:link:follow` | `up.link` | | `up:form:submit` | `up.form` | | `up:layer:open` | `up.layer` | | `up:request:late` | `up.network` | @see up.on @see up.emit @module up.event ### up.event = do -> u = up.util e = up.element reset = -> # Resets the list of registered event listeners to the # moment when the framework was booted. for element in [window, document, e.root, document.body] up.EventListener.unbindNonDefault(element) ###** Listens to a [DOM event](https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Events) on `document` or a given element. `up.on()` has some quality of life improvements over [`Element#addEventListener()`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener): - You may pass a selector for [event delegation](https://davidwalsh.name/event-delegate). - The event target is automatically passed as a second argument. - You may register a listener to multiple events by passing a space-separated list of event name (e.g. `"click mousedown"`) - You may register a listener to multiple elements in a single `up.on()` call, by passing a [list](/up.util.isList) of elements. - You use an [`[up-data]`](/up-data) attribute to [attach structured data](/up.on#attaching-structured-data) to observed elements. If an `[up-data]` attribute is set, its value will automatically be parsed as JSON and passed as a third argument. \#\#\# Basic example The code below will call the listener when a `<a>` is clicked anywhere in the `document`: up.on('click', 'a', function(event, element) { console.log("Click on a link %o", element) }) You may also bind the listener to a given element instead of `document`: var form = document.querySelector('form') up.on(form, 'click', function(event, form) { console.log("Click within %o", form) }) \#\#\# Event delegation You may pass both an element and a selector for [event delegation](https://davidwalsh.name/event-delegate). The example below registers a single event listener to the given `form`, but only calls the listener when the clicked element is a `select` element: var form = document.querySelector('form') up.on(form, 'click', 'select', function(event, select) { console.log("Click on select %o within %o", select, form) }) \#\#\# Attaching structured data In case you want to attach structured data to the event you're observing, you can serialize the data to JSON and put it into an `[up-data]` attribute: <span class='person' up-data='{ "age": 18, "name": "Bob" }'>Bob</span> <span class='person' up-data='{ "age": 22, "name": "Jim" }'>Jim</span> The JSON will be parsed and handed to your event handler as a third argument: up.on('click', '.person', function(event, element, data) { console.log("This is %o who is %o years old", data.name, data.age) }) \#\#\# Unbinding an event listener `up.on()` returns a function that unbinds the event listeners when called: // Define the listener var listener = function(event) { ... } // Binding the listener returns an unbind function var unbind = up.on('click', listener) // Unbind the listener unbind() There is also a function [`up.off()`](/up.off) which you can use for the same purpose: // Define the listener var listener = function(event) { ... } // Bind the listener up.on('click', listener) // Unbind the listener up.off('click', listener) \#\#\# Binding to multiple elements You may register a listener to multiple elements in a single `up.on()` call, by passing a [list](/up.util.isList) of elements: ```javascript let allForms = document.querySelectorAll('form') up.on(allForms, 'submit', function(event, form) { console.log('Submitting form %o', form) }) ``` \#\#\# Binding to multiple event types You may register a listener to multiple event types by passing a space-separated list of event types: ```javascript let element = document.querySelector(...) up.on(element, 'mouseenter mouseleave', function(event) { console.log('Mouse entered or left') }) ``` @function up.on @param {Element|jQuery} [element=document] The element on which to register the event listener. If no element is given, the listener is registered on the `document`. @param {string|Array<string>} types The event types to bind to. Multiple event types may be passed as either a space-separated string or as an array of types. @param {string|Function():string} [selector] The selector of an element on which the event must be triggered. Omit the selector to listen to all events of the given type, regardless of the event target. If the selector is not known in advance you may also pass a function that returns the selector. The function is evaluated every time an event with the given type is observed. @param {boolean} [options.passive=false] Whether to register a [passive event listener](https://developers.google.com/web/updates/2016/06/passive-event-listeners). A passive event listener may not call `event.preventDefault()`. This in particular may improve the frame rate when registering `touchstart` and `touchmove` events. @param {boolean} [options.once=true] Whether the listener should run at most once. If `true` the listener will automatically be unbound after the first invocation. @param {Function(event, [element], [data])} listener The listener function that should be called. The function takes the affected element as a second argument. If the element has an [`up-data`](/up-data) attribute, its value is parsed as JSON and passed as a third argument. @return {Function()} A function that unbinds the event listeners when called. @stable ### bind = (args...) -> bindNow(args) ###** Listens to an event on `document` or a given element. The event handler is called with the event target as a [jQuery collection](https://learn.jquery.com/using-jquery-core/jquery-object/). If you're not using jQuery, use `up.on()` instead, which calls event handlers with a native element. \#\#\# Example ``` up.$on('click', 'a', function(event, $link) { console.log("Click on a link with destination %s", $element.attr('href')) }) ``` @function up.$on @param {Element|jQuery} [element=document] The element on which to register the event listener. If no element is given, the listener is registered on the `document`. @param {string} events A space-separated list of event names to bind to. @param {string} [selector] The selector of an element on which the event must be triggered. Omit the selector to listen to all events with that name, regardless of the event target. @param {boolean} [options.passive=false] Whether to register a [passive event listener](https://developers.google.com/web/updates/2016/06/passive-event-listeners). A passive event listener may not call `event.preventDefault()`. This in particular may improve the frame rate when registering `touchstart` and `touchmove` events. @param {Function(event, [element], [data])} listener The listener function that should be called. The function takes the affected element as the first argument). If the element has an [`up-data`](/up-data) attribute, its value is parsed as JSON and passed as a second argument. @return {Function()} A function that unbinds the event listeners when called. @stable ### $bind = (args...) -> bindNow(args, jQuery: true) bindNow = (args, options) -> up.EventListenerGroup.fromBindArgs(args, options).bind() ###** Unbinds an event listener previously bound with `up.on()`. \#\#\# Example Let's say you are listing to clicks on `.button` elements: var listener = function() { ... } up.on('click', '.button', listener) You can stop listening to these events like this: up.off('click', '.button', listener) @function up.off @param {Element|jQuery} [element=document] @param {string|Function(): string} events @param {string} [selector] @param {Function(event, [element], [data])} listener The listener function to unbind. Note that you must pass a reference to the same function reference that was passed to `up.on()` earlier. @stable ### unbind = (args...) -> up.EventListenerGroup.fromBindArgs(args).unbind() buildEmitter = (args) -> return up.EventEmitter.fromEmitArgs(args) ###** Emits a event with the given name and properties. The event will be triggered as an event on `document` or on the given element. Other code can subscribe to events with that name using [`Element#addEventListener()`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener) or [`up.on()`](/up.on). \#\#\# Example up.on('my:event', function(event) { console.log(event.foo) }) up.emit('my:event', { foo: 'bar' }) // Prints "bar" to the console @function up.emit @param {Element|jQuery} [target=document] The element on which the event is triggered. If omitted, the event will be emitted on the `document`. @param {string} eventType The event type, e.g. `my:event`. @param {Object} [props={}] A list of properties to become part of the event object that will be passed to listeners. @param {up.Layer|string|number} [props.layer] The [layer](/up.layer) on which to emit this event. If this property is set, the event will be emitted on the [layer's outmost element](/up.Layer.prototype.element). Also [up.layer.current](/up.layer.current) will be set to the given layer while event listeners are running. @param {string|Array} [props.log] A message to print to the [log](/up.log) when the event is emitted. Pass `false` to not log this event emission. @param {Element|jQuery} [props.target=document] The element on which the event is triggered. Alternatively the target element may be passed as the first argument. @stable ### emit = (args...) -> buildEmitter(args).emit() ###** Builds an event with the given type and properties. The returned event is not [emitted](/up.emit). \#\#\# Example let event = up.event.build('my:event', { foo: 'bar' }) console.log(event.type) // logs "my:event" console.log(event.foo) // logs "bar" console.log(event.defaultPrevented) // logs "false" up.emit(event) // emits the event @function up.event.build @param {string} [type] The event type. May also be passed as a property `{ type }`. @param {Object} [props={}] An object with event properties. @param {string} [props.type] The event type. May also be passed as a first string argument. @return {Event} @experimental ### build = (args...) -> props = u.extractOptions(args) type = args[0] || props.type || up.fail('Expected event type to be passed as string argument or { type } property') event = document.createEvent('Event') event.initEvent(type, true, true) # name, bubbles, cancelable u.assign(event, u.omit(props, ['type', 'target'])) # IE11 does not set { defaultPrevented: true } after #preventDefault() # was called on a custom event. # See discussion here: https://stackoverflow.com/questions/23349191 if up.browser.isIE11() originalPreventDefault = event.preventDefault event.preventDefault = -> # Even though we're swapping out defaultPrevented() with our own implementation, # we still need to call the original method to trigger the forwarding of up:click. originalPreventDefault.call(event) u.getter(event, 'defaultPrevented', -> true) return event ###** [Emits](/up.emit) the given event and throws an `AbortError` if it was prevented. @function up.event.assertEmitted @param {string} eventType @param {Object} eventProps @param {string|Array} [eventProps.message] @internal ### assertEmitted = (args...) -> buildEmitter(args).assertEmitted() ###** Registers an event listener to be called when the user presses the `Escape` key. \#\#\# Example ```javascript up.event.onEscape(function(event) { console.log('Escape pressed!') }) ``` @function up.event.onEscape @param {Function(Event)} listener The listener function that will be called when `Escape` is pressed. @experimental ### onEscape = (listener) -> return bind('keydown', (event) -> if wasEscapePressed(event) listener(event) ) ###** Returns whether the given keyboard event involved the ESC key. @function up.util.wasEscapePressed @param {Event} event @internal ### wasEscapePressed = (event) -> key = event.key # IE/Edge use 'Esc', other browsers use 'Escape' key == 'Escape' || key == 'Esc' ###** Prevents the event from being processed further. In detail: - It prevents the event from bubbling up the DOM tree. - It prevents other event handlers bound on the same element. - It prevents the event's default action. \#\#\# Example up.on('click', 'link.disabled', function(event) { up.event.halt(event) }) @function up.event.halt @param {Event} event @stable ### halt = (event) -> event.stopImmediatePropagation() event.preventDefault() ###** Runs the given callback when the the initial HTML document has been completely loaded. The callback is guaranteed to see the fully parsed DOM tree. This function does not wait for stylesheets, images or frames to finish loading. If `up.event.onReady()` is called after the initial document was loaded, the given callback is run immediately. @function up.event.onReady @param {Function} callback The function to call then the DOM tree is acessible. @experimental ### onReady = (callback) -> # Values are "loading", "interactive" and "completed". # https://developer.mozilla.org/en-US/docs/Web/API/Document/readyState if document.readyState != 'loading' callback() else document.addEventListener('DOMContentLoaded', callback) keyModifiers = ['metaKey', 'shiftKey', 'ctrlKey', 'altKey'] ###** @function up.event.isUnmodified @internal ### isUnmodified = (event) -> (u.isUndefined(event.button) || event.button == 0) && !u.some(keyModifiers, (modifier) -> event[modifier]) fork = (originalEvent, newType, copyKeys = []) -> newEvent = up.event.build(newType, u.pick(originalEvent, copyKeys)) newEvent.originalEvent = originalEvent # allow users to access other props through event.originalEvent.prop ['stopPropagation', 'stopImmediatePropagation', 'preventDefault'].forEach (key) -> originalMethod = newEvent[key] newEvent[key] = -> originalEvent[key]() return originalMethod.call(newEvent) if originalEvent.defaultPrevented newEvent.preventDefault() return newEvent ###** Emits the given event when this link is clicked. When the emitted event's default' is prevented, the original `click` event's default is also prevented. You may use this attribute to emit events when clicking on areas that are no hyperlinks, by setting it on an `<a>` element without a `[href]` attribute. \#\#\# Example This hyperlink will emit an `user:select` event when clicked: ```html <a href='/users/5' up-emit='user:select' up-emit-props='{ "id": 5, "firstName": "Alice" }'> Alice </a> <script> up.on('a', 'user:select', function(event) { console.log(event.firstName) // logs "Alice" event.preventDefault() // will prevent the link from being followed }) </script> ``` @selector a[up-emit] @param up-emit The type of the event to be emitted. @param [up-emit-props='{}'] The event properties, serialized as JSON. @stable ### executeEmitAttr = (event, element) -> return unless isUnmodified(event) eventType = e.attr(element, 'up-emit') eventProps = e.jsonAttr(element, 'up-emit-props') forkedEvent = fork(event, eventType) u.assign(forkedEvent, eventProps) up.emit(element, forkedEvent) # abortable = -> # signal = document.createElement('up-abort-signal') # abort = -> up.emit(signal, 'abort') # [abort, signal] bind 'up:click', 'a[up-emit]', executeEmitAttr bind 'up:framework:reset', reset on: bind # can't name symbols `on` in Coffeescript $on: $bind off: unbind # can't name symbols `off` in Coffeescript build: build emit: emit assertEmitted: assertEmitted onEscape: onEscape halt: halt onReady: onReady isUnmodified: isUnmodified fork: fork keyModifiers: keyModifiers up.on = up.event.on up.$on = up.event.$on up.off = up.event.off up.$off = up.event.off # it's the same as up.off() up.emit = up.event.emit
95486
###** Events ====== This module contains functions to [emit](/up.emit) and [observe](/up.on) DOM events. While the browser also has built-in functions to work with events, you will find Unpoly's functions to be very concise and feature-rich. ## Events emitted by Unpoly Most Unpoly features emit events that are prefixed with `up:`. Unpoly's own events are documented in their respective modules, for example: | Event | Module | |-----------------------|--------------------| | `up:link:follow` | `up.link` | | `up:form:submit` | `up.form` | | `up:layer:open` | `up.layer` | | `up:request:late` | `up.network` | @see up.on @see up.emit @module up.event ### up.event = do -> u = up.util e = up.element reset = -> # Resets the list of registered event listeners to the # moment when the framework was booted. for element in [window, document, e.root, document.body] up.EventListener.unbindNonDefault(element) ###** Listens to a [DOM event](https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Events) on `document` or a given element. `up.on()` has some quality of life improvements over [`Element#addEventListener()`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener): - You may pass a selector for [event delegation](https://davidwalsh.name/event-delegate). - The event target is automatically passed as a second argument. - You may register a listener to multiple events by passing a space-separated list of event name (e.g. `"click mousedown"`) - You may register a listener to multiple elements in a single `up.on()` call, by passing a [list](/up.util.isList) of elements. - You use an [`[up-data]`](/up-data) attribute to [attach structured data](/up.on#attaching-structured-data) to observed elements. If an `[up-data]` attribute is set, its value will automatically be parsed as JSON and passed as a third argument. \#\#\# Basic example The code below will call the listener when a `<a>` is clicked anywhere in the `document`: up.on('click', 'a', function(event, element) { console.log("Click on a link %o", element) }) You may also bind the listener to a given element instead of `document`: var form = document.querySelector('form') up.on(form, 'click', function(event, form) { console.log("Click within %o", form) }) \#\#\# Event delegation You may pass both an element and a selector for [event delegation](https://davidwalsh.name/event-delegate). The example below registers a single event listener to the given `form`, but only calls the listener when the clicked element is a `select` element: var form = document.querySelector('form') up.on(form, 'click', 'select', function(event, select) { console.log("Click on select %o within %o", select, form) }) \#\#\# Attaching structured data In case you want to attach structured data to the event you're observing, you can serialize the data to JSON and put it into an `[up-data]` attribute: <span class='person' up-data='{ "age": 18, "name": "<NAME>" }'><NAME></span> <span class='person' up-data='{ "age": 22, "name": "<NAME>" }'><NAME></span> The JSON will be parsed and handed to your event handler as a third argument: up.on('click', '.person', function(event, element, data) { console.log("This is %o who is %o years old", data.name, data.age) }) \#\#\# Unbinding an event listener `up.on()` returns a function that unbinds the event listeners when called: // Define the listener var listener = function(event) { ... } // Binding the listener returns an unbind function var unbind = up.on('click', listener) // Unbind the listener unbind() There is also a function [`up.off()`](/up.off) which you can use for the same purpose: // Define the listener var listener = function(event) { ... } // Bind the listener up.on('click', listener) // Unbind the listener up.off('click', listener) \#\#\# Binding to multiple elements You may register a listener to multiple elements in a single `up.on()` call, by passing a [list](/up.util.isList) of elements: ```javascript let allForms = document.querySelectorAll('form') up.on(allForms, 'submit', function(event, form) { console.log('Submitting form %o', form) }) ``` \#\#\# Binding to multiple event types You may register a listener to multiple event types by passing a space-separated list of event types: ```javascript let element = document.querySelector(...) up.on(element, 'mouseenter mouseleave', function(event) { console.log('Mouse entered or left') }) ``` @function up.on @param {Element|jQuery} [element=document] The element on which to register the event listener. If no element is given, the listener is registered on the `document`. @param {string|Array<string>} types The event types to bind to. Multiple event types may be passed as either a space-separated string or as an array of types. @param {string|Function():string} [selector] The selector of an element on which the event must be triggered. Omit the selector to listen to all events of the given type, regardless of the event target. If the selector is not known in advance you may also pass a function that returns the selector. The function is evaluated every time an event with the given type is observed. @param {boolean} [options.passive=false] Whether to register a [passive event listener](https://developers.google.com/web/updates/2016/06/passive-event-listeners). A passive event listener may not call `event.preventDefault()`. This in particular may improve the frame rate when registering `touchstart` and `touchmove` events. @param {boolean} [options.once=true] Whether the listener should run at most once. If `true` the listener will automatically be unbound after the first invocation. @param {Function(event, [element], [data])} listener The listener function that should be called. The function takes the affected element as a second argument. If the element has an [`up-data`](/up-data) attribute, its value is parsed as JSON and passed as a third argument. @return {Function()} A function that unbinds the event listeners when called. @stable ### bind = (args...) -> bindNow(args) ###** Listens to an event on `document` or a given element. The event handler is called with the event target as a [jQuery collection](https://learn.jquery.com/using-jquery-core/jquery-object/). If you're not using jQuery, use `up.on()` instead, which calls event handlers with a native element. \#\#\# Example ``` up.$on('click', 'a', function(event, $link) { console.log("Click on a link with destination %s", $element.attr('href')) }) ``` @function up.$on @param {Element|jQuery} [element=document] The element on which to register the event listener. If no element is given, the listener is registered on the `document`. @param {string} events A space-separated list of event names to bind to. @param {string} [selector] The selector of an element on which the event must be triggered. Omit the selector to listen to all events with that name, regardless of the event target. @param {boolean} [options.passive=false] Whether to register a [passive event listener](https://developers.google.com/web/updates/2016/06/passive-event-listeners). A passive event listener may not call `event.preventDefault()`. This in particular may improve the frame rate when registering `touchstart` and `touchmove` events. @param {Function(event, [element], [data])} listener The listener function that should be called. The function takes the affected element as the first argument). If the element has an [`up-data`](/up-data) attribute, its value is parsed as JSON and passed as a second argument. @return {Function()} A function that unbinds the event listeners when called. @stable ### $bind = (args...) -> bindNow(args, jQuery: true) bindNow = (args, options) -> up.EventListenerGroup.fromBindArgs(args, options).bind() ###** Unbinds an event listener previously bound with `up.on()`. \#\#\# Example Let's say you are listing to clicks on `.button` elements: var listener = function() { ... } up.on('click', '.button', listener) You can stop listening to these events like this: up.off('click', '.button', listener) @function up.off @param {Element|jQuery} [element=document] @param {string|Function(): string} events @param {string} [selector] @param {Function(event, [element], [data])} listener The listener function to unbind. Note that you must pass a reference to the same function reference that was passed to `up.on()` earlier. @stable ### unbind = (args...) -> up.EventListenerGroup.fromBindArgs(args).unbind() buildEmitter = (args) -> return up.EventEmitter.fromEmitArgs(args) ###** Emits a event with the given name and properties. The event will be triggered as an event on `document` or on the given element. Other code can subscribe to events with that name using [`Element#addEventListener()`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener) or [`up.on()`](/up.on). \#\#\# Example up.on('my:event', function(event) { console.log(event.foo) }) up.emit('my:event', { foo: 'bar' }) // Prints "bar" to the console @function up.emit @param {Element|jQuery} [target=document] The element on which the event is triggered. If omitted, the event will be emitted on the `document`. @param {string} eventType The event type, e.g. `my:event`. @param {Object} [props={}] A list of properties to become part of the event object that will be passed to listeners. @param {up.Layer|string|number} [props.layer] The [layer](/up.layer) on which to emit this event. If this property is set, the event will be emitted on the [layer's outmost element](/up.Layer.prototype.element). Also [up.layer.current](/up.layer.current) will be set to the given layer while event listeners are running. @param {string|Array} [props.log] A message to print to the [log](/up.log) when the event is emitted. Pass `false` to not log this event emission. @param {Element|jQuery} [props.target=document] The element on which the event is triggered. Alternatively the target element may be passed as the first argument. @stable ### emit = (args...) -> buildEmitter(args).emit() ###** Builds an event with the given type and properties. The returned event is not [emitted](/up.emit). \#\#\# Example let event = up.event.build('my:event', { foo: 'bar' }) console.log(event.type) // logs "my:event" console.log(event.foo) // logs "bar" console.log(event.defaultPrevented) // logs "false" up.emit(event) // emits the event @function up.event.build @param {string} [type] The event type. May also be passed as a property `{ type }`. @param {Object} [props={}] An object with event properties. @param {string} [props.type] The event type. May also be passed as a first string argument. @return {Event} @experimental ### build = (args...) -> props = u.extractOptions(args) type = args[0] || props.type || up.fail('Expected event type to be passed as string argument or { type } property') event = document.createEvent('Event') event.initEvent(type, true, true) # name, bubbles, cancelable u.assign(event, u.omit(props, ['type', 'target'])) # IE11 does not set { defaultPrevented: true } after #preventDefault() # was called on a custom event. # See discussion here: https://stackoverflow.com/questions/23349191 if up.browser.isIE11() originalPreventDefault = event.preventDefault event.preventDefault = -> # Even though we're swapping out defaultPrevented() with our own implementation, # we still need to call the original method to trigger the forwarding of up:click. originalPreventDefault.call(event) u.getter(event, 'defaultPrevented', -> true) return event ###** [Emits](/up.emit) the given event and throws an `AbortError` if it was prevented. @function up.event.assertEmitted @param {string} eventType @param {Object} eventProps @param {string|Array} [eventProps.message] @internal ### assertEmitted = (args...) -> buildEmitter(args).assertEmitted() ###** Registers an event listener to be called when the user presses the `Escape` key. \#\#\# Example ```javascript up.event.onEscape(function(event) { console.log('Escape pressed!') }) ``` @function up.event.onEscape @param {Function(Event)} listener The listener function that will be called when `Escape` is pressed. @experimental ### onEscape = (listener) -> return bind('keydown', (event) -> if wasEscapePressed(event) listener(event) ) ###** Returns whether the given keyboard event involved the ESC key. @function up.util.wasEscapePressed @param {Event} event @internal ### wasEscapePressed = (event) -> key = event.key # IE/Edge use 'Esc', other browsers use 'Escape' key == 'Escape' || key == 'Esc' ###** Prevents the event from being processed further. In detail: - It prevents the event from bubbling up the DOM tree. - It prevents other event handlers bound on the same element. - It prevents the event's default action. \#\#\# Example up.on('click', 'link.disabled', function(event) { up.event.halt(event) }) @function up.event.halt @param {Event} event @stable ### halt = (event) -> event.stopImmediatePropagation() event.preventDefault() ###** Runs the given callback when the the initial HTML document has been completely loaded. The callback is guaranteed to see the fully parsed DOM tree. This function does not wait for stylesheets, images or frames to finish loading. If `up.event.onReady()` is called after the initial document was loaded, the given callback is run immediately. @function up.event.onReady @param {Function} callback The function to call then the DOM tree is acessible. @experimental ### onReady = (callback) -> # Values are "loading", "interactive" and "completed". # https://developer.mozilla.org/en-US/docs/Web/API/Document/readyState if document.readyState != 'loading' callback() else document.addEventListener('DOMContentLoaded', callback) keyModifiers = ['metaKey', 'shiftKey', 'ctrlKey', 'altKey'] ###** @function up.event.isUnmodified @internal ### isUnmodified = (event) -> (u.isUndefined(event.button) || event.button == 0) && !u.some(keyModifiers, (modifier) -> event[modifier]) fork = (originalEvent, newType, copyKeys = []) -> newEvent = up.event.build(newType, u.pick(originalEvent, copyKeys)) newEvent.originalEvent = originalEvent # allow users to access other props through event.originalEvent.prop ['stopPropagation', 'stopImmediatePropagation', 'preventDefault'].forEach (key) -> originalMethod = newEvent[key] newEvent[key] = -> originalEvent[key]() return originalMethod.call(newEvent) if originalEvent.defaultPrevented newEvent.preventDefault() return newEvent ###** Emits the given event when this link is clicked. When the emitted event's default' is prevented, the original `click` event's default is also prevented. You may use this attribute to emit events when clicking on areas that are no hyperlinks, by setting it on an `<a>` element without a `[href]` attribute. \#\#\# Example This hyperlink will emit an `user:select` event when clicked: ```html <a href='/users/5' up-emit='user:select' up-emit-props='{ "id": 5, "firstName": "<NAME>" }'> <NAME> </a> <script> up.on('a', 'user:select', function(event) { console.log(event.firstName) // logs "<NAME>" event.preventDefault() // will prevent the link from being followed }) </script> ``` @selector a[up-emit] @param up-emit The type of the event to be emitted. @param [up-emit-props='{}'] The event properties, serialized as JSON. @stable ### executeEmitAttr = (event, element) -> return unless isUnmodified(event) eventType = e.attr(element, 'up-emit') eventProps = e.jsonAttr(element, 'up-emit-props') forkedEvent = fork(event, eventType) u.assign(forkedEvent, eventProps) up.emit(element, forkedEvent) # abortable = -> # signal = document.createElement('up-abort-signal') # abort = -> up.emit(signal, 'abort') # [abort, signal] bind 'up:click', 'a[up-emit]', executeEmitAttr bind 'up:framework:reset', reset on: bind # can't name symbols `on` in Coffeescript $on: $bind off: unbind # can't name symbols `off` in Coffeescript build: build emit: emit assertEmitted: assertEmitted onEscape: onEscape halt: halt onReady: onReady isUnmodified: isUnmodified fork: fork keyModifiers: keyModifiers up.on = up.event.on up.$on = up.event.$on up.off = up.event.off up.$off = up.event.off # it's the same as up.off() up.emit = up.event.emit
true
###** Events ====== This module contains functions to [emit](/up.emit) and [observe](/up.on) DOM events. While the browser also has built-in functions to work with events, you will find Unpoly's functions to be very concise and feature-rich. ## Events emitted by Unpoly Most Unpoly features emit events that are prefixed with `up:`. Unpoly's own events are documented in their respective modules, for example: | Event | Module | |-----------------------|--------------------| | `up:link:follow` | `up.link` | | `up:form:submit` | `up.form` | | `up:layer:open` | `up.layer` | | `up:request:late` | `up.network` | @see up.on @see up.emit @module up.event ### up.event = do -> u = up.util e = up.element reset = -> # Resets the list of registered event listeners to the # moment when the framework was booted. for element in [window, document, e.root, document.body] up.EventListener.unbindNonDefault(element) ###** Listens to a [DOM event](https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Events) on `document` or a given element. `up.on()` has some quality of life improvements over [`Element#addEventListener()`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener): - You may pass a selector for [event delegation](https://davidwalsh.name/event-delegate). - The event target is automatically passed as a second argument. - You may register a listener to multiple events by passing a space-separated list of event name (e.g. `"click mousedown"`) - You may register a listener to multiple elements in a single `up.on()` call, by passing a [list](/up.util.isList) of elements. - You use an [`[up-data]`](/up-data) attribute to [attach structured data](/up.on#attaching-structured-data) to observed elements. If an `[up-data]` attribute is set, its value will automatically be parsed as JSON and passed as a third argument. \#\#\# Basic example The code below will call the listener when a `<a>` is clicked anywhere in the `document`: up.on('click', 'a', function(event, element) { console.log("Click on a link %o", element) }) You may also bind the listener to a given element instead of `document`: var form = document.querySelector('form') up.on(form, 'click', function(event, form) { console.log("Click within %o", form) }) \#\#\# Event delegation You may pass both an element and a selector for [event delegation](https://davidwalsh.name/event-delegate). The example below registers a single event listener to the given `form`, but only calls the listener when the clicked element is a `select` element: var form = document.querySelector('form') up.on(form, 'click', 'select', function(event, select) { console.log("Click on select %o within %o", select, form) }) \#\#\# Attaching structured data In case you want to attach structured data to the event you're observing, you can serialize the data to JSON and put it into an `[up-data]` attribute: <span class='person' up-data='{ "age": 18, "name": "PI:NAME:<NAME>END_PI" }'>PI:NAME:<NAME>END_PI</span> <span class='person' up-data='{ "age": 22, "name": "PI:NAME:<NAME>END_PI" }'>PI:NAME:<NAME>END_PI</span> The JSON will be parsed and handed to your event handler as a third argument: up.on('click', '.person', function(event, element, data) { console.log("This is %o who is %o years old", data.name, data.age) }) \#\#\# Unbinding an event listener `up.on()` returns a function that unbinds the event listeners when called: // Define the listener var listener = function(event) { ... } // Binding the listener returns an unbind function var unbind = up.on('click', listener) // Unbind the listener unbind() There is also a function [`up.off()`](/up.off) which you can use for the same purpose: // Define the listener var listener = function(event) { ... } // Bind the listener up.on('click', listener) // Unbind the listener up.off('click', listener) \#\#\# Binding to multiple elements You may register a listener to multiple elements in a single `up.on()` call, by passing a [list](/up.util.isList) of elements: ```javascript let allForms = document.querySelectorAll('form') up.on(allForms, 'submit', function(event, form) { console.log('Submitting form %o', form) }) ``` \#\#\# Binding to multiple event types You may register a listener to multiple event types by passing a space-separated list of event types: ```javascript let element = document.querySelector(...) up.on(element, 'mouseenter mouseleave', function(event) { console.log('Mouse entered or left') }) ``` @function up.on @param {Element|jQuery} [element=document] The element on which to register the event listener. If no element is given, the listener is registered on the `document`. @param {string|Array<string>} types The event types to bind to. Multiple event types may be passed as either a space-separated string or as an array of types. @param {string|Function():string} [selector] The selector of an element on which the event must be triggered. Omit the selector to listen to all events of the given type, regardless of the event target. If the selector is not known in advance you may also pass a function that returns the selector. The function is evaluated every time an event with the given type is observed. @param {boolean} [options.passive=false] Whether to register a [passive event listener](https://developers.google.com/web/updates/2016/06/passive-event-listeners). A passive event listener may not call `event.preventDefault()`. This in particular may improve the frame rate when registering `touchstart` and `touchmove` events. @param {boolean} [options.once=true] Whether the listener should run at most once. If `true` the listener will automatically be unbound after the first invocation. @param {Function(event, [element], [data])} listener The listener function that should be called. The function takes the affected element as a second argument. If the element has an [`up-data`](/up-data) attribute, its value is parsed as JSON and passed as a third argument. @return {Function()} A function that unbinds the event listeners when called. @stable ### bind = (args...) -> bindNow(args) ###** Listens to an event on `document` or a given element. The event handler is called with the event target as a [jQuery collection](https://learn.jquery.com/using-jquery-core/jquery-object/). If you're not using jQuery, use `up.on()` instead, which calls event handlers with a native element. \#\#\# Example ``` up.$on('click', 'a', function(event, $link) { console.log("Click on a link with destination %s", $element.attr('href')) }) ``` @function up.$on @param {Element|jQuery} [element=document] The element on which to register the event listener. If no element is given, the listener is registered on the `document`. @param {string} events A space-separated list of event names to bind to. @param {string} [selector] The selector of an element on which the event must be triggered. Omit the selector to listen to all events with that name, regardless of the event target. @param {boolean} [options.passive=false] Whether to register a [passive event listener](https://developers.google.com/web/updates/2016/06/passive-event-listeners). A passive event listener may not call `event.preventDefault()`. This in particular may improve the frame rate when registering `touchstart` and `touchmove` events. @param {Function(event, [element], [data])} listener The listener function that should be called. The function takes the affected element as the first argument). If the element has an [`up-data`](/up-data) attribute, its value is parsed as JSON and passed as a second argument. @return {Function()} A function that unbinds the event listeners when called. @stable ### $bind = (args...) -> bindNow(args, jQuery: true) bindNow = (args, options) -> up.EventListenerGroup.fromBindArgs(args, options).bind() ###** Unbinds an event listener previously bound with `up.on()`. \#\#\# Example Let's say you are listing to clicks on `.button` elements: var listener = function() { ... } up.on('click', '.button', listener) You can stop listening to these events like this: up.off('click', '.button', listener) @function up.off @param {Element|jQuery} [element=document] @param {string|Function(): string} events @param {string} [selector] @param {Function(event, [element], [data])} listener The listener function to unbind. Note that you must pass a reference to the same function reference that was passed to `up.on()` earlier. @stable ### unbind = (args...) -> up.EventListenerGroup.fromBindArgs(args).unbind() buildEmitter = (args) -> return up.EventEmitter.fromEmitArgs(args) ###** Emits a event with the given name and properties. The event will be triggered as an event on `document` or on the given element. Other code can subscribe to events with that name using [`Element#addEventListener()`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener) or [`up.on()`](/up.on). \#\#\# Example up.on('my:event', function(event) { console.log(event.foo) }) up.emit('my:event', { foo: 'bar' }) // Prints "bar" to the console @function up.emit @param {Element|jQuery} [target=document] The element on which the event is triggered. If omitted, the event will be emitted on the `document`. @param {string} eventType The event type, e.g. `my:event`. @param {Object} [props={}] A list of properties to become part of the event object that will be passed to listeners. @param {up.Layer|string|number} [props.layer] The [layer](/up.layer) on which to emit this event. If this property is set, the event will be emitted on the [layer's outmost element](/up.Layer.prototype.element). Also [up.layer.current](/up.layer.current) will be set to the given layer while event listeners are running. @param {string|Array} [props.log] A message to print to the [log](/up.log) when the event is emitted. Pass `false` to not log this event emission. @param {Element|jQuery} [props.target=document] The element on which the event is triggered. Alternatively the target element may be passed as the first argument. @stable ### emit = (args...) -> buildEmitter(args).emit() ###** Builds an event with the given type and properties. The returned event is not [emitted](/up.emit). \#\#\# Example let event = up.event.build('my:event', { foo: 'bar' }) console.log(event.type) // logs "my:event" console.log(event.foo) // logs "bar" console.log(event.defaultPrevented) // logs "false" up.emit(event) // emits the event @function up.event.build @param {string} [type] The event type. May also be passed as a property `{ type }`. @param {Object} [props={}] An object with event properties. @param {string} [props.type] The event type. May also be passed as a first string argument. @return {Event} @experimental ### build = (args...) -> props = u.extractOptions(args) type = args[0] || props.type || up.fail('Expected event type to be passed as string argument or { type } property') event = document.createEvent('Event') event.initEvent(type, true, true) # name, bubbles, cancelable u.assign(event, u.omit(props, ['type', 'target'])) # IE11 does not set { defaultPrevented: true } after #preventDefault() # was called on a custom event. # See discussion here: https://stackoverflow.com/questions/23349191 if up.browser.isIE11() originalPreventDefault = event.preventDefault event.preventDefault = -> # Even though we're swapping out defaultPrevented() with our own implementation, # we still need to call the original method to trigger the forwarding of up:click. originalPreventDefault.call(event) u.getter(event, 'defaultPrevented', -> true) return event ###** [Emits](/up.emit) the given event and throws an `AbortError` if it was prevented. @function up.event.assertEmitted @param {string} eventType @param {Object} eventProps @param {string|Array} [eventProps.message] @internal ### assertEmitted = (args...) -> buildEmitter(args).assertEmitted() ###** Registers an event listener to be called when the user presses the `Escape` key. \#\#\# Example ```javascript up.event.onEscape(function(event) { console.log('Escape pressed!') }) ``` @function up.event.onEscape @param {Function(Event)} listener The listener function that will be called when `Escape` is pressed. @experimental ### onEscape = (listener) -> return bind('keydown', (event) -> if wasEscapePressed(event) listener(event) ) ###** Returns whether the given keyboard event involved the ESC key. @function up.util.wasEscapePressed @param {Event} event @internal ### wasEscapePressed = (event) -> key = event.key # IE/Edge use 'Esc', other browsers use 'Escape' key == 'Escape' || key == 'Esc' ###** Prevents the event from being processed further. In detail: - It prevents the event from bubbling up the DOM tree. - It prevents other event handlers bound on the same element. - It prevents the event's default action. \#\#\# Example up.on('click', 'link.disabled', function(event) { up.event.halt(event) }) @function up.event.halt @param {Event} event @stable ### halt = (event) -> event.stopImmediatePropagation() event.preventDefault() ###** Runs the given callback when the the initial HTML document has been completely loaded. The callback is guaranteed to see the fully parsed DOM tree. This function does not wait for stylesheets, images or frames to finish loading. If `up.event.onReady()` is called after the initial document was loaded, the given callback is run immediately. @function up.event.onReady @param {Function} callback The function to call then the DOM tree is acessible. @experimental ### onReady = (callback) -> # Values are "loading", "interactive" and "completed". # https://developer.mozilla.org/en-US/docs/Web/API/Document/readyState if document.readyState != 'loading' callback() else document.addEventListener('DOMContentLoaded', callback) keyModifiers = ['metaKey', 'shiftKey', 'ctrlKey', 'altKey'] ###** @function up.event.isUnmodified @internal ### isUnmodified = (event) -> (u.isUndefined(event.button) || event.button == 0) && !u.some(keyModifiers, (modifier) -> event[modifier]) fork = (originalEvent, newType, copyKeys = []) -> newEvent = up.event.build(newType, u.pick(originalEvent, copyKeys)) newEvent.originalEvent = originalEvent # allow users to access other props through event.originalEvent.prop ['stopPropagation', 'stopImmediatePropagation', 'preventDefault'].forEach (key) -> originalMethod = newEvent[key] newEvent[key] = -> originalEvent[key]() return originalMethod.call(newEvent) if originalEvent.defaultPrevented newEvent.preventDefault() return newEvent ###** Emits the given event when this link is clicked. When the emitted event's default' is prevented, the original `click` event's default is also prevented. You may use this attribute to emit events when clicking on areas that are no hyperlinks, by setting it on an `<a>` element without a `[href]` attribute. \#\#\# Example This hyperlink will emit an `user:select` event when clicked: ```html <a href='/users/5' up-emit='user:select' up-emit-props='{ "id": 5, "firstName": "PI:NAME:<NAME>END_PI" }'> PI:NAME:<NAME>END_PI </a> <script> up.on('a', 'user:select', function(event) { console.log(event.firstName) // logs "PI:NAME:<NAME>END_PI" event.preventDefault() // will prevent the link from being followed }) </script> ``` @selector a[up-emit] @param up-emit The type of the event to be emitted. @param [up-emit-props='{}'] The event properties, serialized as JSON. @stable ### executeEmitAttr = (event, element) -> return unless isUnmodified(event) eventType = e.attr(element, 'up-emit') eventProps = e.jsonAttr(element, 'up-emit-props') forkedEvent = fork(event, eventType) u.assign(forkedEvent, eventProps) up.emit(element, forkedEvent) # abortable = -> # signal = document.createElement('up-abort-signal') # abort = -> up.emit(signal, 'abort') # [abort, signal] bind 'up:click', 'a[up-emit]', executeEmitAttr bind 'up:framework:reset', reset on: bind # can't name symbols `on` in Coffeescript $on: $bind off: unbind # can't name symbols `off` in Coffeescript build: build emit: emit assertEmitted: assertEmitted onEscape: onEscape halt: halt onReady: onReady isUnmodified: isUnmodified fork: fork keyModifiers: keyModifiers up.on = up.event.on up.$on = up.event.$on up.off = up.event.off up.$off = up.event.off # it's the same as up.off() up.emit = up.event.emit
[ { "context": "rl = Steedos.absoluteUrl(\"/am/forms?sync_token=#{(new Date()).getTime() / 1000}\")\n\t\tdata = {}\n\t\tform.id = form._id\n\t\tdata['Forms", "end": 618, "score": 0.8757158517837524, "start": 590, "tag": "KEY", "value": "new Date()).getTime() / 1000" } ]
creator/packages/steedos-app-workflow/client/design/form_design.coffee
baozhoutao/steedos-platform
10
Template.formDesign.helpers form: ()-> return Creator.odata.get("forms", Template.instance().data.formId) Template.formDesign.events 'click .btn-confirm': (e, t)-> console.log('click .btn-confirm'); data = $("#fb-editor").data('formBuilder').actions.getData() formFields = Creator.formBuilder.transformFormFieldsOut(data) validate = Creator.formBuilder.validateFormFields formFields if !validate return form = Creator.odata.get("forms", t.data.formId) delete form.historys form.current.fields = formFields url = Steedos.absoluteUrl("/am/forms?sync_token=#{(new Date()).getTime() / 1000}") data = {} form.id = form._id data['Forms'] = [form] $.ajax type: "put" url: url data: JSON.stringify(data) dataType: 'json' contentType: "application/json" processData: false beforeSend: (request) -> request.setRequestHeader('X-User-Id', Meteor.userId()) request.setRequestHeader('X-Auth-Token', Accounts._storedLoginToken()) success: (data) -> toastr.success("修改成功") Modal.hide(t) error: (jqXHR, textStatus, errorThrown) -> if jqXHR.status == 504 toastr?.error?(TAPi18n.__('连接超时,请稍后再试')) else if(jqXHR.responseJSON) error = jqXHR.responseJSON.error console.error error if error.reason toastr?.error?(TAPi18n.__(error.reason)) else if error.message toastr?.error?(TAPi18n.__(error.message)) else toastr?.error?(error) else toastr?.error?(jqXHR.responseText)
35146
Template.formDesign.helpers form: ()-> return Creator.odata.get("forms", Template.instance().data.formId) Template.formDesign.events 'click .btn-confirm': (e, t)-> console.log('click .btn-confirm'); data = $("#fb-editor").data('formBuilder').actions.getData() formFields = Creator.formBuilder.transformFormFieldsOut(data) validate = Creator.formBuilder.validateFormFields formFields if !validate return form = Creator.odata.get("forms", t.data.formId) delete form.historys form.current.fields = formFields url = Steedos.absoluteUrl("/am/forms?sync_token=#{(<KEY>}") data = {} form.id = form._id data['Forms'] = [form] $.ajax type: "put" url: url data: JSON.stringify(data) dataType: 'json' contentType: "application/json" processData: false beforeSend: (request) -> request.setRequestHeader('X-User-Id', Meteor.userId()) request.setRequestHeader('X-Auth-Token', Accounts._storedLoginToken()) success: (data) -> toastr.success("修改成功") Modal.hide(t) error: (jqXHR, textStatus, errorThrown) -> if jqXHR.status == 504 toastr?.error?(TAPi18n.__('连接超时,请稍后再试')) else if(jqXHR.responseJSON) error = jqXHR.responseJSON.error console.error error if error.reason toastr?.error?(TAPi18n.__(error.reason)) else if error.message toastr?.error?(TAPi18n.__(error.message)) else toastr?.error?(error) else toastr?.error?(jqXHR.responseText)
true
Template.formDesign.helpers form: ()-> return Creator.odata.get("forms", Template.instance().data.formId) Template.formDesign.events 'click .btn-confirm': (e, t)-> console.log('click .btn-confirm'); data = $("#fb-editor").data('formBuilder').actions.getData() formFields = Creator.formBuilder.transformFormFieldsOut(data) validate = Creator.formBuilder.validateFormFields formFields if !validate return form = Creator.odata.get("forms", t.data.formId) delete form.historys form.current.fields = formFields url = Steedos.absoluteUrl("/am/forms?sync_token=#{(PI:KEY:<KEY>END_PI}") data = {} form.id = form._id data['Forms'] = [form] $.ajax type: "put" url: url data: JSON.stringify(data) dataType: 'json' contentType: "application/json" processData: false beforeSend: (request) -> request.setRequestHeader('X-User-Id', Meteor.userId()) request.setRequestHeader('X-Auth-Token', Accounts._storedLoginToken()) success: (data) -> toastr.success("修改成功") Modal.hide(t) error: (jqXHR, textStatus, errorThrown) -> if jqXHR.status == 504 toastr?.error?(TAPi18n.__('连接超时,请稍后再试')) else if(jqXHR.responseJSON) error = jqXHR.responseJSON.error console.error error if error.reason toastr?.error?(TAPi18n.__(error.reason)) else if error.message toastr?.error?(TAPi18n.__(error.message)) else toastr?.error?(error) else toastr?.error?(jqXHR.responseText)
[ { "context": "] - show the bottom n (default: 5)\n#\n# Author:\n# D. Stuart Freeman (@stuartf) https://github.com/stuartf\n# Andy Be", "end": 483, "score": 0.9998716115951538, "start": 466, "tag": "NAME", "value": "D. Stuart Freeman" }, { "context": "m n (default: 5)\n#\n# Author...
src/karma-classic.coffee
robertsteilberg/hubot-karma-classic
0
# Description: # Track arbitrary karma # # Dependencies: # None # # Configuration: # None # # Commands: # <thing>++ - give thing some karma # <thing>-- - take away some of thing's karma # hubot karma <thing> - check thing's karma (if <thing> is omitted, show the top 5) # hubot karma empty <thing> - empty a thing's karma # hubot karma best [n] - show the top n (default: 5) # hubot karma worst [n] - show the bottom n (default: 5) # # Author: # D. Stuart Freeman (@stuartf) https://github.com/stuartf # Andy Beger (@abeger) https://github.com/abeger class Karma constructor: (@robot) -> @cache = {} @increment_responses = [ "+1!", "gained a level!", "is on the rise!", "leveled up!" ] @decrement_responses = [ "took a hit! Ouch.", "took a dive.", "lost a life.", "lost a level." ] @robot.brain.on 'loaded', => if @robot.brain.data.karma @cache = @robot.brain.data.karma kill: (thing) -> delete @cache[thing] @robot.brain.data.karma = @cache increment: (thing) -> @cache[thing] ?= 0 @cache[thing] += 1 @robot.brain.data.karma = @cache decrement: (thing) -> @cache[thing] ?= 0 @cache[thing] -= 1 @robot.brain.data.karma = @cache assign: (thing, val) -> @cache[thing] ?= 0 @cache[thing] = val @robot.brain.data.karma = @cache incrementResponse: -> @increment_responses[Math.floor(Math.random() * @increment_responses.length)] decrementResponse: -> @decrement_responses[Math.floor(Math.random() * @decrement_responses.length)] get: (thing) -> k = if @cache[thing] then @cache[thing] else 0 return k sort: -> s = [] for key, val of @cache s.push({ name: key, karma: val }) s.sort (a, b) -> b.karma - a.karma top: (n = 5) => sorted = @sort() sorted.slice(0, n) bottom: (n = 5) => sorted = @sort() sorted.slice(-n).reverse() module.exports = (robot) -> karma = new Karma robot ### # Listen for "++" messages and increment ### robot.hear /@?(\S+[^+\s])\+\+(\s|$)/, (msg) -> subject = msg.match[1].toLowerCase() if subject == "rob" num = 0 if num # msg.send "https://i.imgur.com/zFC8Pp4.jpg" msg.send(rickroll()) else # msg.send "That didn't work." msg.send(rickroll()) else karma.increment subject # msg.send "#{subject} #{karma.incrementResponse()} (Karma: #{karma.get(subject)})" msg.send(rickroll()) ### # Listen for "--" messages and decrement ### robot.hear /@?(\S+[^-\s])--(\s|$)/, (msg) -> subject = msg.match[1].toLowerCase() if subject == "rob" num = 0 if num # msg.send "https://media.giphy.com/media/Mir5fnHxvXrTa/giphy.gif" msg.send(rickroll()) else # msg.send "That didn't work." msg.send(rickroll()) else # avoid catching HTML comments unless subject[-2..] == "<!" karma.decrement subject # msg.send "#{subject} #{karma.decrementResponse()} (Karma: #{karma.get(subject)})" msg.send(rickroll()) ### # Listen for "karma empty x" and empty x's karma ### robot.respond /karma empty ?(\S+[^-\s])$/i, (msg) -> subject = msg.match[1].toLowerCase() karma.kill subject # msg.send "#{subject} has had its karma scattered to the winds." msg.send(rickroll()) ### # Function that handles best and worst list # @param msg The message to be parsed # @param title The title of the list to be returned # @param rankingFunction The function to call to get the ranking list ### parseListMessage = (msg, title, rankingFunction) -> count = if msg.match.length > 1 then msg.match[1] else null verbiage = [title] if count? verbiage[0] = verbiage[0].concat(" ", count.toString()) for item, rank in rankingFunction(count) verbiage.push "#{rank + 1}. #{item.name} - #{item.karma}" # msg.send verbiage.join("\n") msg.send(rickroll()) ### # Listen for "karma best [n]" and return the top n rankings ### robot.respond /karma best\s*(\d+)?$/i, (msg) -> parseData = parseListMessage(msg, "The Best", karma.top) ### # Listen for "karma worst [n]" and return the bottom n rankings ### robot.respond /karma worst\s*(\d+)?$/i, (msg) -> parseData = parseListMessage(msg, "The Worst", karma.bottom) ### # Listen for "karma x" and return karma for x ### robot.respond /karma (\S+[^-\s])$/i, (msg) -> match = msg.match[1].toLowerCase() if not (match in ["best", "worst"]) if match == "rob" # msg.send "Nice try." msg.send(rickroll()) else # msg.send "\"#{match}\" has #{karma.get(match)} karma. You must be proud." msg.send(rickroll()) ### # Listen for "karma set x val" and set x to karma ### robot.respond /karma set (\S+[^-\s]) (-?\d+)$/i, (msg) -> subject = msg.match[1].toLowerCase() val = +msg.match[2] karma.assign subject, val rickroll = -> num = Math.floor(Math.random() * 11) v = Math.floor(Math.random() * 10000) result = switch num when 0 then "https://media.giphy.com/media/629l2uUvy0uyc/giphy.gif" when 1 then "https://media.giphy.com/media/2EibPB1gfjHy0/giphy.gif" when 2 then "https://media.giphy.com/media/quXLseRWeh928/giphy.gif" when 3 then "https://media.giphy.com/media/P4SxYsjDqQwM0/giphy.gif" when 4 then "https://media.giphy.com/media/P4SxYsjDqQwM0/giphy.gif" when 5 then "https://media.giphy.com/media/LrmU6jXIjwziE/giphy.gif" when 6 then "https://media.giphy.com/media/sXX6ZPYWMNkwU/giphy.gif" when 7 then "https://media.giphy.com/media/6LG8fcerztuxy/giphy.gif" when 8 then "https://media.giphy.com/media/g7GKcSzwQfugw/giphy.gif" when 9 then "https://media.giphy.com/media/lgcUUCXgC8mEo/giphy.gif" when 10 then "https://media.giphy.com/media/4SoPtOQAOANMs/giphy.gif" result + "?v=" + v
49634
# Description: # Track arbitrary karma # # Dependencies: # None # # Configuration: # None # # Commands: # <thing>++ - give thing some karma # <thing>-- - take away some of thing's karma # hubot karma <thing> - check thing's karma (if <thing> is omitted, show the top 5) # hubot karma empty <thing> - empty a thing's karma # hubot karma best [n] - show the top n (default: 5) # hubot karma worst [n] - show the bottom n (default: 5) # # Author: # <NAME> (@stuartf) https://github.com/stuartf # <NAME> (@abeger) https://github.com/abeger class Karma constructor: (@robot) -> @cache = {} @increment_responses = [ "+1!", "gained a level!", "is on the rise!", "leveled up!" ] @decrement_responses = [ "took a hit! Ouch.", "took a dive.", "lost a life.", "lost a level." ] @robot.brain.on 'loaded', => if @robot.brain.data.karma @cache = @robot.brain.data.karma kill: (thing) -> delete @cache[thing] @robot.brain.data.karma = @cache increment: (thing) -> @cache[thing] ?= 0 @cache[thing] += 1 @robot.brain.data.karma = @cache decrement: (thing) -> @cache[thing] ?= 0 @cache[thing] -= 1 @robot.brain.data.karma = @cache assign: (thing, val) -> @cache[thing] ?= 0 @cache[thing] = val @robot.brain.data.karma = @cache incrementResponse: -> @increment_responses[Math.floor(Math.random() * @increment_responses.length)] decrementResponse: -> @decrement_responses[Math.floor(Math.random() * @decrement_responses.length)] get: (thing) -> k = if @cache[thing] then @cache[thing] else 0 return k sort: -> s = [] for key, val of @cache s.push({ name: key, karma: val }) s.sort (a, b) -> b.karma - a.karma top: (n = 5) => sorted = @sort() sorted.slice(0, n) bottom: (n = 5) => sorted = @sort() sorted.slice(-n).reverse() module.exports = (robot) -> karma = new Karma robot ### # Listen for "++" messages and increment ### robot.hear /@?(\S+[^+\s])\+\+(\s|$)/, (msg) -> subject = msg.match[1].toLowerCase() if subject == "rob" num = 0 if num # msg.send "https://i.imgur.com/zFC8Pp4.jpg" msg.send(rickroll()) else # msg.send "That didn't work." msg.send(rickroll()) else karma.increment subject # msg.send "#{subject} #{karma.incrementResponse()} (Karma: #{karma.get(subject)})" msg.send(rickroll()) ### # Listen for "--" messages and decrement ### robot.hear /@?(\S+[^-\s])--(\s|$)/, (msg) -> subject = msg.match[1].toLowerCase() if subject == "rob" num = 0 if num # msg.send "https://media.giphy.com/media/Mir5fnHxvXrTa/giphy.gif" msg.send(rickroll()) else # msg.send "That didn't work." msg.send(rickroll()) else # avoid catching HTML comments unless subject[-2..] == "<!" karma.decrement subject # msg.send "#{subject} #{karma.decrementResponse()} (Karma: #{karma.get(subject)})" msg.send(rickroll()) ### # Listen for "karma empty x" and empty x's karma ### robot.respond /karma empty ?(\S+[^-\s])$/i, (msg) -> subject = msg.match[1].toLowerCase() karma.kill subject # msg.send "#{subject} has had its karma scattered to the winds." msg.send(rickroll()) ### # Function that handles best and worst list # @param msg The message to be parsed # @param title The title of the list to be returned # @param rankingFunction The function to call to get the ranking list ### parseListMessage = (msg, title, rankingFunction) -> count = if msg.match.length > 1 then msg.match[1] else null verbiage = [title] if count? verbiage[0] = verbiage[0].concat(" ", count.toString()) for item, rank in rankingFunction(count) verbiage.push "#{rank + 1}. #{item.name} - #{item.karma}" # msg.send verbiage.join("\n") msg.send(rickroll()) ### # Listen for "karma best [n]" and return the top n rankings ### robot.respond /karma best\s*(\d+)?$/i, (msg) -> parseData = parseListMessage(msg, "The Best", karma.top) ### # Listen for "karma worst [n]" and return the bottom n rankings ### robot.respond /karma worst\s*(\d+)?$/i, (msg) -> parseData = parseListMessage(msg, "The Worst", karma.bottom) ### # Listen for "karma x" and return karma for x ### robot.respond /karma (\S+[^-\s])$/i, (msg) -> match = msg.match[1].toLowerCase() if not (match in ["best", "worst"]) if match == "rob" # msg.send "Nice try." msg.send(rickroll()) else # msg.send "\"#{match}\" has #{karma.get(match)} karma. You must be proud." msg.send(rickroll()) ### # Listen for "karma set x val" and set x to karma ### robot.respond /karma set (\S+[^-\s]) (-?\d+)$/i, (msg) -> subject = msg.match[1].toLowerCase() val = +msg.match[2] karma.assign subject, val rickroll = -> num = Math.floor(Math.random() * 11) v = Math.floor(Math.random() * 10000) result = switch num when 0 then "https://media.giphy.com/media/629l2uUvy0uyc/giphy.gif" when 1 then "https://media.giphy.com/media/2EibPB1gfjHy0/giphy.gif" when 2 then "https://media.giphy.com/media/quXLseRWeh928/giphy.gif" when 3 then "https://media.giphy.com/media/P4SxYsjDqQwM0/giphy.gif" when 4 then "https://media.giphy.com/media/P4SxYsjDqQwM0/giphy.gif" when 5 then "https://media.giphy.com/media/LrmU6jXIjwziE/giphy.gif" when 6 then "https://media.giphy.com/media/sXX6ZPYWMNkwU/giphy.gif" when 7 then "https://media.giphy.com/media/6LG8fcerztuxy/giphy.gif" when 8 then "https://media.giphy.com/media/g7GKcSzwQfugw/giphy.gif" when 9 then "https://media.giphy.com/media/lgcUUCXgC8mEo/giphy.gif" when 10 then "https://media.giphy.com/media/4SoPtOQAOANMs/giphy.gif" result + "?v=" + v
true
# Description: # Track arbitrary karma # # Dependencies: # None # # Configuration: # None # # Commands: # <thing>++ - give thing some karma # <thing>-- - take away some of thing's karma # hubot karma <thing> - check thing's karma (if <thing> is omitted, show the top 5) # hubot karma empty <thing> - empty a thing's karma # hubot karma best [n] - show the top n (default: 5) # hubot karma worst [n] - show the bottom n (default: 5) # # Author: # PI:NAME:<NAME>END_PI (@stuartf) https://github.com/stuartf # PI:NAME:<NAME>END_PI (@abeger) https://github.com/abeger class Karma constructor: (@robot) -> @cache = {} @increment_responses = [ "+1!", "gained a level!", "is on the rise!", "leveled up!" ] @decrement_responses = [ "took a hit! Ouch.", "took a dive.", "lost a life.", "lost a level." ] @robot.brain.on 'loaded', => if @robot.brain.data.karma @cache = @robot.brain.data.karma kill: (thing) -> delete @cache[thing] @robot.brain.data.karma = @cache increment: (thing) -> @cache[thing] ?= 0 @cache[thing] += 1 @robot.brain.data.karma = @cache decrement: (thing) -> @cache[thing] ?= 0 @cache[thing] -= 1 @robot.brain.data.karma = @cache assign: (thing, val) -> @cache[thing] ?= 0 @cache[thing] = val @robot.brain.data.karma = @cache incrementResponse: -> @increment_responses[Math.floor(Math.random() * @increment_responses.length)] decrementResponse: -> @decrement_responses[Math.floor(Math.random() * @decrement_responses.length)] get: (thing) -> k = if @cache[thing] then @cache[thing] else 0 return k sort: -> s = [] for key, val of @cache s.push({ name: key, karma: val }) s.sort (a, b) -> b.karma - a.karma top: (n = 5) => sorted = @sort() sorted.slice(0, n) bottom: (n = 5) => sorted = @sort() sorted.slice(-n).reverse() module.exports = (robot) -> karma = new Karma robot ### # Listen for "++" messages and increment ### robot.hear /@?(\S+[^+\s])\+\+(\s|$)/, (msg) -> subject = msg.match[1].toLowerCase() if subject == "rob" num = 0 if num # msg.send "https://i.imgur.com/zFC8Pp4.jpg" msg.send(rickroll()) else # msg.send "That didn't work." msg.send(rickroll()) else karma.increment subject # msg.send "#{subject} #{karma.incrementResponse()} (Karma: #{karma.get(subject)})" msg.send(rickroll()) ### # Listen for "--" messages and decrement ### robot.hear /@?(\S+[^-\s])--(\s|$)/, (msg) -> subject = msg.match[1].toLowerCase() if subject == "rob" num = 0 if num # msg.send "https://media.giphy.com/media/Mir5fnHxvXrTa/giphy.gif" msg.send(rickroll()) else # msg.send "That didn't work." msg.send(rickroll()) else # avoid catching HTML comments unless subject[-2..] == "<!" karma.decrement subject # msg.send "#{subject} #{karma.decrementResponse()} (Karma: #{karma.get(subject)})" msg.send(rickroll()) ### # Listen for "karma empty x" and empty x's karma ### robot.respond /karma empty ?(\S+[^-\s])$/i, (msg) -> subject = msg.match[1].toLowerCase() karma.kill subject # msg.send "#{subject} has had its karma scattered to the winds." msg.send(rickroll()) ### # Function that handles best and worst list # @param msg The message to be parsed # @param title The title of the list to be returned # @param rankingFunction The function to call to get the ranking list ### parseListMessage = (msg, title, rankingFunction) -> count = if msg.match.length > 1 then msg.match[1] else null verbiage = [title] if count? verbiage[0] = verbiage[0].concat(" ", count.toString()) for item, rank in rankingFunction(count) verbiage.push "#{rank + 1}. #{item.name} - #{item.karma}" # msg.send verbiage.join("\n") msg.send(rickroll()) ### # Listen for "karma best [n]" and return the top n rankings ### robot.respond /karma best\s*(\d+)?$/i, (msg) -> parseData = parseListMessage(msg, "The Best", karma.top) ### # Listen for "karma worst [n]" and return the bottom n rankings ### robot.respond /karma worst\s*(\d+)?$/i, (msg) -> parseData = parseListMessage(msg, "The Worst", karma.bottom) ### # Listen for "karma x" and return karma for x ### robot.respond /karma (\S+[^-\s])$/i, (msg) -> match = msg.match[1].toLowerCase() if not (match in ["best", "worst"]) if match == "rob" # msg.send "Nice try." msg.send(rickroll()) else # msg.send "\"#{match}\" has #{karma.get(match)} karma. You must be proud." msg.send(rickroll()) ### # Listen for "karma set x val" and set x to karma ### robot.respond /karma set (\S+[^-\s]) (-?\d+)$/i, (msg) -> subject = msg.match[1].toLowerCase() val = +msg.match[2] karma.assign subject, val rickroll = -> num = Math.floor(Math.random() * 11) v = Math.floor(Math.random() * 10000) result = switch num when 0 then "https://media.giphy.com/media/629l2uUvy0uyc/giphy.gif" when 1 then "https://media.giphy.com/media/2EibPB1gfjHy0/giphy.gif" when 2 then "https://media.giphy.com/media/quXLseRWeh928/giphy.gif" when 3 then "https://media.giphy.com/media/P4SxYsjDqQwM0/giphy.gif" when 4 then "https://media.giphy.com/media/P4SxYsjDqQwM0/giphy.gif" when 5 then "https://media.giphy.com/media/LrmU6jXIjwziE/giphy.gif" when 6 then "https://media.giphy.com/media/sXX6ZPYWMNkwU/giphy.gif" when 7 then "https://media.giphy.com/media/6LG8fcerztuxy/giphy.gif" when 8 then "https://media.giphy.com/media/g7GKcSzwQfugw/giphy.gif" when 9 then "https://media.giphy.com/media/lgcUUCXgC8mEo/giphy.gif" when 10 then "https://media.giphy.com/media/4SoPtOQAOANMs/giphy.gif" result + "?v=" + v
[ { "context": "rson>\n <name>Unknown</name>\n <alias>John Doe</alias>\n <alias>Jane Doe</alias>\n </p", "end": 5154, "score": 0.9993788003921509, "start": 5146, "tag": "NAME", "value": "John Doe" }, { "context": "e>\n <alias>John Doe</alias>\n <...
test/xml/parser.spec.coffee
ashharrison90/ibm-cos-sdk-js
0
helpers = require('../helpers'); AWS = helpers.AWS describe 'AWS.XML.Parser', -> parse = (xml, rules, callback) -> if rules shape = AWS.Model.Shape.create(rules, api: protocol: 'rest-xml') else shape = {} callback.call(this, new AWS.XML.Parser().parse(xml, shape)) describe 'default behavior', -> rules = null # no rules, rely on default parsing behavior it 'returns empty object when string is empty', -> parse '', null, (data) -> expect(data).to.eql({}) it 'returns an empty object from an empty document', -> xml = '<xml/>' parse xml, rules, (data) -> expect(data).to.eql({}) it 'returns empty elements as empty string', -> xml = '<xml><element/></xml>' parse xml, rules, (data) -> expect(data).to.eql({element:''}) it 'converts string elements to properties', -> xml = '<xml><foo>abc</foo><bar>xyz</bar></xml>' parse xml, rules, (data) -> expect(data).to.eql({foo:'abc', bar:'xyz'}) it 'converts nested elements into objects', -> xml = '<xml><foo><bar>yuck</bar></foo></xml>' parse xml, rules, (data) -> expect(data).to.eql({foo:{bar:'yuck'}}) it 'returns everything as a string (even numbers)', -> xml = '<xml><count>123</count></xml>' parse xml, rules, (data) -> expect(data).to.eql({count:'123'}) it 'ignores xmlns on the root element', -> xml = '<xml xmlns="http://foo.bar.com"><Abc>xyz</Abc></xml>' parse xml, rules, (data) -> expect(data).to.eql({Abc:'xyz'}) describe 'structures', -> it 'returns empty objects as {}', -> xml = '<xml><Item/></xml>' rules = type: 'structure' members: Item: type: 'structure' members: Name: type: 'string' parse xml, rules, (data) -> expect(data).to.eql({Item:{}}) it 'parses attributes from tags', -> xml = '<xml xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <Item xsi:name="name"></Item></xml>' rules = type: 'structure' members: Item: type: 'structure' members: Name: type: 'string' xmlAttribute: true locationName: 'xsi:name' parse xml, rules, (data) -> expect(data).to.eql({Item:{Name: 'name'}}) describe 'lists', -> it 'returns empty lists as []', -> xml = '<xml><items/></xml>' rules = type: 'structure' members: items: type: 'list' member: type: 'string' parse xml, rules, (data) -> expect(data).to.eql({items:[]}) it 'returns missing lists as []', -> xml = '<xml></xml>' rules = type: 'structure' members: items: type: 'list' member: type: 'string' parse xml, rules, (data) -> expect(data).to.eql({items:[]}) it 'Converts xml lists of strings into arrays of strings', -> xml = """ <xml> <items> <member>abc</member> <member>xyz</member> </items> </xml> """ rules = type: 'structure' members: items: type: 'list' member: {} parse xml, rules, (data) -> expect(data).to.eql({items:['abc','xyz']}) it 'observes list member names when present', -> xml = """ <xml> <items> <item>abc</item> <item>xyz</item> </items> </xml> """ rules = type: 'structure' members: items: type: 'list' member: locationName: 'item' parse xml, rules, (data) -> expect(data).to.eql({items:['abc','xyz']}) it 'can parse lists of strucures', -> xml = """ <xml> <People> <member><Name>abc</Name></member>> <member><Name>xyz</Name></member>> </People> </xml> """ rules = type: 'structure' members: People: type: 'list' member: type: 'structure' members: Name: type: 'string' parse xml, rules, (data) -> expect(data).to.eql({People:[{Name:'abc'},{Name:'xyz'}]}) it 'can parse lists of strucures with renames', -> xml = """ <xml> <People> <Person><Name>abc</Name></Person>> <Person><Name>xyz</Name></Person>> </People> </xml> """ rules = type: 'structure' members: People: type: 'list' member: type: 'structure' locationName: 'Person' members: Name: type: 'string' parse xml, rules, (data) -> expect(data).to.eql({People:[{Name:'abc'},{Name:'xyz'}]}) describe 'flattened lists', -> xml = """ <xml> <person> <name>Unknown</name> <alias>John Doe</alias> <alias>Jane Doe</alias> </person> </xml> """ it 'collects sibling elements of the same name', -> rules = type: 'structure' members: person: type: 'structure' members: name: {} aka: type: 'list' flattened: true member: locationName: 'alias' parse xml, rules, (data) -> expect(data).to.eql({person:{name:'Unknown',aka:['John Doe', 'Jane Doe']}}) it 'flattened lists can be composed of complex obects', -> xml = """ <xml> <name>Name</name> <complexValue> <a>1</a> <b>2</b> </complexValue> <complexValue> <a>3</a> <b>4</b> </complexValue> </xml> """ rules = type: 'structure' members: name: type: 'string' values: type: 'list' flattened: true member: locationName: 'complexValue' type: 'structure' members: a: type: 'integer' b: type: 'integer' values = {name:'Name',values:[{a:1,b:2},{a:3,b:4}]} parse xml, rules, (data) -> expect(data).to.eql(values) it 'can parse flattened lists of complex objects', -> xml = """ <xml> <Count>2</Count> <Person><Name>abc</Name></Person> <Person><Name>xyz</Name></Person> </xml> """ rules = type: 'structure' members: Count: type: 'integer' People: type: 'list' flattened: true member: type: 'structure' locationName: 'Person' members: Name: {} parse xml, rules, (data) -> expect(data).to.eql({Count:2,People:[{Name:'abc'},{Name:'xyz'}]}) describe 'maps', -> describe 'non-flattened', -> it 'returns empty maps as {}', -> xml = """ <xml> <DomainMap/> </xml> """ rules = type: 'structure' members: DomainMap: type: 'map' value: type: 'string' parse xml, rules, (data) -> expect(data).to.eql(DomainMap: {}) it 'expects entry, key, and value elements by default', -> # example from IAM GetAccountSummary (output) xml = """ <xml> <SummaryMap> <entry> <key>Groups</key> <value>31</value> </entry> <entry> <key>GroupsQuota</key> <value>50</value> </entry> <entry> <key>UsersQuota</key> <value>150</value> </entry> </SummaryMap> </xml> """ rules = type: 'structure' members: SummaryMap: type: 'map' value: type: 'integer' parse xml, rules, (data) -> expect(data).to.eql(SummaryMap:{Groups:31,GroupsQuota:50,UsersQuota:150}) it 'can use alternate names for key and value elements', -> # using Property/Count instead of key/value, also applied a name # trait to the Summary map to rename it xml = """ <xml> <SummaryMap> <entry> <Property>Groups</Property> <Count>31</Count> </entry> <entry> <Property>GroupsQuota</Property> <Count>50</Count> </entry> <entry> <Property>UsersQuota</Property> <Count>150</Count> </entry> </SummaryMap> </xml> """ rules = type: 'structure' members: Summary: type: 'map' locationName: 'SummaryMap', key: locationName: 'Property' value: type: 'integer' locationName: 'Count' parse xml, rules, (data) -> expect(data).to.eql(Summary:{Groups:31,GroupsQuota:50,UsersQuota:150}) describe 'flattened', -> it 'expects key and value elements by default', -> xml = """ <xml> <Attributes> <key>color</key> <value>red</value> </Attributes> <Attributes> <key>size</key> <value>large</value> </Attributes> </xml> """ rules = type: 'structure' members: Attributes: type: 'map' flattened: true parse xml, rules, (data) -> expect(data).to.eql({Attributes:{color:'red',size:'large'}}) it 'can use alternate names for key and value elements', -> # using AttrName/AttrValue instead of key/value, also applied a name # trait to the Attributes map xml = """ <xml> <Attribute> <AttrName>age</AttrName> <AttrValue>35</AttrValue> </Attribute> <Attribute> <AttrName>height</AttrName> <AttrValue>72</AttrValue> </Attribute> </xml> """ rules = type: 'structure' members: Attributes: locationName: 'Attribute' type: 'map' flattened: true key: locationName: 'AttrName' value: locationName: 'AttrValue' type: 'integer' parse xml, rules, (data) -> expect(data).to.eql({Attributes:{age:35,height:72}}) describe 'booleans', -> rules = type: 'structure' members: enabled: type: 'boolean' it 'converts the string "true" in to the boolean value true', -> xml = "<xml><enabled>true</enabled></xml>" parse xml, rules, (data) -> expect(data).to.eql({enabled:true}) it 'converts the string "false" in to the boolean value false', -> xml = "<xml><enabled>false</enabled></xml>" parse xml, rules, (data) -> expect(data).to.eql({enabled:false}) it 'converts the empty elements into null', -> xml = "<xml><enabled/></xml>" parse xml, rules, (data) -> expect(data).to.eql({enabled:null}) describe 'timestamp', -> rules = type: 'structure' members: CreatedAt: type: 'timestamp' it 'returns an empty element as null', -> xml = "<xml><CreatedAt/></xml>" parse xml, rules, (data) -> expect(data).to.eql({CreatedAt:null}) it 'understands unix timestamps', -> timestamp = 1349908100 date = new Date(timestamp * 1000) xml = "<xml><CreatedAt>#{timestamp}</CreatedAt></xml>" parse xml, rules, (data) -> expect(data).to.eql({CreatedAt:date}) it 'understands basic iso8601 strings', -> timestamp = '2012-10-10T15:47:10.001Z' date = new Date(timestamp) xml = "<xml><CreatedAt>#{timestamp}</CreatedAt></xml>" parse xml, rules, (data) -> expect(data).to.eql({CreatedAt:date}) it 'understands basic rfc822 strings', -> timestamp = 'Wed, 10 Oct 2012 15:59:55 UTC' date = new Date(timestamp) xml = "<xml><CreatedAt>#{timestamp}</CreatedAt></xml>" parse xml, rules, (data) -> expect(data).to.eql({CreatedAt:date}) it 'throws an error when unable to determine the format', -> timestamp = 'bad-date-format' xml = "<xml><CreatedAt>#{timestamp}</CreatedAt></xml>" message = 'unhandled timestamp format: ' + timestamp error = {} try parse(xml, rules, ->) catch e error = e expect(error.message).to.eql(message) describe 'numbers', -> rules = type: 'structure' members: decimal: type: 'float' it 'float parses elements types as integer', -> xml = "<xml><decimal>123.456</decimal></xml>" parse xml, rules, (data) -> expect(data).to.eql({decimal:123.456}) it 'returns null for empty elements', -> xml = "<xml><decimal/></xml>" parse xml, rules, (data) -> expect(data).to.eql({decimal:null}) describe 'integers', -> rules = type: 'structure' members: count: type: 'integer' it 'integer parses elements types as integer', -> xml = "<xml><count>123</count></xml>" parse xml, rules, (data) -> expect(data).to.eql({count:123}) it 'returns null for empty elements', -> xml = "<xml><count/></xml>" parse xml, rules, (data) -> expect(data).to.eql({count:null}) describe 'renaming elements', -> it 'can rename scalar elements', -> rules = type: 'structure' members: aka: locationName: 'alias' xml = "<xml><alias>John Doe</alias></xml>" parse xml, rules, (data) -> expect(data).to.eql({aka:'John Doe'}) it 'can rename nested elements', -> rules = type: 'structure' members: person: members: name: {} aka: locationName: 'alias' xml = "<xml><person><name>Joe</name><alias>John Doe</alias></person></xml>" parse xml, rules, (data) -> expect(data).to.eql({person:{name:'Joe',aka:'John Doe'}}) describe 'strings', -> it 'parses empty strings as ""', -> rules = type: 'structure' members: Value: type: 'string' xml = "<xml><Value></Value></xml>" parse xml, rules, (data) -> expect(data.Value).to.equal('') describe 'base64 encoded strings', -> it 'base64 decodes string elements with encoding="base64"', -> rules = type: 'structure' members: Value: type: 'string' xml = """ <xml> <Value encoding="base64">Zm9v</Value> </xml> """ parse xml, rules, (data) -> expect(data.Value.toString()).to.equal('foo') rules = type: 'structure' members: Value: {} xml = """ <xml> <Value encoding="base64">Zm9v</Value> </xml> """ parse xml, rules, (data) -> expect(data.Value.toString()).to.equal('foo') describe 'elements with XML namespaces', -> it 'strips the xmlns element', -> rules = type: 'structure' members: List: type: 'list' member: type: 'structure' members: Attr1: {} Attr2: type: 'structure' members: Foo: {} xml = """ <xml xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> <List> <member> <Attr1 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="CanonicalUser">abc</Attr1> <Attr2 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="CanonicalUser"><Foo>bar</Foo></Attr2> </member> </List> </xml> """ parse xml, rules, (data) -> expect(data).to.eql({List:[{Attr1:'abc',Attr2:{Foo:'bar'}}]}) describe 'parsing errors', -> it 'throws an error when unable to parse the xml', -> xml = 'asdf' rules = {} error = {} try new AWS.XML.Parser().parse(xml, rules) catch e error = e expect(error.code).to.equal('XMLParserError') it 'throws an error when xml is incomplete or does not close all tags', -> xml = '<Content><Member>MemberText</Member><Subcontent><Submember>SubMemberText' rules = {} error = {} try new AWS.XML.Parser().parse(xml, rules) catch e error = e expect(error.code).to.equal('XMLParserError') it 'xml parser errors are retryable', -> xml = '<Content><Member>MemberText</Member><Subcontent><Submember>SubMemberText' rules = {} error = {} try new AWS.XML.Parser().parse(xml, rules) catch e error = e expect(error.retryable).to.be.true
29851
helpers = require('../helpers'); AWS = helpers.AWS describe 'AWS.XML.Parser', -> parse = (xml, rules, callback) -> if rules shape = AWS.Model.Shape.create(rules, api: protocol: 'rest-xml') else shape = {} callback.call(this, new AWS.XML.Parser().parse(xml, shape)) describe 'default behavior', -> rules = null # no rules, rely on default parsing behavior it 'returns empty object when string is empty', -> parse '', null, (data) -> expect(data).to.eql({}) it 'returns an empty object from an empty document', -> xml = '<xml/>' parse xml, rules, (data) -> expect(data).to.eql({}) it 'returns empty elements as empty string', -> xml = '<xml><element/></xml>' parse xml, rules, (data) -> expect(data).to.eql({element:''}) it 'converts string elements to properties', -> xml = '<xml><foo>abc</foo><bar>xyz</bar></xml>' parse xml, rules, (data) -> expect(data).to.eql({foo:'abc', bar:'xyz'}) it 'converts nested elements into objects', -> xml = '<xml><foo><bar>yuck</bar></foo></xml>' parse xml, rules, (data) -> expect(data).to.eql({foo:{bar:'yuck'}}) it 'returns everything as a string (even numbers)', -> xml = '<xml><count>123</count></xml>' parse xml, rules, (data) -> expect(data).to.eql({count:'123'}) it 'ignores xmlns on the root element', -> xml = '<xml xmlns="http://foo.bar.com"><Abc>xyz</Abc></xml>' parse xml, rules, (data) -> expect(data).to.eql({Abc:'xyz'}) describe 'structures', -> it 'returns empty objects as {}', -> xml = '<xml><Item/></xml>' rules = type: 'structure' members: Item: type: 'structure' members: Name: type: 'string' parse xml, rules, (data) -> expect(data).to.eql({Item:{}}) it 'parses attributes from tags', -> xml = '<xml xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <Item xsi:name="name"></Item></xml>' rules = type: 'structure' members: Item: type: 'structure' members: Name: type: 'string' xmlAttribute: true locationName: 'xsi:name' parse xml, rules, (data) -> expect(data).to.eql({Item:{Name: 'name'}}) describe 'lists', -> it 'returns empty lists as []', -> xml = '<xml><items/></xml>' rules = type: 'structure' members: items: type: 'list' member: type: 'string' parse xml, rules, (data) -> expect(data).to.eql({items:[]}) it 'returns missing lists as []', -> xml = '<xml></xml>' rules = type: 'structure' members: items: type: 'list' member: type: 'string' parse xml, rules, (data) -> expect(data).to.eql({items:[]}) it 'Converts xml lists of strings into arrays of strings', -> xml = """ <xml> <items> <member>abc</member> <member>xyz</member> </items> </xml> """ rules = type: 'structure' members: items: type: 'list' member: {} parse xml, rules, (data) -> expect(data).to.eql({items:['abc','xyz']}) it 'observes list member names when present', -> xml = """ <xml> <items> <item>abc</item> <item>xyz</item> </items> </xml> """ rules = type: 'structure' members: items: type: 'list' member: locationName: 'item' parse xml, rules, (data) -> expect(data).to.eql({items:['abc','xyz']}) it 'can parse lists of strucures', -> xml = """ <xml> <People> <member><Name>abc</Name></member>> <member><Name>xyz</Name></member>> </People> </xml> """ rules = type: 'structure' members: People: type: 'list' member: type: 'structure' members: Name: type: 'string' parse xml, rules, (data) -> expect(data).to.eql({People:[{Name:'abc'},{Name:'xyz'}]}) it 'can parse lists of strucures with renames', -> xml = """ <xml> <People> <Person><Name>abc</Name></Person>> <Person><Name>xyz</Name></Person>> </People> </xml> """ rules = type: 'structure' members: People: type: 'list' member: type: 'structure' locationName: 'Person' members: Name: type: 'string' parse xml, rules, (data) -> expect(data).to.eql({People:[{Name:'abc'},{Name:'xyz'}]}) describe 'flattened lists', -> xml = """ <xml> <person> <name>Unknown</name> <alias><NAME></alias> <alias><NAME></alias> </person> </xml> """ it 'collects sibling elements of the same name', -> rules = type: 'structure' members: person: type: 'structure' members: name: {} aka: type: 'list' flattened: true member: locationName: 'alias' parse xml, rules, (data) -> expect(data).to.eql({person:{name:'Unknown',aka:['<NAME>', '<NAME>']}}) it 'flattened lists can be composed of complex obects', -> xml = """ <xml> <name>Name</name> <complexValue> <a>1</a> <b>2</b> </complexValue> <complexValue> <a>3</a> <b>4</b> </complexValue> </xml> """ rules = type: 'structure' members: name: type: 'string' values: type: 'list' flattened: true member: locationName: 'complexValue' type: 'structure' members: a: type: 'integer' b: type: 'integer' values = {name:'Name',values:[{a:1,b:2},{a:3,b:4}]} parse xml, rules, (data) -> expect(data).to.eql(values) it 'can parse flattened lists of complex objects', -> xml = """ <xml> <Count>2</Count> <Person><Name>abc</Name></Person> <Person><Name>xyz</Name></Person> </xml> """ rules = type: 'structure' members: Count: type: 'integer' People: type: 'list' flattened: true member: type: 'structure' locationName: 'Person' members: Name: {} parse xml, rules, (data) -> expect(data).to.eql({Count:2,People:[{Name:'abc'},{Name:'xyz'}]}) describe 'maps', -> describe 'non-flattened', -> it 'returns empty maps as {}', -> xml = """ <xml> <DomainMap/> </xml> """ rules = type: 'structure' members: DomainMap: type: 'map' value: type: 'string' parse xml, rules, (data) -> expect(data).to.eql(DomainMap: {}) it 'expects entry, key, and value elements by default', -> # example from IAM GetAccountSummary (output) xml = """ <xml> <SummaryMap> <entry> <key>Groups</key> <value>31</value> </entry> <entry> <key>GroupsQuota</key> <value>50</value> </entry> <entry> <key>UsersQuota</key> <value>150</value> </entry> </SummaryMap> </xml> """ rules = type: 'structure' members: SummaryMap: type: 'map' value: type: 'integer' parse xml, rules, (data) -> expect(data).to.eql(SummaryMap:{Groups:31,GroupsQuota:50,UsersQuota:150}) it 'can use alternate names for key and value elements', -> # using Property/Count instead of key/value, also applied a name # trait to the Summary map to rename it xml = """ <xml> <SummaryMap> <entry> <Property>Groups</Property> <Count>31</Count> </entry> <entry> <Property>GroupsQuota</Property> <Count>50</Count> </entry> <entry> <Property>UsersQuota</Property> <Count>150</Count> </entry> </SummaryMap> </xml> """ rules = type: 'structure' members: Summary: type: 'map' locationName: 'SummaryMap', key: locationName: 'Property' value: type: 'integer' locationName: 'Count' parse xml, rules, (data) -> expect(data).to.eql(Summary:{Groups:31,GroupsQuota:50,UsersQuota:150}) describe 'flattened', -> it 'expects key and value elements by default', -> xml = """ <xml> <Attributes> <key>color</key> <value>red</value> </Attributes> <Attributes> <key>size</key> <value>large</value> </Attributes> </xml> """ rules = type: 'structure' members: Attributes: type: 'map' flattened: true parse xml, rules, (data) -> expect(data).to.eql({Attributes:{color:'red',size:'large'}}) it 'can use alternate names for key and value elements', -> # using AttrName/AttrValue instead of key/value, also applied a name # trait to the Attributes map xml = """ <xml> <Attribute> <AttrName>age</AttrName> <AttrValue>35</AttrValue> </Attribute> <Attribute> <AttrName>height</AttrName> <AttrValue>72</AttrValue> </Attribute> </xml> """ rules = type: 'structure' members: Attributes: locationName: 'Attribute' type: 'map' flattened: true key: locationName: 'AttrName' value: locationName: 'AttrValue' type: 'integer' parse xml, rules, (data) -> expect(data).to.eql({Attributes:{age:35,height:72}}) describe 'booleans', -> rules = type: 'structure' members: enabled: type: 'boolean' it 'converts the string "true" in to the boolean value true', -> xml = "<xml><enabled>true</enabled></xml>" parse xml, rules, (data) -> expect(data).to.eql({enabled:true}) it 'converts the string "false" in to the boolean value false', -> xml = "<xml><enabled>false</enabled></xml>" parse xml, rules, (data) -> expect(data).to.eql({enabled:false}) it 'converts the empty elements into null', -> xml = "<xml><enabled/></xml>" parse xml, rules, (data) -> expect(data).to.eql({enabled:null}) describe 'timestamp', -> rules = type: 'structure' members: CreatedAt: type: 'timestamp' it 'returns an empty element as null', -> xml = "<xml><CreatedAt/></xml>" parse xml, rules, (data) -> expect(data).to.eql({CreatedAt:null}) it 'understands unix timestamps', -> timestamp = 1349908100 date = new Date(timestamp * 1000) xml = "<xml><CreatedAt>#{timestamp}</CreatedAt></xml>" parse xml, rules, (data) -> expect(data).to.eql({CreatedAt:date}) it 'understands basic iso8601 strings', -> timestamp = '2012-10-10T15:47:10.001Z' date = new Date(timestamp) xml = "<xml><CreatedAt>#{timestamp}</CreatedAt></xml>" parse xml, rules, (data) -> expect(data).to.eql({CreatedAt:date}) it 'understands basic rfc822 strings', -> timestamp = 'Wed, 10 Oct 2012 15:59:55 UTC' date = new Date(timestamp) xml = "<xml><CreatedAt>#{timestamp}</CreatedAt></xml>" parse xml, rules, (data) -> expect(data).to.eql({CreatedAt:date}) it 'throws an error when unable to determine the format', -> timestamp = 'bad-date-format' xml = "<xml><CreatedAt>#{timestamp}</CreatedAt></xml>" message = 'unhandled timestamp format: ' + timestamp error = {} try parse(xml, rules, ->) catch e error = e expect(error.message).to.eql(message) describe 'numbers', -> rules = type: 'structure' members: decimal: type: 'float' it 'float parses elements types as integer', -> xml = "<xml><decimal>123.456</decimal></xml>" parse xml, rules, (data) -> expect(data).to.eql({decimal:123.456}) it 'returns null for empty elements', -> xml = "<xml><decimal/></xml>" parse xml, rules, (data) -> expect(data).to.eql({decimal:null}) describe 'integers', -> rules = type: 'structure' members: count: type: 'integer' it 'integer parses elements types as integer', -> xml = "<xml><count>123</count></xml>" parse xml, rules, (data) -> expect(data).to.eql({count:123}) it 'returns null for empty elements', -> xml = "<xml><count/></xml>" parse xml, rules, (data) -> expect(data).to.eql({count:null}) describe 'renaming elements', -> it 'can rename scalar elements', -> rules = type: 'structure' members: aka: locationName: 'alias' xml = "<xml><alias><NAME></alias></xml>" parse xml, rules, (data) -> expect(data).to.eql({aka:'<NAME>'}) it 'can rename nested elements', -> rules = type: 'structure' members: person: members: name: {} aka: locationName: 'alias' xml = "<xml><person><name><NAME></name><alias><NAME></alias></person></xml>" parse xml, rules, (data) -> expect(data).to.eql({person:{name:'<NAME>',aka:'<NAME>'}}) describe 'strings', -> it 'parses empty strings as ""', -> rules = type: 'structure' members: Value: type: 'string' xml = "<xml><Value></Value></xml>" parse xml, rules, (data) -> expect(data.Value).to.equal('') describe 'base64 encoded strings', -> it 'base64 decodes string elements with encoding="base64"', -> rules = type: 'structure' members: Value: type: 'string' xml = """ <xml> <Value encoding="base64">Zm9v</Value> </xml> """ parse xml, rules, (data) -> expect(data.Value.toString()).to.equal('foo') rules = type: 'structure' members: Value: {} xml = """ <xml> <Value encoding="base64">Zm9v</Value> </xml> """ parse xml, rules, (data) -> expect(data.Value.toString()).to.equal('foo') describe 'elements with XML namespaces', -> it 'strips the xmlns element', -> rules = type: 'structure' members: List: type: 'list' member: type: 'structure' members: Attr1: {} Attr2: type: 'structure' members: Foo: {} xml = """ <xml xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> <List> <member> <Attr1 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="CanonicalUser">abc</Attr1> <Attr2 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="CanonicalUser"><Foo>bar</Foo></Attr2> </member> </List> </xml> """ parse xml, rules, (data) -> expect(data).to.eql({List:[{Attr1:'abc',Attr2:{Foo:'bar'}}]}) describe 'parsing errors', -> it 'throws an error when unable to parse the xml', -> xml = 'asdf' rules = {} error = {} try new AWS.XML.Parser().parse(xml, rules) catch e error = e expect(error.code).to.equal('XMLParserError') it 'throws an error when xml is incomplete or does not close all tags', -> xml = '<Content><Member>MemberText</Member><Subcontent><Submember>SubMemberText' rules = {} error = {} try new AWS.XML.Parser().parse(xml, rules) catch e error = e expect(error.code).to.equal('XMLParserError') it 'xml parser errors are retryable', -> xml = '<Content><Member>MemberText</Member><Subcontent><Submember>SubMemberText' rules = {} error = {} try new AWS.XML.Parser().parse(xml, rules) catch e error = e expect(error.retryable).to.be.true
true
helpers = require('../helpers'); AWS = helpers.AWS describe 'AWS.XML.Parser', -> parse = (xml, rules, callback) -> if rules shape = AWS.Model.Shape.create(rules, api: protocol: 'rest-xml') else shape = {} callback.call(this, new AWS.XML.Parser().parse(xml, shape)) describe 'default behavior', -> rules = null # no rules, rely on default parsing behavior it 'returns empty object when string is empty', -> parse '', null, (data) -> expect(data).to.eql({}) it 'returns an empty object from an empty document', -> xml = '<xml/>' parse xml, rules, (data) -> expect(data).to.eql({}) it 'returns empty elements as empty string', -> xml = '<xml><element/></xml>' parse xml, rules, (data) -> expect(data).to.eql({element:''}) it 'converts string elements to properties', -> xml = '<xml><foo>abc</foo><bar>xyz</bar></xml>' parse xml, rules, (data) -> expect(data).to.eql({foo:'abc', bar:'xyz'}) it 'converts nested elements into objects', -> xml = '<xml><foo><bar>yuck</bar></foo></xml>' parse xml, rules, (data) -> expect(data).to.eql({foo:{bar:'yuck'}}) it 'returns everything as a string (even numbers)', -> xml = '<xml><count>123</count></xml>' parse xml, rules, (data) -> expect(data).to.eql({count:'123'}) it 'ignores xmlns on the root element', -> xml = '<xml xmlns="http://foo.bar.com"><Abc>xyz</Abc></xml>' parse xml, rules, (data) -> expect(data).to.eql({Abc:'xyz'}) describe 'structures', -> it 'returns empty objects as {}', -> xml = '<xml><Item/></xml>' rules = type: 'structure' members: Item: type: 'structure' members: Name: type: 'string' parse xml, rules, (data) -> expect(data).to.eql({Item:{}}) it 'parses attributes from tags', -> xml = '<xml xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <Item xsi:name="name"></Item></xml>' rules = type: 'structure' members: Item: type: 'structure' members: Name: type: 'string' xmlAttribute: true locationName: 'xsi:name' parse xml, rules, (data) -> expect(data).to.eql({Item:{Name: 'name'}}) describe 'lists', -> it 'returns empty lists as []', -> xml = '<xml><items/></xml>' rules = type: 'structure' members: items: type: 'list' member: type: 'string' parse xml, rules, (data) -> expect(data).to.eql({items:[]}) it 'returns missing lists as []', -> xml = '<xml></xml>' rules = type: 'structure' members: items: type: 'list' member: type: 'string' parse xml, rules, (data) -> expect(data).to.eql({items:[]}) it 'Converts xml lists of strings into arrays of strings', -> xml = """ <xml> <items> <member>abc</member> <member>xyz</member> </items> </xml> """ rules = type: 'structure' members: items: type: 'list' member: {} parse xml, rules, (data) -> expect(data).to.eql({items:['abc','xyz']}) it 'observes list member names when present', -> xml = """ <xml> <items> <item>abc</item> <item>xyz</item> </items> </xml> """ rules = type: 'structure' members: items: type: 'list' member: locationName: 'item' parse xml, rules, (data) -> expect(data).to.eql({items:['abc','xyz']}) it 'can parse lists of strucures', -> xml = """ <xml> <People> <member><Name>abc</Name></member>> <member><Name>xyz</Name></member>> </People> </xml> """ rules = type: 'structure' members: People: type: 'list' member: type: 'structure' members: Name: type: 'string' parse xml, rules, (data) -> expect(data).to.eql({People:[{Name:'abc'},{Name:'xyz'}]}) it 'can parse lists of strucures with renames', -> xml = """ <xml> <People> <Person><Name>abc</Name></Person>> <Person><Name>xyz</Name></Person>> </People> </xml> """ rules = type: 'structure' members: People: type: 'list' member: type: 'structure' locationName: 'Person' members: Name: type: 'string' parse xml, rules, (data) -> expect(data).to.eql({People:[{Name:'abc'},{Name:'xyz'}]}) describe 'flattened lists', -> xml = """ <xml> <person> <name>Unknown</name> <alias>PI:NAME:<NAME>END_PI</alias> <alias>PI:NAME:<NAME>END_PI</alias> </person> </xml> """ it 'collects sibling elements of the same name', -> rules = type: 'structure' members: person: type: 'structure' members: name: {} aka: type: 'list' flattened: true member: locationName: 'alias' parse xml, rules, (data) -> expect(data).to.eql({person:{name:'Unknown',aka:['PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI']}}) it 'flattened lists can be composed of complex obects', -> xml = """ <xml> <name>Name</name> <complexValue> <a>1</a> <b>2</b> </complexValue> <complexValue> <a>3</a> <b>4</b> </complexValue> </xml> """ rules = type: 'structure' members: name: type: 'string' values: type: 'list' flattened: true member: locationName: 'complexValue' type: 'structure' members: a: type: 'integer' b: type: 'integer' values = {name:'Name',values:[{a:1,b:2},{a:3,b:4}]} parse xml, rules, (data) -> expect(data).to.eql(values) it 'can parse flattened lists of complex objects', -> xml = """ <xml> <Count>2</Count> <Person><Name>abc</Name></Person> <Person><Name>xyz</Name></Person> </xml> """ rules = type: 'structure' members: Count: type: 'integer' People: type: 'list' flattened: true member: type: 'structure' locationName: 'Person' members: Name: {} parse xml, rules, (data) -> expect(data).to.eql({Count:2,People:[{Name:'abc'},{Name:'xyz'}]}) describe 'maps', -> describe 'non-flattened', -> it 'returns empty maps as {}', -> xml = """ <xml> <DomainMap/> </xml> """ rules = type: 'structure' members: DomainMap: type: 'map' value: type: 'string' parse xml, rules, (data) -> expect(data).to.eql(DomainMap: {}) it 'expects entry, key, and value elements by default', -> # example from IAM GetAccountSummary (output) xml = """ <xml> <SummaryMap> <entry> <key>Groups</key> <value>31</value> </entry> <entry> <key>GroupsQuota</key> <value>50</value> </entry> <entry> <key>UsersQuota</key> <value>150</value> </entry> </SummaryMap> </xml> """ rules = type: 'structure' members: SummaryMap: type: 'map' value: type: 'integer' parse xml, rules, (data) -> expect(data).to.eql(SummaryMap:{Groups:31,GroupsQuota:50,UsersQuota:150}) it 'can use alternate names for key and value elements', -> # using Property/Count instead of key/value, also applied a name # trait to the Summary map to rename it xml = """ <xml> <SummaryMap> <entry> <Property>Groups</Property> <Count>31</Count> </entry> <entry> <Property>GroupsQuota</Property> <Count>50</Count> </entry> <entry> <Property>UsersQuota</Property> <Count>150</Count> </entry> </SummaryMap> </xml> """ rules = type: 'structure' members: Summary: type: 'map' locationName: 'SummaryMap', key: locationName: 'Property' value: type: 'integer' locationName: 'Count' parse xml, rules, (data) -> expect(data).to.eql(Summary:{Groups:31,GroupsQuota:50,UsersQuota:150}) describe 'flattened', -> it 'expects key and value elements by default', -> xml = """ <xml> <Attributes> <key>color</key> <value>red</value> </Attributes> <Attributes> <key>size</key> <value>large</value> </Attributes> </xml> """ rules = type: 'structure' members: Attributes: type: 'map' flattened: true parse xml, rules, (data) -> expect(data).to.eql({Attributes:{color:'red',size:'large'}}) it 'can use alternate names for key and value elements', -> # using AttrName/AttrValue instead of key/value, also applied a name # trait to the Attributes map xml = """ <xml> <Attribute> <AttrName>age</AttrName> <AttrValue>35</AttrValue> </Attribute> <Attribute> <AttrName>height</AttrName> <AttrValue>72</AttrValue> </Attribute> </xml> """ rules = type: 'structure' members: Attributes: locationName: 'Attribute' type: 'map' flattened: true key: locationName: 'AttrName' value: locationName: 'AttrValue' type: 'integer' parse xml, rules, (data) -> expect(data).to.eql({Attributes:{age:35,height:72}}) describe 'booleans', -> rules = type: 'structure' members: enabled: type: 'boolean' it 'converts the string "true" in to the boolean value true', -> xml = "<xml><enabled>true</enabled></xml>" parse xml, rules, (data) -> expect(data).to.eql({enabled:true}) it 'converts the string "false" in to the boolean value false', -> xml = "<xml><enabled>false</enabled></xml>" parse xml, rules, (data) -> expect(data).to.eql({enabled:false}) it 'converts the empty elements into null', -> xml = "<xml><enabled/></xml>" parse xml, rules, (data) -> expect(data).to.eql({enabled:null}) describe 'timestamp', -> rules = type: 'structure' members: CreatedAt: type: 'timestamp' it 'returns an empty element as null', -> xml = "<xml><CreatedAt/></xml>" parse xml, rules, (data) -> expect(data).to.eql({CreatedAt:null}) it 'understands unix timestamps', -> timestamp = 1349908100 date = new Date(timestamp * 1000) xml = "<xml><CreatedAt>#{timestamp}</CreatedAt></xml>" parse xml, rules, (data) -> expect(data).to.eql({CreatedAt:date}) it 'understands basic iso8601 strings', -> timestamp = '2012-10-10T15:47:10.001Z' date = new Date(timestamp) xml = "<xml><CreatedAt>#{timestamp}</CreatedAt></xml>" parse xml, rules, (data) -> expect(data).to.eql({CreatedAt:date}) it 'understands basic rfc822 strings', -> timestamp = 'Wed, 10 Oct 2012 15:59:55 UTC' date = new Date(timestamp) xml = "<xml><CreatedAt>#{timestamp}</CreatedAt></xml>" parse xml, rules, (data) -> expect(data).to.eql({CreatedAt:date}) it 'throws an error when unable to determine the format', -> timestamp = 'bad-date-format' xml = "<xml><CreatedAt>#{timestamp}</CreatedAt></xml>" message = 'unhandled timestamp format: ' + timestamp error = {} try parse(xml, rules, ->) catch e error = e expect(error.message).to.eql(message) describe 'numbers', -> rules = type: 'structure' members: decimal: type: 'float' it 'float parses elements types as integer', -> xml = "<xml><decimal>123.456</decimal></xml>" parse xml, rules, (data) -> expect(data).to.eql({decimal:123.456}) it 'returns null for empty elements', -> xml = "<xml><decimal/></xml>" parse xml, rules, (data) -> expect(data).to.eql({decimal:null}) describe 'integers', -> rules = type: 'structure' members: count: type: 'integer' it 'integer parses elements types as integer', -> xml = "<xml><count>123</count></xml>" parse xml, rules, (data) -> expect(data).to.eql({count:123}) it 'returns null for empty elements', -> xml = "<xml><count/></xml>" parse xml, rules, (data) -> expect(data).to.eql({count:null}) describe 'renaming elements', -> it 'can rename scalar elements', -> rules = type: 'structure' members: aka: locationName: 'alias' xml = "<xml><alias>PI:NAME:<NAME>END_PI</alias></xml>" parse xml, rules, (data) -> expect(data).to.eql({aka:'PI:NAME:<NAME>END_PI'}) it 'can rename nested elements', -> rules = type: 'structure' members: person: members: name: {} aka: locationName: 'alias' xml = "<xml><person><name>PI:NAME:<NAME>END_PI</name><alias>PI:NAME:<NAME>END_PI</alias></person></xml>" parse xml, rules, (data) -> expect(data).to.eql({person:{name:'PI:NAME:<NAME>END_PI',aka:'PI:NAME:<NAME>END_PI'}}) describe 'strings', -> it 'parses empty strings as ""', -> rules = type: 'structure' members: Value: type: 'string' xml = "<xml><Value></Value></xml>" parse xml, rules, (data) -> expect(data.Value).to.equal('') describe 'base64 encoded strings', -> it 'base64 decodes string elements with encoding="base64"', -> rules = type: 'structure' members: Value: type: 'string' xml = """ <xml> <Value encoding="base64">Zm9v</Value> </xml> """ parse xml, rules, (data) -> expect(data.Value.toString()).to.equal('foo') rules = type: 'structure' members: Value: {} xml = """ <xml> <Value encoding="base64">Zm9v</Value> </xml> """ parse xml, rules, (data) -> expect(data.Value.toString()).to.equal('foo') describe 'elements with XML namespaces', -> it 'strips the xmlns element', -> rules = type: 'structure' members: List: type: 'list' member: type: 'structure' members: Attr1: {} Attr2: type: 'structure' members: Foo: {} xml = """ <xml xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> <List> <member> <Attr1 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="CanonicalUser">abc</Attr1> <Attr2 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="CanonicalUser"><Foo>bar</Foo></Attr2> </member> </List> </xml> """ parse xml, rules, (data) -> expect(data).to.eql({List:[{Attr1:'abc',Attr2:{Foo:'bar'}}]}) describe 'parsing errors', -> it 'throws an error when unable to parse the xml', -> xml = 'asdf' rules = {} error = {} try new AWS.XML.Parser().parse(xml, rules) catch e error = e expect(error.code).to.equal('XMLParserError') it 'throws an error when xml is incomplete or does not close all tags', -> xml = '<Content><Member>MemberText</Member><Subcontent><Submember>SubMemberText' rules = {} error = {} try new AWS.XML.Parser().parse(xml, rules) catch e error = e expect(error.code).to.equal('XMLParserError') it 'xml parser errors are retryable', -> xml = '<Content><Member>MemberText</Member><Subcontent><Submember>SubMemberText' rules = {} error = {} try new AWS.XML.Parser().parse(xml, rules) catch e error = e expect(error.retryable).to.be.true
[ { "context": "nd'\n\n @packageOptions =\n name: 'TestName'\n\n copyPackageFile: ->\n @log chalk.", "end": 271, "score": 0.7506187558174133, "start": 267, "tag": "NAME", "value": "Test" }, { "context": "\n @packageOptions =\n name: 'TestNa...
src/app/index.coffee
senritsu/generator-double-expresso
0
generators = require 'yeoman-generator' chalk = require 'chalk' module.exports = class DoubleExpresso extends generators.Base constructor: -> generators.Base.apply this, arguments @option 'frontend' @packageOptions = name: 'TestName' copyPackageFile: -> @log chalk.blue 'copying files' @template 'package.json', 'package.json', @packageOptions @copy 'gulpfile.coffee', 'gulpfile.coffee' if @options.frontend @copy '.bowerrc', '.bowerrc' @template 'bower.json', 'bower.json', @packageOptions dependencies: -> @log chalk.blue 'installing npm dependencies' @npmInstall ['express', 'ect', 'pouchdb', 'mathjs'], save: true @npmInstall ['gulp', 'gulp-plumber', 'gulp-coffee', 'gulp-watch', 'lazypipe'], saveDev: true if @options.frontend @npmInstall ['gulp-sass'], saveDev: true @bowerInstall ['jquery', 'bootstrap#v4.0.0-alpha'], save: true end: -> @log chalk.blue 'compiling gulpfile' @spawnCommand 'coffee', ['-c', 'gulpfile.coffee']
213753
generators = require 'yeoman-generator' chalk = require 'chalk' module.exports = class DoubleExpresso extends generators.Base constructor: -> generators.Base.apply this, arguments @option 'frontend' @packageOptions = name: '<NAME>Name' copyPackageFile: -> @log chalk.blue 'copying files' @template 'package.json', 'package.json', @packageOptions @copy 'gulpfile.coffee', 'gulpfile.coffee' if @options.frontend @copy '.bowerrc', '.bowerrc' @template 'bower.json', 'bower.json', @packageOptions dependencies: -> @log chalk.blue 'installing npm dependencies' @npmInstall ['express', 'ect', 'pouchdb', 'mathjs'], save: true @npmInstall ['gulp', 'gulp-plumber', 'gulp-coffee', 'gulp-watch', 'lazypipe'], saveDev: true if @options.frontend @npmInstall ['gulp-sass'], saveDev: true @bowerInstall ['jquery', 'bootstrap#v4.0.0-alpha'], save: true end: -> @log chalk.blue 'compiling gulpfile' @spawnCommand 'coffee', ['-c', 'gulpfile.coffee']
true
generators = require 'yeoman-generator' chalk = require 'chalk' module.exports = class DoubleExpresso extends generators.Base constructor: -> generators.Base.apply this, arguments @option 'frontend' @packageOptions = name: 'PI:NAME:<NAME>END_PIName' copyPackageFile: -> @log chalk.blue 'copying files' @template 'package.json', 'package.json', @packageOptions @copy 'gulpfile.coffee', 'gulpfile.coffee' if @options.frontend @copy '.bowerrc', '.bowerrc' @template 'bower.json', 'bower.json', @packageOptions dependencies: -> @log chalk.blue 'installing npm dependencies' @npmInstall ['express', 'ect', 'pouchdb', 'mathjs'], save: true @npmInstall ['gulp', 'gulp-plumber', 'gulp-coffee', 'gulp-watch', 'lazypipe'], saveDev: true if @options.frontend @npmInstall ['gulp-sass'], saveDev: true @bowerInstall ['jquery', 'bootstrap#v4.0.0-alpha'], save: true end: -> @log chalk.blue 'compiling gulpfile' @spawnCommand 'coffee', ['-c', 'gulpfile.coffee']
[ { "context": "onfig.environmentVariables.starBucket\n key: \"mixin-code/elk/package.zip\"\n name: \"#{config.environmentVariables.fullN", "end": 1641, "score": 0.917214035987854, "start": 1615, "tag": "KEY", "value": "mixin-code/elk/package.zip" } ]
src/preprocessor.coffee
pandastrike/sky-mixin-log
0
# Panda Sky Mixin: Elasticsearch # This mixin allocates the requested Elasticsearch cluster into your CloudFormation stack. import {resolve} from "path" import {cat, isObject, merge, values, capitalize, camelCase, plainText, difference} from "panda-parchment" import Sundog from "sundog" process = (SDK, config) -> sundog = Sundog SDK s3 = sundog.AWS.S3() Log = sundog.AWS.CloudWatchLogs() # Start by extracting out the KMS Mixin configuration: {env, tags=[]} = config c = config.aws.environments[env].mixins.elk c = if isObject c then c else {} c.tags = cat (c.tags || []), tags c.tags.push {Key: "subtask", Value: "logging"} # This mixin only works with a VPC # if !config.aws.vpc # throw new Error "The Elasticsearch mixin can only be used in environments featuring a VPC." # Elasticsearch cluster configuration... by default only use one subnet. cluster = domain: config.environmentVariables.fullName + "-elk" # subnets: ['"Fn::Select": [ 0, "Fn::Split": [ ",", {Ref: Subnets} ]]'] # if c.cluster.nodes?.highAvailability # cluster.subnets.push '"Fn::Select": [1, "Fn::Split": [ ",", {Ref: Subnets} ]]' cluster = merge cluster, c.cluster if !cluster.nodes cluster.nodes = count: 1 type: "t2.medium.elasticsearch" highAvailability: false if !cluster.nodes.highAvailability cluster.nodes.highAvailability = false # Kinesis stream configuration stream = { name: config.environmentVariables.fullName + "-elk" lambda: bucket: config.environmentVariables.skyBucket || config.environmentVariables.starBucket key: "mixin-code/elk/package.zip" name: "#{config.environmentVariables.fullName}-elk-transform" } stream.lambda.arn = "arn:aws:lambda:#{config.aws.region}:#{config.accountID}:function:#{stream.lambda.name}" # Upload the processing lambda to the main orchestration bucket await s3.bucketTouch stream.lambda.bucket await s3.put stream.lambda.bucket, stream.lambda.key, (resolve __dirname, "..", "..", "..", "files", "package.zip"), false # Go through the lambdas producing log outputs and prepare their log names for the subscription filters. logs = [] cloudformationFormat = (str) -> str = str[config.environmentVariables.fullName.length...] capitalize camelCase plainText str if config.resources for resource in values config.resources for method in values resource.methods name = "/aws/lambda/#{method.lambda.function.name}" if !(await Log.exists name) await Log.create name log = {name} log.templateName = cloudformationFormat method.lambda.function.name logs.push log else if config.environment?.lambdas for lambda in values config.environment.lambdas name = "/aws/lambda/#{lambda.function.name}" if !(await Log.exists name) await Log.create name log = {name} log.templateName = cloudformationFormat lambda.function.name logs.push log else throw new Error "Unable to find Sky resources or Stardust tasks to name lambda log groups." { cluster stream logs tags: c.tags, accountID: config.accountID region: config.aws.region } export default process
189329
# Panda Sky Mixin: Elasticsearch # This mixin allocates the requested Elasticsearch cluster into your CloudFormation stack. import {resolve} from "path" import {cat, isObject, merge, values, capitalize, camelCase, plainText, difference} from "panda-parchment" import Sundog from "sundog" process = (SDK, config) -> sundog = Sundog SDK s3 = sundog.AWS.S3() Log = sundog.AWS.CloudWatchLogs() # Start by extracting out the KMS Mixin configuration: {env, tags=[]} = config c = config.aws.environments[env].mixins.elk c = if isObject c then c else {} c.tags = cat (c.tags || []), tags c.tags.push {Key: "subtask", Value: "logging"} # This mixin only works with a VPC # if !config.aws.vpc # throw new Error "The Elasticsearch mixin can only be used in environments featuring a VPC." # Elasticsearch cluster configuration... by default only use one subnet. cluster = domain: config.environmentVariables.fullName + "-elk" # subnets: ['"Fn::Select": [ 0, "Fn::Split": [ ",", {Ref: Subnets} ]]'] # if c.cluster.nodes?.highAvailability # cluster.subnets.push '"Fn::Select": [1, "Fn::Split": [ ",", {Ref: Subnets} ]]' cluster = merge cluster, c.cluster if !cluster.nodes cluster.nodes = count: 1 type: "t2.medium.elasticsearch" highAvailability: false if !cluster.nodes.highAvailability cluster.nodes.highAvailability = false # Kinesis stream configuration stream = { name: config.environmentVariables.fullName + "-elk" lambda: bucket: config.environmentVariables.skyBucket || config.environmentVariables.starBucket key: "<KEY>" name: "#{config.environmentVariables.fullName}-elk-transform" } stream.lambda.arn = "arn:aws:lambda:#{config.aws.region}:#{config.accountID}:function:#{stream.lambda.name}" # Upload the processing lambda to the main orchestration bucket await s3.bucketTouch stream.lambda.bucket await s3.put stream.lambda.bucket, stream.lambda.key, (resolve __dirname, "..", "..", "..", "files", "package.zip"), false # Go through the lambdas producing log outputs and prepare their log names for the subscription filters. logs = [] cloudformationFormat = (str) -> str = str[config.environmentVariables.fullName.length...] capitalize camelCase plainText str if config.resources for resource in values config.resources for method in values resource.methods name = "/aws/lambda/#{method.lambda.function.name}" if !(await Log.exists name) await Log.create name log = {name} log.templateName = cloudformationFormat method.lambda.function.name logs.push log else if config.environment?.lambdas for lambda in values config.environment.lambdas name = "/aws/lambda/#{lambda.function.name}" if !(await Log.exists name) await Log.create name log = {name} log.templateName = cloudformationFormat lambda.function.name logs.push log else throw new Error "Unable to find Sky resources or Stardust tasks to name lambda log groups." { cluster stream logs tags: c.tags, accountID: config.accountID region: config.aws.region } export default process
true
# Panda Sky Mixin: Elasticsearch # This mixin allocates the requested Elasticsearch cluster into your CloudFormation stack. import {resolve} from "path" import {cat, isObject, merge, values, capitalize, camelCase, plainText, difference} from "panda-parchment" import Sundog from "sundog" process = (SDK, config) -> sundog = Sundog SDK s3 = sundog.AWS.S3() Log = sundog.AWS.CloudWatchLogs() # Start by extracting out the KMS Mixin configuration: {env, tags=[]} = config c = config.aws.environments[env].mixins.elk c = if isObject c then c else {} c.tags = cat (c.tags || []), tags c.tags.push {Key: "subtask", Value: "logging"} # This mixin only works with a VPC # if !config.aws.vpc # throw new Error "The Elasticsearch mixin can only be used in environments featuring a VPC." # Elasticsearch cluster configuration... by default only use one subnet. cluster = domain: config.environmentVariables.fullName + "-elk" # subnets: ['"Fn::Select": [ 0, "Fn::Split": [ ",", {Ref: Subnets} ]]'] # if c.cluster.nodes?.highAvailability # cluster.subnets.push '"Fn::Select": [1, "Fn::Split": [ ",", {Ref: Subnets} ]]' cluster = merge cluster, c.cluster if !cluster.nodes cluster.nodes = count: 1 type: "t2.medium.elasticsearch" highAvailability: false if !cluster.nodes.highAvailability cluster.nodes.highAvailability = false # Kinesis stream configuration stream = { name: config.environmentVariables.fullName + "-elk" lambda: bucket: config.environmentVariables.skyBucket || config.environmentVariables.starBucket key: "PI:KEY:<KEY>END_PI" name: "#{config.environmentVariables.fullName}-elk-transform" } stream.lambda.arn = "arn:aws:lambda:#{config.aws.region}:#{config.accountID}:function:#{stream.lambda.name}" # Upload the processing lambda to the main orchestration bucket await s3.bucketTouch stream.lambda.bucket await s3.put stream.lambda.bucket, stream.lambda.key, (resolve __dirname, "..", "..", "..", "files", "package.zip"), false # Go through the lambdas producing log outputs and prepare their log names for the subscription filters. logs = [] cloudformationFormat = (str) -> str = str[config.environmentVariables.fullName.length...] capitalize camelCase plainText str if config.resources for resource in values config.resources for method in values resource.methods name = "/aws/lambda/#{method.lambda.function.name}" if !(await Log.exists name) await Log.create name log = {name} log.templateName = cloudformationFormat method.lambda.function.name logs.push log else if config.environment?.lambdas for lambda in values config.environment.lambdas name = "/aws/lambda/#{lambda.function.name}" if !(await Log.exists name) await Log.create name log = {name} log.templateName = cloudformationFormat lambda.function.name logs.push log else throw new Error "Unable to find Sky resources or Stardust tasks to name lambda log groups." { cluster stream logs tags: c.tags, accountID: config.accountID region: config.aws.region } export default process
[ { "context": "###*\n# \n# @date 2016-01-09 14:12:49\n# @author vfasky <vfasky@gmail.com>\n# @link http://vfasky.com\n###\n", "end": 52, "score": 0.997418224811554, "start": 46, "tag": "USERNAME", "value": "vfasky" }, { "context": "\n# \n# @date 2016-01-09 14:12:49\n# @author vfasky <...
test/src/index.coffee
vfasky/h2svd-loader
0
###* # # @date 2016-01-09 14:12:49 # @author vfasky <vfasky@gmail.com> # @link http://vfasky.com ### 'use strict' module.exports = tpl: require 'h2svd!./tpl/test.html'
61928
###* # # @date 2016-01-09 14:12:49 # @author vfasky <<EMAIL>> # @link http://vfasky.com ### 'use strict' module.exports = tpl: require 'h2svd!./tpl/test.html'
true
###* # # @date 2016-01-09 14:12:49 # @author vfasky <PI:EMAIL:<EMAIL>END_PI> # @link http://vfasky.com ### 'use strict' module.exports = tpl: require 'h2svd!./tpl/test.html'
[ { "context": "=================================\n# Copyright 2014 Hatio, Lab.\n# Licensed under The MIT License\n# http://o", "end": 67, "score": 0.6088466644287109, "start": 62, "tag": "NAME", "value": "Hatio" } ]
src/backup/base.coffee
heartyoh/infopik
0
# ========================================== # Copyright 2014 Hatio, Lab. # Licensed under The MIT License # http://opensource.org/licenses/MIT # ========================================== define [ './utils' './registry' './debug' ], (utils, registry, debug) -> "use strict" # common mixin allocates basic functionality - used by all component prototypes # callback context is bound to component componentId = 0 teardownInstance= (instanceInfo) -> instance = instanceInfo.instance for event in instanceInfo.events.slice() args = [event.type] event.element && args.unshift(event.element); (typeof event.callback == 'function') && args.push(event.callback) instance.off.apply(instance, args) checkSerializable= (type, data) -> try window.postMessage(data, '*') catch e console.log('unserializable data for event', type, ':', data) throw new Error( ['The event', type, 'on component', this.toString(), 'was triggered with non-serializable data'].join(' ') ) proxyEventTo= (targetEvent) -> (e, data) -> $(e.target).trigger(targetEvent, data) -> # delegate trigger, bind and unbind to an element # if $element not supplied, use component's node # other arguments are passed on # event can be either a string specifying the type # of the event, or a hash specifying both the type # and a default function to be called. this.trigger = -> # var $element, type, data, event, defaultFn; lastIndex = arguments.length - 1 lastArg = arguments[lastIndex] if (typeof lastArg != 'string' && !(lastArg && lastArg.defaultBehavior)) lastIndex-- data = lastArg if (lastIndex == 1) $element = $(arguments[0]) event = arguments[1] else $element = this.$node event = arguments[0] if (event.defaultBehavior) defaultFn = event.defaultBehavior event = $.Event(event.type) type = event.type || event if (debug.enabled && window.postMessage) checkSerializable.call(this, type, data) if (typeof this.attr.eventData is 'object') data = $.extend(true, {}, this.attr.eventData, data) $element.trigger((event || type), data) if (defaultFn && !event.isDefaultPrevented()) (this[defaultFn] || defaultFn).call(this) $element this.on = -> # var $element, type, callback, originalCb; lastIndex = arguments.length - 1 origin = arguments[lastIndex] if (typeof origin == 'object') # delegate callback originalCb = utils.delegate(this.resolveDelegateRules(origin)) else if (typeof origin == 'string') originalCb = proxyEventTo(origin) else originalCb = origin if (lastIndex == 2) $element = $(arguments[0]) type = arguments[1] else $element = this.$node type = arguments[0] if (typeof originalCb != 'function' && typeof originalCb != 'object') throw new Error('Unable to bind to "' + type + '" because the given callback is not a function or an object') callback = originalCb.bind(this) callback.target = originalCb callback.context = this $element.on(type, callback) # store every bound version of the callback originalCb.bound || (originalCb.bound = []) originalCb.bound.push(callback) callback this.off = -> # var $element, type, callback; lastIndex = arguments.length - 1 if (typeof arguments[lastIndex] == 'function') callback = arguments[lastIndex] lastIndex -= 1 if (lastIndex == 1) $element = $(arguments[0]) type = arguments[1] else $element = this.$node type = arguments[0] if (callback) # set callback to version bound against this instance callback.bound && callback.bound.some((fn, i, arr) -> if (fn.context && (this.identity == fn.context.identity)) arr.splice(i, 1) callback = fn return true , this) $element.off(type, callback) this.resolveDelegateRules = (ruleInfo) -> rules = {} Object.keys(ruleInfo).forEach((r) -> if (!(r in this.attr)) throw new Error('Component "' + this.toString() + '" wants to listen on "' + r + '" but no such attribute was defined.') rules[this.attr[r]] = if (typeof ruleInfo[r] == 'string') then proxyEventTo(ruleInfo[r]) else ruleInfo[r] , this) rules this.defaultAttrs = (defaults) -> utils.push(this.defaults, defaults, true) || (this.defaults = defaults) this.select = (attributeKey) -> this.$node.find(this.attr[attributeKey]) this.initialize = (node, attrs) -> attrs || (attrs = {}) # only assign identity if there isn't one (initialize can be called multiple times) this.identity || (this.identity = componentId++) if (!node) throw new Error('Component needs a node') # if (node.jquery) { # this.node = node[0]; # this.$node = node; # } else { this.node = node # this.$node = $(node); # } # merge defaults with supplied options # put options in attr.__proto__ to avoid merge overhead attr = Object.create(attrs) for own key of this.defaults if (!attrs.hasOwnProperty(key)) attr[key] = this.defaults[key] this.attr = attr for own key, val of this.defaults || {} if (val is null && this.attr[key] is null) throw new Error('Required attribute "' + key + '" not specified in attachTo for component "' + this.toString() + '".') this this.teardown = -> teardownInstance(registry.findInstanceInfo(this))
104892
# ========================================== # Copyright 2014 <NAME>, Lab. # Licensed under The MIT License # http://opensource.org/licenses/MIT # ========================================== define [ './utils' './registry' './debug' ], (utils, registry, debug) -> "use strict" # common mixin allocates basic functionality - used by all component prototypes # callback context is bound to component componentId = 0 teardownInstance= (instanceInfo) -> instance = instanceInfo.instance for event in instanceInfo.events.slice() args = [event.type] event.element && args.unshift(event.element); (typeof event.callback == 'function') && args.push(event.callback) instance.off.apply(instance, args) checkSerializable= (type, data) -> try window.postMessage(data, '*') catch e console.log('unserializable data for event', type, ':', data) throw new Error( ['The event', type, 'on component', this.toString(), 'was triggered with non-serializable data'].join(' ') ) proxyEventTo= (targetEvent) -> (e, data) -> $(e.target).trigger(targetEvent, data) -> # delegate trigger, bind and unbind to an element # if $element not supplied, use component's node # other arguments are passed on # event can be either a string specifying the type # of the event, or a hash specifying both the type # and a default function to be called. this.trigger = -> # var $element, type, data, event, defaultFn; lastIndex = arguments.length - 1 lastArg = arguments[lastIndex] if (typeof lastArg != 'string' && !(lastArg && lastArg.defaultBehavior)) lastIndex-- data = lastArg if (lastIndex == 1) $element = $(arguments[0]) event = arguments[1] else $element = this.$node event = arguments[0] if (event.defaultBehavior) defaultFn = event.defaultBehavior event = $.Event(event.type) type = event.type || event if (debug.enabled && window.postMessage) checkSerializable.call(this, type, data) if (typeof this.attr.eventData is 'object') data = $.extend(true, {}, this.attr.eventData, data) $element.trigger((event || type), data) if (defaultFn && !event.isDefaultPrevented()) (this[defaultFn] || defaultFn).call(this) $element this.on = -> # var $element, type, callback, originalCb; lastIndex = arguments.length - 1 origin = arguments[lastIndex] if (typeof origin == 'object') # delegate callback originalCb = utils.delegate(this.resolveDelegateRules(origin)) else if (typeof origin == 'string') originalCb = proxyEventTo(origin) else originalCb = origin if (lastIndex == 2) $element = $(arguments[0]) type = arguments[1] else $element = this.$node type = arguments[0] if (typeof originalCb != 'function' && typeof originalCb != 'object') throw new Error('Unable to bind to "' + type + '" because the given callback is not a function or an object') callback = originalCb.bind(this) callback.target = originalCb callback.context = this $element.on(type, callback) # store every bound version of the callback originalCb.bound || (originalCb.bound = []) originalCb.bound.push(callback) callback this.off = -> # var $element, type, callback; lastIndex = arguments.length - 1 if (typeof arguments[lastIndex] == 'function') callback = arguments[lastIndex] lastIndex -= 1 if (lastIndex == 1) $element = $(arguments[0]) type = arguments[1] else $element = this.$node type = arguments[0] if (callback) # set callback to version bound against this instance callback.bound && callback.bound.some((fn, i, arr) -> if (fn.context && (this.identity == fn.context.identity)) arr.splice(i, 1) callback = fn return true , this) $element.off(type, callback) this.resolveDelegateRules = (ruleInfo) -> rules = {} Object.keys(ruleInfo).forEach((r) -> if (!(r in this.attr)) throw new Error('Component "' + this.toString() + '" wants to listen on "' + r + '" but no such attribute was defined.') rules[this.attr[r]] = if (typeof ruleInfo[r] == 'string') then proxyEventTo(ruleInfo[r]) else ruleInfo[r] , this) rules this.defaultAttrs = (defaults) -> utils.push(this.defaults, defaults, true) || (this.defaults = defaults) this.select = (attributeKey) -> this.$node.find(this.attr[attributeKey]) this.initialize = (node, attrs) -> attrs || (attrs = {}) # only assign identity if there isn't one (initialize can be called multiple times) this.identity || (this.identity = componentId++) if (!node) throw new Error('Component needs a node') # if (node.jquery) { # this.node = node[0]; # this.$node = node; # } else { this.node = node # this.$node = $(node); # } # merge defaults with supplied options # put options in attr.__proto__ to avoid merge overhead attr = Object.create(attrs) for own key of this.defaults if (!attrs.hasOwnProperty(key)) attr[key] = this.defaults[key] this.attr = attr for own key, val of this.defaults || {} if (val is null && this.attr[key] is null) throw new Error('Required attribute "' + key + '" not specified in attachTo for component "' + this.toString() + '".') this this.teardown = -> teardownInstance(registry.findInstanceInfo(this))
true
# ========================================== # Copyright 2014 PI:NAME:<NAME>END_PI, Lab. # Licensed under The MIT License # http://opensource.org/licenses/MIT # ========================================== define [ './utils' './registry' './debug' ], (utils, registry, debug) -> "use strict" # common mixin allocates basic functionality - used by all component prototypes # callback context is bound to component componentId = 0 teardownInstance= (instanceInfo) -> instance = instanceInfo.instance for event in instanceInfo.events.slice() args = [event.type] event.element && args.unshift(event.element); (typeof event.callback == 'function') && args.push(event.callback) instance.off.apply(instance, args) checkSerializable= (type, data) -> try window.postMessage(data, '*') catch e console.log('unserializable data for event', type, ':', data) throw new Error( ['The event', type, 'on component', this.toString(), 'was triggered with non-serializable data'].join(' ') ) proxyEventTo= (targetEvent) -> (e, data) -> $(e.target).trigger(targetEvent, data) -> # delegate trigger, bind and unbind to an element # if $element not supplied, use component's node # other arguments are passed on # event can be either a string specifying the type # of the event, or a hash specifying both the type # and a default function to be called. this.trigger = -> # var $element, type, data, event, defaultFn; lastIndex = arguments.length - 1 lastArg = arguments[lastIndex] if (typeof lastArg != 'string' && !(lastArg && lastArg.defaultBehavior)) lastIndex-- data = lastArg if (lastIndex == 1) $element = $(arguments[0]) event = arguments[1] else $element = this.$node event = arguments[0] if (event.defaultBehavior) defaultFn = event.defaultBehavior event = $.Event(event.type) type = event.type || event if (debug.enabled && window.postMessage) checkSerializable.call(this, type, data) if (typeof this.attr.eventData is 'object') data = $.extend(true, {}, this.attr.eventData, data) $element.trigger((event || type), data) if (defaultFn && !event.isDefaultPrevented()) (this[defaultFn] || defaultFn).call(this) $element this.on = -> # var $element, type, callback, originalCb; lastIndex = arguments.length - 1 origin = arguments[lastIndex] if (typeof origin == 'object') # delegate callback originalCb = utils.delegate(this.resolveDelegateRules(origin)) else if (typeof origin == 'string') originalCb = proxyEventTo(origin) else originalCb = origin if (lastIndex == 2) $element = $(arguments[0]) type = arguments[1] else $element = this.$node type = arguments[0] if (typeof originalCb != 'function' && typeof originalCb != 'object') throw new Error('Unable to bind to "' + type + '" because the given callback is not a function or an object') callback = originalCb.bind(this) callback.target = originalCb callback.context = this $element.on(type, callback) # store every bound version of the callback originalCb.bound || (originalCb.bound = []) originalCb.bound.push(callback) callback this.off = -> # var $element, type, callback; lastIndex = arguments.length - 1 if (typeof arguments[lastIndex] == 'function') callback = arguments[lastIndex] lastIndex -= 1 if (lastIndex == 1) $element = $(arguments[0]) type = arguments[1] else $element = this.$node type = arguments[0] if (callback) # set callback to version bound against this instance callback.bound && callback.bound.some((fn, i, arr) -> if (fn.context && (this.identity == fn.context.identity)) arr.splice(i, 1) callback = fn return true , this) $element.off(type, callback) this.resolveDelegateRules = (ruleInfo) -> rules = {} Object.keys(ruleInfo).forEach((r) -> if (!(r in this.attr)) throw new Error('Component "' + this.toString() + '" wants to listen on "' + r + '" but no such attribute was defined.') rules[this.attr[r]] = if (typeof ruleInfo[r] == 'string') then proxyEventTo(ruleInfo[r]) else ruleInfo[r] , this) rules this.defaultAttrs = (defaults) -> utils.push(this.defaults, defaults, true) || (this.defaults = defaults) this.select = (attributeKey) -> this.$node.find(this.attr[attributeKey]) this.initialize = (node, attrs) -> attrs || (attrs = {}) # only assign identity if there isn't one (initialize can be called multiple times) this.identity || (this.identity = componentId++) if (!node) throw new Error('Component needs a node') # if (node.jquery) { # this.node = node[0]; # this.$node = node; # } else { this.node = node # this.$node = $(node); # } # merge defaults with supplied options # put options in attr.__proto__ to avoid merge overhead attr = Object.create(attrs) for own key of this.defaults if (!attrs.hasOwnProperty(key)) attr[key] = this.defaults[key] this.attr = attr for own key, val of this.defaults || {} if (val is null && this.attr[key] is null) throw new Error('Required attribute "' + key + '" not specified in attachTo for component "' + this.toString() + '".') this this.teardown = -> teardownInstance(registry.findInstanceInfo(this))
[ { "context": "Title: WIKIEDU ASSIGNMENT DESIGN WIZARD\n# Author: kevin@wintr.us @ WINTR\n#########################################", "end": 126, "score": 0.9999076724052429, "start": 112, "tag": "EMAIL", "value": "kevin@wintr.us" } ]
source/javascripts/app.coffee
WikiEducationFoundation/WikiEduWizard
1
######################################################### # Title: WIKIEDU ASSIGNMENT DESIGN WIZARD # Author: kevin@wintr.us @ WINTR ######################################################### Application = initialize: -> @WizardConfig = require('./data/WizardConfig') @timelineData = require('./data/TimelineData') @timelineDataAlt = require('./data/TimelineDataAlt') # Import views HomeView = require('./views/HomeView') LoginView = require('./views/LoginView') Router = require('./routers/Router') InputItemView = require('./views/InputItemView') OutputView = require('./views/OutputView') # Initialize views @homeView = new HomeView() @loginView = new LoginView() @inputItemView = new InputItemView() @outputView = new OutputView() @router = new Router() module.exports = Application
179896
######################################################### # Title: WIKIEDU ASSIGNMENT DESIGN WIZARD # Author: <EMAIL> @ WINTR ######################################################### Application = initialize: -> @WizardConfig = require('./data/WizardConfig') @timelineData = require('./data/TimelineData') @timelineDataAlt = require('./data/TimelineDataAlt') # Import views HomeView = require('./views/HomeView') LoginView = require('./views/LoginView') Router = require('./routers/Router') InputItemView = require('./views/InputItemView') OutputView = require('./views/OutputView') # Initialize views @homeView = new HomeView() @loginView = new LoginView() @inputItemView = new InputItemView() @outputView = new OutputView() @router = new Router() module.exports = Application
true
######################################################### # Title: WIKIEDU ASSIGNMENT DESIGN WIZARD # Author: PI:EMAIL:<EMAIL>END_PI @ WINTR ######################################################### Application = initialize: -> @WizardConfig = require('./data/WizardConfig') @timelineData = require('./data/TimelineData') @timelineDataAlt = require('./data/TimelineDataAlt') # Import views HomeView = require('./views/HomeView') LoginView = require('./views/LoginView') Router = require('./routers/Router') InputItemView = require('./views/InputItemView') OutputView = require('./views/OutputView') # Initialize views @homeView = new HomeView() @loginView = new LoginView() @inputItemView = new InputItemView() @outputView = new OutputView() @router = new Router() module.exports = Application
[ { "context": "module.exports =\n\towner: '责任人'\n\townerTips: '未指定'\n\tfinishDate: '完成日期'\n\tpriorityT", "end": 29, "score": 0.811225414276123, "start": 26, "tag": "NAME", "value": "责任人" } ]
src/i18n/zh-cn/client/issue.coffee
kiteam/kiteam
0
module.exports = owner: '责任人' ownerTips: '未指定' finishDate: '完成日期' priorityTips: '请选择优先级' categoryTips: '请选择分类'
117228
module.exports = owner: '<NAME>' ownerTips: '未指定' finishDate: '完成日期' priorityTips: '请选择优先级' categoryTips: '请选择分类'
true
module.exports = owner: 'PI:NAME:<NAME>END_PI' ownerTips: '未指定' finishDate: '完成日期' priorityTips: '请选择优先级' categoryTips: '请选择分类'
[ { "context": "EntityDropdown\n model: model\n key: @id\n multiple: @attributes.multiple\n re", "end": 191, "score": 0.6097460985183716, "start": 189, "tag": "KEY", "value": "id" } ]
app/vendor/kalnoy/cruddy/resources/assets/coffee/fields/relation.coffee
EH7AN/lawyers
0
class Cruddy.Fields.Relation extends Cruddy.Fields.BaseRelation createInput: (model, inputId, forceDisable = no) -> new Cruddy.Inputs.EntityDropdown model: model key: @id multiple: @attributes.multiple reference: @getReferencedEntity() owner: @entity.id + "." + @id constraint: @attributes.constraint enabled: not forceDisable and @isEditable(model) createFilterInput: (model) -> new Cruddy.Inputs.EntityDropdown model: model key: @id reference: @getReferencedEntity() allowEdit: no placeholder: Cruddy.lang.any_value owner: @entity.id + "." + @id constraint: @attributes.constraint multiple: yes isEditable: -> @getReferencedEntity().readPermitted() and super canFilter: -> @getReferencedEntity().readPermitted() and super formatItem: (item) -> ref = @getReferencedEntity() return item.title unless ref.readPermitted() """<a href="#{ ref.link item.id }">#{ _.escape item.title }</a>""" prepareAttribute: (value) -> return null unless value? return _.pluck(value, "id").join(",") if _.isArray value return value.id prepareFilterData: (value) -> value = super if _.isEmpty value then null else value parseFilterData: (value) -> return null unless _.isString(value) or _.isNumber(value) value = value.toString() return null unless value.length value = value.split "," return _.map value, (value) -> { id: value }
171537
class Cruddy.Fields.Relation extends Cruddy.Fields.BaseRelation createInput: (model, inputId, forceDisable = no) -> new Cruddy.Inputs.EntityDropdown model: model key: @<KEY> multiple: @attributes.multiple reference: @getReferencedEntity() owner: @entity.id + "." + @id constraint: @attributes.constraint enabled: not forceDisable and @isEditable(model) createFilterInput: (model) -> new Cruddy.Inputs.EntityDropdown model: model key: @id reference: @getReferencedEntity() allowEdit: no placeholder: Cruddy.lang.any_value owner: @entity.id + "." + @id constraint: @attributes.constraint multiple: yes isEditable: -> @getReferencedEntity().readPermitted() and super canFilter: -> @getReferencedEntity().readPermitted() and super formatItem: (item) -> ref = @getReferencedEntity() return item.title unless ref.readPermitted() """<a href="#{ ref.link item.id }">#{ _.escape item.title }</a>""" prepareAttribute: (value) -> return null unless value? return _.pluck(value, "id").join(",") if _.isArray value return value.id prepareFilterData: (value) -> value = super if _.isEmpty value then null else value parseFilterData: (value) -> return null unless _.isString(value) or _.isNumber(value) value = value.toString() return null unless value.length value = value.split "," return _.map value, (value) -> { id: value }
true
class Cruddy.Fields.Relation extends Cruddy.Fields.BaseRelation createInput: (model, inputId, forceDisable = no) -> new Cruddy.Inputs.EntityDropdown model: model key: @PI:KEY:<KEY>END_PI multiple: @attributes.multiple reference: @getReferencedEntity() owner: @entity.id + "." + @id constraint: @attributes.constraint enabled: not forceDisable and @isEditable(model) createFilterInput: (model) -> new Cruddy.Inputs.EntityDropdown model: model key: @id reference: @getReferencedEntity() allowEdit: no placeholder: Cruddy.lang.any_value owner: @entity.id + "." + @id constraint: @attributes.constraint multiple: yes isEditable: -> @getReferencedEntity().readPermitted() and super canFilter: -> @getReferencedEntity().readPermitted() and super formatItem: (item) -> ref = @getReferencedEntity() return item.title unless ref.readPermitted() """<a href="#{ ref.link item.id }">#{ _.escape item.title }</a>""" prepareAttribute: (value) -> return null unless value? return _.pluck(value, "id").join(",") if _.isArray value return value.id prepareFilterData: (value) -> value = super if _.isEmpty value then null else value parseFilterData: (value) -> return null unless _.isString(value) or _.isNumber(value) value = value.toString() return null unless value.length value = value.split "," return _.map value, (value) -> { id: value }
[ { "context": "name: \"Turing\"\nscopeName: \"source.turing\"\nfileTypes: [\"t\", \"tu\"", "end": 13, "score": 0.9361127614974976, "start": 7, "tag": "NAME", "value": "Turing" } ]
lsp-client/vscode/syntaxes/turing.cson
DropDemBits/turse-rs
1
name: "Turing" scopeName: "source.turing" fileTypes: ["t", "tu"] firstLineMatch: """(?x) # Emacs modeline -\\*-(?i:[ \\t]*(?=[^:;\\s]+[ \\t]*-\\*-)|(?:.*?[ \\t;]|(?<=-\\*-))[ \\t]*mode[ \\t]*:[ \\t]*) (?i:turing) (?=[ \\t;]|(?<![-*])-\\*-).*?-\\*- | # Vim modeline (?:(?:^|[ \\t])(?:vi|Vi(?=m))(?:m[<=>]?[0-9]+|m)?|[ \\t]ex)(?=:(?=[ \\t]*set?[ \\t][^\\r\\n:]+:)|:(?![ \\t]*set?[ \\t])) (?:(?:[ \\t]*:[ \\t]*|[ \\t])\\w*(?:[ \\t]*=(?:[^\\\\\\s]|\\\\.)*)?)*[ \\t:] (?:filetype|ft|syntax)[ \\t]*= (?i:turing) (?=$|\\s|:) """ patterns: [include: "#main"] repository: # Common patterns main: patterns: [ { include: "#comments" } { include: "#boolean" } { include: "#strings" } { include: "#numbers" } { include: "#cc" } { include: "#for" } { include: "#loop" } { include: "#if" } { include: "#case" } { include: "#block" } { include: "#function" } { include: "#modifiers" } { include: "#variables" } { include: "#punctuation" } { include: "#forward" } { include: "#procedure" } { include: "#process" } { include: "#handler" } { include: "#class" } { include: "#type" } { include: "#record" } { include: "#union" } { include: "#types" } { include: "#keywords" } { include: "#function-call" } { include: "#stdlib" } ] # Comments comments: patterns: [{ # End-of-line comment name: "comment.line.percentage.turing" begin: "%" end: "$" beginCaptures: 0: name: "punctuation.definition.comment.turing" },{ # Bracketed name: "comment.block.bracketed.turing" begin: "/\\*" end: "\\*/" beginCaptures: 0: name: "punctuation.definition.comment.turing" endCaptures: 0: name: "punctuation.definition.comment.turing" }] # String literals strings: patterns: [ {name: "string.quoted.double.turing", begin: '"', end: '"', patterns: [include: "#escapes"]} {name: "string.quoted.single.turing", begin: "'", end: "'", patterns: [include: "#escapes"]} ] # Numbers numbers: patterns: [ {name: "constant.numeric.base-16.hex.turing", match: "16#[A-Fa-f0-9]+"} {name: "constant.numeric.base-$1.turing", match: "(\\d+)#\\d+"} {name: "constant.numeric.float.turing", match: "\\b\\d+\\.\\d+(?:[Ee][\\+\\-]?\\d+)?\\b"} {name: "constant.numeric.int.turing", match: "\\b\\d+\\b"} ] # List of named values list: patterns: [ {match: "\\w+", name: "variable.name.turing"} {match: ",", name: "meta.delimiter.object.comma.turing"} ] # Escaped characters escapes: patterns: [ {match: '\\\\"', name: "constant.character.escape.double-quote.turing"} {match: "\\\\'", name: "constant.character.escape.single-quote.turing"} {match: "\\\\[nN]", name: "constant.character.escape.newline.turing"} {match: "\\\\[tT]", name: "constant.character.escape.tab.turing"} {match: "\\\\[fF]", name: "constant.character.escape.form-feed.turing"} {match: "\\\\[rR]", name: "constant.character.escape.return.turing"} {match: "\\\\[bB]", name: "constant.character.escape.backspace.turing"} {match: "\\\\[eE]", name: "constant.character.escape.esc.turing"} {match: "\\\\\\\\", name: "constant.character.escape.backslash.turing"} ] # Function declaration function: name: "meta.function.turing" begin: """(?x) \\b (?: (body) # 1: storage.modifier.body.turing \\s+ )? (function|fcn) # 2: storage.type.function.turing (?: \\s+ (pervasive|\\*) # 3: storage.modifier.pervasive.turing )? \\s+ (\\w+) # 4: entity.name.function.turing \\s* ( # 5: meta.function.parameters.turing (\\() # 6: punctuation.definition.parameters.begin.turing (.*) # 7: include: “#param-declarations” (\\)) # 8: punctuation.definition.parameters.end.turing ) \\s* (:) # 9: punctuation.separator.key-value.turing \\s* (\\w+) # 10: storage.type.type-spec.turing """ end: "\\b(end)\\s+(\\4)" patterns: [{ # pre|init|post clause name: "meta.$1-function.turing" begin: "^\\s*(pre|init|post)(?=\\s|$)" end: "$" patterns: [include: "$self"] beginCaptures: 1: name: "keyword.function.$1.turing" },{ include: "$self" } ] beginCaptures: 1: name: "storage.modifier.body.turing" 2: name: "storage.type.function.turing" 3: name: "storage.modifier.pervasive.turing" 4: name: "entity.name.function.turing" 5: name: "meta.function.parameters.turing" 6: name: "punctuation.definition.parameters.begin.turing" 7: patterns: [include: "#param-declarations"] 8: name: "punctuation.definition.parameters.end.turing" 9: name: "punctuation.separator.key-value.turing" 10: name: "storage.type.type-spec.turing" endCaptures: 1: name: "storage.type.function.end.turing" 2: name: "entity.name.function.turing" # Function parameters "param-declarations": match: "\\b(\\w+)\\s+(:)\\s+((\\w+))" captures: 1: name: "variable.parameter.function.turing" 2: name: "storage.type.turing" 3: patterns: [include: "#types"] # Function call "function-call": patterns: [{ # functionName ( args ) name: "meta.function-call.turing" begin: /(([\w.]+))\s*(\()/ end: /\)/ contentName: "meta.function-call.arguments.turing" beginCaptures: 1: name: "entity.function.name.turing" 2: patterns: [include: "#function-name"] 3: name: "punctuation.definition.arguments.begin.turing" endCaptures: 0: name: "punctuation.definition.arguments.end.turing" patterns: [include: "$self"] },{ # functionName name: "meta.function-call.turing" match: /^\s*(([\\w.]+))\s*(?=$|%|\/\*)/ captures: 1: name: "entity.function.name.turing" 2: patterns: [include: "#function-name"] }] # Function name: Wrapper for bundled inclusions "function-name": patterns: [ {include: "#stdlib"} {match: "\\.", name: "punctuation.separator.method.turing"} ] # Keywords keywords: patterns: [{ # Control flow match: /// \b( (?:end\s+)?if|(?:end\s+)?loop|(?:end\s+)?for|(?:end\s+)?case| endif|endloop|endfor|endcase|label| then|elsif|elseif|elif|else|exit|when|include|in|begin|end|by )\b /// name: "keyword.control.$1.turing" },{ # Logical operators match: /\b(and|not|x?or)\b/ name: "keyword.operator.logical.$1.turing" },{ # Other operators match: /\b(all|bits|cheat|decreasing|div|lower|mod|nil|of|rem|shl|shr|to|unit|upper)\b/ name: "keyword.operator.$1.turing" },{ # Statements match: /\b(asm|begin|break|close|exit|fork|free|get|init|new|objectclass|open|pause|put|quit|read|result|return|seek|signal|tag|tell|wait|write)\b/ name: "keyword.other.statement.$1.turing" },{ # Items patterns: [{ # General match: /\b(class|module|monitor|const|var|type)\b/ name: "storage.type.$1.turing" },{ # Function-like items match: /\b(function|fcn|procedure|proc|process)\b/ name: "storage.type.function.turing" },{ # Handler match: /\b(handler)\b/ name: "storage.type.handler.turing" }] },{ # Other patterns: [{ match: /\b(import|export)\b/ name: "keyword.other.$1.turing" },{ match: /\b(pre|post|assert|invariant)\b/ name: "keyword.function.$1.turing" }] },{ # Character type of specified length match: /\b(char)\s*(\()(\d+)(\))/ name: "storage.type.$3-char.turing" captures: 2: name: "punctuation.definition.arguments.begin.turing" 4: name: "punctuation.definition.arguments.end.turing" },{ # Colour constants match: ///\b (black|blue|brightblue|brightcyan|brightgreen|brightmagenta|brightpurple|brightred |brightwhite|brown|colou?r[bf]g|cyan|darkgr[ae]y|gr[ae]y|green|magenta|purple|red |white|yellow)\b/// name: "constant.other.colour.turing" },{ # Language variables match: /\b(skip|self)\b/ name: "constant.language.$1.turing" }] # Various modifier keywords modifiers: patterns: [{ # Checked/unchecked match: /\b(unchecked|checked)\b/ name: "storage.modifier.$1.compiler-directive.oot.turing" },{ # Unqualified match: /\b(unqualified|~(?=\s*\.))\b/ name: "storage.modifier.unqualified.turing" },{ # Implement match: /\b(implement)\b/ name: "storage.modifier.implements.turing" },{ # Other match: /\b(body|def|deferred|forward|external|flexible|inherit|opaque|packed|timeout|priority)\b/ name: "storage.modifier.$1.turing" },{ # OOT other match: /\b(pervasive|register)\b/ name: "storage.modifier.$1.oot.turing" }] # Types types: match: /// \b( addressint|array|boolean|char|string|collection|enum| int[124]?|nat[124]?|real[48]?|pointer(\s+to)?|set(\s+of)?| record|union|condition )\b /// name: "storage.type.$1-type.turing" # Conditional compilation cc: name: "meta.preprocessor.$3.turing" match: "^\\s*((#)((?:end\\s+)?if|elsif|else))" captures: 1: name: "keyword.control.directive.conditional.turing" 2: name: "punctuation.definition.directive.turing" # For loops for: name: "meta.scope.for-loop.turing" begin: "^\\s*(for)\\b(?:\\s+(decreasing)\\b)?" end: "^\\s*(end)\\s+(for)" patterns: [{ match: "\\G(.*?)\\b(by)\\b" captures: 1: patterns: [include: "$self"] 2: name: "keyword.control.by.turing" }, include: "$self"] beginCaptures: 0: name: "meta.scope.begin.turing" 1: name: "keyword.control.for.turing" 2: name: "keyword.operator.decreasing.turing" endCaptures: 0: name: "meta.scope.end.turing" 1: name: "keyword.control.for.end.turing" 2: name: "keyword.control.for.turing" # Loop loops loop: name: "meta.scope.loop.turing" begin: /\b(loop)\b/ end: /\b(end)\s*(loop)\b/ patterns: [{ include: "$self" }] beginCaptures: 0: name: "meta.scope.begin.turing" 1: name: "keyword.control.loop.turing" endCaptures: 0: name: "meta.scope.end.turing" 1: name: "keyword.control.loop.end.turing" 2: name: "keyword.control.loop.turing" # Conditional execution if: name: "meta.scope.if-block.turing" begin: /\b(if)\b/ end: /\b(end\s+if)\b/ beginCaptures: 0: name: "meta.scope.begin.turing" 1: name: "keyword.control.conditional.turing" endCaptures: 0: name: "meta.scope.end.turing" 1: name: "keyword.control.conditional.turing" patterns: [include: "$self"] # Case blocks case: name: "meta.scope.case-block.turing" begin: "^\\s*(case)\\s+(\\w+)\\s+(of)\\b" end: "^\\s*(end\\s+case)\\b" patterns: [ {include: "#label"} {include: "$self"} ] beginCaptures: 0: name: "meta.scope.begin.turing" 1: name: "keyword.control.case.turing" 2: name: "variable.parameter.turing" 3: name: "keyword.operator.of.turing" endCaptures: 0: name: "meta.scope.end.turing" 1: name: "keyword.control.case.end.turing" # Label statements label: name: "meta.label.turing" begin: "\\b(label)\\b" end: ":" beginCaptures: 1: name: "keyword.other.statement.label.turing" endCaptures: 0: name: "punctuation.separator.key-value.turing" patterns: [ {include: "$self"} {include: "#list"} ] # Block statements block: name: "meta.scope.block.turing" begin: /\b(begin)\b/ end: /\b(end)\s*(?!for|loop|case|if|\w+)/ beginCaptures: 0: name: "meta.scope.begin.turing" 1: name: "keyword.control.begin.turing" endCaptures: 0: name: "meta.scope.end.turing" 1: name: "keyword.control.end.turing" patterns: [ { include: "$self" } ] # Forward/deferred procedure forward: patterns: [{ # Procedure name: "meta.$1.procedure.turing" begin: "^\\s*\\b(deferred|forward)\\s+(procedure|proc)\\s+(\\w+)" end: "(?=$|%|/\\*)" beginCaptures: 1: name: "storage.modifier.$1.turing" 2: name: "storage.type.function.turing" 3: name: "entity.name.function.turing" patterns: [ {include: "#parameters"} {include: "$self"} ] },{ # Function name: "meta.$1.function.turing" begin: "^\\s*\\b(deferred|forward)\\s+(function|fcn)\\s+(\\w+)" end: "(?=$|%|/\\*)" beginCaptures: 1: name: "storage.modifier.$1.turing" 2: name: "storage.type.function.turing" 3: name: "entity.name.function.turing" patterns: [ {include: "#parameters"} {include: "$self"} ] }] # Procedure declaration procedure: name: "meta.scope.procedure.turing" begin: "^\\s*(?:(body)\\s+)?(procedure|proc)\\s+(\\w+)" end: "^\\s*(end)\\s+(\\3)" patterns: [ {include: "#parameters"} {include: "$self"} ] beginCaptures: 0: name: "meta.scope.begin.turing" 1: name: "storage.modifier.$1.turing" 2: name: "storage.type.function.turing" 3: name: "entity.name.function.turing" endCaptures: 0: name: "meta.scope.end.turing" 1: name: "storage.type.function.end.turing" 2: name: "entity.name.function.turing" # Process statement process: name: "meta.scope.process.turing" begin: "^\\s*(process)(?:\\s+(pervasive|\\*)(?=\\s))?\\s+(\\w+)" end: "^\\s*(end)\\s+(\\3)" patterns: [ {include: "#parameters"} {include: "$self"} ] beginCaptures: 0: name: "meta.scope.begin.turing" 1: name: "storage.type.function.turing" 2: name: "storage.modifier.pervasive.turing" 3: name: "entity.name.function.turing" endCaptures: 0: name: "meta.scope.end.turing" 1: name: "storage.type.function.end.turing" 2: name: "entity.name.function.turing" # Bracketed parameter declarations used in procedure/process headers parameters: name: "meta.function.parameters.turing" begin: "\\G\\s*(\\()" end: "\\)" beginCaptures: 1: name: "punctuation.definition.arguments.begin.turing" endCaptures: 0: name: "punctuation.definition.arguments.end.turing" patterns: [ {include: "$self"} {match: "\\w+", name: "variable.parameter.function.turing"} ] # Exception handler handler: name: "meta.scope.handler.turing" begin: "^\\s*(handler)\\s*(\\()\\s*(\\w+)\\s*(\\))" end: "^\\s*(end)\\s+(handler)\\b" patterns: [include: "$self"] beginCaptures: 0: name: "meta.scope.begin.turing" 1: name: "storage.type.handler.turing" 2: name: "punctuation.definition.arguments.begin.turing" 3: name: "variable.parameter.handler.turing" 4: name: "punctuation.definition.arguments.end.turing" endCaptures: 0: name: "meta.scope.end.turing" 1: name: "storage.type.handler.end.turing" 2: name: "storage.type.handler.turing" # Class, module and monitor declarations class: name: "meta.scope.$1-block.turing" begin: /^\s*(class|module|monitor)\s+(\w+)/ end: /\b(end)\s+(\2)/ patterns: [ {include: "#class-innards"} {include: "$self"} ] beginCaptures: 0: name: "meta.scope.begin.turing" 1: name: "storage.type.$1.turing" 2: name: "entity.name.type.class.turing" endCaptures: 0: name: "meta.scope.end.turing" 1: name: "storage.type.$1.end.turing" 2: name: "entity.name.type.class.turing" # Various clauses for inheritance, importing/exporting, etc "class-innards": patterns: [{ # Import/export begin: "\\b(import|export)\\b" end: "(?=$|%|/\\*)" beginCaptures: 1: name: "keyword.other.$1.turing" patterns: [ {include: "#list"} {include: "$self"} ] },{ # Inherited class name: "meta.other.inherited-class.turing" begin: "\\b(inherit)\\b" end: "\\w+" beginCaptures: 1: name: "storage.modifier.inherit.turing" endCaptures: 0: name: "entity.other.inherited-class.turing" patterns: [include: "$self"] },{ # Implement/Implement by name: "meta.other.$1.turing" begin: "\\b(implement(?:\\s+by)?)\\b" end: "\\w+" beginCaptures: 1: name: "storage.modifier.implements.turing" endCaptures: 0: name: "entity.other.inherited-class.turing" patterns: [include: "$self"] }] # Variables and constants variables: patterns: [{ # Declaration name: "meta.variable-declaration.turing" begin: "\\b(var|const)\\s+" end: "(:=?)\\s*((?!\\d)((?:\\w+(?:\\s+to)?)(?:\\s*\\(\\s*\\d+\\s*\\))?))?\\s*(:=)?" beginCaptures: 1: name: "storage.type.$1.turing" endCaptures: 1: name: "punctuation.separator.key-value.turing" 2: name: "storage.type.type-spec.turing" 3: patterns: [include: "#types"] 4: name: "punctuation.separator.key-value.turing" patterns: [ # Object-oriented Turing: Additional keywords { match: "\\G(?:\\s*(pervasive|\\*)(?=\\s))?\\s*(register)(?=\\s)" captures: 1: name: "storage.modifier.pervasive.oot.turing" 2: name: "storage.modifier.register.oot.turing" } {include: "#types"} {include: "#list"} ] },{ # Assignment name: "meta.variable-assignment.turing" begin: "(\\w+)\\s*(:=)" end: "(?=\\S)" beginCaptures: 1: name: "variable.name.turing" 2: name: "punctuation.separator.key-value.turing" },{ # Bindings name: "meta.binding.turing" begin: "\\b(bind)\\b" end: "(?=$|%|/\\*)" beginCaptures: 1: name: "keyword.operator.bind.turing" patterns: [{ # Individual variable bindings begin: "\\b(var)\\b" end: "\\b(to)\\b" patterns: [include: "#list"] beginCaptures: 1: name: "storage.type.$1.turing" endCaptures: 1: name: "keyword.operator.to.turing" },{ # Comma separators include: "#list" }] }] # Boolean values boolean: name: "constant.language.boolean.$1.turing" match: "\\b(true|false)\\b" # Arithmetic/Punctuation punctuation: patterns: [ {match: "\\.\\.", name: "punctuation.definition.range.turing"} {match: ":=", name: "punctuation.separator.key-value.assignment.turing"} {match: "->", name: "punctuation.separator.class.accessor.turing"} {match: "\\+", name: "keyword.operator.arithmetic.add.turing"} {match: "-", name: "keyword.operator.arithmetic.subtract.turing"} {match: "\\*", name: "keyword.operator.arithmetic.multiply.turing"} {match: "\\/", name: "keyword.operator.arithmetic.divide.turing"} {match: "<=", name: "keyword.operator.logical.equal-or-less.subset.turing"} {match: ">=", name: "keyword.operator.logical.equal-or-greater.superset.turing"} {match: "<", name: "keyword.operator.logical.less.turing"} {match: ">", name: "keyword.operator.logical.greater.turing"} {match: "=", name: "keyword.operator.logical.equal.turing"} {match: "not=|~=", name: "keyword.operator.logical.not.turing"} {match: "\\^", name: "keyword.operator.pointer-following.turing"} {match: "#", name: "keyword.operator.type-cheat.turing"} {match: "@", name: "keyword.operator.indirection.turing"} {match: ":", name: "punctuation.separator.key-value.turing"} {match: "\\(", name: "punctuation.definition.arguments.begin.turing"} {match: "\\)", name: "punctuation.definition.arguments.end.turing"} ] # Type declaration type: match: "\\b(type)(?:\\s+(pervasive|\\*)(?=\\s))?\\s+(\\w+)" captures: 1: name: "storage.type.turing" 2: name: "storage.modifier.pervasive.turing" 3: name: "entity.name.type.turing" # Record declaration record: name: "meta.scope.record-block.turing" begin: "^\\s*(record)\\b" end: "^\\s*(end)\\s+(record)\\b" patterns: [{ # Field names match: "((\\s*\\w+\\s*,?)+)(:)" captures: 1: patterns: [include: "#list"] 3: name: "punctuation.separator.record.key-value.turing" }, include: "$self"] beginCaptures: 0: name: "meta.scope.begin.turing" 1: name: "storage.type.record.turing" endCaptures: 0: name: "meta.scope.end.turing" 1: name: "storage.type.record.end.turing" 2: name: "storage.type.record.turing" # Union/variant record union: name: "meta.scope.union.turing" begin: "^\\s*(union)\\s+(\\w+)\\s*(:)(.*)\\b(of)\\b" end: "^\\s*(end)\\s+(union)\\b" patterns: [ {include: "#label"} {include: "$self"} ] beginCaptures: 0: name: "meta.scope.begin.turing" 1: name: "storage.type.union.turing" 2: name: "entity.name.union.turing" 3: name: "punctuation.separator.key-value.turing" 4: patterns: [include: "$self"] 5: name: "keyword.operator.of.turing" endCaptures: 0: name: "meta.scope.end.turing" 1: name: "storage.type.union.end.turing" 2: name: "storage.type.union.turing" # Standard library stdlib: patterns: [ {include: "#modules"} {include: "#stdproc"} {match: "\\b(anyclass)\\b", name: "support.class.anyclass.turing"} # Routines/constants exported unqualified {include: "#keyboard-constants"} {include: "#math-routines"} {include: "#str-routines"} {include: "#typeconv-routines"} ] # Procedures not associated with any specific module stdproc: name: "support.function.${1:/downcase}.turing" match: """(?x)\\b (addr|buttonchoose|buttonmoved|buttonwait|clock|cls|colou?r|colou?rback|date|delay|drawarc|drawbox|drawdot |drawfill|drawfillarc|drawfillbox|drawfillmapleleaf|drawfilloval|drawfillpolygon|drawfillstar|drawline |drawmapleleaf|drawoval|drawpic|drawpolygon|drawstar|empty|eof|fetcharg|getch|getchar|getenv|getpid |getpriority|hasch|locate|locatexy|maxcol|maxcolou?r|maxint|maxnat|maxrow|maxx|maxy|minint|minnat |mousewhere|nargs|parallelget|parallelput|play|playdone|pred|rand|randint|randnext|randomize |randseed|setpriority|setscreen|simutime|sizeof|sizepic|sound|succ|sysclock|takepic|time|wallclock |whatcol|whatcolou?r|whatcolou?rback|whatdotcolou?r|whatrow)\\b """ # Keyboard constants: http://compsci.ca/holtsoft/doc/keyboardmodule.html "keyboard-constants": name: "support.constant.keyboard.turing" match: """(?x)\\b(?: (?:KEY|ORD)_(?: F1[0-2]|F[1-9]|CTRL_[A-Z]|ALT_[A-Z0-9]|(?:CTRL|ALT|SHIFT)_(?:F1[0-2]|F[1-9])| ALT(?:_EQUALS|_MINUS)?|BACK_TAB|BACKSPACE|CTRL|DELETE|END|ENTER|ESC|HOME|INSERT|KEYPAD_5|PGDN|PGUP|SHIFT|SHIFT_TAB|TAB| CTRL_(?:BACKSLASH|BACKSPACE|CARET|(?:UP|RIGHT|LEFT|DOWN)_ARROW|CLOSE_BRACKET|DELETE|END|HOME|INSERT|OPEN_BRACKET|PGDN|PGUP|UNDERSCORE)| (?:UP|RIGHT|LEFT|DOWN)_ARROW) | ORD_(?: AMPERSAND|APOSTROPHE|ASTERISK|BACKSLASH|BAR|CARET|COLON|COMMA|DOT|EQUALS|(?:GREATER|LESS)_THAN| (?:CLOSE|OPEN)_(?:BRACE|BRACKET|PARENTHESIS)|(?:EXCALAMATION|HAS|QUESTION|QUOTATION)_MARK|MINUS| (?:AT|DOLLAR|PERCENT)_SIGN|PERIOD|PLUS|SEMICOLON|SINGLE_QUOTE|SLASH|SPACE|TILDE|UNDERSCORE|[A-Z0-9]|LOWER_[A-Z]) )\\b """ # Math routines: http://compsci.ca/holtsoft/doc/mathmodule.html "math-routines": name: "support.function.${1:/downcase}.turing" match: "\\b(abs|arccos|arccosd|arcsin|arcsind|arctan|arctand|cos|cosd|exp|ln|max|min|sign|sin|sind|tan|tand|sqrt)\\b" # Str routines: http://compsci.ca/holtsoft/doc/strmodule.html "str-routines": name: "support.function.${1:/downcase}.turing" match: "\\b(Lower|Upper|Trim|index|length|repeat)\\b" # TypeConv routines: http://compsci.ca/holtsoft/doc/typeconvmodule.html "typeconv-routines": name: "support.function.${1:/downcase}.turing" match: "\\b(ceil|chr|erealstr|floor|frealstr|intreal|intstr|natreal|natstr|ord|realstr|round|strint|strintok|strnat|strnatok|strreal|strrealok)\\b" # Modules modules: patterns: [{ # Concurrency match: "\\b(Concurrency)\\b(?:(\\.)(empty|[gs]etpriority|simutime)?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.function.$3.turing" },{ # Config match: "\\b(Config)\\b(?:(\\.)(Display|Lang|Machine)?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.function.${3:/downcase}.turing" },{ # Dir match: "\\b(Dir)\\b(?:(\\.)(Change|Close|Create|Current|Delete|Get|GetLong|Open)?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.function.${3:/downcase}.turing" },{ # Draw match: "\\b(Draw)\\b(?:(\\.)(Arc|Box|Cls|Dot|Fill|FillArc|FillBox|FillMapleLeaf|FillOval|FillPolygon|FillStar|Line|MapleLeaf|Oval|Polygon|Star|Text)?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.function.${3:/downcase}.turing" },{ # Error match: "\\b(Error)\\b(?:(\\.)(Last|LastMsg|LastStr|Msg|Str|Trip)?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.function.${3:/downcase}.turing" },{ # ErrorNum/Exceptions match: "\\b(ErrorNum|Exceptions)\\b(?:(\\.)(\\w+)?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.function.${3:/downcase}.turing" },{ # File match: "\\b(File)\\b(?:(\\.)(Copy|Delete|DiskFree|Exists|Rename|Status)?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.function.${3:/downcase}.turing" },{ # Font match: "\\b(Font)\\b(?:(\\.)(Draw|Free|GetName|GetSize|GetStyle|Name|New|Sizes|StartName|StartSize|Width)?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.function.${3:/downcase}.turing" },{ # GUI match: """(?x)\\b(GUI)\\b(?:(\\.) (AddLine|AddText|Alert|Alert2|Alert3|AlertFull|Choose|ChooseFull|ClearText|CloseWindow|CreateButton|CreateButtonFull |CreateCanvas|CreateCanvasFull|CreateCheckBox|CreateCheckBoxFull|CreateFrame|CreateHorizontalScrollBar|CreateHorizontalScrollBarFull |CreateHorizontalSlider|CreateLabel|CreateLabelFull|CreateLabelledFrame|CreateLine|CreateMenu|CreateMenuItem|CreateMenuItemFull |CreatePicture|CreatePictureButton|CreatePictureButtonFull|CreatePictureRadioButton|CreatePictureRadioButtonFull|CreateRadioButton |CreateRadioButtonFull|CreateTextBox|CreateTextBoxFull|CreateTextField|CreateTextFieldFull|CreateVerticalScrollBar|CreateVerticalScrollBarFull |CreateVerticalSlider|Disable|Dispose|DrawArc|DrawBox|DrawCls|DrawDot|DrawFill|DrawFillArc|DrawFillBox|DrawFillMapleLeaf|DrawFillOval |DrawFillPolygon|DrawFillStar|DrawLine|DrawMapleLeaf|DrawOval|DrawPolygon|DrawStar|DrawText|Enable|FontDraw|GetCheckBox|GetEventTime |GetEventWidgetID|GetEventWindow|GetHeight|GetMenuBarHeight|GetScrollBarWidth|GetSliderValue|GetText|GetVersion|GetWidth|GetX|GetY|Hide |HideMenuBar|OpenFile|OpenFileFull|PicDraw|PicNew|PicScreenLoad|PicScreenSave|ProcessEvent|Quit|Refresh|SaveFile|SaveFileFull|SelectRadio |SetActive|SetBackgroundColor|SetBackgroundColour|SetCheckBox|SetDefault|SetDisplayWhenCreated|SetKeyEventHandler|SetLabel|SetMouseEventHandler |SetNullEventHandler|SetPosition|SetPositionAndSize|SetScrollAmount|SetSelection|SetSize|SetSliderMinMax|SetSliderReverse|SetSliderSize |SetSliderValue|SetText|SetXOR|Show|ShowMenuBar)?\\b)? """ captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.function.${3:/downcase}.turing" },{ # Input match: "\\b(Input)\\b(?:(\\.)(getch|getchar|hasch|KeyDown|Pause)?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.function.${3:/downcase}.turing" },{ # Joystick match: "\\b(Joystick)\\b(?:(\\.)(GetInfo)?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.function.${3:/downcase}.turing" },{ # Keyboard match: "\\b(Keyboard)\\b(?:(\\.)(\\w+)?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: patterns: [include: "#keyboard-constants"] },{ # Limits match: "\\b(Limits)\\b(?:(\\.)(DefaultFW|DefaultEW|minint|maxint|minnat|maxnat)?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.function.${3:/downcase}.turing" },{ # Math match: "(?x)\\b(Math)\\b(?:(\\.)(?:(PI|E)|(Distance|DistancePointLine)|(\\w+))?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.constant.${3:/downcase}.turing" 4: name: "support.function.${4:/downcase}.turing" 5: patterns: [include: "#math-routines"] },{ # Mouse match: "\\b(Mouse)\\b(?:(\\.)(ButtonChoose|ButtonMoved|ButtonWait|Where)?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.function.${3:/downcase}.turing" },{ # Music match: "\\b(Music)\\b(?:(\\.)(Play|PlayFile|PlayFileStop|Sound|SoundOff)?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.function.${3:/downcase}.turing" },{ # Net match: """(?x) \\b(Net)\\b(?:(\\.) (BytesAvailable|CharAvailable|CloseConnection|HostAddressFromName|HostNameFromAddress |LineAvailable|LocalAddress|LocalName|OpenConnection|OpenURLConnection|TokenAvailable |WaitForConnection)?\\b)?""" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.function.${3:/downcase}.turing" },{ # PC match: "\\b(PC)\\b(?:(\\.)(ParallelGet|ParallelPut)?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.function.${3:/downcase}.turing" },{ # Pic match: """(?x) \\b(Pic)\\b(?:(\\.) (Blend|Blur|Draw|DrawFrames|DrawFramesBack|DrawSpecial|DrawSpecialBack|FileNew |FileNewFrames|Flip|Frames|Free|Height|Mirror|New|Rotate|Save|Scale|ScreenLoad |ScreenSave|SetTransparentColou?r|Width)? \\b)?""" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.function.${3:/downcase}.turing" },{ # Rand match: "\\b(Rand)\\b(?:(\\.)(Int|Next|Real|Reset|Seed|Set)?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.function.${3:/downcase}.turing" },{ # RGB match: "\\b(RGB)\\b(?:(\\.)(AddColou?r|[GS]etColou?r|maxcolou?r)?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.function.${3:/downcase}.turing" },{ # Sprite match: "\\b(Sprite)\\b(?:(\\.)(Animate|ChangePic|Free|Hide|New|SetFrameRate|SetHeight|SetPosition|Show)?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.function.${3:/downcase}.turing" },{ # Stream match: "\\b(Stream)\\b(?:(\\.)(eof|Flush|FlushAll)?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.function.${3:/downcase}.turing" },{ # Str match: "\\b(Str)\\b(?:(\\.)(\\w+)?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: patterns: [include: "#str-routines"] },{ # Sys match: "\\b(Sys)\\b(?:(\\.)(Exec|FetchArg|GetComputerName|GetEnv|GetPid|GetUserName|Nargs)?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.function.${3:/downcase}.turing" },{ # Text match: "\\b(Text)\\b(?:(\\.)(Cls|Colou?r|Colou?rBack|Locate|LocateXY|maxcol|maxrow|WhatCol|WhatColou?r|WhatColou?rBack|WhatRow)?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.function.${3:/downcase}.turing" },{ # Time match: "\\b(Time)\\b(?:(\\.)(Date|DateSec|Delay|Elapsed|ElapsedCPU|PartsSec|Sec|SecDate|SecParts)?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.function.${3:/downcase}.turing" },{ # TypeConv match: "\\b(TypeConv)\\b(?:(\\.)(\\w+)?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: patterns: [include: "#typeconv-routines"] },{ # View match: "\\b(View)\\b(?:(\\.)(ClipAdd|ClipOff|ClipSet|maxcolou?r|maxx|maxy|Set|Update|WhatDotColou?r)?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.function.${3:/downcase}.turing" },{ # Window match: "\\b(Window)\\b(?:(\\.)(Close|GetActive|GetPosition|GetSelect|Hide|Open|Select|Set|SetActive|SetPosition|Show|Update)?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.function.${3:/downcase}.turing" }]
193094
name: "<NAME>" scopeName: "source.turing" fileTypes: ["t", "tu"] firstLineMatch: """(?x) # Emacs modeline -\\*-(?i:[ \\t]*(?=[^:;\\s]+[ \\t]*-\\*-)|(?:.*?[ \\t;]|(?<=-\\*-))[ \\t]*mode[ \\t]*:[ \\t]*) (?i:turing) (?=[ \\t;]|(?<![-*])-\\*-).*?-\\*- | # Vim modeline (?:(?:^|[ \\t])(?:vi|Vi(?=m))(?:m[<=>]?[0-9]+|m)?|[ \\t]ex)(?=:(?=[ \\t]*set?[ \\t][^\\r\\n:]+:)|:(?![ \\t]*set?[ \\t])) (?:(?:[ \\t]*:[ \\t]*|[ \\t])\\w*(?:[ \\t]*=(?:[^\\\\\\s]|\\\\.)*)?)*[ \\t:] (?:filetype|ft|syntax)[ \\t]*= (?i:turing) (?=$|\\s|:) """ patterns: [include: "#main"] repository: # Common patterns main: patterns: [ { include: "#comments" } { include: "#boolean" } { include: "#strings" } { include: "#numbers" } { include: "#cc" } { include: "#for" } { include: "#loop" } { include: "#if" } { include: "#case" } { include: "#block" } { include: "#function" } { include: "#modifiers" } { include: "#variables" } { include: "#punctuation" } { include: "#forward" } { include: "#procedure" } { include: "#process" } { include: "#handler" } { include: "#class" } { include: "#type" } { include: "#record" } { include: "#union" } { include: "#types" } { include: "#keywords" } { include: "#function-call" } { include: "#stdlib" } ] # Comments comments: patterns: [{ # End-of-line comment name: "comment.line.percentage.turing" begin: "%" end: "$" beginCaptures: 0: name: "punctuation.definition.comment.turing" },{ # Bracketed name: "comment.block.bracketed.turing" begin: "/\\*" end: "\\*/" beginCaptures: 0: name: "punctuation.definition.comment.turing" endCaptures: 0: name: "punctuation.definition.comment.turing" }] # String literals strings: patterns: [ {name: "string.quoted.double.turing", begin: '"', end: '"', patterns: [include: "#escapes"]} {name: "string.quoted.single.turing", begin: "'", end: "'", patterns: [include: "#escapes"]} ] # Numbers numbers: patterns: [ {name: "constant.numeric.base-16.hex.turing", match: "16#[A-Fa-f0-9]+"} {name: "constant.numeric.base-$1.turing", match: "(\\d+)#\\d+"} {name: "constant.numeric.float.turing", match: "\\b\\d+\\.\\d+(?:[Ee][\\+\\-]?\\d+)?\\b"} {name: "constant.numeric.int.turing", match: "\\b\\d+\\b"} ] # List of named values list: patterns: [ {match: "\\w+", name: "variable.name.turing"} {match: ",", name: "meta.delimiter.object.comma.turing"} ] # Escaped characters escapes: patterns: [ {match: '\\\\"', name: "constant.character.escape.double-quote.turing"} {match: "\\\\'", name: "constant.character.escape.single-quote.turing"} {match: "\\\\[nN]", name: "constant.character.escape.newline.turing"} {match: "\\\\[tT]", name: "constant.character.escape.tab.turing"} {match: "\\\\[fF]", name: "constant.character.escape.form-feed.turing"} {match: "\\\\[rR]", name: "constant.character.escape.return.turing"} {match: "\\\\[bB]", name: "constant.character.escape.backspace.turing"} {match: "\\\\[eE]", name: "constant.character.escape.esc.turing"} {match: "\\\\\\\\", name: "constant.character.escape.backslash.turing"} ] # Function declaration function: name: "meta.function.turing" begin: """(?x) \\b (?: (body) # 1: storage.modifier.body.turing \\s+ )? (function|fcn) # 2: storage.type.function.turing (?: \\s+ (pervasive|\\*) # 3: storage.modifier.pervasive.turing )? \\s+ (\\w+) # 4: entity.name.function.turing \\s* ( # 5: meta.function.parameters.turing (\\() # 6: punctuation.definition.parameters.begin.turing (.*) # 7: include: “#param-declarations” (\\)) # 8: punctuation.definition.parameters.end.turing ) \\s* (:) # 9: punctuation.separator.key-value.turing \\s* (\\w+) # 10: storage.type.type-spec.turing """ end: "\\b(end)\\s+(\\4)" patterns: [{ # pre|init|post clause name: "meta.$1-function.turing" begin: "^\\s*(pre|init|post)(?=\\s|$)" end: "$" patterns: [include: "$self"] beginCaptures: 1: name: "keyword.function.$1.turing" },{ include: "$self" } ] beginCaptures: 1: name: "storage.modifier.body.turing" 2: name: "storage.type.function.turing" 3: name: "storage.modifier.pervasive.turing" 4: name: "entity.name.function.turing" 5: name: "meta.function.parameters.turing" 6: name: "punctuation.definition.parameters.begin.turing" 7: patterns: [include: "#param-declarations"] 8: name: "punctuation.definition.parameters.end.turing" 9: name: "punctuation.separator.key-value.turing" 10: name: "storage.type.type-spec.turing" endCaptures: 1: name: "storage.type.function.end.turing" 2: name: "entity.name.function.turing" # Function parameters "param-declarations": match: "\\b(\\w+)\\s+(:)\\s+((\\w+))" captures: 1: name: "variable.parameter.function.turing" 2: name: "storage.type.turing" 3: patterns: [include: "#types"] # Function call "function-call": patterns: [{ # functionName ( args ) name: "meta.function-call.turing" begin: /(([\w.]+))\s*(\()/ end: /\)/ contentName: "meta.function-call.arguments.turing" beginCaptures: 1: name: "entity.function.name.turing" 2: patterns: [include: "#function-name"] 3: name: "punctuation.definition.arguments.begin.turing" endCaptures: 0: name: "punctuation.definition.arguments.end.turing" patterns: [include: "$self"] },{ # functionName name: "meta.function-call.turing" match: /^\s*(([\\w.]+))\s*(?=$|%|\/\*)/ captures: 1: name: "entity.function.name.turing" 2: patterns: [include: "#function-name"] }] # Function name: Wrapper for bundled inclusions "function-name": patterns: [ {include: "#stdlib"} {match: "\\.", name: "punctuation.separator.method.turing"} ] # Keywords keywords: patterns: [{ # Control flow match: /// \b( (?:end\s+)?if|(?:end\s+)?loop|(?:end\s+)?for|(?:end\s+)?case| endif|endloop|endfor|endcase|label| then|elsif|elseif|elif|else|exit|when|include|in|begin|end|by )\b /// name: "keyword.control.$1.turing" },{ # Logical operators match: /\b(and|not|x?or)\b/ name: "keyword.operator.logical.$1.turing" },{ # Other operators match: /\b(all|bits|cheat|decreasing|div|lower|mod|nil|of|rem|shl|shr|to|unit|upper)\b/ name: "keyword.operator.$1.turing" },{ # Statements match: /\b(asm|begin|break|close|exit|fork|free|get|init|new|objectclass|open|pause|put|quit|read|result|return|seek|signal|tag|tell|wait|write)\b/ name: "keyword.other.statement.$1.turing" },{ # Items patterns: [{ # General match: /\b(class|module|monitor|const|var|type)\b/ name: "storage.type.$1.turing" },{ # Function-like items match: /\b(function|fcn|procedure|proc|process)\b/ name: "storage.type.function.turing" },{ # Handler match: /\b(handler)\b/ name: "storage.type.handler.turing" }] },{ # Other patterns: [{ match: /\b(import|export)\b/ name: "keyword.other.$1.turing" },{ match: /\b(pre|post|assert|invariant)\b/ name: "keyword.function.$1.turing" }] },{ # Character type of specified length match: /\b(char)\s*(\()(\d+)(\))/ name: "storage.type.$3-char.turing" captures: 2: name: "punctuation.definition.arguments.begin.turing" 4: name: "punctuation.definition.arguments.end.turing" },{ # Colour constants match: ///\b (black|blue|brightblue|brightcyan|brightgreen|brightmagenta|brightpurple|brightred |brightwhite|brown|colou?r[bf]g|cyan|darkgr[ae]y|gr[ae]y|green|magenta|purple|red |white|yellow)\b/// name: "constant.other.colour.turing" },{ # Language variables match: /\b(skip|self)\b/ name: "constant.language.$1.turing" }] # Various modifier keywords modifiers: patterns: [{ # Checked/unchecked match: /\b(unchecked|checked)\b/ name: "storage.modifier.$1.compiler-directive.oot.turing" },{ # Unqualified match: /\b(unqualified|~(?=\s*\.))\b/ name: "storage.modifier.unqualified.turing" },{ # Implement match: /\b(implement)\b/ name: "storage.modifier.implements.turing" },{ # Other match: /\b(body|def|deferred|forward|external|flexible|inherit|opaque|packed|timeout|priority)\b/ name: "storage.modifier.$1.turing" },{ # OOT other match: /\b(pervasive|register)\b/ name: "storage.modifier.$1.oot.turing" }] # Types types: match: /// \b( addressint|array|boolean|char|string|collection|enum| int[124]?|nat[124]?|real[48]?|pointer(\s+to)?|set(\s+of)?| record|union|condition )\b /// name: "storage.type.$1-type.turing" # Conditional compilation cc: name: "meta.preprocessor.$3.turing" match: "^\\s*((#)((?:end\\s+)?if|elsif|else))" captures: 1: name: "keyword.control.directive.conditional.turing" 2: name: "punctuation.definition.directive.turing" # For loops for: name: "meta.scope.for-loop.turing" begin: "^\\s*(for)\\b(?:\\s+(decreasing)\\b)?" end: "^\\s*(end)\\s+(for)" patterns: [{ match: "\\G(.*?)\\b(by)\\b" captures: 1: patterns: [include: "$self"] 2: name: "keyword.control.by.turing" }, include: "$self"] beginCaptures: 0: name: "meta.scope.begin.turing" 1: name: "keyword.control.for.turing" 2: name: "keyword.operator.decreasing.turing" endCaptures: 0: name: "meta.scope.end.turing" 1: name: "keyword.control.for.end.turing" 2: name: "keyword.control.for.turing" # Loop loops loop: name: "meta.scope.loop.turing" begin: /\b(loop)\b/ end: /\b(end)\s*(loop)\b/ patterns: [{ include: "$self" }] beginCaptures: 0: name: "meta.scope.begin.turing" 1: name: "keyword.control.loop.turing" endCaptures: 0: name: "meta.scope.end.turing" 1: name: "keyword.control.loop.end.turing" 2: name: "keyword.control.loop.turing" # Conditional execution if: name: "meta.scope.if-block.turing" begin: /\b(if)\b/ end: /\b(end\s+if)\b/ beginCaptures: 0: name: "meta.scope.begin.turing" 1: name: "keyword.control.conditional.turing" endCaptures: 0: name: "meta.scope.end.turing" 1: name: "keyword.control.conditional.turing" patterns: [include: "$self"] # Case blocks case: name: "meta.scope.case-block.turing" begin: "^\\s*(case)\\s+(\\w+)\\s+(of)\\b" end: "^\\s*(end\\s+case)\\b" patterns: [ {include: "#label"} {include: "$self"} ] beginCaptures: 0: name: "meta.scope.begin.turing" 1: name: "keyword.control.case.turing" 2: name: "variable.parameter.turing" 3: name: "keyword.operator.of.turing" endCaptures: 0: name: "meta.scope.end.turing" 1: name: "keyword.control.case.end.turing" # Label statements label: name: "meta.label.turing" begin: "\\b(label)\\b" end: ":" beginCaptures: 1: name: "keyword.other.statement.label.turing" endCaptures: 0: name: "punctuation.separator.key-value.turing" patterns: [ {include: "$self"} {include: "#list"} ] # Block statements block: name: "meta.scope.block.turing" begin: /\b(begin)\b/ end: /\b(end)\s*(?!for|loop|case|if|\w+)/ beginCaptures: 0: name: "meta.scope.begin.turing" 1: name: "keyword.control.begin.turing" endCaptures: 0: name: "meta.scope.end.turing" 1: name: "keyword.control.end.turing" patterns: [ { include: "$self" } ] # Forward/deferred procedure forward: patterns: [{ # Procedure name: "meta.$1.procedure.turing" begin: "^\\s*\\b(deferred|forward)\\s+(procedure|proc)\\s+(\\w+)" end: "(?=$|%|/\\*)" beginCaptures: 1: name: "storage.modifier.$1.turing" 2: name: "storage.type.function.turing" 3: name: "entity.name.function.turing" patterns: [ {include: "#parameters"} {include: "$self"} ] },{ # Function name: "meta.$1.function.turing" begin: "^\\s*\\b(deferred|forward)\\s+(function|fcn)\\s+(\\w+)" end: "(?=$|%|/\\*)" beginCaptures: 1: name: "storage.modifier.$1.turing" 2: name: "storage.type.function.turing" 3: name: "entity.name.function.turing" patterns: [ {include: "#parameters"} {include: "$self"} ] }] # Procedure declaration procedure: name: "meta.scope.procedure.turing" begin: "^\\s*(?:(body)\\s+)?(procedure|proc)\\s+(\\w+)" end: "^\\s*(end)\\s+(\\3)" patterns: [ {include: "#parameters"} {include: "$self"} ] beginCaptures: 0: name: "meta.scope.begin.turing" 1: name: "storage.modifier.$1.turing" 2: name: "storage.type.function.turing" 3: name: "entity.name.function.turing" endCaptures: 0: name: "meta.scope.end.turing" 1: name: "storage.type.function.end.turing" 2: name: "entity.name.function.turing" # Process statement process: name: "meta.scope.process.turing" begin: "^\\s*(process)(?:\\s+(pervasive|\\*)(?=\\s))?\\s+(\\w+)" end: "^\\s*(end)\\s+(\\3)" patterns: [ {include: "#parameters"} {include: "$self"} ] beginCaptures: 0: name: "meta.scope.begin.turing" 1: name: "storage.type.function.turing" 2: name: "storage.modifier.pervasive.turing" 3: name: "entity.name.function.turing" endCaptures: 0: name: "meta.scope.end.turing" 1: name: "storage.type.function.end.turing" 2: name: "entity.name.function.turing" # Bracketed parameter declarations used in procedure/process headers parameters: name: "meta.function.parameters.turing" begin: "\\G\\s*(\\()" end: "\\)" beginCaptures: 1: name: "punctuation.definition.arguments.begin.turing" endCaptures: 0: name: "punctuation.definition.arguments.end.turing" patterns: [ {include: "$self"} {match: "\\w+", name: "variable.parameter.function.turing"} ] # Exception handler handler: name: "meta.scope.handler.turing" begin: "^\\s*(handler)\\s*(\\()\\s*(\\w+)\\s*(\\))" end: "^\\s*(end)\\s+(handler)\\b" patterns: [include: "$self"] beginCaptures: 0: name: "meta.scope.begin.turing" 1: name: "storage.type.handler.turing" 2: name: "punctuation.definition.arguments.begin.turing" 3: name: "variable.parameter.handler.turing" 4: name: "punctuation.definition.arguments.end.turing" endCaptures: 0: name: "meta.scope.end.turing" 1: name: "storage.type.handler.end.turing" 2: name: "storage.type.handler.turing" # Class, module and monitor declarations class: name: "meta.scope.$1-block.turing" begin: /^\s*(class|module|monitor)\s+(\w+)/ end: /\b(end)\s+(\2)/ patterns: [ {include: "#class-innards"} {include: "$self"} ] beginCaptures: 0: name: "meta.scope.begin.turing" 1: name: "storage.type.$1.turing" 2: name: "entity.name.type.class.turing" endCaptures: 0: name: "meta.scope.end.turing" 1: name: "storage.type.$1.end.turing" 2: name: "entity.name.type.class.turing" # Various clauses for inheritance, importing/exporting, etc "class-innards": patterns: [{ # Import/export begin: "\\b(import|export)\\b" end: "(?=$|%|/\\*)" beginCaptures: 1: name: "keyword.other.$1.turing" patterns: [ {include: "#list"} {include: "$self"} ] },{ # Inherited class name: "meta.other.inherited-class.turing" begin: "\\b(inherit)\\b" end: "\\w+" beginCaptures: 1: name: "storage.modifier.inherit.turing" endCaptures: 0: name: "entity.other.inherited-class.turing" patterns: [include: "$self"] },{ # Implement/Implement by name: "meta.other.$1.turing" begin: "\\b(implement(?:\\s+by)?)\\b" end: "\\w+" beginCaptures: 1: name: "storage.modifier.implements.turing" endCaptures: 0: name: "entity.other.inherited-class.turing" patterns: [include: "$self"] }] # Variables and constants variables: patterns: [{ # Declaration name: "meta.variable-declaration.turing" begin: "\\b(var|const)\\s+" end: "(:=?)\\s*((?!\\d)((?:\\w+(?:\\s+to)?)(?:\\s*\\(\\s*\\d+\\s*\\))?))?\\s*(:=)?" beginCaptures: 1: name: "storage.type.$1.turing" endCaptures: 1: name: "punctuation.separator.key-value.turing" 2: name: "storage.type.type-spec.turing" 3: patterns: [include: "#types"] 4: name: "punctuation.separator.key-value.turing" patterns: [ # Object-oriented Turing: Additional keywords { match: "\\G(?:\\s*(pervasive|\\*)(?=\\s))?\\s*(register)(?=\\s)" captures: 1: name: "storage.modifier.pervasive.oot.turing" 2: name: "storage.modifier.register.oot.turing" } {include: "#types"} {include: "#list"} ] },{ # Assignment name: "meta.variable-assignment.turing" begin: "(\\w+)\\s*(:=)" end: "(?=\\S)" beginCaptures: 1: name: "variable.name.turing" 2: name: "punctuation.separator.key-value.turing" },{ # Bindings name: "meta.binding.turing" begin: "\\b(bind)\\b" end: "(?=$|%|/\\*)" beginCaptures: 1: name: "keyword.operator.bind.turing" patterns: [{ # Individual variable bindings begin: "\\b(var)\\b" end: "\\b(to)\\b" patterns: [include: "#list"] beginCaptures: 1: name: "storage.type.$1.turing" endCaptures: 1: name: "keyword.operator.to.turing" },{ # Comma separators include: "#list" }] }] # Boolean values boolean: name: "constant.language.boolean.$1.turing" match: "\\b(true|false)\\b" # Arithmetic/Punctuation punctuation: patterns: [ {match: "\\.\\.", name: "punctuation.definition.range.turing"} {match: ":=", name: "punctuation.separator.key-value.assignment.turing"} {match: "->", name: "punctuation.separator.class.accessor.turing"} {match: "\\+", name: "keyword.operator.arithmetic.add.turing"} {match: "-", name: "keyword.operator.arithmetic.subtract.turing"} {match: "\\*", name: "keyword.operator.arithmetic.multiply.turing"} {match: "\\/", name: "keyword.operator.arithmetic.divide.turing"} {match: "<=", name: "keyword.operator.logical.equal-or-less.subset.turing"} {match: ">=", name: "keyword.operator.logical.equal-or-greater.superset.turing"} {match: "<", name: "keyword.operator.logical.less.turing"} {match: ">", name: "keyword.operator.logical.greater.turing"} {match: "=", name: "keyword.operator.logical.equal.turing"} {match: "not=|~=", name: "keyword.operator.logical.not.turing"} {match: "\\^", name: "keyword.operator.pointer-following.turing"} {match: "#", name: "keyword.operator.type-cheat.turing"} {match: "@", name: "keyword.operator.indirection.turing"} {match: ":", name: "punctuation.separator.key-value.turing"} {match: "\\(", name: "punctuation.definition.arguments.begin.turing"} {match: "\\)", name: "punctuation.definition.arguments.end.turing"} ] # Type declaration type: match: "\\b(type)(?:\\s+(pervasive|\\*)(?=\\s))?\\s+(\\w+)" captures: 1: name: "storage.type.turing" 2: name: "storage.modifier.pervasive.turing" 3: name: "entity.name.type.turing" # Record declaration record: name: "meta.scope.record-block.turing" begin: "^\\s*(record)\\b" end: "^\\s*(end)\\s+(record)\\b" patterns: [{ # Field names match: "((\\s*\\w+\\s*,?)+)(:)" captures: 1: patterns: [include: "#list"] 3: name: "punctuation.separator.record.key-value.turing" }, include: "$self"] beginCaptures: 0: name: "meta.scope.begin.turing" 1: name: "storage.type.record.turing" endCaptures: 0: name: "meta.scope.end.turing" 1: name: "storage.type.record.end.turing" 2: name: "storage.type.record.turing" # Union/variant record union: name: "meta.scope.union.turing" begin: "^\\s*(union)\\s+(\\w+)\\s*(:)(.*)\\b(of)\\b" end: "^\\s*(end)\\s+(union)\\b" patterns: [ {include: "#label"} {include: "$self"} ] beginCaptures: 0: name: "meta.scope.begin.turing" 1: name: "storage.type.union.turing" 2: name: "entity.name.union.turing" 3: name: "punctuation.separator.key-value.turing" 4: patterns: [include: "$self"] 5: name: "keyword.operator.of.turing" endCaptures: 0: name: "meta.scope.end.turing" 1: name: "storage.type.union.end.turing" 2: name: "storage.type.union.turing" # Standard library stdlib: patterns: [ {include: "#modules"} {include: "#stdproc"} {match: "\\b(anyclass)\\b", name: "support.class.anyclass.turing"} # Routines/constants exported unqualified {include: "#keyboard-constants"} {include: "#math-routines"} {include: "#str-routines"} {include: "#typeconv-routines"} ] # Procedures not associated with any specific module stdproc: name: "support.function.${1:/downcase}.turing" match: """(?x)\\b (addr|buttonchoose|buttonmoved|buttonwait|clock|cls|colou?r|colou?rback|date|delay|drawarc|drawbox|drawdot |drawfill|drawfillarc|drawfillbox|drawfillmapleleaf|drawfilloval|drawfillpolygon|drawfillstar|drawline |drawmapleleaf|drawoval|drawpic|drawpolygon|drawstar|empty|eof|fetcharg|getch|getchar|getenv|getpid |getpriority|hasch|locate|locatexy|maxcol|maxcolou?r|maxint|maxnat|maxrow|maxx|maxy|minint|minnat |mousewhere|nargs|parallelget|parallelput|play|playdone|pred|rand|randint|randnext|randomize |randseed|setpriority|setscreen|simutime|sizeof|sizepic|sound|succ|sysclock|takepic|time|wallclock |whatcol|whatcolou?r|whatcolou?rback|whatdotcolou?r|whatrow)\\b """ # Keyboard constants: http://compsci.ca/holtsoft/doc/keyboardmodule.html "keyboard-constants": name: "support.constant.keyboard.turing" match: """(?x)\\b(?: (?:KEY|ORD)_(?: F1[0-2]|F[1-9]|CTRL_[A-Z]|ALT_[A-Z0-9]|(?:CTRL|ALT|SHIFT)_(?:F1[0-2]|F[1-9])| ALT(?:_EQUALS|_MINUS)?|BACK_TAB|BACKSPACE|CTRL|DELETE|END|ENTER|ESC|HOME|INSERT|KEYPAD_5|PGDN|PGUP|SHIFT|SHIFT_TAB|TAB| CTRL_(?:BACKSLASH|BACKSPACE|CARET|(?:UP|RIGHT|LEFT|DOWN)_ARROW|CLOSE_BRACKET|DELETE|END|HOME|INSERT|OPEN_BRACKET|PGDN|PGUP|UNDERSCORE)| (?:UP|RIGHT|LEFT|DOWN)_ARROW) | ORD_(?: AMPERSAND|APOSTROPHE|ASTERISK|BACKSLASH|BAR|CARET|COLON|COMMA|DOT|EQUALS|(?:GREATER|LESS)_THAN| (?:CLOSE|OPEN)_(?:BRACE|BRACKET|PARENTHESIS)|(?:EXCALAMATION|HAS|QUESTION|QUOTATION)_MARK|MINUS| (?:AT|DOLLAR|PERCENT)_SIGN|PERIOD|PLUS|SEMICOLON|SINGLE_QUOTE|SLASH|SPACE|TILDE|UNDERSCORE|[A-Z0-9]|LOWER_[A-Z]) )\\b """ # Math routines: http://compsci.ca/holtsoft/doc/mathmodule.html "math-routines": name: "support.function.${1:/downcase}.turing" match: "\\b(abs|arccos|arccosd|arcsin|arcsind|arctan|arctand|cos|cosd|exp|ln|max|min|sign|sin|sind|tan|tand|sqrt)\\b" # Str routines: http://compsci.ca/holtsoft/doc/strmodule.html "str-routines": name: "support.function.${1:/downcase}.turing" match: "\\b(Lower|Upper|Trim|index|length|repeat)\\b" # TypeConv routines: http://compsci.ca/holtsoft/doc/typeconvmodule.html "typeconv-routines": name: "support.function.${1:/downcase}.turing" match: "\\b(ceil|chr|erealstr|floor|frealstr|intreal|intstr|natreal|natstr|ord|realstr|round|strint|strintok|strnat|strnatok|strreal|strrealok)\\b" # Modules modules: patterns: [{ # Concurrency match: "\\b(Concurrency)\\b(?:(\\.)(empty|[gs]etpriority|simutime)?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.function.$3.turing" },{ # Config match: "\\b(Config)\\b(?:(\\.)(Display|Lang|Machine)?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.function.${3:/downcase}.turing" },{ # Dir match: "\\b(Dir)\\b(?:(\\.)(Change|Close|Create|Current|Delete|Get|GetLong|Open)?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.function.${3:/downcase}.turing" },{ # Draw match: "\\b(Draw)\\b(?:(\\.)(Arc|Box|Cls|Dot|Fill|FillArc|FillBox|FillMapleLeaf|FillOval|FillPolygon|FillStar|Line|MapleLeaf|Oval|Polygon|Star|Text)?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.function.${3:/downcase}.turing" },{ # Error match: "\\b(Error)\\b(?:(\\.)(Last|LastMsg|LastStr|Msg|Str|Trip)?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.function.${3:/downcase}.turing" },{ # ErrorNum/Exceptions match: "\\b(ErrorNum|Exceptions)\\b(?:(\\.)(\\w+)?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.function.${3:/downcase}.turing" },{ # File match: "\\b(File)\\b(?:(\\.)(Copy|Delete|DiskFree|Exists|Rename|Status)?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.function.${3:/downcase}.turing" },{ # Font match: "\\b(Font)\\b(?:(\\.)(Draw|Free|GetName|GetSize|GetStyle|Name|New|Sizes|StartName|StartSize|Width)?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.function.${3:/downcase}.turing" },{ # GUI match: """(?x)\\b(GUI)\\b(?:(\\.) (AddLine|AddText|Alert|Alert2|Alert3|AlertFull|Choose|ChooseFull|ClearText|CloseWindow|CreateButton|CreateButtonFull |CreateCanvas|CreateCanvasFull|CreateCheckBox|CreateCheckBoxFull|CreateFrame|CreateHorizontalScrollBar|CreateHorizontalScrollBarFull |CreateHorizontalSlider|CreateLabel|CreateLabelFull|CreateLabelledFrame|CreateLine|CreateMenu|CreateMenuItem|CreateMenuItemFull |CreatePicture|CreatePictureButton|CreatePictureButtonFull|CreatePictureRadioButton|CreatePictureRadioButtonFull|CreateRadioButton |CreateRadioButtonFull|CreateTextBox|CreateTextBoxFull|CreateTextField|CreateTextFieldFull|CreateVerticalScrollBar|CreateVerticalScrollBarFull |CreateVerticalSlider|Disable|Dispose|DrawArc|DrawBox|DrawCls|DrawDot|DrawFill|DrawFillArc|DrawFillBox|DrawFillMapleLeaf|DrawFillOval |DrawFillPolygon|DrawFillStar|DrawLine|DrawMapleLeaf|DrawOval|DrawPolygon|DrawStar|DrawText|Enable|FontDraw|GetCheckBox|GetEventTime |GetEventWidgetID|GetEventWindow|GetHeight|GetMenuBarHeight|GetScrollBarWidth|GetSliderValue|GetText|GetVersion|GetWidth|GetX|GetY|Hide |HideMenuBar|OpenFile|OpenFileFull|PicDraw|PicNew|PicScreenLoad|PicScreenSave|ProcessEvent|Quit|Refresh|SaveFile|SaveFileFull|SelectRadio |SetActive|SetBackgroundColor|SetBackgroundColour|SetCheckBox|SetDefault|SetDisplayWhenCreated|SetKeyEventHandler|SetLabel|SetMouseEventHandler |SetNullEventHandler|SetPosition|SetPositionAndSize|SetScrollAmount|SetSelection|SetSize|SetSliderMinMax|SetSliderReverse|SetSliderSize |SetSliderValue|SetText|SetXOR|Show|ShowMenuBar)?\\b)? """ captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.function.${3:/downcase}.turing" },{ # Input match: "\\b(Input)\\b(?:(\\.)(getch|getchar|hasch|KeyDown|Pause)?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.function.${3:/downcase}.turing" },{ # Joystick match: "\\b(Joystick)\\b(?:(\\.)(GetInfo)?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.function.${3:/downcase}.turing" },{ # Keyboard match: "\\b(Keyboard)\\b(?:(\\.)(\\w+)?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: patterns: [include: "#keyboard-constants"] },{ # Limits match: "\\b(Limits)\\b(?:(\\.)(DefaultFW|DefaultEW|minint|maxint|minnat|maxnat)?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.function.${3:/downcase}.turing" },{ # Math match: "(?x)\\b(Math)\\b(?:(\\.)(?:(PI|E)|(Distance|DistancePointLine)|(\\w+))?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.constant.${3:/downcase}.turing" 4: name: "support.function.${4:/downcase}.turing" 5: patterns: [include: "#math-routines"] },{ # Mouse match: "\\b(Mouse)\\b(?:(\\.)(ButtonChoose|ButtonMoved|ButtonWait|Where)?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.function.${3:/downcase}.turing" },{ # Music match: "\\b(Music)\\b(?:(\\.)(Play|PlayFile|PlayFileStop|Sound|SoundOff)?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.function.${3:/downcase}.turing" },{ # Net match: """(?x) \\b(Net)\\b(?:(\\.) (BytesAvailable|CharAvailable|CloseConnection|HostAddressFromName|HostNameFromAddress |LineAvailable|LocalAddress|LocalName|OpenConnection|OpenURLConnection|TokenAvailable |WaitForConnection)?\\b)?""" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.function.${3:/downcase}.turing" },{ # PC match: "\\b(PC)\\b(?:(\\.)(ParallelGet|ParallelPut)?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.function.${3:/downcase}.turing" },{ # Pic match: """(?x) \\b(Pic)\\b(?:(\\.) (Blend|Blur|Draw|DrawFrames|DrawFramesBack|DrawSpecial|DrawSpecialBack|FileNew |FileNewFrames|Flip|Frames|Free|Height|Mirror|New|Rotate|Save|Scale|ScreenLoad |ScreenSave|SetTransparentColou?r|Width)? \\b)?""" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.function.${3:/downcase}.turing" },{ # Rand match: "\\b(Rand)\\b(?:(\\.)(Int|Next|Real|Reset|Seed|Set)?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.function.${3:/downcase}.turing" },{ # RGB match: "\\b(RGB)\\b(?:(\\.)(AddColou?r|[GS]etColou?r|maxcolou?r)?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.function.${3:/downcase}.turing" },{ # Sprite match: "\\b(Sprite)\\b(?:(\\.)(Animate|ChangePic|Free|Hide|New|SetFrameRate|SetHeight|SetPosition|Show)?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.function.${3:/downcase}.turing" },{ # Stream match: "\\b(Stream)\\b(?:(\\.)(eof|Flush|FlushAll)?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.function.${3:/downcase}.turing" },{ # Str match: "\\b(Str)\\b(?:(\\.)(\\w+)?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: patterns: [include: "#str-routines"] },{ # Sys match: "\\b(Sys)\\b(?:(\\.)(Exec|FetchArg|GetComputerName|GetEnv|GetPid|GetUserName|Nargs)?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.function.${3:/downcase}.turing" },{ # Text match: "\\b(Text)\\b(?:(\\.)(Cls|Colou?r|Colou?rBack|Locate|LocateXY|maxcol|maxrow|WhatCol|WhatColou?r|WhatColou?rBack|WhatRow)?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.function.${3:/downcase}.turing" },{ # Time match: "\\b(Time)\\b(?:(\\.)(Date|DateSec|Delay|Elapsed|ElapsedCPU|PartsSec|Sec|SecDate|SecParts)?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.function.${3:/downcase}.turing" },{ # TypeConv match: "\\b(TypeConv)\\b(?:(\\.)(\\w+)?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: patterns: [include: "#typeconv-routines"] },{ # View match: "\\b(View)\\b(?:(\\.)(ClipAdd|ClipOff|ClipSet|maxcolou?r|maxx|maxy|Set|Update|WhatDotColou?r)?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.function.${3:/downcase}.turing" },{ # Window match: "\\b(Window)\\b(?:(\\.)(Close|GetActive|GetPosition|GetSelect|Hide|Open|Select|Set|SetActive|SetPosition|Show|Update)?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.function.${3:/downcase}.turing" }]
true
name: "PI:NAME:<NAME>END_PI" scopeName: "source.turing" fileTypes: ["t", "tu"] firstLineMatch: """(?x) # Emacs modeline -\\*-(?i:[ \\t]*(?=[^:;\\s]+[ \\t]*-\\*-)|(?:.*?[ \\t;]|(?<=-\\*-))[ \\t]*mode[ \\t]*:[ \\t]*) (?i:turing) (?=[ \\t;]|(?<![-*])-\\*-).*?-\\*- | # Vim modeline (?:(?:^|[ \\t])(?:vi|Vi(?=m))(?:m[<=>]?[0-9]+|m)?|[ \\t]ex)(?=:(?=[ \\t]*set?[ \\t][^\\r\\n:]+:)|:(?![ \\t]*set?[ \\t])) (?:(?:[ \\t]*:[ \\t]*|[ \\t])\\w*(?:[ \\t]*=(?:[^\\\\\\s]|\\\\.)*)?)*[ \\t:] (?:filetype|ft|syntax)[ \\t]*= (?i:turing) (?=$|\\s|:) """ patterns: [include: "#main"] repository: # Common patterns main: patterns: [ { include: "#comments" } { include: "#boolean" } { include: "#strings" } { include: "#numbers" } { include: "#cc" } { include: "#for" } { include: "#loop" } { include: "#if" } { include: "#case" } { include: "#block" } { include: "#function" } { include: "#modifiers" } { include: "#variables" } { include: "#punctuation" } { include: "#forward" } { include: "#procedure" } { include: "#process" } { include: "#handler" } { include: "#class" } { include: "#type" } { include: "#record" } { include: "#union" } { include: "#types" } { include: "#keywords" } { include: "#function-call" } { include: "#stdlib" } ] # Comments comments: patterns: [{ # End-of-line comment name: "comment.line.percentage.turing" begin: "%" end: "$" beginCaptures: 0: name: "punctuation.definition.comment.turing" },{ # Bracketed name: "comment.block.bracketed.turing" begin: "/\\*" end: "\\*/" beginCaptures: 0: name: "punctuation.definition.comment.turing" endCaptures: 0: name: "punctuation.definition.comment.turing" }] # String literals strings: patterns: [ {name: "string.quoted.double.turing", begin: '"', end: '"', patterns: [include: "#escapes"]} {name: "string.quoted.single.turing", begin: "'", end: "'", patterns: [include: "#escapes"]} ] # Numbers numbers: patterns: [ {name: "constant.numeric.base-16.hex.turing", match: "16#[A-Fa-f0-9]+"} {name: "constant.numeric.base-$1.turing", match: "(\\d+)#\\d+"} {name: "constant.numeric.float.turing", match: "\\b\\d+\\.\\d+(?:[Ee][\\+\\-]?\\d+)?\\b"} {name: "constant.numeric.int.turing", match: "\\b\\d+\\b"} ] # List of named values list: patterns: [ {match: "\\w+", name: "variable.name.turing"} {match: ",", name: "meta.delimiter.object.comma.turing"} ] # Escaped characters escapes: patterns: [ {match: '\\\\"', name: "constant.character.escape.double-quote.turing"} {match: "\\\\'", name: "constant.character.escape.single-quote.turing"} {match: "\\\\[nN]", name: "constant.character.escape.newline.turing"} {match: "\\\\[tT]", name: "constant.character.escape.tab.turing"} {match: "\\\\[fF]", name: "constant.character.escape.form-feed.turing"} {match: "\\\\[rR]", name: "constant.character.escape.return.turing"} {match: "\\\\[bB]", name: "constant.character.escape.backspace.turing"} {match: "\\\\[eE]", name: "constant.character.escape.esc.turing"} {match: "\\\\\\\\", name: "constant.character.escape.backslash.turing"} ] # Function declaration function: name: "meta.function.turing" begin: """(?x) \\b (?: (body) # 1: storage.modifier.body.turing \\s+ )? (function|fcn) # 2: storage.type.function.turing (?: \\s+ (pervasive|\\*) # 3: storage.modifier.pervasive.turing )? \\s+ (\\w+) # 4: entity.name.function.turing \\s* ( # 5: meta.function.parameters.turing (\\() # 6: punctuation.definition.parameters.begin.turing (.*) # 7: include: “#param-declarations” (\\)) # 8: punctuation.definition.parameters.end.turing ) \\s* (:) # 9: punctuation.separator.key-value.turing \\s* (\\w+) # 10: storage.type.type-spec.turing """ end: "\\b(end)\\s+(\\4)" patterns: [{ # pre|init|post clause name: "meta.$1-function.turing" begin: "^\\s*(pre|init|post)(?=\\s|$)" end: "$" patterns: [include: "$self"] beginCaptures: 1: name: "keyword.function.$1.turing" },{ include: "$self" } ] beginCaptures: 1: name: "storage.modifier.body.turing" 2: name: "storage.type.function.turing" 3: name: "storage.modifier.pervasive.turing" 4: name: "entity.name.function.turing" 5: name: "meta.function.parameters.turing" 6: name: "punctuation.definition.parameters.begin.turing" 7: patterns: [include: "#param-declarations"] 8: name: "punctuation.definition.parameters.end.turing" 9: name: "punctuation.separator.key-value.turing" 10: name: "storage.type.type-spec.turing" endCaptures: 1: name: "storage.type.function.end.turing" 2: name: "entity.name.function.turing" # Function parameters "param-declarations": match: "\\b(\\w+)\\s+(:)\\s+((\\w+))" captures: 1: name: "variable.parameter.function.turing" 2: name: "storage.type.turing" 3: patterns: [include: "#types"] # Function call "function-call": patterns: [{ # functionName ( args ) name: "meta.function-call.turing" begin: /(([\w.]+))\s*(\()/ end: /\)/ contentName: "meta.function-call.arguments.turing" beginCaptures: 1: name: "entity.function.name.turing" 2: patterns: [include: "#function-name"] 3: name: "punctuation.definition.arguments.begin.turing" endCaptures: 0: name: "punctuation.definition.arguments.end.turing" patterns: [include: "$self"] },{ # functionName name: "meta.function-call.turing" match: /^\s*(([\\w.]+))\s*(?=$|%|\/\*)/ captures: 1: name: "entity.function.name.turing" 2: patterns: [include: "#function-name"] }] # Function name: Wrapper for bundled inclusions "function-name": patterns: [ {include: "#stdlib"} {match: "\\.", name: "punctuation.separator.method.turing"} ] # Keywords keywords: patterns: [{ # Control flow match: /// \b( (?:end\s+)?if|(?:end\s+)?loop|(?:end\s+)?for|(?:end\s+)?case| endif|endloop|endfor|endcase|label| then|elsif|elseif|elif|else|exit|when|include|in|begin|end|by )\b /// name: "keyword.control.$1.turing" },{ # Logical operators match: /\b(and|not|x?or)\b/ name: "keyword.operator.logical.$1.turing" },{ # Other operators match: /\b(all|bits|cheat|decreasing|div|lower|mod|nil|of|rem|shl|shr|to|unit|upper)\b/ name: "keyword.operator.$1.turing" },{ # Statements match: /\b(asm|begin|break|close|exit|fork|free|get|init|new|objectclass|open|pause|put|quit|read|result|return|seek|signal|tag|tell|wait|write)\b/ name: "keyword.other.statement.$1.turing" },{ # Items patterns: [{ # General match: /\b(class|module|monitor|const|var|type)\b/ name: "storage.type.$1.turing" },{ # Function-like items match: /\b(function|fcn|procedure|proc|process)\b/ name: "storage.type.function.turing" },{ # Handler match: /\b(handler)\b/ name: "storage.type.handler.turing" }] },{ # Other patterns: [{ match: /\b(import|export)\b/ name: "keyword.other.$1.turing" },{ match: /\b(pre|post|assert|invariant)\b/ name: "keyword.function.$1.turing" }] },{ # Character type of specified length match: /\b(char)\s*(\()(\d+)(\))/ name: "storage.type.$3-char.turing" captures: 2: name: "punctuation.definition.arguments.begin.turing" 4: name: "punctuation.definition.arguments.end.turing" },{ # Colour constants match: ///\b (black|blue|brightblue|brightcyan|brightgreen|brightmagenta|brightpurple|brightred |brightwhite|brown|colou?r[bf]g|cyan|darkgr[ae]y|gr[ae]y|green|magenta|purple|red |white|yellow)\b/// name: "constant.other.colour.turing" },{ # Language variables match: /\b(skip|self)\b/ name: "constant.language.$1.turing" }] # Various modifier keywords modifiers: patterns: [{ # Checked/unchecked match: /\b(unchecked|checked)\b/ name: "storage.modifier.$1.compiler-directive.oot.turing" },{ # Unqualified match: /\b(unqualified|~(?=\s*\.))\b/ name: "storage.modifier.unqualified.turing" },{ # Implement match: /\b(implement)\b/ name: "storage.modifier.implements.turing" },{ # Other match: /\b(body|def|deferred|forward|external|flexible|inherit|opaque|packed|timeout|priority)\b/ name: "storage.modifier.$1.turing" },{ # OOT other match: /\b(pervasive|register)\b/ name: "storage.modifier.$1.oot.turing" }] # Types types: match: /// \b( addressint|array|boolean|char|string|collection|enum| int[124]?|nat[124]?|real[48]?|pointer(\s+to)?|set(\s+of)?| record|union|condition )\b /// name: "storage.type.$1-type.turing" # Conditional compilation cc: name: "meta.preprocessor.$3.turing" match: "^\\s*((#)((?:end\\s+)?if|elsif|else))" captures: 1: name: "keyword.control.directive.conditional.turing" 2: name: "punctuation.definition.directive.turing" # For loops for: name: "meta.scope.for-loop.turing" begin: "^\\s*(for)\\b(?:\\s+(decreasing)\\b)?" end: "^\\s*(end)\\s+(for)" patterns: [{ match: "\\G(.*?)\\b(by)\\b" captures: 1: patterns: [include: "$self"] 2: name: "keyword.control.by.turing" }, include: "$self"] beginCaptures: 0: name: "meta.scope.begin.turing" 1: name: "keyword.control.for.turing" 2: name: "keyword.operator.decreasing.turing" endCaptures: 0: name: "meta.scope.end.turing" 1: name: "keyword.control.for.end.turing" 2: name: "keyword.control.for.turing" # Loop loops loop: name: "meta.scope.loop.turing" begin: /\b(loop)\b/ end: /\b(end)\s*(loop)\b/ patterns: [{ include: "$self" }] beginCaptures: 0: name: "meta.scope.begin.turing" 1: name: "keyword.control.loop.turing" endCaptures: 0: name: "meta.scope.end.turing" 1: name: "keyword.control.loop.end.turing" 2: name: "keyword.control.loop.turing" # Conditional execution if: name: "meta.scope.if-block.turing" begin: /\b(if)\b/ end: /\b(end\s+if)\b/ beginCaptures: 0: name: "meta.scope.begin.turing" 1: name: "keyword.control.conditional.turing" endCaptures: 0: name: "meta.scope.end.turing" 1: name: "keyword.control.conditional.turing" patterns: [include: "$self"] # Case blocks case: name: "meta.scope.case-block.turing" begin: "^\\s*(case)\\s+(\\w+)\\s+(of)\\b" end: "^\\s*(end\\s+case)\\b" patterns: [ {include: "#label"} {include: "$self"} ] beginCaptures: 0: name: "meta.scope.begin.turing" 1: name: "keyword.control.case.turing" 2: name: "variable.parameter.turing" 3: name: "keyword.operator.of.turing" endCaptures: 0: name: "meta.scope.end.turing" 1: name: "keyword.control.case.end.turing" # Label statements label: name: "meta.label.turing" begin: "\\b(label)\\b" end: ":" beginCaptures: 1: name: "keyword.other.statement.label.turing" endCaptures: 0: name: "punctuation.separator.key-value.turing" patterns: [ {include: "$self"} {include: "#list"} ] # Block statements block: name: "meta.scope.block.turing" begin: /\b(begin)\b/ end: /\b(end)\s*(?!for|loop|case|if|\w+)/ beginCaptures: 0: name: "meta.scope.begin.turing" 1: name: "keyword.control.begin.turing" endCaptures: 0: name: "meta.scope.end.turing" 1: name: "keyword.control.end.turing" patterns: [ { include: "$self" } ] # Forward/deferred procedure forward: patterns: [{ # Procedure name: "meta.$1.procedure.turing" begin: "^\\s*\\b(deferred|forward)\\s+(procedure|proc)\\s+(\\w+)" end: "(?=$|%|/\\*)" beginCaptures: 1: name: "storage.modifier.$1.turing" 2: name: "storage.type.function.turing" 3: name: "entity.name.function.turing" patterns: [ {include: "#parameters"} {include: "$self"} ] },{ # Function name: "meta.$1.function.turing" begin: "^\\s*\\b(deferred|forward)\\s+(function|fcn)\\s+(\\w+)" end: "(?=$|%|/\\*)" beginCaptures: 1: name: "storage.modifier.$1.turing" 2: name: "storage.type.function.turing" 3: name: "entity.name.function.turing" patterns: [ {include: "#parameters"} {include: "$self"} ] }] # Procedure declaration procedure: name: "meta.scope.procedure.turing" begin: "^\\s*(?:(body)\\s+)?(procedure|proc)\\s+(\\w+)" end: "^\\s*(end)\\s+(\\3)" patterns: [ {include: "#parameters"} {include: "$self"} ] beginCaptures: 0: name: "meta.scope.begin.turing" 1: name: "storage.modifier.$1.turing" 2: name: "storage.type.function.turing" 3: name: "entity.name.function.turing" endCaptures: 0: name: "meta.scope.end.turing" 1: name: "storage.type.function.end.turing" 2: name: "entity.name.function.turing" # Process statement process: name: "meta.scope.process.turing" begin: "^\\s*(process)(?:\\s+(pervasive|\\*)(?=\\s))?\\s+(\\w+)" end: "^\\s*(end)\\s+(\\3)" patterns: [ {include: "#parameters"} {include: "$self"} ] beginCaptures: 0: name: "meta.scope.begin.turing" 1: name: "storage.type.function.turing" 2: name: "storage.modifier.pervasive.turing" 3: name: "entity.name.function.turing" endCaptures: 0: name: "meta.scope.end.turing" 1: name: "storage.type.function.end.turing" 2: name: "entity.name.function.turing" # Bracketed parameter declarations used in procedure/process headers parameters: name: "meta.function.parameters.turing" begin: "\\G\\s*(\\()" end: "\\)" beginCaptures: 1: name: "punctuation.definition.arguments.begin.turing" endCaptures: 0: name: "punctuation.definition.arguments.end.turing" patterns: [ {include: "$self"} {match: "\\w+", name: "variable.parameter.function.turing"} ] # Exception handler handler: name: "meta.scope.handler.turing" begin: "^\\s*(handler)\\s*(\\()\\s*(\\w+)\\s*(\\))" end: "^\\s*(end)\\s+(handler)\\b" patterns: [include: "$self"] beginCaptures: 0: name: "meta.scope.begin.turing" 1: name: "storage.type.handler.turing" 2: name: "punctuation.definition.arguments.begin.turing" 3: name: "variable.parameter.handler.turing" 4: name: "punctuation.definition.arguments.end.turing" endCaptures: 0: name: "meta.scope.end.turing" 1: name: "storage.type.handler.end.turing" 2: name: "storage.type.handler.turing" # Class, module and monitor declarations class: name: "meta.scope.$1-block.turing" begin: /^\s*(class|module|monitor)\s+(\w+)/ end: /\b(end)\s+(\2)/ patterns: [ {include: "#class-innards"} {include: "$self"} ] beginCaptures: 0: name: "meta.scope.begin.turing" 1: name: "storage.type.$1.turing" 2: name: "entity.name.type.class.turing" endCaptures: 0: name: "meta.scope.end.turing" 1: name: "storage.type.$1.end.turing" 2: name: "entity.name.type.class.turing" # Various clauses for inheritance, importing/exporting, etc "class-innards": patterns: [{ # Import/export begin: "\\b(import|export)\\b" end: "(?=$|%|/\\*)" beginCaptures: 1: name: "keyword.other.$1.turing" patterns: [ {include: "#list"} {include: "$self"} ] },{ # Inherited class name: "meta.other.inherited-class.turing" begin: "\\b(inherit)\\b" end: "\\w+" beginCaptures: 1: name: "storage.modifier.inherit.turing" endCaptures: 0: name: "entity.other.inherited-class.turing" patterns: [include: "$self"] },{ # Implement/Implement by name: "meta.other.$1.turing" begin: "\\b(implement(?:\\s+by)?)\\b" end: "\\w+" beginCaptures: 1: name: "storage.modifier.implements.turing" endCaptures: 0: name: "entity.other.inherited-class.turing" patterns: [include: "$self"] }] # Variables and constants variables: patterns: [{ # Declaration name: "meta.variable-declaration.turing" begin: "\\b(var|const)\\s+" end: "(:=?)\\s*((?!\\d)((?:\\w+(?:\\s+to)?)(?:\\s*\\(\\s*\\d+\\s*\\))?))?\\s*(:=)?" beginCaptures: 1: name: "storage.type.$1.turing" endCaptures: 1: name: "punctuation.separator.key-value.turing" 2: name: "storage.type.type-spec.turing" 3: patterns: [include: "#types"] 4: name: "punctuation.separator.key-value.turing" patterns: [ # Object-oriented Turing: Additional keywords { match: "\\G(?:\\s*(pervasive|\\*)(?=\\s))?\\s*(register)(?=\\s)" captures: 1: name: "storage.modifier.pervasive.oot.turing" 2: name: "storage.modifier.register.oot.turing" } {include: "#types"} {include: "#list"} ] },{ # Assignment name: "meta.variable-assignment.turing" begin: "(\\w+)\\s*(:=)" end: "(?=\\S)" beginCaptures: 1: name: "variable.name.turing" 2: name: "punctuation.separator.key-value.turing" },{ # Bindings name: "meta.binding.turing" begin: "\\b(bind)\\b" end: "(?=$|%|/\\*)" beginCaptures: 1: name: "keyword.operator.bind.turing" patterns: [{ # Individual variable bindings begin: "\\b(var)\\b" end: "\\b(to)\\b" patterns: [include: "#list"] beginCaptures: 1: name: "storage.type.$1.turing" endCaptures: 1: name: "keyword.operator.to.turing" },{ # Comma separators include: "#list" }] }] # Boolean values boolean: name: "constant.language.boolean.$1.turing" match: "\\b(true|false)\\b" # Arithmetic/Punctuation punctuation: patterns: [ {match: "\\.\\.", name: "punctuation.definition.range.turing"} {match: ":=", name: "punctuation.separator.key-value.assignment.turing"} {match: "->", name: "punctuation.separator.class.accessor.turing"} {match: "\\+", name: "keyword.operator.arithmetic.add.turing"} {match: "-", name: "keyword.operator.arithmetic.subtract.turing"} {match: "\\*", name: "keyword.operator.arithmetic.multiply.turing"} {match: "\\/", name: "keyword.operator.arithmetic.divide.turing"} {match: "<=", name: "keyword.operator.logical.equal-or-less.subset.turing"} {match: ">=", name: "keyword.operator.logical.equal-or-greater.superset.turing"} {match: "<", name: "keyword.operator.logical.less.turing"} {match: ">", name: "keyword.operator.logical.greater.turing"} {match: "=", name: "keyword.operator.logical.equal.turing"} {match: "not=|~=", name: "keyword.operator.logical.not.turing"} {match: "\\^", name: "keyword.operator.pointer-following.turing"} {match: "#", name: "keyword.operator.type-cheat.turing"} {match: "@", name: "keyword.operator.indirection.turing"} {match: ":", name: "punctuation.separator.key-value.turing"} {match: "\\(", name: "punctuation.definition.arguments.begin.turing"} {match: "\\)", name: "punctuation.definition.arguments.end.turing"} ] # Type declaration type: match: "\\b(type)(?:\\s+(pervasive|\\*)(?=\\s))?\\s+(\\w+)" captures: 1: name: "storage.type.turing" 2: name: "storage.modifier.pervasive.turing" 3: name: "entity.name.type.turing" # Record declaration record: name: "meta.scope.record-block.turing" begin: "^\\s*(record)\\b" end: "^\\s*(end)\\s+(record)\\b" patterns: [{ # Field names match: "((\\s*\\w+\\s*,?)+)(:)" captures: 1: patterns: [include: "#list"] 3: name: "punctuation.separator.record.key-value.turing" }, include: "$self"] beginCaptures: 0: name: "meta.scope.begin.turing" 1: name: "storage.type.record.turing" endCaptures: 0: name: "meta.scope.end.turing" 1: name: "storage.type.record.end.turing" 2: name: "storage.type.record.turing" # Union/variant record union: name: "meta.scope.union.turing" begin: "^\\s*(union)\\s+(\\w+)\\s*(:)(.*)\\b(of)\\b" end: "^\\s*(end)\\s+(union)\\b" patterns: [ {include: "#label"} {include: "$self"} ] beginCaptures: 0: name: "meta.scope.begin.turing" 1: name: "storage.type.union.turing" 2: name: "entity.name.union.turing" 3: name: "punctuation.separator.key-value.turing" 4: patterns: [include: "$self"] 5: name: "keyword.operator.of.turing" endCaptures: 0: name: "meta.scope.end.turing" 1: name: "storage.type.union.end.turing" 2: name: "storage.type.union.turing" # Standard library stdlib: patterns: [ {include: "#modules"} {include: "#stdproc"} {match: "\\b(anyclass)\\b", name: "support.class.anyclass.turing"} # Routines/constants exported unqualified {include: "#keyboard-constants"} {include: "#math-routines"} {include: "#str-routines"} {include: "#typeconv-routines"} ] # Procedures not associated with any specific module stdproc: name: "support.function.${1:/downcase}.turing" match: """(?x)\\b (addr|buttonchoose|buttonmoved|buttonwait|clock|cls|colou?r|colou?rback|date|delay|drawarc|drawbox|drawdot |drawfill|drawfillarc|drawfillbox|drawfillmapleleaf|drawfilloval|drawfillpolygon|drawfillstar|drawline |drawmapleleaf|drawoval|drawpic|drawpolygon|drawstar|empty|eof|fetcharg|getch|getchar|getenv|getpid |getpriority|hasch|locate|locatexy|maxcol|maxcolou?r|maxint|maxnat|maxrow|maxx|maxy|minint|minnat |mousewhere|nargs|parallelget|parallelput|play|playdone|pred|rand|randint|randnext|randomize |randseed|setpriority|setscreen|simutime|sizeof|sizepic|sound|succ|sysclock|takepic|time|wallclock |whatcol|whatcolou?r|whatcolou?rback|whatdotcolou?r|whatrow)\\b """ # Keyboard constants: http://compsci.ca/holtsoft/doc/keyboardmodule.html "keyboard-constants": name: "support.constant.keyboard.turing" match: """(?x)\\b(?: (?:KEY|ORD)_(?: F1[0-2]|F[1-9]|CTRL_[A-Z]|ALT_[A-Z0-9]|(?:CTRL|ALT|SHIFT)_(?:F1[0-2]|F[1-9])| ALT(?:_EQUALS|_MINUS)?|BACK_TAB|BACKSPACE|CTRL|DELETE|END|ENTER|ESC|HOME|INSERT|KEYPAD_5|PGDN|PGUP|SHIFT|SHIFT_TAB|TAB| CTRL_(?:BACKSLASH|BACKSPACE|CARET|(?:UP|RIGHT|LEFT|DOWN)_ARROW|CLOSE_BRACKET|DELETE|END|HOME|INSERT|OPEN_BRACKET|PGDN|PGUP|UNDERSCORE)| (?:UP|RIGHT|LEFT|DOWN)_ARROW) | ORD_(?: AMPERSAND|APOSTROPHE|ASTERISK|BACKSLASH|BAR|CARET|COLON|COMMA|DOT|EQUALS|(?:GREATER|LESS)_THAN| (?:CLOSE|OPEN)_(?:BRACE|BRACKET|PARENTHESIS)|(?:EXCALAMATION|HAS|QUESTION|QUOTATION)_MARK|MINUS| (?:AT|DOLLAR|PERCENT)_SIGN|PERIOD|PLUS|SEMICOLON|SINGLE_QUOTE|SLASH|SPACE|TILDE|UNDERSCORE|[A-Z0-9]|LOWER_[A-Z]) )\\b """ # Math routines: http://compsci.ca/holtsoft/doc/mathmodule.html "math-routines": name: "support.function.${1:/downcase}.turing" match: "\\b(abs|arccos|arccosd|arcsin|arcsind|arctan|arctand|cos|cosd|exp|ln|max|min|sign|sin|sind|tan|tand|sqrt)\\b" # Str routines: http://compsci.ca/holtsoft/doc/strmodule.html "str-routines": name: "support.function.${1:/downcase}.turing" match: "\\b(Lower|Upper|Trim|index|length|repeat)\\b" # TypeConv routines: http://compsci.ca/holtsoft/doc/typeconvmodule.html "typeconv-routines": name: "support.function.${1:/downcase}.turing" match: "\\b(ceil|chr|erealstr|floor|frealstr|intreal|intstr|natreal|natstr|ord|realstr|round|strint|strintok|strnat|strnatok|strreal|strrealok)\\b" # Modules modules: patterns: [{ # Concurrency match: "\\b(Concurrency)\\b(?:(\\.)(empty|[gs]etpriority|simutime)?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.function.$3.turing" },{ # Config match: "\\b(Config)\\b(?:(\\.)(Display|Lang|Machine)?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.function.${3:/downcase}.turing" },{ # Dir match: "\\b(Dir)\\b(?:(\\.)(Change|Close|Create|Current|Delete|Get|GetLong|Open)?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.function.${3:/downcase}.turing" },{ # Draw match: "\\b(Draw)\\b(?:(\\.)(Arc|Box|Cls|Dot|Fill|FillArc|FillBox|FillMapleLeaf|FillOval|FillPolygon|FillStar|Line|MapleLeaf|Oval|Polygon|Star|Text)?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.function.${3:/downcase}.turing" },{ # Error match: "\\b(Error)\\b(?:(\\.)(Last|LastMsg|LastStr|Msg|Str|Trip)?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.function.${3:/downcase}.turing" },{ # ErrorNum/Exceptions match: "\\b(ErrorNum|Exceptions)\\b(?:(\\.)(\\w+)?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.function.${3:/downcase}.turing" },{ # File match: "\\b(File)\\b(?:(\\.)(Copy|Delete|DiskFree|Exists|Rename|Status)?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.function.${3:/downcase}.turing" },{ # Font match: "\\b(Font)\\b(?:(\\.)(Draw|Free|GetName|GetSize|GetStyle|Name|New|Sizes|StartName|StartSize|Width)?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.function.${3:/downcase}.turing" },{ # GUI match: """(?x)\\b(GUI)\\b(?:(\\.) (AddLine|AddText|Alert|Alert2|Alert3|AlertFull|Choose|ChooseFull|ClearText|CloseWindow|CreateButton|CreateButtonFull |CreateCanvas|CreateCanvasFull|CreateCheckBox|CreateCheckBoxFull|CreateFrame|CreateHorizontalScrollBar|CreateHorizontalScrollBarFull |CreateHorizontalSlider|CreateLabel|CreateLabelFull|CreateLabelledFrame|CreateLine|CreateMenu|CreateMenuItem|CreateMenuItemFull |CreatePicture|CreatePictureButton|CreatePictureButtonFull|CreatePictureRadioButton|CreatePictureRadioButtonFull|CreateRadioButton |CreateRadioButtonFull|CreateTextBox|CreateTextBoxFull|CreateTextField|CreateTextFieldFull|CreateVerticalScrollBar|CreateVerticalScrollBarFull |CreateVerticalSlider|Disable|Dispose|DrawArc|DrawBox|DrawCls|DrawDot|DrawFill|DrawFillArc|DrawFillBox|DrawFillMapleLeaf|DrawFillOval |DrawFillPolygon|DrawFillStar|DrawLine|DrawMapleLeaf|DrawOval|DrawPolygon|DrawStar|DrawText|Enable|FontDraw|GetCheckBox|GetEventTime |GetEventWidgetID|GetEventWindow|GetHeight|GetMenuBarHeight|GetScrollBarWidth|GetSliderValue|GetText|GetVersion|GetWidth|GetX|GetY|Hide |HideMenuBar|OpenFile|OpenFileFull|PicDraw|PicNew|PicScreenLoad|PicScreenSave|ProcessEvent|Quit|Refresh|SaveFile|SaveFileFull|SelectRadio |SetActive|SetBackgroundColor|SetBackgroundColour|SetCheckBox|SetDefault|SetDisplayWhenCreated|SetKeyEventHandler|SetLabel|SetMouseEventHandler |SetNullEventHandler|SetPosition|SetPositionAndSize|SetScrollAmount|SetSelection|SetSize|SetSliderMinMax|SetSliderReverse|SetSliderSize |SetSliderValue|SetText|SetXOR|Show|ShowMenuBar)?\\b)? """ captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.function.${3:/downcase}.turing" },{ # Input match: "\\b(Input)\\b(?:(\\.)(getch|getchar|hasch|KeyDown|Pause)?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.function.${3:/downcase}.turing" },{ # Joystick match: "\\b(Joystick)\\b(?:(\\.)(GetInfo)?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.function.${3:/downcase}.turing" },{ # Keyboard match: "\\b(Keyboard)\\b(?:(\\.)(\\w+)?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: patterns: [include: "#keyboard-constants"] },{ # Limits match: "\\b(Limits)\\b(?:(\\.)(DefaultFW|DefaultEW|minint|maxint|minnat|maxnat)?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.function.${3:/downcase}.turing" },{ # Math match: "(?x)\\b(Math)\\b(?:(\\.)(?:(PI|E)|(Distance|DistancePointLine)|(\\w+))?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.constant.${3:/downcase}.turing" 4: name: "support.function.${4:/downcase}.turing" 5: patterns: [include: "#math-routines"] },{ # Mouse match: "\\b(Mouse)\\b(?:(\\.)(ButtonChoose|ButtonMoved|ButtonWait|Where)?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.function.${3:/downcase}.turing" },{ # Music match: "\\b(Music)\\b(?:(\\.)(Play|PlayFile|PlayFileStop|Sound|SoundOff)?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.function.${3:/downcase}.turing" },{ # Net match: """(?x) \\b(Net)\\b(?:(\\.) (BytesAvailable|CharAvailable|CloseConnection|HostAddressFromName|HostNameFromAddress |LineAvailable|LocalAddress|LocalName|OpenConnection|OpenURLConnection|TokenAvailable |WaitForConnection)?\\b)?""" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.function.${3:/downcase}.turing" },{ # PC match: "\\b(PC)\\b(?:(\\.)(ParallelGet|ParallelPut)?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.function.${3:/downcase}.turing" },{ # Pic match: """(?x) \\b(Pic)\\b(?:(\\.) (Blend|Blur|Draw|DrawFrames|DrawFramesBack|DrawSpecial|DrawSpecialBack|FileNew |FileNewFrames|Flip|Frames|Free|Height|Mirror|New|Rotate|Save|Scale|ScreenLoad |ScreenSave|SetTransparentColou?r|Width)? \\b)?""" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.function.${3:/downcase}.turing" },{ # Rand match: "\\b(Rand)\\b(?:(\\.)(Int|Next|Real|Reset|Seed|Set)?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.function.${3:/downcase}.turing" },{ # RGB match: "\\b(RGB)\\b(?:(\\.)(AddColou?r|[GS]etColou?r|maxcolou?r)?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.function.${3:/downcase}.turing" },{ # Sprite match: "\\b(Sprite)\\b(?:(\\.)(Animate|ChangePic|Free|Hide|New|SetFrameRate|SetHeight|SetPosition|Show)?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.function.${3:/downcase}.turing" },{ # Stream match: "\\b(Stream)\\b(?:(\\.)(eof|Flush|FlushAll)?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.function.${3:/downcase}.turing" },{ # Str match: "\\b(Str)\\b(?:(\\.)(\\w+)?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: patterns: [include: "#str-routines"] },{ # Sys match: "\\b(Sys)\\b(?:(\\.)(Exec|FetchArg|GetComputerName|GetEnv|GetPid|GetUserName|Nargs)?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.function.${3:/downcase}.turing" },{ # Text match: "\\b(Text)\\b(?:(\\.)(Cls|Colou?r|Colou?rBack|Locate|LocateXY|maxcol|maxrow|WhatCol|WhatColou?r|WhatColou?rBack|WhatRow)?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.function.${3:/downcase}.turing" },{ # Time match: "\\b(Time)\\b(?:(\\.)(Date|DateSec|Delay|Elapsed|ElapsedCPU|PartsSec|Sec|SecDate|SecParts)?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.function.${3:/downcase}.turing" },{ # TypeConv match: "\\b(TypeConv)\\b(?:(\\.)(\\w+)?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: patterns: [include: "#typeconv-routines"] },{ # View match: "\\b(View)\\b(?:(\\.)(ClipAdd|ClipOff|ClipSet|maxcolou?r|maxx|maxy|Set|Update|WhatDotColou?r)?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.function.${3:/downcase}.turing" },{ # Window match: "\\b(Window)\\b(?:(\\.)(Close|GetActive|GetPosition|GetSelect|Hide|Open|Select|Set|SetActive|SetPosition|Show|Update)?\\b)?" captures: 1: name: "support.class.${1:/downcase}.turing" 2: name: "meta.delimiter.property.period.turing" 3: name: "support.function.${3:/downcase}.turing" }]
[ { "context": "###\n© Copyright 2013-2014 Stephan Jorek <stephan.jorek@gmail.com> \n\nLicensed under the A", "end": 39, "score": 0.9998863339424133, "start": 26, "tag": "NAME", "value": "Stephan Jorek" }, { "context": "###\n© Copyright 2013-2014 Stephan Jorek <stephan.jorek@gmail.com...
src/Dom/Traversal/Level2NodeIterator.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. ### #~ require {Node:{ DOCUMENT_NODE }} = require '../Node' {Document:{ ownerDocument }} = require '../Document' {Traversal} = require '../Traversal' #~ export exports = module?.exports ? this # Level2NodeIterator # ================================ # -------------------------------- # A class to hold state for a DOM traversal. # # This implementation depends on *DOM Level ≥ 2*'s `NodeIterator`. # # @public # @class Level2NodeIterator # @extends goatee.Dom.Traversal # @namespace goatee.Dom.Traversal # @see [DOM Level 2 `NodeIterator` Interface-Specification](http://www.w3.org/TR/DOM-Level-2-Traversal-Range/traversal.html#Traversal-NodeIterator) exports.Level2NodeIterator = \ class Level2NodeIterator extends Traversal # -------------------------------- # > Bitwise OR'd list of Filter specification constants from the NodeFilter # DOM interface, indicating which nodes to iterate over. # # @public # @property filter # @type {Number} # @see [DOM Level 2 `NodeFilter` Interface-Specification](http://www.w3.org/TR/DOM-Level-2-Traversal-Range/traversal.html#Traversal-NodeFilter) # @see [`NodeFilter` Constants](https://developer.mozilla.org/en/DOM/NodeFilter#Filter_specification_constants) filter: NodeFilter.SHOW_ELEMENT # -------------------------------- # > An object implementing the NodeFilter interface; its `acceptNode()` method # will be called for each node in the subtree based at root which is accepted # as included by the `filter` flag (above) to determine whether or not to # include it in the list of iterable nodes (a simple callback function may # also be used instead). The method should return one of # `NodeFilter.[FILTER_ACCEPT|FILTER_REJECT|FILTER_SKIP]`, ie.: # > # > { # > acceptNode: function (node) { # > return NodeFilter.FILTER_ACCEPT; # > } # > } # # @public # @property options # @type {Object} # @see [DOM Level 2 `NodeFilter` Interface-Specification](http://www.w3.org/TR/DOM-Level-2-Traversal-Range/traversal.html#Traversal-NodeFilter) # @see [`NodeFilter` Documentation](https://developer.mozilla.org/en-US/docs/DOM/NodeFilter) options: null # -------------------------------- # Processes the DOM tree in breadth-first order. # # @public # @method run # @param {Node} root The root node of the traversal # @return {goatee.Dom.Traversal} run: (root) -> @process root, @prepare root # -------------------------------- # Prepare the node iterator for a single root node. # # @public # @method prepare # @param {Node} root The root node of the traversal # @return {NodeIterator} prepare: (root) -> @collect root, ownerDocument(root) # -------------------------------- # Create an iterator collecting a single node's immediate child-nodes. # # @public # @method collect # @param {Node} root The root node of the traversal. # @param {Document} doc Root's owner-document. # @return {NodeIterator} # @see [`createNodeIterator` Documentation](https://developer.mozilla.org/en-US/docs/Web/API/Document.createNodeIterator) collect: (root, doc) -> doc.createNodeIterator( # Node to use as root root, # Only consider nodes that match this filter @filter, # Object containing the function to use as method of the NodeFilter @options, # > Note: Prior to Gecko 12.0 (Firefox 12.0 / Thunderbird 12.0 / # SeaMonkey 2.9), this method accepted an optional fourth parameter # (entityReferenceExpansion) that is not part of the DOM4 specification, # and has therefore been removed. This parameter indicated whether or # not the children of entity reference nodes were visible to the # iterator. Since such nodes were never created in browsers, this # parameter had no effect. # @deprecated false ) # -------------------------------- # Processes the root node and all of its children. # # @public # @method process # @param {Node} root The root node of the traversal. # @param {NodeIterator} node The current node of the traversal. # @return {goatee.Dom.Traversal} process: (root, iterator) -> # We deliberately enforce equality instead of identity here. @callback root if `root.nodeType == DOCUMENT_NODE` @callback node while node = iterator.nextNode() return this # -------------------------------- # Creates the `Traversal`-instance. # # @static # @public # @method create # @param {Function} callback A function, called for each traversed node # @return {goatee.Dom.Traversal} @create: (callback) -> new Level2NodeIterator callback
174579
### © 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. ### #~ require {Node:{ DOCUMENT_NODE }} = require '../Node' {Document:{ ownerDocument }} = require '../Document' {Traversal} = require '../Traversal' #~ export exports = module?.exports ? this # Level2NodeIterator # ================================ # -------------------------------- # A class to hold state for a DOM traversal. # # This implementation depends on *DOM Level ≥ 2*'s `NodeIterator`. # # @public # @class Level2NodeIterator # @extends goatee.Dom.Traversal # @namespace goatee.Dom.Traversal # @see [DOM Level 2 `NodeIterator` Interface-Specification](http://www.w3.org/TR/DOM-Level-2-Traversal-Range/traversal.html#Traversal-NodeIterator) exports.Level2NodeIterator = \ class Level2NodeIterator extends Traversal # -------------------------------- # > Bitwise OR'd list of Filter specification constants from the NodeFilter # DOM interface, indicating which nodes to iterate over. # # @public # @property filter # @type {Number} # @see [DOM Level 2 `NodeFilter` Interface-Specification](http://www.w3.org/TR/DOM-Level-2-Traversal-Range/traversal.html#Traversal-NodeFilter) # @see [`NodeFilter` Constants](https://developer.mozilla.org/en/DOM/NodeFilter#Filter_specification_constants) filter: NodeFilter.SHOW_ELEMENT # -------------------------------- # > An object implementing the NodeFilter interface; its `acceptNode()` method # will be called for each node in the subtree based at root which is accepted # as included by the `filter` flag (above) to determine whether or not to # include it in the list of iterable nodes (a simple callback function may # also be used instead). The method should return one of # `NodeFilter.[FILTER_ACCEPT|FILTER_REJECT|FILTER_SKIP]`, ie.: # > # > { # > acceptNode: function (node) { # > return NodeFilter.FILTER_ACCEPT; # > } # > } # # @public # @property options # @type {Object} # @see [DOM Level 2 `NodeFilter` Interface-Specification](http://www.w3.org/TR/DOM-Level-2-Traversal-Range/traversal.html#Traversal-NodeFilter) # @see [`NodeFilter` Documentation](https://developer.mozilla.org/en-US/docs/DOM/NodeFilter) options: null # -------------------------------- # Processes the DOM tree in breadth-first order. # # @public # @method run # @param {Node} root The root node of the traversal # @return {goatee.Dom.Traversal} run: (root) -> @process root, @prepare root # -------------------------------- # Prepare the node iterator for a single root node. # # @public # @method prepare # @param {Node} root The root node of the traversal # @return {NodeIterator} prepare: (root) -> @collect root, ownerDocument(root) # -------------------------------- # Create an iterator collecting a single node's immediate child-nodes. # # @public # @method collect # @param {Node} root The root node of the traversal. # @param {Document} doc Root's owner-document. # @return {NodeIterator} # @see [`createNodeIterator` Documentation](https://developer.mozilla.org/en-US/docs/Web/API/Document.createNodeIterator) collect: (root, doc) -> doc.createNodeIterator( # Node to use as root root, # Only consider nodes that match this filter @filter, # Object containing the function to use as method of the NodeFilter @options, # > Note: Prior to Gecko 12.0 (Firefox 12.0 / Thunderbird 12.0 / # SeaMonkey 2.9), this method accepted an optional fourth parameter # (entityReferenceExpansion) that is not part of the DOM4 specification, # and has therefore been removed. This parameter indicated whether or # not the children of entity reference nodes were visible to the # iterator. Since such nodes were never created in browsers, this # parameter had no effect. # @deprecated false ) # -------------------------------- # Processes the root node and all of its children. # # @public # @method process # @param {Node} root The root node of the traversal. # @param {NodeIterator} node The current node of the traversal. # @return {goatee.Dom.Traversal} process: (root, iterator) -> # We deliberately enforce equality instead of identity here. @callback root if `root.nodeType == DOCUMENT_NODE` @callback node while node = iterator.nextNode() return this # -------------------------------- # Creates the `Traversal`-instance. # # @static # @public # @method create # @param {Function} callback A function, called for each traversed node # @return {goatee.Dom.Traversal} @create: (callback) -> new Level2NodeIterator callback
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. ### #~ require {Node:{ DOCUMENT_NODE }} = require '../Node' {Document:{ ownerDocument }} = require '../Document' {Traversal} = require '../Traversal' #~ export exports = module?.exports ? this # Level2NodeIterator # ================================ # -------------------------------- # A class to hold state for a DOM traversal. # # This implementation depends on *DOM Level ≥ 2*'s `NodeIterator`. # # @public # @class Level2NodeIterator # @extends goatee.Dom.Traversal # @namespace goatee.Dom.Traversal # @see [DOM Level 2 `NodeIterator` Interface-Specification](http://www.w3.org/TR/DOM-Level-2-Traversal-Range/traversal.html#Traversal-NodeIterator) exports.Level2NodeIterator = \ class Level2NodeIterator extends Traversal # -------------------------------- # > Bitwise OR'd list of Filter specification constants from the NodeFilter # DOM interface, indicating which nodes to iterate over. # # @public # @property filter # @type {Number} # @see [DOM Level 2 `NodeFilter` Interface-Specification](http://www.w3.org/TR/DOM-Level-2-Traversal-Range/traversal.html#Traversal-NodeFilter) # @see [`NodeFilter` Constants](https://developer.mozilla.org/en/DOM/NodeFilter#Filter_specification_constants) filter: NodeFilter.SHOW_ELEMENT # -------------------------------- # > An object implementing the NodeFilter interface; its `acceptNode()` method # will be called for each node in the subtree based at root which is accepted # as included by the `filter` flag (above) to determine whether or not to # include it in the list of iterable nodes (a simple callback function may # also be used instead). The method should return one of # `NodeFilter.[FILTER_ACCEPT|FILTER_REJECT|FILTER_SKIP]`, ie.: # > # > { # > acceptNode: function (node) { # > return NodeFilter.FILTER_ACCEPT; # > } # > } # # @public # @property options # @type {Object} # @see [DOM Level 2 `NodeFilter` Interface-Specification](http://www.w3.org/TR/DOM-Level-2-Traversal-Range/traversal.html#Traversal-NodeFilter) # @see [`NodeFilter` Documentation](https://developer.mozilla.org/en-US/docs/DOM/NodeFilter) options: null # -------------------------------- # Processes the DOM tree in breadth-first order. # # @public # @method run # @param {Node} root The root node of the traversal # @return {goatee.Dom.Traversal} run: (root) -> @process root, @prepare root # -------------------------------- # Prepare the node iterator for a single root node. # # @public # @method prepare # @param {Node} root The root node of the traversal # @return {NodeIterator} prepare: (root) -> @collect root, ownerDocument(root) # -------------------------------- # Create an iterator collecting a single node's immediate child-nodes. # # @public # @method collect # @param {Node} root The root node of the traversal. # @param {Document} doc Root's owner-document. # @return {NodeIterator} # @see [`createNodeIterator` Documentation](https://developer.mozilla.org/en-US/docs/Web/API/Document.createNodeIterator) collect: (root, doc) -> doc.createNodeIterator( # Node to use as root root, # Only consider nodes that match this filter @filter, # Object containing the function to use as method of the NodeFilter @options, # > Note: Prior to Gecko 12.0 (Firefox 12.0 / Thunderbird 12.0 / # SeaMonkey 2.9), this method accepted an optional fourth parameter # (entityReferenceExpansion) that is not part of the DOM4 specification, # and has therefore been removed. This parameter indicated whether or # not the children of entity reference nodes were visible to the # iterator. Since such nodes were never created in browsers, this # parameter had no effect. # @deprecated false ) # -------------------------------- # Processes the root node and all of its children. # # @public # @method process # @param {Node} root The root node of the traversal. # @param {NodeIterator} node The current node of the traversal. # @return {goatee.Dom.Traversal} process: (root, iterator) -> # We deliberately enforce equality instead of identity here. @callback root if `root.nodeType == DOCUMENT_NODE` @callback node while node = iterator.nextNode() return this # -------------------------------- # Creates the `Traversal`-instance. # # @static # @public # @method create # @param {Function} callback A function, called for each traversed node # @return {goatee.Dom.Traversal} @create: (callback) -> new Level2NodeIterator callback
[ { "context": "ped()\n data =\n id: sessionId\n name: \"test Session\"\n description: \"meine super test ses", "end": 1546, "score": 0.590667188167572, "start": 1542, "tag": "NAME", "value": "test" } ]
app/coffee/controllers/sessions.coffee
sebastian-alfers/google-fit-js
2
"use strict" ###* @ngdoc function @name gFitJsApp.controller:AboutCtrl @description # AboutCtrl Controller of the gFitJsApp ### angular.module("gFitJsApp").controller "SessionsCtrl", ($location, $scope, Game, GoogleFitAuth) -> # Requests if !GoogleFitAuth.isLoggedIn() $location.path("/login") return $scope.onSuccessSessionDeleted = () -> console.log 'session was deleted' $scope.listSessions() $scope.onErrorSessionDeleted = () -> alert 'error while deleting session' $scope.removeSession = (session) -> s = $scope.onSuccessSessionDeleted e = $scope.onErrorSessionDeleted url = "https://www.googleapis.com/fitness/v1/users/me/sessions/#{session.id}" # Requests.DELETE(url, s, e) $.ajax url: url type: "DELETE" success: s error: e beforeSend: window.setHeader getTimestamp = () -> (new Date).getTime() $scope.startSession = () -> $scope.started = getTimestamp() sessionStarted() getRandomId = () -> getTimestamp() + Math.floor((Math.random()*100000)+1) errorAddDataPoints = (error) -> console.log 'mist, error while adding data points' console.log error successAddDataPoints = (dataPointsResponse) -> activityTypeWeightLifting = 97 sessionId = getRandomId() url = "https://www.googleapis.com/fitness/v1/users/me/sessions/"+sessionId #scope = "https://www.googleapis.com/auth/fitness.activity.write" $scope.stopped = getTimestamp() sessionStopped() data = id: sessionId name: "test Session" description: "meine super test session" startTimeMillis: $scope.started endTimeMillis: $scope.stopped modifiedTimeMillis: $scope.stopped application: packageName: "htw.maph.weightlifting" version: "0.1" detailsUrl: "http://health.sebalf.de/#/details" name: "Test App for Weightlifting" activityType: activityTypeWeightLifting $.ajax url: url data: JSON.stringify(data) type: "PUT" #datatype: "application/json" success: success error: error beforeSend: window.setHeader $scope.stopSession = () -> if $scope.dataPoints.length == 0 alert 'no data points' sessionStopped() return $('.session-container').hide() $('.load-sessions').show() # add data pints dataSourceId = window.gapi.currentDevice.dataStreamId firstDataPointStart = $scope.firstDataPointStart lastDataPointEnd = $scope.lastDataPointEnd dataSetId = "#{firstDataPointStart}-#{lastDataPointEnd}" addPointsUrl = encodeURI("https://www.googleapis.com/fitness/v1/users/me/dataSources/#{dataSourceId}/datasets/#{dataSetId}") dataSetData = minStartTimeNs: firstDataPointStart maxEndTimeNs: lastDataPointEnd dataSourceId: dataSourceId point: $scope.dataPoints console.log 'first point: ' + moment(parseInt(firstDataPointStart)).format('MMMM Do YYYY, h:mm:ss a') console.log '*********' for point in $scope.dataPoints console.log point.created.format('MMMM Do YYYY, h:mm:ss a') console.log '*********' console.log 'last point: ' + moment(parseInt(lastDataPointEnd)).format('MMMM Do YYYY, h:mm:ss a') $.ajax url: addPointsUrl data: JSON.stringify(dataSetData) type: "PATCH" success: successAddDataPoints error: errorAddDataPoints beforeSend: window.setHeader # clear data points $scope.dataPoints = [] success = (data) -> console.log '**added session****' console.log data $scope.listSessions() error = (data) -> console.log '*error while adding*****' console.log data sessionStopped = () -> $('#startSessionBtn').show() $('#stopSessionBtn').hide() return true sessionStarted = () -> $('#startSessionBtn').hide() $('#stopSessionBtn').show() Game.start(pointScored) return true pointScored = (points) -> $scope.addDataPoint() $scope.sessionList = [] successListSessions = (data) -> $scope.sessionList = [] if data.session.length for session in data.session session.startTimeMoment = moment(parseInt(session.startTimeMillis)) session.endTimeMoment = moment(parseInt(session.endTimeMillis)) session.duration = moment.duration(session.endTimeMoment.diff(session.startTimeMoment)) $scope.sessionList.push session console.log $scope.sessionList $scope.$apply() $('.session-container').show() $('.load-sessions').hide() errorListSessions = (data) -> console.log 'error while reading sessions' $scope.listSessions = () -> $('.session-container').hide() $('.load-sessions').show() url = "https://www.googleapis.com/fitness/v1/users/me/sessions" $.ajax url: url type: "GET" #datatype: "application/json" success: successListSessions error: errorListSessions beforeSend: window.setHeader return true #$scope.sessions.push 'test'+getRandomId() #console.log $scope.sessions # $scope.apply() $scope.dataPoints = [] $scope.addDataPoint = () -> startTime = getTimestamp() *1000000 endTime = startTime if(!$scope.dataPoints.length) $scope.firstDataPointStart = startTime $scope.lastDataPointEnd = endTime data = startTimeNanos: startTime endTimeNanos: endTime dataTypeName: "com.google.step_count.delta" value: [intVal: 1] created: moment() $scope.dataPoints.push data $scope.$apply() $scope.showSessionDetails = (session) -> console.log 'data set from' + moment(parseInt(session.startTimeMillis)).format('MMMM Do YYYY, h:mm:ss a') console.log 'data set to' + moment(parseInt(session.endTimeMillis)).format('MMMM Do YYYY, h:mm:ss a') datasetId = session.endTimeMillis*1000000 + "-" + session.startTimeMillis*1000000 # datasetId = "1416137954720000000-1416137954729000000" getDataSet(datasetId) $scope.successGetDataSet = (data) -> $scope.sessionStarted = moment(data.minStartTimeNs / 1000000) $scope.sessionStopped = moment(data.maxEndTimeNs / 1000000) $scope.sessionDataPoints = null if data.point? for point in data.point point.startTimeMoment = moment(point.startTimeNanos / 1000000) $scope.sessionDataPoints = data.point console.log $scope.sessionDataPoints $scope.$apply() $('.loading').hide() $('.session-details-content').show() $scope.errorGetDataSet = (error) -> alert 'eror while getting dataSet' console.log error getDataSet = (datasetId) -> dataSourceId = window.gapi.currentDevice.dataStreamId url = encodeURI("https://www.googleapis.com/fitness/v1/users/me/dataSources/#{dataSourceId}/datasets/#{datasetId}") console.log url $.ajax url: url type: "GET" #datatype: "application/json" success: $scope.successGetDataSet error: $scope.errorGetDataSet beforeSend: window.setHeader
34468
"use strict" ###* @ngdoc function @name gFitJsApp.controller:AboutCtrl @description # AboutCtrl Controller of the gFitJsApp ### angular.module("gFitJsApp").controller "SessionsCtrl", ($location, $scope, Game, GoogleFitAuth) -> # Requests if !GoogleFitAuth.isLoggedIn() $location.path("/login") return $scope.onSuccessSessionDeleted = () -> console.log 'session was deleted' $scope.listSessions() $scope.onErrorSessionDeleted = () -> alert 'error while deleting session' $scope.removeSession = (session) -> s = $scope.onSuccessSessionDeleted e = $scope.onErrorSessionDeleted url = "https://www.googleapis.com/fitness/v1/users/me/sessions/#{session.id}" # Requests.DELETE(url, s, e) $.ajax url: url type: "DELETE" success: s error: e beforeSend: window.setHeader getTimestamp = () -> (new Date).getTime() $scope.startSession = () -> $scope.started = getTimestamp() sessionStarted() getRandomId = () -> getTimestamp() + Math.floor((Math.random()*100000)+1) errorAddDataPoints = (error) -> console.log 'mist, error while adding data points' console.log error successAddDataPoints = (dataPointsResponse) -> activityTypeWeightLifting = 97 sessionId = getRandomId() url = "https://www.googleapis.com/fitness/v1/users/me/sessions/"+sessionId #scope = "https://www.googleapis.com/auth/fitness.activity.write" $scope.stopped = getTimestamp() sessionStopped() data = id: sessionId name: "<NAME> Session" description: "meine super test session" startTimeMillis: $scope.started endTimeMillis: $scope.stopped modifiedTimeMillis: $scope.stopped application: packageName: "htw.maph.weightlifting" version: "0.1" detailsUrl: "http://health.sebalf.de/#/details" name: "Test App for Weightlifting" activityType: activityTypeWeightLifting $.ajax url: url data: JSON.stringify(data) type: "PUT" #datatype: "application/json" success: success error: error beforeSend: window.setHeader $scope.stopSession = () -> if $scope.dataPoints.length == 0 alert 'no data points' sessionStopped() return $('.session-container').hide() $('.load-sessions').show() # add data pints dataSourceId = window.gapi.currentDevice.dataStreamId firstDataPointStart = $scope.firstDataPointStart lastDataPointEnd = $scope.lastDataPointEnd dataSetId = "#{firstDataPointStart}-#{lastDataPointEnd}" addPointsUrl = encodeURI("https://www.googleapis.com/fitness/v1/users/me/dataSources/#{dataSourceId}/datasets/#{dataSetId}") dataSetData = minStartTimeNs: firstDataPointStart maxEndTimeNs: lastDataPointEnd dataSourceId: dataSourceId point: $scope.dataPoints console.log 'first point: ' + moment(parseInt(firstDataPointStart)).format('MMMM Do YYYY, h:mm:ss a') console.log '*********' for point in $scope.dataPoints console.log point.created.format('MMMM Do YYYY, h:mm:ss a') console.log '*********' console.log 'last point: ' + moment(parseInt(lastDataPointEnd)).format('MMMM Do YYYY, h:mm:ss a') $.ajax url: addPointsUrl data: JSON.stringify(dataSetData) type: "PATCH" success: successAddDataPoints error: errorAddDataPoints beforeSend: window.setHeader # clear data points $scope.dataPoints = [] success = (data) -> console.log '**added session****' console.log data $scope.listSessions() error = (data) -> console.log '*error while adding*****' console.log data sessionStopped = () -> $('#startSessionBtn').show() $('#stopSessionBtn').hide() return true sessionStarted = () -> $('#startSessionBtn').hide() $('#stopSessionBtn').show() Game.start(pointScored) return true pointScored = (points) -> $scope.addDataPoint() $scope.sessionList = [] successListSessions = (data) -> $scope.sessionList = [] if data.session.length for session in data.session session.startTimeMoment = moment(parseInt(session.startTimeMillis)) session.endTimeMoment = moment(parseInt(session.endTimeMillis)) session.duration = moment.duration(session.endTimeMoment.diff(session.startTimeMoment)) $scope.sessionList.push session console.log $scope.sessionList $scope.$apply() $('.session-container').show() $('.load-sessions').hide() errorListSessions = (data) -> console.log 'error while reading sessions' $scope.listSessions = () -> $('.session-container').hide() $('.load-sessions').show() url = "https://www.googleapis.com/fitness/v1/users/me/sessions" $.ajax url: url type: "GET" #datatype: "application/json" success: successListSessions error: errorListSessions beforeSend: window.setHeader return true #$scope.sessions.push 'test'+getRandomId() #console.log $scope.sessions # $scope.apply() $scope.dataPoints = [] $scope.addDataPoint = () -> startTime = getTimestamp() *1000000 endTime = startTime if(!$scope.dataPoints.length) $scope.firstDataPointStart = startTime $scope.lastDataPointEnd = endTime data = startTimeNanos: startTime endTimeNanos: endTime dataTypeName: "com.google.step_count.delta" value: [intVal: 1] created: moment() $scope.dataPoints.push data $scope.$apply() $scope.showSessionDetails = (session) -> console.log 'data set from' + moment(parseInt(session.startTimeMillis)).format('MMMM Do YYYY, h:mm:ss a') console.log 'data set to' + moment(parseInt(session.endTimeMillis)).format('MMMM Do YYYY, h:mm:ss a') datasetId = session.endTimeMillis*1000000 + "-" + session.startTimeMillis*1000000 # datasetId = "1416137954720000000-1416137954729000000" getDataSet(datasetId) $scope.successGetDataSet = (data) -> $scope.sessionStarted = moment(data.minStartTimeNs / 1000000) $scope.sessionStopped = moment(data.maxEndTimeNs / 1000000) $scope.sessionDataPoints = null if data.point? for point in data.point point.startTimeMoment = moment(point.startTimeNanos / 1000000) $scope.sessionDataPoints = data.point console.log $scope.sessionDataPoints $scope.$apply() $('.loading').hide() $('.session-details-content').show() $scope.errorGetDataSet = (error) -> alert 'eror while getting dataSet' console.log error getDataSet = (datasetId) -> dataSourceId = window.gapi.currentDevice.dataStreamId url = encodeURI("https://www.googleapis.com/fitness/v1/users/me/dataSources/#{dataSourceId}/datasets/#{datasetId}") console.log url $.ajax url: url type: "GET" #datatype: "application/json" success: $scope.successGetDataSet error: $scope.errorGetDataSet beforeSend: window.setHeader
true
"use strict" ###* @ngdoc function @name gFitJsApp.controller:AboutCtrl @description # AboutCtrl Controller of the gFitJsApp ### angular.module("gFitJsApp").controller "SessionsCtrl", ($location, $scope, Game, GoogleFitAuth) -> # Requests if !GoogleFitAuth.isLoggedIn() $location.path("/login") return $scope.onSuccessSessionDeleted = () -> console.log 'session was deleted' $scope.listSessions() $scope.onErrorSessionDeleted = () -> alert 'error while deleting session' $scope.removeSession = (session) -> s = $scope.onSuccessSessionDeleted e = $scope.onErrorSessionDeleted url = "https://www.googleapis.com/fitness/v1/users/me/sessions/#{session.id}" # Requests.DELETE(url, s, e) $.ajax url: url type: "DELETE" success: s error: e beforeSend: window.setHeader getTimestamp = () -> (new Date).getTime() $scope.startSession = () -> $scope.started = getTimestamp() sessionStarted() getRandomId = () -> getTimestamp() + Math.floor((Math.random()*100000)+1) errorAddDataPoints = (error) -> console.log 'mist, error while adding data points' console.log error successAddDataPoints = (dataPointsResponse) -> activityTypeWeightLifting = 97 sessionId = getRandomId() url = "https://www.googleapis.com/fitness/v1/users/me/sessions/"+sessionId #scope = "https://www.googleapis.com/auth/fitness.activity.write" $scope.stopped = getTimestamp() sessionStopped() data = id: sessionId name: "PI:NAME:<NAME>END_PI Session" description: "meine super test session" startTimeMillis: $scope.started endTimeMillis: $scope.stopped modifiedTimeMillis: $scope.stopped application: packageName: "htw.maph.weightlifting" version: "0.1" detailsUrl: "http://health.sebalf.de/#/details" name: "Test App for Weightlifting" activityType: activityTypeWeightLifting $.ajax url: url data: JSON.stringify(data) type: "PUT" #datatype: "application/json" success: success error: error beforeSend: window.setHeader $scope.stopSession = () -> if $scope.dataPoints.length == 0 alert 'no data points' sessionStopped() return $('.session-container').hide() $('.load-sessions').show() # add data pints dataSourceId = window.gapi.currentDevice.dataStreamId firstDataPointStart = $scope.firstDataPointStart lastDataPointEnd = $scope.lastDataPointEnd dataSetId = "#{firstDataPointStart}-#{lastDataPointEnd}" addPointsUrl = encodeURI("https://www.googleapis.com/fitness/v1/users/me/dataSources/#{dataSourceId}/datasets/#{dataSetId}") dataSetData = minStartTimeNs: firstDataPointStart maxEndTimeNs: lastDataPointEnd dataSourceId: dataSourceId point: $scope.dataPoints console.log 'first point: ' + moment(parseInt(firstDataPointStart)).format('MMMM Do YYYY, h:mm:ss a') console.log '*********' for point in $scope.dataPoints console.log point.created.format('MMMM Do YYYY, h:mm:ss a') console.log '*********' console.log 'last point: ' + moment(parseInt(lastDataPointEnd)).format('MMMM Do YYYY, h:mm:ss a') $.ajax url: addPointsUrl data: JSON.stringify(dataSetData) type: "PATCH" success: successAddDataPoints error: errorAddDataPoints beforeSend: window.setHeader # clear data points $scope.dataPoints = [] success = (data) -> console.log '**added session****' console.log data $scope.listSessions() error = (data) -> console.log '*error while adding*****' console.log data sessionStopped = () -> $('#startSessionBtn').show() $('#stopSessionBtn').hide() return true sessionStarted = () -> $('#startSessionBtn').hide() $('#stopSessionBtn').show() Game.start(pointScored) return true pointScored = (points) -> $scope.addDataPoint() $scope.sessionList = [] successListSessions = (data) -> $scope.sessionList = [] if data.session.length for session in data.session session.startTimeMoment = moment(parseInt(session.startTimeMillis)) session.endTimeMoment = moment(parseInt(session.endTimeMillis)) session.duration = moment.duration(session.endTimeMoment.diff(session.startTimeMoment)) $scope.sessionList.push session console.log $scope.sessionList $scope.$apply() $('.session-container').show() $('.load-sessions').hide() errorListSessions = (data) -> console.log 'error while reading sessions' $scope.listSessions = () -> $('.session-container').hide() $('.load-sessions').show() url = "https://www.googleapis.com/fitness/v1/users/me/sessions" $.ajax url: url type: "GET" #datatype: "application/json" success: successListSessions error: errorListSessions beforeSend: window.setHeader return true #$scope.sessions.push 'test'+getRandomId() #console.log $scope.sessions # $scope.apply() $scope.dataPoints = [] $scope.addDataPoint = () -> startTime = getTimestamp() *1000000 endTime = startTime if(!$scope.dataPoints.length) $scope.firstDataPointStart = startTime $scope.lastDataPointEnd = endTime data = startTimeNanos: startTime endTimeNanos: endTime dataTypeName: "com.google.step_count.delta" value: [intVal: 1] created: moment() $scope.dataPoints.push data $scope.$apply() $scope.showSessionDetails = (session) -> console.log 'data set from' + moment(parseInt(session.startTimeMillis)).format('MMMM Do YYYY, h:mm:ss a') console.log 'data set to' + moment(parseInt(session.endTimeMillis)).format('MMMM Do YYYY, h:mm:ss a') datasetId = session.endTimeMillis*1000000 + "-" + session.startTimeMillis*1000000 # datasetId = "1416137954720000000-1416137954729000000" getDataSet(datasetId) $scope.successGetDataSet = (data) -> $scope.sessionStarted = moment(data.minStartTimeNs / 1000000) $scope.sessionStopped = moment(data.maxEndTimeNs / 1000000) $scope.sessionDataPoints = null if data.point? for point in data.point point.startTimeMoment = moment(point.startTimeNanos / 1000000) $scope.sessionDataPoints = data.point console.log $scope.sessionDataPoints $scope.$apply() $('.loading').hide() $('.session-details-content').show() $scope.errorGetDataSet = (error) -> alert 'eror while getting dataSet' console.log error getDataSet = (datasetId) -> dataSourceId = window.gapi.currentDevice.dataStreamId url = encodeURI("https://www.googleapis.com/fitness/v1/users/me/dataSources/#{dataSourceId}/datasets/#{datasetId}") console.log url $.ajax url: url type: "GET" #datatype: "application/json" success: $scope.successGetDataSet error: $scope.errorGetDataSet beforeSend: window.setHeader
[ { "context": "###################################\n#\n# Created by Markus\n#\n###############################################", "end": 77, "score": 0.9981158971786499, "start": 71, "tag": "NAME", "value": "Markus" } ]
server/3_database/collection.coffee
agottschalk10/worklearn
0
####################################################### # # Created by Markus # ####################################################### ####################################################### @get_collection_save = (collection_name) -> check collection_name, String collection = get_collection collection_name if not collection throw new Meteor.Error "Collection not found: " + collection_name return collection ####################################################### @backup_collection = (collection_name) -> collection = get_collection_save collection_name data = export_data(collection) return data
69955
####################################################### # # Created by <NAME> # ####################################################### ####################################################### @get_collection_save = (collection_name) -> check collection_name, String collection = get_collection collection_name if not collection throw new Meteor.Error "Collection not found: " + collection_name return collection ####################################################### @backup_collection = (collection_name) -> collection = get_collection_save collection_name data = export_data(collection) return data
true
####################################################### # # Created by PI:NAME:<NAME>END_PI # ####################################################### ####################################################### @get_collection_save = (collection_name) -> check collection_name, String collection = get_collection collection_name if not collection throw new Meteor.Error "Collection not found: " + collection_name return collection ####################################################### @backup_collection = (collection_name) -> collection = get_collection_save collection_name data = export_data(collection) return data
[ { "context": "hains, and they shouldn't break. \"\"\"\n\nusers: {\n \"herb\": {}\n \"basil\": {}\n}\n\nteams: {\n \"cabal\": {\n l", "end": 493, "score": 0.99940025806427, "start": 489, "tag": "USERNAME", "value": "herb" }, { "context": "ey shouldn't break. \"\"\"\n\nusers: {\n...
teamchains/inputs/invite_obsolete_trick.iced
keybase/keybase-test-vectors
4
description: """Admin got tricked into using an old invite. Note that this cannot happen anymore, because when replaying team chains, invites for users that were added afterwards are automatically cleared from ActiveInvites. If SBS message arrived for such invite, admin would ignore it because the inviteId would be invalid for them. But: We want this chain to still be valid, because there may be teams in the wild that had similar sigchains, and they shouldn't break. """ users: { "herb": {} "basil": {} } teams: { "cabal": { links: [ type: "root" members: owner: ["herb"] , type: "invite" signer: "herb" invites: writer: [ { id: "54eafff3400b5bcd8b40bff3d225ab27", # basil%1 name: "579651b0d574971040b531b66efbc519%1", type: "keybase" } ] , type: "change_membership" signer: "herb" members: writer: ["basil"] , # Basil leaves type: "leave" signer: "basil" , # Assume rogue server tricked Herb with SBS message with invite # 54eafff3400b5bcd8b40bff3d225ab27. The invite was not explicitly # cleared nor completed. type: "change_membership" signer: "herb" completed_invites: # Even on new clients, where this invite would have been implicitly # completed, team player shouldn't fail on this link. "54eafff3400b5bcd8b40bff3d225ab27": "basil" members: writer: ["basil"] ] } } sessions: [ loads: [ error: false ] ]
89612
description: """Admin got tricked into using an old invite. Note that this cannot happen anymore, because when replaying team chains, invites for users that were added afterwards are automatically cleared from ActiveInvites. If SBS message arrived for such invite, admin would ignore it because the inviteId would be invalid for them. But: We want this chain to still be valid, because there may be teams in the wild that had similar sigchains, and they shouldn't break. """ users: { "herb": {} "basil": {} } teams: { "cabal": { links: [ type: "root" members: owner: ["herb"] , type: "invite" signer: "herb" invites: writer: [ { id: "<KEY>", # basil%1 name: "579651b0d574971040b531b66efbc519%1", type: "keybase" } ] , type: "change_membership" signer: "herb" members: writer: ["basil"] , # Basil leaves type: "leave" signer: "basil" , # Assume rogue server tricked Herb with SBS message with invite # 5<KEY>. The invite was not explicitly # cleared nor completed. type: "change_membership" signer: "herb" completed_invites: # Even on new clients, where this invite would have been implicitly # completed, team player shouldn't fail on this link. "<KEY>": "basil" members: writer: ["basil"] ] } } sessions: [ loads: [ error: false ] ]
true
description: """Admin got tricked into using an old invite. Note that this cannot happen anymore, because when replaying team chains, invites for users that were added afterwards are automatically cleared from ActiveInvites. If SBS message arrived for such invite, admin would ignore it because the inviteId would be invalid for them. But: We want this chain to still be valid, because there may be teams in the wild that had similar sigchains, and they shouldn't break. """ users: { "herb": {} "basil": {} } teams: { "cabal": { links: [ type: "root" members: owner: ["herb"] , type: "invite" signer: "herb" invites: writer: [ { id: "PI:KEY:<KEY>END_PI", # basil%1 name: "579651b0d574971040b531b66efbc519%1", type: "keybase" } ] , type: "change_membership" signer: "herb" members: writer: ["basil"] , # Basil leaves type: "leave" signer: "basil" , # Assume rogue server tricked Herb with SBS message with invite # 5PI:KEY:<KEY>END_PI. The invite was not explicitly # cleared nor completed. type: "change_membership" signer: "herb" completed_invites: # Even on new clients, where this invite would have been implicitly # completed, team player shouldn't fail on this link. "PI:KEY:<KEY>END_PI": "basil" members: writer: ["basil"] ] } } sessions: [ loads: [ error: false ] ]
[ { "context": " data =\n name : 'My Workspace'\n isDefault : yes\n ", "end": 6499, "score": 0.6429531574249268, "start": 6497, "tag": "NAME", "value": "My" } ]
workers/social/lib/social/models/workspace.coffee
ezgikaysi/koding
1
{ Module } = require 'jraphical' JMachine = require './computeproviders/machine' module.exports = class JWorkspace extends Module KodingError = require '../error' { slugify } = require '../traits/slugifiable' { signature, secure, ObjectId } = require 'bongo' @share() @set indexes : originId : 'sparse' slug : 'sparse' schema : name : String slug : String isDefault : type : Boolean default : no channelId : String machineUId : String machineLabel : String rootPath : String originId : ObjectId layout : Object sharedMethods : static : create : signature Object, Function deleteById : signature String, Function deleteByUid : signature String, Function update : signature String, Object, Function fetchByMachines : signature Function createDefault : signature String, Function instance : delete : signature Function sharedEvents : instance : [] @create$ = secure (client, data, callback) -> { delegate } = client.connection data.originId = delegate._id @create client, data, callback @create = secure (client, data, callback) -> { delegate } = client.connection data.originId ?= delegate._id nickname = delegate.profile.nickname data.slug = slugify data.name?.toLowerCase() { name, slug, machineUId, rootPath, originId, machineLabel } = data # we don't support saving layout for now, i will set it to empty object # to prevent storing any kind of data in it. -- acetz! data.layout = {} kallback = (name, slug) -> data.name = name data.slug = slug data.rootPath = "/home/#{nickname}/Workspaces/#{slug}" unless data.rootPath workspace = new JWorkspace data workspace.save (err) -> if err switch err.code when 11000 # duplicate key error callback() else callback err if err return message = accountId: delegate.socialApiId name: name groupName: slug require('./socialapi/requests').dispatchEvent 'social.workspace_created', message, (err) -> console.error '[dispatchEvent][workspace_created]', err if err uid = machineUId eventName = 'NewWorkspaceCreated' options = { nickname, workspace, uid, eventName } notifyUsers options, callback if data.isDefault then kallback data.name, data.slug else generateUniqueName { originId, name, machineUId }, (err, res) -> return callback err if err? { name, slug } = res kallback name, slug notifyUsers = (options, callback) -> { nickname, workspace, uid, eventName } = options JMachine.one { uid }, (err, machine) -> return callback err if err return callback new KodingError 'Machine not found.' unless machine users = machine.users.map (user) -> user.username if users.length { notifyByUsernames } = require './notify' notifyByUsernames users, eventName, workspace return callback null, workspace generateUniqueName = ({ originId, machineUId, name, index }, callback) -> slug = if index? then "#{name}-#{index}" else name slug = slugify slug JWorkspace.count { originId, slug, machineUId }, (err, count) -> return callback err if err? if count is 0 name = "#{name} #{index}" if index? callback null, { name, slug } else index ?= 0 index += 1 generateUniqueName { originId, machineUId, name, index }, callback @fetch = secure (client, query = {}, callback) -> query.originId = client.connection.delegate._id JWorkspace.some query, { limit: 30 }, callback @fetchByMachines$ = secure (client, callback) -> query = {} JMachine.some$ client, query, (err, machines) -> return callback err if err machineUIds = machines.map (machine) -> machine.uid JWorkspace.some { machineUId: { $in: machineUIds } }, {}, callback @deleteById = secure (client, id, callback) -> delegate = client.connection.delegate selector = originId : delegate._id _id : ObjectId id JWorkspace.one selector, (err, ws) -> return callback err if err? return callback new KodingError 'Workspace not found.' unless ws ws.remove (err) -> return callback err if err options = uid : ws.machineUId nickname : delegate.profile.nickname workspace: ws eventName: 'WorkspaceRemoved' group : client?.context?.group notifyUsers options, callback @deleteByUid = secure (client, uid, callback) -> selector = originId : client.connection.delegate._id machineUId : uid JWorkspace.remove selector, (err) -> callback err delete: secure (client, callback) -> { delegate } = client.connection unless delegate.getId().equals this.originId return callback new KodingError 'Access denied' @remove callback @update$ = secure (client, id, options, callback) -> selector = originId : client.connection.delegate._id _id : ObjectId id JWorkspace.one selector, (err, ws) -> return callback err if err return callback new KodingError 'Workspace not found.' unless ws ws.update options, callback @createDefault = secure (client, machineUId, callback) -> JMachine.one$ client, machineUId, (err, machine) => return callback err if err return callback 'Machine not found' unless machine { nickname } = client.connection.delegate.profile rootPath = '/' if machine.provider is 'managed' selector = { machineUId, slug: 'my-workspace' } @one selector, (err, workspace) => return callback err if err return callback null, workspace if workspace machine.fetchOwner (err, account) => return callback err if err { nickname } = account.profile data = name : 'My Workspace' isDefault : yes machineLabel : machine.label machineUId : machine.uid rootPath : rootPath ? "/home/#{nickname}" originId : account.getId() @create client, data, callback
173691
{ Module } = require 'jraphical' JMachine = require './computeproviders/machine' module.exports = class JWorkspace extends Module KodingError = require '../error' { slugify } = require '../traits/slugifiable' { signature, secure, ObjectId } = require 'bongo' @share() @set indexes : originId : 'sparse' slug : 'sparse' schema : name : String slug : String isDefault : type : Boolean default : no channelId : String machineUId : String machineLabel : String rootPath : String originId : ObjectId layout : Object sharedMethods : static : create : signature Object, Function deleteById : signature String, Function deleteByUid : signature String, Function update : signature String, Object, Function fetchByMachines : signature Function createDefault : signature String, Function instance : delete : signature Function sharedEvents : instance : [] @create$ = secure (client, data, callback) -> { delegate } = client.connection data.originId = delegate._id @create client, data, callback @create = secure (client, data, callback) -> { delegate } = client.connection data.originId ?= delegate._id nickname = delegate.profile.nickname data.slug = slugify data.name?.toLowerCase() { name, slug, machineUId, rootPath, originId, machineLabel } = data # we don't support saving layout for now, i will set it to empty object # to prevent storing any kind of data in it. -- acetz! data.layout = {} kallback = (name, slug) -> data.name = name data.slug = slug data.rootPath = "/home/#{nickname}/Workspaces/#{slug}" unless data.rootPath workspace = new JWorkspace data workspace.save (err) -> if err switch err.code when 11000 # duplicate key error callback() else callback err if err return message = accountId: delegate.socialApiId name: name groupName: slug require('./socialapi/requests').dispatchEvent 'social.workspace_created', message, (err) -> console.error '[dispatchEvent][workspace_created]', err if err uid = machineUId eventName = 'NewWorkspaceCreated' options = { nickname, workspace, uid, eventName } notifyUsers options, callback if data.isDefault then kallback data.name, data.slug else generateUniqueName { originId, name, machineUId }, (err, res) -> return callback err if err? { name, slug } = res kallback name, slug notifyUsers = (options, callback) -> { nickname, workspace, uid, eventName } = options JMachine.one { uid }, (err, machine) -> return callback err if err return callback new KodingError 'Machine not found.' unless machine users = machine.users.map (user) -> user.username if users.length { notifyByUsernames } = require './notify' notifyByUsernames users, eventName, workspace return callback null, workspace generateUniqueName = ({ originId, machineUId, name, index }, callback) -> slug = if index? then "#{name}-#{index}" else name slug = slugify slug JWorkspace.count { originId, slug, machineUId }, (err, count) -> return callback err if err? if count is 0 name = "#{name} #{index}" if index? callback null, { name, slug } else index ?= 0 index += 1 generateUniqueName { originId, machineUId, name, index }, callback @fetch = secure (client, query = {}, callback) -> query.originId = client.connection.delegate._id JWorkspace.some query, { limit: 30 }, callback @fetchByMachines$ = secure (client, callback) -> query = {} JMachine.some$ client, query, (err, machines) -> return callback err if err machineUIds = machines.map (machine) -> machine.uid JWorkspace.some { machineUId: { $in: machineUIds } }, {}, callback @deleteById = secure (client, id, callback) -> delegate = client.connection.delegate selector = originId : delegate._id _id : ObjectId id JWorkspace.one selector, (err, ws) -> return callback err if err? return callback new KodingError 'Workspace not found.' unless ws ws.remove (err) -> return callback err if err options = uid : ws.machineUId nickname : delegate.profile.nickname workspace: ws eventName: 'WorkspaceRemoved' group : client?.context?.group notifyUsers options, callback @deleteByUid = secure (client, uid, callback) -> selector = originId : client.connection.delegate._id machineUId : uid JWorkspace.remove selector, (err) -> callback err delete: secure (client, callback) -> { delegate } = client.connection unless delegate.getId().equals this.originId return callback new KodingError 'Access denied' @remove callback @update$ = secure (client, id, options, callback) -> selector = originId : client.connection.delegate._id _id : ObjectId id JWorkspace.one selector, (err, ws) -> return callback err if err return callback new KodingError 'Workspace not found.' unless ws ws.update options, callback @createDefault = secure (client, machineUId, callback) -> JMachine.one$ client, machineUId, (err, machine) => return callback err if err return callback 'Machine not found' unless machine { nickname } = client.connection.delegate.profile rootPath = '/' if machine.provider is 'managed' selector = { machineUId, slug: 'my-workspace' } @one selector, (err, workspace) => return callback err if err return callback null, workspace if workspace machine.fetchOwner (err, account) => return callback err if err { nickname } = account.profile data = name : '<NAME> Workspace' isDefault : yes machineLabel : machine.label machineUId : machine.uid rootPath : rootPath ? "/home/#{nickname}" originId : account.getId() @create client, data, callback
true
{ Module } = require 'jraphical' JMachine = require './computeproviders/machine' module.exports = class JWorkspace extends Module KodingError = require '../error' { slugify } = require '../traits/slugifiable' { signature, secure, ObjectId } = require 'bongo' @share() @set indexes : originId : 'sparse' slug : 'sparse' schema : name : String slug : String isDefault : type : Boolean default : no channelId : String machineUId : String machineLabel : String rootPath : String originId : ObjectId layout : Object sharedMethods : static : create : signature Object, Function deleteById : signature String, Function deleteByUid : signature String, Function update : signature String, Object, Function fetchByMachines : signature Function createDefault : signature String, Function instance : delete : signature Function sharedEvents : instance : [] @create$ = secure (client, data, callback) -> { delegate } = client.connection data.originId = delegate._id @create client, data, callback @create = secure (client, data, callback) -> { delegate } = client.connection data.originId ?= delegate._id nickname = delegate.profile.nickname data.slug = slugify data.name?.toLowerCase() { name, slug, machineUId, rootPath, originId, machineLabel } = data # we don't support saving layout for now, i will set it to empty object # to prevent storing any kind of data in it. -- acetz! data.layout = {} kallback = (name, slug) -> data.name = name data.slug = slug data.rootPath = "/home/#{nickname}/Workspaces/#{slug}" unless data.rootPath workspace = new JWorkspace data workspace.save (err) -> if err switch err.code when 11000 # duplicate key error callback() else callback err if err return message = accountId: delegate.socialApiId name: name groupName: slug require('./socialapi/requests').dispatchEvent 'social.workspace_created', message, (err) -> console.error '[dispatchEvent][workspace_created]', err if err uid = machineUId eventName = 'NewWorkspaceCreated' options = { nickname, workspace, uid, eventName } notifyUsers options, callback if data.isDefault then kallback data.name, data.slug else generateUniqueName { originId, name, machineUId }, (err, res) -> return callback err if err? { name, slug } = res kallback name, slug notifyUsers = (options, callback) -> { nickname, workspace, uid, eventName } = options JMachine.one { uid }, (err, machine) -> return callback err if err return callback new KodingError 'Machine not found.' unless machine users = machine.users.map (user) -> user.username if users.length { notifyByUsernames } = require './notify' notifyByUsernames users, eventName, workspace return callback null, workspace generateUniqueName = ({ originId, machineUId, name, index }, callback) -> slug = if index? then "#{name}-#{index}" else name slug = slugify slug JWorkspace.count { originId, slug, machineUId }, (err, count) -> return callback err if err? if count is 0 name = "#{name} #{index}" if index? callback null, { name, slug } else index ?= 0 index += 1 generateUniqueName { originId, machineUId, name, index }, callback @fetch = secure (client, query = {}, callback) -> query.originId = client.connection.delegate._id JWorkspace.some query, { limit: 30 }, callback @fetchByMachines$ = secure (client, callback) -> query = {} JMachine.some$ client, query, (err, machines) -> return callback err if err machineUIds = machines.map (machine) -> machine.uid JWorkspace.some { machineUId: { $in: machineUIds } }, {}, callback @deleteById = secure (client, id, callback) -> delegate = client.connection.delegate selector = originId : delegate._id _id : ObjectId id JWorkspace.one selector, (err, ws) -> return callback err if err? return callback new KodingError 'Workspace not found.' unless ws ws.remove (err) -> return callback err if err options = uid : ws.machineUId nickname : delegate.profile.nickname workspace: ws eventName: 'WorkspaceRemoved' group : client?.context?.group notifyUsers options, callback @deleteByUid = secure (client, uid, callback) -> selector = originId : client.connection.delegate._id machineUId : uid JWorkspace.remove selector, (err) -> callback err delete: secure (client, callback) -> { delegate } = client.connection unless delegate.getId().equals this.originId return callback new KodingError 'Access denied' @remove callback @update$ = secure (client, id, options, callback) -> selector = originId : client.connection.delegate._id _id : ObjectId id JWorkspace.one selector, (err, ws) -> return callback err if err return callback new KodingError 'Workspace not found.' unless ws ws.update options, callback @createDefault = secure (client, machineUId, callback) -> JMachine.one$ client, machineUId, (err, machine) => return callback err if err return callback 'Machine not found' unless machine { nickname } = client.connection.delegate.profile rootPath = '/' if machine.provider is 'managed' selector = { machineUId, slug: 'my-workspace' } @one selector, (err, workspace) => return callback err if err return callback null, workspace if workspace machine.fetchOwner (err, account) => return callback err if err { nickname } = account.profile data = name : 'PI:NAME:<NAME>END_PI Workspace' isDefault : yes machineLabel : machine.label machineUId : machine.uid rootPath : rootPath ? "/home/#{nickname}" originId : account.getId() @create client, data, callback
[ { "context": "t drawing a link to itself!\n #Thanks past Brad I'm doing it now\n else if @tempLinks[0].", "end": 2291, "score": 0.9591364860534668, "start": 2287, "tag": "NAME", "value": "Brad" } ]
app/assets/javascripts/visualisation/D3/links.js.coffee
CiscoSystems/curvature
16
class D3.Links constructor: (@graph) -> @links = [] @tempLinks = [] # Add the node passed to the tempLinks array # This function works out if it can create the new link # or it is connecting multiple nodes to a single node # # @param d [Object] The data object of the node to be linked to/from # newTemporaryLink: (d) -> exists = false sameType = true if not (d.data instanceof(Nodes.Container)) # get object type of first temporary link if @tempLinks.length > 0 firstType = Nodes.Server if @tempLinks[0].source.data instanceof(Nodes.Server) firstType = Nodes.Network if @tempLinks[0].source.data instanceof(Nodes.Network) firstType = Nodes.Router if @tempLinks[0].source.data instanceof(Nodes.Router) firstType = Nodes.ExternalNetwork if @tempLinks[0].source.data instanceof(Nodes.ExternalNetwork) firstType = Nodes.Volume if @tempLinks[0].source.data instanceof(Nodes.Volume) #firstType = Nodes.Container if @tempLinks[0].source.data instanceof(Nodes.Container) sameType = d.data instanceof firstType for l in @tempLinks exists = true if l.source is d if exists if @tempLinks[0].source isnt d @tempLinks.push {source: d} else @tempLinks.splice(0,@tempLinks.length) @graph.vis.selectAll("line.templink").data(@tempLinks).exit().remove() else if sameType is true @tempLinks.push {source: d} else # Check for connection from server to router if (firstType is Nodes.Server and d.data instanceof(Nodes.Router)) or (firstType is Nodes.Router and d.data instanceof(Nodes.Server)) @tempLinks.splice(0,@tempLinks.length) @graph.vis.selectAll("line.templink").data(@tempLinks).exit().remove() # Check for connection from network to exnet if (firstType is Nodes.Network and d.data instanceof(Nodes.ExternalNetwork)) or (firstType is Nodes.ExternalNetwork and d.data instanceof(Nodes.Network)) @tempLinks.splice(0,@tempLinks.length) @graph.vis.selectAll("line.templink").data(@tempLinks).exit().remove() #Need to check it isn't drawing a link to itself! #Thanks past Brad I'm doing it now else if @tempLinks[0].source.data isnt d.data # convert temporary links to perminant links for l in @tempLinks this.newLink(l.source.data,d.data,'undeployed') if @graph.tools.currentToolLocked @tempLinks.splice(0,@tempLinks.length) @graph.vis.selectAll("line.templink").data(@tempLinks).exit().remove() else @graph.tools.resetTools() else if @graph.tools.currentToolLocked @tempLinks.splice(0,@tempLinks.length) @graph.vis.selectAll("line.templink").data(@tempLinks).exit().remove() else @graph.tools.resetTools() # Draw the temporary links to the screen # drawTemporaryLinks: () -> # Temporary links between nodes used just to visualised what is being connected temporaryLine = @graph.vis.selectAll("line.templink").data(@tempLinks) if @graph.convexHulls(@graph.nodes.nodes).length > 0 temporaryLine.enter().insert("svg:line","path.hulls") .attr("class", "templink") .attr("x1", (d) -> d.source.x) .attr("y1", (d) -> d.source.y) .attr("x2", () => @graph.mouse.x) .attr("y2", () => @graph.mouse.y) .style("stroke", "blue") else temporaryLine.enter().insert("svg:line","g.node") .attr("class", "templink") .attr("x1", (d) -> d.source.x) .attr("y1", (d) -> d.source.y) .attr("x2", () => @graph.mouse.x) .attr("y2", () => @graph.mouse.y) .style("stroke", "blue") @graph.force.start() # Add new link to the links array and draw it # # @param source [Node] The source of the link # @param target [Node] The target of the link # @param deployStatus [String] The deploy status of the new link # newLink: (source, target, deployStatus) -> #Get d3 objects for source and target #Setting s & t to node when getting info from openstack for d in @graph.nodes.nodes s = d if d.data is source t = d if d.data is target if s? and t? #Check to see if there is already a link exists = false for l in @links exists = true if (l.source == s or l.source == t) and (l.target == t or l.target == s) unless exists # Code to make a server appear as if it is part of a network if s.data instanceof Nodes.Server and t.data instanceof Nodes.Network and !t.data.inContainerAsEndpoint?# and !(@graph instanceof D3.ContainerVisualisation) if s.data.networks if s.data.networks.indexOf(t.data) is -1 s.data.networks.push t.data else s.data.networks = [] s.data.networks.push t.data else if s.data instanceof Nodes.Network and t.data instanceof Nodes.Server and !s.data.inContainerAsEndpoint?# and !(@graph instanceof D3.ContainerVisualisation) if t.data.networks t.data.networks.push s.data else t.data.networks = [] t.data.networks.push s.data #Routers if s.data instanceof Nodes.Router and t.data instanceof Nodes.Network and !t.data.inContainerAsEndpoint? if s.data.networks if s.data.networks.indexOf(t.data) is -1 s.data.networks.push t.data else s.data.networks = [] s.data.networks.push t.data else if s.data instanceof Nodes.Network and t.data instanceof Nodes.Router and !s.data.inContainerAsEndpoint? if t.data.networks t.data.networks.push s.data else t.data.networks = [] t.data.networks.push s.data # If no connection between the two exists create one @links.push({source: s, target:t, deployStatus:deployStatus}) # drawing the links between nodes line = @graph.vis.selectAll("line.link").data(@links) line.enter().insert("svg:line", "g.node") .attr("class", "link") .attr("x1", (d) -> d.source.x) .attr("y1", (d) -> d.source.y) .attr("x2", (d) -> d.target.x) .attr("y2", (d) -> d.target.y) .style("stroke", (d) -> switch d.deployStatus when "deployed" then "black" when "undeployed" then "blue" ) # Remove a single link # # @param link [Object] The link object of the link to be removed # removeLink: (link) -> index = -1 for l, i in @links if l is link index = i break @links.splice(index,1) if index != -1 @graph.vis.selectAll("line.link").data(@links).exit().remove() linkActionFired: (obj) -> d3Links = d3.selectAll('line.link') # Get all of the svg nodes d3Links.each (d,i) -> link = d # find the correct node if link is obj #determine what type of node this is if link.deployStatus is 'deployed' then d3Links[0][i].style.stroke = 'black'
97823
class D3.Links constructor: (@graph) -> @links = [] @tempLinks = [] # Add the node passed to the tempLinks array # This function works out if it can create the new link # or it is connecting multiple nodes to a single node # # @param d [Object] The data object of the node to be linked to/from # newTemporaryLink: (d) -> exists = false sameType = true if not (d.data instanceof(Nodes.Container)) # get object type of first temporary link if @tempLinks.length > 0 firstType = Nodes.Server if @tempLinks[0].source.data instanceof(Nodes.Server) firstType = Nodes.Network if @tempLinks[0].source.data instanceof(Nodes.Network) firstType = Nodes.Router if @tempLinks[0].source.data instanceof(Nodes.Router) firstType = Nodes.ExternalNetwork if @tempLinks[0].source.data instanceof(Nodes.ExternalNetwork) firstType = Nodes.Volume if @tempLinks[0].source.data instanceof(Nodes.Volume) #firstType = Nodes.Container if @tempLinks[0].source.data instanceof(Nodes.Container) sameType = d.data instanceof firstType for l in @tempLinks exists = true if l.source is d if exists if @tempLinks[0].source isnt d @tempLinks.push {source: d} else @tempLinks.splice(0,@tempLinks.length) @graph.vis.selectAll("line.templink").data(@tempLinks).exit().remove() else if sameType is true @tempLinks.push {source: d} else # Check for connection from server to router if (firstType is Nodes.Server and d.data instanceof(Nodes.Router)) or (firstType is Nodes.Router and d.data instanceof(Nodes.Server)) @tempLinks.splice(0,@tempLinks.length) @graph.vis.selectAll("line.templink").data(@tempLinks).exit().remove() # Check for connection from network to exnet if (firstType is Nodes.Network and d.data instanceof(Nodes.ExternalNetwork)) or (firstType is Nodes.ExternalNetwork and d.data instanceof(Nodes.Network)) @tempLinks.splice(0,@tempLinks.length) @graph.vis.selectAll("line.templink").data(@tempLinks).exit().remove() #Need to check it isn't drawing a link to itself! #Thanks past <NAME> I'm doing it now else if @tempLinks[0].source.data isnt d.data # convert temporary links to perminant links for l in @tempLinks this.newLink(l.source.data,d.data,'undeployed') if @graph.tools.currentToolLocked @tempLinks.splice(0,@tempLinks.length) @graph.vis.selectAll("line.templink").data(@tempLinks).exit().remove() else @graph.tools.resetTools() else if @graph.tools.currentToolLocked @tempLinks.splice(0,@tempLinks.length) @graph.vis.selectAll("line.templink").data(@tempLinks).exit().remove() else @graph.tools.resetTools() # Draw the temporary links to the screen # drawTemporaryLinks: () -> # Temporary links between nodes used just to visualised what is being connected temporaryLine = @graph.vis.selectAll("line.templink").data(@tempLinks) if @graph.convexHulls(@graph.nodes.nodes).length > 0 temporaryLine.enter().insert("svg:line","path.hulls") .attr("class", "templink") .attr("x1", (d) -> d.source.x) .attr("y1", (d) -> d.source.y) .attr("x2", () => @graph.mouse.x) .attr("y2", () => @graph.mouse.y) .style("stroke", "blue") else temporaryLine.enter().insert("svg:line","g.node") .attr("class", "templink") .attr("x1", (d) -> d.source.x) .attr("y1", (d) -> d.source.y) .attr("x2", () => @graph.mouse.x) .attr("y2", () => @graph.mouse.y) .style("stroke", "blue") @graph.force.start() # Add new link to the links array and draw it # # @param source [Node] The source of the link # @param target [Node] The target of the link # @param deployStatus [String] The deploy status of the new link # newLink: (source, target, deployStatus) -> #Get d3 objects for source and target #Setting s & t to node when getting info from openstack for d in @graph.nodes.nodes s = d if d.data is source t = d if d.data is target if s? and t? #Check to see if there is already a link exists = false for l in @links exists = true if (l.source == s or l.source == t) and (l.target == t or l.target == s) unless exists # Code to make a server appear as if it is part of a network if s.data instanceof Nodes.Server and t.data instanceof Nodes.Network and !t.data.inContainerAsEndpoint?# and !(@graph instanceof D3.ContainerVisualisation) if s.data.networks if s.data.networks.indexOf(t.data) is -1 s.data.networks.push t.data else s.data.networks = [] s.data.networks.push t.data else if s.data instanceof Nodes.Network and t.data instanceof Nodes.Server and !s.data.inContainerAsEndpoint?# and !(@graph instanceof D3.ContainerVisualisation) if t.data.networks t.data.networks.push s.data else t.data.networks = [] t.data.networks.push s.data #Routers if s.data instanceof Nodes.Router and t.data instanceof Nodes.Network and !t.data.inContainerAsEndpoint? if s.data.networks if s.data.networks.indexOf(t.data) is -1 s.data.networks.push t.data else s.data.networks = [] s.data.networks.push t.data else if s.data instanceof Nodes.Network and t.data instanceof Nodes.Router and !s.data.inContainerAsEndpoint? if t.data.networks t.data.networks.push s.data else t.data.networks = [] t.data.networks.push s.data # If no connection between the two exists create one @links.push({source: s, target:t, deployStatus:deployStatus}) # drawing the links between nodes line = @graph.vis.selectAll("line.link").data(@links) line.enter().insert("svg:line", "g.node") .attr("class", "link") .attr("x1", (d) -> d.source.x) .attr("y1", (d) -> d.source.y) .attr("x2", (d) -> d.target.x) .attr("y2", (d) -> d.target.y) .style("stroke", (d) -> switch d.deployStatus when "deployed" then "black" when "undeployed" then "blue" ) # Remove a single link # # @param link [Object] The link object of the link to be removed # removeLink: (link) -> index = -1 for l, i in @links if l is link index = i break @links.splice(index,1) if index != -1 @graph.vis.selectAll("line.link").data(@links).exit().remove() linkActionFired: (obj) -> d3Links = d3.selectAll('line.link') # Get all of the svg nodes d3Links.each (d,i) -> link = d # find the correct node if link is obj #determine what type of node this is if link.deployStatus is 'deployed' then d3Links[0][i].style.stroke = 'black'
true
class D3.Links constructor: (@graph) -> @links = [] @tempLinks = [] # Add the node passed to the tempLinks array # This function works out if it can create the new link # or it is connecting multiple nodes to a single node # # @param d [Object] The data object of the node to be linked to/from # newTemporaryLink: (d) -> exists = false sameType = true if not (d.data instanceof(Nodes.Container)) # get object type of first temporary link if @tempLinks.length > 0 firstType = Nodes.Server if @tempLinks[0].source.data instanceof(Nodes.Server) firstType = Nodes.Network if @tempLinks[0].source.data instanceof(Nodes.Network) firstType = Nodes.Router if @tempLinks[0].source.data instanceof(Nodes.Router) firstType = Nodes.ExternalNetwork if @tempLinks[0].source.data instanceof(Nodes.ExternalNetwork) firstType = Nodes.Volume if @tempLinks[0].source.data instanceof(Nodes.Volume) #firstType = Nodes.Container if @tempLinks[0].source.data instanceof(Nodes.Container) sameType = d.data instanceof firstType for l in @tempLinks exists = true if l.source is d if exists if @tempLinks[0].source isnt d @tempLinks.push {source: d} else @tempLinks.splice(0,@tempLinks.length) @graph.vis.selectAll("line.templink").data(@tempLinks).exit().remove() else if sameType is true @tempLinks.push {source: d} else # Check for connection from server to router if (firstType is Nodes.Server and d.data instanceof(Nodes.Router)) or (firstType is Nodes.Router and d.data instanceof(Nodes.Server)) @tempLinks.splice(0,@tempLinks.length) @graph.vis.selectAll("line.templink").data(@tempLinks).exit().remove() # Check for connection from network to exnet if (firstType is Nodes.Network and d.data instanceof(Nodes.ExternalNetwork)) or (firstType is Nodes.ExternalNetwork and d.data instanceof(Nodes.Network)) @tempLinks.splice(0,@tempLinks.length) @graph.vis.selectAll("line.templink").data(@tempLinks).exit().remove() #Need to check it isn't drawing a link to itself! #Thanks past PI:NAME:<NAME>END_PI I'm doing it now else if @tempLinks[0].source.data isnt d.data # convert temporary links to perminant links for l in @tempLinks this.newLink(l.source.data,d.data,'undeployed') if @graph.tools.currentToolLocked @tempLinks.splice(0,@tempLinks.length) @graph.vis.selectAll("line.templink").data(@tempLinks).exit().remove() else @graph.tools.resetTools() else if @graph.tools.currentToolLocked @tempLinks.splice(0,@tempLinks.length) @graph.vis.selectAll("line.templink").data(@tempLinks).exit().remove() else @graph.tools.resetTools() # Draw the temporary links to the screen # drawTemporaryLinks: () -> # Temporary links between nodes used just to visualised what is being connected temporaryLine = @graph.vis.selectAll("line.templink").data(@tempLinks) if @graph.convexHulls(@graph.nodes.nodes).length > 0 temporaryLine.enter().insert("svg:line","path.hulls") .attr("class", "templink") .attr("x1", (d) -> d.source.x) .attr("y1", (d) -> d.source.y) .attr("x2", () => @graph.mouse.x) .attr("y2", () => @graph.mouse.y) .style("stroke", "blue") else temporaryLine.enter().insert("svg:line","g.node") .attr("class", "templink") .attr("x1", (d) -> d.source.x) .attr("y1", (d) -> d.source.y) .attr("x2", () => @graph.mouse.x) .attr("y2", () => @graph.mouse.y) .style("stroke", "blue") @graph.force.start() # Add new link to the links array and draw it # # @param source [Node] The source of the link # @param target [Node] The target of the link # @param deployStatus [String] The deploy status of the new link # newLink: (source, target, deployStatus) -> #Get d3 objects for source and target #Setting s & t to node when getting info from openstack for d in @graph.nodes.nodes s = d if d.data is source t = d if d.data is target if s? and t? #Check to see if there is already a link exists = false for l in @links exists = true if (l.source == s or l.source == t) and (l.target == t or l.target == s) unless exists # Code to make a server appear as if it is part of a network if s.data instanceof Nodes.Server and t.data instanceof Nodes.Network and !t.data.inContainerAsEndpoint?# and !(@graph instanceof D3.ContainerVisualisation) if s.data.networks if s.data.networks.indexOf(t.data) is -1 s.data.networks.push t.data else s.data.networks = [] s.data.networks.push t.data else if s.data instanceof Nodes.Network and t.data instanceof Nodes.Server and !s.data.inContainerAsEndpoint?# and !(@graph instanceof D3.ContainerVisualisation) if t.data.networks t.data.networks.push s.data else t.data.networks = [] t.data.networks.push s.data #Routers if s.data instanceof Nodes.Router and t.data instanceof Nodes.Network and !t.data.inContainerAsEndpoint? if s.data.networks if s.data.networks.indexOf(t.data) is -1 s.data.networks.push t.data else s.data.networks = [] s.data.networks.push t.data else if s.data instanceof Nodes.Network and t.data instanceof Nodes.Router and !s.data.inContainerAsEndpoint? if t.data.networks t.data.networks.push s.data else t.data.networks = [] t.data.networks.push s.data # If no connection between the two exists create one @links.push({source: s, target:t, deployStatus:deployStatus}) # drawing the links between nodes line = @graph.vis.selectAll("line.link").data(@links) line.enter().insert("svg:line", "g.node") .attr("class", "link") .attr("x1", (d) -> d.source.x) .attr("y1", (d) -> d.source.y) .attr("x2", (d) -> d.target.x) .attr("y2", (d) -> d.target.y) .style("stroke", (d) -> switch d.deployStatus when "deployed" then "black" when "undeployed" then "blue" ) # Remove a single link # # @param link [Object] The link object of the link to be removed # removeLink: (link) -> index = -1 for l, i in @links if l is link index = i break @links.splice(index,1) if index != -1 @graph.vis.selectAll("line.link").data(@links).exit().remove() linkActionFired: (obj) -> d3Links = d3.selectAll('line.link') # Get all of the svg nodes d3Links.each (d,i) -> link = d # find the correct node if link is obj #determine what type of node this is if link.deployStatus is 'deployed' then d3Links[0][i].style.stroke = 'black'
[ { "context": "Value))\n# dialog.positiveLocalizableKey = 'common.yes'\n# dialog.message = _.str.sprintf(t('commo", "end": 3584, "score": 0.9861640930175781, "start": 3574, "tag": "KEY", "value": "common.yes" } ]
app/src/controllers/wallet/send/wallet_send_index_dialog_view_controller.coffee
ipsBruno/ledger-wallet-chrome
173
class @WalletSendIndexDialogViewController extends ledger.common.DialogViewController view: amountInput: '#amount_input' currencyContainer: '#currency_container' sendButton: '#send_button' totalLabel: '#total_label' counterValueTotalLabel: '#countervalue_total_label' errorContainer: '#error_container' receiverInput: '#receiver_input' dataInput: '#data_input' dataRow: '#data_row' openScannerButton: '#open_scanner_button' feesSelect: '#fees_select' accountsSelect: '#accounts_select' colorSquare: '#color_square' maxButton: '#max_button' customFeesRow: '#custom_fees_row' warning: '#warning' link: '#link' blogLink = "" RefreshWalletInterval: 15 * 60 * 1000 # 15 Minutes onAfterRender: () -> super @view.dataRow.hide() l ledger.config.network ledger.api.WarningRestClient.instance.getWarning().then((json) => if json[ledger.config.network.ticker]? if json[ledger.config.network.ticker].message? @view.warning.css('visibility', 'visible') @view.warning.text(json[ledger.config.network.ticker].message) #@view.warning.show() if json[ledger.config.network.ticker].link? @blogLink = json[ledger.config.network.ticker].link @view.link.css('visibility', 'visible') #@view.link.show() ) @view.warning.show() # apply params if @params.amount? @view.amountInput.val @params.amount if @params.address? @view.receiverInput.val @params.address if @params.data? && @params.data.length > 0 @view.dataInput.val @params.data @view.dataRow.show() @view.customFeesRow.hide() # configure view @view.amountInput.amountInput(ledger.preferences.instance.getBitcoinUnitMaximumDecimalDigitsCount()) @view.errorContainer.hide() @_utxo = [] @_updateFeesSelect() @_updateAccountsSelect() @_updateCurrentAccount() @_updateTotalLabel() @_listenEvents() @_ensureDatabaseUpToDate() @_updateSendButton() @_updateTotalLabel = _.debounce(@_updateTotalLabel.bind(this), 500) openLink: -> open(@blogLink) onShow: -> super @view.amountInput.focus() onDismiss: -> super clearTimeout(@_scheduledRefresh) if @_scheduledRefresh? cancel: -> Api.callback_cancel 'send_payment', t('wallet.send.errors.cancelled') @dismiss() openCashConverter: -> window.open "https\://cashaddr.bitcoincash.org/" send: -> nextError = @_nextFormError() if nextError? @view.errorContainer.show() @view.errorContainer.html nextError else @view.errorContainer.hide() pushDialogBlock = (fees) => {utxo, fees} = @_computeAmount(ledger.Amount.fromSatoshi(fees).divide(1000)) data = if (@_dataValue().length > 0) then @_dataValue() else undefined dialog = new WalletSendPreparingDialogViewController amount: @_transactionAmount(), address: @_receiverBitcoinAddress(), fees: fees, account: @_selectedAccount(), utxo: utxo, data: data @getDialog().push dialog {amount, fees} = @_computeAmount() # check transactions fees # if +fees > ledger.preferences.fees.MaxValue # # warn if wrong # dialog = new CommonDialogsConfirmationDialogViewController() # dialog.showsCancelButton = yes # dialog.restrainsDialogWidth = no # dialog.negativeText = _.str.sprintf(t('wallet.send.index.no_use'), ledger.formatters.formatValue(ledger.preferences.fees.MaxValue)) # dialog.positiveLocalizableKey = 'common.yes' # dialog.message = _.str.sprintf(t('common.errors.fees_too_high'), ledger.formatters.formatValue(fees)) # dialog.once 'click:positive', => pushDialogBlock(@view.feesSelect.val()) # dialog.once 'click:negative', => pushDialogBlock(ledger.preferences.fees.MaxValue) # dialog.show() # else # # push next dialog pushDialogBlock(@view.feesSelect.val()) max: -> feePerByte = ledger.Amount.fromSatoshi(@view.feesSelect.val()).divide(1000) utxo = @_utxo total = ledger.Amount.fromSatoshi(0) for output in utxo total = total.add(output.get('value')) {fees} = @_computeAmount(feePerByte, total) amount = total.subtract(fees) if amount.lte(0) amount = ledger.Amount.fromSatoshi(0) @view.amountInput.val ledger.formatters.fromValue(amount, -1, off) _.defer => @_updateTotalLabel() @_updateExchangeValue() openScanner: -> dialog = new CommonDialogsQrcodeDialogViewController dialog.qrcodeCheckBlock = (data) => if Bitcoin.Address.validate data return true params = ledger.managers.schemes.bitcoin.parseURI data return params? dialog.once 'qrcode', (event, data) => if Bitcoin.Address.validate data params = {address: data} else params = ledger.managers.schemes.bitcoin.parseURI data if params?.amount? separator = ledger.number.getLocaleDecimalSeparator(ledger.preferences.instance.getLocale().replace('_', '-')) @view.amountInput.val(ledger.formatters.formatUnit(ledger.formatters.fromBtcToSatoshi(params.amount), ledger.preferences.instance.getBtcUnit()).replace(separator, '.')) @view.receiverInput.val params.address if params?.address? @_updateTotalLabel() dialog.show() openSensitive: -> window.open t 'application.sensitive_url' _listenEvents: -> @view.amountInput.on 'keyup', => _.defer => @_updateTotalLabel() @_updateExchangeValue() @view.openScannerButton.on 'click', => @openScanner() @view.customFeesRow.find('input').keypress (e) => if (e.which < 48 || 57 < e.which) e.preventDefault() @view.customFeesRow.find('input').on 'keyup', => _.defer => @view.feesSelect.find(":selected").attr('value', parseInt(@view.customFeesRow.find('input').val()) * 1000) @_updateTotalLabel() @view.feesSelect.on 'change', => if @view.feesSelect.find(":selected").text() is t("wallet.send.index.custom_fees") @view.customFeesRow.show() else @view.customFeesRow.hide() @_updateTotalLabel() @view.accountsSelect.on 'change', => @_updateCurrentAccount() @_updateTotalLabel() ledger.app.on 'wallet:operations:changed', => @_updateUtxo() @_updateTotalLabel() _updateCustomFees: -> _receiverBitcoinAddress: -> _.str.trim(@view.receiverInput.val()) _transactionAmount: -> ledger.formatters.fromValueToSatoshi(_.str.trim(@view.amountInput.val())) _dataValue: -> @view.dataInput.val() _isDataValid: -> s = @_dataValue() s.match(/^[a-f0-9]+$/i) != null && s.length % 2 == 0 && s.length <= 160 _nextFormError: -> # check amount if @_transactionAmount().length == 0 or not ledger.Amount.fromSatoshi(@_transactionAmount()).gt(0) return t 'common.errors.invalid_amount' else if ledger.config.network.ticker == 'abc' && @_receiverBitcoinAddress().startsWith("bitcoincash") return t 'abc.convert_address' else if not ledger.bitcoin.checkAddress @_receiverBitcoinAddress() || @_receiverBitcoinAddress().startsWith("z") return _.str.sprintf(t('common.errors.invalid_receiver_address'), ledger.config.network.display_name) else if @_dataValue().length > 0 && not @_isDataValid() return t 'common.errors.invalid_op_return_data' else if ledger.Amount.fromSatoshi(@view.feesSelect.val()).divide(1000).lt(0) && @view.customFeesRow.is(':visible') return t 'wallet.send.index.satoshi_per_byte_too_low' undefined _updateFeesSelect: -> @view.feesSelect.empty() for id in _.sortBy(_.keys(ledger.preferences.defaults.Coin.fees), (id) -> ledger.preferences.defaults.Coin.fees[id].value).reverse() fee = ledger.preferences.defaults.Coin.fees[id] text = t(fee.localization) node = $("<option></option>").text(text).attr('value', ledger.tasks.FeesComputationTask.instance.getFeesForLevelId(fee.value.toString()).value) if fee.value == ledger.preferences.instance.getMiningFee() node.attr 'selected', true @view.feesSelect.append node node = $("<option></option>").text(t("wallet.send.index.custom_fees")).attr('value', 0) @view.feesSelect.append node _updateTotalLabel: -> {amount, fees} = @_computeAmount() @view.totalLabel.text ledger.formatters.formatValue(amount) + ' ' + _.str.sprintf(t('wallet.send.index.transaction_fees_text'), ledger.formatters.formatValue(fees)) counterValueFee = ledger.converters.satoshiToCurrencyFormatted(fees) if parseInt(ledger.converters.satoshiToCurrency(fees, "USD")) >= 1 counterValueFee = '<span class="bold-invalid-text">' + counterValueFee + '</span>' @view.counterValueTotalLabel.html ledger.converters.satoshiToCurrencyFormatted(amount) + ' ' + _.str.sprintf(t('wallet.send.index.transaction_fees_text'), counterValueFee) _updateExchangeValue: -> value = ledger.Amount.fromSatoshi(@_transactionAmount()) if ledger.preferences.instance.isCurrencyActive() if value.toString() != @view.currencyContainer.attr('data-countervalue') @view.currencyContainer.removeAttr 'data-countervalue' @view.currencyContainer.empty() @view.currencyContainer.attr 'data-countervalue', value else @view.currencyContainer.hide() _updateAccountsSelect: -> accounts = Account.displayableAccounts() for account in accounts option = $('<option></option>').text(account.name + ' (' + ledger.formatters.formatValue(account.balance) + ')').val(account.index) option.attr('selected', true) if @params.account_id? and account.index is +@params.account_id @view.accountsSelect.append option @_updateUtxo() _updateCurrentAccount: -> @_updateUtxo() @_updateColorSquare() _updateUtxo: -> @_utxo = _(@_selectedAccount().getUtxo()).sortBy (o) -> o.get('transaction').get('confirmations') _updateColorSquare: -> @view.colorSquare.css('color', @_selectedAccount().get('color')) _selectedAccount: -> Account.find(index: parseInt(@view.accountsSelect.val())).first() _computeAmount: (feePerByte = ledger.Amount.fromSatoshi(@view.feesSelect.val()).divide(1000), desiredAmount = undefined) -> account = @_selectedAccount() desiredAmount ?= ledger.Amount.fromSatoshi(@_transactionAmount()) if desiredAmount.lte(0) return total: ledger.Amount.fromSatoshi(0), amount: ledger.Amount.fromSatoshi(0), fees: ledger.Amount.fromSatoshi(0), utxo: [], size: 0 utxo = @_utxo compute = (target) => selectedUtxo = [] total = ledger.Amount.fromSatoshi(0) for output in utxo when total.lt(target) selectedUtxo.push output total = total.add(output.get('value')) estimatedSize = ledger.bitcoin.estimateTransactionSize(selectedUtxo.length, 2).max # For now always consider we need a change output if (@_dataValue().length > 0) estimatedSize += @_dataValue().length / 2 + 4 + 1 if ledger.config.network.handleFeePerByte fees = feePerByte.multiply(estimatedSize) else fees = feePerByte.multiply(1000).multiply(Math.floor(estimatedSize / 1000) + (if estimatedSize % 1000 != 0 then 1 else 0)) if desiredAmount.gt(0) and total.lt(desiredAmount.add(fees)) and selectedUtxo.length is utxo.length # Not enough funds total: total, amount: desiredAmount.add(fees), fees: fees, utxo: selectedUtxo, size: estimatedSize else if desiredAmount.gt(0) and total.lt(desiredAmount.add(fees)) compute(desiredAmount.add(fees)) else total: total, amount: desiredAmount.add(fees), fees: fees, utxo: selectedUtxo, size: estimatedSize compute(desiredAmount) _ensureDatabaseUpToDate: -> task = ledger.tasks.WalletLayoutRecoveryTask.instance task.getLastSynchronizationStatus().then (status) => d = ledger.defer() if task.isRunning() or _.isEmpty(status) or status is 'failure' @_updateSendButton(yes) task.startIfNeccessary() task.once 'done', => d.resolve() task.once 'fatal_error', => d.reject(new Error("Fatal error during sync")) else d.resolve() d.promise .fail (er) => return unless @isShown() e er @_scheduledRefresh = _.delay(@_ensureDatabaseUpToDate.bind(this), 30 * 1000) throw er .then () => ledger.tasks.FeesComputationTask.instance.update().then => @_updateSendButton(no) @_updateFeesSelect() @_updateTotalLabel() return unless @isShown() return _updateSendButton: (syncing = ledger.tasks.WalletLayoutRecoveryTask.instance.isRunning()) -> if syncing @view.sendButton.addClass('disabled') @view.sendButton.text(t('wallet.send.index.syncing')) else @view.sendButton.removeClass('disabled') @view.sendButton.text(t('common.send'))
212575
class @WalletSendIndexDialogViewController extends ledger.common.DialogViewController view: amountInput: '#amount_input' currencyContainer: '#currency_container' sendButton: '#send_button' totalLabel: '#total_label' counterValueTotalLabel: '#countervalue_total_label' errorContainer: '#error_container' receiverInput: '#receiver_input' dataInput: '#data_input' dataRow: '#data_row' openScannerButton: '#open_scanner_button' feesSelect: '#fees_select' accountsSelect: '#accounts_select' colorSquare: '#color_square' maxButton: '#max_button' customFeesRow: '#custom_fees_row' warning: '#warning' link: '#link' blogLink = "" RefreshWalletInterval: 15 * 60 * 1000 # 15 Minutes onAfterRender: () -> super @view.dataRow.hide() l ledger.config.network ledger.api.WarningRestClient.instance.getWarning().then((json) => if json[ledger.config.network.ticker]? if json[ledger.config.network.ticker].message? @view.warning.css('visibility', 'visible') @view.warning.text(json[ledger.config.network.ticker].message) #@view.warning.show() if json[ledger.config.network.ticker].link? @blogLink = json[ledger.config.network.ticker].link @view.link.css('visibility', 'visible') #@view.link.show() ) @view.warning.show() # apply params if @params.amount? @view.amountInput.val @params.amount if @params.address? @view.receiverInput.val @params.address if @params.data? && @params.data.length > 0 @view.dataInput.val @params.data @view.dataRow.show() @view.customFeesRow.hide() # configure view @view.amountInput.amountInput(ledger.preferences.instance.getBitcoinUnitMaximumDecimalDigitsCount()) @view.errorContainer.hide() @_utxo = [] @_updateFeesSelect() @_updateAccountsSelect() @_updateCurrentAccount() @_updateTotalLabel() @_listenEvents() @_ensureDatabaseUpToDate() @_updateSendButton() @_updateTotalLabel = _.debounce(@_updateTotalLabel.bind(this), 500) openLink: -> open(@blogLink) onShow: -> super @view.amountInput.focus() onDismiss: -> super clearTimeout(@_scheduledRefresh) if @_scheduledRefresh? cancel: -> Api.callback_cancel 'send_payment', t('wallet.send.errors.cancelled') @dismiss() openCashConverter: -> window.open "https\://cashaddr.bitcoincash.org/" send: -> nextError = @_nextFormError() if nextError? @view.errorContainer.show() @view.errorContainer.html nextError else @view.errorContainer.hide() pushDialogBlock = (fees) => {utxo, fees} = @_computeAmount(ledger.Amount.fromSatoshi(fees).divide(1000)) data = if (@_dataValue().length > 0) then @_dataValue() else undefined dialog = new WalletSendPreparingDialogViewController amount: @_transactionAmount(), address: @_receiverBitcoinAddress(), fees: fees, account: @_selectedAccount(), utxo: utxo, data: data @getDialog().push dialog {amount, fees} = @_computeAmount() # check transactions fees # if +fees > ledger.preferences.fees.MaxValue # # warn if wrong # dialog = new CommonDialogsConfirmationDialogViewController() # dialog.showsCancelButton = yes # dialog.restrainsDialogWidth = no # dialog.negativeText = _.str.sprintf(t('wallet.send.index.no_use'), ledger.formatters.formatValue(ledger.preferences.fees.MaxValue)) # dialog.positiveLocalizableKey = '<KEY>' # dialog.message = _.str.sprintf(t('common.errors.fees_too_high'), ledger.formatters.formatValue(fees)) # dialog.once 'click:positive', => pushDialogBlock(@view.feesSelect.val()) # dialog.once 'click:negative', => pushDialogBlock(ledger.preferences.fees.MaxValue) # dialog.show() # else # # push next dialog pushDialogBlock(@view.feesSelect.val()) max: -> feePerByte = ledger.Amount.fromSatoshi(@view.feesSelect.val()).divide(1000) utxo = @_utxo total = ledger.Amount.fromSatoshi(0) for output in utxo total = total.add(output.get('value')) {fees} = @_computeAmount(feePerByte, total) amount = total.subtract(fees) if amount.lte(0) amount = ledger.Amount.fromSatoshi(0) @view.amountInput.val ledger.formatters.fromValue(amount, -1, off) _.defer => @_updateTotalLabel() @_updateExchangeValue() openScanner: -> dialog = new CommonDialogsQrcodeDialogViewController dialog.qrcodeCheckBlock = (data) => if Bitcoin.Address.validate data return true params = ledger.managers.schemes.bitcoin.parseURI data return params? dialog.once 'qrcode', (event, data) => if Bitcoin.Address.validate data params = {address: data} else params = ledger.managers.schemes.bitcoin.parseURI data if params?.amount? separator = ledger.number.getLocaleDecimalSeparator(ledger.preferences.instance.getLocale().replace('_', '-')) @view.amountInput.val(ledger.formatters.formatUnit(ledger.formatters.fromBtcToSatoshi(params.amount), ledger.preferences.instance.getBtcUnit()).replace(separator, '.')) @view.receiverInput.val params.address if params?.address? @_updateTotalLabel() dialog.show() openSensitive: -> window.open t 'application.sensitive_url' _listenEvents: -> @view.amountInput.on 'keyup', => _.defer => @_updateTotalLabel() @_updateExchangeValue() @view.openScannerButton.on 'click', => @openScanner() @view.customFeesRow.find('input').keypress (e) => if (e.which < 48 || 57 < e.which) e.preventDefault() @view.customFeesRow.find('input').on 'keyup', => _.defer => @view.feesSelect.find(":selected").attr('value', parseInt(@view.customFeesRow.find('input').val()) * 1000) @_updateTotalLabel() @view.feesSelect.on 'change', => if @view.feesSelect.find(":selected").text() is t("wallet.send.index.custom_fees") @view.customFeesRow.show() else @view.customFeesRow.hide() @_updateTotalLabel() @view.accountsSelect.on 'change', => @_updateCurrentAccount() @_updateTotalLabel() ledger.app.on 'wallet:operations:changed', => @_updateUtxo() @_updateTotalLabel() _updateCustomFees: -> _receiverBitcoinAddress: -> _.str.trim(@view.receiverInput.val()) _transactionAmount: -> ledger.formatters.fromValueToSatoshi(_.str.trim(@view.amountInput.val())) _dataValue: -> @view.dataInput.val() _isDataValid: -> s = @_dataValue() s.match(/^[a-f0-9]+$/i) != null && s.length % 2 == 0 && s.length <= 160 _nextFormError: -> # check amount if @_transactionAmount().length == 0 or not ledger.Amount.fromSatoshi(@_transactionAmount()).gt(0) return t 'common.errors.invalid_amount' else if ledger.config.network.ticker == 'abc' && @_receiverBitcoinAddress().startsWith("bitcoincash") return t 'abc.convert_address' else if not ledger.bitcoin.checkAddress @_receiverBitcoinAddress() || @_receiverBitcoinAddress().startsWith("z") return _.str.sprintf(t('common.errors.invalid_receiver_address'), ledger.config.network.display_name) else if @_dataValue().length > 0 && not @_isDataValid() return t 'common.errors.invalid_op_return_data' else if ledger.Amount.fromSatoshi(@view.feesSelect.val()).divide(1000).lt(0) && @view.customFeesRow.is(':visible') return t 'wallet.send.index.satoshi_per_byte_too_low' undefined _updateFeesSelect: -> @view.feesSelect.empty() for id in _.sortBy(_.keys(ledger.preferences.defaults.Coin.fees), (id) -> ledger.preferences.defaults.Coin.fees[id].value).reverse() fee = ledger.preferences.defaults.Coin.fees[id] text = t(fee.localization) node = $("<option></option>").text(text).attr('value', ledger.tasks.FeesComputationTask.instance.getFeesForLevelId(fee.value.toString()).value) if fee.value == ledger.preferences.instance.getMiningFee() node.attr 'selected', true @view.feesSelect.append node node = $("<option></option>").text(t("wallet.send.index.custom_fees")).attr('value', 0) @view.feesSelect.append node _updateTotalLabel: -> {amount, fees} = @_computeAmount() @view.totalLabel.text ledger.formatters.formatValue(amount) + ' ' + _.str.sprintf(t('wallet.send.index.transaction_fees_text'), ledger.formatters.formatValue(fees)) counterValueFee = ledger.converters.satoshiToCurrencyFormatted(fees) if parseInt(ledger.converters.satoshiToCurrency(fees, "USD")) >= 1 counterValueFee = '<span class="bold-invalid-text">' + counterValueFee + '</span>' @view.counterValueTotalLabel.html ledger.converters.satoshiToCurrencyFormatted(amount) + ' ' + _.str.sprintf(t('wallet.send.index.transaction_fees_text'), counterValueFee) _updateExchangeValue: -> value = ledger.Amount.fromSatoshi(@_transactionAmount()) if ledger.preferences.instance.isCurrencyActive() if value.toString() != @view.currencyContainer.attr('data-countervalue') @view.currencyContainer.removeAttr 'data-countervalue' @view.currencyContainer.empty() @view.currencyContainer.attr 'data-countervalue', value else @view.currencyContainer.hide() _updateAccountsSelect: -> accounts = Account.displayableAccounts() for account in accounts option = $('<option></option>').text(account.name + ' (' + ledger.formatters.formatValue(account.balance) + ')').val(account.index) option.attr('selected', true) if @params.account_id? and account.index is +@params.account_id @view.accountsSelect.append option @_updateUtxo() _updateCurrentAccount: -> @_updateUtxo() @_updateColorSquare() _updateUtxo: -> @_utxo = _(@_selectedAccount().getUtxo()).sortBy (o) -> o.get('transaction').get('confirmations') _updateColorSquare: -> @view.colorSquare.css('color', @_selectedAccount().get('color')) _selectedAccount: -> Account.find(index: parseInt(@view.accountsSelect.val())).first() _computeAmount: (feePerByte = ledger.Amount.fromSatoshi(@view.feesSelect.val()).divide(1000), desiredAmount = undefined) -> account = @_selectedAccount() desiredAmount ?= ledger.Amount.fromSatoshi(@_transactionAmount()) if desiredAmount.lte(0) return total: ledger.Amount.fromSatoshi(0), amount: ledger.Amount.fromSatoshi(0), fees: ledger.Amount.fromSatoshi(0), utxo: [], size: 0 utxo = @_utxo compute = (target) => selectedUtxo = [] total = ledger.Amount.fromSatoshi(0) for output in utxo when total.lt(target) selectedUtxo.push output total = total.add(output.get('value')) estimatedSize = ledger.bitcoin.estimateTransactionSize(selectedUtxo.length, 2).max # For now always consider we need a change output if (@_dataValue().length > 0) estimatedSize += @_dataValue().length / 2 + 4 + 1 if ledger.config.network.handleFeePerByte fees = feePerByte.multiply(estimatedSize) else fees = feePerByte.multiply(1000).multiply(Math.floor(estimatedSize / 1000) + (if estimatedSize % 1000 != 0 then 1 else 0)) if desiredAmount.gt(0) and total.lt(desiredAmount.add(fees)) and selectedUtxo.length is utxo.length # Not enough funds total: total, amount: desiredAmount.add(fees), fees: fees, utxo: selectedUtxo, size: estimatedSize else if desiredAmount.gt(0) and total.lt(desiredAmount.add(fees)) compute(desiredAmount.add(fees)) else total: total, amount: desiredAmount.add(fees), fees: fees, utxo: selectedUtxo, size: estimatedSize compute(desiredAmount) _ensureDatabaseUpToDate: -> task = ledger.tasks.WalletLayoutRecoveryTask.instance task.getLastSynchronizationStatus().then (status) => d = ledger.defer() if task.isRunning() or _.isEmpty(status) or status is 'failure' @_updateSendButton(yes) task.startIfNeccessary() task.once 'done', => d.resolve() task.once 'fatal_error', => d.reject(new Error("Fatal error during sync")) else d.resolve() d.promise .fail (er) => return unless @isShown() e er @_scheduledRefresh = _.delay(@_ensureDatabaseUpToDate.bind(this), 30 * 1000) throw er .then () => ledger.tasks.FeesComputationTask.instance.update().then => @_updateSendButton(no) @_updateFeesSelect() @_updateTotalLabel() return unless @isShown() return _updateSendButton: (syncing = ledger.tasks.WalletLayoutRecoveryTask.instance.isRunning()) -> if syncing @view.sendButton.addClass('disabled') @view.sendButton.text(t('wallet.send.index.syncing')) else @view.sendButton.removeClass('disabled') @view.sendButton.text(t('common.send'))
true
class @WalletSendIndexDialogViewController extends ledger.common.DialogViewController view: amountInput: '#amount_input' currencyContainer: '#currency_container' sendButton: '#send_button' totalLabel: '#total_label' counterValueTotalLabel: '#countervalue_total_label' errorContainer: '#error_container' receiverInput: '#receiver_input' dataInput: '#data_input' dataRow: '#data_row' openScannerButton: '#open_scanner_button' feesSelect: '#fees_select' accountsSelect: '#accounts_select' colorSquare: '#color_square' maxButton: '#max_button' customFeesRow: '#custom_fees_row' warning: '#warning' link: '#link' blogLink = "" RefreshWalletInterval: 15 * 60 * 1000 # 15 Minutes onAfterRender: () -> super @view.dataRow.hide() l ledger.config.network ledger.api.WarningRestClient.instance.getWarning().then((json) => if json[ledger.config.network.ticker]? if json[ledger.config.network.ticker].message? @view.warning.css('visibility', 'visible') @view.warning.text(json[ledger.config.network.ticker].message) #@view.warning.show() if json[ledger.config.network.ticker].link? @blogLink = json[ledger.config.network.ticker].link @view.link.css('visibility', 'visible') #@view.link.show() ) @view.warning.show() # apply params if @params.amount? @view.amountInput.val @params.amount if @params.address? @view.receiverInput.val @params.address if @params.data? && @params.data.length > 0 @view.dataInput.val @params.data @view.dataRow.show() @view.customFeesRow.hide() # configure view @view.amountInput.amountInput(ledger.preferences.instance.getBitcoinUnitMaximumDecimalDigitsCount()) @view.errorContainer.hide() @_utxo = [] @_updateFeesSelect() @_updateAccountsSelect() @_updateCurrentAccount() @_updateTotalLabel() @_listenEvents() @_ensureDatabaseUpToDate() @_updateSendButton() @_updateTotalLabel = _.debounce(@_updateTotalLabel.bind(this), 500) openLink: -> open(@blogLink) onShow: -> super @view.amountInput.focus() onDismiss: -> super clearTimeout(@_scheduledRefresh) if @_scheduledRefresh? cancel: -> Api.callback_cancel 'send_payment', t('wallet.send.errors.cancelled') @dismiss() openCashConverter: -> window.open "https\://cashaddr.bitcoincash.org/" send: -> nextError = @_nextFormError() if nextError? @view.errorContainer.show() @view.errorContainer.html nextError else @view.errorContainer.hide() pushDialogBlock = (fees) => {utxo, fees} = @_computeAmount(ledger.Amount.fromSatoshi(fees).divide(1000)) data = if (@_dataValue().length > 0) then @_dataValue() else undefined dialog = new WalletSendPreparingDialogViewController amount: @_transactionAmount(), address: @_receiverBitcoinAddress(), fees: fees, account: @_selectedAccount(), utxo: utxo, data: data @getDialog().push dialog {amount, fees} = @_computeAmount() # check transactions fees # if +fees > ledger.preferences.fees.MaxValue # # warn if wrong # dialog = new CommonDialogsConfirmationDialogViewController() # dialog.showsCancelButton = yes # dialog.restrainsDialogWidth = no # dialog.negativeText = _.str.sprintf(t('wallet.send.index.no_use'), ledger.formatters.formatValue(ledger.preferences.fees.MaxValue)) # dialog.positiveLocalizableKey = 'PI:KEY:<KEY>END_PI' # dialog.message = _.str.sprintf(t('common.errors.fees_too_high'), ledger.formatters.formatValue(fees)) # dialog.once 'click:positive', => pushDialogBlock(@view.feesSelect.val()) # dialog.once 'click:negative', => pushDialogBlock(ledger.preferences.fees.MaxValue) # dialog.show() # else # # push next dialog pushDialogBlock(@view.feesSelect.val()) max: -> feePerByte = ledger.Amount.fromSatoshi(@view.feesSelect.val()).divide(1000) utxo = @_utxo total = ledger.Amount.fromSatoshi(0) for output in utxo total = total.add(output.get('value')) {fees} = @_computeAmount(feePerByte, total) amount = total.subtract(fees) if amount.lte(0) amount = ledger.Amount.fromSatoshi(0) @view.amountInput.val ledger.formatters.fromValue(amount, -1, off) _.defer => @_updateTotalLabel() @_updateExchangeValue() openScanner: -> dialog = new CommonDialogsQrcodeDialogViewController dialog.qrcodeCheckBlock = (data) => if Bitcoin.Address.validate data return true params = ledger.managers.schemes.bitcoin.parseURI data return params? dialog.once 'qrcode', (event, data) => if Bitcoin.Address.validate data params = {address: data} else params = ledger.managers.schemes.bitcoin.parseURI data if params?.amount? separator = ledger.number.getLocaleDecimalSeparator(ledger.preferences.instance.getLocale().replace('_', '-')) @view.amountInput.val(ledger.formatters.formatUnit(ledger.formatters.fromBtcToSatoshi(params.amount), ledger.preferences.instance.getBtcUnit()).replace(separator, '.')) @view.receiverInput.val params.address if params?.address? @_updateTotalLabel() dialog.show() openSensitive: -> window.open t 'application.sensitive_url' _listenEvents: -> @view.amountInput.on 'keyup', => _.defer => @_updateTotalLabel() @_updateExchangeValue() @view.openScannerButton.on 'click', => @openScanner() @view.customFeesRow.find('input').keypress (e) => if (e.which < 48 || 57 < e.which) e.preventDefault() @view.customFeesRow.find('input').on 'keyup', => _.defer => @view.feesSelect.find(":selected").attr('value', parseInt(@view.customFeesRow.find('input').val()) * 1000) @_updateTotalLabel() @view.feesSelect.on 'change', => if @view.feesSelect.find(":selected").text() is t("wallet.send.index.custom_fees") @view.customFeesRow.show() else @view.customFeesRow.hide() @_updateTotalLabel() @view.accountsSelect.on 'change', => @_updateCurrentAccount() @_updateTotalLabel() ledger.app.on 'wallet:operations:changed', => @_updateUtxo() @_updateTotalLabel() _updateCustomFees: -> _receiverBitcoinAddress: -> _.str.trim(@view.receiverInput.val()) _transactionAmount: -> ledger.formatters.fromValueToSatoshi(_.str.trim(@view.amountInput.val())) _dataValue: -> @view.dataInput.val() _isDataValid: -> s = @_dataValue() s.match(/^[a-f0-9]+$/i) != null && s.length % 2 == 0 && s.length <= 160 _nextFormError: -> # check amount if @_transactionAmount().length == 0 or not ledger.Amount.fromSatoshi(@_transactionAmount()).gt(0) return t 'common.errors.invalid_amount' else if ledger.config.network.ticker == 'abc' && @_receiverBitcoinAddress().startsWith("bitcoincash") return t 'abc.convert_address' else if not ledger.bitcoin.checkAddress @_receiverBitcoinAddress() || @_receiverBitcoinAddress().startsWith("z") return _.str.sprintf(t('common.errors.invalid_receiver_address'), ledger.config.network.display_name) else if @_dataValue().length > 0 && not @_isDataValid() return t 'common.errors.invalid_op_return_data' else if ledger.Amount.fromSatoshi(@view.feesSelect.val()).divide(1000).lt(0) && @view.customFeesRow.is(':visible') return t 'wallet.send.index.satoshi_per_byte_too_low' undefined _updateFeesSelect: -> @view.feesSelect.empty() for id in _.sortBy(_.keys(ledger.preferences.defaults.Coin.fees), (id) -> ledger.preferences.defaults.Coin.fees[id].value).reverse() fee = ledger.preferences.defaults.Coin.fees[id] text = t(fee.localization) node = $("<option></option>").text(text).attr('value', ledger.tasks.FeesComputationTask.instance.getFeesForLevelId(fee.value.toString()).value) if fee.value == ledger.preferences.instance.getMiningFee() node.attr 'selected', true @view.feesSelect.append node node = $("<option></option>").text(t("wallet.send.index.custom_fees")).attr('value', 0) @view.feesSelect.append node _updateTotalLabel: -> {amount, fees} = @_computeAmount() @view.totalLabel.text ledger.formatters.formatValue(amount) + ' ' + _.str.sprintf(t('wallet.send.index.transaction_fees_text'), ledger.formatters.formatValue(fees)) counterValueFee = ledger.converters.satoshiToCurrencyFormatted(fees) if parseInt(ledger.converters.satoshiToCurrency(fees, "USD")) >= 1 counterValueFee = '<span class="bold-invalid-text">' + counterValueFee + '</span>' @view.counterValueTotalLabel.html ledger.converters.satoshiToCurrencyFormatted(amount) + ' ' + _.str.sprintf(t('wallet.send.index.transaction_fees_text'), counterValueFee) _updateExchangeValue: -> value = ledger.Amount.fromSatoshi(@_transactionAmount()) if ledger.preferences.instance.isCurrencyActive() if value.toString() != @view.currencyContainer.attr('data-countervalue') @view.currencyContainer.removeAttr 'data-countervalue' @view.currencyContainer.empty() @view.currencyContainer.attr 'data-countervalue', value else @view.currencyContainer.hide() _updateAccountsSelect: -> accounts = Account.displayableAccounts() for account in accounts option = $('<option></option>').text(account.name + ' (' + ledger.formatters.formatValue(account.balance) + ')').val(account.index) option.attr('selected', true) if @params.account_id? and account.index is +@params.account_id @view.accountsSelect.append option @_updateUtxo() _updateCurrentAccount: -> @_updateUtxo() @_updateColorSquare() _updateUtxo: -> @_utxo = _(@_selectedAccount().getUtxo()).sortBy (o) -> o.get('transaction').get('confirmations') _updateColorSquare: -> @view.colorSquare.css('color', @_selectedAccount().get('color')) _selectedAccount: -> Account.find(index: parseInt(@view.accountsSelect.val())).first() _computeAmount: (feePerByte = ledger.Amount.fromSatoshi(@view.feesSelect.val()).divide(1000), desiredAmount = undefined) -> account = @_selectedAccount() desiredAmount ?= ledger.Amount.fromSatoshi(@_transactionAmount()) if desiredAmount.lte(0) return total: ledger.Amount.fromSatoshi(0), amount: ledger.Amount.fromSatoshi(0), fees: ledger.Amount.fromSatoshi(0), utxo: [], size: 0 utxo = @_utxo compute = (target) => selectedUtxo = [] total = ledger.Amount.fromSatoshi(0) for output in utxo when total.lt(target) selectedUtxo.push output total = total.add(output.get('value')) estimatedSize = ledger.bitcoin.estimateTransactionSize(selectedUtxo.length, 2).max # For now always consider we need a change output if (@_dataValue().length > 0) estimatedSize += @_dataValue().length / 2 + 4 + 1 if ledger.config.network.handleFeePerByte fees = feePerByte.multiply(estimatedSize) else fees = feePerByte.multiply(1000).multiply(Math.floor(estimatedSize / 1000) + (if estimatedSize % 1000 != 0 then 1 else 0)) if desiredAmount.gt(0) and total.lt(desiredAmount.add(fees)) and selectedUtxo.length is utxo.length # Not enough funds total: total, amount: desiredAmount.add(fees), fees: fees, utxo: selectedUtxo, size: estimatedSize else if desiredAmount.gt(0) and total.lt(desiredAmount.add(fees)) compute(desiredAmount.add(fees)) else total: total, amount: desiredAmount.add(fees), fees: fees, utxo: selectedUtxo, size: estimatedSize compute(desiredAmount) _ensureDatabaseUpToDate: -> task = ledger.tasks.WalletLayoutRecoveryTask.instance task.getLastSynchronizationStatus().then (status) => d = ledger.defer() if task.isRunning() or _.isEmpty(status) or status is 'failure' @_updateSendButton(yes) task.startIfNeccessary() task.once 'done', => d.resolve() task.once 'fatal_error', => d.reject(new Error("Fatal error during sync")) else d.resolve() d.promise .fail (er) => return unless @isShown() e er @_scheduledRefresh = _.delay(@_ensureDatabaseUpToDate.bind(this), 30 * 1000) throw er .then () => ledger.tasks.FeesComputationTask.instance.update().then => @_updateSendButton(no) @_updateFeesSelect() @_updateTotalLabel() return unless @isShown() return _updateSendButton: (syncing = ledger.tasks.WalletLayoutRecoveryTask.instance.isRunning()) -> if syncing @view.sendButton.addClass('disabled') @view.sendButton.text(t('wallet.send.index.syncing')) else @view.sendButton.removeClass('disabled') @view.sendButton.text(t('common.send'))
[ { "context": "topology\n\n properties =\n listenOn: \"tcp://127.0.0.1:1221\",\n broadcastOn: \"tcp://127.0.0.1:2998\",", "end": 1947, "score": 0.9992615580558777, "start": 1938, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": "\"tcp://127.0.0.1:1221\",\n b...
test/hSubscribe.coffee
fredpottier/hubiquitus
2
# # * Copyright (c) Novedia Group 2012. # * # * This file is part of Hubiquitus # * # * 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. # * # * You should have received a copy of the MIT License along with Hubiquitus. # * If not, see <http://opensource.org/licenses/mit-license.php>. # should = require("should") config = require("./_config") _ = require "underscore" describe "hSubscribe", -> cmd = undefined hActor = undefined hActor2 = undefined hChannel = undefined hChannel2 = undefined status = require("../lib/codes").hResultStatus Actor = require "../lib/actors/hactor" Tracker = require ("../lib/actors/htracker") existingCHID = "urn:localhost:#{config.getUUID()}" before () -> topology = { actor: config.logins[0].urn, type: "hactor" } hActor = new Actor topology properties = listenOn: "tcp://127.0.0.1:1221", broadcastOn: "tcp://127.0.0.1:2998", subscribers: [config.logins[0].urn], db:{ host: "localhost", port: 27017, name: "test" }, collection: existingCHID.replace(/[-.]/g, "") hActor.createChild "hchannel", "inproc", {actor: existingCHID, type : "hActor", properties: properties}, (child) => hChannel = child after () -> hActor.h_tearDown() hActor = null it "should return hResult error MISSING_ATTR when actor is missing", (done) -> try hActor.subscribe undefined, "", (statuses, result) -> catch error should.exist error.message done() it "should return hResult error INVALID_ATTR with actor not a channel", (done) -> hActor.subscribe hActor.actor, "", (statuses, result) -> statuses.should.be.equal(status.NOT_AVAILABLE) result.should.match(/actor/) done() it "should return hResult error NOT_AUTHORIZED if not in subscribers list", (done) -> hChannel.properties.subscribers = [config.logins[2].urn] hActor.subscribe existingCHID, "", (statuses, result) -> statuses.should.be.equal(status.NOT_AUTHORIZED) result.should.be.a('string') hChannel.properties.subscribers = [config.logins[0].urn] done() it "should return hResult OK when correct", (done) -> hActor.subscribe existingCHID, "", (statuses, result) -> statuses.should.be.equal(status.OK) done() it "should return hResult error if already subscribed", (done) -> hActor.subscribe existingCHID, "", (statuses, result) -> statuses.should.be.equal(status.NOT_AUTHORIZED) result.should.be.a "string" done() it "should return hResult OK if correctly add a quickfilter", (done) -> find = false hActor.subscribe existingCHID, "quickfilter1", (statuses, result) -> statuses.should.be.equal(status.OK) result.should.be.equal("QuickFilter added") _.forEach hActor.inboundAdapters, (inbound) => if inbound.channel is existingCHID for filter in inbound.listQuickFilter if filter is "" find = true unless find done() describe "from topology", -> before () -> topology = { actor: config.logins[2].urn, type: "hactor" adapters:[ { type: "channel_in", channel:existingCHID } ] } hActor2 = new Actor topology hActor2.h_start() properties = listenOn: "tcp://127.0.0.1:2112", broadcastOn: "tcp://127.0.0.1:9289", subscribers: [config.logins[2].urn], db:{ name: "test", } collection: existingCHID.replace(/[-.]/g, "") hActor2.createChild "hchannel", "inproc", {actor: existingCHID, type : "hActor", properties: properties}, (child) => hChannel2 = child after () -> hActor2.h_tearDown() hActor2 = null it "should have channel in for existing channel", (done) -> hActor2.inboundAdapters.length.should.be.equal(0) setTimeout(=> hActor2.inboundAdapters.length.should.be.equal(1) done() , 600) describe "Channel Stop & Restart", -> hActor = undefined hChannel = undefined hTracker = undefined before () -> htrackerProps = { actor: "urn:localhost:tracker", type: "htracker", properties:{ channel: { actor: "urn:localhost:trackChannel", type: "hchannel", properties: { listenOn: "tcp://127.0.0.1", broadcastOn: "tcp://127.0.0.1", subscribers: [], db:{ host: "localhost", port: 27017, name: "admin" }, collection: "trackChannel" } } }, adapters: [ { type: "socket_in", url: "tcp://127.0.0.1:2997" } ] } hactorProps = { actor: config.logins[0].urn, type: "hactor", adapters: [ {type: "socket_in", url: "tcp://127.0.0.1:2992" }, {type: "channel_in", channel: "urn:localhost:channel"} ], trackers: [{ trackerId: "urn:localhost:tracker", trackerUrl: "tcp://127.0.1:2997", trackerChannel: "urn:localhost:trackChannel" }] } hchannelProps = { actor: "urn:localhost:channel", type: "hchannel", properties: { subscribers: [], db:{ host: "localhost", port: 27017, name: "admin" }, collection: "channel" }, trackers: [{ trackerId: "urn:localhost:tracker", trackerUrl: "tcp://127.0.1:2997", trackerChannel: "urn:localhost:trackChannel" }] } hTracker = new Tracker htrackerProps hTracker.h_start() hTracker.createChild "hchannel", "inproc", hchannelProps, (child) => hChannel = child hTracker.createChild "hactor", "inproc", hactorProps, (child) => hActor = child after () -> hTracker.h_tearDown() it "Channel should be restarted correctly", (done) -> @timeout 3500 setTimeout(=> hActor.subscriptions.should.include hChannel.actor hChannel.h_tearDown() setTimeout(=> hActor.subscriptions.length.should.equal 0 hChannel.h_start() setTimeout(=> hActor.subscriptions.should.include hChannel.actor done() ,1000) ,1000) ,1000)
101847
# # * Copyright (c) Novedia Group 2012. # * # * This file is part of Hubiquitus # * # * 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. # * # * You should have received a copy of the MIT License along with Hubiquitus. # * If not, see <http://opensource.org/licenses/mit-license.php>. # should = require("should") config = require("./_config") _ = require "underscore" describe "hSubscribe", -> cmd = undefined hActor = undefined hActor2 = undefined hChannel = undefined hChannel2 = undefined status = require("../lib/codes").hResultStatus Actor = require "../lib/actors/hactor" Tracker = require ("../lib/actors/htracker") existingCHID = "urn:localhost:#{config.getUUID()}" before () -> topology = { actor: config.logins[0].urn, type: "hactor" } hActor = new Actor topology properties = listenOn: "tcp://127.0.0.1:1221", broadcastOn: "tcp://127.0.0.1:2998", subscribers: [config.logins[0].urn], db:{ host: "localhost", port: 27017, name: "test" }, collection: existingCHID.replace(/[-.]/g, "") hActor.createChild "hchannel", "inproc", {actor: existingCHID, type : "hActor", properties: properties}, (child) => hChannel = child after () -> hActor.h_tearDown() hActor = null it "should return hResult error MISSING_ATTR when actor is missing", (done) -> try hActor.subscribe undefined, "", (statuses, result) -> catch error should.exist error.message done() it "should return hResult error INVALID_ATTR with actor not a channel", (done) -> hActor.subscribe hActor.actor, "", (statuses, result) -> statuses.should.be.equal(status.NOT_AVAILABLE) result.should.match(/actor/) done() it "should return hResult error NOT_AUTHORIZED if not in subscribers list", (done) -> hChannel.properties.subscribers = [config.logins[2].urn] hActor.subscribe existingCHID, "", (statuses, result) -> statuses.should.be.equal(status.NOT_AUTHORIZED) result.should.be.a('string') hChannel.properties.subscribers = [config.logins[0].urn] done() it "should return hResult OK when correct", (done) -> hActor.subscribe existingCHID, "", (statuses, result) -> statuses.should.be.equal(status.OK) done() it "should return hResult error if already subscribed", (done) -> hActor.subscribe existingCHID, "", (statuses, result) -> statuses.should.be.equal(status.NOT_AUTHORIZED) result.should.be.a "string" done() it "should return hResult OK if correctly add a quickfilter", (done) -> find = false hActor.subscribe existingCHID, "quickfilter1", (statuses, result) -> statuses.should.be.equal(status.OK) result.should.be.equal("QuickFilter added") _.forEach hActor.inboundAdapters, (inbound) => if inbound.channel is existingCHID for filter in inbound.listQuickFilter if filter is "" find = true unless find done() describe "from topology", -> before () -> topology = { actor: config.logins[2].urn, type: "hactor" adapters:[ { type: "channel_in", channel:existingCHID } ] } hActor2 = new Actor topology hActor2.h_start() properties = listenOn: "tcp://127.0.0.1:2112", broadcastOn: "tcp://127.0.0.1:9289", subscribers: [config.logins[2].urn], db:{ name: "test", } collection: existingCHID.replace(/[-.]/g, "") hActor2.createChild "hchannel", "inproc", {actor: existingCHID, type : "hActor", properties: properties}, (child) => hChannel2 = child after () -> hActor2.h_tearDown() hActor2 = null it "should have channel in for existing channel", (done) -> hActor2.inboundAdapters.length.should.be.equal(0) setTimeout(=> hActor2.inboundAdapters.length.should.be.equal(1) done() , 600) describe "Channel Stop & Restart", -> hActor = undefined hChannel = undefined hTracker = undefined before () -> htrackerProps = { actor: "urn:localhost:tracker", type: "htracker", properties:{ channel: { actor: "urn:localhost:trackChannel", type: "hchannel", properties: { listenOn: "tcp://127.0.0.1", broadcastOn: "tcp://127.0.0.1", subscribers: [], db:{ host: "localhost", port: 27017, name: "<NAME>" }, collection: "trackChannel" } } }, adapters: [ { type: "socket_in", url: "tcp://127.0.0.1:2997" } ] } hactorProps = { actor: config.logins[0].urn, type: "hactor", adapters: [ {type: "socket_in", url: "tcp://127.0.0.1:2992" }, {type: "channel_in", channel: "urn:localhost:channel"} ], trackers: [{ trackerId: "urn:localhost:tracker", trackerUrl: "tcp://127.0.1:2997", trackerChannel: "urn:localhost:trackChannel" }] } hchannelProps = { actor: "urn:localhost:channel", type: "hchannel", properties: { subscribers: [], db:{ host: "localhost", port: 27017, name: "admin" }, collection: "channel" }, trackers: [{ trackerId: "urn:localhost:tracker", trackerUrl: "tcp://127.0.1:2997", trackerChannel: "urn:localhost:trackChannel" }] } hTracker = new Tracker htrackerProps hTracker.h_start() hTracker.createChild "hchannel", "inproc", hchannelProps, (child) => hChannel = child hTracker.createChild "hactor", "inproc", hactorProps, (child) => hActor = child after () -> hTracker.h_tearDown() it "Channel should be restarted correctly", (done) -> @timeout 3500 setTimeout(=> hActor.subscriptions.should.include hChannel.actor hChannel.h_tearDown() setTimeout(=> hActor.subscriptions.length.should.equal 0 hChannel.h_start() setTimeout(=> hActor.subscriptions.should.include hChannel.actor done() ,1000) ,1000) ,1000)
true
# # * Copyright (c) Novedia Group 2012. # * # * This file is part of Hubiquitus # * # * 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. # * # * You should have received a copy of the MIT License along with Hubiquitus. # * If not, see <http://opensource.org/licenses/mit-license.php>. # should = require("should") config = require("./_config") _ = require "underscore" describe "hSubscribe", -> cmd = undefined hActor = undefined hActor2 = undefined hChannel = undefined hChannel2 = undefined status = require("../lib/codes").hResultStatus Actor = require "../lib/actors/hactor" Tracker = require ("../lib/actors/htracker") existingCHID = "urn:localhost:#{config.getUUID()}" before () -> topology = { actor: config.logins[0].urn, type: "hactor" } hActor = new Actor topology properties = listenOn: "tcp://127.0.0.1:1221", broadcastOn: "tcp://127.0.0.1:2998", subscribers: [config.logins[0].urn], db:{ host: "localhost", port: 27017, name: "test" }, collection: existingCHID.replace(/[-.]/g, "") hActor.createChild "hchannel", "inproc", {actor: existingCHID, type : "hActor", properties: properties}, (child) => hChannel = child after () -> hActor.h_tearDown() hActor = null it "should return hResult error MISSING_ATTR when actor is missing", (done) -> try hActor.subscribe undefined, "", (statuses, result) -> catch error should.exist error.message done() it "should return hResult error INVALID_ATTR with actor not a channel", (done) -> hActor.subscribe hActor.actor, "", (statuses, result) -> statuses.should.be.equal(status.NOT_AVAILABLE) result.should.match(/actor/) done() it "should return hResult error NOT_AUTHORIZED if not in subscribers list", (done) -> hChannel.properties.subscribers = [config.logins[2].urn] hActor.subscribe existingCHID, "", (statuses, result) -> statuses.should.be.equal(status.NOT_AUTHORIZED) result.should.be.a('string') hChannel.properties.subscribers = [config.logins[0].urn] done() it "should return hResult OK when correct", (done) -> hActor.subscribe existingCHID, "", (statuses, result) -> statuses.should.be.equal(status.OK) done() it "should return hResult error if already subscribed", (done) -> hActor.subscribe existingCHID, "", (statuses, result) -> statuses.should.be.equal(status.NOT_AUTHORIZED) result.should.be.a "string" done() it "should return hResult OK if correctly add a quickfilter", (done) -> find = false hActor.subscribe existingCHID, "quickfilter1", (statuses, result) -> statuses.should.be.equal(status.OK) result.should.be.equal("QuickFilter added") _.forEach hActor.inboundAdapters, (inbound) => if inbound.channel is existingCHID for filter in inbound.listQuickFilter if filter is "" find = true unless find done() describe "from topology", -> before () -> topology = { actor: config.logins[2].urn, type: "hactor" adapters:[ { type: "channel_in", channel:existingCHID } ] } hActor2 = new Actor topology hActor2.h_start() properties = listenOn: "tcp://127.0.0.1:2112", broadcastOn: "tcp://127.0.0.1:9289", subscribers: [config.logins[2].urn], db:{ name: "test", } collection: existingCHID.replace(/[-.]/g, "") hActor2.createChild "hchannel", "inproc", {actor: existingCHID, type : "hActor", properties: properties}, (child) => hChannel2 = child after () -> hActor2.h_tearDown() hActor2 = null it "should have channel in for existing channel", (done) -> hActor2.inboundAdapters.length.should.be.equal(0) setTimeout(=> hActor2.inboundAdapters.length.should.be.equal(1) done() , 600) describe "Channel Stop & Restart", -> hActor = undefined hChannel = undefined hTracker = undefined before () -> htrackerProps = { actor: "urn:localhost:tracker", type: "htracker", properties:{ channel: { actor: "urn:localhost:trackChannel", type: "hchannel", properties: { listenOn: "tcp://127.0.0.1", broadcastOn: "tcp://127.0.0.1", subscribers: [], db:{ host: "localhost", port: 27017, name: "PI:NAME:<NAME>END_PI" }, collection: "trackChannel" } } }, adapters: [ { type: "socket_in", url: "tcp://127.0.0.1:2997" } ] } hactorProps = { actor: config.logins[0].urn, type: "hactor", adapters: [ {type: "socket_in", url: "tcp://127.0.0.1:2992" }, {type: "channel_in", channel: "urn:localhost:channel"} ], trackers: [{ trackerId: "urn:localhost:tracker", trackerUrl: "tcp://127.0.1:2997", trackerChannel: "urn:localhost:trackChannel" }] } hchannelProps = { actor: "urn:localhost:channel", type: "hchannel", properties: { subscribers: [], db:{ host: "localhost", port: 27017, name: "admin" }, collection: "channel" }, trackers: [{ trackerId: "urn:localhost:tracker", trackerUrl: "tcp://127.0.1:2997", trackerChannel: "urn:localhost:trackChannel" }] } hTracker = new Tracker htrackerProps hTracker.h_start() hTracker.createChild "hchannel", "inproc", hchannelProps, (child) => hChannel = child hTracker.createChild "hactor", "inproc", hactorProps, (child) => hActor = child after () -> hTracker.h_tearDown() it "Channel should be restarted correctly", (done) -> @timeout 3500 setTimeout(=> hActor.subscriptions.should.include hChannel.actor hChannel.h_tearDown() setTimeout(=> hActor.subscriptions.length.should.equal 0 hChannel.h_start() setTimeout(=> hActor.subscriptions.should.include hChannel.actor done() ,1000) ,1000) ,1000)
[ { "context": "'saves properly', (done) ->\n user.save \"ok\", \"pwd\", (err) ->\n should.not.exist err \n done", "end": 144, "score": 0.7219075560569763, "start": 141, "tag": "PASSWORD", "value": "pwd" } ]
tests/user.coffee
charlesandre/TP1_NodeJS
1
should = require 'should' user = require '../src/user.coffee' describe 'user', () -> it 'saves properly', (done) -> user.save "ok", "pwd", (err) -> should.not.exist err done() it 'doesn\'t save because missing parameter', (done) -> user.save "only name", (err) -> should.exist err done() it 'get', (done) -> # do something done()
161817
should = require 'should' user = require '../src/user.coffee' describe 'user', () -> it 'saves properly', (done) -> user.save "ok", "<PASSWORD>", (err) -> should.not.exist err done() it 'doesn\'t save because missing parameter', (done) -> user.save "only name", (err) -> should.exist err done() it 'get', (done) -> # do something done()
true
should = require 'should' user = require '../src/user.coffee' describe 'user', () -> it 'saves properly', (done) -> user.save "ok", "PI:PASSWORD:<PASSWORD>END_PI", (err) -> should.not.exist err done() it 'doesn\'t save because missing parameter', (done) -> user.save "only name", (err) -> should.exist err done() it 'get', (done) -> # do something done()
[ { "context": "Need More Help?</h6>\" +\n \"<p><a href='mailto:rr@childrenscouncil.org'>Write an email</a><br/>\" +\n \"<a href='tel:4", "end": 4271, "score": 0.9999257326126099, "start": 4248, "tag": "EMAIL", "value": "rr@childrenscouncil.org" } ]
app/assets/javascripts/ccr.js.coffee
Exygy/Children-s-Council
1
angular.module 'CCR', [ 'angularjs-dropdown-multiselect', 'angularMoment', 'checklist-model', 'Devise', 'mm.foundation', 'ngAnimate', 'ngAria', 'ngCookies', 'ngMap', 'ng-token-auth-custom', 'ngSanitize', 'templates', 'truncate', 'ui.select', 'ui.slider', 'ui.router', ] .constant '_', window._ .constant 'deepFilter', window.deepFilter .constant 'CC_COOKIE', 'cc_api_key' .config [ '$locationProvider', '$stateProvider', '$urlRouterProvider', '$urlServiceProvider', ($locationProvider, $stateProvider, $urlRouterProvider, $urlServiceProvider) -> $locationProvider.html5Mode(true) # Allow optional trailing slashes $urlServiceProvider.config.strictMode(false) $stateProvider .state('search', { url: '/?searchType', component: 'search', onEnter: showSidebar, resolve: { searchType: ['$stateParams', ($stateParams) -> return $stateParams.searchType ] } }) .state('results', { url: '/providers', component: 'results', onEnter: hideSidebar, }) .state('provider', { url: '/providers/:id', component: 'provider', onEnter: hideSidebar, resolve: { id: ['$stateParams', ($stateParams) -> return $stateParams.id; ] } }) .state('compare', { url: '/compare', component: 'compare', onEnter: hideSidebar, }) .state('reset_password', { url: '/reset_password/:token', component: 'search', onEnter: showSidebar, resolve: { token: ['$stateParams', ($stateParams) -> return $stateParams.token; ] } }) .state('account_info', { url: '/account/info/', component: 'account', onEnter: hideSidebar resolve: { security: ['$q', '$auth', ($q, $auth) -> if(!$auth.retrieveData('auth_headers')) return $q.reject("Not Authorized") ] } }) .state('account_favorites', { url: '/account/favorites/', component: 'favorites', onEnter: hideSidebar resolve: { security: ['$q', '$auth', ($q, $auth) -> if(!$auth.retrieveData('auth_headers')) return $q.reject("Not Authorized") ] } }) $urlRouterProvider.otherwise('/') ] .config ['$httpProvider', ($httpProvider) -> # HTTP Access Control https://en.wikipedia.org/wiki/Cross-origin_resource_sharing $httpProvider.defaults.useXDomain = true delete $httpProvider.defaults.headers.common['X-Requested-With'] $httpProvider.defaults.headers.common['Accept'] = 'application/json' $httpProvider.defaults.headers.common['Content-Type'] = 'application/json' $httpProvider.interceptors.push('APIInterceptor') ] .config ['$authProvider', ($authProvider) -> $authProvider.configure({ apiUrl: CCR_ENV['RAILS_API_URL'] + '/api' }) ] .run ['$rootScope', '$state', '$transitions', ($rootScope, $state, $transitions) -> $transitions.onError {}, ($transition$) -> if $transition$._error.type != 5 $state.go("search") $rootScope.state_loading = false $rootScope.$on '$stateChangeStart', (event) -> $rootScope.state_loading = true # state_loading set to false when $viewContentLoaded is triggered within each state controller ] hideSidebar = () -> $(document.getElementById('main')).addClass 'expanded' $(document.getElementById('sidebar')).addClass 'hide' $(document.getElementById('content')).addClass 'providers' showSidebar = () -> $(document.getElementById('main')).removeClass 'expanded' $(document.getElementById('sidebar')).removeClass 'hide' $(document.getElementById('content')).removeClass 'providers' if !document.getElementById('need-help') $(document.getElementById('sidebar')).append("<div id='need-help' class='panel ccr-scope margin-top-2'>" + "<h6>Need More Help?</h6>" + "<p><a href='mailto:rr@childrenscouncil.org'>Write an email</a><br/>" + "<a href='tel:415-343-3300'>Call 415-343-3300</a></p>" + "<p class='small margin-top-1'>Counselors available<br/>Mon–Thu 8:30am– 4pm<br/>Fri 8:30am–noon</p></div>")
214183
angular.module 'CCR', [ 'angularjs-dropdown-multiselect', 'angularMoment', 'checklist-model', 'Devise', 'mm.foundation', 'ngAnimate', 'ngAria', 'ngCookies', 'ngMap', 'ng-token-auth-custom', 'ngSanitize', 'templates', 'truncate', 'ui.select', 'ui.slider', 'ui.router', ] .constant '_', window._ .constant 'deepFilter', window.deepFilter .constant 'CC_COOKIE', 'cc_api_key' .config [ '$locationProvider', '$stateProvider', '$urlRouterProvider', '$urlServiceProvider', ($locationProvider, $stateProvider, $urlRouterProvider, $urlServiceProvider) -> $locationProvider.html5Mode(true) # Allow optional trailing slashes $urlServiceProvider.config.strictMode(false) $stateProvider .state('search', { url: '/?searchType', component: 'search', onEnter: showSidebar, resolve: { searchType: ['$stateParams', ($stateParams) -> return $stateParams.searchType ] } }) .state('results', { url: '/providers', component: 'results', onEnter: hideSidebar, }) .state('provider', { url: '/providers/:id', component: 'provider', onEnter: hideSidebar, resolve: { id: ['$stateParams', ($stateParams) -> return $stateParams.id; ] } }) .state('compare', { url: '/compare', component: 'compare', onEnter: hideSidebar, }) .state('reset_password', { url: '/reset_password/:token', component: 'search', onEnter: showSidebar, resolve: { token: ['$stateParams', ($stateParams) -> return $stateParams.token; ] } }) .state('account_info', { url: '/account/info/', component: 'account', onEnter: hideSidebar resolve: { security: ['$q', '$auth', ($q, $auth) -> if(!$auth.retrieveData('auth_headers')) return $q.reject("Not Authorized") ] } }) .state('account_favorites', { url: '/account/favorites/', component: 'favorites', onEnter: hideSidebar resolve: { security: ['$q', '$auth', ($q, $auth) -> if(!$auth.retrieveData('auth_headers')) return $q.reject("Not Authorized") ] } }) $urlRouterProvider.otherwise('/') ] .config ['$httpProvider', ($httpProvider) -> # HTTP Access Control https://en.wikipedia.org/wiki/Cross-origin_resource_sharing $httpProvider.defaults.useXDomain = true delete $httpProvider.defaults.headers.common['X-Requested-With'] $httpProvider.defaults.headers.common['Accept'] = 'application/json' $httpProvider.defaults.headers.common['Content-Type'] = 'application/json' $httpProvider.interceptors.push('APIInterceptor') ] .config ['$authProvider', ($authProvider) -> $authProvider.configure({ apiUrl: CCR_ENV['RAILS_API_URL'] + '/api' }) ] .run ['$rootScope', '$state', '$transitions', ($rootScope, $state, $transitions) -> $transitions.onError {}, ($transition$) -> if $transition$._error.type != 5 $state.go("search") $rootScope.state_loading = false $rootScope.$on '$stateChangeStart', (event) -> $rootScope.state_loading = true # state_loading set to false when $viewContentLoaded is triggered within each state controller ] hideSidebar = () -> $(document.getElementById('main')).addClass 'expanded' $(document.getElementById('sidebar')).addClass 'hide' $(document.getElementById('content')).addClass 'providers' showSidebar = () -> $(document.getElementById('main')).removeClass 'expanded' $(document.getElementById('sidebar')).removeClass 'hide' $(document.getElementById('content')).removeClass 'providers' if !document.getElementById('need-help') $(document.getElementById('sidebar')).append("<div id='need-help' class='panel ccr-scope margin-top-2'>" + "<h6>Need More Help?</h6>" + "<p><a href='mailto:<EMAIL>'>Write an email</a><br/>" + "<a href='tel:415-343-3300'>Call 415-343-3300</a></p>" + "<p class='small margin-top-1'>Counselors available<br/>Mon–Thu 8:30am– 4pm<br/>Fri 8:30am–noon</p></div>")
true
angular.module 'CCR', [ 'angularjs-dropdown-multiselect', 'angularMoment', 'checklist-model', 'Devise', 'mm.foundation', 'ngAnimate', 'ngAria', 'ngCookies', 'ngMap', 'ng-token-auth-custom', 'ngSanitize', 'templates', 'truncate', 'ui.select', 'ui.slider', 'ui.router', ] .constant '_', window._ .constant 'deepFilter', window.deepFilter .constant 'CC_COOKIE', 'cc_api_key' .config [ '$locationProvider', '$stateProvider', '$urlRouterProvider', '$urlServiceProvider', ($locationProvider, $stateProvider, $urlRouterProvider, $urlServiceProvider) -> $locationProvider.html5Mode(true) # Allow optional trailing slashes $urlServiceProvider.config.strictMode(false) $stateProvider .state('search', { url: '/?searchType', component: 'search', onEnter: showSidebar, resolve: { searchType: ['$stateParams', ($stateParams) -> return $stateParams.searchType ] } }) .state('results', { url: '/providers', component: 'results', onEnter: hideSidebar, }) .state('provider', { url: '/providers/:id', component: 'provider', onEnter: hideSidebar, resolve: { id: ['$stateParams', ($stateParams) -> return $stateParams.id; ] } }) .state('compare', { url: '/compare', component: 'compare', onEnter: hideSidebar, }) .state('reset_password', { url: '/reset_password/:token', component: 'search', onEnter: showSidebar, resolve: { token: ['$stateParams', ($stateParams) -> return $stateParams.token; ] } }) .state('account_info', { url: '/account/info/', component: 'account', onEnter: hideSidebar resolve: { security: ['$q', '$auth', ($q, $auth) -> if(!$auth.retrieveData('auth_headers')) return $q.reject("Not Authorized") ] } }) .state('account_favorites', { url: '/account/favorites/', component: 'favorites', onEnter: hideSidebar resolve: { security: ['$q', '$auth', ($q, $auth) -> if(!$auth.retrieveData('auth_headers')) return $q.reject("Not Authorized") ] } }) $urlRouterProvider.otherwise('/') ] .config ['$httpProvider', ($httpProvider) -> # HTTP Access Control https://en.wikipedia.org/wiki/Cross-origin_resource_sharing $httpProvider.defaults.useXDomain = true delete $httpProvider.defaults.headers.common['X-Requested-With'] $httpProvider.defaults.headers.common['Accept'] = 'application/json' $httpProvider.defaults.headers.common['Content-Type'] = 'application/json' $httpProvider.interceptors.push('APIInterceptor') ] .config ['$authProvider', ($authProvider) -> $authProvider.configure({ apiUrl: CCR_ENV['RAILS_API_URL'] + '/api' }) ] .run ['$rootScope', '$state', '$transitions', ($rootScope, $state, $transitions) -> $transitions.onError {}, ($transition$) -> if $transition$._error.type != 5 $state.go("search") $rootScope.state_loading = false $rootScope.$on '$stateChangeStart', (event) -> $rootScope.state_loading = true # state_loading set to false when $viewContentLoaded is triggered within each state controller ] hideSidebar = () -> $(document.getElementById('main')).addClass 'expanded' $(document.getElementById('sidebar')).addClass 'hide' $(document.getElementById('content')).addClass 'providers' showSidebar = () -> $(document.getElementById('main')).removeClass 'expanded' $(document.getElementById('sidebar')).removeClass 'hide' $(document.getElementById('content')).removeClass 'providers' if !document.getElementById('need-help') $(document.getElementById('sidebar')).append("<div id='need-help' class='panel ccr-scope margin-top-2'>" + "<h6>Need More Help?</h6>" + "<p><a href='mailto:PI:EMAIL:<EMAIL>END_PI'>Write an email</a><br/>" + "<a href='tel:415-343-3300'>Call 415-343-3300</a></p>" + "<p class='small margin-top-1'>Counselors available<br/>Mon–Thu 8:30am– 4pm<br/>Fri 8:30am–noon</p></div>")
[ { "context": "n\",\n data: {user_name: user_name, password: password}\n success: (r)->\n if r.result\n ", "end": 217, "score": 0.9958258867263794, "start": 209, "tag": "PASSWORD", "value": "password" } ]
static/coffee/www/login.coffee
tonghuashuai/51xuehuahua
0
$('form').submit (e)-> user_name = $("input[name='user_name']").val() password = $("input[name='password']").val() $._ajax({ url: "/j/login", data: {user_name: user_name, password: password} success: (r)-> if r.result window.location.href = '/' }) e.preventDefault()
53872
$('form').submit (e)-> user_name = $("input[name='user_name']").val() password = $("input[name='password']").val() $._ajax({ url: "/j/login", data: {user_name: user_name, password: <PASSWORD>} success: (r)-> if r.result window.location.href = '/' }) e.preventDefault()
true
$('form').submit (e)-> user_name = $("input[name='user_name']").val() password = $("input[name='password']").val() $._ajax({ url: "/j/login", data: {user_name: user_name, password: PI:PASSWORD:<PASSWORD>END_PI} success: (r)-> if r.result window.location.href = '/' }) e.preventDefault()
[ { "context": "ioned', ->\n expect(notification.shouldNotify('sallyjoe', 'sallyjoe')).toBe true\n expect(notificati", "end": 181, "score": 0.5675778388977051, "start": 177, "tag": "NAME", "value": "ally" }, { "context": " expect(notification.shouldNotify('sallyjoe', 'sallyjoe'...
test/nick_mentioned_notification_test.coffee
nornagon/ircv
20
describe 'A nick mentioned notifier', -> notification = chat.NickMentionedNotification it 'should notify when nick is mentioned', -> expect(notification.shouldNotify('sallyjoe', 'sallyjoe')).toBe true expect(notification.shouldNotify('thragtusk', 'thragtusk')).toBe true expect(notification.shouldNotify('sallyjoe', 'bill and sallyjoe and thragtusk')).toBe true expect(notification.shouldNotify('sallyjoe', 'bobsallyjoe is a sallyjoe of sorts')).toBe true it 'should be case insensitive ', -> expect(notification.shouldNotify('sallyjoe', 'Sallyjoe')).toBe true expect(notification.shouldNotify('thragtusk', 'tHrAgTuSk')).toBe true expect(notification.shouldNotify('sallyjoe', 'bill and SALLYJOE and thragtusk')).toBe true it 'should notify when there is trailing punctuation', -> expect(notification.shouldNotify('sallyjoe', 'sallyjoe!')).toBe true expect(notification.shouldNotify('sallyjoe', 'sallyjoe?')).toBe true expect(notification.shouldNotify('sallyjoe', 'sallyjoe!?!?!!!!??')).toBe true expect(notification.shouldNotify('sallyjoe', 'sallyjoe*')).toBe true expect(notification.shouldNotify('sallyjoe', 'sallyjoe:')).toBe true expect(notification.shouldNotify('sallyjoe', 'sallyjoe;')).toBe true expect(notification.shouldNotify('sallyjoe', 'sallyjoe-')).toBe true expect(notification.shouldNotify('sallyjoe', 'sallyjoe~')).toBe true expect(notification.shouldNotify('sallyjoe', "oh, it's sallyjoe...")).toBe true expect(notification.shouldNotify('sallyjoe', 'bye sallyjoe.')).toBe true expect(notification.shouldNotify('sallyjoe', 'ssssallyjoe! Sallyjoe, you there?')).toBe true it 'should notify when there is a preceding @', -> expect(notification.shouldNotify('sallyjoe', '@sallyjoe, look at this!')).toBe true it 'should notify when there is a preceding ,', -> expect(notification.shouldNotify('sallyjoe', 'thragtusk,sallyjoe,joe: come to my desk')).toBe true it 'should notify with variable preceding and trailing whitespace', -> expect(notification.shouldNotify('sallyjoe', 'sallyjoe ')).toBe true expect(notification.shouldNotify('sallyjoe', ' sallyjoe')).toBe true expect(notification.shouldNotify('sallyjoe', ' sallyjoe ')).toBe true it 'should notify with combinations of @, punctuation and whitespace', -> expect(notification.shouldNotify('sallyjoe', 'I mean @sallyjoe*')).toBe true expect(notification.shouldNotify('sallyjoe', 'oh its @sallyjoe!!?? ')).toBe true it 'should not notify when nick is not mentioned', -> expect(notification.shouldNotify('thragtusk', 'sallyjoe')).toBe false expect(notification.shouldNotify('sallyjoe', '-sallyjoe-')).toBe false expect(notification.shouldNotify('sallyjoe', 'sallyjoe::')).toBe false expect(notification.shouldNotify('sallyjoe', 'sallyjoe--')).toBe false expect(notification.shouldNotify('sallyjoe', 'asallyjoe')).toBe false expect(notification.shouldNotify('sallyjoe', 'sallyjoea')).toBe false expect(notification.shouldNotify('sallyjoe', 'sallyjoe!?!;')).toBe false expect(notification.shouldNotify('sallyjoe', '@@sallyjoe')).toBe false expect(notification.shouldNotify('sallyjoe', '#sallyjoe')).toBe false expect(notification.shouldNotify('sallyjoe', '#nick#')).toBe false expect(notification.shouldNotify('sallyjoe', 'sallyjoe#')).toBe false expect(notification.shouldNotify('sallyjoe', 'sallyjoesallyjoe')).toBe false expect(notification.shouldNotify('sallyjoe', 'sallyjoe1')).toBe false expect(notification.shouldNotify('sallyjoe', '1sallyjoe')).toBe false it 'should match with optional underscores', -> expect(notification.shouldNotify('sallyjoe', 'sallyjoe______')).toBe true expect(notification.shouldNotify('sallyjoe', '@sallyjoe_... you there?')).toBe true expect(notification.shouldNotify('sallyjoe__', 'sallyjoe')).toBe true expect(notification.shouldNotify('sallyjoe____', 'sallyjoe_')).toBe true
58802
describe 'A nick mentioned notifier', -> notification = chat.NickMentionedNotification it 'should notify when nick is mentioned', -> expect(notification.shouldNotify('s<NAME>joe', 's<NAME>')).toBe true expect(notification.shouldNotify('thragtusk', 'thragtusk')).toBe true expect(notification.shouldNotify('sallyjoe', 'bill and sallyjoe and thragtusk')).toBe true expect(notification.shouldNotify('sallyjoe', 'bobsallyjoe is a sallyjoe of sorts')).toBe true it 'should be case insensitive ', -> expect(notification.shouldNotify('sallyjoe', 'Sallyjoe')).toBe true expect(notification.shouldNotify('thragtusk', 'tHrAgTuSk')).toBe true expect(notification.shouldNotify('sallyjoe', 'bill and SALLYJOE and thragtusk')).toBe true it 'should notify when there is trailing punctuation', -> expect(notification.shouldNotify('sallyjoe', 'sallyjoe!')).toBe true expect(notification.shouldNotify('sallyjoe', 'sallyjoe?')).toBe true expect(notification.shouldNotify('sallyjoe', 'sallyjoe!?!?!!!!??')).toBe true expect(notification.shouldNotify('sallyjoe', 'sallyjoe*')).toBe true expect(notification.shouldNotify('sallyjoe', 'sallyjoe:')).toBe true expect(notification.shouldNotify('sallyjoe', 'sallyjoe;')).toBe true expect(notification.shouldNotify('sallyjoe', 'sallyjoe-')).toBe true expect(notification.shouldNotify('sallyjoe', 'sallyjoe~')).toBe true expect(notification.shouldNotify('sallyjoe', "oh, it's sallyjoe...")).toBe true expect(notification.shouldNotify('sallyjoe', 'bye sallyjoe.')).toBe true expect(notification.shouldNotify('sallyjoe', 'ssssallyjoe! Sallyjoe, you there?')).toBe true it 'should notify when there is a preceding @', -> expect(notification.shouldNotify('sallyjoe', '@sallyjoe, look at this!')).toBe true it 'should notify when there is a preceding ,', -> expect(notification.shouldNotify('sallyjoe', 'thragtusk,sallyjoe,joe: come to my desk')).toBe true it 'should notify with variable preceding and trailing whitespace', -> expect(notification.shouldNotify('sallyjoe', 'sallyjoe ')).toBe true expect(notification.shouldNotify('sallyjoe', ' sallyjoe')).toBe true expect(notification.shouldNotify('sallyjoe', ' sallyjoe ')).toBe true it 'should notify with combinations of @, punctuation and whitespace', -> expect(notification.shouldNotify('sallyjoe', 'I mean @sallyjoe*')).toBe true expect(notification.shouldNotify('sallyjoe', 'oh its @sallyjoe!!?? ')).toBe true it 'should not notify when nick is not mentioned', -> expect(notification.shouldNotify('thragtusk', 'sallyjoe')).toBe false expect(notification.shouldNotify('sallyjoe', '-sallyjoe-')).toBe false expect(notification.shouldNotify('sallyjoe', 'sallyjoe::')).toBe false expect(notification.shouldNotify('sallyjoe', 'sallyjoe--')).toBe false expect(notification.shouldNotify('sallyjoe', 'asallyjoe')).toBe false expect(notification.shouldNotify('sallyjoe', 'sallyjoea')).toBe false expect(notification.shouldNotify('sallyjoe', 'sallyjoe!?!;')).toBe false expect(notification.shouldNotify('sallyjoe', '@@sallyjoe')).toBe false expect(notification.shouldNotify('sallyjoe', '#sallyjoe')).toBe false expect(notification.shouldNotify('sallyjoe', '#nick#')).toBe false expect(notification.shouldNotify('sallyjoe', 'sallyjoe#')).toBe false expect(notification.shouldNotify('sallyjoe', 'sallyjoesallyjoe')).toBe false expect(notification.shouldNotify('sallyjoe', 'sallyjoe1')).toBe false expect(notification.shouldNotify('sallyjoe', '1sallyjoe')).toBe false it 'should match with optional underscores', -> expect(notification.shouldNotify('sallyjoe', 'sallyjoe______')).toBe true expect(notification.shouldNotify('sallyjoe', '@sallyjoe_... you there?')).toBe true expect(notification.shouldNotify('sallyjoe__', 'sallyjoe')).toBe true expect(notification.shouldNotify('sallyjoe____', 'sallyjoe_')).toBe true
true
describe 'A nick mentioned notifier', -> notification = chat.NickMentionedNotification it 'should notify when nick is mentioned', -> expect(notification.shouldNotify('sPI:NAME:<NAME>END_PIjoe', 'sPI:NAME:<NAME>END_PI')).toBe true expect(notification.shouldNotify('thragtusk', 'thragtusk')).toBe true expect(notification.shouldNotify('sallyjoe', 'bill and sallyjoe and thragtusk')).toBe true expect(notification.shouldNotify('sallyjoe', 'bobsallyjoe is a sallyjoe of sorts')).toBe true it 'should be case insensitive ', -> expect(notification.shouldNotify('sallyjoe', 'Sallyjoe')).toBe true expect(notification.shouldNotify('thragtusk', 'tHrAgTuSk')).toBe true expect(notification.shouldNotify('sallyjoe', 'bill and SALLYJOE and thragtusk')).toBe true it 'should notify when there is trailing punctuation', -> expect(notification.shouldNotify('sallyjoe', 'sallyjoe!')).toBe true expect(notification.shouldNotify('sallyjoe', 'sallyjoe?')).toBe true expect(notification.shouldNotify('sallyjoe', 'sallyjoe!?!?!!!!??')).toBe true expect(notification.shouldNotify('sallyjoe', 'sallyjoe*')).toBe true expect(notification.shouldNotify('sallyjoe', 'sallyjoe:')).toBe true expect(notification.shouldNotify('sallyjoe', 'sallyjoe;')).toBe true expect(notification.shouldNotify('sallyjoe', 'sallyjoe-')).toBe true expect(notification.shouldNotify('sallyjoe', 'sallyjoe~')).toBe true expect(notification.shouldNotify('sallyjoe', "oh, it's sallyjoe...")).toBe true expect(notification.shouldNotify('sallyjoe', 'bye sallyjoe.')).toBe true expect(notification.shouldNotify('sallyjoe', 'ssssallyjoe! Sallyjoe, you there?')).toBe true it 'should notify when there is a preceding @', -> expect(notification.shouldNotify('sallyjoe', '@sallyjoe, look at this!')).toBe true it 'should notify when there is a preceding ,', -> expect(notification.shouldNotify('sallyjoe', 'thragtusk,sallyjoe,joe: come to my desk')).toBe true it 'should notify with variable preceding and trailing whitespace', -> expect(notification.shouldNotify('sallyjoe', 'sallyjoe ')).toBe true expect(notification.shouldNotify('sallyjoe', ' sallyjoe')).toBe true expect(notification.shouldNotify('sallyjoe', ' sallyjoe ')).toBe true it 'should notify with combinations of @, punctuation and whitespace', -> expect(notification.shouldNotify('sallyjoe', 'I mean @sallyjoe*')).toBe true expect(notification.shouldNotify('sallyjoe', 'oh its @sallyjoe!!?? ')).toBe true it 'should not notify when nick is not mentioned', -> expect(notification.shouldNotify('thragtusk', 'sallyjoe')).toBe false expect(notification.shouldNotify('sallyjoe', '-sallyjoe-')).toBe false expect(notification.shouldNotify('sallyjoe', 'sallyjoe::')).toBe false expect(notification.shouldNotify('sallyjoe', 'sallyjoe--')).toBe false expect(notification.shouldNotify('sallyjoe', 'asallyjoe')).toBe false expect(notification.shouldNotify('sallyjoe', 'sallyjoea')).toBe false expect(notification.shouldNotify('sallyjoe', 'sallyjoe!?!;')).toBe false expect(notification.shouldNotify('sallyjoe', '@@sallyjoe')).toBe false expect(notification.shouldNotify('sallyjoe', '#sallyjoe')).toBe false expect(notification.shouldNotify('sallyjoe', '#nick#')).toBe false expect(notification.shouldNotify('sallyjoe', 'sallyjoe#')).toBe false expect(notification.shouldNotify('sallyjoe', 'sallyjoesallyjoe')).toBe false expect(notification.shouldNotify('sallyjoe', 'sallyjoe1')).toBe false expect(notification.shouldNotify('sallyjoe', '1sallyjoe')).toBe false it 'should match with optional underscores', -> expect(notification.shouldNotify('sallyjoe', 'sallyjoe______')).toBe true expect(notification.shouldNotify('sallyjoe', '@sallyjoe_... you there?')).toBe true expect(notification.shouldNotify('sallyjoe__', 'sallyjoe')).toBe true expect(notification.shouldNotify('sallyjoe____', 'sallyjoe_')).toBe true
[ { "context": "7/blog_example'\n\nauthor = new User\n username : 'humanchimp'\n fullName : 'Chris Thorn'\n email : \"chris", "end": 134, "score": 0.9996479153633118, "start": 124, "tag": "USERNAME", "value": "humanchimp" }, { "context": "ew User\n username : 'humanchimp'\n ...
node_modules_koding/bongo/examples/blog_example/index.coffee
ezgikaysi/koding
1
{User, Post, Comment} = require './models' Post.setClient 'localhost:27017/blog_example' author = new User username : 'humanchimp' fullName : 'Chris Thorn' email : "chris@koding.com" foo : 'abcd' commenter1 = new User username : 'fooman' fullName : 'Nroht Srihc' email : 'nroht@jraphical.com' foo : 'zyxw' author.save (err)-> throw err if err # make a new blog post post = new Post author : author._id title : "zO hai!" body : "Welcome to my hella coole new Blog!!!" post.on 'error', console.log post.on 'save', (step)-> switch step when 0 console.log post when 1 console.log 'saved' post.save (err)-> throw err if err commenter1.on 'error', console.log commenter1.save (err)-> throw err if err comment1 = new Comment author : commenter1._id body : 'This blog is teh kule!' # save a comment to the blog post post.addComment comment1 post.save()
60260
{User, Post, Comment} = require './models' Post.setClient 'localhost:27017/blog_example' author = new User username : 'humanchimp' fullName : '<NAME>' email : "<EMAIL>" foo : 'abcd' commenter1 = new User username : 'fooman' fullName : '<NAME>' email : '<EMAIL>' foo : 'zyxw' author.save (err)-> throw err if err # make a new blog post post = new Post author : author._id title : "zO hai!" body : "Welcome to my hella coole new Blog!!!" post.on 'error', console.log post.on 'save', (step)-> switch step when 0 console.log post when 1 console.log 'saved' post.save (err)-> throw err if err commenter1.on 'error', console.log commenter1.save (err)-> throw err if err comment1 = new Comment author : commenter1._id body : 'This blog is teh kule!' # save a comment to the blog post post.addComment comment1 post.save()
true
{User, Post, Comment} = require './models' Post.setClient 'localhost:27017/blog_example' author = new User username : 'humanchimp' fullName : 'PI:NAME:<NAME>END_PI' email : "PI:EMAIL:<EMAIL>END_PI" foo : 'abcd' commenter1 = new User username : 'fooman' fullName : 'PI:NAME:<NAME>END_PI' email : 'PI:EMAIL:<EMAIL>END_PI' foo : 'zyxw' author.save (err)-> throw err if err # make a new blog post post = new Post author : author._id title : "zO hai!" body : "Welcome to my hella coole new Blog!!!" post.on 'error', console.log post.on 'save', (step)-> switch step when 0 console.log post when 1 console.log 'saved' post.save (err)-> throw err if err commenter1.on 'error', console.log commenter1.save (err)-> throw err if err comment1 = new Comment author : commenter1._id body : 'This blog is teh kule!' # save a comment to the blog post post.addComment comment1 post.save()
[ { "context": "hbluServer\n\n beforeEach (done) ->\n @redisKey = UUID.v1()\n meshbluConfig =\n server: 'localhost'\n ", "end": 415, "score": 0.9957100749015808, "start": 406, "tag": "KEY", "value": "UUID.v1()" }, { "context": "0000'\n uuid: 'governator-uuid'\n ...
test/integration/status-spec.coffee
octoblu/governator-service
0
request = require 'request' shmock = require 'shmock' enableDestroy = require 'server-destroy' UUID = require 'uuid' RedisNs = require '@octoblu/redis-ns' redis = require 'ioredis' Server = require '../../server' describe 'Get Status', -> beforeEach -> @meshbluServer = shmock 30000 enableDestroy @meshbluServer beforeEach (done) -> @redisKey = UUID.v1() meshbluConfig = server: 'localhost' port: '30000' uuid: 'governator-uuid' token: 'governator-token' @client = new RedisNs @redisKey, redis.createClient 'redis://localhost:6379', dropBufferSupport: true @sut = new Server { meshbluConfig: meshbluConfig port: 20000 disableLogging: true deployDelay: 0 redisUri: 'redis://localhost:6379' namespace: @redisKey maxConnections: 2, requiredClusters: ['minor'] cluster: 'super' deployStateUri: 'http://localhost' } @sut.run done afterEach -> @sut.destroy() @meshbluServer.destroy() describe 'GET /status', -> describe 'when called with valid auth', -> describe 'when called with a pending deploy', -> beforeEach (done) -> metadata = etcdDir: '/foo/bar' dockerUrl: 'quay.io/foo/bar:v1.0.0' @client.hset "governator:/foo/bar:quay.io/foo/bar:v1.0.0", 'request:metadata', JSON.stringify(metadata), done beforeEach (done) -> @client.zadd "governator:deploys", 1921925912, "governator:/foo/bar:quay.io/foo/bar:v1.0.0", done beforeEach (done) -> governatorAuth = new Buffer('governator-uuid:governator-token').toString 'base64' @meshbluServer .get '/v2/whoami' .set 'Authorization', "Basic #{governatorAuth}" .reply 200, uuid: 'governator-uuid' options = uri: '/status' baseUrl: 'http://localhost:20000' auth: {username: 'governator-uuid', password: 'governator-token'} json: true request.get options, (error, @response, @body) => return done error if error? done() it 'should return a 200', -> expect(@response.statusCode).to.equal 200, @body it 'should return a response', -> expectedResponse = 'governator:/foo/bar:quay.io/foo/bar:v1.0.0': key: 'governator:/foo/bar:quay.io/foo/bar:v1.0.0' deployAt: 1921925912 status: 'pending' expect(@response.body).to.deep.equal expectedResponse describe 'when called with a cancelled deploy', -> beforeEach (done) -> metadata = etcdDir: '/foo/bar' dockerUrl: 'quay.io/foo/bar:v1.0.0' @client.hset "governator:/foo/bar:quay.io/foo/bar:v1.0.0", 'request:metadata', JSON.stringify(metadata), done beforeEach (done) -> @client.zadd "governator:deploys", 1921925912, "governator:/foo/bar:quay.io/foo/bar:v1.0.0", done beforeEach (done) -> @client.hset "governator:/foo/bar:quay.io/foo/bar:v1.0.0", 'cancellation', Date.now(), done beforeEach (done) -> governatorAuth = new Buffer('governator-uuid:governator-token').toString 'base64' @meshbluServer .get '/v2/whoami' .set 'Authorization', "Basic #{governatorAuth}" .reply 200, uuid: 'governator-uuid' options = uri: '/status' baseUrl: 'http://localhost:20000' auth: {username: 'governator-uuid', password: 'governator-token'} json: true request.get options, (error, @response, @body) => return done error if error? done() it 'should return a 200', -> expect(@response.statusCode).to.equal 200, @body it 'should return a response', -> expectedResponse = 'governator:/foo/bar:quay.io/foo/bar:v1.0.0': key: 'governator:/foo/bar:quay.io/foo/bar:v1.0.0' deployAt: 1921925912 status: 'cancelled' expect(@response.body).to.deep.equal expectedResponse
83253
request = require 'request' shmock = require 'shmock' enableDestroy = require 'server-destroy' UUID = require 'uuid' RedisNs = require '@octoblu/redis-ns' redis = require 'ioredis' Server = require '../../server' describe 'Get Status', -> beforeEach -> @meshbluServer = shmock 30000 enableDestroy @meshbluServer beforeEach (done) -> @redisKey = <KEY> meshbluConfig = server: 'localhost' port: '30000' uuid: 'governator-uuid' token: '<PASSWORD>' @client = new RedisNs @redisKey, redis.createClient 'redis://localhost:6379', dropBufferSupport: true @sut = new Server { meshbluConfig: meshbluConfig port: 20000 disableLogging: true deployDelay: 0 redisUri: 'redis://localhost:6379' namespace: @redisKey maxConnections: 2, requiredClusters: ['minor'] cluster: 'super' deployStateUri: 'http://localhost' } @sut.run done afterEach -> @sut.destroy() @meshbluServer.destroy() describe 'GET /status', -> describe 'when called with valid auth', -> describe 'when called with a pending deploy', -> beforeEach (done) -> metadata = etcdDir: '/foo/bar' dockerUrl: 'quay.io/foo/bar:v1.0.0' @client.hset "governator:/foo/bar:quay.io/foo/bar:v1.0.0", 'request:metadata', JSON.stringify(metadata), done beforeEach (done) -> @client.zadd "governator:deploys", 1921925912, "governator:/foo/bar:quay.io/foo/bar:v1.0.0", done beforeEach (done) -> governatorAuth = new Buffer('governator-uuid:governator-token').toString 'base64' @meshbluServer .get '/v2/whoami' .set 'Authorization', "Basic #{governatorAuth}" .reply 200, uuid: 'governator-uuid' options = uri: '/status' baseUrl: 'http://localhost:20000' auth: {username: 'governator-uuid', password: '<PASSWORD>'} json: true request.get options, (error, @response, @body) => return done error if error? done() it 'should return a 200', -> expect(@response.statusCode).to.equal 200, @body it 'should return a response', -> expectedResponse = 'governator:/foo/bar:quay.io/foo/bar:v1.0.0': key: 'governator:/foo/bar:quay.io/foo/bar:v1.0.0' deployAt: 1921925912 status: 'pending' expect(@response.body).to.deep.equal expectedResponse describe 'when called with a cancelled deploy', -> beforeEach (done) -> metadata = etcdDir: '/foo/bar' dockerUrl: 'quay.io/foo/bar:v1.0.0' @client.hset "governator:/foo/bar:quay.io/foo/bar:v1.0.0", 'request:metadata', JSON.stringify(metadata), done beforeEach (done) -> @client.zadd "governator:deploys", 1921925912, "governator:/foo/bar:quay.io/foo/bar:v1.0.0", done beforeEach (done) -> @client.hset "governator:/foo/bar:quay.io/foo/bar:v1.0.0", 'cancellation', Date.now(), done beforeEach (done) -> governatorAuth = new Buffer('governator-uuid:governator-token').toString 'base64' @meshbluServer .get '/v2/whoami' .set 'Authorization', "Basic #{governatorAuth}" .reply 200, uuid: 'governator-uuid' options = uri: '/status' baseUrl: 'http://localhost:20000' auth: {username: 'governator-uuid', password: '<PASSWORD>'} json: true request.get options, (error, @response, @body) => return done error if error? done() it 'should return a 200', -> expect(@response.statusCode).to.equal 200, @body it 'should return a response', -> expectedResponse = 'governator:/foo/bar:quay.io/foo/bar:v1.0.0': key: 'governator:/foo/bar:quay.io/foo/bar:v1.0.0' deployAt: 1921925912 status: 'cancelled' expect(@response.body).to.deep.equal expectedResponse
true
request = require 'request' shmock = require 'shmock' enableDestroy = require 'server-destroy' UUID = require 'uuid' RedisNs = require '@octoblu/redis-ns' redis = require 'ioredis' Server = require '../../server' describe 'Get Status', -> beforeEach -> @meshbluServer = shmock 30000 enableDestroy @meshbluServer beforeEach (done) -> @redisKey = PI:KEY:<KEY>END_PI meshbluConfig = server: 'localhost' port: '30000' uuid: 'governator-uuid' token: 'PI:PASSWORD:<PASSWORD>END_PI' @client = new RedisNs @redisKey, redis.createClient 'redis://localhost:6379', dropBufferSupport: true @sut = new Server { meshbluConfig: meshbluConfig port: 20000 disableLogging: true deployDelay: 0 redisUri: 'redis://localhost:6379' namespace: @redisKey maxConnections: 2, requiredClusters: ['minor'] cluster: 'super' deployStateUri: 'http://localhost' } @sut.run done afterEach -> @sut.destroy() @meshbluServer.destroy() describe 'GET /status', -> describe 'when called with valid auth', -> describe 'when called with a pending deploy', -> beforeEach (done) -> metadata = etcdDir: '/foo/bar' dockerUrl: 'quay.io/foo/bar:v1.0.0' @client.hset "governator:/foo/bar:quay.io/foo/bar:v1.0.0", 'request:metadata', JSON.stringify(metadata), done beforeEach (done) -> @client.zadd "governator:deploys", 1921925912, "governator:/foo/bar:quay.io/foo/bar:v1.0.0", done beforeEach (done) -> governatorAuth = new Buffer('governator-uuid:governator-token').toString 'base64' @meshbluServer .get '/v2/whoami' .set 'Authorization', "Basic #{governatorAuth}" .reply 200, uuid: 'governator-uuid' options = uri: '/status' baseUrl: 'http://localhost:20000' auth: {username: 'governator-uuid', password: 'PI:PASSWORD:<PASSWORD>END_PI'} json: true request.get options, (error, @response, @body) => return done error if error? done() it 'should return a 200', -> expect(@response.statusCode).to.equal 200, @body it 'should return a response', -> expectedResponse = 'governator:/foo/bar:quay.io/foo/bar:v1.0.0': key: 'governator:/foo/bar:quay.io/foo/bar:v1.0.0' deployAt: 1921925912 status: 'pending' expect(@response.body).to.deep.equal expectedResponse describe 'when called with a cancelled deploy', -> beforeEach (done) -> metadata = etcdDir: '/foo/bar' dockerUrl: 'quay.io/foo/bar:v1.0.0' @client.hset "governator:/foo/bar:quay.io/foo/bar:v1.0.0", 'request:metadata', JSON.stringify(metadata), done beforeEach (done) -> @client.zadd "governator:deploys", 1921925912, "governator:/foo/bar:quay.io/foo/bar:v1.0.0", done beforeEach (done) -> @client.hset "governator:/foo/bar:quay.io/foo/bar:v1.0.0", 'cancellation', Date.now(), done beforeEach (done) -> governatorAuth = new Buffer('governator-uuid:governator-token').toString 'base64' @meshbluServer .get '/v2/whoami' .set 'Authorization', "Basic #{governatorAuth}" .reply 200, uuid: 'governator-uuid' options = uri: '/status' baseUrl: 'http://localhost:20000' auth: {username: 'governator-uuid', password: 'PI:PASSWORD:<PASSWORD>END_PI'} json: true request.get options, (error, @response, @body) => return done error if error? done() it 'should return a 200', -> expect(@response.statusCode).to.equal 200, @body it 'should return a response', -> expectedResponse = 'governator:/foo/bar:quay.io/foo/bar:v1.0.0': key: 'governator:/foo/bar:quay.io/foo/bar:v1.0.0' deployAt: 1921925912 status: 'cancelled' expect(@response.body).to.deep.equal expectedResponse
[ { "context": "ack at the highest level\n# see https://github.com/TooTallNate/node-weak#weak-callback-function-best-practices\n#", "end": 1110, "score": 0.99961918592453, "start": 1099, "tag": "USERNAME", "value": "TooTallNate" }, { "context": "TODO make it configurable\n c...
src/server/virtual_browser/index.coffee
bladepan/cloudbrowser
0
Util = require('util') Path = require('path') FS = require('fs') Weak = require('weak') {EventEmitter} = require('events') url = require('url') debug = require('debug') lodash = require('lodash') Browser = require('./browser') ResourceProxy = require('./resource_proxy') SocketAdvice = require('./socket_advice') TestClient = require('./test_client') {serialize} = require('./serializer') routes = require('../application_manager/routes') Compressor = require('../../shared/compressor') EmbedAPI = require('../../api') TaggedNodeCollection = require('../../shared/tagged_node_collection') {isVisibleOnClient} = require('../../shared/utils') {eventTypeToGroup, clientEvents, defaultEvents} = require('../../shared/event_lists') logger = debug("cloudbrowser:worker:browser") errorLogger = debug("cloudbrowser:worker:error") # Defining callback at the highest level # see https://github.com/TooTallNate/node-weak#weak-callback-function-best-practices # Dummy callback, does nothing cleanupBserver = (id) -> return () -> logger "[Virtual Browser] - Garbage collected virtual browser #{id}" # Serves 1 Browser to n clients. Managing sockets, rpc calls class VirtualBrowser extends EventEmitter __r_skip :['server','browser','sockets','compressor','registeredEventTypes', 'localState','consoleLog','rpcLog', 'nodes', 'resources'] constructor : (vbInfo) -> {@server, @id, @mountPoint, @appInstance} = vbInfo {@workerId} = @appInstance @appInstanceId = @appInstance.id weakRefToThis = Weak(this, cleanupBserver(@id)) @compressor = new Compressor() # make the compressed result deterministic for k in keywordsList @compressor.compress(k) @browser = new Browser(@id, weakRefToThis, @server.config) # we definetly don't want to send everything in config to client, # like database, emailer settings configToInclude = ['compression'] @_clientEngineConfig = {} for k, v of @server.config if configToInclude.indexOf(k) isnt -1 @_clientEngineConfig[k] = v @dateCreated = new Date() @localState = {} # TODO : Causes memory leak, must fix @browser.on 'PageLoaded', () => @browser.window.addEventListener 'hashchange', (event) => @broadcastEvent('UpdateLocationHash', @browser.window.location.hash) @sockets = [] @compressor.on 'newSymbol', (args) => for socket in @sockets socket.emit('newSymbol', args.original, args.compressed) @registeredEventTypes = [] # Indicates whether @browser is currently loading a page. # If so, we don't process client events/updates. @browserLoading = false # Indicates whether the browser has loaded its first page. @browserInitialized = false for own event, handler of DOMEventHandlers do (event, handler) => @browser.on event, () -> handler.apply(weakRefToThis, arguments) # referenced in api.getLogger, for client code only @_logger = debug("cloudbrowser:worker:browser:#{@id}") #@initLogs() if !@server.config.noLogs getID : () -> return @id getUrl : () -> return "#{@server.config.getHttpAddr()}#{routes.buildBrowserPath(@mountPoint, @appInstanceId, @id)}" getDateCreated : () -> return @dateCreated getName : () -> return @name setName : (name) -> @name = name getBrowser : () -> return @browser getMountPoint : () -> return @mountPoint getAppInstance : () -> return @appInstance getConnectedClients : () -> clients = [] for socket in @sockets {address} = socket {user} = socket.request clients.push address : address email : user return clients setLocalState : (property, value) -> @localState[property] = value getLocalState : (property) -> return @localState[property] redirect : (URL) -> @broadcastEvent('Redirect', URL) getSessions : (callback) -> mongoInterface = @server.mongoInterface getFromDB = (socket, callback) -> sessionID = socket.request.sessionID mongoInterface.getSession(sessionID, callback) Async.map(@sockets, getFromDB, callback) getFirstSession : (callback) -> mongoInterface = @server.mongoInterface sessionID = @sockets[0].request.sessionID mongoInterface.getSession(sessionID, callback) # arg can be an Application or URL string. load : (arg, callback) -> if not arg then arg = @server.applicationManager.find(@mountPoint) self = this @browser.load(arg, (err)-> return callback(err) if err? weakRefToThis = Weak(self, cleanupBserver(@id)) EmbedAPI(weakRefToThis) callback null ) # For testing purposes, return an emulated client for this browser. createTestClient : () -> if !process.env.TESTS_RUNNING throw new Error('Called createTestClient but not running tests.') return new TestClient(@id, @mountPoint) initLogs : () -> logDir = Path.resolve(__dirname, '..', '..', '..', 'logs') @consoleLogPath = Path.resolve(logDir, "#{@browser.id}.log") @consoleLog = FS.createWriteStream(@consoleLogPath) @consoleLog.write("Log opened: #{Date()}\n") @consoleLog.write("BrowserID: #{@browser.id}\n") if @server.config.traceProtocol rpcLogPath = Path.resolve(logDir, "#{@browser.id}-rpc.log") @rpcLog = FS.createWriteStream(rpcLogPath) close : () -> return if @closed @closed = true @stop() @compressor.removeAllListeners() @browser.close() @browser = null @emit('BrowserClose') @removeAllListeners() @consoleLog?.end() @rpcLog?.end() stop : (callback)-> for socket in @sockets socket.disconnect() socket.removeAllListeners() @sockets = [] callback(null) if callback? # this mountPoint is the real application this authentication vb delegates, # it is not the same as this vb's own mountPoint _redirectToGoogleAuth : (mountPoint)-> logger("prepare redirect to google auth") @getFirstSession (err, session) => if err? errorLogger(err) return sessionManager = @server.sessionManager # random string, google will pass it back, we use it to # check if the callback is forged or not state = Math.random().toString() sessionManager.setPropOnSession(session, 'googleAuthInfo', { mountPoint : mountPoint state : state }) # TODO make it configurable clientId = "247142348909-2s8tudf2n69iedmt4tvt2bun5bu2ro5t.apps.googleusercontent.com" clientSecret = "rPk5XM_ggD2bHku2xewOmf-U" # cannot use customized port in redirect_uri, # see https://github.com/brianmcd/cloudbrowser/wiki/Authentication-with-Google redirectUri = "#{@server.config.getHttpAddr()}/checkauth" googleAuthUrl = url.format({ protocol : "https", host :"accounts.google.com", pathname : "/o/oauth2/auth", query : { "scope":"https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email", "state" : state, "redirect_uri" : redirectUri, "response_type" : "code", "client_id" : clientId, "access_type" : "offline" } }) logger("redirect to "+ googleAuthUrl) @redirect(googleAuthUrl) # Kill the browser once client has been authenticated @once 'NoClients', () => @close() logRPCMethod : (name, params) -> @rpcLog.write("#{name}(") if params.length == 0 return @rpcLog.write(")\n") lastIdx = params.length - 1 for param, idx in params if name == 'PageLoaded' str = Util.inspect(param, false, null).replace /[^\}],\n/g, (str) -> str[0] else str = Util.inspect(param, false, null).replace(/[\n\t]/g, '') @rpcLog.write(str) if idx == lastIdx @rpcLog.write(')\n') else @rpcLog.write(', ') broadcastEvent : (name, args...) -> if @server.config.traceProtocol @logRPCMethod(name, args) args.unshift(name) if @sockets.length is 1 @sockets[0].emitCompressed(args, @clientContext) return allArgs = [args] # the emitCompressed would modify args in deduplication/compression. # only clone things when needed for i in [1...@sockets.length] by 1 allArgs.push(lodash.cloneDeep(args)) for i in [0...@sockets.length] by 1 socket = @sockets[i] socket.emitCompressed(allArgs[i], @clientContext) return addSocket : (s) -> socket = SocketAdvice.adviceSocket({ socket : s buffer : true compression : @server.config.compression compressor : @compressor }) address = socket.request.connection.remoteAddress socket.address = address {user} = socket.request # if it is not issued from web browser, address is empty if address address = "#{address.address}:#{address.port}" userInfo = address : address email : user @emit('connect', userInfo) for own type, func of RPCMethods do (type, func) => socket.on type, () => if @server.config.traceProtocol @logRPCMethod(type, arguments) args = Array.prototype.slice.call(arguments) args.push(socket) # Weak ref not required here try func.apply(this, args) catch e console.log e socket.on 'disconnect', () => @sockets = (s for s in @sockets when s != socket) @emit('disconnect', address) if not @sockets.length @emit 'NoClients' socket.emit('SetConfig', @_clientEngineConfig) if !@browserInitialized return @sockets.push(socket) # the socket is added after the first pageloaded event emitted nodes = serialize(@browser.window.document, @resources, @browser.window.document, @server.config) compressionTable = undefined if @server.config.compression compressionTable = @compressor.textToSymbol socket.emit('PageLoaded', nodes, @registeredEventTypes, @browser.clientComponents, compressionTable) @sockets.push(socket) gc() if @server.config.traceMem @emit('ClientAdded') handleComponentRequest : (componentId, req, res)-> @browser.handleComponentRequest(componentId, req, res) # The VirtualBrowser constructor iterates over the properties in this object and # adds an event handler to the Browser for each one. The function name must # match the Browser event name. 'this' is set to the Browser via apply. DOMEventHandlers = PageLoading : (event) -> @nodes = new TaggedNodeCollection() if @server.config.resourceProxy @resources = new ResourceProxy(event.url) @browserLoading = true PageLoaded : () -> @browserInitialized = true @browserLoading = false nodes = serialize(@browser.window.document, @resources, @browser.window.document, @server.config) compressionTable = undefined if @server.config.compression compressionTable = @compressor.textToSymbol if @server.config.traceProtocol @logRPCMethod('PageLoaded', [nodes, @browser.clientComponents, compressionTable]) for socket in @sockets socket.emit('PageLoaded', nodes, @registeredEventTypes, @browser.clientComponents, compressionTable) if @server.config.traceMem gc() DocumentCreated : (event) -> @nodes.add(event.target) FrameLoaded : (event) -> {target} = event targetID = target.__nodeID @broadcastEvent('clear', targetID) @broadcastEvent('TagDocument', targetID, target.contentDocument.__nodeID) # Tag all newly created nodes. # This seems cleaner than having serializer do the tagging. DOMNodeInserted : (event) -> {target} = event if !target.__nodeID @nodes.add(target) if /[i]?frame/.test(target.tagName?.toLowerCase()) # TODO: This is a temp hack, we shouldn't rely on JSDOM's # MutationEvents. listener = target.addEventListener 'DOMNodeInsertedIntoDocument', () => target.removeEventListener('DOMNodeInsertedIntoDocument', listener) if isVisibleOnClient(target, @browser) @broadcastEvent('ResetFrame', target.__nodeID, target.contentDocument.__nodeID) ResetFrame : (event) -> return if @browserLoading {target} = event @broadcastEvent('ResetFrame', target.__nodeID, target.contentDocument.__nodeID) # TODO: consider doctypes. DOMNodeInsertedIntoDocument : (event) -> return if @browserLoading {target} = event nodes = serialize(target, @resources, @browser.window.document, @server.config) return if nodes.length == 0 # 'sibling' tells the client where to insert the top level node in # relation to its siblings. # We only need it for the top level node because nodes in its tree # are serialized in order. sibling = target.nextSibling while sibling?.tagName == 'SCRIPT' sibling = sibling.nextSibling @broadcastEvent('DOMNodeInsertedIntoDocument', nodes, sibling?.__nodeID) DOMNodeRemovedFromDocument : (event) -> return if @browserLoading event = @nodes.scrub(event) return if not event.relatedNode? # nodes use weak to auto reclaim garbage nodes @broadcastEvent('DOMNodeRemovedFromDocument', event.relatedNode, event.target) DOMAttrModified : (event) -> {attrName, newValue, attrChange, target} = event tagName = target.tagName?.toLowerCase() if /i?frame|script/.test(tagName) return isAddition = (attrChange == 'ADDITION') if isAddition && attrName == 'src' newValue = @resources.addURL(newValue) if @browserLoading return @broadcastEvent('DOMAttrModified', target.__nodeID, attrName, newValue, attrChange) AddEventListener : (event) -> {target, type} = event # click and change are always listened return if !clientEvents[type] || defaultEvents[type] idx = @registeredEventTypes.indexOf(type) return if idx != -1 @registeredEventTypes.push(type) @broadcastEvent('AddEventListener', type) EnteredTimer : () -> return if @browserLoading @broadcastEvent 'pauseRendering' # TODO DOM updates in timers should be batched, # there is no point to send any events to client if # there's no DOM updates happened in the timer ExitedTimer : () -> return if @browserLoading @broadcastEvent 'resumeRendering' ConsoleLog : (event) -> @consoleLog?.write(event.msg + '\n') # TODO: debug flag to enable line below. # @broadcastEvent('ConsoleLog', event) DOMStyleChanged : (event) -> return if @browserLoading @broadcastEvent('DOMStyleChanged', event.target.__nodeID, event.attribute, event.value) DOMPropertyModified : (event) -> return if @browserLoading @broadcastEvent('DOMPropertyModified', event.target.__nodeID, event.property, event.value) DOMCharacterDataModified : (event) -> return if @browserLoading @broadcastEvent('DOMCharacterDataModified', event.target.__nodeID, event.value) WindowMethodCalled : (event) -> return if @browserLoading @broadcastEvent('WindowMethodCalled', event.method, event.args) CreateComponent : (component) -> #console.log("Inside createComponent: #{@browserLoading}") return if @browserLoading {target, name, options} = component @broadcastEvent('CreateComponent', name, target.id, options) ComponentMethod : (event) -> return if @browserLoading {target, method, args} = event @broadcastEvent('ComponentMethod', target.__nodeID, method, args) TestDone : () -> throw new Error() if @browserLoading @broadcastEvent('TestDone') inputTags = ['INPUT', 'TEXTAREA'] RPCMethods = setAttribute : (targetId, attribute, value, socket) -> return if @browserLoading @clientContext={ from : socket target : targetId value : value } target = @nodes.get(targetId) if attribute == 'src' return if attribute == 'selectedIndex' return target[attribute] = value if inputTags.indexOf(target.tagName) >= 0 and attribute is "value" RPCMethods._setInputElementValue(target, value) else target.setAttribute(attribute, value) @clientContext=null _setInputElementValue : (target, value)-> # coping the implementation of textarea target.value = value # pan : to my knowledge, this id is used in benchmark tools to track which client instance # triggered 'processEvent', a better naming would be clientId processEvent : (event, id) -> if !@browserLoading # TODO # This bail out happens when an event fires on a component, which # only really exists client side and doesn't have a nodeID (and we # can't handle clicks on the server anyway). # Need something more elegant. return if !event.target # Swap nodeIDs with nodes clientEv = @nodes.unscrub(event) # Create an event we can dispatch on the server. serverEv = RPCMethods._createEvent(clientEv, @browser.window) @broadcastEvent('pauseRendering', id) clientEv.target.dispatchEvent(serverEv) @broadcastEvent('resumeRendering', id) if @server.config.traceMem gc() @server.eventTracker.inc() input : (events, id, socket)-> return if @browserLoading inputEvent = events[events.length-1] @clientContext={ from : socket target : inputEvent.target value : inputEvent._newValue } @broadcastEvent('pauseRendering', id) skipInputEvent = false for clientEv in events @nodes.unscrub(clientEv) switch clientEv.type when 'input' # it is always the last event if not skipInputEvent RPCMethods._setInputElementValue(clientEv.target, clientEv._newValue) RPCMethods._dispatchEvent(@, clientEv) break when 'keydown' serverEv = RPCMethods._dispatchEvent(@, clientEv) if serverEv skipInputEvent = serverEv._preventDefault break when 'keypress' if not skipInputEvent RPCMethods._dispatchEvent(@, clientEv) break else logger("unexpected event #{clientEv.type}") @broadcastEvent('resumeRendering', id) @clientContext=null _dispatchEvent : (vbrowser, clientEv)-> browser = vbrowser.browser if vbrowser.registeredEventTypes.indexOf(clientEv.type) >=0 or defaultEvents[clientEv.type]? serverEv = RPCMethods._createEvent(clientEv, browser.window) clientEv.target.dispatchEvent(serverEv) return serverEv # Takes a clientEv (an event generated on the client and sent over DNode) # and creates a corresponding event for the server's DOM. _createEvent : (clientEv, window) -> group = eventTypeToGroup[clientEv.type] event = window.document.createEvent(group) switch group when 'UIEvents' event.initUIEvent(clientEv.type, clientEv.bubbles, clientEv.cancelable, window, clientEv.detail) when 'HTMLEvents' event.initEvent(clientEv.type, clientEv.bubbles, clientEv.cancelable) when 'MouseEvents' event.initMouseEvent(clientEv.type, clientEv.bubbles, clientEv.cancelable, window, clientEv.detail, clientEv.screenX, clientEv.screenY, clientEv.clientX, clientEv.clientY, clientEv.ctrlKey, clientEv.altKey, clientEv.shiftKey, clientEv.metaKey, clientEv.button, clientEv.relatedTarget) # Eventually, we'll detect events from different browsers and # handle them accordingly. when 'KeyboardEvent' # For Chrome: char = String.fromCharCode(clientEv.which) locale = modifiersList = "" repeat = false if clientEv.altGraphKey then modifiersList += "AltGraph" if clientEv.altKey then modifiersList += "Alt" if clientEv.ctrlKey then modifiersList += "Ctrl" if clientEv.metaKey then modifiersList += "Meta" if clientEv.shiftKey then modifiersList += "Shift" # TODO: to get the "keyArg" parameter right, we'd need a lookup # table for: # http://www.w3.org/TR/DOM-Level-3-Events/#key-values-list event.initKeyboardEvent(clientEv.type, clientEv.bubbles, clientEv.cancelable, window, char, char, clientEv.keyLocation, modifiersList, repeat, locale) event.keyCode = clientEv.keyCode event.which = clientEv.which return event componentEvent : (params) -> {nodeID} = params node = @nodes.get(nodeID) if !node throw new Error("Invalid component nodeID: #{nodeID}") component = @browser.components[nodeID] if !component throw new Error("No component on node: #{nodeID}") for own key, val of params.attrs component.attrs?[key] = val @broadcastEvent('pauseRendering') event = @browser.window.document.createEvent('HTMLEvents') event.initEvent(params.event.type, false, false) event.info = params.event node.dispatchEvent(event) @broadcastEvent('resumeRendering') domEventHandlerNames = lodash.keys(DOMEventHandlers) # put frequent occurred events in front domEventHandlerNames = lodash.sortBy(domEventHandlerNames, (name)-> if name.indexOf('DOM') is 0 return 0 return 1 ) keywordsList = ['pauseRendering', 'resumeRendering', 'batch'].concat(domEventHandlerNames) module.exports = VirtualBrowser
101343
Util = require('util') Path = require('path') FS = require('fs') Weak = require('weak') {EventEmitter} = require('events') url = require('url') debug = require('debug') lodash = require('lodash') Browser = require('./browser') ResourceProxy = require('./resource_proxy') SocketAdvice = require('./socket_advice') TestClient = require('./test_client') {serialize} = require('./serializer') routes = require('../application_manager/routes') Compressor = require('../../shared/compressor') EmbedAPI = require('../../api') TaggedNodeCollection = require('../../shared/tagged_node_collection') {isVisibleOnClient} = require('../../shared/utils') {eventTypeToGroup, clientEvents, defaultEvents} = require('../../shared/event_lists') logger = debug("cloudbrowser:worker:browser") errorLogger = debug("cloudbrowser:worker:error") # Defining callback at the highest level # see https://github.com/TooTallNate/node-weak#weak-callback-function-best-practices # Dummy callback, does nothing cleanupBserver = (id) -> return () -> logger "[Virtual Browser] - Garbage collected virtual browser #{id}" # Serves 1 Browser to n clients. Managing sockets, rpc calls class VirtualBrowser extends EventEmitter __r_skip :['server','browser','sockets','compressor','registeredEventTypes', 'localState','consoleLog','rpcLog', 'nodes', 'resources'] constructor : (vbInfo) -> {@server, @id, @mountPoint, @appInstance} = vbInfo {@workerId} = @appInstance @appInstanceId = @appInstance.id weakRefToThis = Weak(this, cleanupBserver(@id)) @compressor = new Compressor() # make the compressed result deterministic for k in keywordsList @compressor.compress(k) @browser = new Browser(@id, weakRefToThis, @server.config) # we definetly don't want to send everything in config to client, # like database, emailer settings configToInclude = ['compression'] @_clientEngineConfig = {} for k, v of @server.config if configToInclude.indexOf(k) isnt -1 @_clientEngineConfig[k] = v @dateCreated = new Date() @localState = {} # TODO : Causes memory leak, must fix @browser.on 'PageLoaded', () => @browser.window.addEventListener 'hashchange', (event) => @broadcastEvent('UpdateLocationHash', @browser.window.location.hash) @sockets = [] @compressor.on 'newSymbol', (args) => for socket in @sockets socket.emit('newSymbol', args.original, args.compressed) @registeredEventTypes = [] # Indicates whether @browser is currently loading a page. # If so, we don't process client events/updates. @browserLoading = false # Indicates whether the browser has loaded its first page. @browserInitialized = false for own event, handler of DOMEventHandlers do (event, handler) => @browser.on event, () -> handler.apply(weakRefToThis, arguments) # referenced in api.getLogger, for client code only @_logger = debug("cloudbrowser:worker:browser:#{@id}") #@initLogs() if !@server.config.noLogs getID : () -> return @id getUrl : () -> return "#{@server.config.getHttpAddr()}#{routes.buildBrowserPath(@mountPoint, @appInstanceId, @id)}" getDateCreated : () -> return @dateCreated getName : () -> return @name setName : (name) -> @name = name getBrowser : () -> return @browser getMountPoint : () -> return @mountPoint getAppInstance : () -> return @appInstance getConnectedClients : () -> clients = [] for socket in @sockets {address} = socket {user} = socket.request clients.push address : address email : user return clients setLocalState : (property, value) -> @localState[property] = value getLocalState : (property) -> return @localState[property] redirect : (URL) -> @broadcastEvent('Redirect', URL) getSessions : (callback) -> mongoInterface = @server.mongoInterface getFromDB = (socket, callback) -> sessionID = socket.request.sessionID mongoInterface.getSession(sessionID, callback) Async.map(@sockets, getFromDB, callback) getFirstSession : (callback) -> mongoInterface = @server.mongoInterface sessionID = @sockets[0].request.sessionID mongoInterface.getSession(sessionID, callback) # arg can be an Application or URL string. load : (arg, callback) -> if not arg then arg = @server.applicationManager.find(@mountPoint) self = this @browser.load(arg, (err)-> return callback(err) if err? weakRefToThis = Weak(self, cleanupBserver(@id)) EmbedAPI(weakRefToThis) callback null ) # For testing purposes, return an emulated client for this browser. createTestClient : () -> if !process.env.TESTS_RUNNING throw new Error('Called createTestClient but not running tests.') return new TestClient(@id, @mountPoint) initLogs : () -> logDir = Path.resolve(__dirname, '..', '..', '..', 'logs') @consoleLogPath = Path.resolve(logDir, "#{@browser.id}.log") @consoleLog = FS.createWriteStream(@consoleLogPath) @consoleLog.write("Log opened: #{Date()}\n") @consoleLog.write("BrowserID: #{@browser.id}\n") if @server.config.traceProtocol rpcLogPath = Path.resolve(logDir, "#{@browser.id}-rpc.log") @rpcLog = FS.createWriteStream(rpcLogPath) close : () -> return if @closed @closed = true @stop() @compressor.removeAllListeners() @browser.close() @browser = null @emit('BrowserClose') @removeAllListeners() @consoleLog?.end() @rpcLog?.end() stop : (callback)-> for socket in @sockets socket.disconnect() socket.removeAllListeners() @sockets = [] callback(null) if callback? # this mountPoint is the real application this authentication vb delegates, # it is not the same as this vb's own mountPoint _redirectToGoogleAuth : (mountPoint)-> logger("prepare redirect to google auth") @getFirstSession (err, session) => if err? errorLogger(err) return sessionManager = @server.sessionManager # random string, google will pass it back, we use it to # check if the callback is forged or not state = Math.random().toString() sessionManager.setPropOnSession(session, 'googleAuthInfo', { mountPoint : mountPoint state : state }) # TODO make it configurable clientId = "<KEY>" clientSecret = "<KEY>" # cannot use customized port in redirect_uri, # see https://github.com/brianmcd/cloudbrowser/wiki/Authentication-with-Google redirectUri = "#{@server.config.getHttpAddr()}/checkauth" googleAuthUrl = url.format({ protocol : "https", host :"accounts.google.com", pathname : "/o/oauth2/auth", query : { "scope":"https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email", "state" : state, "redirect_uri" : redirectUri, "response_type" : "code", "client_id" : clientId, "access_type" : "offline" } }) logger("redirect to "+ googleAuthUrl) @redirect(googleAuthUrl) # Kill the browser once client has been authenticated @once 'NoClients', () => @close() logRPCMethod : (name, params) -> @rpcLog.write("#{name}(") if params.length == 0 return @rpcLog.write(")\n") lastIdx = params.length - 1 for param, idx in params if name == 'PageLoaded' str = Util.inspect(param, false, null).replace /[^\}],\n/g, (str) -> str[0] else str = Util.inspect(param, false, null).replace(/[\n\t]/g, '') @rpcLog.write(str) if idx == lastIdx @rpcLog.write(')\n') else @rpcLog.write(', ') broadcastEvent : (name, args...) -> if @server.config.traceProtocol @logRPCMethod(name, args) args.unshift(name) if @sockets.length is 1 @sockets[0].emitCompressed(args, @clientContext) return allArgs = [args] # the emitCompressed would modify args in deduplication/compression. # only clone things when needed for i in [1...@sockets.length] by 1 allArgs.push(lodash.cloneDeep(args)) for i in [0...@sockets.length] by 1 socket = @sockets[i] socket.emitCompressed(allArgs[i], @clientContext) return addSocket : (s) -> socket = SocketAdvice.adviceSocket({ socket : s buffer : true compression : @server.config.compression compressor : @compressor }) address = socket.request.connection.remoteAddress socket.address = address {user} = socket.request # if it is not issued from web browser, address is empty if address address = "#{address.address}:#{address.port}" userInfo = address : address email : user @emit('connect', userInfo) for own type, func of RPCMethods do (type, func) => socket.on type, () => if @server.config.traceProtocol @logRPCMethod(type, arguments) args = Array.prototype.slice.call(arguments) args.push(socket) # Weak ref not required here try func.apply(this, args) catch e console.log e socket.on 'disconnect', () => @sockets = (s for s in @sockets when s != socket) @emit('disconnect', address) if not @sockets.length @emit 'NoClients' socket.emit('SetConfig', @_clientEngineConfig) if !@browserInitialized return @sockets.push(socket) # the socket is added after the first pageloaded event emitted nodes = serialize(@browser.window.document, @resources, @browser.window.document, @server.config) compressionTable = undefined if @server.config.compression compressionTable = @compressor.textToSymbol socket.emit('PageLoaded', nodes, @registeredEventTypes, @browser.clientComponents, compressionTable) @sockets.push(socket) gc() if @server.config.traceMem @emit('ClientAdded') handleComponentRequest : (componentId, req, res)-> @browser.handleComponentRequest(componentId, req, res) # The VirtualBrowser constructor iterates over the properties in this object and # adds an event handler to the Browser for each one. The function name must # match the Browser event name. 'this' is set to the Browser via apply. DOMEventHandlers = PageLoading : (event) -> @nodes = new TaggedNodeCollection() if @server.config.resourceProxy @resources = new ResourceProxy(event.url) @browserLoading = true PageLoaded : () -> @browserInitialized = true @browserLoading = false nodes = serialize(@browser.window.document, @resources, @browser.window.document, @server.config) compressionTable = undefined if @server.config.compression compressionTable = @compressor.textToSymbol if @server.config.traceProtocol @logRPCMethod('PageLoaded', [nodes, @browser.clientComponents, compressionTable]) for socket in @sockets socket.emit('PageLoaded', nodes, @registeredEventTypes, @browser.clientComponents, compressionTable) if @server.config.traceMem gc() DocumentCreated : (event) -> @nodes.add(event.target) FrameLoaded : (event) -> {target} = event targetID = target.__nodeID @broadcastEvent('clear', targetID) @broadcastEvent('TagDocument', targetID, target.contentDocument.__nodeID) # Tag all newly created nodes. # This seems cleaner than having serializer do the tagging. DOMNodeInserted : (event) -> {target} = event if !target.__nodeID @nodes.add(target) if /[i]?frame/.test(target.tagName?.toLowerCase()) # TODO: This is a temp hack, we shouldn't rely on JSDOM's # MutationEvents. listener = target.addEventListener 'DOMNodeInsertedIntoDocument', () => target.removeEventListener('DOMNodeInsertedIntoDocument', listener) if isVisibleOnClient(target, @browser) @broadcastEvent('ResetFrame', target.__nodeID, target.contentDocument.__nodeID) ResetFrame : (event) -> return if @browserLoading {target} = event @broadcastEvent('ResetFrame', target.__nodeID, target.contentDocument.__nodeID) # TODO: consider doctypes. DOMNodeInsertedIntoDocument : (event) -> return if @browserLoading {target} = event nodes = serialize(target, @resources, @browser.window.document, @server.config) return if nodes.length == 0 # 'sibling' tells the client where to insert the top level node in # relation to its siblings. # We only need it for the top level node because nodes in its tree # are serialized in order. sibling = target.nextSibling while sibling?.tagName == 'SCRIPT' sibling = sibling.nextSibling @broadcastEvent('DOMNodeInsertedIntoDocument', nodes, sibling?.__nodeID) DOMNodeRemovedFromDocument : (event) -> return if @browserLoading event = @nodes.scrub(event) return if not event.relatedNode? # nodes use weak to auto reclaim garbage nodes @broadcastEvent('DOMNodeRemovedFromDocument', event.relatedNode, event.target) DOMAttrModified : (event) -> {attrName, newValue, attrChange, target} = event tagName = target.tagName?.toLowerCase() if /i?frame|script/.test(tagName) return isAddition = (attrChange == 'ADDITION') if isAddition && attrName == 'src' newValue = @resources.addURL(newValue) if @browserLoading return @broadcastEvent('DOMAttrModified', target.__nodeID, attrName, newValue, attrChange) AddEventListener : (event) -> {target, type} = event # click and change are always listened return if !clientEvents[type] || defaultEvents[type] idx = @registeredEventTypes.indexOf(type) return if idx != -1 @registeredEventTypes.push(type) @broadcastEvent('AddEventListener', type) EnteredTimer : () -> return if @browserLoading @broadcastEvent 'pauseRendering' # TODO DOM updates in timers should be batched, # there is no point to send any events to client if # there's no DOM updates happened in the timer ExitedTimer : () -> return if @browserLoading @broadcastEvent 'resumeRendering' ConsoleLog : (event) -> @consoleLog?.write(event.msg + '\n') # TODO: debug flag to enable line below. # @broadcastEvent('ConsoleLog', event) DOMStyleChanged : (event) -> return if @browserLoading @broadcastEvent('DOMStyleChanged', event.target.__nodeID, event.attribute, event.value) DOMPropertyModified : (event) -> return if @browserLoading @broadcastEvent('DOMPropertyModified', event.target.__nodeID, event.property, event.value) DOMCharacterDataModified : (event) -> return if @browserLoading @broadcastEvent('DOMCharacterDataModified', event.target.__nodeID, event.value) WindowMethodCalled : (event) -> return if @browserLoading @broadcastEvent('WindowMethodCalled', event.method, event.args) CreateComponent : (component) -> #console.log("Inside createComponent: #{@browserLoading}") return if @browserLoading {target, name, options} = component @broadcastEvent('CreateComponent', name, target.id, options) ComponentMethod : (event) -> return if @browserLoading {target, method, args} = event @broadcastEvent('ComponentMethod', target.__nodeID, method, args) TestDone : () -> throw new Error() if @browserLoading @broadcastEvent('TestDone') inputTags = ['INPUT', 'TEXTAREA'] RPCMethods = setAttribute : (targetId, attribute, value, socket) -> return if @browserLoading @clientContext={ from : socket target : targetId value : value } target = @nodes.get(targetId) if attribute == 'src' return if attribute == 'selectedIndex' return target[attribute] = value if inputTags.indexOf(target.tagName) >= 0 and attribute is "value" RPCMethods._setInputElementValue(target, value) else target.setAttribute(attribute, value) @clientContext=null _setInputElementValue : (target, value)-> # coping the implementation of textarea target.value = value # pan : to my knowledge, this id is used in benchmark tools to track which client instance # triggered 'processEvent', a better naming would be clientId processEvent : (event, id) -> if !@browserLoading # TODO # This bail out happens when an event fires on a component, which # only really exists client side and doesn't have a nodeID (and we # can't handle clicks on the server anyway). # Need something more elegant. return if !event.target # Swap nodeIDs with nodes clientEv = @nodes.unscrub(event) # Create an event we can dispatch on the server. serverEv = RPCMethods._createEvent(clientEv, @browser.window) @broadcastEvent('pauseRendering', id) clientEv.target.dispatchEvent(serverEv) @broadcastEvent('resumeRendering', id) if @server.config.traceMem gc() @server.eventTracker.inc() input : (events, id, socket)-> return if @browserLoading inputEvent = events[events.length-1] @clientContext={ from : socket target : inputEvent.target value : inputEvent._newValue } @broadcastEvent('pauseRendering', id) skipInputEvent = false for clientEv in events @nodes.unscrub(clientEv) switch clientEv.type when 'input' # it is always the last event if not skipInputEvent RPCMethods._setInputElementValue(clientEv.target, clientEv._newValue) RPCMethods._dispatchEvent(@, clientEv) break when 'keydown' serverEv = RPCMethods._dispatchEvent(@, clientEv) if serverEv skipInputEvent = serverEv._preventDefault break when 'keypress' if not skipInputEvent RPCMethods._dispatchEvent(@, clientEv) break else logger("unexpected event #{clientEv.type}") @broadcastEvent('resumeRendering', id) @clientContext=null _dispatchEvent : (vbrowser, clientEv)-> browser = vbrowser.browser if vbrowser.registeredEventTypes.indexOf(clientEv.type) >=0 or defaultEvents[clientEv.type]? serverEv = RPCMethods._createEvent(clientEv, browser.window) clientEv.target.dispatchEvent(serverEv) return serverEv # Takes a clientEv (an event generated on the client and sent over DNode) # and creates a corresponding event for the server's DOM. _createEvent : (clientEv, window) -> group = eventTypeToGroup[clientEv.type] event = window.document.createEvent(group) switch group when 'UIEvents' event.initUIEvent(clientEv.type, clientEv.bubbles, clientEv.cancelable, window, clientEv.detail) when 'HTMLEvents' event.initEvent(clientEv.type, clientEv.bubbles, clientEv.cancelable) when 'MouseEvents' event.initMouseEvent(clientEv.type, clientEv.bubbles, clientEv.cancelable, window, clientEv.detail, clientEv.screenX, clientEv.screenY, clientEv.clientX, clientEv.clientY, clientEv.ctrlKey, clientEv.altKey, clientEv.shiftKey, clientEv.metaKey, clientEv.button, clientEv.relatedTarget) # Eventually, we'll detect events from different browsers and # handle them accordingly. when 'KeyboardEvent' # For Chrome: char = String.fromCharCode(clientEv.which) locale = modifiersList = "" repeat = false if clientEv.altGraphKey then modifiersList += "AltGraph" if clientEv.altKey then modifiersList += "Alt" if clientEv.ctrlKey then modifiersList += "Ctrl" if clientEv.metaKey then modifiersList += "Meta" if clientEv.shiftKey then modifiersList += "Shift" # TODO: to get the "keyArg" parameter right, we'd need a lookup # table for: # http://www.w3.org/TR/DOM-Level-3-Events/#key-values-list event.initKeyboardEvent(clientEv.type, clientEv.bubbles, clientEv.cancelable, window, char, char, clientEv.keyLocation, modifiersList, repeat, locale) event.keyCode = clientEv.keyCode event.which = clientEv.which return event componentEvent : (params) -> {nodeID} = params node = @nodes.get(nodeID) if !node throw new Error("Invalid component nodeID: #{nodeID}") component = @browser.components[nodeID] if !component throw new Error("No component on node: #{nodeID}") for own key, val of params.attrs component.attrs?[key] = val @broadcastEvent('pauseRendering') event = @browser.window.document.createEvent('HTMLEvents') event.initEvent(params.event.type, false, false) event.info = params.event node.dispatchEvent(event) @broadcastEvent('resumeRendering') domEventHandlerNames = lodash.keys(DOMEventHandlers) # put frequent occurred events in front domEventHandlerNames = lodash.sortBy(domEventHandlerNames, (name)-> if name.indexOf('DOM') is 0 return 0 return 1 ) keywordsList = ['pauseRendering', 'resumeRendering', 'batch'].concat(domEventHandlerNames) module.exports = VirtualBrowser
true
Util = require('util') Path = require('path') FS = require('fs') Weak = require('weak') {EventEmitter} = require('events') url = require('url') debug = require('debug') lodash = require('lodash') Browser = require('./browser') ResourceProxy = require('./resource_proxy') SocketAdvice = require('./socket_advice') TestClient = require('./test_client') {serialize} = require('./serializer') routes = require('../application_manager/routes') Compressor = require('../../shared/compressor') EmbedAPI = require('../../api') TaggedNodeCollection = require('../../shared/tagged_node_collection') {isVisibleOnClient} = require('../../shared/utils') {eventTypeToGroup, clientEvents, defaultEvents} = require('../../shared/event_lists') logger = debug("cloudbrowser:worker:browser") errorLogger = debug("cloudbrowser:worker:error") # Defining callback at the highest level # see https://github.com/TooTallNate/node-weak#weak-callback-function-best-practices # Dummy callback, does nothing cleanupBserver = (id) -> return () -> logger "[Virtual Browser] - Garbage collected virtual browser #{id}" # Serves 1 Browser to n clients. Managing sockets, rpc calls class VirtualBrowser extends EventEmitter __r_skip :['server','browser','sockets','compressor','registeredEventTypes', 'localState','consoleLog','rpcLog', 'nodes', 'resources'] constructor : (vbInfo) -> {@server, @id, @mountPoint, @appInstance} = vbInfo {@workerId} = @appInstance @appInstanceId = @appInstance.id weakRefToThis = Weak(this, cleanupBserver(@id)) @compressor = new Compressor() # make the compressed result deterministic for k in keywordsList @compressor.compress(k) @browser = new Browser(@id, weakRefToThis, @server.config) # we definetly don't want to send everything in config to client, # like database, emailer settings configToInclude = ['compression'] @_clientEngineConfig = {} for k, v of @server.config if configToInclude.indexOf(k) isnt -1 @_clientEngineConfig[k] = v @dateCreated = new Date() @localState = {} # TODO : Causes memory leak, must fix @browser.on 'PageLoaded', () => @browser.window.addEventListener 'hashchange', (event) => @broadcastEvent('UpdateLocationHash', @browser.window.location.hash) @sockets = [] @compressor.on 'newSymbol', (args) => for socket in @sockets socket.emit('newSymbol', args.original, args.compressed) @registeredEventTypes = [] # Indicates whether @browser is currently loading a page. # If so, we don't process client events/updates. @browserLoading = false # Indicates whether the browser has loaded its first page. @browserInitialized = false for own event, handler of DOMEventHandlers do (event, handler) => @browser.on event, () -> handler.apply(weakRefToThis, arguments) # referenced in api.getLogger, for client code only @_logger = debug("cloudbrowser:worker:browser:#{@id}") #@initLogs() if !@server.config.noLogs getID : () -> return @id getUrl : () -> return "#{@server.config.getHttpAddr()}#{routes.buildBrowserPath(@mountPoint, @appInstanceId, @id)}" getDateCreated : () -> return @dateCreated getName : () -> return @name setName : (name) -> @name = name getBrowser : () -> return @browser getMountPoint : () -> return @mountPoint getAppInstance : () -> return @appInstance getConnectedClients : () -> clients = [] for socket in @sockets {address} = socket {user} = socket.request clients.push address : address email : user return clients setLocalState : (property, value) -> @localState[property] = value getLocalState : (property) -> return @localState[property] redirect : (URL) -> @broadcastEvent('Redirect', URL) getSessions : (callback) -> mongoInterface = @server.mongoInterface getFromDB = (socket, callback) -> sessionID = socket.request.sessionID mongoInterface.getSession(sessionID, callback) Async.map(@sockets, getFromDB, callback) getFirstSession : (callback) -> mongoInterface = @server.mongoInterface sessionID = @sockets[0].request.sessionID mongoInterface.getSession(sessionID, callback) # arg can be an Application or URL string. load : (arg, callback) -> if not arg then arg = @server.applicationManager.find(@mountPoint) self = this @browser.load(arg, (err)-> return callback(err) if err? weakRefToThis = Weak(self, cleanupBserver(@id)) EmbedAPI(weakRefToThis) callback null ) # For testing purposes, return an emulated client for this browser. createTestClient : () -> if !process.env.TESTS_RUNNING throw new Error('Called createTestClient but not running tests.') return new TestClient(@id, @mountPoint) initLogs : () -> logDir = Path.resolve(__dirname, '..', '..', '..', 'logs') @consoleLogPath = Path.resolve(logDir, "#{@browser.id}.log") @consoleLog = FS.createWriteStream(@consoleLogPath) @consoleLog.write("Log opened: #{Date()}\n") @consoleLog.write("BrowserID: #{@browser.id}\n") if @server.config.traceProtocol rpcLogPath = Path.resolve(logDir, "#{@browser.id}-rpc.log") @rpcLog = FS.createWriteStream(rpcLogPath) close : () -> return if @closed @closed = true @stop() @compressor.removeAllListeners() @browser.close() @browser = null @emit('BrowserClose') @removeAllListeners() @consoleLog?.end() @rpcLog?.end() stop : (callback)-> for socket in @sockets socket.disconnect() socket.removeAllListeners() @sockets = [] callback(null) if callback? # this mountPoint is the real application this authentication vb delegates, # it is not the same as this vb's own mountPoint _redirectToGoogleAuth : (mountPoint)-> logger("prepare redirect to google auth") @getFirstSession (err, session) => if err? errorLogger(err) return sessionManager = @server.sessionManager # random string, google will pass it back, we use it to # check if the callback is forged or not state = Math.random().toString() sessionManager.setPropOnSession(session, 'googleAuthInfo', { mountPoint : mountPoint state : state }) # TODO make it configurable clientId = "PI:KEY:<KEY>END_PI" clientSecret = "PI:KEY:<KEY>END_PI" # cannot use customized port in redirect_uri, # see https://github.com/brianmcd/cloudbrowser/wiki/Authentication-with-Google redirectUri = "#{@server.config.getHttpAddr()}/checkauth" googleAuthUrl = url.format({ protocol : "https", host :"accounts.google.com", pathname : "/o/oauth2/auth", query : { "scope":"https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email", "state" : state, "redirect_uri" : redirectUri, "response_type" : "code", "client_id" : clientId, "access_type" : "offline" } }) logger("redirect to "+ googleAuthUrl) @redirect(googleAuthUrl) # Kill the browser once client has been authenticated @once 'NoClients', () => @close() logRPCMethod : (name, params) -> @rpcLog.write("#{name}(") if params.length == 0 return @rpcLog.write(")\n") lastIdx = params.length - 1 for param, idx in params if name == 'PageLoaded' str = Util.inspect(param, false, null).replace /[^\}],\n/g, (str) -> str[0] else str = Util.inspect(param, false, null).replace(/[\n\t]/g, '') @rpcLog.write(str) if idx == lastIdx @rpcLog.write(')\n') else @rpcLog.write(', ') broadcastEvent : (name, args...) -> if @server.config.traceProtocol @logRPCMethod(name, args) args.unshift(name) if @sockets.length is 1 @sockets[0].emitCompressed(args, @clientContext) return allArgs = [args] # the emitCompressed would modify args in deduplication/compression. # only clone things when needed for i in [1...@sockets.length] by 1 allArgs.push(lodash.cloneDeep(args)) for i in [0...@sockets.length] by 1 socket = @sockets[i] socket.emitCompressed(allArgs[i], @clientContext) return addSocket : (s) -> socket = SocketAdvice.adviceSocket({ socket : s buffer : true compression : @server.config.compression compressor : @compressor }) address = socket.request.connection.remoteAddress socket.address = address {user} = socket.request # if it is not issued from web browser, address is empty if address address = "#{address.address}:#{address.port}" userInfo = address : address email : user @emit('connect', userInfo) for own type, func of RPCMethods do (type, func) => socket.on type, () => if @server.config.traceProtocol @logRPCMethod(type, arguments) args = Array.prototype.slice.call(arguments) args.push(socket) # Weak ref not required here try func.apply(this, args) catch e console.log e socket.on 'disconnect', () => @sockets = (s for s in @sockets when s != socket) @emit('disconnect', address) if not @sockets.length @emit 'NoClients' socket.emit('SetConfig', @_clientEngineConfig) if !@browserInitialized return @sockets.push(socket) # the socket is added after the first pageloaded event emitted nodes = serialize(@browser.window.document, @resources, @browser.window.document, @server.config) compressionTable = undefined if @server.config.compression compressionTable = @compressor.textToSymbol socket.emit('PageLoaded', nodes, @registeredEventTypes, @browser.clientComponents, compressionTable) @sockets.push(socket) gc() if @server.config.traceMem @emit('ClientAdded') handleComponentRequest : (componentId, req, res)-> @browser.handleComponentRequest(componentId, req, res) # The VirtualBrowser constructor iterates over the properties in this object and # adds an event handler to the Browser for each one. The function name must # match the Browser event name. 'this' is set to the Browser via apply. DOMEventHandlers = PageLoading : (event) -> @nodes = new TaggedNodeCollection() if @server.config.resourceProxy @resources = new ResourceProxy(event.url) @browserLoading = true PageLoaded : () -> @browserInitialized = true @browserLoading = false nodes = serialize(@browser.window.document, @resources, @browser.window.document, @server.config) compressionTable = undefined if @server.config.compression compressionTable = @compressor.textToSymbol if @server.config.traceProtocol @logRPCMethod('PageLoaded', [nodes, @browser.clientComponents, compressionTable]) for socket in @sockets socket.emit('PageLoaded', nodes, @registeredEventTypes, @browser.clientComponents, compressionTable) if @server.config.traceMem gc() DocumentCreated : (event) -> @nodes.add(event.target) FrameLoaded : (event) -> {target} = event targetID = target.__nodeID @broadcastEvent('clear', targetID) @broadcastEvent('TagDocument', targetID, target.contentDocument.__nodeID) # Tag all newly created nodes. # This seems cleaner than having serializer do the tagging. DOMNodeInserted : (event) -> {target} = event if !target.__nodeID @nodes.add(target) if /[i]?frame/.test(target.tagName?.toLowerCase()) # TODO: This is a temp hack, we shouldn't rely on JSDOM's # MutationEvents. listener = target.addEventListener 'DOMNodeInsertedIntoDocument', () => target.removeEventListener('DOMNodeInsertedIntoDocument', listener) if isVisibleOnClient(target, @browser) @broadcastEvent('ResetFrame', target.__nodeID, target.contentDocument.__nodeID) ResetFrame : (event) -> return if @browserLoading {target} = event @broadcastEvent('ResetFrame', target.__nodeID, target.contentDocument.__nodeID) # TODO: consider doctypes. DOMNodeInsertedIntoDocument : (event) -> return if @browserLoading {target} = event nodes = serialize(target, @resources, @browser.window.document, @server.config) return if nodes.length == 0 # 'sibling' tells the client where to insert the top level node in # relation to its siblings. # We only need it for the top level node because nodes in its tree # are serialized in order. sibling = target.nextSibling while sibling?.tagName == 'SCRIPT' sibling = sibling.nextSibling @broadcastEvent('DOMNodeInsertedIntoDocument', nodes, sibling?.__nodeID) DOMNodeRemovedFromDocument : (event) -> return if @browserLoading event = @nodes.scrub(event) return if not event.relatedNode? # nodes use weak to auto reclaim garbage nodes @broadcastEvent('DOMNodeRemovedFromDocument', event.relatedNode, event.target) DOMAttrModified : (event) -> {attrName, newValue, attrChange, target} = event tagName = target.tagName?.toLowerCase() if /i?frame|script/.test(tagName) return isAddition = (attrChange == 'ADDITION') if isAddition && attrName == 'src' newValue = @resources.addURL(newValue) if @browserLoading return @broadcastEvent('DOMAttrModified', target.__nodeID, attrName, newValue, attrChange) AddEventListener : (event) -> {target, type} = event # click and change are always listened return if !clientEvents[type] || defaultEvents[type] idx = @registeredEventTypes.indexOf(type) return if idx != -1 @registeredEventTypes.push(type) @broadcastEvent('AddEventListener', type) EnteredTimer : () -> return if @browserLoading @broadcastEvent 'pauseRendering' # TODO DOM updates in timers should be batched, # there is no point to send any events to client if # there's no DOM updates happened in the timer ExitedTimer : () -> return if @browserLoading @broadcastEvent 'resumeRendering' ConsoleLog : (event) -> @consoleLog?.write(event.msg + '\n') # TODO: debug flag to enable line below. # @broadcastEvent('ConsoleLog', event) DOMStyleChanged : (event) -> return if @browserLoading @broadcastEvent('DOMStyleChanged', event.target.__nodeID, event.attribute, event.value) DOMPropertyModified : (event) -> return if @browserLoading @broadcastEvent('DOMPropertyModified', event.target.__nodeID, event.property, event.value) DOMCharacterDataModified : (event) -> return if @browserLoading @broadcastEvent('DOMCharacterDataModified', event.target.__nodeID, event.value) WindowMethodCalled : (event) -> return if @browserLoading @broadcastEvent('WindowMethodCalled', event.method, event.args) CreateComponent : (component) -> #console.log("Inside createComponent: #{@browserLoading}") return if @browserLoading {target, name, options} = component @broadcastEvent('CreateComponent', name, target.id, options) ComponentMethod : (event) -> return if @browserLoading {target, method, args} = event @broadcastEvent('ComponentMethod', target.__nodeID, method, args) TestDone : () -> throw new Error() if @browserLoading @broadcastEvent('TestDone') inputTags = ['INPUT', 'TEXTAREA'] RPCMethods = setAttribute : (targetId, attribute, value, socket) -> return if @browserLoading @clientContext={ from : socket target : targetId value : value } target = @nodes.get(targetId) if attribute == 'src' return if attribute == 'selectedIndex' return target[attribute] = value if inputTags.indexOf(target.tagName) >= 0 and attribute is "value" RPCMethods._setInputElementValue(target, value) else target.setAttribute(attribute, value) @clientContext=null _setInputElementValue : (target, value)-> # coping the implementation of textarea target.value = value # pan : to my knowledge, this id is used in benchmark tools to track which client instance # triggered 'processEvent', a better naming would be clientId processEvent : (event, id) -> if !@browserLoading # TODO # This bail out happens when an event fires on a component, which # only really exists client side and doesn't have a nodeID (and we # can't handle clicks on the server anyway). # Need something more elegant. return if !event.target # Swap nodeIDs with nodes clientEv = @nodes.unscrub(event) # Create an event we can dispatch on the server. serverEv = RPCMethods._createEvent(clientEv, @browser.window) @broadcastEvent('pauseRendering', id) clientEv.target.dispatchEvent(serverEv) @broadcastEvent('resumeRendering', id) if @server.config.traceMem gc() @server.eventTracker.inc() input : (events, id, socket)-> return if @browserLoading inputEvent = events[events.length-1] @clientContext={ from : socket target : inputEvent.target value : inputEvent._newValue } @broadcastEvent('pauseRendering', id) skipInputEvent = false for clientEv in events @nodes.unscrub(clientEv) switch clientEv.type when 'input' # it is always the last event if not skipInputEvent RPCMethods._setInputElementValue(clientEv.target, clientEv._newValue) RPCMethods._dispatchEvent(@, clientEv) break when 'keydown' serverEv = RPCMethods._dispatchEvent(@, clientEv) if serverEv skipInputEvent = serverEv._preventDefault break when 'keypress' if not skipInputEvent RPCMethods._dispatchEvent(@, clientEv) break else logger("unexpected event #{clientEv.type}") @broadcastEvent('resumeRendering', id) @clientContext=null _dispatchEvent : (vbrowser, clientEv)-> browser = vbrowser.browser if vbrowser.registeredEventTypes.indexOf(clientEv.type) >=0 or defaultEvents[clientEv.type]? serverEv = RPCMethods._createEvent(clientEv, browser.window) clientEv.target.dispatchEvent(serverEv) return serverEv # Takes a clientEv (an event generated on the client and sent over DNode) # and creates a corresponding event for the server's DOM. _createEvent : (clientEv, window) -> group = eventTypeToGroup[clientEv.type] event = window.document.createEvent(group) switch group when 'UIEvents' event.initUIEvent(clientEv.type, clientEv.bubbles, clientEv.cancelable, window, clientEv.detail) when 'HTMLEvents' event.initEvent(clientEv.type, clientEv.bubbles, clientEv.cancelable) when 'MouseEvents' event.initMouseEvent(clientEv.type, clientEv.bubbles, clientEv.cancelable, window, clientEv.detail, clientEv.screenX, clientEv.screenY, clientEv.clientX, clientEv.clientY, clientEv.ctrlKey, clientEv.altKey, clientEv.shiftKey, clientEv.metaKey, clientEv.button, clientEv.relatedTarget) # Eventually, we'll detect events from different browsers and # handle them accordingly. when 'KeyboardEvent' # For Chrome: char = String.fromCharCode(clientEv.which) locale = modifiersList = "" repeat = false if clientEv.altGraphKey then modifiersList += "AltGraph" if clientEv.altKey then modifiersList += "Alt" if clientEv.ctrlKey then modifiersList += "Ctrl" if clientEv.metaKey then modifiersList += "Meta" if clientEv.shiftKey then modifiersList += "Shift" # TODO: to get the "keyArg" parameter right, we'd need a lookup # table for: # http://www.w3.org/TR/DOM-Level-3-Events/#key-values-list event.initKeyboardEvent(clientEv.type, clientEv.bubbles, clientEv.cancelable, window, char, char, clientEv.keyLocation, modifiersList, repeat, locale) event.keyCode = clientEv.keyCode event.which = clientEv.which return event componentEvent : (params) -> {nodeID} = params node = @nodes.get(nodeID) if !node throw new Error("Invalid component nodeID: #{nodeID}") component = @browser.components[nodeID] if !component throw new Error("No component on node: #{nodeID}") for own key, val of params.attrs component.attrs?[key] = val @broadcastEvent('pauseRendering') event = @browser.window.document.createEvent('HTMLEvents') event.initEvent(params.event.type, false, false) event.info = params.event node.dispatchEvent(event) @broadcastEvent('resumeRendering') domEventHandlerNames = lodash.keys(DOMEventHandlers) # put frequent occurred events in front domEventHandlerNames = lodash.sortBy(domEventHandlerNames, (name)-> if name.indexOf('DOM') is 0 return 0 return 1 ) keywordsList = ['pauseRendering', 'resumeRendering', 'batch'].concat(domEventHandlerNames) module.exports = VirtualBrowser
[ { "context": " return\n\n return\n\nsearches = [\n {\n term: \"f36b6a6123da50959741e2ce4d634f96ec668c56\"\n description: \"non-regex\"\n location: 241\n ", "end": 3247, "score": 0.987019419670105, "start": 3207, "tag": "KEY", "value": "f36b6a6123da50959741e2ce4d634f96ec668c56" ...
deps/npm/test/tap/search.coffee
lxe/io.coffee
0
# filled by since server callback cleanupCache = -> rimraf.sync cache return cleanup = -> cleanupCache() return setupCache = -> mkdirp.sync cache mkdirp.sync registryCache res = fs.writeFileSync(cacheJsonFile, stringifyUpdated(timeMock.epoch)) throw new Error("Creating cache file failed") if res return # Since request, always response with an _update time > the time requested # \033 == \u001B stringifyUpdated = (time) -> JSON.stringify _updated: String(time) common = require("../common-tap.js") test = require("tap").test rimraf = require("rimraf") mr = require("npm-registry-mock") fs = require("fs") path = require("path") pkg = path.resolve(__dirname, "search") cache = path.resolve(pkg, "cache") registryCache = path.resolve(cache, "localhost_1337", "-", "all") cacheJsonFile = path.resolve(registryCache, ".cache.json") mkdirp = require("mkdirp") timeMock = epoch: 1411727900 future: 1411727900 + 100 all: 1411727900 + 25 since: 0 EXEC_OPTS = {} mocks = sinceFuture: (server) -> server.filteringPathRegEx /startkey=[^&]*/g, (s) -> _allMock = JSON.parse(JSON.stringify(allMock)) timeMock.since = _allMock._updated = s.replace("startkey=", "") server.get("/-/all/since?stale=update_after&" + s).reply 200, _allMock s return allFutureUpdatedOnly: (server) -> server.get("/-/all").reply 200, stringifyUpdated(timeMock.future) return all: (server) -> server.get("/-/all").reply 200, allMock return test "No previous cache, init cache triggered by first search", (t) -> cleanupCache() mr port: common.port mocks: mocks.allFutureUpdatedOnly , (s) -> common.npm [ "search" "do not do extra search work on my behalf" "--registry" common.registry "--cache" cache "--loglevel" "silent" "--color" "always" ], EXEC_OPTS, (err, code) -> s.close() t.equal code, 0, "search finished successfully" t.ifErr err, "search finished successfully" t.ok fs.existsSync(cacheJsonFile), cacheJsonFile + " expected to have been created" cacheData = JSON.parse(fs.readFileSync(cacheJsonFile, "utf8")) t.equal cacheData._updated, String(timeMock.future) t.end() return return return test "previous cache, _updated set, should trigger since request", (t) -> m = (server) -> [ mocks.all mocks.sinceFuture ].forEach (m) -> m server return return cleanupCache() setupCache() mr port: common.port mocks: m , (s) -> common.npm [ "search" "do not do extra search work on my behalf" "--registry" common.registry "--cache" cache "--loglevel" "silly" "--color" "always" ], EXEC_OPTS, (err, code) -> s.close() t.equal code, 0, "search finished successfully" t.ifErr err, "search finished successfully" cacheData = JSON.parse(fs.readFileSync(cacheJsonFile, "utf8")) t.equal cacheData._updated, timeMock.since, "cache update time gotten from since response" cleanupCache() t.end() return return return searches = [ { term: "f36b6a6123da50959741e2ce4d634f96ec668c56" description: "non-regex" location: 241 } { term: "/f36b6a6123da50959741e2ce4d634f96ec668c56/" description: "regex" location: 241 } ] searches.forEach (search) -> test search.description + " search in color", (t) -> cleanupCache() mr port: common.port mocks: mocks.all , (s) -> common.npm [ "search" search.term "--registry" common.registry "--cache" cache "--loglevel" "silent" "--color" "always" ], EXEC_OPTS, (err, code, stdout) -> s.close() t.equal code, 0, "search finished successfully" t.ifErr err, "search finished successfully" markStart = "\u001b\\[[0-9][0-9]m" markEnd = "\u001b\\[0m" re = new RegExp(markStart + ".*?" + markEnd) cnt = stdout.search(re) t.equal cnt, search.location, search.description + " search for " + search.term t.end() return return return return test "cleanup", (t) -> cleanup() t.end() return allMock = _updated: timeMock.all "generator-frontcow": name: "generator-frontcow" description: "f36b6a6123da50959741e2ce4d634f96ec668c56 This is a fake description to ensure we do not accidentally search the real npm registry or use some kind of cache" "dist-tags": latest: "0.1.19" maintainers: [ name: "bcabanes" email: "contact@benjamincabanes.com" ] homepage: "https://github.com/bcabanes/generator-frontcow" keywords: [ "sass" "frontend" "yeoman-generator" "atomic" "design" "sass" "foundation" "foundation5" "atomic design" "bourbon" "polyfill" "font awesome" ] repository: type: "git" url: "https://github.com/bcabanes/generator-frontcow" author: name: "ben" email: "contact@benjamincabanes.com" url: "https://github.com/bcabanes" bugs: url: "https://github.com/bcabanes/generator-frontcow/issues" license: "MIT" readmeFilename: "README.md" time: modified: "2014-10-03T02:26:18.406Z" versions: "0.1.19": "latest" marko: name: "marko" description: "Marko is an extensible, streaming, asynchronous, high performance, HTML-based templating language that can be used in Node.js or in the browser." "dist-tags": latest: "1.2.16" maintainers: [ { name: "pnidem" email: "pnidem@gmail.com" } { name: "philidem" email: "phillip.idem@gmail.com" } ] homepage: "https://github.com/raptorjs/marko" keywords: [ "templating" "template" "async" "streaming" ] repository: type: "git" url: "https://github.com/raptorjs/marko.git" author: name: "Patrick Steele-Idem" email: "pnidem@gmail.com" bugs: url: "https://github.com/raptorjs/marko/issues" license: "Apache License v2.0" readmeFilename: "README.md" users: pnidem: true time: modified: "2014-10-03T02:27:31.775Z" versions: "1.2.16": "latest"
161468
# filled by since server callback cleanupCache = -> rimraf.sync cache return cleanup = -> cleanupCache() return setupCache = -> mkdirp.sync cache mkdirp.sync registryCache res = fs.writeFileSync(cacheJsonFile, stringifyUpdated(timeMock.epoch)) throw new Error("Creating cache file failed") if res return # Since request, always response with an _update time > the time requested # \033 == \u001B stringifyUpdated = (time) -> JSON.stringify _updated: String(time) common = require("../common-tap.js") test = require("tap").test rimraf = require("rimraf") mr = require("npm-registry-mock") fs = require("fs") path = require("path") pkg = path.resolve(__dirname, "search") cache = path.resolve(pkg, "cache") registryCache = path.resolve(cache, "localhost_1337", "-", "all") cacheJsonFile = path.resolve(registryCache, ".cache.json") mkdirp = require("mkdirp") timeMock = epoch: 1411727900 future: 1411727900 + 100 all: 1411727900 + 25 since: 0 EXEC_OPTS = {} mocks = sinceFuture: (server) -> server.filteringPathRegEx /startkey=[^&]*/g, (s) -> _allMock = JSON.parse(JSON.stringify(allMock)) timeMock.since = _allMock._updated = s.replace("startkey=", "") server.get("/-/all/since?stale=update_after&" + s).reply 200, _allMock s return allFutureUpdatedOnly: (server) -> server.get("/-/all").reply 200, stringifyUpdated(timeMock.future) return all: (server) -> server.get("/-/all").reply 200, allMock return test "No previous cache, init cache triggered by first search", (t) -> cleanupCache() mr port: common.port mocks: mocks.allFutureUpdatedOnly , (s) -> common.npm [ "search" "do not do extra search work on my behalf" "--registry" common.registry "--cache" cache "--loglevel" "silent" "--color" "always" ], EXEC_OPTS, (err, code) -> s.close() t.equal code, 0, "search finished successfully" t.ifErr err, "search finished successfully" t.ok fs.existsSync(cacheJsonFile), cacheJsonFile + " expected to have been created" cacheData = JSON.parse(fs.readFileSync(cacheJsonFile, "utf8")) t.equal cacheData._updated, String(timeMock.future) t.end() return return return test "previous cache, _updated set, should trigger since request", (t) -> m = (server) -> [ mocks.all mocks.sinceFuture ].forEach (m) -> m server return return cleanupCache() setupCache() mr port: common.port mocks: m , (s) -> common.npm [ "search" "do not do extra search work on my behalf" "--registry" common.registry "--cache" cache "--loglevel" "silly" "--color" "always" ], EXEC_OPTS, (err, code) -> s.close() t.equal code, 0, "search finished successfully" t.ifErr err, "search finished successfully" cacheData = JSON.parse(fs.readFileSync(cacheJsonFile, "utf8")) t.equal cacheData._updated, timeMock.since, "cache update time gotten from since response" cleanupCache() t.end() return return return searches = [ { term: "<KEY>" description: "non-regex" location: 241 } { term: "/f<KEY>ce4d634f96ec668c56/" description: "regex" location: 241 } ] searches.forEach (search) -> test search.description + " search in color", (t) -> cleanupCache() mr port: common.port mocks: mocks.all , (s) -> common.npm [ "search" search.term "--registry" common.registry "--cache" cache "--loglevel" "silent" "--color" "always" ], EXEC_OPTS, (err, code, stdout) -> s.close() t.equal code, 0, "search finished successfully" t.ifErr err, "search finished successfully" markStart = "\u001b\\[[0-9][0-9]m" markEnd = "\u001b\\[0m" re = new RegExp(markStart + ".*?" + markEnd) cnt = stdout.search(re) t.equal cnt, search.location, search.description + " search for " + search.term t.end() return return return return test "cleanup", (t) -> cleanup() t.end() return allMock = _updated: timeMock.all "generator-frontcow": name: "generator-frontcow" description: "f36b6a6123da50959741e2ce4d634f96ec668c56 This is a fake description to ensure we do not accidentally search the real npm registry or use some kind of cache" "dist-tags": latest: "0.1.19" maintainers: [ name: "bcabanes" email: "<EMAIL>" ] homepage: "https://github.com/bcabanes/generator-frontcow" keywords: [ "sass" "frontend" "yeoman-generator" "atomic" "design" "sass" "foundation" "foundation5" "atomic design" "bourbon" "polyfill" "font awesome" ] repository: type: "git" url: "https://github.com/bcabanes/generator-frontcow" author: name: "ben" email: "<EMAIL>" url: "https://github.com/bcabanes" bugs: url: "https://github.com/bcabanes/generator-frontcow/issues" license: "MIT" readmeFilename: "README.md" time: modified: "2014-10-03T02:26:18.406Z" versions: "0.1.19": "latest" marko: name: "marko" description: "Marko is an extensible, streaming, asynchronous, high performance, HTML-based templating language that can be used in Node.js or in the browser." "dist-tags": latest: "1.2.16" maintainers: [ { name: "pnidem" email: "<EMAIL>" } { name: "philidem" email: "<EMAIL>" } ] homepage: "https://github.com/raptorjs/marko" keywords: [ "templating" "template" "async" "streaming" ] repository: type: "git" url: "https://github.com/raptorjs/marko.git" author: name: "<NAME>" email: "<EMAIL>" bugs: url: "https://github.com/raptorjs/marko/issues" license: "Apache License v2.0" readmeFilename: "README.md" users: pnidem: true time: modified: "2014-10-03T02:27:31.775Z" versions: "1.2.16": "latest"
true
# filled by since server callback cleanupCache = -> rimraf.sync cache return cleanup = -> cleanupCache() return setupCache = -> mkdirp.sync cache mkdirp.sync registryCache res = fs.writeFileSync(cacheJsonFile, stringifyUpdated(timeMock.epoch)) throw new Error("Creating cache file failed") if res return # Since request, always response with an _update time > the time requested # \033 == \u001B stringifyUpdated = (time) -> JSON.stringify _updated: String(time) common = require("../common-tap.js") test = require("tap").test rimraf = require("rimraf") mr = require("npm-registry-mock") fs = require("fs") path = require("path") pkg = path.resolve(__dirname, "search") cache = path.resolve(pkg, "cache") registryCache = path.resolve(cache, "localhost_1337", "-", "all") cacheJsonFile = path.resolve(registryCache, ".cache.json") mkdirp = require("mkdirp") timeMock = epoch: 1411727900 future: 1411727900 + 100 all: 1411727900 + 25 since: 0 EXEC_OPTS = {} mocks = sinceFuture: (server) -> server.filteringPathRegEx /startkey=[^&]*/g, (s) -> _allMock = JSON.parse(JSON.stringify(allMock)) timeMock.since = _allMock._updated = s.replace("startkey=", "") server.get("/-/all/since?stale=update_after&" + s).reply 200, _allMock s return allFutureUpdatedOnly: (server) -> server.get("/-/all").reply 200, stringifyUpdated(timeMock.future) return all: (server) -> server.get("/-/all").reply 200, allMock return test "No previous cache, init cache triggered by first search", (t) -> cleanupCache() mr port: common.port mocks: mocks.allFutureUpdatedOnly , (s) -> common.npm [ "search" "do not do extra search work on my behalf" "--registry" common.registry "--cache" cache "--loglevel" "silent" "--color" "always" ], EXEC_OPTS, (err, code) -> s.close() t.equal code, 0, "search finished successfully" t.ifErr err, "search finished successfully" t.ok fs.existsSync(cacheJsonFile), cacheJsonFile + " expected to have been created" cacheData = JSON.parse(fs.readFileSync(cacheJsonFile, "utf8")) t.equal cacheData._updated, String(timeMock.future) t.end() return return return test "previous cache, _updated set, should trigger since request", (t) -> m = (server) -> [ mocks.all mocks.sinceFuture ].forEach (m) -> m server return return cleanupCache() setupCache() mr port: common.port mocks: m , (s) -> common.npm [ "search" "do not do extra search work on my behalf" "--registry" common.registry "--cache" cache "--loglevel" "silly" "--color" "always" ], EXEC_OPTS, (err, code) -> s.close() t.equal code, 0, "search finished successfully" t.ifErr err, "search finished successfully" cacheData = JSON.parse(fs.readFileSync(cacheJsonFile, "utf8")) t.equal cacheData._updated, timeMock.since, "cache update time gotten from since response" cleanupCache() t.end() return return return searches = [ { term: "PI:KEY:<KEY>END_PI" description: "non-regex" location: 241 } { term: "/fPI:KEY:<KEY>END_PIce4d634f96ec668c56/" description: "regex" location: 241 } ] searches.forEach (search) -> test search.description + " search in color", (t) -> cleanupCache() mr port: common.port mocks: mocks.all , (s) -> common.npm [ "search" search.term "--registry" common.registry "--cache" cache "--loglevel" "silent" "--color" "always" ], EXEC_OPTS, (err, code, stdout) -> s.close() t.equal code, 0, "search finished successfully" t.ifErr err, "search finished successfully" markStart = "\u001b\\[[0-9][0-9]m" markEnd = "\u001b\\[0m" re = new RegExp(markStart + ".*?" + markEnd) cnt = stdout.search(re) t.equal cnt, search.location, search.description + " search for " + search.term t.end() return return return return test "cleanup", (t) -> cleanup() t.end() return allMock = _updated: timeMock.all "generator-frontcow": name: "generator-frontcow" description: "f36b6a6123da50959741e2ce4d634f96ec668c56 This is a fake description to ensure we do not accidentally search the real npm registry or use some kind of cache" "dist-tags": latest: "0.1.19" maintainers: [ name: "bcabanes" email: "PI:EMAIL:<EMAIL>END_PI" ] homepage: "https://github.com/bcabanes/generator-frontcow" keywords: [ "sass" "frontend" "yeoman-generator" "atomic" "design" "sass" "foundation" "foundation5" "atomic design" "bourbon" "polyfill" "font awesome" ] repository: type: "git" url: "https://github.com/bcabanes/generator-frontcow" author: name: "ben" email: "PI:EMAIL:<EMAIL>END_PI" url: "https://github.com/bcabanes" bugs: url: "https://github.com/bcabanes/generator-frontcow/issues" license: "MIT" readmeFilename: "README.md" time: modified: "2014-10-03T02:26:18.406Z" versions: "0.1.19": "latest" marko: name: "marko" description: "Marko is an extensible, streaming, asynchronous, high performance, HTML-based templating language that can be used in Node.js or in the browser." "dist-tags": latest: "1.2.16" maintainers: [ { name: "pnidem" email: "PI:EMAIL:<EMAIL>END_PI" } { name: "philidem" email: "PI:EMAIL:<EMAIL>END_PI" } ] homepage: "https://github.com/raptorjs/marko" keywords: [ "templating" "template" "async" "streaming" ] repository: type: "git" url: "https://github.com/raptorjs/marko.git" author: name: "PI:NAME:<NAME>END_PI" email: "PI:EMAIL:<EMAIL>END_PI" bugs: url: "https://github.com/raptorjs/marko/issues" license: "Apache License v2.0" readmeFilename: "README.md" users: pnidem: true time: modified: "2014-10-03T02:27:31.775Z" versions: "1.2.16": "latest"
[ { "context": " WebMoney classes\n#\n# June, 2013 year\n#\n# Author - Vladimir Andreev\n#\n# E-Mail: volodya@netfolder.ru\n\n# WebMoney util", "end": 68, "score": 0.9998784065246582, "start": 52, "tag": "NAME", "value": "Vladimir Andreev" }, { "context": "013 year\n#\n# Author - Vladi...
src/index.coffee
listepo/webmoney
1
# WebMoney classes # # June, 2013 year # # Author - Vladimir Andreev # # E-Mail: volodya@netfolder.ru # WebMoney utils exports.Key = require('./key') exports.Signer = require('./signer') # WebMoney services exports.W3Service = require('./service/w3') exports.PassportService = require('./service/passport') exports.MerchantService = require('./service/merchant') exports.ArbitrageService = require('./service/arbitrage') exports.TransferService = require('./service/transfer')
18848
# WebMoney classes # # June, 2013 year # # Author - <NAME> # # E-Mail: <EMAIL> # WebMoney utils exports.Key = require('./key') exports.Signer = require('./signer') # WebMoney services exports.W3Service = require('./service/w3') exports.PassportService = require('./service/passport') exports.MerchantService = require('./service/merchant') exports.ArbitrageService = require('./service/arbitrage') exports.TransferService = require('./service/transfer')
true
# WebMoney classes # # June, 2013 year # # Author - PI:NAME:<NAME>END_PI # # E-Mail: PI:EMAIL:<EMAIL>END_PI # WebMoney utils exports.Key = require('./key') exports.Signer = require('./signer') # WebMoney services exports.W3Service = require('./service/w3') exports.PassportService = require('./service/passport') exports.MerchantService = require('./service/merchant') exports.ArbitrageService = require('./service/arbitrage') exports.TransferService = require('./service/transfer')
[ { "context": "(next) ->\n bodyString = JSON.stringify email: \"dorian@ethylocle.com\", password: \"1234\"\n headers = GetOptionsWithHe", "end": 1995, "score": 0.9999228715896606, "start": 1975, "tag": "EMAIL", "value": "dorian@ethylocle.com" }, { "context": "ringify email: \"do...
routes/test/user.coffee
dorianb/Web-application---Ethylocl-
0
rimraf = require 'rimraf' should = require 'should' db = require '../../lib/factory/model' app = require '../../lib/host/app' https = require 'https' fs = require 'fs' port = process.env.PORT || 443 server = undefined process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0" hskey = fs.readFileSync __dirname + "/../../resource/key/key.pem" hscert = fs.readFileSync __dirname + "/../../resource/key/cert.pem" options = key: hskey cert: hscert defaultGetOptions = (path) -> options = "host": "localhost" "port": port "path": path "method": "POST" GetOptionsWithHeaders = (path, body, cookie) -> headers = 'Content-Type': 'application/json' 'Content-Length': body.length 'Cookie': cookie || "" options = "host": "localhost" "port": port "path": path "method": "POST" "headers": headers describe 'User routes', -> before (next) -> server = https.createServer(options, app).listen port, (err, result) -> return next err if err next() after (next) -> server.close() next() beforeEach (next) -> rimraf "#{__dirname}/../../db/tmp/user", next it 'should exist', (next) -> should.exist app next() it "should be listening at localhost:#{port}", (next) -> headers = defaultGetOptions '/' headers.method = "GET" https.get headers, (res) -> res.statusCode.should.eql 200 next() it 'Sign in without body (without email or password)', (next) -> headers = defaultGetOptions '/usr/signin' https.get headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql false res.data.should.eql "Email ou mot de passe manquant" next() it 'Sign in without signed up', (next) -> bodyString = JSON.stringify email: "dorian@ethylocle.com", password: "1234" headers = GetOptionsWithHeaders '/usr/signin', bodyString req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql false res.data.should.eql "Email ou mot de passe incorrect" next() req.write bodyString req.end() it 'Sign up correctly', (next) -> bodyString = JSON.stringify email: "dorian@ethylocle.com", password: "12345678" headers = GetOptionsWithHeaders '/usr/signup', bodyString req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql true should.not.exists res.data next() req.write bodyString req.end() it 'Sign up without email or password', (next) -> bodyString = JSON.stringify password: "1234" headers = GetOptionsWithHeaders '/usr/signup', bodyString req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql false res.data.should.eql "Email ou mot de passe manquant" next() req.write bodyString req.end() it 'Sign up without a valid email', (next) -> bodyString = JSON.stringify email: "dorianethylocle.com", password: "1234" headers = GetOptionsWithHeaders '/usr/signup', bodyString req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql false res.data.should.eql "Cette adresse email est invalide" next() req.write bodyString req.end() it 'Sign up without a strong password', (next) -> bodyString = JSON.stringify email: "dorian@ethylocle.com", password: "1234" headers = GetOptionsWithHeaders '/usr/signup', bodyString req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql false res.data.should.eql "Le mot de passe doit comporter au moins 8 caractères" next() req.write bodyString req.end() it 'Sign in after signed up', (next) -> bodyString = JSON.stringify email: "dorian@ethylocle.com", password: "12345678" headers = GetOptionsWithHeaders '/usr/signup', bodyString req = https.request headers, (res) -> res.on 'data', (data) -> res.on 'end', (err) -> return next err if err bodyString = JSON.stringify email: "dorian@ethylocle.com", password: "12345678" headers = GetOptionsWithHeaders '/usr/signin', bodyString req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql true should.not.exists res.data next() req.write bodyString req.end() req.write bodyString req.end() it 'Check password without signed in', (next) -> bodyString = JSON.stringify password: "12345678" headers = GetOptionsWithHeaders '/usr/checkpassword', bodyString req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql false res.data.should.eql "Authentification requise" next() req.write bodyString req.end() it 'Check password after signed up', (next) -> bodyString = JSON.stringify email: "dorian@ethylocle.com", password: "12345678" headers = GetOptionsWithHeaders '/usr/signup', bodyString req = https.request headers, (res) -> res.on 'data', (data) -> res.on 'end', (err) -> return next err if err bodyString = JSON.stringify password: "12345678" headers = GetOptionsWithHeaders '/usr/checkpassword', bodyString, res.headers['set-cookie'] req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql true should.not.exists res.data next() req.write bodyString req.end() req.write bodyString req.end() it 'Check password without password (after signed up)', (next) -> bodyString = JSON.stringify email: "dorian@ethylocle.com", password: "12345678" headers = GetOptionsWithHeaders '/usr/signup', bodyString req = https.request headers, (res) -> res.on 'data', (data) -> res.on 'end', (err) -> return next err if err bodyString = JSON.stringify email: "12345678" headers = GetOptionsWithHeaders '/usr/checkpassword', bodyString, res.headers['set-cookie'] req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql false res.data.should.eql "Mot de passe manquant" next() req.write bodyString req.end() req.write bodyString req.end() it 'Update email without signed in', (next) -> bodyString = JSON.stringify email: "dorian@ethylocle.com" headers = GetOptionsWithHeaders '/usr/updateemail', bodyString req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql false res.data.should.eql "Authentification requise" next() req.write bodyString req.end() it 'Update email after signed up', (next) -> bodyString = JSON.stringify email: "dorian@ethylocle.com", password: "12345678" headers = GetOptionsWithHeaders '/usr/signup', bodyString req = https.request headers, (res) -> res.on 'data', (data) -> res.on 'end', (err) -> return next err if err bodyString = JSON.stringify email: "robin@ethylocle.com" headers = GetOptionsWithHeaders '/usr/updateemail', bodyString, res.headers['set-cookie'] req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql true should.not.exists res.data next() req.write bodyString req.end() req.write bodyString req.end() it 'Update email without email (after signed up)', (next) -> bodyString = JSON.stringify email: "dorian@ethylocle.com", password: "12345678" headers = GetOptionsWithHeaders '/usr/signup', bodyString req = https.request headers, (res) -> res.on 'data', (data) -> res.on 'end', (err) -> return next err if err headers = GetOptionsWithHeaders '/usr/updateemail', "", res.headers['set-cookie'] req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql false res.data.should.eql "Email manquant" next() req.end() req.write bodyString req.end() it 'Update email with an unvalid email (after signed up)', (next) -> bodyString = JSON.stringify email: "dorian@ethylocle.com", password: "12345678" headers = GetOptionsWithHeaders '/usr/signup', bodyString req = https.request headers, (res) -> res.on 'data', (data) -> res.on 'end', (err) -> return next err if err bodyString = JSON.stringify email: "robinethylocle.com" headers = GetOptionsWithHeaders '/usr/updateemail', bodyString, res.headers['set-cookie'] req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql false res.data.should.eql "Cette adresse email est invalide" next() req.write bodyString req.end() req.write bodyString req.end() it 'Update without signed in', (next) -> bodyString = JSON.stringify email: "maoqiao@ethylocle.com", lastName: "Bagur", firstName: "Dorian" headers = GetOptionsWithHeaders '/usr/update', bodyString req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql false res.data.should.eql "Authentification requise" next() req.write bodyString req.end() it 'Update after signed up', (next) -> bodyString = JSON.stringify email: "dorian@ethylocle.com", password: "12345678" headers = GetOptionsWithHeaders '/usr/signup', bodyString req = https.request headers, (res) -> res.on 'data', (data) -> res.on 'end', (err) -> return next err if err bodyString = JSON.stringify email: "maoqiao@ethylocle.com", lastName: "Bagur", firstName: "Dorian", password: "87654321" headers = GetOptionsWithHeaders '/usr/update', bodyString, res.headers['set-cookie'] req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql true should.not.exists res.data next() req.write bodyString req.end() req.write bodyString req.end() it 'Update without arguments (after signed up)', (next) -> bodyString = JSON.stringify email: "dorian@ethylocle.com", password: "12345678" headers = GetOptionsWithHeaders '/usr/signup', bodyString req = https.request headers, (res) -> res.on 'data', (data) -> res.on 'end', (err) -> return next err if err bodyString = "" headers = GetOptionsWithHeaders '/usr/update', bodyString, res.headers['set-cookie'] req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql false res.data.should.eql "La requête ne comporte aucun argument" next() req.write bodyString req.end() req.write bodyString req.end() it 'Update without password (after signed up)', (next) -> bodyString = JSON.stringify email: "dorian@ethylocle.com", password: "12345678" headers = GetOptionsWithHeaders '/usr/signup', bodyString req = https.request headers, (res) -> res.on 'data', (data) -> res.on 'end', (err) -> return next err if err bodyString = JSON.stringify email: "maoqiao@ethylocle.com", lastName: "Bagur", firstName: "Dorian" headers = GetOptionsWithHeaders '/usr/update', bodyString, res.headers['set-cookie'] req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql true should.not.exists res.data next() req.write bodyString req.end() req.write bodyString req.end() it 'Update with an unvalid password (after signed up)', (next) -> bodyString = JSON.stringify email: "dorian@ethylocle.com", password: "12345678" headers = GetOptionsWithHeaders '/usr/signup', bodyString req = https.request headers, (res) -> res.on 'data', (data) -> res.on 'end', (err) -> return next err if err bodyString = JSON.stringify password: "1234" headers = GetOptionsWithHeaders '/usr/update', bodyString, res.headers['set-cookie'] req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql false res.data.should.eql "Le mot de passe doit comporter au moins 8 caractères" next() req.write bodyString req.end() req.write bodyString req.end() it 'Get without signed in', (next) -> headers = GetOptionsWithHeaders '/usr/get', "" req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql false res.data.should.eql "Authentification requise" next() req.end() it 'Get (after signed up)', (next) -> bodyString = JSON.stringify email: "dorian@ethylocle.com", password: "12345678" headers = GetOptionsWithHeaders '/usr/signup', bodyString req = https.request headers, (res) -> res.on 'data', (data) -> res.on 'end', (err) -> return next err if err headers = GetOptionsWithHeaders '/usr/get', "", res.headers['set-cookie'] req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql true Object.keys(res.data).length.should.eql 2 res.data.id.should.eql '0' res.data.email.should.eql 'dorian@ethylocle.com' next() req.end() req.write bodyString req.end() it 'Get by id without signed in', (next) -> headers = GetOptionsWithHeaders '/usr/getbyid', "" req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql false res.data.should.eql "Authentification requise" next() req.end() it 'Get by id (after signed up)', (next) -> bodyString = JSON.stringify email: "dorian@ethylocle.com", password: "12345678" headers = GetOptionsWithHeaders '/usr/signup', bodyString req = https.request headers, (res) -> res.on 'data', (data) -> res.on 'end', (err) -> return next err if err bodyString = JSON.stringify id: "0" headers = GetOptionsWithHeaders '/usr/getbyid', bodyString, res.headers['set-cookie'] req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql true Object.keys(res.data).length.should.eql 1 res.data.id.should.eql '0' next() req.write bodyString req.end() req.write bodyString req.end() it 'Get by id without id (after signed up)', (next) -> bodyString = JSON.stringify email: "dorian@ethylocle.com", password: "12345678" headers = GetOptionsWithHeaders '/usr/signup', bodyString req = https.request headers, (res) -> res.on 'data', (data) -> res.on 'end', (err) -> return next err if err headers = GetOptionsWithHeaders '/usr/getbyid', "", res.headers['set-cookie'] req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql false res.data.should.eql "Identifiant manquant" next() req.end() req.write bodyString req.end() it 'Get by id with null id (after signed up)', (next) -> bodyString = JSON.stringify email: "dorian@ethylocle.com", password: "12345678" headers = GetOptionsWithHeaders '/usr/signup', bodyString req = https.request headers, (res) -> res.on 'data', (data) -> res.on 'end', (err) -> return next err if err bodyString = JSON.stringify id: null headers = GetOptionsWithHeaders '/usr/getbyid', bodyString, res.headers['set-cookie'] req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body res.result.should.eql false res.data.should.eql "L'utilisateur n'existe pas" next() req.write bodyString req.end() req.write bodyString req.end() it 'Delete without signed in', (next) -> headers = GetOptionsWithHeaders '/usr/delete', "" req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql false res.data.should.eql "Authentification requise" next() req.end() it 'Delete (after signed up)', (next) -> bodyString = JSON.stringify email: "dorian@ethylocle.com", password: "12345678" headers = GetOptionsWithHeaders '/usr/signup', bodyString req = https.request headers, (res) -> res.on 'data', (data) -> res.on 'end', (err) -> return next err if err bodyString = "" headers = GetOptionsWithHeaders '/usr/delete', bodyString, res.headers['set-cookie'] req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql true should.not.exists res.data headers = GetOptionsWithHeaders '/usr/delete', "" req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql false res.data.should.eql "Authentification requise" next() req.end() req.write bodyString req.end() req.write bodyString req.end() it 'Sign out (after signed up)', (next) -> bodyString = JSON.stringify email: "dorian@ethylocle.com", password: "12345678" headers = GetOptionsWithHeaders '/usr/signup', bodyString req = https.request headers, (res) -> res.on 'data', (data) -> res.on 'end', (err) -> return next err if err bodyString = "" headers = GetOptionsWithHeaders '/usr/signout', bodyString, res.headers['set-cookie'] req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql true should.not.exists res.data headers = GetOptionsWithHeaders '/usr/signout', "" req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql false res.data.should.eql "Authentification requise" next() req.end() req.write bodyString req.end() req.write bodyString req.end()
87975
rimraf = require 'rimraf' should = require 'should' db = require '../../lib/factory/model' app = require '../../lib/host/app' https = require 'https' fs = require 'fs' port = process.env.PORT || 443 server = undefined process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0" hskey = fs.readFileSync __dirname + "/../../resource/key/key.pem" hscert = fs.readFileSync __dirname + "/../../resource/key/cert.pem" options = key: hskey cert: hscert defaultGetOptions = (path) -> options = "host": "localhost" "port": port "path": path "method": "POST" GetOptionsWithHeaders = (path, body, cookie) -> headers = 'Content-Type': 'application/json' 'Content-Length': body.length 'Cookie': cookie || "" options = "host": "localhost" "port": port "path": path "method": "POST" "headers": headers describe 'User routes', -> before (next) -> server = https.createServer(options, app).listen port, (err, result) -> return next err if err next() after (next) -> server.close() next() beforeEach (next) -> rimraf "#{__dirname}/../../db/tmp/user", next it 'should exist', (next) -> should.exist app next() it "should be listening at localhost:#{port}", (next) -> headers = defaultGetOptions '/' headers.method = "GET" https.get headers, (res) -> res.statusCode.should.eql 200 next() it 'Sign in without body (without email or password)', (next) -> headers = defaultGetOptions '/usr/signin' https.get headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql false res.data.should.eql "Email ou mot de passe manquant" next() it 'Sign in without signed up', (next) -> bodyString = JSON.stringify email: "<EMAIL>", password: "<PASSWORD>" headers = GetOptionsWithHeaders '/usr/signin', bodyString req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql false res.data.should.eql "Email ou mot de passe incorrect" next() req.write bodyString req.end() it 'Sign up correctly', (next) -> bodyString = JSON.stringify email: "<EMAIL>", password: "<PASSWORD>" headers = GetOptionsWithHeaders '/usr/signup', bodyString req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql true should.not.exists res.data next() req.write bodyString req.end() it 'Sign up without email or password', (next) -> bodyString = JSON.stringify password: "<PASSWORD>" headers = GetOptionsWithHeaders '/usr/signup', bodyString req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql false res.data.should.eql "Email ou mot de passe manquant" next() req.write bodyString req.end() it 'Sign up without a valid email', (next) -> bodyString = JSON.stringify email: "<EMAIL>", password: "<PASSWORD>" headers = GetOptionsWithHeaders '/usr/signup', bodyString req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql false res.data.should.eql "Cette adresse email est invalide" next() req.write bodyString req.end() it 'Sign up without a strong password', (next) -> bodyString = JSON.stringify email: "<EMAIL>", password: "<PASSWORD>" headers = GetOptionsWithHeaders '/usr/signup', bodyString req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql false res.data.should.eql "Le mot de passe doit comporter au moins 8 caractères" next() req.write bodyString req.end() it 'Sign in after signed up', (next) -> bodyString = JSON.stringify email: "<EMAIL>", password: "<PASSWORD>" headers = GetOptionsWithHeaders '/usr/signup', bodyString req = https.request headers, (res) -> res.on 'data', (data) -> res.on 'end', (err) -> return next err if err bodyString = JSON.stringify email: "<EMAIL>", password: "<PASSWORD>" headers = GetOptionsWithHeaders '/usr/signin', bodyString req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql true should.not.exists res.data next() req.write bodyString req.end() req.write bodyString req.end() it 'Check password without signed in', (next) -> bodyString = JSON.stringify password: "<PASSWORD>" headers = GetOptionsWithHeaders '/usr/checkpassword', bodyString req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql false res.data.should.eql "Authentification requise" next() req.write bodyString req.end() it 'Check password after signed up', (next) -> bodyString = JSON.stringify email: "<EMAIL>", password: "<PASSWORD>" headers = GetOptionsWithHeaders '/usr/signup', bodyString req = https.request headers, (res) -> res.on 'data', (data) -> res.on 'end', (err) -> return next err if err bodyString = JSON.stringify password: "<PASSWORD>" headers = GetOptionsWithHeaders '/usr/checkpassword', bodyString, res.headers['set-cookie'] req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql true should.not.exists res.data next() req.write bodyString req.end() req.write bodyString req.end() it 'Check password without password (after signed up)', (next) -> bodyString = JSON.stringify email: "<EMAIL>", password: "<PASSWORD>" headers = GetOptionsWithHeaders '/usr/signup', bodyString req = https.request headers, (res) -> res.on 'data', (data) -> res.on 'end', (err) -> return next err if err bodyString = JSON.stringify email: "12345678" headers = GetOptionsWithHeaders '/usr/checkpassword', bodyString, res.headers['set-cookie'] req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql false res.data.should.eql "Mot de passe manquant" next() req.write bodyString req.end() req.write bodyString req.end() it 'Update email without signed in', (next) -> bodyString = JSON.stringify email: "<EMAIL>" headers = GetOptionsWithHeaders '/usr/updateemail', bodyString req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql false res.data.should.eql "Authentification requise" next() req.write bodyString req.end() it 'Update email after signed up', (next) -> bodyString = JSON.stringify email: "<EMAIL>", password: "<PASSWORD>" headers = GetOptionsWithHeaders '/usr/signup', bodyString req = https.request headers, (res) -> res.on 'data', (data) -> res.on 'end', (err) -> return next err if err bodyString = JSON.stringify email: "<EMAIL>" headers = GetOptionsWithHeaders '/usr/updateemail', bodyString, res.headers['set-cookie'] req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql true should.not.exists res.data next() req.write bodyString req.end() req.write bodyString req.end() it 'Update email without email (after signed up)', (next) -> bodyString = JSON.stringify email: "<EMAIL>", password: "<PASSWORD>" headers = GetOptionsWithHeaders '/usr/signup', bodyString req = https.request headers, (res) -> res.on 'data', (data) -> res.on 'end', (err) -> return next err if err headers = GetOptionsWithHeaders '/usr/updateemail', "", res.headers['set-cookie'] req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql false res.data.should.eql "Email manquant" next() req.end() req.write bodyString req.end() it 'Update email with an unvalid email (after signed up)', (next) -> bodyString = JSON.stringify email: "<EMAIL>", password: "<PASSWORD>" headers = GetOptionsWithHeaders '/usr/signup', bodyString req = https.request headers, (res) -> res.on 'data', (data) -> res.on 'end', (err) -> return next err if err bodyString = JSON.stringify email: "robinethylocle.com" headers = GetOptionsWithHeaders '/usr/updateemail', bodyString, res.headers['set-cookie'] req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql false res.data.should.eql "Cette adresse email est invalide" next() req.write bodyString req.end() req.write bodyString req.end() it 'Update without signed in', (next) -> bodyString = JSON.stringify email: "<EMAIL>", lastName: "Bag<NAME>", firstName: "<NAME>" headers = GetOptionsWithHeaders '/usr/update', bodyString req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql false res.data.should.eql "Authentification requise" next() req.write bodyString req.end() it 'Update after signed up', (next) -> bodyString = JSON.stringify email: "<EMAIL>", password: "<PASSWORD>" headers = GetOptionsWithHeaders '/usr/signup', bodyString req = https.request headers, (res) -> res.on 'data', (data) -> res.on 'end', (err) -> return next err if err bodyString = JSON.stringify email: "<EMAIL>", lastName: "<NAME>", firstName: "<NAME>", password: "<PASSWORD>" headers = GetOptionsWithHeaders '/usr/update', bodyString, res.headers['set-cookie'] req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql true should.not.exists res.data next() req.write bodyString req.end() req.write bodyString req.end() it 'Update without arguments (after signed up)', (next) -> bodyString = JSON.stringify email: "<EMAIL>", password: "<PASSWORD>" headers = GetOptionsWithHeaders '/usr/signup', bodyString req = https.request headers, (res) -> res.on 'data', (data) -> res.on 'end', (err) -> return next err if err bodyString = "" headers = GetOptionsWithHeaders '/usr/update', bodyString, res.headers['set-cookie'] req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql false res.data.should.eql "La requête ne comporte aucun argument" next() req.write bodyString req.end() req.write bodyString req.end() it 'Update without password (after signed up)', (next) -> bodyString = JSON.stringify email: "<EMAIL>", password: "<PASSWORD>" headers = GetOptionsWithHeaders '/usr/signup', bodyString req = https.request headers, (res) -> res.on 'data', (data) -> res.on 'end', (err) -> return next err if err bodyString = JSON.stringify email: "<EMAIL>", lastName: "<NAME>", firstName: "<NAME>" headers = GetOptionsWithHeaders '/usr/update', bodyString, res.headers['set-cookie'] req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql true should.not.exists res.data next() req.write bodyString req.end() req.write bodyString req.end() it 'Update with an unvalid password (after signed up)', (next) -> bodyString = JSON.stringify email: "<EMAIL>", password: "<PASSWORD>" headers = GetOptionsWithHeaders '/usr/signup', bodyString req = https.request headers, (res) -> res.on 'data', (data) -> res.on 'end', (err) -> return next err if err bodyString = JSON.stringify password: "<PASSWORD>" headers = GetOptionsWithHeaders '/usr/update', bodyString, res.headers['set-cookie'] req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql false res.data.should.eql "Le mot de passe doit comporter au moins 8 caractères" next() req.write bodyString req.end() req.write bodyString req.end() it 'Get without signed in', (next) -> headers = GetOptionsWithHeaders '/usr/get', "" req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql false res.data.should.eql "Authentification requise" next() req.end() it 'Get (after signed up)', (next) -> bodyString = JSON.stringify email: "<EMAIL>", password: "<PASSWORD>" headers = GetOptionsWithHeaders '/usr/signup', bodyString req = https.request headers, (res) -> res.on 'data', (data) -> res.on 'end', (err) -> return next err if err headers = GetOptionsWithHeaders '/usr/get', "", res.headers['set-cookie'] req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql true Object.keys(res.data).length.should.eql 2 res.data.id.should.eql '0' res.data.email.should.eql '<EMAIL>' next() req.end() req.write bodyString req.end() it 'Get by id without signed in', (next) -> headers = GetOptionsWithHeaders '/usr/getbyid', "" req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql false res.data.should.eql "Authentification requise" next() req.end() it 'Get by id (after signed up)', (next) -> bodyString = JSON.stringify email: "<EMAIL>", password: "<PASSWORD>" headers = GetOptionsWithHeaders '/usr/signup', bodyString req = https.request headers, (res) -> res.on 'data', (data) -> res.on 'end', (err) -> return next err if err bodyString = JSON.stringify id: "0" headers = GetOptionsWithHeaders '/usr/getbyid', bodyString, res.headers['set-cookie'] req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql true Object.keys(res.data).length.should.eql 1 res.data.id.should.eql '0' next() req.write bodyString req.end() req.write bodyString req.end() it 'Get by id without id (after signed up)', (next) -> bodyString = JSON.stringify email: "<EMAIL>", password: "<PASSWORD>" headers = GetOptionsWithHeaders '/usr/signup', bodyString req = https.request headers, (res) -> res.on 'data', (data) -> res.on 'end', (err) -> return next err if err headers = GetOptionsWithHeaders '/usr/getbyid', "", res.headers['set-cookie'] req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql false res.data.should.eql "Identifiant manquant" next() req.end() req.write bodyString req.end() it 'Get by id with null id (after signed up)', (next) -> bodyString = JSON.stringify email: "<EMAIL>", password: "<PASSWORD>" headers = GetOptionsWithHeaders '/usr/signup', bodyString req = https.request headers, (res) -> res.on 'data', (data) -> res.on 'end', (err) -> return next err if err bodyString = JSON.stringify id: null headers = GetOptionsWithHeaders '/usr/getbyid', bodyString, res.headers['set-cookie'] req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body res.result.should.eql false res.data.should.eql "L'utilisateur n'existe pas" next() req.write bodyString req.end() req.write bodyString req.end() it 'Delete without signed in', (next) -> headers = GetOptionsWithHeaders '/usr/delete', "" req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql false res.data.should.eql "Authentification requise" next() req.end() it 'Delete (after signed up)', (next) -> bodyString = JSON.stringify email: "<EMAIL>", password: "<PASSWORD>" headers = GetOptionsWithHeaders '/usr/signup', bodyString req = https.request headers, (res) -> res.on 'data', (data) -> res.on 'end', (err) -> return next err if err bodyString = "" headers = GetOptionsWithHeaders '/usr/delete', bodyString, res.headers['set-cookie'] req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql true should.not.exists res.data headers = GetOptionsWithHeaders '/usr/delete', "" req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql false res.data.should.eql "Authentification requise" next() req.end() req.write bodyString req.end() req.write bodyString req.end() it 'Sign out (after signed up)', (next) -> bodyString = JSON.stringify email: "<EMAIL>", password: "<PASSWORD>" headers = GetOptionsWithHeaders '/usr/signup', bodyString req = https.request headers, (res) -> res.on 'data', (data) -> res.on 'end', (err) -> return next err if err bodyString = "" headers = GetOptionsWithHeaders '/usr/signout', bodyString, res.headers['set-cookie'] req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql true should.not.exists res.data headers = GetOptionsWithHeaders '/usr/signout', "" req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql false res.data.should.eql "Authentification requise" next() req.end() req.write bodyString req.end() req.write bodyString req.end()
true
rimraf = require 'rimraf' should = require 'should' db = require '../../lib/factory/model' app = require '../../lib/host/app' https = require 'https' fs = require 'fs' port = process.env.PORT || 443 server = undefined process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0" hskey = fs.readFileSync __dirname + "/../../resource/key/key.pem" hscert = fs.readFileSync __dirname + "/../../resource/key/cert.pem" options = key: hskey cert: hscert defaultGetOptions = (path) -> options = "host": "localhost" "port": port "path": path "method": "POST" GetOptionsWithHeaders = (path, body, cookie) -> headers = 'Content-Type': 'application/json' 'Content-Length': body.length 'Cookie': cookie || "" options = "host": "localhost" "port": port "path": path "method": "POST" "headers": headers describe 'User routes', -> before (next) -> server = https.createServer(options, app).listen port, (err, result) -> return next err if err next() after (next) -> server.close() next() beforeEach (next) -> rimraf "#{__dirname}/../../db/tmp/user", next it 'should exist', (next) -> should.exist app next() it "should be listening at localhost:#{port}", (next) -> headers = defaultGetOptions '/' headers.method = "GET" https.get headers, (res) -> res.statusCode.should.eql 200 next() it 'Sign in without body (without email or password)', (next) -> headers = defaultGetOptions '/usr/signin' https.get headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql false res.data.should.eql "Email ou mot de passe manquant" next() it 'Sign in without signed up', (next) -> bodyString = JSON.stringify email: "PI:EMAIL:<EMAIL>END_PI", password: "PI:PASSWORD:<PASSWORD>END_PI" headers = GetOptionsWithHeaders '/usr/signin', bodyString req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql false res.data.should.eql "Email ou mot de passe incorrect" next() req.write bodyString req.end() it 'Sign up correctly', (next) -> bodyString = JSON.stringify email: "PI:EMAIL:<EMAIL>END_PI", password: "PI:PASSWORD:<PASSWORD>END_PI" headers = GetOptionsWithHeaders '/usr/signup', bodyString req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql true should.not.exists res.data next() req.write bodyString req.end() it 'Sign up without email or password', (next) -> bodyString = JSON.stringify password: "PI:PASSWORD:<PASSWORD>END_PI" headers = GetOptionsWithHeaders '/usr/signup', bodyString req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql false res.data.should.eql "Email ou mot de passe manquant" next() req.write bodyString req.end() it 'Sign up without a valid email', (next) -> bodyString = JSON.stringify email: "PI:EMAIL:<EMAIL>END_PI", password: "PI:PASSWORD:<PASSWORD>END_PI" headers = GetOptionsWithHeaders '/usr/signup', bodyString req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql false res.data.should.eql "Cette adresse email est invalide" next() req.write bodyString req.end() it 'Sign up without a strong password', (next) -> bodyString = JSON.stringify email: "PI:EMAIL:<EMAIL>END_PI", password: "PI:PASSWORD:<PASSWORD>END_PI" headers = GetOptionsWithHeaders '/usr/signup', bodyString req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql false res.data.should.eql "Le mot de passe doit comporter au moins 8 caractères" next() req.write bodyString req.end() it 'Sign in after signed up', (next) -> bodyString = JSON.stringify email: "PI:EMAIL:<EMAIL>END_PI", password: "PI:PASSWORD:<PASSWORD>END_PI" headers = GetOptionsWithHeaders '/usr/signup', bodyString req = https.request headers, (res) -> res.on 'data', (data) -> res.on 'end', (err) -> return next err if err bodyString = JSON.stringify email: "PI:EMAIL:<EMAIL>END_PI", password: "PI:PASSWORD:<PASSWORD>END_PI" headers = GetOptionsWithHeaders '/usr/signin', bodyString req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql true should.not.exists res.data next() req.write bodyString req.end() req.write bodyString req.end() it 'Check password without signed in', (next) -> bodyString = JSON.stringify password: "PI:PASSWORD:<PASSWORD>END_PI" headers = GetOptionsWithHeaders '/usr/checkpassword', bodyString req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql false res.data.should.eql "Authentification requise" next() req.write bodyString req.end() it 'Check password after signed up', (next) -> bodyString = JSON.stringify email: "PI:EMAIL:<EMAIL>END_PI", password: "PI:PASSWORD:<PASSWORD>END_PI" headers = GetOptionsWithHeaders '/usr/signup', bodyString req = https.request headers, (res) -> res.on 'data', (data) -> res.on 'end', (err) -> return next err if err bodyString = JSON.stringify password: "PI:PASSWORD:<PASSWORD>END_PI" headers = GetOptionsWithHeaders '/usr/checkpassword', bodyString, res.headers['set-cookie'] req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql true should.not.exists res.data next() req.write bodyString req.end() req.write bodyString req.end() it 'Check password without password (after signed up)', (next) -> bodyString = JSON.stringify email: "PI:EMAIL:<EMAIL>END_PI", password: "PI:PASSWORD:<PASSWORD>END_PI" headers = GetOptionsWithHeaders '/usr/signup', bodyString req = https.request headers, (res) -> res.on 'data', (data) -> res.on 'end', (err) -> return next err if err bodyString = JSON.stringify email: "12345678" headers = GetOptionsWithHeaders '/usr/checkpassword', bodyString, res.headers['set-cookie'] req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql false res.data.should.eql "Mot de passe manquant" next() req.write bodyString req.end() req.write bodyString req.end() it 'Update email without signed in', (next) -> bodyString = JSON.stringify email: "PI:EMAIL:<EMAIL>END_PI" headers = GetOptionsWithHeaders '/usr/updateemail', bodyString req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql false res.data.should.eql "Authentification requise" next() req.write bodyString req.end() it 'Update email after signed up', (next) -> bodyString = JSON.stringify email: "PI:EMAIL:<EMAIL>END_PI", password: "PI:PASSWORD:<PASSWORD>END_PI" headers = GetOptionsWithHeaders '/usr/signup', bodyString req = https.request headers, (res) -> res.on 'data', (data) -> res.on 'end', (err) -> return next err if err bodyString = JSON.stringify email: "PI:EMAIL:<EMAIL>END_PI" headers = GetOptionsWithHeaders '/usr/updateemail', bodyString, res.headers['set-cookie'] req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql true should.not.exists res.data next() req.write bodyString req.end() req.write bodyString req.end() it 'Update email without email (after signed up)', (next) -> bodyString = JSON.stringify email: "PI:EMAIL:<EMAIL>END_PI", password: "PI:PASSWORD:<PASSWORD>END_PI" headers = GetOptionsWithHeaders '/usr/signup', bodyString req = https.request headers, (res) -> res.on 'data', (data) -> res.on 'end', (err) -> return next err if err headers = GetOptionsWithHeaders '/usr/updateemail', "", res.headers['set-cookie'] req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql false res.data.should.eql "Email manquant" next() req.end() req.write bodyString req.end() it 'Update email with an unvalid email (after signed up)', (next) -> bodyString = JSON.stringify email: "PI:EMAIL:<EMAIL>END_PI", password: "PI:PASSWORD:<PASSWORD>END_PI" headers = GetOptionsWithHeaders '/usr/signup', bodyString req = https.request headers, (res) -> res.on 'data', (data) -> res.on 'end', (err) -> return next err if err bodyString = JSON.stringify email: "robinethylocle.com" headers = GetOptionsWithHeaders '/usr/updateemail', bodyString, res.headers['set-cookie'] req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql false res.data.should.eql "Cette adresse email est invalide" next() req.write bodyString req.end() req.write bodyString req.end() it 'Update without signed in', (next) -> bodyString = JSON.stringify email: "PI:EMAIL:<EMAIL>END_PI", lastName: "BagPI:NAME:<NAME>END_PI", firstName: "PI:NAME:<NAME>END_PI" headers = GetOptionsWithHeaders '/usr/update', bodyString req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql false res.data.should.eql "Authentification requise" next() req.write bodyString req.end() it 'Update after signed up', (next) -> bodyString = JSON.stringify email: "PI:EMAIL:<EMAIL>END_PI", password: "PI:PASSWORD:<PASSWORD>END_PI" headers = GetOptionsWithHeaders '/usr/signup', bodyString req = https.request headers, (res) -> res.on 'data', (data) -> res.on 'end', (err) -> return next err if err bodyString = JSON.stringify email: "PI:EMAIL:<EMAIL>END_PI", lastName: "PI:NAME:<NAME>END_PI", firstName: "PI:NAME:<NAME>END_PI", password: "PI:PASSWORD:<PASSWORD>END_PI" headers = GetOptionsWithHeaders '/usr/update', bodyString, res.headers['set-cookie'] req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql true should.not.exists res.data next() req.write bodyString req.end() req.write bodyString req.end() it 'Update without arguments (after signed up)', (next) -> bodyString = JSON.stringify email: "PI:EMAIL:<EMAIL>END_PI", password: "PI:PASSWORD:<PASSWORD>END_PI" headers = GetOptionsWithHeaders '/usr/signup', bodyString req = https.request headers, (res) -> res.on 'data', (data) -> res.on 'end', (err) -> return next err if err bodyString = "" headers = GetOptionsWithHeaders '/usr/update', bodyString, res.headers['set-cookie'] req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql false res.data.should.eql "La requête ne comporte aucun argument" next() req.write bodyString req.end() req.write bodyString req.end() it 'Update without password (after signed up)', (next) -> bodyString = JSON.stringify email: "PI:EMAIL:<EMAIL>END_PI", password: "PI:PASSWORD:<PASSWORD>END_PI" headers = GetOptionsWithHeaders '/usr/signup', bodyString req = https.request headers, (res) -> res.on 'data', (data) -> res.on 'end', (err) -> return next err if err bodyString = JSON.stringify email: "PI:EMAIL:<EMAIL>END_PI", lastName: "PI:NAME:<NAME>END_PI", firstName: "PI:NAME:<NAME>END_PI" headers = GetOptionsWithHeaders '/usr/update', bodyString, res.headers['set-cookie'] req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql true should.not.exists res.data next() req.write bodyString req.end() req.write bodyString req.end() it 'Update with an unvalid password (after signed up)', (next) -> bodyString = JSON.stringify email: "PI:EMAIL:<EMAIL>END_PI", password: "PI:PASSWORD:<PASSWORD>END_PI" headers = GetOptionsWithHeaders '/usr/signup', bodyString req = https.request headers, (res) -> res.on 'data', (data) -> res.on 'end', (err) -> return next err if err bodyString = JSON.stringify password: "PI:PASSWORD:<PASSWORD>END_PI" headers = GetOptionsWithHeaders '/usr/update', bodyString, res.headers['set-cookie'] req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql false res.data.should.eql "Le mot de passe doit comporter au moins 8 caractères" next() req.write bodyString req.end() req.write bodyString req.end() it 'Get without signed in', (next) -> headers = GetOptionsWithHeaders '/usr/get', "" req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql false res.data.should.eql "Authentification requise" next() req.end() it 'Get (after signed up)', (next) -> bodyString = JSON.stringify email: "PI:EMAIL:<EMAIL>END_PI", password: "PI:PASSWORD:<PASSWORD>END_PI" headers = GetOptionsWithHeaders '/usr/signup', bodyString req = https.request headers, (res) -> res.on 'data', (data) -> res.on 'end', (err) -> return next err if err headers = GetOptionsWithHeaders '/usr/get', "", res.headers['set-cookie'] req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql true Object.keys(res.data).length.should.eql 2 res.data.id.should.eql '0' res.data.email.should.eql 'PI:EMAIL:<EMAIL>END_PI' next() req.end() req.write bodyString req.end() it 'Get by id without signed in', (next) -> headers = GetOptionsWithHeaders '/usr/getbyid', "" req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql false res.data.should.eql "Authentification requise" next() req.end() it 'Get by id (after signed up)', (next) -> bodyString = JSON.stringify email: "PI:EMAIL:<EMAIL>END_PI", password: "PI:PASSWORD:<PASSWORD>END_PI" headers = GetOptionsWithHeaders '/usr/signup', bodyString req = https.request headers, (res) -> res.on 'data', (data) -> res.on 'end', (err) -> return next err if err bodyString = JSON.stringify id: "0" headers = GetOptionsWithHeaders '/usr/getbyid', bodyString, res.headers['set-cookie'] req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql true Object.keys(res.data).length.should.eql 1 res.data.id.should.eql '0' next() req.write bodyString req.end() req.write bodyString req.end() it 'Get by id without id (after signed up)', (next) -> bodyString = JSON.stringify email: "PI:EMAIL:<EMAIL>END_PI", password: "PI:PASSWORD:<PASSWORD>END_PI" headers = GetOptionsWithHeaders '/usr/signup', bodyString req = https.request headers, (res) -> res.on 'data', (data) -> res.on 'end', (err) -> return next err if err headers = GetOptionsWithHeaders '/usr/getbyid', "", res.headers['set-cookie'] req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql false res.data.should.eql "Identifiant manquant" next() req.end() req.write bodyString req.end() it 'Get by id with null id (after signed up)', (next) -> bodyString = JSON.stringify email: "PI:EMAIL:<EMAIL>END_PI", password: "PI:PASSWORD:<PASSWORD>END_PI" headers = GetOptionsWithHeaders '/usr/signup', bodyString req = https.request headers, (res) -> res.on 'data', (data) -> res.on 'end', (err) -> return next err if err bodyString = JSON.stringify id: null headers = GetOptionsWithHeaders '/usr/getbyid', bodyString, res.headers['set-cookie'] req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body res.result.should.eql false res.data.should.eql "L'utilisateur n'existe pas" next() req.write bodyString req.end() req.write bodyString req.end() it 'Delete without signed in', (next) -> headers = GetOptionsWithHeaders '/usr/delete', "" req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql false res.data.should.eql "Authentification requise" next() req.end() it 'Delete (after signed up)', (next) -> bodyString = JSON.stringify email: "PI:EMAIL:<EMAIL>END_PI", password: "PI:PASSWORD:<PASSWORD>END_PI" headers = GetOptionsWithHeaders '/usr/signup', bodyString req = https.request headers, (res) -> res.on 'data', (data) -> res.on 'end', (err) -> return next err if err bodyString = "" headers = GetOptionsWithHeaders '/usr/delete', bodyString, res.headers['set-cookie'] req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql true should.not.exists res.data headers = GetOptionsWithHeaders '/usr/delete', "" req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql false res.data.should.eql "Authentification requise" next() req.end() req.write bodyString req.end() req.write bodyString req.end() it 'Sign out (after signed up)', (next) -> bodyString = JSON.stringify email: "PI:EMAIL:<EMAIL>END_PI", password: "PI:PASSWORD:<PASSWORD>END_PI" headers = GetOptionsWithHeaders '/usr/signup', bodyString req = https.request headers, (res) -> res.on 'data', (data) -> res.on 'end', (err) -> return next err if err bodyString = "" headers = GetOptionsWithHeaders '/usr/signout', bodyString, res.headers['set-cookie'] req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql true should.not.exists res.data headers = GetOptionsWithHeaders '/usr/signout', "" req = https.request headers, (res) -> res.statusCode.should.eql 200 body = "" res.on 'data', (data) -> body += data res.on 'end', (err) -> return next err if err res = JSON.parse body Object.keys(res).length.should.eql 2 res.result.should.eql false res.data.should.eql "Authentification requise" next() req.end() req.write bodyString req.end() req.write bodyString req.end()
[ { "context": "tup config keys for all notifiers\nCONFIG_KEYS = ['message']\n_.each notifiers, (n)->\n CONFIG_KEYS = CONFIG_", "end": 586, "score": 0.9551634788513184, "start": 579, "tag": "KEY", "value": "message" } ]
lib/notifyme.coffee
hybridknight/notifyme
1
path = require 'path' _ = require 'lodash' config = require('./config.coffee') notifiers = require './notifiers' notifiers = _.map notifiers, (notifier)-> new notifier argv = require('minimist')(process.argv.slice(2), default: growl: true sms: null voice: null push: false debug: false by: null message: null version: false alias: d: "debug" g: "growl" s: "sms" p: "push" b: "by" m: "message" vv: "version" v: "voice" boolean: ['debug', 'version'] ) # setup config keys for all notifiers CONFIG_KEYS = ['message'] _.each notifiers, (n)-> CONFIG_KEYS = CONFIG_KEYS.concat n.config_keys if n.config_keys # setup log filter global.log = (args...)-> if argv.debug console.log.apply @, args exports.run = -> return console.log require(path.resolve __dirname, "../package.json").version if argv.version # setup "--by" command if argv.by notify_by = argv.by.split "," _.each notify_by, (b)-> argv[b] = argv[b] || true log "argv:", argv log "notifiers:", _.map notifiers, (n)-> n.name if argv._[0] == 'set' configs = argv._.slice(1) _.map configs, (e)-> c = e.split "=" config.config().set c[0], c[1] config.config().save (err)-> console.error err if err console.log "#{c[0]}: #{c[1]}" else if argv._[0] == 'config' config.print(CONFIG_KEYS) else process.stdin.setEncoding('utf8') process.stdin.pipe process.stdout process.stdin.on 'end', -> done_message = if argv.message then argv.message else config.config().get('message') || 'Task done! yey' _.each notifiers, (notifier)-> if notifier.should_be_used(argv) invalid_config = notifier.has_invalid_config(argv) if invalid_config console.warn "[notifyme] #{notifier.name} has to be configured before using. #{invalid_config}" else notifier.notify argv, done_message
207687
path = require 'path' _ = require 'lodash' config = require('./config.coffee') notifiers = require './notifiers' notifiers = _.map notifiers, (notifier)-> new notifier argv = require('minimist')(process.argv.slice(2), default: growl: true sms: null voice: null push: false debug: false by: null message: null version: false alias: d: "debug" g: "growl" s: "sms" p: "push" b: "by" m: "message" vv: "version" v: "voice" boolean: ['debug', 'version'] ) # setup config keys for all notifiers CONFIG_KEYS = ['<KEY>'] _.each notifiers, (n)-> CONFIG_KEYS = CONFIG_KEYS.concat n.config_keys if n.config_keys # setup log filter global.log = (args...)-> if argv.debug console.log.apply @, args exports.run = -> return console.log require(path.resolve __dirname, "../package.json").version if argv.version # setup "--by" command if argv.by notify_by = argv.by.split "," _.each notify_by, (b)-> argv[b] = argv[b] || true log "argv:", argv log "notifiers:", _.map notifiers, (n)-> n.name if argv._[0] == 'set' configs = argv._.slice(1) _.map configs, (e)-> c = e.split "=" config.config().set c[0], c[1] config.config().save (err)-> console.error err if err console.log "#{c[0]}: #{c[1]}" else if argv._[0] == 'config' config.print(CONFIG_KEYS) else process.stdin.setEncoding('utf8') process.stdin.pipe process.stdout process.stdin.on 'end', -> done_message = if argv.message then argv.message else config.config().get('message') || 'Task done! yey' _.each notifiers, (notifier)-> if notifier.should_be_used(argv) invalid_config = notifier.has_invalid_config(argv) if invalid_config console.warn "[notifyme] #{notifier.name} has to be configured before using. #{invalid_config}" else notifier.notify argv, done_message
true
path = require 'path' _ = require 'lodash' config = require('./config.coffee') notifiers = require './notifiers' notifiers = _.map notifiers, (notifier)-> new notifier argv = require('minimist')(process.argv.slice(2), default: growl: true sms: null voice: null push: false debug: false by: null message: null version: false alias: d: "debug" g: "growl" s: "sms" p: "push" b: "by" m: "message" vv: "version" v: "voice" boolean: ['debug', 'version'] ) # setup config keys for all notifiers CONFIG_KEYS = ['PI:KEY:<KEY>END_PI'] _.each notifiers, (n)-> CONFIG_KEYS = CONFIG_KEYS.concat n.config_keys if n.config_keys # setup log filter global.log = (args...)-> if argv.debug console.log.apply @, args exports.run = -> return console.log require(path.resolve __dirname, "../package.json").version if argv.version # setup "--by" command if argv.by notify_by = argv.by.split "," _.each notify_by, (b)-> argv[b] = argv[b] || true log "argv:", argv log "notifiers:", _.map notifiers, (n)-> n.name if argv._[0] == 'set' configs = argv._.slice(1) _.map configs, (e)-> c = e.split "=" config.config().set c[0], c[1] config.config().save (err)-> console.error err if err console.log "#{c[0]}: #{c[1]}" else if argv._[0] == 'config' config.print(CONFIG_KEYS) else process.stdin.setEncoding('utf8') process.stdin.pipe process.stdout process.stdin.on 'end', -> done_message = if argv.message then argv.message else config.config().get('message') || 'Task done! yey' _.each notifiers, (notifier)-> if notifier.should_be_used(argv) invalid_config = notifier.has_invalid_config(argv) if invalid_config console.warn "[notifyme] #{notifier.name} has to be configured before using. #{invalid_config}" else notifier.notify argv, done_message
[ { "context": "ong()', ->\n\n\t\tbeforeEach ->\n\t\t\t@song = { artist: 'Taylor Swift', title: 'Shake It Off' }\n\n\t\tit 'should throw an ", "end": 1964, "score": 0.9998541474342346, "start": 1952, "tag": "NAME", "value": "Taylor Swift" } ]
tests/player.spec.coffee
balena-io/musync
1
_ = require('lodash') sinon = require('sinon') chai = require('chai') chai.use(require('sinon-chai')) expect = chai.expect MockRes = require('mock-res') Player = require('../lib/player') describe 'Player:', -> beforeEach -> @format = sampleRate: 44100 channels: 1 bitDepth: 16 describe '#constructor()', -> it 'should throw an error if no stream', -> expect => new Player(null, new MockRes(), @format) .to.throw('Missing stream argument') it 'should throw an error if stream is not a readable stream', -> expect => new Player({}, new MockRes(), @format) .to.throw('Invalid stream argument: not a readable stream') it 'should throw an error if no decoder', -> expect => new Player(new MockRes(), null, @format) .to.throw('Missing decoder argument') it 'should throw an error if no format', -> expect -> new Player(new MockRes(), new MockRes(), null) .to.throw('Missing format argument') describe '#play()', -> it 'should emit a play event', -> player = new Player(new MockRes(), new MockRes(), @format) spy = sinon.spy() player.on('play', spy) player.play() expect(spy).to.have.been.calledOnce describe '#pause()', -> it 'should emit a pause event', -> player = new Player(new MockRes(), new MockRes(), @format) spy = sinon.spy() player.on('pause', spy) player.pause() expect(spy).to.have.been.calledOnce describe '#stop()', -> it 'should emit a stop event', -> player = new Player(new MockRes(), new MockRes(), @format) spy = sinon.spy() player.on('stop', spy) player.stop() expect(spy).to.have.been.calledOnce describe '#onFinish()', -> it 'should emit a finish event', -> player = new Player(new MockRes(), new MockRes(), @format) spy = sinon.spy() player.on('finish', spy) player.onFinish() expect(spy).to.have.been.calledOnce describe '.createFromSong()', -> beforeEach -> @song = { artist: 'Taylor Swift', title: 'Shake It Off' } it 'should throw an error if no song', -> expect -> Player.createFromSong(null, { search: _.noop }, _.noop) .to.throw('Missing song argument') it 'should throw an error if no backend', -> expect => Player.createFromSong(@song, null, _.noop) .to.throw('Missing backend argument') it 'should throw an error if backend is missing the search function', -> expect => Player.createFromSong(@song, {}, _.noop) .to.throw('Invalid backend argument: no search function') it 'should throw an error if backend.search is not a function', -> expect => Player.createFromSong(@song, { search: [ _.noop ] }, _.noop) .to.throw('Invalid backend argument: search is not a function')
219209
_ = require('lodash') sinon = require('sinon') chai = require('chai') chai.use(require('sinon-chai')) expect = chai.expect MockRes = require('mock-res') Player = require('../lib/player') describe 'Player:', -> beforeEach -> @format = sampleRate: 44100 channels: 1 bitDepth: 16 describe '#constructor()', -> it 'should throw an error if no stream', -> expect => new Player(null, new MockRes(), @format) .to.throw('Missing stream argument') it 'should throw an error if stream is not a readable stream', -> expect => new Player({}, new MockRes(), @format) .to.throw('Invalid stream argument: not a readable stream') it 'should throw an error if no decoder', -> expect => new Player(new MockRes(), null, @format) .to.throw('Missing decoder argument') it 'should throw an error if no format', -> expect -> new Player(new MockRes(), new MockRes(), null) .to.throw('Missing format argument') describe '#play()', -> it 'should emit a play event', -> player = new Player(new MockRes(), new MockRes(), @format) spy = sinon.spy() player.on('play', spy) player.play() expect(spy).to.have.been.calledOnce describe '#pause()', -> it 'should emit a pause event', -> player = new Player(new MockRes(), new MockRes(), @format) spy = sinon.spy() player.on('pause', spy) player.pause() expect(spy).to.have.been.calledOnce describe '#stop()', -> it 'should emit a stop event', -> player = new Player(new MockRes(), new MockRes(), @format) spy = sinon.spy() player.on('stop', spy) player.stop() expect(spy).to.have.been.calledOnce describe '#onFinish()', -> it 'should emit a finish event', -> player = new Player(new MockRes(), new MockRes(), @format) spy = sinon.spy() player.on('finish', spy) player.onFinish() expect(spy).to.have.been.calledOnce describe '.createFromSong()', -> beforeEach -> @song = { artist: '<NAME>', title: 'Shake It Off' } it 'should throw an error if no song', -> expect -> Player.createFromSong(null, { search: _.noop }, _.noop) .to.throw('Missing song argument') it 'should throw an error if no backend', -> expect => Player.createFromSong(@song, null, _.noop) .to.throw('Missing backend argument') it 'should throw an error if backend is missing the search function', -> expect => Player.createFromSong(@song, {}, _.noop) .to.throw('Invalid backend argument: no search function') it 'should throw an error if backend.search is not a function', -> expect => Player.createFromSong(@song, { search: [ _.noop ] }, _.noop) .to.throw('Invalid backend argument: search is not a function')
true
_ = require('lodash') sinon = require('sinon') chai = require('chai') chai.use(require('sinon-chai')) expect = chai.expect MockRes = require('mock-res') Player = require('../lib/player') describe 'Player:', -> beforeEach -> @format = sampleRate: 44100 channels: 1 bitDepth: 16 describe '#constructor()', -> it 'should throw an error if no stream', -> expect => new Player(null, new MockRes(), @format) .to.throw('Missing stream argument') it 'should throw an error if stream is not a readable stream', -> expect => new Player({}, new MockRes(), @format) .to.throw('Invalid stream argument: not a readable stream') it 'should throw an error if no decoder', -> expect => new Player(new MockRes(), null, @format) .to.throw('Missing decoder argument') it 'should throw an error if no format', -> expect -> new Player(new MockRes(), new MockRes(), null) .to.throw('Missing format argument') describe '#play()', -> it 'should emit a play event', -> player = new Player(new MockRes(), new MockRes(), @format) spy = sinon.spy() player.on('play', spy) player.play() expect(spy).to.have.been.calledOnce describe '#pause()', -> it 'should emit a pause event', -> player = new Player(new MockRes(), new MockRes(), @format) spy = sinon.spy() player.on('pause', spy) player.pause() expect(spy).to.have.been.calledOnce describe '#stop()', -> it 'should emit a stop event', -> player = new Player(new MockRes(), new MockRes(), @format) spy = sinon.spy() player.on('stop', spy) player.stop() expect(spy).to.have.been.calledOnce describe '#onFinish()', -> it 'should emit a finish event', -> player = new Player(new MockRes(), new MockRes(), @format) spy = sinon.spy() player.on('finish', spy) player.onFinish() expect(spy).to.have.been.calledOnce describe '.createFromSong()', -> beforeEach -> @song = { artist: 'PI:NAME:<NAME>END_PI', title: 'Shake It Off' } it 'should throw an error if no song', -> expect -> Player.createFromSong(null, { search: _.noop }, _.noop) .to.throw('Missing song argument') it 'should throw an error if no backend', -> expect => Player.createFromSong(@song, null, _.noop) .to.throw('Missing backend argument') it 'should throw an error if backend is missing the search function', -> expect => Player.createFromSong(@song, {}, _.noop) .to.throw('Invalid backend argument: no search function') it 'should throw an error if backend.search is not a function', -> expect => Player.createFromSong(@song, { search: [ _.noop ] }, _.noop) .to.throw('Invalid backend argument: search is not a function')
[ { "context": "req, 'foo-token', 'token-secret', { displayName: 'Craig' }\n res = { body: { error_description: 'no acc", "end": 2604, "score": 0.9809350371360779, "start": 2599, "tag": "NAME", "value": "Craig" } ]
test/passport/callbacks.coffee
anandaroop/artsy-passport
0
Backbone = require 'backbone' rewire = require 'rewire' sinon = require 'sinon' cbs = rewire '../../lib/passport/callbacks' describe 'passport callbacks', -> beforeEach -> @req = { get: sinon.stub() } @request = {} @request.get = sinon.stub().returns @request @request.query = sinon.stub().returns @request @request.set = sinon.stub().returns @request @request.end = sinon.stub().returns @request @request.post = sinon.stub().returns @request @request.send = sinon.stub().returns @request cbs.__set__ 'request', @request cbs.__set__ 'opts', { ARTSY_ID: 'artsy-id' ARTSY_SECRET: 'artsy-secret' ARTSY_URL: 'http://apiz.artsy.net' CurrentUser: Backbone.Model } it 'gets a user with an access token email/password', (done) -> cbs.local @req, 'craig', 'foo', (err, user) -> user.get('accessToken').should.equal 'access-token' done() @request.post.args[0][0].should .equal 'http://apiz.artsy.net/oauth2/access_token' res = { body: { access_token: 'access-token' }, status: 200 } @request.end.args[0][0](null, res) it 'gets a user with an access token facebook', (done) -> cbs.facebook @req, 'foo-token', 'refresh-token', {}, (err, user) -> user.get('accessToken').should.equal 'access-token' done() @request.post.args[0][0].should .equal 'http://apiz.artsy.net/oauth2/access_token' queryParams = @request.query.args[0][0] queryParams.oauth_provider.should.equal 'facebook' queryParams.oauth_token.should.equal 'foo-token' res = { body: { access_token: 'access-token' }, status: 200 } @request.end.args[0][0](null, res) it 'gets a user with an access token apple', (done) -> cbs.apple @req, 'foo-token', 'refresh-token', { id: 'some-apple-uid' }, (err, user) -> user.get('accessToken').should.equal 'access-token' done() @request.post.args[0][0].should .equal 'http://apiz.artsy.net/oauth2/access_token' queryParams = @request.query.args[0][0] queryParams.grant_type.should.equal 'apple_uid' queryParams.apple_uid.should.equal 'some-apple-uid' res = { body: { access_token: 'access-token' }, status: 200 } @request.end.args[0][0](null, res) it 'passes the user agent through login', -> @req.get.returns 'chrome-foo' cbs.local @req, 'craig', 'foo' @request.set.args[0][0].should.containEql { 'User-Agent': 'chrome-foo' } it 'passes the user agent through facebook signup', -> @req.get.returns 'foo-bar-baz-ua' cbs.facebook @req, 'foo-token', 'token-secret', { displayName: 'Craig' } res = { body: { error_description: 'no account linked' }, status: 403 } @request.end.args[0][0](null, res) @request.set.args[1][0]['User-Agent'].should.equal 'foo-bar-baz-ua' it 'passes the user agent through apple signup', -> @req.get.returns 'foo-bar-baz-ua' cbs.apple @req, 'foo-token', 'refresh-token', 'id-token', {} res = { body: { error_description: 'no account linked' }, status: 403 } @request.end.args[0][0](null, res) @request.set.args[1][0]['User-Agent'].should.equal 'foo-bar-baz-ua'
221125
Backbone = require 'backbone' rewire = require 'rewire' sinon = require 'sinon' cbs = rewire '../../lib/passport/callbacks' describe 'passport callbacks', -> beforeEach -> @req = { get: sinon.stub() } @request = {} @request.get = sinon.stub().returns @request @request.query = sinon.stub().returns @request @request.set = sinon.stub().returns @request @request.end = sinon.stub().returns @request @request.post = sinon.stub().returns @request @request.send = sinon.stub().returns @request cbs.__set__ 'request', @request cbs.__set__ 'opts', { ARTSY_ID: 'artsy-id' ARTSY_SECRET: 'artsy-secret' ARTSY_URL: 'http://apiz.artsy.net' CurrentUser: Backbone.Model } it 'gets a user with an access token email/password', (done) -> cbs.local @req, 'craig', 'foo', (err, user) -> user.get('accessToken').should.equal 'access-token' done() @request.post.args[0][0].should .equal 'http://apiz.artsy.net/oauth2/access_token' res = { body: { access_token: 'access-token' }, status: 200 } @request.end.args[0][0](null, res) it 'gets a user with an access token facebook', (done) -> cbs.facebook @req, 'foo-token', 'refresh-token', {}, (err, user) -> user.get('accessToken').should.equal 'access-token' done() @request.post.args[0][0].should .equal 'http://apiz.artsy.net/oauth2/access_token' queryParams = @request.query.args[0][0] queryParams.oauth_provider.should.equal 'facebook' queryParams.oauth_token.should.equal 'foo-token' res = { body: { access_token: 'access-token' }, status: 200 } @request.end.args[0][0](null, res) it 'gets a user with an access token apple', (done) -> cbs.apple @req, 'foo-token', 'refresh-token', { id: 'some-apple-uid' }, (err, user) -> user.get('accessToken').should.equal 'access-token' done() @request.post.args[0][0].should .equal 'http://apiz.artsy.net/oauth2/access_token' queryParams = @request.query.args[0][0] queryParams.grant_type.should.equal 'apple_uid' queryParams.apple_uid.should.equal 'some-apple-uid' res = { body: { access_token: 'access-token' }, status: 200 } @request.end.args[0][0](null, res) it 'passes the user agent through login', -> @req.get.returns 'chrome-foo' cbs.local @req, 'craig', 'foo' @request.set.args[0][0].should.containEql { 'User-Agent': 'chrome-foo' } it 'passes the user agent through facebook signup', -> @req.get.returns 'foo-bar-baz-ua' cbs.facebook @req, 'foo-token', 'token-secret', { displayName: '<NAME>' } res = { body: { error_description: 'no account linked' }, status: 403 } @request.end.args[0][0](null, res) @request.set.args[1][0]['User-Agent'].should.equal 'foo-bar-baz-ua' it 'passes the user agent through apple signup', -> @req.get.returns 'foo-bar-baz-ua' cbs.apple @req, 'foo-token', 'refresh-token', 'id-token', {} res = { body: { error_description: 'no account linked' }, status: 403 } @request.end.args[0][0](null, res) @request.set.args[1][0]['User-Agent'].should.equal 'foo-bar-baz-ua'
true
Backbone = require 'backbone' rewire = require 'rewire' sinon = require 'sinon' cbs = rewire '../../lib/passport/callbacks' describe 'passport callbacks', -> beforeEach -> @req = { get: sinon.stub() } @request = {} @request.get = sinon.stub().returns @request @request.query = sinon.stub().returns @request @request.set = sinon.stub().returns @request @request.end = sinon.stub().returns @request @request.post = sinon.stub().returns @request @request.send = sinon.stub().returns @request cbs.__set__ 'request', @request cbs.__set__ 'opts', { ARTSY_ID: 'artsy-id' ARTSY_SECRET: 'artsy-secret' ARTSY_URL: 'http://apiz.artsy.net' CurrentUser: Backbone.Model } it 'gets a user with an access token email/password', (done) -> cbs.local @req, 'craig', 'foo', (err, user) -> user.get('accessToken').should.equal 'access-token' done() @request.post.args[0][0].should .equal 'http://apiz.artsy.net/oauth2/access_token' res = { body: { access_token: 'access-token' }, status: 200 } @request.end.args[0][0](null, res) it 'gets a user with an access token facebook', (done) -> cbs.facebook @req, 'foo-token', 'refresh-token', {}, (err, user) -> user.get('accessToken').should.equal 'access-token' done() @request.post.args[0][0].should .equal 'http://apiz.artsy.net/oauth2/access_token' queryParams = @request.query.args[0][0] queryParams.oauth_provider.should.equal 'facebook' queryParams.oauth_token.should.equal 'foo-token' res = { body: { access_token: 'access-token' }, status: 200 } @request.end.args[0][0](null, res) it 'gets a user with an access token apple', (done) -> cbs.apple @req, 'foo-token', 'refresh-token', { id: 'some-apple-uid' }, (err, user) -> user.get('accessToken').should.equal 'access-token' done() @request.post.args[0][0].should .equal 'http://apiz.artsy.net/oauth2/access_token' queryParams = @request.query.args[0][0] queryParams.grant_type.should.equal 'apple_uid' queryParams.apple_uid.should.equal 'some-apple-uid' res = { body: { access_token: 'access-token' }, status: 200 } @request.end.args[0][0](null, res) it 'passes the user agent through login', -> @req.get.returns 'chrome-foo' cbs.local @req, 'craig', 'foo' @request.set.args[0][0].should.containEql { 'User-Agent': 'chrome-foo' } it 'passes the user agent through facebook signup', -> @req.get.returns 'foo-bar-baz-ua' cbs.facebook @req, 'foo-token', 'token-secret', { displayName: 'PI:NAME:<NAME>END_PI' } res = { body: { error_description: 'no account linked' }, status: 403 } @request.end.args[0][0](null, res) @request.set.args[1][0]['User-Agent'].should.equal 'foo-bar-baz-ua' it 'passes the user agent through apple signup', -> @req.get.returns 'foo-bar-baz-ua' cbs.apple @req, 'foo-token', 'refresh-token', 'id-token', {} res = { body: { error_description: 'no account linked' }, status: 403 } @request.end.args[0][0](null, res) @request.set.args[1][0]['User-Agent'].should.equal 'foo-bar-baz-ua'
[ { "context": "= 'https://static.zdassets.com/ekr/snippet.js?key=ed461a46-91a6-430a-a09c-73c364e02ffe'\n script = document.getElementsByTagName('scri", "end": 1130, "score": 0.9996088147163391, "start": 1094, "tag": "KEY", "value": "ed461a46-91a6-430a-a09c-73c364e02ffe" } ]
app/core/services/zendesk.coffee
cihatislamdede/codecombat
4,858
loadZendesk = _.once () -> return new Promise (accept, reject) -> onLoad = -> # zE is the global variable created by the script. We never want the floating button to show, so we: # 1: Hide it right away # 2: Bind showing it to opening it # 3: Bind closing it to hiding it zE('webWidget', 'hide') zE('webWidget:on', 'userEvent', (event) -> if event.action == 'Contact Form Shown' zE('webWidget', 'open') ) zE('webWidget:on', 'close', -> zE('webWidget', 'hide')) zE('webWidget', 'updateSettings', { webWidget: { offset: { horizontal: '100px', vertical: '20px' } } }) accept() onError = (e) -> console.error 'Zendesk failed to initialize:', e reject() zendeskElement = document.createElement('script') zendeskElement.id ="ze-snippet" zendeskElement.type = 'text/javascript' zendeskElement.async = true zendeskElement.onerror = onError zendeskElement.onload = onLoad zendeskElement.src = 'https://static.zdassets.com/ekr/snippet.js?key=ed461a46-91a6-430a-a09c-73c364e02ffe' script = document.getElementsByTagName('script')[0] script.parentNode.insertBefore(zendeskElement, script) openZendesk = -> try if !me.isAnonymous() zE('webWidget', 'prefill', { email: { value: me.get('email') } }) zE('webWidget', 'open') zE('webWidget', 'show') catch e console.error('Error trying to open Zendesk widget: ', e) return false return true module.exports = { loadZendesk openZendesk }
119671
loadZendesk = _.once () -> return new Promise (accept, reject) -> onLoad = -> # zE is the global variable created by the script. We never want the floating button to show, so we: # 1: Hide it right away # 2: Bind showing it to opening it # 3: Bind closing it to hiding it zE('webWidget', 'hide') zE('webWidget:on', 'userEvent', (event) -> if event.action == 'Contact Form Shown' zE('webWidget', 'open') ) zE('webWidget:on', 'close', -> zE('webWidget', 'hide')) zE('webWidget', 'updateSettings', { webWidget: { offset: { horizontal: '100px', vertical: '20px' } } }) accept() onError = (e) -> console.error 'Zendesk failed to initialize:', e reject() zendeskElement = document.createElement('script') zendeskElement.id ="ze-snippet" zendeskElement.type = 'text/javascript' zendeskElement.async = true zendeskElement.onerror = onError zendeskElement.onload = onLoad zendeskElement.src = 'https://static.zdassets.com/ekr/snippet.js?key=<KEY>' script = document.getElementsByTagName('script')[0] script.parentNode.insertBefore(zendeskElement, script) openZendesk = -> try if !me.isAnonymous() zE('webWidget', 'prefill', { email: { value: me.get('email') } }) zE('webWidget', 'open') zE('webWidget', 'show') catch e console.error('Error trying to open Zendesk widget: ', e) return false return true module.exports = { loadZendesk openZendesk }
true
loadZendesk = _.once () -> return new Promise (accept, reject) -> onLoad = -> # zE is the global variable created by the script. We never want the floating button to show, so we: # 1: Hide it right away # 2: Bind showing it to opening it # 3: Bind closing it to hiding it zE('webWidget', 'hide') zE('webWidget:on', 'userEvent', (event) -> if event.action == 'Contact Form Shown' zE('webWidget', 'open') ) zE('webWidget:on', 'close', -> zE('webWidget', 'hide')) zE('webWidget', 'updateSettings', { webWidget: { offset: { horizontal: '100px', vertical: '20px' } } }) accept() onError = (e) -> console.error 'Zendesk failed to initialize:', e reject() zendeskElement = document.createElement('script') zendeskElement.id ="ze-snippet" zendeskElement.type = 'text/javascript' zendeskElement.async = true zendeskElement.onerror = onError zendeskElement.onload = onLoad zendeskElement.src = 'https://static.zdassets.com/ekr/snippet.js?key=PI:KEY:<KEY>END_PI' script = document.getElementsByTagName('script')[0] script.parentNode.insertBefore(zendeskElement, script) openZendesk = -> try if !me.isAnonymous() zE('webWidget', 'prefill', { email: { value: me.get('email') } }) zE('webWidget', 'open') zE('webWidget', 'show') catch e console.error('Error trying to open Zendesk widget: ', e) return false return true module.exports = { loadZendesk openZendesk }
[ { "context": "if aff.name and aff.name.toLowerCase().includes 'gates'\n# ret += 'Author ' + a.given + ' ' + a.", "end": 2904, "score": 0.9719924926757812, "start": 2900, "tag": "NAME", "value": "ates" } ]
client/svc/oaworks/report.coffee
oaworks/paradigm
1
P.append 'body', ' <div id="welcome"> <div class="flex" style="margin-top: 5%;"><div class="c6 off3"> <h1 id="title" class="centre statement" style="font-size:40px;">Welcome to OA.Report</h1> </div></div> <div class="flex" style="margin-top: 5%;"> <div class="c6 off3"> <div id="funders"> <p>Great tool does great things.</p> <p>RIGHT NOW DOES NOTHING! UNDERGOING CHANGES...</p> <p>Funders! (or organisations) Find out if your recipients are meeting your policy expectations, take action if not:</p> <p><input type="text" class="PSuggest PForOrganisation" placeholder="Find an organisation" url="/src/ror/suggest/name/"></p> <div class="PSuggestions PForOrganisation"></div> </div> </div> </div> </div> <div id="report" style="display:none;"></div>' P.suggest {include: ["_id"], suggestion: (e, val, rec) -> window.location = window.location.href + "/" + rec._id }, "#funders" report = ' <div class="flex" style="margin-top: 5%;"> <div class="c1 off1 green"><h1 class="centre" id="rating"></h1></div><div class="c8"> <h1 id="title" class="centre statement" style="font-size:40px;"> </div> </div> <div class="flex" style="margin-top: 5%;"> <div class="c5 off1"> <p id="papercount"></p> <p id="citationcount"></p> <p><a href="//static.oa.works/report">Export</a> or <a id="refresh" href="#">refresh</a></p> <p><br></p> <div id="records"></div> </div> <div id="publishers" class="c5 off1">Publishers<br><br></div> </div>' P.html '#report', report # await @svc.oaworks.report.rating ror) + % # (if ror._id is '0456r8d26' then '<div class="centre"><img src="https://www.gatesfoundation.org/-/media/logos/logolg.svg"></div>' else '') + ' # (if ror._id is '0456r8d26' then '<a target="_blank" href="https://www.gatesfoundation.org/about/policies-and-resources/open-access-policy">' else '') + ror.name + (if ror._id is '0456r8d26' then '</a>' else '') + '</h1> # papers = if ror._id is '0456r8d26' then await @svc.oaworks.report.supplements.count() else await @src.crossref.works.count filter # citations = await @svc.oaworks.report.citations ror # if citations.oa_extra_percent # ret += '<br>Get ' + citations.oa_extra_percent + '% more citations by publishing OA!' # for await rec from @index._for (if ror._id is '0456r8d26' then 'svc_oaworks_report_supplements' else 'src_crossref_works'), filter, {sort: {published: 'desc'}, until: 100} # rec = rec.crossref # ret += '<div class="bordered-warning">' if not rec.is_oa # ret += '<a target="_blank" href="https://doi.org/' + rec.DOI + '">' + rec.title?[0] + '</a><br>' # ret += rec['container-title']?[0] + ', ' + rec.published.split('-').reverse().join('/') + '. ' + rec.publisher + '<br>' # for a in rec.author ? [] # for aff in a.affiliation ? [] # if aff.name and aff.name.toLowerCase().includes 'gates' # ret += 'Author ' + a.given + ' ' + a.family + ' affiliated with ' + aff.name + '. ' # ret += '</div>' if not rec.is_oa # ret += '<br><br>' # ret += '<p>TODO add autoscroll to load more</p>' #for pu in await @svc.oaworks.report.publishers filter # ret += '<p>' + pu.name + '<br>' + pu.percent + '% of ' + pu.papers + ' papers open' + (if pu.percent >= 50 then '!' else '') + '</p>'
74995
P.append 'body', ' <div id="welcome"> <div class="flex" style="margin-top: 5%;"><div class="c6 off3"> <h1 id="title" class="centre statement" style="font-size:40px;">Welcome to OA.Report</h1> </div></div> <div class="flex" style="margin-top: 5%;"> <div class="c6 off3"> <div id="funders"> <p>Great tool does great things.</p> <p>RIGHT NOW DOES NOTHING! UNDERGOING CHANGES...</p> <p>Funders! (or organisations) Find out if your recipients are meeting your policy expectations, take action if not:</p> <p><input type="text" class="PSuggest PForOrganisation" placeholder="Find an organisation" url="/src/ror/suggest/name/"></p> <div class="PSuggestions PForOrganisation"></div> </div> </div> </div> </div> <div id="report" style="display:none;"></div>' P.suggest {include: ["_id"], suggestion: (e, val, rec) -> window.location = window.location.href + "/" + rec._id }, "#funders" report = ' <div class="flex" style="margin-top: 5%;"> <div class="c1 off1 green"><h1 class="centre" id="rating"></h1></div><div class="c8"> <h1 id="title" class="centre statement" style="font-size:40px;"> </div> </div> <div class="flex" style="margin-top: 5%;"> <div class="c5 off1"> <p id="papercount"></p> <p id="citationcount"></p> <p><a href="//static.oa.works/report">Export</a> or <a id="refresh" href="#">refresh</a></p> <p><br></p> <div id="records"></div> </div> <div id="publishers" class="c5 off1">Publishers<br><br></div> </div>' P.html '#report', report # await @svc.oaworks.report.rating ror) + % # (if ror._id is '0456r8d26' then '<div class="centre"><img src="https://www.gatesfoundation.org/-/media/logos/logolg.svg"></div>' else '') + ' # (if ror._id is '0456r8d26' then '<a target="_blank" href="https://www.gatesfoundation.org/about/policies-and-resources/open-access-policy">' else '') + ror.name + (if ror._id is '0456r8d26' then '</a>' else '') + '</h1> # papers = if ror._id is '0456r8d26' then await @svc.oaworks.report.supplements.count() else await @src.crossref.works.count filter # citations = await @svc.oaworks.report.citations ror # if citations.oa_extra_percent # ret += '<br>Get ' + citations.oa_extra_percent + '% more citations by publishing OA!' # for await rec from @index._for (if ror._id is '0456r8d26' then 'svc_oaworks_report_supplements' else 'src_crossref_works'), filter, {sort: {published: 'desc'}, until: 100} # rec = rec.crossref # ret += '<div class="bordered-warning">' if not rec.is_oa # ret += '<a target="_blank" href="https://doi.org/' + rec.DOI + '">' + rec.title?[0] + '</a><br>' # ret += rec['container-title']?[0] + ', ' + rec.published.split('-').reverse().join('/') + '. ' + rec.publisher + '<br>' # for a in rec.author ? [] # for aff in a.affiliation ? [] # if aff.name and aff.name.toLowerCase().includes 'g<NAME>' # ret += 'Author ' + a.given + ' ' + a.family + ' affiliated with ' + aff.name + '. ' # ret += '</div>' if not rec.is_oa # ret += '<br><br>' # ret += '<p>TODO add autoscroll to load more</p>' #for pu in await @svc.oaworks.report.publishers filter # ret += '<p>' + pu.name + '<br>' + pu.percent + '% of ' + pu.papers + ' papers open' + (if pu.percent >= 50 then '!' else '') + '</p>'
true
P.append 'body', ' <div id="welcome"> <div class="flex" style="margin-top: 5%;"><div class="c6 off3"> <h1 id="title" class="centre statement" style="font-size:40px;">Welcome to OA.Report</h1> </div></div> <div class="flex" style="margin-top: 5%;"> <div class="c6 off3"> <div id="funders"> <p>Great tool does great things.</p> <p>RIGHT NOW DOES NOTHING! UNDERGOING CHANGES...</p> <p>Funders! (or organisations) Find out if your recipients are meeting your policy expectations, take action if not:</p> <p><input type="text" class="PSuggest PForOrganisation" placeholder="Find an organisation" url="/src/ror/suggest/name/"></p> <div class="PSuggestions PForOrganisation"></div> </div> </div> </div> </div> <div id="report" style="display:none;"></div>' P.suggest {include: ["_id"], suggestion: (e, val, rec) -> window.location = window.location.href + "/" + rec._id }, "#funders" report = ' <div class="flex" style="margin-top: 5%;"> <div class="c1 off1 green"><h1 class="centre" id="rating"></h1></div><div class="c8"> <h1 id="title" class="centre statement" style="font-size:40px;"> </div> </div> <div class="flex" style="margin-top: 5%;"> <div class="c5 off1"> <p id="papercount"></p> <p id="citationcount"></p> <p><a href="//static.oa.works/report">Export</a> or <a id="refresh" href="#">refresh</a></p> <p><br></p> <div id="records"></div> </div> <div id="publishers" class="c5 off1">Publishers<br><br></div> </div>' P.html '#report', report # await @svc.oaworks.report.rating ror) + % # (if ror._id is '0456r8d26' then '<div class="centre"><img src="https://www.gatesfoundation.org/-/media/logos/logolg.svg"></div>' else '') + ' # (if ror._id is '0456r8d26' then '<a target="_blank" href="https://www.gatesfoundation.org/about/policies-and-resources/open-access-policy">' else '') + ror.name + (if ror._id is '0456r8d26' then '</a>' else '') + '</h1> # papers = if ror._id is '0456r8d26' then await @svc.oaworks.report.supplements.count() else await @src.crossref.works.count filter # citations = await @svc.oaworks.report.citations ror # if citations.oa_extra_percent # ret += '<br>Get ' + citations.oa_extra_percent + '% more citations by publishing OA!' # for await rec from @index._for (if ror._id is '0456r8d26' then 'svc_oaworks_report_supplements' else 'src_crossref_works'), filter, {sort: {published: 'desc'}, until: 100} # rec = rec.crossref # ret += '<div class="bordered-warning">' if not rec.is_oa # ret += '<a target="_blank" href="https://doi.org/' + rec.DOI + '">' + rec.title?[0] + '</a><br>' # ret += rec['container-title']?[0] + ', ' + rec.published.split('-').reverse().join('/') + '. ' + rec.publisher + '<br>' # for a in rec.author ? [] # for aff in a.affiliation ? [] # if aff.name and aff.name.toLowerCase().includes 'gPI:NAME:<NAME>END_PI' # ret += 'Author ' + a.given + ' ' + a.family + ' affiliated with ' + aff.name + '. ' # ret += '</div>' if not rec.is_oa # ret += '<br><br>' # ret += '<p>TODO add autoscroll to load more</p>' #for pu in await @svc.oaworks.report.publishers filter # ret += '<p>' + pu.name + '<br>' + pu.percent + '% of ' + pu.papers + ' papers open' + (if pu.percent >= 50 then '!' else '') + '</p>'
[ { "context": "(app)\n .post \"/profile\"\n .send { name: \"John Doe\", password: \"password\" }\n .expect 201\n ", "end": 326, "score": 0.9998476505279541, "start": 318, "tag": "NAME", "value": "John Doe" }, { "context": "ofile\"\n .send { name: \"John Doe\",...
test/signup.coffee
aegypius/smarter-tv
0
describe "Signup", -> it "should display signup form when navigating to /signup", (done)-> request(app) .get "/signup" .expect "Content-Type", /html/ .expect 200 .end done it "should be able to register new user", (done)-> request(app) .post "/profile" .send { name: "John Doe", password: "password" } .expect 201 .end done
30301
describe "Signup", -> it "should display signup form when navigating to /signup", (done)-> request(app) .get "/signup" .expect "Content-Type", /html/ .expect 200 .end done it "should be able to register new user", (done)-> request(app) .post "/profile" .send { name: "<NAME>", password: "<PASSWORD>" } .expect 201 .end done
true
describe "Signup", -> it "should display signup form when navigating to /signup", (done)-> request(app) .get "/signup" .expect "Content-Type", /html/ .expect 200 .end done it "should be able to register new user", (done)-> request(app) .post "/profile" .send { name: "PI:NAME:<NAME>END_PI", password: "PI:PASSWORD:<PASSWORD>END_PI" } .expect 201 .end done
[ { "context": "(package) -> package.meatyGoodness\n keys: ['Bacon', 'BloodSausage']\n\n.export(module)\n", "end": 1279, "score": 0.9304208159446716, "start": 1274, "tag": "KEY", "value": "Bacon" }, { "context": " -> package.meatyGoodness\n keys: ['Bacon', 'BloodSausage']\n...
cdap-web-app/tools/node_modules/groc/node_modules/autorequire/test/classical_convention_test.coffee
cybervisiontech/cdap
0
test = require './common' process.env['convention'] = 'Classical' subModulesShouldMatch = (opts) -> topic: opts.topic 'we should be given an object with a CamelCaps key per submodule': (package) -> test.assert.keysEqual package, opts.keys 'each exported property should match the exports of each submodule': (package) -> test.assert.deepEqual (v[0] for k,v of package).sort(), opts.keys.sort() test.vows.describe('Classical Convention').addBatch 'when we autorequire the example package "fuzzy"': subModulesShouldMatch topic: -> test.autorequire('./examples/fuzzy', 'Classical') keys: ['BabyThing', 'Kitten', 'Puppy', 'Squidlet'] 'when we require the example autorequired package "mixed_tastes"': topic: -> require('./examples/mixed_tastes') 'we should be given an object with a camelCase key per namespace': (package) -> test.assert.keysEqual package, ['imbibables', 'Legumes', 'meatyGoodness'] 'and we traverse into the "imbibables" namespace': subModulesShouldMatch topic: (package) -> package.imbibables keys: ['Coffee', 'HighlyDistilledCactusJuice', 'Tea'] 'and we traverse into the "meatyGoodness" namespace': subModulesShouldMatch topic: (package) -> package.meatyGoodness keys: ['Bacon', 'BloodSausage'] .export(module)
6129
test = require './common' process.env['convention'] = 'Classical' subModulesShouldMatch = (opts) -> topic: opts.topic 'we should be given an object with a CamelCaps key per submodule': (package) -> test.assert.keysEqual package, opts.keys 'each exported property should match the exports of each submodule': (package) -> test.assert.deepEqual (v[0] for k,v of package).sort(), opts.keys.sort() test.vows.describe('Classical Convention').addBatch 'when we autorequire the example package "fuzzy"': subModulesShouldMatch topic: -> test.autorequire('./examples/fuzzy', 'Classical') keys: ['BabyThing', 'Kitten', 'Puppy', 'Squidlet'] 'when we require the example autorequired package "mixed_tastes"': topic: -> require('./examples/mixed_tastes') 'we should be given an object with a camelCase key per namespace': (package) -> test.assert.keysEqual package, ['imbibables', 'Legumes', 'meatyGoodness'] 'and we traverse into the "imbibables" namespace': subModulesShouldMatch topic: (package) -> package.imbibables keys: ['Coffee', 'HighlyDistilledCactusJuice', 'Tea'] 'and we traverse into the "meatyGoodness" namespace': subModulesShouldMatch topic: (package) -> package.meatyGoodness keys: ['<KEY>', '<KEY>'] .export(module)
true
test = require './common' process.env['convention'] = 'Classical' subModulesShouldMatch = (opts) -> topic: opts.topic 'we should be given an object with a CamelCaps key per submodule': (package) -> test.assert.keysEqual package, opts.keys 'each exported property should match the exports of each submodule': (package) -> test.assert.deepEqual (v[0] for k,v of package).sort(), opts.keys.sort() test.vows.describe('Classical Convention').addBatch 'when we autorequire the example package "fuzzy"': subModulesShouldMatch topic: -> test.autorequire('./examples/fuzzy', 'Classical') keys: ['BabyThing', 'Kitten', 'Puppy', 'Squidlet'] 'when we require the example autorequired package "mixed_tastes"': topic: -> require('./examples/mixed_tastes') 'we should be given an object with a camelCase key per namespace': (package) -> test.assert.keysEqual package, ['imbibables', 'Legumes', 'meatyGoodness'] 'and we traverse into the "imbibables" namespace': subModulesShouldMatch topic: (package) -> package.imbibables keys: ['Coffee', 'HighlyDistilledCactusJuice', 'Tea'] 'and we traverse into the "meatyGoodness" namespace': subModulesShouldMatch topic: (package) -> package.meatyGoodness keys: ['PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI'] .export(module)
[ { "context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission", "end": 18, "score": 0.9993665814399719, "start": 12, "tag": "NAME", "value": "Joyent" } ]
test/common.coffee
lxe/io.coffee
0
# Copyright Joyent, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. # Remove manually, the test runner won't do it # for us like it does for files in test/tmp. # Ignore. #for (var i in exports) global[i] = exports[i]; protoCtrChain = (o) -> result = [] while o result.push o.constructor o = o.__proto__ result.join() # Enumerable in V8 3.21. # Harmony features. leakedGlobals = -> leaked = [] for val of global continue leaked # Turn this off if the test should not check for global leaks. runCallChecks = (exitCode) -> return if exitCode isnt 0 failed = mustCallChecks.filter((context) -> context.actual isnt context.expected ) failed.forEach (context) -> console.log "Mismatched %s function calls. Expected %d, actual %d.", context.name, context.expected, context.actual console.log context.stack.split("\n").slice(2).join("\n") return process.exit 1 if failed.length return path = require("path") fs = require("fs") assert = require("assert") os = require("os") exports.testDir = path.dirname(__filename) exports.fixturesDir = path.join(exports.testDir, "fixtures") exports.libDir = path.join(exports.testDir, "../lib") exports.tmpDir = path.join(exports.testDir, "tmp") exports.PORT = +process.env.NODE_COMMON_PORT or 12346 exports.opensslCli = path.join(path.dirname(process.execPath), "openssl-cli") if process.platform is "win32" exports.PIPE = "\\\\.\\pipe\\libuv-test" exports.opensslCli += ".exe" else exports.PIPE = exports.tmpDir + "/test.sock" if process.env.NODE_COMMON_PIPE exports.PIPE = process.env.NODE_COMMON_PIPE try fs.unlinkSync exports.PIPE exports.opensslCli = false unless fs.existsSync(exports.opensslCli) if process.platform is "win32" exports.faketimeCli = false else exports.faketimeCli = path.join(__dirname, "..", "tools", "faketime", "src", "faketime") ifaces = os.networkInterfaces() exports.hasIPv6 = Object.keys(ifaces).some((name) -> /lo/.test(name) and ifaces[name].some((info) -> info.family is "IPv6" ) ) util = require("util") for i of util exports[i] = util[i] exports.indirectInstanceOf = (obj, cls) -> return true if obj instanceof cls clsChain = protoCtrChain(cls::) objChain = protoCtrChain(obj) objChain.slice(-clsChain.length) is clsChain exports.ddCommand = (filename, kilobytes) -> if process.platform is "win32" p = path.resolve(exports.fixturesDir, "create-file.js") "\"" + process.argv[0] + "\" \"" + p + "\" \"" + filename + "\" " + (kilobytes * 1024) else "dd if=/dev/zero of=\"" + filename + "\" bs=1024 count=" + kilobytes exports.spawnCat = (options) -> spawn = require("child_process").spawn if process.platform is "win32" spawn "more", [], options else spawn "cat", [], options exports.spawnPwd = (options) -> spawn = require("child_process").spawn if process.platform is "win32" spawn "cmd.exe", [ "/c" "cd" ], options else spawn "pwd", [], options knownGlobals = [ setTimeout setInterval setImmediate clearTimeout clearInterval clearImmediate console constructor Buffer process global ] knownGlobals.push gc if global.gc if global.DTRACE_HTTP_SERVER_RESPONSE knownGlobals.push DTRACE_HTTP_SERVER_RESPONSE knownGlobals.push DTRACE_HTTP_SERVER_REQUEST knownGlobals.push DTRACE_HTTP_CLIENT_RESPONSE knownGlobals.push DTRACE_HTTP_CLIENT_REQUEST knownGlobals.push DTRACE_NET_STREAM_END knownGlobals.push DTRACE_NET_SERVER_CONNECTION knownGlobals.push DTRACE_NET_SOCKET_READ knownGlobals.push DTRACE_NET_SOCKET_WRITE if global.COUNTER_NET_SERVER_CONNECTION knownGlobals.push COUNTER_NET_SERVER_CONNECTION knownGlobals.push COUNTER_NET_SERVER_CONNECTION_CLOSE knownGlobals.push COUNTER_HTTP_SERVER_REQUEST knownGlobals.push COUNTER_HTTP_SERVER_RESPONSE knownGlobals.push COUNTER_HTTP_CLIENT_REQUEST knownGlobals.push COUNTER_HTTP_CLIENT_RESPONSE if global.ArrayBuffer knownGlobals.push ArrayBuffer knownGlobals.push Int8Array knownGlobals.push Uint8Array knownGlobals.push Uint8ClampedArray knownGlobals.push Int16Array knownGlobals.push Uint16Array knownGlobals.push Int32Array knownGlobals.push Uint32Array knownGlobals.push Float32Array knownGlobals.push Float64Array knownGlobals.push DataView knownGlobals.push Proxy if global.Proxy knownGlobals.push Symbol if global.Symbol exports.leakedGlobals = leakedGlobals exports.globalCheck = true process.on "exit", -> return unless exports.globalCheck leaked = leakedGlobals() if leaked.length > 0 console.error "Unknown globals: %s", leaked assert.ok false, "Unknown global found" return mustCallChecks = [] exports.mustCall = (fn, expected) -> expected = 1 if typeof expected isnt "number" context = expected: expected actual: 0 stack: (new Error).stack name: fn.name or "<anonymous>" # add the exit listener only once to avoid listener leak warnings process.on "exit", runCallChecks if mustCallChecks.length is 0 mustCallChecks.push context -> context.actual++ fn.apply this, arguments exports.checkSpawnSyncRet = (ret) -> assert.strictEqual ret.status, 0 assert.strictEqual ret.error, `undefined` return etcServicesFileName = path.join("/etc", "services") etcServicesFileName = path.join(process.env.SystemRoot, "System32", "drivers", "etc", "services") if process.platform is "win32" # # * Returns a string that represents the service name associated # * to the service bound to port "port" and using protocol "protocol". # * # * If the service is not defined in the services file, it returns # * the port number as a string. # * # * Returns undefined if /etc/services (or its equivalent on non-UNIX # * platforms) can't be read. # exports.getServiceName = getServiceName = (port, protocol) -> throw new Error("Missing port number") unless port? throw new Error("Protocol must be a string") if typeof protocol isnt "string" # # * By default, if a service can't be found in /etc/services, # * its name is considered to be its port number. # serviceName = port.toString() try # # * I'm not a big fan of readFileSync, but reading /etc/services asynchronously # * here would require implementing a simple line parser, which seems overkill # * for a simple utility function that is not running concurrently with any # * other one. # servicesContent = fs.readFileSync(etcServicesFileName, encoding: "utf8" ) regexp = util.format("^(\\w+)\\s+\\s%d/%s\\s", port, protocol) re = new RegExp(regexp, "m") matches = re.exec(servicesContent) serviceName = matches[1] if matches and matches.length > 1 catch e console.error "Cannot read file: ", etcServicesFileName return `undefined` serviceName exports.isValidHostname = (str) -> # See http://stackoverflow.com/a/3824105 re = new RegExp("^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])" + "(\\.([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9]))*$") !!str.match(re) and str.length <= 255
186254
# Copyright <NAME>, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. # Remove manually, the test runner won't do it # for us like it does for files in test/tmp. # Ignore. #for (var i in exports) global[i] = exports[i]; protoCtrChain = (o) -> result = [] while o result.push o.constructor o = o.__proto__ result.join() # Enumerable in V8 3.21. # Harmony features. leakedGlobals = -> leaked = [] for val of global continue leaked # Turn this off if the test should not check for global leaks. runCallChecks = (exitCode) -> return if exitCode isnt 0 failed = mustCallChecks.filter((context) -> context.actual isnt context.expected ) failed.forEach (context) -> console.log "Mismatched %s function calls. Expected %d, actual %d.", context.name, context.expected, context.actual console.log context.stack.split("\n").slice(2).join("\n") return process.exit 1 if failed.length return path = require("path") fs = require("fs") assert = require("assert") os = require("os") exports.testDir = path.dirname(__filename) exports.fixturesDir = path.join(exports.testDir, "fixtures") exports.libDir = path.join(exports.testDir, "../lib") exports.tmpDir = path.join(exports.testDir, "tmp") exports.PORT = +process.env.NODE_COMMON_PORT or 12346 exports.opensslCli = path.join(path.dirname(process.execPath), "openssl-cli") if process.platform is "win32" exports.PIPE = "\\\\.\\pipe\\libuv-test" exports.opensslCli += ".exe" else exports.PIPE = exports.tmpDir + "/test.sock" if process.env.NODE_COMMON_PIPE exports.PIPE = process.env.NODE_COMMON_PIPE try fs.unlinkSync exports.PIPE exports.opensslCli = false unless fs.existsSync(exports.opensslCli) if process.platform is "win32" exports.faketimeCli = false else exports.faketimeCli = path.join(__dirname, "..", "tools", "faketime", "src", "faketime") ifaces = os.networkInterfaces() exports.hasIPv6 = Object.keys(ifaces).some((name) -> /lo/.test(name) and ifaces[name].some((info) -> info.family is "IPv6" ) ) util = require("util") for i of util exports[i] = util[i] exports.indirectInstanceOf = (obj, cls) -> return true if obj instanceof cls clsChain = protoCtrChain(cls::) objChain = protoCtrChain(obj) objChain.slice(-clsChain.length) is clsChain exports.ddCommand = (filename, kilobytes) -> if process.platform is "win32" p = path.resolve(exports.fixturesDir, "create-file.js") "\"" + process.argv[0] + "\" \"" + p + "\" \"" + filename + "\" " + (kilobytes * 1024) else "dd if=/dev/zero of=\"" + filename + "\" bs=1024 count=" + kilobytes exports.spawnCat = (options) -> spawn = require("child_process").spawn if process.platform is "win32" spawn "more", [], options else spawn "cat", [], options exports.spawnPwd = (options) -> spawn = require("child_process").spawn if process.platform is "win32" spawn "cmd.exe", [ "/c" "cd" ], options else spawn "pwd", [], options knownGlobals = [ setTimeout setInterval setImmediate clearTimeout clearInterval clearImmediate console constructor Buffer process global ] knownGlobals.push gc if global.gc if global.DTRACE_HTTP_SERVER_RESPONSE knownGlobals.push DTRACE_HTTP_SERVER_RESPONSE knownGlobals.push DTRACE_HTTP_SERVER_REQUEST knownGlobals.push DTRACE_HTTP_CLIENT_RESPONSE knownGlobals.push DTRACE_HTTP_CLIENT_REQUEST knownGlobals.push DTRACE_NET_STREAM_END knownGlobals.push DTRACE_NET_SERVER_CONNECTION knownGlobals.push DTRACE_NET_SOCKET_READ knownGlobals.push DTRACE_NET_SOCKET_WRITE if global.COUNTER_NET_SERVER_CONNECTION knownGlobals.push COUNTER_NET_SERVER_CONNECTION knownGlobals.push COUNTER_NET_SERVER_CONNECTION_CLOSE knownGlobals.push COUNTER_HTTP_SERVER_REQUEST knownGlobals.push COUNTER_HTTP_SERVER_RESPONSE knownGlobals.push COUNTER_HTTP_CLIENT_REQUEST knownGlobals.push COUNTER_HTTP_CLIENT_RESPONSE if global.ArrayBuffer knownGlobals.push ArrayBuffer knownGlobals.push Int8Array knownGlobals.push Uint8Array knownGlobals.push Uint8ClampedArray knownGlobals.push Int16Array knownGlobals.push Uint16Array knownGlobals.push Int32Array knownGlobals.push Uint32Array knownGlobals.push Float32Array knownGlobals.push Float64Array knownGlobals.push DataView knownGlobals.push Proxy if global.Proxy knownGlobals.push Symbol if global.Symbol exports.leakedGlobals = leakedGlobals exports.globalCheck = true process.on "exit", -> return unless exports.globalCheck leaked = leakedGlobals() if leaked.length > 0 console.error "Unknown globals: %s", leaked assert.ok false, "Unknown global found" return mustCallChecks = [] exports.mustCall = (fn, expected) -> expected = 1 if typeof expected isnt "number" context = expected: expected actual: 0 stack: (new Error).stack name: fn.name or "<anonymous>" # add the exit listener only once to avoid listener leak warnings process.on "exit", runCallChecks if mustCallChecks.length is 0 mustCallChecks.push context -> context.actual++ fn.apply this, arguments exports.checkSpawnSyncRet = (ret) -> assert.strictEqual ret.status, 0 assert.strictEqual ret.error, `undefined` return etcServicesFileName = path.join("/etc", "services") etcServicesFileName = path.join(process.env.SystemRoot, "System32", "drivers", "etc", "services") if process.platform is "win32" # # * Returns a string that represents the service name associated # * to the service bound to port "port" and using protocol "protocol". # * # * If the service is not defined in the services file, it returns # * the port number as a string. # * # * Returns undefined if /etc/services (or its equivalent on non-UNIX # * platforms) can't be read. # exports.getServiceName = getServiceName = (port, protocol) -> throw new Error("Missing port number") unless port? throw new Error("Protocol must be a string") if typeof protocol isnt "string" # # * By default, if a service can't be found in /etc/services, # * its name is considered to be its port number. # serviceName = port.toString() try # # * I'm not a big fan of readFileSync, but reading /etc/services asynchronously # * here would require implementing a simple line parser, which seems overkill # * for a simple utility function that is not running concurrently with any # * other one. # servicesContent = fs.readFileSync(etcServicesFileName, encoding: "utf8" ) regexp = util.format("^(\\w+)\\s+\\s%d/%s\\s", port, protocol) re = new RegExp(regexp, "m") matches = re.exec(servicesContent) serviceName = matches[1] if matches and matches.length > 1 catch e console.error "Cannot read file: ", etcServicesFileName return `undefined` serviceName exports.isValidHostname = (str) -> # See http://stackoverflow.com/a/3824105 re = new RegExp("^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])" + "(\\.([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9]))*$") !!str.match(re) and str.length <= 255
true
# Copyright PI:NAME:<NAME>END_PI, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. # Remove manually, the test runner won't do it # for us like it does for files in test/tmp. # Ignore. #for (var i in exports) global[i] = exports[i]; protoCtrChain = (o) -> result = [] while o result.push o.constructor o = o.__proto__ result.join() # Enumerable in V8 3.21. # Harmony features. leakedGlobals = -> leaked = [] for val of global continue leaked # Turn this off if the test should not check for global leaks. runCallChecks = (exitCode) -> return if exitCode isnt 0 failed = mustCallChecks.filter((context) -> context.actual isnt context.expected ) failed.forEach (context) -> console.log "Mismatched %s function calls. Expected %d, actual %d.", context.name, context.expected, context.actual console.log context.stack.split("\n").slice(2).join("\n") return process.exit 1 if failed.length return path = require("path") fs = require("fs") assert = require("assert") os = require("os") exports.testDir = path.dirname(__filename) exports.fixturesDir = path.join(exports.testDir, "fixtures") exports.libDir = path.join(exports.testDir, "../lib") exports.tmpDir = path.join(exports.testDir, "tmp") exports.PORT = +process.env.NODE_COMMON_PORT or 12346 exports.opensslCli = path.join(path.dirname(process.execPath), "openssl-cli") if process.platform is "win32" exports.PIPE = "\\\\.\\pipe\\libuv-test" exports.opensslCli += ".exe" else exports.PIPE = exports.tmpDir + "/test.sock" if process.env.NODE_COMMON_PIPE exports.PIPE = process.env.NODE_COMMON_PIPE try fs.unlinkSync exports.PIPE exports.opensslCli = false unless fs.existsSync(exports.opensslCli) if process.platform is "win32" exports.faketimeCli = false else exports.faketimeCli = path.join(__dirname, "..", "tools", "faketime", "src", "faketime") ifaces = os.networkInterfaces() exports.hasIPv6 = Object.keys(ifaces).some((name) -> /lo/.test(name) and ifaces[name].some((info) -> info.family is "IPv6" ) ) util = require("util") for i of util exports[i] = util[i] exports.indirectInstanceOf = (obj, cls) -> return true if obj instanceof cls clsChain = protoCtrChain(cls::) objChain = protoCtrChain(obj) objChain.slice(-clsChain.length) is clsChain exports.ddCommand = (filename, kilobytes) -> if process.platform is "win32" p = path.resolve(exports.fixturesDir, "create-file.js") "\"" + process.argv[0] + "\" \"" + p + "\" \"" + filename + "\" " + (kilobytes * 1024) else "dd if=/dev/zero of=\"" + filename + "\" bs=1024 count=" + kilobytes exports.spawnCat = (options) -> spawn = require("child_process").spawn if process.platform is "win32" spawn "more", [], options else spawn "cat", [], options exports.spawnPwd = (options) -> spawn = require("child_process").spawn if process.platform is "win32" spawn "cmd.exe", [ "/c" "cd" ], options else spawn "pwd", [], options knownGlobals = [ setTimeout setInterval setImmediate clearTimeout clearInterval clearImmediate console constructor Buffer process global ] knownGlobals.push gc if global.gc if global.DTRACE_HTTP_SERVER_RESPONSE knownGlobals.push DTRACE_HTTP_SERVER_RESPONSE knownGlobals.push DTRACE_HTTP_SERVER_REQUEST knownGlobals.push DTRACE_HTTP_CLIENT_RESPONSE knownGlobals.push DTRACE_HTTP_CLIENT_REQUEST knownGlobals.push DTRACE_NET_STREAM_END knownGlobals.push DTRACE_NET_SERVER_CONNECTION knownGlobals.push DTRACE_NET_SOCKET_READ knownGlobals.push DTRACE_NET_SOCKET_WRITE if global.COUNTER_NET_SERVER_CONNECTION knownGlobals.push COUNTER_NET_SERVER_CONNECTION knownGlobals.push COUNTER_NET_SERVER_CONNECTION_CLOSE knownGlobals.push COUNTER_HTTP_SERVER_REQUEST knownGlobals.push COUNTER_HTTP_SERVER_RESPONSE knownGlobals.push COUNTER_HTTP_CLIENT_REQUEST knownGlobals.push COUNTER_HTTP_CLIENT_RESPONSE if global.ArrayBuffer knownGlobals.push ArrayBuffer knownGlobals.push Int8Array knownGlobals.push Uint8Array knownGlobals.push Uint8ClampedArray knownGlobals.push Int16Array knownGlobals.push Uint16Array knownGlobals.push Int32Array knownGlobals.push Uint32Array knownGlobals.push Float32Array knownGlobals.push Float64Array knownGlobals.push DataView knownGlobals.push Proxy if global.Proxy knownGlobals.push Symbol if global.Symbol exports.leakedGlobals = leakedGlobals exports.globalCheck = true process.on "exit", -> return unless exports.globalCheck leaked = leakedGlobals() if leaked.length > 0 console.error "Unknown globals: %s", leaked assert.ok false, "Unknown global found" return mustCallChecks = [] exports.mustCall = (fn, expected) -> expected = 1 if typeof expected isnt "number" context = expected: expected actual: 0 stack: (new Error).stack name: fn.name or "<anonymous>" # add the exit listener only once to avoid listener leak warnings process.on "exit", runCallChecks if mustCallChecks.length is 0 mustCallChecks.push context -> context.actual++ fn.apply this, arguments exports.checkSpawnSyncRet = (ret) -> assert.strictEqual ret.status, 0 assert.strictEqual ret.error, `undefined` return etcServicesFileName = path.join("/etc", "services") etcServicesFileName = path.join(process.env.SystemRoot, "System32", "drivers", "etc", "services") if process.platform is "win32" # # * Returns a string that represents the service name associated # * to the service bound to port "port" and using protocol "protocol". # * # * If the service is not defined in the services file, it returns # * the port number as a string. # * # * Returns undefined if /etc/services (or its equivalent on non-UNIX # * platforms) can't be read. # exports.getServiceName = getServiceName = (port, protocol) -> throw new Error("Missing port number") unless port? throw new Error("Protocol must be a string") if typeof protocol isnt "string" # # * By default, if a service can't be found in /etc/services, # * its name is considered to be its port number. # serviceName = port.toString() try # # * I'm not a big fan of readFileSync, but reading /etc/services asynchronously # * here would require implementing a simple line parser, which seems overkill # * for a simple utility function that is not running concurrently with any # * other one. # servicesContent = fs.readFileSync(etcServicesFileName, encoding: "utf8" ) regexp = util.format("^(\\w+)\\s+\\s%d/%s\\s", port, protocol) re = new RegExp(regexp, "m") matches = re.exec(servicesContent) serviceName = matches[1] if matches and matches.length > 1 catch e console.error "Cannot read file: ", etcServicesFileName return `undefined` serviceName exports.isValidHostname = (str) -> # See http://stackoverflow.com/a/3824105 re = new RegExp("^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])" + "(\\.([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9]))*$") !!str.match(re) and str.length <= 255
[ { "context": "ser:\n email: @state.email\n password: @state.password\n\n @props.onSignIn(data)\n\n render: ->\n <div", "end": 375, "score": 0.997913122177124, "start": 360, "tag": "PASSWORD", "value": "@state.password" }, { "context": "me='input-field'>\n ...
src/auth.cjsx
Boxenite/daemon
0
Router = require 'react-router' React = Router.React module.exports = Auth = React.createClass getInitialState: -> {} changeEmail: (e) -> @setState(email: e.target.value) changePassword: (e) -> @setState(password: e.target.value) submit: (e) -> e.preventDefault() data = user: email: @state.email password: @state.password @props.onSignIn(data) render: -> <div className='container'> <div className='logo row'> <div className='col s8'> <img className='responsive-img' src='img/logo.png' /> </div> </div> <form onSubmit={@submit}> <div className='row'> <div className='input-field'> <input placeholder='Email' type='text' value={@state.email} onChange={@changeEmail}/> </div> </div> <div className='row'> <div className='input-field'> <input placeholder='Password' type='password' value={@state.password} onChange={@changePassword}/> </div> </div> <div className='row center-align'> <div className='input-field'> <button className="waves-effect waves-light btn-large">Sign in</button> </div> </div> </form> </div>
33762
Router = require 'react-router' React = Router.React module.exports = Auth = React.createClass getInitialState: -> {} changeEmail: (e) -> @setState(email: e.target.value) changePassword: (e) -> @setState(password: e.target.value) submit: (e) -> e.preventDefault() data = user: email: @state.email password: <PASSWORD> @props.onSignIn(data) render: -> <div className='container'> <div className='logo row'> <div className='col s8'> <img className='responsive-img' src='img/logo.png' /> </div> </div> <form onSubmit={@submit}> <div className='row'> <div className='input-field'> <input placeholder='Email' type='text' value={@state.email} onChange={@changeEmail}/> </div> </div> <div className='row'> <div className='input-field'> <input placeholder='<PASSWORD>' type='password' value={<PASSWORD>} onChange={@changePassword}/> </div> </div> <div className='row center-align'> <div className='input-field'> <button className="waves-effect waves-light btn-large">Sign in</button> </div> </div> </form> </div>
true
Router = require 'react-router' React = Router.React module.exports = Auth = React.createClass getInitialState: -> {} changeEmail: (e) -> @setState(email: e.target.value) changePassword: (e) -> @setState(password: e.target.value) submit: (e) -> e.preventDefault() data = user: email: @state.email password: PI:PASSWORD:<PASSWORD>END_PI @props.onSignIn(data) render: -> <div className='container'> <div className='logo row'> <div className='col s8'> <img className='responsive-img' src='img/logo.png' /> </div> </div> <form onSubmit={@submit}> <div className='row'> <div className='input-field'> <input placeholder='Email' type='text' value={@state.email} onChange={@changeEmail}/> </div> </div> <div className='row'> <div className='input-field'> <input placeholder='PI:PASSWORD:<PASSWORD>END_PI' type='password' value={PI:PASSWORD:<PASSWORD>END_PI} onChange={@changePassword}/> </div> </div> <div className='row center-align'> <div className='input-field'> <button className="waves-effect waves-light btn-large">Sign in</button> </div> </div> </form> </div>
[ { "context": "da database for genomic variation frequencies.\n#\n# Martijn Vermaat <m.vermaat.hg@lumc.nl>\n#\n# Licensed under the MIT", "end": 103, "score": 0.9998842477798462, "start": 88, "tag": "NAME", "value": "Martijn Vermaat" }, { "context": "nomic variation frequencies.\n#\n#...
scripts/init.coffee
varda/aule-test
1
# Aulë # # A web interface to the Varda database for genomic variation frequencies. # # Martijn Vermaat <m.vermaat.hg@lumc.nl> # # Licensed under the MIT license, see the LICENSE file. $ = require 'jquery' td = require 'throttle-debounce' config = require 'config' Api = require './api' app = require './app' require 'bootstrap/js/bootstrap-alert' require 'bootstrap/js/bootstrap-collapse' require 'bootstrap/js/bootstrap-modal' require 'bootstrap/js/bootstrap-transition' require 'bootstrap/less/bootstrap.less' require 'bootstrap/less/responsive.less' require '../stylesheets/aule.less' # On document ready $ -> # Capture authentication form submit with Sammy (it's outside its # element). $(document).on 'submit', '#form-authenticate', (e) -> returned = app._checkFormSubmission $(e.target).closest 'form' if returned is false e.preventDefault() else false # Clear the authentication status when we type. $(document).on 'input', '#form-authenticate input', -> $('#form-authenticate').removeClass 'success fail' # Helper function for updating dirty flags on edit forms. Both # arguments should be jQuery objects. setDirty = (field, label) -> field.addClass 'dirty' label.addClass 'dirty' # Here we aggregate the names of the dirty form fields into the field # '#dirty'. Unfortunately I couldn't manage to do this in the form # submit handler because it would always be called after the Sammy # route was called. So we do this aggregation on every field change # (this includes pressing a key in a text field). form = field.closest 'form' #$('#dirty', form).val ($(x).attr 'name' for x in $(':input.dirty', form)) $('#dirty', form).val (for x in $(':input.dirty, .form-picker.dirty', form) ($(x).attr 'name') or ($(x).data 'name')) # Keep track of dirty fields in edit forms. $(document).on 'input', '.form-edit :input', -> setDirty $(@), $("label[for='#{ @id }']") $(document).on 'change','.form-edit input:checkbox, .form-edit input:radio', -> setDirty $(@), $(@).parent('label') $(document).on 'reset', '.form-edit', -> $(':input, .form-picker, label', @).removeClass 'dirty' $('#dirty', @).val [] # Facilitate clicking anywhere in a table row. $(document).on 'click', 'tbody tr[data-href]', (e) -> e.preventDefault() app.setLocation $(this).data('href') # Open the picker modal. $(document).on 'click', 'a.picker-open', (e) -> e.preventDefault() $('#picker').data('source', $(this).closest('.form-picker')) app.runRoute 'get', $(this).attr('href') # Clicking a row in the picker. $(document).on 'click', '#picker tbody tr[data-value]', (e) -> e.preventDefault() source = $('#picker').data('source') add = $('div', source).last() element = $("<div> <input name=\"#{ source.data 'name' }\" type=\"hidden\" value=\"#{ $(this).data 'value' }\"> <i class=\"fa fa-remove\"></i> #{ $(this).data 'name' } </div>") add.before(element) add.hide() unless source.data 'multi' setDirty source, $("label[for='#{ source.data 'name' }']") $('#picker').modal('hide') # Removing an element from a picker field. $(document).on 'click', '.form-picker div i', (e) -> element = $(this).closest('div') source = element.parent() add = $('div', source).last() element.remove() add.show() setDirty source, $("label[for='#{ source.data 'name' }']") # Navigation in the picker modal. $(document).on 'click', '#picker a', (e) -> e.preventDefault() app.runRoute 'get', $(this).attr('href') # Reset all pickers. $(document).on 'reset', 'form', -> $('.form-picker', @).each -> add = $('div', this).last().detach() $('div', this).remove() add.appendTo this add.show() # Transcript query input element. $(document).on 'input', '.transcript-querier', td.debounce 250, -> route = "#{ config.RESOURCES_PREFIX }/transcript_query" app.runRoute 'get', route, query: $(@).val().trim() # Show the user that we are waiting for the server. $(document) .bind('ajaxStart', -> $('#waiting').fadeIn duration: 'slow', queue: false $('button').prop 'disabled', true) .bind('ajaxStop', -> $('#waiting').fadeOut duration: 'fast', queue: false $('button').prop 'disabled', false) # Instantiate API client and run app. $('body').html require('../templates/loading.hb')() api = new Api config.API_ROOT api.init error: (code, message) -> $('body').html require('../templates/loading_error.hb') error: code: code message: message success: -> $('body').html require('../templates/application.hb') base: config.BASE app.init api app.run() module.exports = {}
70280
# Aulë # # A web interface to the Varda database for genomic variation frequencies. # # <NAME> <<EMAIL>> # # Licensed under the MIT license, see the LICENSE file. $ = require 'jquery' td = require 'throttle-debounce' config = require 'config' Api = require './api' app = require './app' require 'bootstrap/js/bootstrap-alert' require 'bootstrap/js/bootstrap-collapse' require 'bootstrap/js/bootstrap-modal' require 'bootstrap/js/bootstrap-transition' require 'bootstrap/less/bootstrap.less' require 'bootstrap/less/responsive.less' require '../stylesheets/aule.less' # On document ready $ -> # Capture authentication form submit with Sammy (it's outside its # element). $(document).on 'submit', '#form-authenticate', (e) -> returned = app._checkFormSubmission $(e.target).closest 'form' if returned is false e.preventDefault() else false # Clear the authentication status when we type. $(document).on 'input', '#form-authenticate input', -> $('#form-authenticate').removeClass 'success fail' # Helper function for updating dirty flags on edit forms. Both # arguments should be jQuery objects. setDirty = (field, label) -> field.addClass 'dirty' label.addClass 'dirty' # Here we aggregate the names of the dirty form fields into the field # '#dirty'. Unfortunately I couldn't manage to do this in the form # submit handler because it would always be called after the Sammy # route was called. So we do this aggregation on every field change # (this includes pressing a key in a text field). form = field.closest 'form' #$('#dirty', form).val ($(x).attr 'name' for x in $(':input.dirty', form)) $('#dirty', form).val (for x in $(':input.dirty, .form-picker.dirty', form) ($(x).attr 'name') or ($(x).data 'name')) # Keep track of dirty fields in edit forms. $(document).on 'input', '.form-edit :input', -> setDirty $(@), $("label[for='#{ @id }']") $(document).on 'change','.form-edit input:checkbox, .form-edit input:radio', -> setDirty $(@), $(@).parent('label') $(document).on 'reset', '.form-edit', -> $(':input, .form-picker, label', @).removeClass 'dirty' $('#dirty', @).val [] # Facilitate clicking anywhere in a table row. $(document).on 'click', 'tbody tr[data-href]', (e) -> e.preventDefault() app.setLocation $(this).data('href') # Open the picker modal. $(document).on 'click', 'a.picker-open', (e) -> e.preventDefault() $('#picker').data('source', $(this).closest('.form-picker')) app.runRoute 'get', $(this).attr('href') # Clicking a row in the picker. $(document).on 'click', '#picker tbody tr[data-value]', (e) -> e.preventDefault() source = $('#picker').data('source') add = $('div', source).last() element = $("<div> <input name=\"#{ source.data 'name' }\" type=\"hidden\" value=\"#{ $(this).data 'value' }\"> <i class=\"fa fa-remove\"></i> #{ $(this).data 'name' } </div>") add.before(element) add.hide() unless source.data 'multi' setDirty source, $("label[for='#{ source.data 'name' }']") $('#picker').modal('hide') # Removing an element from a picker field. $(document).on 'click', '.form-picker div i', (e) -> element = $(this).closest('div') source = element.parent() add = $('div', source).last() element.remove() add.show() setDirty source, $("label[for='#{ source.data 'name' }']") # Navigation in the picker modal. $(document).on 'click', '#picker a', (e) -> e.preventDefault() app.runRoute 'get', $(this).attr('href') # Reset all pickers. $(document).on 'reset', 'form', -> $('.form-picker', @).each -> add = $('div', this).last().detach() $('div', this).remove() add.appendTo this add.show() # Transcript query input element. $(document).on 'input', '.transcript-querier', td.debounce 250, -> route = "#{ config.RESOURCES_PREFIX }/transcript_query" app.runRoute 'get', route, query: $(@).val().trim() # Show the user that we are waiting for the server. $(document) .bind('ajaxStart', -> $('#waiting').fadeIn duration: 'slow', queue: false $('button').prop 'disabled', true) .bind('ajaxStop', -> $('#waiting').fadeOut duration: 'fast', queue: false $('button').prop 'disabled', false) # Instantiate API client and run app. $('body').html require('../templates/loading.hb')() api = new Api config.API_ROOT api.init error: (code, message) -> $('body').html require('../templates/loading_error.hb') error: code: code message: message success: -> $('body').html require('../templates/application.hb') base: config.BASE app.init api app.run() module.exports = {}
true
# Aulë # # A web interface to the Varda database for genomic variation frequencies. # # PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # # Licensed under the MIT license, see the LICENSE file. $ = require 'jquery' td = require 'throttle-debounce' config = require 'config' Api = require './api' app = require './app' require 'bootstrap/js/bootstrap-alert' require 'bootstrap/js/bootstrap-collapse' require 'bootstrap/js/bootstrap-modal' require 'bootstrap/js/bootstrap-transition' require 'bootstrap/less/bootstrap.less' require 'bootstrap/less/responsive.less' require '../stylesheets/aule.less' # On document ready $ -> # Capture authentication form submit with Sammy (it's outside its # element). $(document).on 'submit', '#form-authenticate', (e) -> returned = app._checkFormSubmission $(e.target).closest 'form' if returned is false e.preventDefault() else false # Clear the authentication status when we type. $(document).on 'input', '#form-authenticate input', -> $('#form-authenticate').removeClass 'success fail' # Helper function for updating dirty flags on edit forms. Both # arguments should be jQuery objects. setDirty = (field, label) -> field.addClass 'dirty' label.addClass 'dirty' # Here we aggregate the names of the dirty form fields into the field # '#dirty'. Unfortunately I couldn't manage to do this in the form # submit handler because it would always be called after the Sammy # route was called. So we do this aggregation on every field change # (this includes pressing a key in a text field). form = field.closest 'form' #$('#dirty', form).val ($(x).attr 'name' for x in $(':input.dirty', form)) $('#dirty', form).val (for x in $(':input.dirty, .form-picker.dirty', form) ($(x).attr 'name') or ($(x).data 'name')) # Keep track of dirty fields in edit forms. $(document).on 'input', '.form-edit :input', -> setDirty $(@), $("label[for='#{ @id }']") $(document).on 'change','.form-edit input:checkbox, .form-edit input:radio', -> setDirty $(@), $(@).parent('label') $(document).on 'reset', '.form-edit', -> $(':input, .form-picker, label', @).removeClass 'dirty' $('#dirty', @).val [] # Facilitate clicking anywhere in a table row. $(document).on 'click', 'tbody tr[data-href]', (e) -> e.preventDefault() app.setLocation $(this).data('href') # Open the picker modal. $(document).on 'click', 'a.picker-open', (e) -> e.preventDefault() $('#picker').data('source', $(this).closest('.form-picker')) app.runRoute 'get', $(this).attr('href') # Clicking a row in the picker. $(document).on 'click', '#picker tbody tr[data-value]', (e) -> e.preventDefault() source = $('#picker').data('source') add = $('div', source).last() element = $("<div> <input name=\"#{ source.data 'name' }\" type=\"hidden\" value=\"#{ $(this).data 'value' }\"> <i class=\"fa fa-remove\"></i> #{ $(this).data 'name' } </div>") add.before(element) add.hide() unless source.data 'multi' setDirty source, $("label[for='#{ source.data 'name' }']") $('#picker').modal('hide') # Removing an element from a picker field. $(document).on 'click', '.form-picker div i', (e) -> element = $(this).closest('div') source = element.parent() add = $('div', source).last() element.remove() add.show() setDirty source, $("label[for='#{ source.data 'name' }']") # Navigation in the picker modal. $(document).on 'click', '#picker a', (e) -> e.preventDefault() app.runRoute 'get', $(this).attr('href') # Reset all pickers. $(document).on 'reset', 'form', -> $('.form-picker', @).each -> add = $('div', this).last().detach() $('div', this).remove() add.appendTo this add.show() # Transcript query input element. $(document).on 'input', '.transcript-querier', td.debounce 250, -> route = "#{ config.RESOURCES_PREFIX }/transcript_query" app.runRoute 'get', route, query: $(@).val().trim() # Show the user that we are waiting for the server. $(document) .bind('ajaxStart', -> $('#waiting').fadeIn duration: 'slow', queue: false $('button').prop 'disabled', true) .bind('ajaxStop', -> $('#waiting').fadeOut duration: 'fast', queue: false $('button').prop 'disabled', false) # Instantiate API client and run app. $('body').html require('../templates/loading.hb')() api = new Api config.API_ROOT api.init error: (code, message) -> $('body').html require('../templates/loading_error.hb') error: code: code message: message success: -> $('body').html require('../templates/application.hb') base: config.BASE app.init api app.run() module.exports = {}
[ { "context": "utton\")\n lead_button.data\n first_name: @first_name\n last_name: @last_name\n e", "end": 4062, "score": 0.9969323873519897, "start": 4062, "tag": "NAME", "value": "" }, { "context": "ton\")\n lead_button.data\n first_name: @first_...
src/browser_action/js/author_finder.coffee
hunter-io/browser-extension
10
AuthorFinder = -> { launch: -> @url = window.url @trial = (typeof window.api_key == "undefined" || window.api_key == "") @fetch() fetch: -> # @cleanFinderResults() _this = @ $.ajax url: Api.authorFinder(_this.url, window.api_key) headers: "Email-Hunter-Origin": "chrome_extension" type: "GET" data: format: "json" dataType: "json" jsonp: false error: (xhr, statusText, err) -> # If any error occurs, we move to the Domain Search logic. If there # are issues with the account, it will be managed from there. _this.switchToDomainSearch() success: (result) -> if result.data.email == null # If we coulnd't find the author's email address, we display # the Domain Search instead _this.switchToDomainSearch() else _this.domain = result.data.domain _this.email = result.data.email _this.score = result.data.score _this.accept_all = result.data.accept_all _this.verification = result.data.verification _this.position = result.data.position _this.company = result.data.company _this.twitter = result.data.twitter _this.linkedin = result.data.linkedin _this.sources = result.data.sources _this.first_name = Utilities.toTitleCase(result.data.first_name) _this.last_name = Utilities.toTitleCase(result.data.last_name) _this.render() render: -> $("#loading-placeholder").hide() $("#author-finder").show() # Display: complete search link or Sign up CTA unless @trial $("#author-finder .header-search-link").html("See " + DOMPurify.sanitize(@domain) + " email addresses") _this = this $("#author-finder .header-search-link").unbind("click").click -> _this.switchToDomainSearch() $("#author-finder .header-search-link").show() else $("#author-finder .header-signup-link").show() # Confidence score color if @score < 30 @confidence_score_class = "low-score" else if @score > 70 @confidence_score_class = "high-score" else @confidence_score_class = "average-score" # The title of the profile if @position? && @company? @title = "#{@position} at #{@company}" else if @position? @title = "#{@position} at #{@domain}" else if @company? @title = @company else @title = @domain # Display: the method used if @sources.length > 0 s = if @sources.length == 1 then "" else "s" @method = "We found this email address <strong>" + @sources.length + "</strong> time"+s+" on the web." else @method = "This email address is our best guess for this person. We haven't found it on the web." # Prepare the template Handlebars.registerHelper "ifIsVerified", (verification_status, options) -> if verification_status == "valid" return options.fn(this) options.inverse this Handlebars.registerHelper "md5", (options) -> new Handlebars.SafeString(Utilities.MD5(options.fn(this))) template = JST["src/browser_action/templates/finder.hbs"] finder_html = $(template(@)) # Generate the DOM with the template and display it $("#author-finder .finder-result").html finder_html $("#author-finder").show() # Display: the sources if any if @sources.length > 0 $("#author-finder .finder-result-sources").show() # Display: the tooltips $("[data-toggle='tooltip']").tooltip() # Event: the copy action Utilities.copyEmailListener() $("#author-finder .finder-result-pic img").on "load", -> $(this).css "opacity", "1" # Display: the button to save the lead lead_button = $(".finder-result-email .save-lead-button") lead_button.data first_name: @first_name last_name: @last_name email: @email confidence_score: @score lead = new LeadButton lead.saveButtonListener(lead_button) lead.disableSaveLeadButtonIfLeadExists(lead_button) switchToDomainSearch: -> $("#author-finder").hide() $("#author-finder .finder-result").html "" domainSearch = new DomainSearch domainSearch.launch() }
115459
AuthorFinder = -> { launch: -> @url = window.url @trial = (typeof window.api_key == "undefined" || window.api_key == "") @fetch() fetch: -> # @cleanFinderResults() _this = @ $.ajax url: Api.authorFinder(_this.url, window.api_key) headers: "Email-Hunter-Origin": "chrome_extension" type: "GET" data: format: "json" dataType: "json" jsonp: false error: (xhr, statusText, err) -> # If any error occurs, we move to the Domain Search logic. If there # are issues with the account, it will be managed from there. _this.switchToDomainSearch() success: (result) -> if result.data.email == null # If we coulnd't find the author's email address, we display # the Domain Search instead _this.switchToDomainSearch() else _this.domain = result.data.domain _this.email = result.data.email _this.score = result.data.score _this.accept_all = result.data.accept_all _this.verification = result.data.verification _this.position = result.data.position _this.company = result.data.company _this.twitter = result.data.twitter _this.linkedin = result.data.linkedin _this.sources = result.data.sources _this.first_name = Utilities.toTitleCase(result.data.first_name) _this.last_name = Utilities.toTitleCase(result.data.last_name) _this.render() render: -> $("#loading-placeholder").hide() $("#author-finder").show() # Display: complete search link or Sign up CTA unless @trial $("#author-finder .header-search-link").html("See " + DOMPurify.sanitize(@domain) + " email addresses") _this = this $("#author-finder .header-search-link").unbind("click").click -> _this.switchToDomainSearch() $("#author-finder .header-search-link").show() else $("#author-finder .header-signup-link").show() # Confidence score color if @score < 30 @confidence_score_class = "low-score" else if @score > 70 @confidence_score_class = "high-score" else @confidence_score_class = "average-score" # The title of the profile if @position? && @company? @title = "#{@position} at #{@company}" else if @position? @title = "#{@position} at #{@domain}" else if @company? @title = @company else @title = @domain # Display: the method used if @sources.length > 0 s = if @sources.length == 1 then "" else "s" @method = "We found this email address <strong>" + @sources.length + "</strong> time"+s+" on the web." else @method = "This email address is our best guess for this person. We haven't found it on the web." # Prepare the template Handlebars.registerHelper "ifIsVerified", (verification_status, options) -> if verification_status == "valid" return options.fn(this) options.inverse this Handlebars.registerHelper "md5", (options) -> new Handlebars.SafeString(Utilities.MD5(options.fn(this))) template = JST["src/browser_action/templates/finder.hbs"] finder_html = $(template(@)) # Generate the DOM with the template and display it $("#author-finder .finder-result").html finder_html $("#author-finder").show() # Display: the sources if any if @sources.length > 0 $("#author-finder .finder-result-sources").show() # Display: the tooltips $("[data-toggle='tooltip']").tooltip() # Event: the copy action Utilities.copyEmailListener() $("#author-finder .finder-result-pic img").on "load", -> $(this).css "opacity", "1" # Display: the button to save the lead lead_button = $(".finder-result-email .save-lead-button") lead_button.data first_name:<NAME> @first_<NAME> last_name:<NAME> @last_<NAME> email: @email confidence_score: @score lead = new LeadButton lead.saveButtonListener(lead_button) lead.disableSaveLeadButtonIfLeadExists(lead_button) switchToDomainSearch: -> $("#author-finder").hide() $("#author-finder .finder-result").html "" domainSearch = new DomainSearch domainSearch.launch() }
true
AuthorFinder = -> { launch: -> @url = window.url @trial = (typeof window.api_key == "undefined" || window.api_key == "") @fetch() fetch: -> # @cleanFinderResults() _this = @ $.ajax url: Api.authorFinder(_this.url, window.api_key) headers: "Email-Hunter-Origin": "chrome_extension" type: "GET" data: format: "json" dataType: "json" jsonp: false error: (xhr, statusText, err) -> # If any error occurs, we move to the Domain Search logic. If there # are issues with the account, it will be managed from there. _this.switchToDomainSearch() success: (result) -> if result.data.email == null # If we coulnd't find the author's email address, we display # the Domain Search instead _this.switchToDomainSearch() else _this.domain = result.data.domain _this.email = result.data.email _this.score = result.data.score _this.accept_all = result.data.accept_all _this.verification = result.data.verification _this.position = result.data.position _this.company = result.data.company _this.twitter = result.data.twitter _this.linkedin = result.data.linkedin _this.sources = result.data.sources _this.first_name = Utilities.toTitleCase(result.data.first_name) _this.last_name = Utilities.toTitleCase(result.data.last_name) _this.render() render: -> $("#loading-placeholder").hide() $("#author-finder").show() # Display: complete search link or Sign up CTA unless @trial $("#author-finder .header-search-link").html("See " + DOMPurify.sanitize(@domain) + " email addresses") _this = this $("#author-finder .header-search-link").unbind("click").click -> _this.switchToDomainSearch() $("#author-finder .header-search-link").show() else $("#author-finder .header-signup-link").show() # Confidence score color if @score < 30 @confidence_score_class = "low-score" else if @score > 70 @confidence_score_class = "high-score" else @confidence_score_class = "average-score" # The title of the profile if @position? && @company? @title = "#{@position} at #{@company}" else if @position? @title = "#{@position} at #{@domain}" else if @company? @title = @company else @title = @domain # Display: the method used if @sources.length > 0 s = if @sources.length == 1 then "" else "s" @method = "We found this email address <strong>" + @sources.length + "</strong> time"+s+" on the web." else @method = "This email address is our best guess for this person. We haven't found it on the web." # Prepare the template Handlebars.registerHelper "ifIsVerified", (verification_status, options) -> if verification_status == "valid" return options.fn(this) options.inverse this Handlebars.registerHelper "md5", (options) -> new Handlebars.SafeString(Utilities.MD5(options.fn(this))) template = JST["src/browser_action/templates/finder.hbs"] finder_html = $(template(@)) # Generate the DOM with the template and display it $("#author-finder .finder-result").html finder_html $("#author-finder").show() # Display: the sources if any if @sources.length > 0 $("#author-finder .finder-result-sources").show() # Display: the tooltips $("[data-toggle='tooltip']").tooltip() # Event: the copy action Utilities.copyEmailListener() $("#author-finder .finder-result-pic img").on "load", -> $(this).css "opacity", "1" # Display: the button to save the lead lead_button = $(".finder-result-email .save-lead-button") lead_button.data first_name:PI:NAME:<NAME>END_PI @first_PI:NAME:<NAME>END_PI last_name:PI:NAME:<NAME>END_PI @last_PI:NAME:<NAME>END_PI email: @email confidence_score: @score lead = new LeadButton lead.saveButtonListener(lead_button) lead.disableSaveLeadButtonIfLeadExists(lead_button) switchToDomainSearch: -> $("#author-finder").hide() $("#author-finder .finder-result").html "" domainSearch = new DomainSearch domainSearch.launch() }
[ { "context": " init: (el) ->\n el = $ el\n dataKey = \"catbug-#{@name}\"\n unless el.data dataKey\n context = to", "end": 373, "score": 0.946101725101471, "start": 357, "tag": "KEY", "value": "catbug-#{@name}\"" } ]
src/core.coffee
pozadi/catbug
1
catbug.ns 'core', (ns, top) -> ns.instances = {} class ns.Module constructor: (@name, @rootSelector, @elements, @builder) -> _buildElements: (defaultContext) -> result = {} for info in @elements result[info.name] = top.element.create(info, defaultContext) result init: (el) -> el = $ el dataKey = "catbug-#{@name}" unless el.data dataKey context = top.builderContext.create(el, @_buildElements el) el.data dataKey, @builder.call(context, context) el.data dataKey initAll: => for el in $ @rootSelector @init el ns.module = (tree, name, builder) -> unless builder? builder = name name = _.uniqueId 'lambda-' elementInfos = top.elementMeta.getInfos tree ns.instances[name] = module = new ns.Module( name, elementInfos.root.selector, elementInfos.elements, builder ) $ module.initAll module top.init = (names) -> if _.isString names names = names.split ' ' result = {} for name in names result[name] = ns.instances[name].initAll() result top.initAll = -> result = {} for name, module of ns.instances result[name] = module.initAll() result
191564
catbug.ns 'core', (ns, top) -> ns.instances = {} class ns.Module constructor: (@name, @rootSelector, @elements, @builder) -> _buildElements: (defaultContext) -> result = {} for info in @elements result[info.name] = top.element.create(info, defaultContext) result init: (el) -> el = $ el dataKey = "<KEY> unless el.data dataKey context = top.builderContext.create(el, @_buildElements el) el.data dataKey, @builder.call(context, context) el.data dataKey initAll: => for el in $ @rootSelector @init el ns.module = (tree, name, builder) -> unless builder? builder = name name = _.uniqueId 'lambda-' elementInfos = top.elementMeta.getInfos tree ns.instances[name] = module = new ns.Module( name, elementInfos.root.selector, elementInfos.elements, builder ) $ module.initAll module top.init = (names) -> if _.isString names names = names.split ' ' result = {} for name in names result[name] = ns.instances[name].initAll() result top.initAll = -> result = {} for name, module of ns.instances result[name] = module.initAll() result
true
catbug.ns 'core', (ns, top) -> ns.instances = {} class ns.Module constructor: (@name, @rootSelector, @elements, @builder) -> _buildElements: (defaultContext) -> result = {} for info in @elements result[info.name] = top.element.create(info, defaultContext) result init: (el) -> el = $ el dataKey = "PI:KEY:<KEY>END_PI unless el.data dataKey context = top.builderContext.create(el, @_buildElements el) el.data dataKey, @builder.call(context, context) el.data dataKey initAll: => for el in $ @rootSelector @init el ns.module = (tree, name, builder) -> unless builder? builder = name name = _.uniqueId 'lambda-' elementInfos = top.elementMeta.getInfos tree ns.instances[name] = module = new ns.Module( name, elementInfos.root.selector, elementInfos.elements, builder ) $ module.initAll module top.init = (names) -> if _.isString names names = names.split ' ' result = {} for name in names result[name] = ns.instances[name].initAll() result top.initAll = -> result = {} for name, module of ns.instances result[name] = module.initAll() result
[ { "context": "updateName: ->\n\n model = Puppy.create(name: 'gus') \n\n view = new BindedView()\n spy =", "end": 11916, "score": 0.4251340925693512, "start": 11913, "tag": "USERNAME", "value": "gus" }, { "context": "Model(model)\n model.updateAttribute('name',...
spec/view_spec.coffee
ryggrad/Ryggrad
0
describe "Ryggrad.View", -> view = null view3 = null view4 = null view2 = null TestRyggradView = null BadRyggradView = null content = null viewafterAttachStub = null viewSubviewafterAttachStub = null view2afterAttachStub = null viewa3fterAttachStub = null describe "Ryggrad.View objects", -> beforeEach -> class Subview extends Ryggrad.View @content: (params={}, otherArg) -> @div => @h2 { outlet: "header" }, params.title + " " + otherArg @div "I am a subview" @tag 'mytag', id: 'thetag', 'Non standard tag' initialize: (args...) -> @initializeCalledWith = args afterAttach: -> class TestRyggradView extends Ryggrad.View @content: (params={}, otherArg) -> @div keydown: 'viewClicked', class: 'rootDiv', => @h1 { outlet: 'header' }, params.title + " " + otherArg @list() @subview 'subview', new Subview(title: "Subview", 43) @list: -> @ol => @li outlet: 'li1', click: 'li1Clicked', class: 'foo', "one" @li outlet: 'li2', keypress:'li2Keypressed', class: 'bar', "two" initialize: (args...) -> @initializeCalledWith = args foo: "bar", li1Clicked: ->, li2Keypressed: -> viewClicked: -> afterAttach: -> beforeRemove: -> view = new TestRyggradView({title: "Zebra"}, 42) describe "constructor", -> it "calls the content class method with the given params to produce the view's html", -> view.should.match "div" view.find("h1:contains(Zebra 42)").should.exist view.find("mytag#thetag:contains(Non standard tag)").should.exist view.find("ol > li.foo:contains(one)").should.exist view.find("ol > li.bar:contains(two)").should.exist it "calls initialize on the view with the given params", -> _.isEqual(view.initializeCalledWith, [{title: "Zebra"}, 42]).should.be.true it "wires outlet referenecs to elements with 'outlet' attributes", -> view.li1.should.match "li.foo:contains(one)" view.li2.should.match "li.bar:contains(two)" it "removes the outlet attribute from markup", -> expect(view.li1.attr('outlet')).to.be.falsey expect(view.li2.attr('outlet')).to.be.falsey it "constructs and wires outlets for subviews", -> view.subview.should.exist view.subview.find('h2:contains(Subview 43)').should.exist view.subview.parentView.should.be view view.subview.constructor.currentBuilder.should.be.falsey _.isEqual(view.subview.initializeCalledWith, [{title: "Subview"}, 43]).should.be.true it "does not overwrite outlets on the superview with outlets from the subviews", -> view.header.should.match "h1" view.subview.header.should.match "h2" it "binds events for elements with event name attributes", -> viewClickedStub = sinon.stub view, "viewClicked", (event, elt) -> event.type.should.be 'keydown' elt.should.match "div.rootDiv" li1ClickedStub = sinon.stub view, 'li1Clicked', (event, elt) -> event.type.should.be 'click' elt.should.match 'li.foo:contains(one)' li2KeypressedStub = sinon.stub view, 'li2Keypressed', (event, elt) -> event.type.should.be 'keypress' elt.should.match "li.bar:contains(two)" view.keydown() viewClickedStub.should.have.been.called viewClickedStub.restore() view.li1.click() li1ClickedStub.should.have.been.called li2KeypressedStub.should.not.have.been.called view.li1Clicked.reset() view.li2.keypress() li2KeypressedStub.should.have.been.called li1ClickedStub.should.not.have.been.called li2KeypressedStub.restore() li1ClickedStub.restore() it "makes the view object accessible via the calling 'view' method on any child element", -> view.view().should.be view view.header.view().should.be view view.subview.view().should.be view.subview view.subview.header.view().should.be view.subview it "throws an exception if the view has more than one root element", -> class BadRyggradView extends Ryggrad.View @content: -> @div id: 'one' @div id: 'two' expect( -> new BadRyggradView ).to.throw(Error) it "throws an exception if the view has no content", -> class BadRyggradView extends Ryggrad.View @content: -> left blank intentionally expect(-> new BadRyggradView ).to.throw(Error) describe "when a view is attached to another element via jQuery", -> beforeEach -> view4 = new TestRyggradView() view3 = new TestRyggradView() view2 = new TestRyggradView() describe "when attached to an element that is on the DOM", -> beforeEach -> content = $('#mocha') afterEach -> content.empty() describe "when $.fn.append is called with a single argument", -> it "calls afterAttach (if it is present) on the appended view and its subviews, passing true to indicate they are on the DOM", -> viewafterAttachStub = sinon.stub(view, 'afterAttach') viewSubviewafterAttachStub = sinon.stub(view.subview, 'afterAttach') view2afterAttachStub = sinon.stub(view2, 'afterAttach') viewa3fterAttachStub = sinon.stub(view3, 'afterAttach') content.append view view.afterAttach.should.have.been.calledWith(true) view.subview.afterAttach.should.have.been.calledWith(true) viewafterAttachStub.restore() viewSubviewafterAttachStub.restore() view2afterAttachStub.restore() viewa3fterAttachStub.restore() describe "when $.fn.append is called with multiple arguments", -> it "calls afterAttach (if it is present) on all appended views and their subviews, passing true to indicate they are on the DOM", -> viewafterAttachStub = sinon.stub(view, 'afterAttach') viewSubviewafterAttachStub = sinon.stub(view.subview, 'afterAttach') view2afterAttachStub = sinon.stub(view2, 'afterAttach') viewa3fterAttachStub = sinon.stub(view3, 'afterAttach') content.append view, view2, [view3, view4] view.afterAttach.should.have.been.calledWith(true) view.subview.afterAttach.should.have.been.calledWith(true) view2.afterAttach.should.have.been.calledWith(true) view3.afterAttach.should.have.been.calledWith(true) viewafterAttachStub.restore() viewSubviewafterAttachStub.restore() view2afterAttachStub.restore() viewa3fterAttachStub.restore() describe "when $.fn.insertBefore is called on the view", -> it "calls afterAttach on the view and its subviews", -> viewafterAttachStub = sinon.stub(view, 'afterAttach') viewSubviewafterAttachStub = sinon.stub(view.subview, 'afterAttach') otherElt = $('<div>') content.append(otherElt) view.insertBefore(otherElt) view.afterAttach.should.have.been.calledWith(true) view.subview.afterAttach.should.have.been.calledWith(true) viewafterAttachStub.restore() viewSubviewafterAttachStub.restore() describe "when a view is attached as part of a larger dom fragment", -> it "calls afterAttach on the view and its subviews", -> viewafterAttachStub = sinon.stub(view, 'afterAttach') viewSubviewafterAttachStub = sinon.stub(view.subview, 'afterAttach') otherElt = $('<div>') otherElt.append(view) content.append(otherElt) view.afterAttach.should.have.been.calledWith(true) view.subview.afterAttach.should.have.been.calledWith(true) viewafterAttachStub.restore() viewSubviewafterAttachStub.restore() describe "when attached to an element that is not on the DOM", -> it "calls afterAttach (if it is present) on the appended view, passing false to indicate it isn't on the DOM", -> viewafterAttachStub = sinon.stub(view, 'afterAttach') fragment = $('<div>') fragment.append view view.afterAttach.should.have.been.calledWith(false) viewafterAttachStub.restore() it "doesn't call afterAttach a second time until the view is attached to the DOM", -> viewafterAttachStub = sinon.stub(view, 'afterAttach') fragment = $('<div>') fragment.append view view.afterAttach.reset() otherFragment = $('<div>') otherFragment.append(fragment) view.afterAttach.should.not.have.been.called view.afterAttach.restore() it "allows $.fn.append to be called with undefined without raising an exception", -> expect(-> view.append undefined ).to.not.throw(Error) describe "when a view is removed from the DOM", -> it "calls the `beforeRemove` hook once for each view", -> view = new TestRyggradView() content = $('#mocha') parent = $$ -> @div() parent.append(view) content.append(parent) subviewParentViewDuringRemove = null spy = sinon.stub view, 'beforeRemove', -> subviewParentViewDuringRemove = view.subview.parent().view() subviewParentViewDuringRemove = null parent.remove() expect(spy).to.have.been.called expect(spy.callCount).to.be 1 expect(subviewParentViewDuringRemove).to.be view it "the view instance is no longer accessible by calling view()", -> content = $('#mocha') parent = $$ -> @div() parent.append(view) content.append(parent) expect($(view[0]).view()).to.be view parent.remove() expect($(view[0]).view()).to.be.falsy describe "when the view constructs a new jQuery wrapper", -> it "constructs instances of jQuery rather than the view class", -> expect(view.eq(0) instanceof jQuery).to.be.truthy expect(view.eq(0) instanceof TestRyggradView).to.be.falsy expect(view.end() instanceof jQuery).to.be.truthy expect(view.end() instanceof TestRyggradView).to.be.falsy describe "Ryggrad.View.render (bound to $$)", -> it "renders a document fragment based on tag methods called by the given function", -> fragment = $$ -> @div class: "foo", => @ol => @li id: 'one' @li id: 'two' fragment.should.match('div.foo') fragment.find('ol').should.exist fragment.find('ol li#one').should.exist fragment.find('ol li#two').should.exist it "renders subviews", -> fragment = $$ -> @div => @subview 'foo', $$ -> @div id: "subview" fragment.find('div#subview').should.exist fragment.foo.should.match('#subview') describe "View bindings", -> it "should bind model events to view methods", -> class Puppy extends Ryggrad.Model @configure("Puppy", "name") @extend Ryggrad.AttributeTracking class BindedView extends Ryggrad.View @content: (params={}, otherArg) -> @div => @h2 { outlet: "header" }, params.title + " " + otherArg @div "I am a subview" @tag 'mytag', id: 'thetag', 'Non standard tag' @model_events: "update:name": "updateName" updateName: -> model = Puppy.create(name: 'gus') view = new BindedView() spy = sinon.spy(view, "updateName") view.setModel(model) model.updateAttribute('name', 'jake') spy.should.have.been.called describe "$$$", -> it "returns the raw HTML constructed by tag methods called by the given function (not a jQuery wrapper)", -> html = $$$ -> @div class: "foo", => @ol => @li id: 'one' @li id: 'two' typeof html.should.be 'string' fragment = $(html) fragment.should.match('div.foo') fragment.find('ol').should.exist fragment.find('ol li#one').should.exist fragment.find('ol li#two').should.exist
25513
describe "Ryggrad.View", -> view = null view3 = null view4 = null view2 = null TestRyggradView = null BadRyggradView = null content = null viewafterAttachStub = null viewSubviewafterAttachStub = null view2afterAttachStub = null viewa3fterAttachStub = null describe "Ryggrad.View objects", -> beforeEach -> class Subview extends Ryggrad.View @content: (params={}, otherArg) -> @div => @h2 { outlet: "header" }, params.title + " " + otherArg @div "I am a subview" @tag 'mytag', id: 'thetag', 'Non standard tag' initialize: (args...) -> @initializeCalledWith = args afterAttach: -> class TestRyggradView extends Ryggrad.View @content: (params={}, otherArg) -> @div keydown: 'viewClicked', class: 'rootDiv', => @h1 { outlet: 'header' }, params.title + " " + otherArg @list() @subview 'subview', new Subview(title: "Subview", 43) @list: -> @ol => @li outlet: 'li1', click: 'li1Clicked', class: 'foo', "one" @li outlet: 'li2', keypress:'li2Keypressed', class: 'bar', "two" initialize: (args...) -> @initializeCalledWith = args foo: "bar", li1Clicked: ->, li2Keypressed: -> viewClicked: -> afterAttach: -> beforeRemove: -> view = new TestRyggradView({title: "Zebra"}, 42) describe "constructor", -> it "calls the content class method with the given params to produce the view's html", -> view.should.match "div" view.find("h1:contains(Zebra 42)").should.exist view.find("mytag#thetag:contains(Non standard tag)").should.exist view.find("ol > li.foo:contains(one)").should.exist view.find("ol > li.bar:contains(two)").should.exist it "calls initialize on the view with the given params", -> _.isEqual(view.initializeCalledWith, [{title: "Zebra"}, 42]).should.be.true it "wires outlet referenecs to elements with 'outlet' attributes", -> view.li1.should.match "li.foo:contains(one)" view.li2.should.match "li.bar:contains(two)" it "removes the outlet attribute from markup", -> expect(view.li1.attr('outlet')).to.be.falsey expect(view.li2.attr('outlet')).to.be.falsey it "constructs and wires outlets for subviews", -> view.subview.should.exist view.subview.find('h2:contains(Subview 43)').should.exist view.subview.parentView.should.be view view.subview.constructor.currentBuilder.should.be.falsey _.isEqual(view.subview.initializeCalledWith, [{title: "Subview"}, 43]).should.be.true it "does not overwrite outlets on the superview with outlets from the subviews", -> view.header.should.match "h1" view.subview.header.should.match "h2" it "binds events for elements with event name attributes", -> viewClickedStub = sinon.stub view, "viewClicked", (event, elt) -> event.type.should.be 'keydown' elt.should.match "div.rootDiv" li1ClickedStub = sinon.stub view, 'li1Clicked', (event, elt) -> event.type.should.be 'click' elt.should.match 'li.foo:contains(one)' li2KeypressedStub = sinon.stub view, 'li2Keypressed', (event, elt) -> event.type.should.be 'keypress' elt.should.match "li.bar:contains(two)" view.keydown() viewClickedStub.should.have.been.called viewClickedStub.restore() view.li1.click() li1ClickedStub.should.have.been.called li2KeypressedStub.should.not.have.been.called view.li1Clicked.reset() view.li2.keypress() li2KeypressedStub.should.have.been.called li1ClickedStub.should.not.have.been.called li2KeypressedStub.restore() li1ClickedStub.restore() it "makes the view object accessible via the calling 'view' method on any child element", -> view.view().should.be view view.header.view().should.be view view.subview.view().should.be view.subview view.subview.header.view().should.be view.subview it "throws an exception if the view has more than one root element", -> class BadRyggradView extends Ryggrad.View @content: -> @div id: 'one' @div id: 'two' expect( -> new BadRyggradView ).to.throw(Error) it "throws an exception if the view has no content", -> class BadRyggradView extends Ryggrad.View @content: -> left blank intentionally expect(-> new BadRyggradView ).to.throw(Error) describe "when a view is attached to another element via jQuery", -> beforeEach -> view4 = new TestRyggradView() view3 = new TestRyggradView() view2 = new TestRyggradView() describe "when attached to an element that is on the DOM", -> beforeEach -> content = $('#mocha') afterEach -> content.empty() describe "when $.fn.append is called with a single argument", -> it "calls afterAttach (if it is present) on the appended view and its subviews, passing true to indicate they are on the DOM", -> viewafterAttachStub = sinon.stub(view, 'afterAttach') viewSubviewafterAttachStub = sinon.stub(view.subview, 'afterAttach') view2afterAttachStub = sinon.stub(view2, 'afterAttach') viewa3fterAttachStub = sinon.stub(view3, 'afterAttach') content.append view view.afterAttach.should.have.been.calledWith(true) view.subview.afterAttach.should.have.been.calledWith(true) viewafterAttachStub.restore() viewSubviewafterAttachStub.restore() view2afterAttachStub.restore() viewa3fterAttachStub.restore() describe "when $.fn.append is called with multiple arguments", -> it "calls afterAttach (if it is present) on all appended views and their subviews, passing true to indicate they are on the DOM", -> viewafterAttachStub = sinon.stub(view, 'afterAttach') viewSubviewafterAttachStub = sinon.stub(view.subview, 'afterAttach') view2afterAttachStub = sinon.stub(view2, 'afterAttach') viewa3fterAttachStub = sinon.stub(view3, 'afterAttach') content.append view, view2, [view3, view4] view.afterAttach.should.have.been.calledWith(true) view.subview.afterAttach.should.have.been.calledWith(true) view2.afterAttach.should.have.been.calledWith(true) view3.afterAttach.should.have.been.calledWith(true) viewafterAttachStub.restore() viewSubviewafterAttachStub.restore() view2afterAttachStub.restore() viewa3fterAttachStub.restore() describe "when $.fn.insertBefore is called on the view", -> it "calls afterAttach on the view and its subviews", -> viewafterAttachStub = sinon.stub(view, 'afterAttach') viewSubviewafterAttachStub = sinon.stub(view.subview, 'afterAttach') otherElt = $('<div>') content.append(otherElt) view.insertBefore(otherElt) view.afterAttach.should.have.been.calledWith(true) view.subview.afterAttach.should.have.been.calledWith(true) viewafterAttachStub.restore() viewSubviewafterAttachStub.restore() describe "when a view is attached as part of a larger dom fragment", -> it "calls afterAttach on the view and its subviews", -> viewafterAttachStub = sinon.stub(view, 'afterAttach') viewSubviewafterAttachStub = sinon.stub(view.subview, 'afterAttach') otherElt = $('<div>') otherElt.append(view) content.append(otherElt) view.afterAttach.should.have.been.calledWith(true) view.subview.afterAttach.should.have.been.calledWith(true) viewafterAttachStub.restore() viewSubviewafterAttachStub.restore() describe "when attached to an element that is not on the DOM", -> it "calls afterAttach (if it is present) on the appended view, passing false to indicate it isn't on the DOM", -> viewafterAttachStub = sinon.stub(view, 'afterAttach') fragment = $('<div>') fragment.append view view.afterAttach.should.have.been.calledWith(false) viewafterAttachStub.restore() it "doesn't call afterAttach a second time until the view is attached to the DOM", -> viewafterAttachStub = sinon.stub(view, 'afterAttach') fragment = $('<div>') fragment.append view view.afterAttach.reset() otherFragment = $('<div>') otherFragment.append(fragment) view.afterAttach.should.not.have.been.called view.afterAttach.restore() it "allows $.fn.append to be called with undefined without raising an exception", -> expect(-> view.append undefined ).to.not.throw(Error) describe "when a view is removed from the DOM", -> it "calls the `beforeRemove` hook once for each view", -> view = new TestRyggradView() content = $('#mocha') parent = $$ -> @div() parent.append(view) content.append(parent) subviewParentViewDuringRemove = null spy = sinon.stub view, 'beforeRemove', -> subviewParentViewDuringRemove = view.subview.parent().view() subviewParentViewDuringRemove = null parent.remove() expect(spy).to.have.been.called expect(spy.callCount).to.be 1 expect(subviewParentViewDuringRemove).to.be view it "the view instance is no longer accessible by calling view()", -> content = $('#mocha') parent = $$ -> @div() parent.append(view) content.append(parent) expect($(view[0]).view()).to.be view parent.remove() expect($(view[0]).view()).to.be.falsy describe "when the view constructs a new jQuery wrapper", -> it "constructs instances of jQuery rather than the view class", -> expect(view.eq(0) instanceof jQuery).to.be.truthy expect(view.eq(0) instanceof TestRyggradView).to.be.falsy expect(view.end() instanceof jQuery).to.be.truthy expect(view.end() instanceof TestRyggradView).to.be.falsy describe "Ryggrad.View.render (bound to $$)", -> it "renders a document fragment based on tag methods called by the given function", -> fragment = $$ -> @div class: "foo", => @ol => @li id: 'one' @li id: 'two' fragment.should.match('div.foo') fragment.find('ol').should.exist fragment.find('ol li#one').should.exist fragment.find('ol li#two').should.exist it "renders subviews", -> fragment = $$ -> @div => @subview 'foo', $$ -> @div id: "subview" fragment.find('div#subview').should.exist fragment.foo.should.match('#subview') describe "View bindings", -> it "should bind model events to view methods", -> class Puppy extends Ryggrad.Model @configure("Puppy", "name") @extend Ryggrad.AttributeTracking class BindedView extends Ryggrad.View @content: (params={}, otherArg) -> @div => @h2 { outlet: "header" }, params.title + " " + otherArg @div "I am a subview" @tag 'mytag', id: 'thetag', 'Non standard tag' @model_events: "update:name": "updateName" updateName: -> model = Puppy.create(name: 'gus') view = new BindedView() spy = sinon.spy(view, "updateName") view.setModel(model) model.updateAttribute('name', '<NAME>') spy.should.have.been.called describe "$$$", -> it "returns the raw HTML constructed by tag methods called by the given function (not a jQuery wrapper)", -> html = $$$ -> @div class: "foo", => @ol => @li id: 'one' @li id: 'two' typeof html.should.be 'string' fragment = $(html) fragment.should.match('div.foo') fragment.find('ol').should.exist fragment.find('ol li#one').should.exist fragment.find('ol li#two').should.exist
true
describe "Ryggrad.View", -> view = null view3 = null view4 = null view2 = null TestRyggradView = null BadRyggradView = null content = null viewafterAttachStub = null viewSubviewafterAttachStub = null view2afterAttachStub = null viewa3fterAttachStub = null describe "Ryggrad.View objects", -> beforeEach -> class Subview extends Ryggrad.View @content: (params={}, otherArg) -> @div => @h2 { outlet: "header" }, params.title + " " + otherArg @div "I am a subview" @tag 'mytag', id: 'thetag', 'Non standard tag' initialize: (args...) -> @initializeCalledWith = args afterAttach: -> class TestRyggradView extends Ryggrad.View @content: (params={}, otherArg) -> @div keydown: 'viewClicked', class: 'rootDiv', => @h1 { outlet: 'header' }, params.title + " " + otherArg @list() @subview 'subview', new Subview(title: "Subview", 43) @list: -> @ol => @li outlet: 'li1', click: 'li1Clicked', class: 'foo', "one" @li outlet: 'li2', keypress:'li2Keypressed', class: 'bar', "two" initialize: (args...) -> @initializeCalledWith = args foo: "bar", li1Clicked: ->, li2Keypressed: -> viewClicked: -> afterAttach: -> beforeRemove: -> view = new TestRyggradView({title: "Zebra"}, 42) describe "constructor", -> it "calls the content class method with the given params to produce the view's html", -> view.should.match "div" view.find("h1:contains(Zebra 42)").should.exist view.find("mytag#thetag:contains(Non standard tag)").should.exist view.find("ol > li.foo:contains(one)").should.exist view.find("ol > li.bar:contains(two)").should.exist it "calls initialize on the view with the given params", -> _.isEqual(view.initializeCalledWith, [{title: "Zebra"}, 42]).should.be.true it "wires outlet referenecs to elements with 'outlet' attributes", -> view.li1.should.match "li.foo:contains(one)" view.li2.should.match "li.bar:contains(two)" it "removes the outlet attribute from markup", -> expect(view.li1.attr('outlet')).to.be.falsey expect(view.li2.attr('outlet')).to.be.falsey it "constructs and wires outlets for subviews", -> view.subview.should.exist view.subview.find('h2:contains(Subview 43)').should.exist view.subview.parentView.should.be view view.subview.constructor.currentBuilder.should.be.falsey _.isEqual(view.subview.initializeCalledWith, [{title: "Subview"}, 43]).should.be.true it "does not overwrite outlets on the superview with outlets from the subviews", -> view.header.should.match "h1" view.subview.header.should.match "h2" it "binds events for elements with event name attributes", -> viewClickedStub = sinon.stub view, "viewClicked", (event, elt) -> event.type.should.be 'keydown' elt.should.match "div.rootDiv" li1ClickedStub = sinon.stub view, 'li1Clicked', (event, elt) -> event.type.should.be 'click' elt.should.match 'li.foo:contains(one)' li2KeypressedStub = sinon.stub view, 'li2Keypressed', (event, elt) -> event.type.should.be 'keypress' elt.should.match "li.bar:contains(two)" view.keydown() viewClickedStub.should.have.been.called viewClickedStub.restore() view.li1.click() li1ClickedStub.should.have.been.called li2KeypressedStub.should.not.have.been.called view.li1Clicked.reset() view.li2.keypress() li2KeypressedStub.should.have.been.called li1ClickedStub.should.not.have.been.called li2KeypressedStub.restore() li1ClickedStub.restore() it "makes the view object accessible via the calling 'view' method on any child element", -> view.view().should.be view view.header.view().should.be view view.subview.view().should.be view.subview view.subview.header.view().should.be view.subview it "throws an exception if the view has more than one root element", -> class BadRyggradView extends Ryggrad.View @content: -> @div id: 'one' @div id: 'two' expect( -> new BadRyggradView ).to.throw(Error) it "throws an exception if the view has no content", -> class BadRyggradView extends Ryggrad.View @content: -> left blank intentionally expect(-> new BadRyggradView ).to.throw(Error) describe "when a view is attached to another element via jQuery", -> beforeEach -> view4 = new TestRyggradView() view3 = new TestRyggradView() view2 = new TestRyggradView() describe "when attached to an element that is on the DOM", -> beforeEach -> content = $('#mocha') afterEach -> content.empty() describe "when $.fn.append is called with a single argument", -> it "calls afterAttach (if it is present) on the appended view and its subviews, passing true to indicate they are on the DOM", -> viewafterAttachStub = sinon.stub(view, 'afterAttach') viewSubviewafterAttachStub = sinon.stub(view.subview, 'afterAttach') view2afterAttachStub = sinon.stub(view2, 'afterAttach') viewa3fterAttachStub = sinon.stub(view3, 'afterAttach') content.append view view.afterAttach.should.have.been.calledWith(true) view.subview.afterAttach.should.have.been.calledWith(true) viewafterAttachStub.restore() viewSubviewafterAttachStub.restore() view2afterAttachStub.restore() viewa3fterAttachStub.restore() describe "when $.fn.append is called with multiple arguments", -> it "calls afterAttach (if it is present) on all appended views and their subviews, passing true to indicate they are on the DOM", -> viewafterAttachStub = sinon.stub(view, 'afterAttach') viewSubviewafterAttachStub = sinon.stub(view.subview, 'afterAttach') view2afterAttachStub = sinon.stub(view2, 'afterAttach') viewa3fterAttachStub = sinon.stub(view3, 'afterAttach') content.append view, view2, [view3, view4] view.afterAttach.should.have.been.calledWith(true) view.subview.afterAttach.should.have.been.calledWith(true) view2.afterAttach.should.have.been.calledWith(true) view3.afterAttach.should.have.been.calledWith(true) viewafterAttachStub.restore() viewSubviewafterAttachStub.restore() view2afterAttachStub.restore() viewa3fterAttachStub.restore() describe "when $.fn.insertBefore is called on the view", -> it "calls afterAttach on the view and its subviews", -> viewafterAttachStub = sinon.stub(view, 'afterAttach') viewSubviewafterAttachStub = sinon.stub(view.subview, 'afterAttach') otherElt = $('<div>') content.append(otherElt) view.insertBefore(otherElt) view.afterAttach.should.have.been.calledWith(true) view.subview.afterAttach.should.have.been.calledWith(true) viewafterAttachStub.restore() viewSubviewafterAttachStub.restore() describe "when a view is attached as part of a larger dom fragment", -> it "calls afterAttach on the view and its subviews", -> viewafterAttachStub = sinon.stub(view, 'afterAttach') viewSubviewafterAttachStub = sinon.stub(view.subview, 'afterAttach') otherElt = $('<div>') otherElt.append(view) content.append(otherElt) view.afterAttach.should.have.been.calledWith(true) view.subview.afterAttach.should.have.been.calledWith(true) viewafterAttachStub.restore() viewSubviewafterAttachStub.restore() describe "when attached to an element that is not on the DOM", -> it "calls afterAttach (if it is present) on the appended view, passing false to indicate it isn't on the DOM", -> viewafterAttachStub = sinon.stub(view, 'afterAttach') fragment = $('<div>') fragment.append view view.afterAttach.should.have.been.calledWith(false) viewafterAttachStub.restore() it "doesn't call afterAttach a second time until the view is attached to the DOM", -> viewafterAttachStub = sinon.stub(view, 'afterAttach') fragment = $('<div>') fragment.append view view.afterAttach.reset() otherFragment = $('<div>') otherFragment.append(fragment) view.afterAttach.should.not.have.been.called view.afterAttach.restore() it "allows $.fn.append to be called with undefined without raising an exception", -> expect(-> view.append undefined ).to.not.throw(Error) describe "when a view is removed from the DOM", -> it "calls the `beforeRemove` hook once for each view", -> view = new TestRyggradView() content = $('#mocha') parent = $$ -> @div() parent.append(view) content.append(parent) subviewParentViewDuringRemove = null spy = sinon.stub view, 'beforeRemove', -> subviewParentViewDuringRemove = view.subview.parent().view() subviewParentViewDuringRemove = null parent.remove() expect(spy).to.have.been.called expect(spy.callCount).to.be 1 expect(subviewParentViewDuringRemove).to.be view it "the view instance is no longer accessible by calling view()", -> content = $('#mocha') parent = $$ -> @div() parent.append(view) content.append(parent) expect($(view[0]).view()).to.be view parent.remove() expect($(view[0]).view()).to.be.falsy describe "when the view constructs a new jQuery wrapper", -> it "constructs instances of jQuery rather than the view class", -> expect(view.eq(0) instanceof jQuery).to.be.truthy expect(view.eq(0) instanceof TestRyggradView).to.be.falsy expect(view.end() instanceof jQuery).to.be.truthy expect(view.end() instanceof TestRyggradView).to.be.falsy describe "Ryggrad.View.render (bound to $$)", -> it "renders a document fragment based on tag methods called by the given function", -> fragment = $$ -> @div class: "foo", => @ol => @li id: 'one' @li id: 'two' fragment.should.match('div.foo') fragment.find('ol').should.exist fragment.find('ol li#one').should.exist fragment.find('ol li#two').should.exist it "renders subviews", -> fragment = $$ -> @div => @subview 'foo', $$ -> @div id: "subview" fragment.find('div#subview').should.exist fragment.foo.should.match('#subview') describe "View bindings", -> it "should bind model events to view methods", -> class Puppy extends Ryggrad.Model @configure("Puppy", "name") @extend Ryggrad.AttributeTracking class BindedView extends Ryggrad.View @content: (params={}, otherArg) -> @div => @h2 { outlet: "header" }, params.title + " " + otherArg @div "I am a subview" @tag 'mytag', id: 'thetag', 'Non standard tag' @model_events: "update:name": "updateName" updateName: -> model = Puppy.create(name: 'gus') view = new BindedView() spy = sinon.spy(view, "updateName") view.setModel(model) model.updateAttribute('name', 'PI:NAME:<NAME>END_PI') spy.should.have.been.called describe "$$$", -> it "returns the raw HTML constructed by tag methods called by the given function (not a jQuery wrapper)", -> html = $$$ -> @div class: "foo", => @ol => @li id: 'one' @li id: 'two' typeof html.should.be 'string' fragment = $(html) fragment.should.match('div.foo') fragment.find('ol').should.exist fragment.find('ol li#one').should.exist fragment.find('ol li#two').should.exist
[ { "context": " .get('/api/3.0/search/artists.json?query=carvil&apikey=myapikey&per_page=50&page=1')\n .r", "end": 2234, "score": 0.9707664251327515, "start": 2228, "tag": "NAME", "value": "carvil" }, { "context": "pty results\", (done) ->\n sk.artist.search(\"...
spec/artist_spec.coffee
carvil/node-songkick
1
nock = require 'nock' fs = require 'fs' Songkick = require "../lib/node-songkick" sk = new Songkick("myapikey") describe "Songkick", -> describe "All artists", -> describe "given a valid search for the first page of all artists", -> beforeEach -> placebo = nock('http://api.songkick.com/') .get('/api/3.0/artists.json?apikey=myapikey&page=1') .replyWithFile(200, __dirname + '/fixtures/search_all_artists.json') it "should return the first 30 artists", (done) -> sk.artist.all({page: 1}, (result) -> expect(result.resultsPage.totalEntries).toEqual(266226) expect(result.resultsPage.perPage).toEqual(30) expect(result.resultsPage.page).toEqual(1) expect(result.resultsPage.results.artist.length).toEqual(30) expect(result.resultsPage.results.artist[0].displayName).toEqual("TH26") done() ) describe "Artist search", -> describe "given a valid search for an artist is returned", -> beforeEach -> placebo = nock('http://api.songkick.com/') .get('/api/3.0/search/artists.json?query=placebo&apikey=myapikey&per_page=50&page=1') .replyWithFile(200, __dirname + '/fixtures/search_success.json') it "should return the total number of entries", (done) -> sk.artist.search("placebo", {}, (result) -> expect(result.resultsPage.status).toEqual('ok') expect(result.resultsPage.totalEntries).toEqual(15) expect(result.resultsPage.perPage).toEqual(50) expect(result.resultsPage.page).toEqual(1) expect(result.resultsPage.results.artist[0].displayName).toEqual("Placebo") expect(result.resultsPage.results.artist[0].id).toEqual(324967) expect(result.resultsPage.results.artist[0].onTourUntil).toEqual("2012-09-22") expect(result.resultsPage.results.artist[0].uri).toEqual("http://www.songkick.com/artists/324967-placebo?utm_source=14303&utm_medium=partner") done() ) describe "when searching for a non-existing artist", -> beforeEach -> carvil = nock('http://api.songkick.com/') .get('/api/3.0/search/artists.json?query=carvil&apikey=myapikey&per_page=50&page=1') .replyWithFile(200, __dirname + '/fixtures/search_not_found.json') it "should return the empty results", (done) -> sk.artist.search("carvil", {}, (result) -> expect(result.resultsPage.results).toEqual({}) expect(result.resultsPage.status).toEqual('ok') expect(result.resultsPage.totalEntries).toEqual(0) expect(result.resultsPage.perPage).toEqual(50) expect(result.resultsPage.page).toEqual(1) done() ) describe "Calendar search", -> describe "given a valid search for an artist's calendar", -> beforeEach -> calendar = nock('http://api.songkick.com/') .get('/api/3.0/artists/324967/calendar.json?apikey=myapikey&per_page=50&page=1') .replyWithFile(200, __dirname + '/fixtures/calendar_success.json') it "should return the calendar data", (done) -> sk.artist.calendar("artist_id", 324967, {}, (result) -> expect(result.resultsPage.status).toEqual('ok') expect(result.resultsPage.totalEntries).toEqual(7) expect(result.resultsPage.perPage).toEqual(50) expect(result.resultsPage.page).toEqual(1) expect(result.resultsPage.results.event[0].displayName).toEqual("Rock en Seine 2012") expect(result.resultsPage.results.event[0].id).toEqual(12166218) done() ) describe "given an invalid type", -> it "should return an error message", (done) -> sk.artist.calendar("invalid", 0, {}, (result) -> expect(result).toEqual({ error: 'Unknown type: must be artist_id or music_brainz_id' }) done() ) describe "given a search by a valid music_brainz_id", -> beforeEach -> calendar = nock('http://api.songkick.com/') .get('/api/3.0/artists/mbid:cc197bad-dc9c-440d-a5b5-d52ba2e14234/calendar.json?apikey=myapikey&per_page=50&page=1') .replyWithFile(200, __dirname + '/fixtures/calendar_by_musicbrainz.json') it "should return events' data", (done) -> sk.artist.calendar("music_brainz_id", "cc197bad-dc9c-440d-a5b5-d52ba2e14234", {}, (result) -> expect(result.resultsPage.status).toEqual('ok') expect(result.resultsPage.totalEntries).toEqual(22) expect(result.resultsPage.perPage).toEqual(50) expect(result.resultsPage.page).toEqual(1) expect(result.resultsPage.results.event[0].popularity).toEqual(1) expect(result.resultsPage.results.event[0].displayName).toEqual('Coldplay with Marina and the Diamonds and Punky the Singer at Parken (August 28, 2012)') expect(result.resultsPage.results.event[0].type).toEqual('Concert') done() ) describe "given a search by an invalid id", -> beforeEach -> calendar = nock('http://api.songkick.com/') .get('/api/3.0/artists/mbid:invalid/calendar.json?apikey=myapikey&per_page=50&page=1') .replyWithFile(200, __dirname + '/fixtures/calendar_invalid_musicbrainz.json') it "should return an empty object", (done) -> sk.artist.calendar("music_brainz_id", "invalid", {}, (result) -> expect(result.resultsPage.results).toEqual({}) expect(result.resultsPage.status).toEqual('ok') expect(result.resultsPage.totalEntries).toEqual(0) expect(result.resultsPage.perPage).toEqual(50) expect(result.resultsPage.page).toEqual(1) done() ) describe "Gigography search", -> describe "given an invalid type", -> it "should return an error message", (done) -> sk.artist.gigography("invalid", 0, {}, (result) -> expect(result).toEqual({ error: 'Unknown type: must be either artist_id or music_brainz_id' }) done() ) describe "given a valid search for an artist's gigography by artist_id", -> beforeEach -> calendar = nock('http://api.songkick.com/') .get('/api/3.0/artists/324967/gigography.json?apikey=myapikey&per_page=50&page=1') .replyWithFile(200, __dirname + '/fixtures/gigography_success.json') it "should return the gigography_success data", (done) -> sk.artist.gigography("artist_id", 324967, {}, (result) -> expect(result.resultsPage.status).toEqual('ok') expect(result.resultsPage.totalEntries).toEqual(958) expect(result.resultsPage.perPage).toEqual(50) expect(result.resultsPage.page).toEqual(1) expect(result.resultsPage.results.event[0].displayName).toEqual("Placebo with Nameshaker at The Rock Garden (January 23, 1995)") expect(result.resultsPage.results.event[0].id).toEqual(937131) done() ) describe "given a search by an invalid id", -> beforeEach -> calendar = nock('http://api.songkick.com/') .get('/api/3.0/artists/invalid/gigography.json?apikey=myapikey&per_page=50&page=1') .replyWithFile(200, __dirname + '/fixtures/gigography_invalid_musicbrainz.json') it "should return an empty object", (done) -> sk.artist.gigography("artist_id", "invalid", {}, (result) -> expect(result.resultsPage.results).toEqual({}) expect(result.resultsPage.status).toEqual('ok') expect(result.resultsPage.totalEntries).toEqual(0) expect(result.resultsPage.perPage).toEqual(50) expect(result.resultsPage.page).toEqual(1) done() )
138655
nock = require 'nock' fs = require 'fs' Songkick = require "../lib/node-songkick" sk = new Songkick("myapikey") describe "Songkick", -> describe "All artists", -> describe "given a valid search for the first page of all artists", -> beforeEach -> placebo = nock('http://api.songkick.com/') .get('/api/3.0/artists.json?apikey=myapikey&page=1') .replyWithFile(200, __dirname + '/fixtures/search_all_artists.json') it "should return the first 30 artists", (done) -> sk.artist.all({page: 1}, (result) -> expect(result.resultsPage.totalEntries).toEqual(266226) expect(result.resultsPage.perPage).toEqual(30) expect(result.resultsPage.page).toEqual(1) expect(result.resultsPage.results.artist.length).toEqual(30) expect(result.resultsPage.results.artist[0].displayName).toEqual("TH26") done() ) describe "Artist search", -> describe "given a valid search for an artist is returned", -> beforeEach -> placebo = nock('http://api.songkick.com/') .get('/api/3.0/search/artists.json?query=placebo&apikey=myapikey&per_page=50&page=1') .replyWithFile(200, __dirname + '/fixtures/search_success.json') it "should return the total number of entries", (done) -> sk.artist.search("placebo", {}, (result) -> expect(result.resultsPage.status).toEqual('ok') expect(result.resultsPage.totalEntries).toEqual(15) expect(result.resultsPage.perPage).toEqual(50) expect(result.resultsPage.page).toEqual(1) expect(result.resultsPage.results.artist[0].displayName).toEqual("Placebo") expect(result.resultsPage.results.artist[0].id).toEqual(324967) expect(result.resultsPage.results.artist[0].onTourUntil).toEqual("2012-09-22") expect(result.resultsPage.results.artist[0].uri).toEqual("http://www.songkick.com/artists/324967-placebo?utm_source=14303&utm_medium=partner") done() ) describe "when searching for a non-existing artist", -> beforeEach -> carvil = nock('http://api.songkick.com/') .get('/api/3.0/search/artists.json?query=<NAME>&apikey=myapikey&per_page=50&page=1') .replyWithFile(200, __dirname + '/fixtures/search_not_found.json') it "should return the empty results", (done) -> sk.artist.search("<NAME>", {}, (result) -> expect(result.resultsPage.results).toEqual({}) expect(result.resultsPage.status).toEqual('ok') expect(result.resultsPage.totalEntries).toEqual(0) expect(result.resultsPage.perPage).toEqual(50) expect(result.resultsPage.page).toEqual(1) done() ) describe "Calendar search", -> describe "given a valid search for an artist's calendar", -> beforeEach -> calendar = nock('http://api.songkick.com/') .get('/api/3.0/artists/324967/calendar.json?apikey=myapikey&per_page=50&page=1') .replyWithFile(200, __dirname + '/fixtures/calendar_success.json') it "should return the calendar data", (done) -> sk.artist.calendar("artist_id", 324967, {}, (result) -> expect(result.resultsPage.status).toEqual('ok') expect(result.resultsPage.totalEntries).toEqual(7) expect(result.resultsPage.perPage).toEqual(50) expect(result.resultsPage.page).toEqual(1) expect(result.resultsPage.results.event[0].displayName).toEqual("Rock en Seine 2012") expect(result.resultsPage.results.event[0].id).toEqual(12166218) done() ) describe "given an invalid type", -> it "should return an error message", (done) -> sk.artist.calendar("invalid", 0, {}, (result) -> expect(result).toEqual({ error: 'Unknown type: must be artist_id or music_brainz_id' }) done() ) describe "given a search by a valid music_brainz_id", -> beforeEach -> calendar = nock('http://api.songkick.com/') .get('/api/3.0/artists/mbid:cc197bad-dc9c-440d-a5b5-d52ba2e14234/calendar.json?apikey=myapikey&per_page=50&page=1') .replyWithFile(200, __dirname + '/fixtures/calendar_by_musicbrainz.json') it "should return events' data", (done) -> sk.artist.calendar("music_brainz_id", "cc197bad-dc9c-440d-a5b5-d52ba2e14234", {}, (result) -> expect(result.resultsPage.status).toEqual('ok') expect(result.resultsPage.totalEntries).toEqual(22) expect(result.resultsPage.perPage).toEqual(50) expect(result.resultsPage.page).toEqual(1) expect(result.resultsPage.results.event[0].popularity).toEqual(1) expect(result.resultsPage.results.event[0].displayName).toEqual('Coldplay with <NAME> and the Diamonds and Punky the Singer at Parken (August 28, 2012)') expect(result.resultsPage.results.event[0].type).toEqual('Concert') done() ) describe "given a search by an invalid id", -> beforeEach -> calendar = nock('http://api.songkick.com/') .get('/api/3.0/artists/mbid:invalid/calendar.json?apikey=myapikey&per_page=50&page=1') .replyWithFile(200, __dirname + '/fixtures/calendar_invalid_musicbrainz.json') it "should return an empty object", (done) -> sk.artist.calendar("music_brainz_id", "invalid", {}, (result) -> expect(result.resultsPage.results).toEqual({}) expect(result.resultsPage.status).toEqual('ok') expect(result.resultsPage.totalEntries).toEqual(0) expect(result.resultsPage.perPage).toEqual(50) expect(result.resultsPage.page).toEqual(1) done() ) describe "Gigography search", -> describe "given an invalid type", -> it "should return an error message", (done) -> sk.artist.gigography("invalid", 0, {}, (result) -> expect(result).toEqual({ error: 'Unknown type: must be either artist_id or music_brainz_id' }) done() ) describe "given a valid search for an artist's gigography by artist_id", -> beforeEach -> calendar = nock('http://api.songkick.com/') .get('/api/3.0/artists/324967/gigography.json?apikey=myapikey&per_page=50&page=1') .replyWithFile(200, __dirname + '/fixtures/gigography_success.json') it "should return the gigography_success data", (done) -> sk.artist.gigography("artist_id", 324967, {}, (result) -> expect(result.resultsPage.status).toEqual('ok') expect(result.resultsPage.totalEntries).toEqual(958) expect(result.resultsPage.perPage).toEqual(50) expect(result.resultsPage.page).toEqual(1) expect(result.resultsPage.results.event[0].displayName).toEqual("Placebo with Nameshaker at The Rock Garden (January 23, 1995)") expect(result.resultsPage.results.event[0].id).toEqual(937131) done() ) describe "given a search by an invalid id", -> beforeEach -> calendar = nock('http://api.songkick.com/') .get('/api/3.0/artists/invalid/gigography.json?apikey=myapikey&per_page=50&page=1') .replyWithFile(200, __dirname + '/fixtures/gigography_invalid_musicbrainz.json') it "should return an empty object", (done) -> sk.artist.gigography("artist_id", "invalid", {}, (result) -> expect(result.resultsPage.results).toEqual({}) expect(result.resultsPage.status).toEqual('ok') expect(result.resultsPage.totalEntries).toEqual(0) expect(result.resultsPage.perPage).toEqual(50) expect(result.resultsPage.page).toEqual(1) done() )
true
nock = require 'nock' fs = require 'fs' Songkick = require "../lib/node-songkick" sk = new Songkick("myapikey") describe "Songkick", -> describe "All artists", -> describe "given a valid search for the first page of all artists", -> beforeEach -> placebo = nock('http://api.songkick.com/') .get('/api/3.0/artists.json?apikey=myapikey&page=1') .replyWithFile(200, __dirname + '/fixtures/search_all_artists.json') it "should return the first 30 artists", (done) -> sk.artist.all({page: 1}, (result) -> expect(result.resultsPage.totalEntries).toEqual(266226) expect(result.resultsPage.perPage).toEqual(30) expect(result.resultsPage.page).toEqual(1) expect(result.resultsPage.results.artist.length).toEqual(30) expect(result.resultsPage.results.artist[0].displayName).toEqual("TH26") done() ) describe "Artist search", -> describe "given a valid search for an artist is returned", -> beforeEach -> placebo = nock('http://api.songkick.com/') .get('/api/3.0/search/artists.json?query=placebo&apikey=myapikey&per_page=50&page=1') .replyWithFile(200, __dirname + '/fixtures/search_success.json') it "should return the total number of entries", (done) -> sk.artist.search("placebo", {}, (result) -> expect(result.resultsPage.status).toEqual('ok') expect(result.resultsPage.totalEntries).toEqual(15) expect(result.resultsPage.perPage).toEqual(50) expect(result.resultsPage.page).toEqual(1) expect(result.resultsPage.results.artist[0].displayName).toEqual("Placebo") expect(result.resultsPage.results.artist[0].id).toEqual(324967) expect(result.resultsPage.results.artist[0].onTourUntil).toEqual("2012-09-22") expect(result.resultsPage.results.artist[0].uri).toEqual("http://www.songkick.com/artists/324967-placebo?utm_source=14303&utm_medium=partner") done() ) describe "when searching for a non-existing artist", -> beforeEach -> carvil = nock('http://api.songkick.com/') .get('/api/3.0/search/artists.json?query=PI:NAME:<NAME>END_PI&apikey=myapikey&per_page=50&page=1') .replyWithFile(200, __dirname + '/fixtures/search_not_found.json') it "should return the empty results", (done) -> sk.artist.search("PI:NAME:<NAME>END_PI", {}, (result) -> expect(result.resultsPage.results).toEqual({}) expect(result.resultsPage.status).toEqual('ok') expect(result.resultsPage.totalEntries).toEqual(0) expect(result.resultsPage.perPage).toEqual(50) expect(result.resultsPage.page).toEqual(1) done() ) describe "Calendar search", -> describe "given a valid search for an artist's calendar", -> beforeEach -> calendar = nock('http://api.songkick.com/') .get('/api/3.0/artists/324967/calendar.json?apikey=myapikey&per_page=50&page=1') .replyWithFile(200, __dirname + '/fixtures/calendar_success.json') it "should return the calendar data", (done) -> sk.artist.calendar("artist_id", 324967, {}, (result) -> expect(result.resultsPage.status).toEqual('ok') expect(result.resultsPage.totalEntries).toEqual(7) expect(result.resultsPage.perPage).toEqual(50) expect(result.resultsPage.page).toEqual(1) expect(result.resultsPage.results.event[0].displayName).toEqual("Rock en Seine 2012") expect(result.resultsPage.results.event[0].id).toEqual(12166218) done() ) describe "given an invalid type", -> it "should return an error message", (done) -> sk.artist.calendar("invalid", 0, {}, (result) -> expect(result).toEqual({ error: 'Unknown type: must be artist_id or music_brainz_id' }) done() ) describe "given a search by a valid music_brainz_id", -> beforeEach -> calendar = nock('http://api.songkick.com/') .get('/api/3.0/artists/mbid:cc197bad-dc9c-440d-a5b5-d52ba2e14234/calendar.json?apikey=myapikey&per_page=50&page=1') .replyWithFile(200, __dirname + '/fixtures/calendar_by_musicbrainz.json') it "should return events' data", (done) -> sk.artist.calendar("music_brainz_id", "cc197bad-dc9c-440d-a5b5-d52ba2e14234", {}, (result) -> expect(result.resultsPage.status).toEqual('ok') expect(result.resultsPage.totalEntries).toEqual(22) expect(result.resultsPage.perPage).toEqual(50) expect(result.resultsPage.page).toEqual(1) expect(result.resultsPage.results.event[0].popularity).toEqual(1) expect(result.resultsPage.results.event[0].displayName).toEqual('Coldplay with PI:NAME:<NAME>END_PI and the Diamonds and Punky the Singer at Parken (August 28, 2012)') expect(result.resultsPage.results.event[0].type).toEqual('Concert') done() ) describe "given a search by an invalid id", -> beforeEach -> calendar = nock('http://api.songkick.com/') .get('/api/3.0/artists/mbid:invalid/calendar.json?apikey=myapikey&per_page=50&page=1') .replyWithFile(200, __dirname + '/fixtures/calendar_invalid_musicbrainz.json') it "should return an empty object", (done) -> sk.artist.calendar("music_brainz_id", "invalid", {}, (result) -> expect(result.resultsPage.results).toEqual({}) expect(result.resultsPage.status).toEqual('ok') expect(result.resultsPage.totalEntries).toEqual(0) expect(result.resultsPage.perPage).toEqual(50) expect(result.resultsPage.page).toEqual(1) done() ) describe "Gigography search", -> describe "given an invalid type", -> it "should return an error message", (done) -> sk.artist.gigography("invalid", 0, {}, (result) -> expect(result).toEqual({ error: 'Unknown type: must be either artist_id or music_brainz_id' }) done() ) describe "given a valid search for an artist's gigography by artist_id", -> beforeEach -> calendar = nock('http://api.songkick.com/') .get('/api/3.0/artists/324967/gigography.json?apikey=myapikey&per_page=50&page=1') .replyWithFile(200, __dirname + '/fixtures/gigography_success.json') it "should return the gigography_success data", (done) -> sk.artist.gigography("artist_id", 324967, {}, (result) -> expect(result.resultsPage.status).toEqual('ok') expect(result.resultsPage.totalEntries).toEqual(958) expect(result.resultsPage.perPage).toEqual(50) expect(result.resultsPage.page).toEqual(1) expect(result.resultsPage.results.event[0].displayName).toEqual("Placebo with Nameshaker at The Rock Garden (January 23, 1995)") expect(result.resultsPage.results.event[0].id).toEqual(937131) done() ) describe "given a search by an invalid id", -> beforeEach -> calendar = nock('http://api.songkick.com/') .get('/api/3.0/artists/invalid/gigography.json?apikey=myapikey&per_page=50&page=1') .replyWithFile(200, __dirname + '/fixtures/gigography_invalid_musicbrainz.json') it "should return an empty object", (done) -> sk.artist.gigography("artist_id", "invalid", {}, (result) -> expect(result.resultsPage.results).toEqual({}) expect(result.resultsPage.status).toEqual('ok') expect(result.resultsPage.totalEntries).toEqual(0) expect(result.resultsPage.perPage).toEqual(50) expect(result.resultsPage.page).toEqual(1) done() )
[ { "context": "name: \"Leeds ONE\"\naddress: \"Leeds One, City Office Park, LS11 5BD\"", "end": 16, "score": 0.9996724128723145, "start": 7, "tag": "NAME", "value": "Leeds ONE" }, { "context": "\"Leeds One, City Office Park, LS11 5BD\"\ncontact: \"Ben Holliday\"\nmap:\n lon: 53.79016...
app/data/locations/leedsone.cson
dwpdigitaltech/DWPwelcome
0
name: "Leeds ONE" address: "Leeds One, City Office Park, LS11 5BD" contact: "Ben Holliday" map: lon: 53.790166 lat: -1.543319 desc: "Leeds One is located on the corner of the A61 and Meadow Lane." directions: train: [ "The office is a 10 minute walk from Leeds mainline station." "Exit the station by the main entrance by M&S." "Go straight across the road to the bike shop." "Take the stairs down, immediately to the right of the shop." "Turn right and walk under the rail bridge." "Cross the road at the crossing after the Marriott hotel." "Turn right after crossing and carry on walking along the main road on the other side, it crosses the River Aire and bends to the left, then passes Asda HQ on the left." "Leeds ONE is the building diagonally across the main junction - use the pedestrian crossings to cross to it." ] car: [ "There's no parking for visitors to Leeds ONE. The nearest car park is at the Tetley building (£7 a day). Staff parking is limited and there may be a waiting list to get a parking spot if you need one." ] gettinginandout: [ "You must sign in as a visitor each morning until you have a buildings pass." "Visitor passes will only work in the gate to the far left of reception as you come in. Once inside your visitor pass will open the security doors on each floor of the building." "If you're going for lunch and intending to come back to the office don't put your pass in the slot on the gate. Ask the concierge to let you through instead and give them your pass - remembering your pass number beforehand. You then won't have to sign in again when you return." "At the end of the day, put your visitor pass in the slot on the visitor's gate. The gate will open but will keep your pass. You don't need to sign out." ] toilets: [ "Female and male toilets are located on each landing of the main stairs (behind reception and through two sets of double doors)." ] eatinganddrinking: [ "There's a Costa coffee stand immediately behind reception." "Kitchen areas are located on each floor, and have fridges, kettles and microwaves." "Turn left out of the main entrance for the Crown Point shopping centre. There's a Boot's store, a small cafe upstairs in the Asda homeware store and a Subway fast food restaurant." "Turn right out of the building and head towards the large silver sky high rise building (Bridgewater Place) to find a Tesco metro, Philpotts sandwich delicatessen and a lunch time takeaway 'Juici Sushi'." ]
10968
name: "<NAME>" address: "Leeds One, City Office Park, LS11 5BD" contact: "<NAME>" map: lon: 53.790166 lat: -1.543319 desc: "Leeds One is located on the corner of the A61 and Meadow Lane." directions: train: [ "The office is a 10 minute walk from Leeds mainline station." "Exit the station by the main entrance by M&S." "Go straight across the road to the bike shop." "Take the stairs down, immediately to the right of the shop." "Turn right and walk under the rail bridge." "Cross the road at the crossing after the Marriott hotel." "Turn right after crossing and carry on walking along the main road on the other side, it crosses the River Aire and bends to the left, then passes Asda HQ on the left." "Leeds ONE is the building diagonally across the main junction - use the pedestrian crossings to cross to it." ] car: [ "There's no parking for visitors to Leeds ONE. The nearest car park is at the Tetley building (£7 a day). Staff parking is limited and there may be a waiting list to get a parking spot if you need one." ] gettinginandout: [ "You must sign in as a visitor each morning until you have a buildings pass." "Visitor passes will only work in the gate to the far left of reception as you come in. Once inside your visitor pass will open the security doors on each floor of the building." "If you're going for lunch and intending to come back to the office don't put your pass in the slot on the gate. Ask the concierge to let you through instead and give them your pass - remembering your pass number beforehand. You then won't have to sign in again when you return." "At the end of the day, put your visitor pass in the slot on the visitor's gate. The gate will open but will keep your pass. You don't need to sign out." ] toilets: [ "Female and male toilets are located on each landing of the main stairs (behind reception and through two sets of double doors)." ] eatinganddrinking: [ "There's a Costa coffee stand immediately behind reception." "Kitchen areas are located on each floor, and have fridges, kettles and microwaves." "Turn left out of the main entrance for the Crown Point shopping centre. There's a Boot's store, a small cafe upstairs in the Asda homeware store and a Subway fast food restaurant." "Turn right out of the building and head towards the large silver sky high rise building (Bridgewater Place) to find a Tesco metro, Philpotts sandwich delicatessen and a lunch time takeaway '<NAME> S<NAME>i'." ]
true
name: "PI:NAME:<NAME>END_PI" address: "Leeds One, City Office Park, LS11 5BD" contact: "PI:NAME:<NAME>END_PI" map: lon: 53.790166 lat: -1.543319 desc: "Leeds One is located on the corner of the A61 and Meadow Lane." directions: train: [ "The office is a 10 minute walk from Leeds mainline station." "Exit the station by the main entrance by M&S." "Go straight across the road to the bike shop." "Take the stairs down, immediately to the right of the shop." "Turn right and walk under the rail bridge." "Cross the road at the crossing after the Marriott hotel." "Turn right after crossing and carry on walking along the main road on the other side, it crosses the River Aire and bends to the left, then passes Asda HQ on the left." "Leeds ONE is the building diagonally across the main junction - use the pedestrian crossings to cross to it." ] car: [ "There's no parking for visitors to Leeds ONE. The nearest car park is at the Tetley building (£7 a day). Staff parking is limited and there may be a waiting list to get a parking spot if you need one." ] gettinginandout: [ "You must sign in as a visitor each morning until you have a buildings pass." "Visitor passes will only work in the gate to the far left of reception as you come in. Once inside your visitor pass will open the security doors on each floor of the building." "If you're going for lunch and intending to come back to the office don't put your pass in the slot on the gate. Ask the concierge to let you through instead and give them your pass - remembering your pass number beforehand. You then won't have to sign in again when you return." "At the end of the day, put your visitor pass in the slot on the visitor's gate. The gate will open but will keep your pass. You don't need to sign out." ] toilets: [ "Female and male toilets are located on each landing of the main stairs (behind reception and through two sets of double doors)." ] eatinganddrinking: [ "There's a Costa coffee stand immediately behind reception." "Kitchen areas are located on each floor, and have fridges, kettles and microwaves." "Turn left out of the main entrance for the Crown Point shopping centre. There's a Boot's store, a small cafe upstairs in the Asda homeware store and a Subway fast food restaurant." "Turn right out of the building and head towards the large silver sky high rise building (Bridgewater Place) to find a Tesco metro, Philpotts sandwich delicatessen and a lunch time takeaway 'PI:NAME:<NAME>END_PI SPI:NAME:<NAME>END_PIi'." ]
[ { "context": "y,value_key) =>\n add_key = dkey + ':addv:' + value_key + ':' + label_key\n tot_k", "end": 3105, "score": 0.5381251573562622, "start": 3104, "tag": "KEY", "value": "v" }, { "context": "':' + label_key\n tot_key = dkey + ':addv:' + value_...
src/module.iced
tosadvisor/trk
1
# vim: set expandtab tabstop=2 shiftwidth=2 softtabstop=2 log = (x...) -> try console.log x... lp = (x) -> log JSON.stringify(x,null,2) _ = require('wegweg')({ globals: off }) require 'date-utils' async = require 'async' minimatch = require 'minimatch' Members = require 'taky-redis-members' ident = require './lib/redis-ident' module.exports = class Metrics constructor: (opt={}) -> # define storage instances @redis = opt.redis ? opt.client ? _.redis() @memcached = opt.memcached ? opt.memcached ? _.memcached() @key = opt.key ? opt.prefix ? 'tky' @members_keys = new Members { redis: @redis prefix: @key + ':k' } @map = { bmp: [] add: [] addv: [] top: [] } if opt.map @map[k] = v for k,v of opt.map # record an event using the metrics utility, perform redis # operations according to the constructed map configuration record: (event,cb) -> dkey = @key + ':' + (today = _.today()) obj = _.clone event for x of obj for y of obj if x != y and !x.match(/\~/) and !y.match(/\~/) cat = [x,y].sort() key = cat.join('~') if not obj[key] obj[key] = obj[cat[0]] + '~' + obj[cat[1]] # function container arr = [] # key membership queue keys_queue = [] m = @redis.multi() if @map.bmp?.length for x in @map.bmp if x.match(/\~/) x = x.split(/\~/).sort().join('~') if obj[x] do (x) => bmp_id = ident @redis, dkey + ':bmp:i:' + x bmp_key = dkey + ':bmp:' + x keys_queue.push bmp_key = dkey + ':bmp:' + x fns = [ (c) => bmp_id obj[x], (e,id) -> c null, id (i,c) => @redis.setbit bmp_key, i, 1, (e,r) -> c null, r ] arr.push((c) -> async.waterfall fns, c) ### # hyperloglog implementation; no noticable performance benefit arr.push ((c) => @redis.send_command 'pfadd', [bmp_key,obj[x]], c ) ### if @map.add?.length for x in @map.add if x.match(/\~/) x = x.split(/\~/).sort().join('~') if obj[x] do (x) => add_key = dkey + ':add:' + x keys_queue.push add_key m.hincrby add_key, obj[x], 1 if @map.top?.length for x in @map.top if x.match(/\~/) x = x.split(/\~/).sort().join('~') if obj[x] do (x) => set_key = dkey + ':top:' + x keys_queue.push set_key m.zincrby set_key, 1, obj[x] if @map.addv?.length for x in @map.addv if _.type(x) is 'object' label_key = x.key value_key = x.value ? x.val else label_key = x value_key = x if label_key.match(/\~/) label_key = label_key.split(/\~/).sort().join('~') if obj[label_key] and obj[value_key] and !isNaN(obj[value_key]) do (label_key,value_key) => add_key = dkey + ':addv:' + value_key + ':' + label_key tot_key = dkey + ':addv:' + value_key + ':' + 'i' keys_queue.push add_key keys_queue.push tot_key if label_key isnt value_key m.hincrby add_key, obj[label_key], +(obj[value_key]) m.hincrby tot_key, 'sum', +(obj[value_key]) m.hincrby tot_key, 'count', 1 # write key members for the current day arr.push (c) => @members_keys.add today, keys_queue, c # perform redis operations arr.push ((c) -> m.exec c) await _.par arr, defer e,r cb null, r if cb # primary query-style, unix_min, unix_max query: (min,max,opt,cb) -> if !cb and _.type(opt) is 'function' cb = opt opt = {} dkey = @key + ':' + _.today() if !cb cb = max max = min min_date = new Date min * 1000 max_date = new Date max * 1000 min_date.clearTime() max_date.clearTime() num_days = min_date.getDaysBetween max_date prefix = @key ret = {} arr = [] all_days = [] while max_date >= min_date do => day = min_date.clone() day.clearTime() unix = Math.round day.getTime()/1000 # get key memberships for this day arr.push (c) => @members_keys.list unix, c all_days.push unix ret[unix] = date: day.toFormat 'MM/DD/YYYY' result: [] min_date.addDays 1 await _.par arr, defer e,r if !r?.length return cb null, ret jobs = @_jobs r fns = {} job_keys = [] blacklist = [] for k,v of jobs for path,func of v job_keys.push path # ignore/accept glob-style path matching opt.ignore ?= [] opt.accept ?= (opt.allow ? []) if opt.ignore opt.ignore = [opt.ignore] if _.type(opt.ignore) is 'string' opt.ignore = opt.ignore if opt.accept opt.accept = [opt.accept] if _.type(opt.accept) is 'string' opt.accept = opt.accept if opt.ignore.length for x in job_keys raw = x.substr(@key.length + 1) parts = raw.split ':' parts.shift() raw = parts.join ':' for pattern in opt.ignore blacklist.push(x) if minimatch(raw,pattern) if opt.accept.length for x in job_keys continue if x in blacklist raw = x.substr(@key.length + 1) parts = raw.split ':' parts.shift() raw = parts.join ':' valid = no for pattern in opt.accept if minimatch(raw,pattern) valid = yes break blacklist.push x if !valid # return here if we only want the jobs back if opt.return_jobs if blacklist.length return cb null, (_.difference job_keys,blacklist) else return cb null, job_keys for k,v of jobs do (k,v) -> # delete job if the key is in our blacklist if blacklist.length for k2,v2 of v delete v[k2] if k2 in blacklist if opt.ignore_jobs for x in opt.ignore_jobs return if k.includes(x) fns[k] = ((c) -> _.series v, c ) await _.par fns, defer e2,r2 if e2 or !_.size(r2) return cb null, ret for type,results of r2 do (results) -> for location,item of results do (item) -> return if !ret[item.day] item.key = location.split(':').pop().split '~' ret[item.day].result.push item return cb null, (@_format ret,no) # alternative query-style, days relative to today query_days: (num_days,cb) -> max_date = new Date min_date = new Date if num_days > 0 then num_days *= -1 ++ num_days min_date.add days:num_days min = Math.round min_date.getTime()/1000 max = Math.round max_date.getTime()/1000 @query min, max, cb _query_keys: (keys,cb) -> start = new Date min = no max = no for x in keys do (x) -> time = x.split(':')[1] if !min or time < min then min = time if !max or time > max then max = time range = [min..max] days = (x for x in range by (3600 * 24)).reverse() fns = @_jobs keys afns = {} for k,v of fns do (k,v) -> afns[k] = (c) -> _.par fns[k], c _.par afns, (e,r) -> out = { days: {} min: min max: max elapsed: "#{new Date() - start}ms" } if _.keys(r).length for k,v of r do (k,v) => for key,stats of v do (key,stats) => if !out.days[stats.day] out.days[stats.day] = {} if !out.days[stats.day][stats.type] out.days[stats.day][stats.type] = {} map_key = stats.location.split /:/ map_key = map_key.slice -1 out.days[stats.day][stats.type][map_key] = stats for x in days do (x) -> if !out.days[x] then out.days[x] = {} out.days[x].date = new Date(x * 1000).toFormat 'MM/DD/YYYY' cb null, out # creates an object filled with functions for async to execute # based on the type of redis key for each item _jobs: (keys) -> fns = add: {} top: {} bmp: {} addv: {} keys = _.uniq _.flatten keys for y in keys do (y) => # fix for keys with colons if @key.includes(':') y = y.split(@key).join('_tmp_') [key,time,type...,fields] = y.split /:/ # fix for keys with colons if y.includes('_tmp_') y = y.split('_tmp_').join @key if _.first(type) is 'addv' type = ['addv'] return if type.length is 2 job = day: time type: type.shift() location: y cache_key: "_cache:#{y}" do_cache = no do_cache = yes if job.day < _.today() if job.type is 'add' fns.add[job.location] = (c) => if do_cache await @memcached.get job.cache_key, defer e,cache_r if cache_r then return c null, cache_r @redis.hgetall job.location, (e,r) => job.result = r await @memcached.set job.cache_key, job, 0, defer() if do_cache c null, job if job.type is 'addv' fns.add[job.location] = (c) => if do_cache await @memcached.get job.cache_key, defer e,cache_r if cache_r then return c null, cache_r @redis.hgetall job.location, (e,r) => job.result = r await @memcached.set job.cache_key, job, 0, defer() if do_cache c null, job else if job.type is 'bmp' fns.bmp[job.location] = (c) => if do_cache await @memcached.get job.cache_key, defer e,cache_r if cache_r then return c null, cache_r @redis.bitcount job.location, (e,r) => job.result = r await @memcached.set job.cache_key, job, 0, defer() if do_cache c null, job else if job.type is 'top' fns.top[job.location] = (c) => if do_cache await @memcached.get job.cache_key, defer e,cache_r if cache_r then return c null, cache_r args = [ job.location '+inf' '-inf' 'WITHSCORES' 'LIMIT' 0 250 ] @redis.zrevrangebyscore args, (e,r) => ret = {} if r?.length last = null i = 0; for z in r do (z) => ++i; if i % 2 ret[z] = null last = z else ret[last] = parseInt z job.result = ret await @memcached.set job.cache_key, job, 0, defer() if do_cache c null, job return fns # output formatting, creates and attached a filter function to easily # sort the result object data for reporting use _format: (obj,cached) -> merge_numeric = ((uno,dos) -> return dos if !uno and dos return uno if uno and !dos for k,v of dos uno[k] ?= 0 uno[k] += (+v) return uno ) output = days: obj cache: (if cached then 'hit' else 'miss') find: (o) -> opt = { type: null key: null day: no merge: no } if typeof o is 'object' if o.keys and !o.key o.key = o.keys delete o.keys opt = _.merge o else parts = o.split '/' opt.type = parts.shift() opt.key = parts.shift() if parts.length opt.day = parts.shift() opt.key = opt.key.split('~').sort().join '~' if opt.day if !obj[opt.day]?.result? return null for v in obj[opt.day].result if v.type is opt.type if v.location.substr((opt.key.length + 1) * -1) is ":#{opt.key}" return v.result return null else ret = {} for unix,item of obj if opt.type is 'bmp' val = 0 else if opt.type in ['top','add'] val = {} else if opt.type is 'addv' val = {} ret[item.date] = val continue if !item?.result?.length for v in item.result if v.type is opt.type if v.location.substr((opt.key.length + 1) * -1) is ":#{opt.key}" ret[item.date] = v.result if opt.merge tot = {} arr = _.vals ret for x in arr do (x) -> tot = merge_numeric tot, x tot else ret ## if !module.parent log /DEVEL/ process.exit 0
153651
# vim: set expandtab tabstop=2 shiftwidth=2 softtabstop=2 log = (x...) -> try console.log x... lp = (x) -> log JSON.stringify(x,null,2) _ = require('wegweg')({ globals: off }) require 'date-utils' async = require 'async' minimatch = require 'minimatch' Members = require 'taky-redis-members' ident = require './lib/redis-ident' module.exports = class Metrics constructor: (opt={}) -> # define storage instances @redis = opt.redis ? opt.client ? _.redis() @memcached = opt.memcached ? opt.memcached ? _.memcached() @key = opt.key ? opt.prefix ? 'tky' @members_keys = new Members { redis: @redis prefix: @key + ':k' } @map = { bmp: [] add: [] addv: [] top: [] } if opt.map @map[k] = v for k,v of opt.map # record an event using the metrics utility, perform redis # operations according to the constructed map configuration record: (event,cb) -> dkey = @key + ':' + (today = _.today()) obj = _.clone event for x of obj for y of obj if x != y and !x.match(/\~/) and !y.match(/\~/) cat = [x,y].sort() key = cat.join('~') if not obj[key] obj[key] = obj[cat[0]] + '~' + obj[cat[1]] # function container arr = [] # key membership queue keys_queue = [] m = @redis.multi() if @map.bmp?.length for x in @map.bmp if x.match(/\~/) x = x.split(/\~/).sort().join('~') if obj[x] do (x) => bmp_id = ident @redis, dkey + ':bmp:i:' + x bmp_key = dkey + ':bmp:' + x keys_queue.push bmp_key = dkey + ':bmp:' + x fns = [ (c) => bmp_id obj[x], (e,id) -> c null, id (i,c) => @redis.setbit bmp_key, i, 1, (e,r) -> c null, r ] arr.push((c) -> async.waterfall fns, c) ### # hyperloglog implementation; no noticable performance benefit arr.push ((c) => @redis.send_command 'pfadd', [bmp_key,obj[x]], c ) ### if @map.add?.length for x in @map.add if x.match(/\~/) x = x.split(/\~/).sort().join('~') if obj[x] do (x) => add_key = dkey + ':add:' + x keys_queue.push add_key m.hincrby add_key, obj[x], 1 if @map.top?.length for x in @map.top if x.match(/\~/) x = x.split(/\~/).sort().join('~') if obj[x] do (x) => set_key = dkey + ':top:' + x keys_queue.push set_key m.zincrby set_key, 1, obj[x] if @map.addv?.length for x in @map.addv if _.type(x) is 'object' label_key = x.key value_key = x.value ? x.val else label_key = x value_key = x if label_key.match(/\~/) label_key = label_key.split(/\~/).sort().join('~') if obj[label_key] and obj[value_key] and !isNaN(obj[value_key]) do (label_key,value_key) => add_key = dkey + ':add<KEY>:' + value_key + ':' + label_key tot_key = dkey + ':add<KEY>:' + value_key + ':' + 'i' keys_queue.push add_key keys_queue.push tot_key if label_key isnt value_key m.hincrby add_key, obj[label_key], +(obj[value_key]) m.hincrby tot_key, 'sum', +(obj[value_key]) m.hincrby tot_key, 'count', 1 # write key members for the current day arr.push (c) => @members_keys.add today, keys_queue, c # perform redis operations arr.push ((c) -> m.exec c) await _.par arr, defer e,r cb null, r if cb # primary query-style, unix_min, unix_max query: (min,max,opt,cb) -> if !cb and _.type(opt) is 'function' cb = opt opt = {} dkey = @key + ':' + _.<KEY>() if !cb cb = max max = min min_date = new Date min * 1000 max_date = new Date max * 1000 min_date.clearTime() max_date.clearTime() num_days = min_date.getDaysBetween max_date prefix = @key ret = {} arr = [] all_days = [] while max_date >= min_date do => day = min_date.clone() day.clearTime() unix = Math.round day.getTime()/1000 # get key memberships for this day arr.push (c) => @members_keys.list unix, c all_days.push unix ret[unix] = date: day.toFormat 'MM/DD/YYYY' result: [] min_date.addDays 1 await _.par arr, defer e,r if !r?.length return cb null, ret jobs = @_jobs r fns = {} job_keys = [] blacklist = [] for k,v of jobs for path,func of v job_keys.push path # ignore/accept glob-style path matching opt.ignore ?= [] opt.accept ?= (opt.allow ? []) if opt.ignore opt.ignore = [opt.ignore] if _.type(opt.ignore) is 'string' opt.ignore = opt.ignore if opt.accept opt.accept = [opt.accept] if _.type(opt.accept) is 'string' opt.accept = opt.accept if opt.ignore.length for x in job_keys raw = x.substr(@key.length + 1) parts = raw.split ':' parts.shift() raw = parts.join ':' for pattern in opt.ignore blacklist.push(x) if minimatch(raw,pattern) if opt.accept.length for x in job_keys continue if x in blacklist raw = x.substr(@key.length + 1) parts = raw.split ':' parts.shift() raw = parts.join ':' valid = no for pattern in opt.accept if minimatch(raw,pattern) valid = yes break blacklist.push x if !valid # return here if we only want the jobs back if opt.return_jobs if blacklist.length return cb null, (_.difference job_keys,blacklist) else return cb null, job_keys for k,v of jobs do (k,v) -> # delete job if the key is in our blacklist if blacklist.length for k2,v2 of v delete v[k2] if k2 in blacklist if opt.ignore_jobs for x in opt.ignore_jobs return if k.includes(x) fns[k] = ((c) -> _.series v, c ) await _.par fns, defer e2,r2 if e2 or !_.size(r2) return cb null, ret for type,results of r2 do (results) -> for location,item of results do (item) -> return if !ret[item.day] item.key = location.split(':').<KEY>split '~' ret[item.day].result.push item return cb null, (@_format ret,no) # alternative query-style, days relative to today query_days: (num_days,cb) -> max_date = new Date min_date = new Date if num_days > 0 then num_days *= -1 ++ num_days min_date.add days:num_days min = Math.round min_date.getTime()/1000 max = Math.round max_date.getTime()/1000 @query min, max, cb _query_keys: (keys,cb) -> start = new Date min = no max = no for x in keys do (x) -> time = x.split(':')[1] if !min or time < min then min = time if !max or time > max then max = time range = [min..max] days = (x for x in range by (3600 * 24)).reverse() fns = @_jobs keys afns = {} for k,v of fns do (k,v) -> afns[k] = (c) -> _.par fns[k], c _.par afns, (e,r) -> out = { days: {} min: min max: max elapsed: "#{new Date() - start}ms" } if _.keys(r).length for k,v of r do (k,v) => for key,stats of v do (key,stats) => if !out.days[stats.day] out.days[stats.day] = {} if !out.days[stats.day][stats.type] out.days[stats.day][stats.type] = {} map_key = stats.location.split /:/ map_key = map_key.slice -1 out.days[stats.day][stats.type][map_key] = stats for x in days do (x) -> if !out.days[x] then out.days[x] = {} out.days[x].date = new Date(x * 1000).toFormat 'MM/DD/YYYY' cb null, out # creates an object filled with functions for async to execute # based on the type of redis key for each item _jobs: (keys) -> fns = add: {} top: {} bmp: {} addv: {} keys = _.uniq _.flatten keys for y in keys do (y) => # fix for keys with colons if @key.includes(':') y = y.split(@key).join('_tmp_') [key,time,type...,fields] = y.split /:/ # fix for keys with colons if y.includes('_tmp_') y = y.split('_tmp_').join @key if _.first(type) is 'addv' type = ['addv'] return if type.length is 2 job = day: time type: type.shift() location: y cache_key: <KEY>}" do_cache = no do_cache = yes if job.day < _.today() if job.type is 'add' fns.add[job.location] = (c) => if do_cache await @memcached.get job.cache_key, defer e,cache_r if cache_r then return c null, cache_r @redis.hgetall job.location, (e,r) => job.result = r await @memcached.set job.cache_key, job, 0, defer() if do_cache c null, job if job.type is 'addv' fns.add[job.location] = (c) => if do_cache await @memcached.get job.cache_key, defer e,cache_r if cache_r then return c null, cache_r @redis.hgetall job.location, (e,r) => job.result = r await @memcached.set job.cache_key, job, 0, defer() if do_cache c null, job else if job.type is 'bmp' fns.bmp[job.location] = (c) => if do_cache await @memcached.get job.cache_key, defer e,cache_r if cache_r then return c null, cache_r @redis.bitcount job.location, (e,r) => job.result = r await @memcached.set job.cache_key, job, 0, defer() if do_cache c null, job else if job.type is 'top' fns.top[job.location] = (c) => if do_cache await @memcached.get job.cache_key, defer e,cache_r if cache_r then return c null, cache_r args = [ job.location '+inf' '-inf' 'WITHSCORES' 'LIMIT' 0 250 ] @redis.zrevrangebyscore args, (e,r) => ret = {} if r?.length last = null i = 0; for z in r do (z) => ++i; if i % 2 ret[z] = null last = z else ret[last] = parseInt z job.result = ret await @memcached.set job.cache_key, job, 0, defer() if do_cache c null, job return fns # output formatting, creates and attached a filter function to easily # sort the result object data for reporting use _format: (obj,cached) -> merge_numeric = ((uno,dos) -> return dos if !uno and dos return uno if uno and !dos for k,v of dos uno[k] ?= 0 uno[k] += (+v) return uno ) output = days: obj cache: (if cached then 'hit' else 'miss') find: (o) -> opt = { type: null key: null day: no merge: no } if typeof o is 'object' if o.keys and !o.key o.key = o.keys delete o.keys opt = _.merge o else parts = o.split '/' opt.type = parts.shift() opt.key = parts.shift() if parts.length opt.day = parts.shift() opt.key = opt.key.split('~').<KEY> '~' if opt.day if !obj[opt.day]?.result? return null for v in obj[opt.day].result if v.type is opt.type if v.location.substr((opt.key.length + 1) * -1) is ":#{opt.key}" return v.result return null else ret = {} for unix,item of obj if opt.type is 'bmp' val = 0 else if opt.type in ['top','add'] val = {} else if opt.type is 'addv' val = {} ret[item.date] = val continue if !item?.result?.length for v in item.result if v.type is opt.type if v.location.substr((opt.key.length + 1) * -1) is ":#{opt.key}" ret[item.date] = v.result if opt.merge tot = {} arr = _.vals ret for x in arr do (x) -> tot = merge_numeric tot, x tot else ret ## if !module.parent log /DEVEL/ process.exit 0
true
# vim: set expandtab tabstop=2 shiftwidth=2 softtabstop=2 log = (x...) -> try console.log x... lp = (x) -> log JSON.stringify(x,null,2) _ = require('wegweg')({ globals: off }) require 'date-utils' async = require 'async' minimatch = require 'minimatch' Members = require 'taky-redis-members' ident = require './lib/redis-ident' module.exports = class Metrics constructor: (opt={}) -> # define storage instances @redis = opt.redis ? opt.client ? _.redis() @memcached = opt.memcached ? opt.memcached ? _.memcached() @key = opt.key ? opt.prefix ? 'tky' @members_keys = new Members { redis: @redis prefix: @key + ':k' } @map = { bmp: [] add: [] addv: [] top: [] } if opt.map @map[k] = v for k,v of opt.map # record an event using the metrics utility, perform redis # operations according to the constructed map configuration record: (event,cb) -> dkey = @key + ':' + (today = _.today()) obj = _.clone event for x of obj for y of obj if x != y and !x.match(/\~/) and !y.match(/\~/) cat = [x,y].sort() key = cat.join('~') if not obj[key] obj[key] = obj[cat[0]] + '~' + obj[cat[1]] # function container arr = [] # key membership queue keys_queue = [] m = @redis.multi() if @map.bmp?.length for x in @map.bmp if x.match(/\~/) x = x.split(/\~/).sort().join('~') if obj[x] do (x) => bmp_id = ident @redis, dkey + ':bmp:i:' + x bmp_key = dkey + ':bmp:' + x keys_queue.push bmp_key = dkey + ':bmp:' + x fns = [ (c) => bmp_id obj[x], (e,id) -> c null, id (i,c) => @redis.setbit bmp_key, i, 1, (e,r) -> c null, r ] arr.push((c) -> async.waterfall fns, c) ### # hyperloglog implementation; no noticable performance benefit arr.push ((c) => @redis.send_command 'pfadd', [bmp_key,obj[x]], c ) ### if @map.add?.length for x in @map.add if x.match(/\~/) x = x.split(/\~/).sort().join('~') if obj[x] do (x) => add_key = dkey + ':add:' + x keys_queue.push add_key m.hincrby add_key, obj[x], 1 if @map.top?.length for x in @map.top if x.match(/\~/) x = x.split(/\~/).sort().join('~') if obj[x] do (x) => set_key = dkey + ':top:' + x keys_queue.push set_key m.zincrby set_key, 1, obj[x] if @map.addv?.length for x in @map.addv if _.type(x) is 'object' label_key = x.key value_key = x.value ? x.val else label_key = x value_key = x if label_key.match(/\~/) label_key = label_key.split(/\~/).sort().join('~') if obj[label_key] and obj[value_key] and !isNaN(obj[value_key]) do (label_key,value_key) => add_key = dkey + ':addPI:KEY:<KEY>END_PI:' + value_key + ':' + label_key tot_key = dkey + ':addPI:KEY:<KEY>END_PI:' + value_key + ':' + 'i' keys_queue.push add_key keys_queue.push tot_key if label_key isnt value_key m.hincrby add_key, obj[label_key], +(obj[value_key]) m.hincrby tot_key, 'sum', +(obj[value_key]) m.hincrby tot_key, 'count', 1 # write key members for the current day arr.push (c) => @members_keys.add today, keys_queue, c # perform redis operations arr.push ((c) -> m.exec c) await _.par arr, defer e,r cb null, r if cb # primary query-style, unix_min, unix_max query: (min,max,opt,cb) -> if !cb and _.type(opt) is 'function' cb = opt opt = {} dkey = @key + ':' + _.PI:KEY:<KEY>END_PI() if !cb cb = max max = min min_date = new Date min * 1000 max_date = new Date max * 1000 min_date.clearTime() max_date.clearTime() num_days = min_date.getDaysBetween max_date prefix = @key ret = {} arr = [] all_days = [] while max_date >= min_date do => day = min_date.clone() day.clearTime() unix = Math.round day.getTime()/1000 # get key memberships for this day arr.push (c) => @members_keys.list unix, c all_days.push unix ret[unix] = date: day.toFormat 'MM/DD/YYYY' result: [] min_date.addDays 1 await _.par arr, defer e,r if !r?.length return cb null, ret jobs = @_jobs r fns = {} job_keys = [] blacklist = [] for k,v of jobs for path,func of v job_keys.push path # ignore/accept glob-style path matching opt.ignore ?= [] opt.accept ?= (opt.allow ? []) if opt.ignore opt.ignore = [opt.ignore] if _.type(opt.ignore) is 'string' opt.ignore = opt.ignore if opt.accept opt.accept = [opt.accept] if _.type(opt.accept) is 'string' opt.accept = opt.accept if opt.ignore.length for x in job_keys raw = x.substr(@key.length + 1) parts = raw.split ':' parts.shift() raw = parts.join ':' for pattern in opt.ignore blacklist.push(x) if minimatch(raw,pattern) if opt.accept.length for x in job_keys continue if x in blacklist raw = x.substr(@key.length + 1) parts = raw.split ':' parts.shift() raw = parts.join ':' valid = no for pattern in opt.accept if minimatch(raw,pattern) valid = yes break blacklist.push x if !valid # return here if we only want the jobs back if opt.return_jobs if blacklist.length return cb null, (_.difference job_keys,blacklist) else return cb null, job_keys for k,v of jobs do (k,v) -> # delete job if the key is in our blacklist if blacklist.length for k2,v2 of v delete v[k2] if k2 in blacklist if opt.ignore_jobs for x in opt.ignore_jobs return if k.includes(x) fns[k] = ((c) -> _.series v, c ) await _.par fns, defer e2,r2 if e2 or !_.size(r2) return cb null, ret for type,results of r2 do (results) -> for location,item of results do (item) -> return if !ret[item.day] item.key = location.split(':').PI:KEY:<KEY>END_PIsplit '~' ret[item.day].result.push item return cb null, (@_format ret,no) # alternative query-style, days relative to today query_days: (num_days,cb) -> max_date = new Date min_date = new Date if num_days > 0 then num_days *= -1 ++ num_days min_date.add days:num_days min = Math.round min_date.getTime()/1000 max = Math.round max_date.getTime()/1000 @query min, max, cb _query_keys: (keys,cb) -> start = new Date min = no max = no for x in keys do (x) -> time = x.split(':')[1] if !min or time < min then min = time if !max or time > max then max = time range = [min..max] days = (x for x in range by (3600 * 24)).reverse() fns = @_jobs keys afns = {} for k,v of fns do (k,v) -> afns[k] = (c) -> _.par fns[k], c _.par afns, (e,r) -> out = { days: {} min: min max: max elapsed: "#{new Date() - start}ms" } if _.keys(r).length for k,v of r do (k,v) => for key,stats of v do (key,stats) => if !out.days[stats.day] out.days[stats.day] = {} if !out.days[stats.day][stats.type] out.days[stats.day][stats.type] = {} map_key = stats.location.split /:/ map_key = map_key.slice -1 out.days[stats.day][stats.type][map_key] = stats for x in days do (x) -> if !out.days[x] then out.days[x] = {} out.days[x].date = new Date(x * 1000).toFormat 'MM/DD/YYYY' cb null, out # creates an object filled with functions for async to execute # based on the type of redis key for each item _jobs: (keys) -> fns = add: {} top: {} bmp: {} addv: {} keys = _.uniq _.flatten keys for y in keys do (y) => # fix for keys with colons if @key.includes(':') y = y.split(@key).join('_tmp_') [key,time,type...,fields] = y.split /:/ # fix for keys with colons if y.includes('_tmp_') y = y.split('_tmp_').join @key if _.first(type) is 'addv' type = ['addv'] return if type.length is 2 job = day: time type: type.shift() location: y cache_key: PI:KEY:<KEY>END_PI}" do_cache = no do_cache = yes if job.day < _.today() if job.type is 'add' fns.add[job.location] = (c) => if do_cache await @memcached.get job.cache_key, defer e,cache_r if cache_r then return c null, cache_r @redis.hgetall job.location, (e,r) => job.result = r await @memcached.set job.cache_key, job, 0, defer() if do_cache c null, job if job.type is 'addv' fns.add[job.location] = (c) => if do_cache await @memcached.get job.cache_key, defer e,cache_r if cache_r then return c null, cache_r @redis.hgetall job.location, (e,r) => job.result = r await @memcached.set job.cache_key, job, 0, defer() if do_cache c null, job else if job.type is 'bmp' fns.bmp[job.location] = (c) => if do_cache await @memcached.get job.cache_key, defer e,cache_r if cache_r then return c null, cache_r @redis.bitcount job.location, (e,r) => job.result = r await @memcached.set job.cache_key, job, 0, defer() if do_cache c null, job else if job.type is 'top' fns.top[job.location] = (c) => if do_cache await @memcached.get job.cache_key, defer e,cache_r if cache_r then return c null, cache_r args = [ job.location '+inf' '-inf' 'WITHSCORES' 'LIMIT' 0 250 ] @redis.zrevrangebyscore args, (e,r) => ret = {} if r?.length last = null i = 0; for z in r do (z) => ++i; if i % 2 ret[z] = null last = z else ret[last] = parseInt z job.result = ret await @memcached.set job.cache_key, job, 0, defer() if do_cache c null, job return fns # output formatting, creates and attached a filter function to easily # sort the result object data for reporting use _format: (obj,cached) -> merge_numeric = ((uno,dos) -> return dos if !uno and dos return uno if uno and !dos for k,v of dos uno[k] ?= 0 uno[k] += (+v) return uno ) output = days: obj cache: (if cached then 'hit' else 'miss') find: (o) -> opt = { type: null key: null day: no merge: no } if typeof o is 'object' if o.keys and !o.key o.key = o.keys delete o.keys opt = _.merge o else parts = o.split '/' opt.type = parts.shift() opt.key = parts.shift() if parts.length opt.day = parts.shift() opt.key = opt.key.split('~').PI:KEY:<KEY>END_PI '~' if opt.day if !obj[opt.day]?.result? return null for v in obj[opt.day].result if v.type is opt.type if v.location.substr((opt.key.length + 1) * -1) is ":#{opt.key}" return v.result return null else ret = {} for unix,item of obj if opt.type is 'bmp' val = 0 else if opt.type in ['top','add'] val = {} else if opt.type is 'addv' val = {} ret[item.date] = val continue if !item?.result?.length for v in item.result if v.type is opt.type if v.location.substr((opt.key.length + 1) * -1) is ":#{opt.key}" ret[item.date] = v.result if opt.merge tot = {} arr = _.vals ret for x in arr do (x) -> tot = merge_numeric tot, x tot else ret ## if !module.parent log /DEVEL/ process.exit 0
[ { "context": "#\n# middleware/not_authenticated.coffee\n#\n# © 2014 Dan Nichols\n# See LICENSE for more details\n#\n# Middleware to ", "end": 64, "score": 0.999693751335144, "start": 53, "tag": "NAME", "value": "Dan Nichols" } ]
lib/middleware/not_authenticated.coffee
dlnichols/h_media
0
### # middleware/not_authenticated.coffee # # © 2014 Dan Nichols # See LICENSE for more details # # Middleware to check that no user is authenticated ### 'use strict' # External libs debug = require('debug') 'hMedia:middleware:notAuthenticated' ### # notAuthenticated ### module.exports = exports = # Stop authenticated users from performing actions limited to unauthenticated users (req, res, next) -> if process.env.SKIP_AUTH debug 'Skipping authentication...' return next() unless req.isAuthenticated() next() else res.status 400 .json error: 'Must be logged out'
1454
### # middleware/not_authenticated.coffee # # © 2014 <NAME> # See LICENSE for more details # # Middleware to check that no user is authenticated ### 'use strict' # External libs debug = require('debug') 'hMedia:middleware:notAuthenticated' ### # notAuthenticated ### module.exports = exports = # Stop authenticated users from performing actions limited to unauthenticated users (req, res, next) -> if process.env.SKIP_AUTH debug 'Skipping authentication...' return next() unless req.isAuthenticated() next() else res.status 400 .json error: 'Must be logged out'
true
### # middleware/not_authenticated.coffee # # © 2014 PI:NAME:<NAME>END_PI # See LICENSE for more details # # Middleware to check that no user is authenticated ### 'use strict' # External libs debug = require('debug') 'hMedia:middleware:notAuthenticated' ### # notAuthenticated ### module.exports = exports = # Stop authenticated users from performing actions limited to unauthenticated users (req, res, next) -> if process.env.SKIP_AUTH debug 'Skipping authentication...' return next() unless req.isAuthenticated() next() else res.status 400 .json error: 'Must be logged out'
[ { "context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission", "end": 18, "score": 0.9976070523262024, "start": 12, "tag": "NAME", "value": "Joyent" } ]
test/simple/test-cluster-eaccess.coffee
lxe/io.coffee
0
# Copyright Joyent, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. # test that errors propagated from cluster children are properly received in their master # creates an EADDRINUSE condition by also forking a child process to listen on a socket common = require("../common") assert = require("assert") cluster = require("cluster") fork = require("child_process").fork fs = require("fs") net = require("net") if cluster.isMaster worker = cluster.fork() gotError = 0 worker.on "message", (err) -> gotError++ console.log err assert.strictEqual "EADDRINUSE", err.code worker.disconnect() return process.on "exit", -> console.log "master exited" try fs.unlinkSync common.PIPE assert.equal gotError, 1 return else cp = fork(common.fixturesDir + "/listen-on-socket-and-exit.js", stdio: "inherit" ) # message from the child indicates it's ready and listening cp.on "message", -> server = net.createServer().listen(common.PIPE, -> console.log "parent listening, should not be!" return ) server.on "error", (err) -> console.log "parent error, ending" # message to child process tells it to exit cp.send "end" # propagate error to parent process.send err return return
129122
# Copyright <NAME>, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. # test that errors propagated from cluster children are properly received in their master # creates an EADDRINUSE condition by also forking a child process to listen on a socket common = require("../common") assert = require("assert") cluster = require("cluster") fork = require("child_process").fork fs = require("fs") net = require("net") if cluster.isMaster worker = cluster.fork() gotError = 0 worker.on "message", (err) -> gotError++ console.log err assert.strictEqual "EADDRINUSE", err.code worker.disconnect() return process.on "exit", -> console.log "master exited" try fs.unlinkSync common.PIPE assert.equal gotError, 1 return else cp = fork(common.fixturesDir + "/listen-on-socket-and-exit.js", stdio: "inherit" ) # message from the child indicates it's ready and listening cp.on "message", -> server = net.createServer().listen(common.PIPE, -> console.log "parent listening, should not be!" return ) server.on "error", (err) -> console.log "parent error, ending" # message to child process tells it to exit cp.send "end" # propagate error to parent process.send err return return
true
# Copyright PI:NAME:<NAME>END_PI, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. # test that errors propagated from cluster children are properly received in their master # creates an EADDRINUSE condition by also forking a child process to listen on a socket common = require("../common") assert = require("assert") cluster = require("cluster") fork = require("child_process").fork fs = require("fs") net = require("net") if cluster.isMaster worker = cluster.fork() gotError = 0 worker.on "message", (err) -> gotError++ console.log err assert.strictEqual "EADDRINUSE", err.code worker.disconnect() return process.on "exit", -> console.log "master exited" try fs.unlinkSync common.PIPE assert.equal gotError, 1 return else cp = fork(common.fixturesDir + "/listen-on-socket-and-exit.js", stdio: "inherit" ) # message from the child indicates it's ready and listening cp.on "message", -> server = net.createServer().listen(common.PIPE, -> console.log "parent listening, should not be!" return ) server.on "error", (err) -> console.log "parent error, ending" # message to child process tells it to exit cp.send "end" # propagate error to parent process.send err return return
[ { "context": "module.exports = (robot) ->\n\n key = 'teeder_status'\n maxMessageLength = 140\n maxMessageHistory = 1", "end": 51, "score": 0.9985289573669434, "start": 38, "tag": "KEY", "value": "teeder_status" } ]
scripts/status.coffee
brian915/hubot-teeder
0
module.exports = (robot) -> key = 'teeder_status' maxMessageLength = 140 maxMessageHistory = 100 defaultResponseSize = 5 robot.respond /status (.*)/i, (msg) -> message = msg.match[1].trim().substring(0,maxMessageLength) if message.match /list/ getStatus(msg) else msg.send "OK, got it: " + message putStatus(message) robot.respond /drop/i, (msg) -> dropStatus(msg) robot.respond /list/i, (msg) -> getStatus(msg) putStatus = (message, text) -> data = robot.brain.get(key) unless data instanceof Array data = [] data.unshift message robot.brain.set(key, data.slice(0, maxMessageHistory)) getStatus = (msg) -> data = robot.brain.get(key).slice(0,defaultResponseSize).reverse() for message in data msg.send(message) dropStatus = (msg) -> data = robot.brain.get(key).shift() getStatus(msg)
134951
module.exports = (robot) -> key = '<KEY>' maxMessageLength = 140 maxMessageHistory = 100 defaultResponseSize = 5 robot.respond /status (.*)/i, (msg) -> message = msg.match[1].trim().substring(0,maxMessageLength) if message.match /list/ getStatus(msg) else msg.send "OK, got it: " + message putStatus(message) robot.respond /drop/i, (msg) -> dropStatus(msg) robot.respond /list/i, (msg) -> getStatus(msg) putStatus = (message, text) -> data = robot.brain.get(key) unless data instanceof Array data = [] data.unshift message robot.brain.set(key, data.slice(0, maxMessageHistory)) getStatus = (msg) -> data = robot.brain.get(key).slice(0,defaultResponseSize).reverse() for message in data msg.send(message) dropStatus = (msg) -> data = robot.brain.get(key).shift() getStatus(msg)
true
module.exports = (robot) -> key = 'PI:KEY:<KEY>END_PI' maxMessageLength = 140 maxMessageHistory = 100 defaultResponseSize = 5 robot.respond /status (.*)/i, (msg) -> message = msg.match[1].trim().substring(0,maxMessageLength) if message.match /list/ getStatus(msg) else msg.send "OK, got it: " + message putStatus(message) robot.respond /drop/i, (msg) -> dropStatus(msg) robot.respond /list/i, (msg) -> getStatus(msg) putStatus = (message, text) -> data = robot.brain.get(key) unless data instanceof Array data = [] data.unshift message robot.brain.set(key, data.slice(0, maxMessageHistory)) getStatus = (msg) -> data = robot.brain.get(key).slice(0,defaultResponseSize).reverse() for message in data msg.send(message) dropStatus = (msg) -> data = robot.brain.get(key).shift() getStatus(msg)
[ { "context": "overview Enforce component methods order\n# @author Yannick Croissant\n###\n'use strict'\n\n{has} = require 'lodash'\nutil =", "end": 80, "score": 0.9998589158058167, "start": 63, "tag": "NAME", "value": "Yannick Croissant" } ]
src/rules/sort-comp.coffee
danielbayley/eslint-plugin-coffee
21
###* # @fileoverview Enforce component methods order # @author Yannick Croissant ### 'use strict' {has} = require 'lodash' util = require 'util' Components = require '../util/react/Components' astUtil = require '../util/react/ast' docsUrl = require 'eslint-plugin-react/lib/util/docsUrl' defaultConfig = order: ['static-methods', 'lifecycle', 'everything-else', 'render'] groups: lifecycle: [ 'displayName' 'propTypes' 'contextTypes' 'childContextTypes' 'mixins' 'statics' 'defaultProps' 'constructor' 'getDefaultProps' 'state' 'getInitialState' 'getChildContext' 'getDerivedStateFromProps' 'componentWillMount' 'UNSAFE_componentWillMount' 'componentDidMount' 'componentWillReceiveProps' 'UNSAFE_componentWillReceiveProps' 'shouldComponentUpdate' 'componentWillUpdate' 'UNSAFE_componentWillUpdate' 'getSnapshotBeforeUpdate' 'componentDidUpdate' 'componentDidCatch' 'componentWillUnmount' ] ###* # Get the methods order from the default config and the user config # @param {Object} userConfig The user configuration. # @returns {Array} Methods order ### getMethodsOrder = (userConfig) -> userConfig or= {} groups = util._extend defaultConfig.groups, userConfig.groups order = userConfig.order or defaultConfig.order config = [] for entry in order if has groups, entry config = config.concat groups[entry] else config.push entry config # ------------------------------------------------------------------------------ # Rule Definition # ------------------------------------------------------------------------------ module.exports = { meta: docs: description: 'Enforce component methods order' category: 'Stylistic Issues' recommended: no url: docsUrl 'sort-comp' schema: [ type: 'object' properties: order: type: 'array' items: type: 'string' groups: type: 'object' patternProperties: '^.*$': type: 'array' items: type: 'string' additionalProperties: no ] create: Components.detect (context, components) -> errors = {} MISPOSITION_MESSAGE = '{{propA}} should be placed {{position}} {{propB}}' methodsOrder = getMethodsOrder context.options[0] # -------------------------------------------------------------------------- # Public # -------------------------------------------------------------------------- regExpRegExp = /\/(.*)\/([g|y|i|m]*)/ ###* # Get indexes of the matching patterns in methods order configuration # @param {Object} method - Method metadata. # @returns {Array} The matching patterns indexes. Return [Infinity] if there is no match. ### getRefPropIndexes = (method) -> methodGroupIndexes = [] methodsOrder.forEach (currentGroup, groupIndex) -> if currentGroup is 'getters' if method.getter then methodGroupIndexes.push groupIndex else if currentGroup is 'setters' if method.setter then methodGroupIndexes.push groupIndex else if currentGroup is 'type-annotations' if method.typeAnnotation then methodGroupIndexes.push groupIndex else if currentGroup is 'static-methods' if method.static then methodGroupIndexes.push groupIndex else if currentGroup is 'instance-variables' if method.instanceVariable then methodGroupIndexes.push groupIndex else if currentGroup is 'instance-methods' if method.instanceMethod then methodGroupIndexes.push groupIndex else if currentGroup in [ 'displayName' 'propTypes' 'contextTypes' 'childContextTypes' 'mixins' 'statics' 'defaultProps' 'constructor' 'getDefaultProps' 'state' 'getInitialState' 'getChildContext' 'getDerivedStateFromProps' 'componentWillMount' 'UNSAFE_componentWillMount' 'componentDidMount' 'componentWillReceiveProps' 'UNSAFE_componentWillReceiveProps' 'shouldComponentUpdate' 'componentWillUpdate' 'UNSAFE_componentWillUpdate' 'getSnapshotBeforeUpdate' 'componentDidUpdate' 'componentDidCatch' 'componentWillUnmount' 'render' ] methodGroupIndexes.push groupIndex if currentGroup is method.name else # Is the group a regex? isRegExp = currentGroup.match regExpRegExp if isRegExp isMatching = new RegExp(isRegExp[1], isRegExp[2]).test method.name methodGroupIndexes.push groupIndex if isMatching else if currentGroup is method.name methodGroupIndexes.push groupIndex # No matching pattern, return 'everything-else' index if methodGroupIndexes.length is 0 everythingElseIndex = methodsOrder.indexOf 'everything-else' unless everythingElseIndex is -1 methodGroupIndexes.push everythingElseIndex else # No matching pattern and no 'everything-else' group methodGroupIndexes.push Infinity methodGroupIndexes ###* # Get properties name # @param {Object} node - Property. # @returns {String} Property name. ### getPropertyName = (node) -> return 'getter functions' if node.kind is 'get' return 'setter functions' if node.kind is 'set' astUtil.getPropertyName node ###* # Store a new error in the error list # @param {Object} propA - Mispositioned property. # @param {Object} propB - Reference property. ### storeError = (propA, propB) -> # Initialize the error object if needed unless errors[propA.index] errors[propA.index] = node: propA.node score: 0 closest: distance: Infinity ref: node: null index: 0 # Increment the prop score errors[propA.index].score++ # Stop here if we already have pushed another node at this position return unless ( getPropertyName(errors[propA.index].node) is getPropertyName propA.node ) # Stop here if we already have a closer reference return if ( Math.abs(propA.index - propB.index) > errors[propA.index].closest.distance ) # Update the closest reference errors[propA.index].closest.distance = Math.abs propA.index - propB.index errors[propA.index].closest.ref.node = propB.node errors[propA.index].closest.ref.index = propB.index ###* # Dedupe errors, only keep the ones with the highest score and delete the others ### dedupeErrors = -> for own i, error of errors {index} = error.closest.ref continue unless errors[index] if error.score > errors[index].score delete errors[index] else delete errors[i] ###* # Report errors ### reportErrors = -> dedupeErrors() for own i, error of errors nodeA = error.node nodeB = error.closest.ref.node indexA = i indexB = error.closest.ref.index context.report node: nodeA message: MISPOSITION_MESSAGE data: propA: getPropertyName nodeA propB: getPropertyName nodeB position: if indexA < indexB then 'before' else 'after' ###* # Compare two properties and find out if they are in the right order # @param {Array} propertiesInfos Array containing all the properties metadata. # @param {Object} propA First property name and metadata # @param {Object} propB Second property name. # @returns {Object} Object containing a correct true/false flag and the correct indexes for the two properties. ### comparePropsOrder = (propertiesInfos, propA, propB) -> # Get references indexes (the correct position) for given properties refIndexesA = getRefPropIndexes propA refIndexesB = getRefPropIndexes propB # Get current indexes for given properties classIndexA = propertiesInfos.indexOf propA classIndexB = propertiesInfos.indexOf propB # Loop around the references indexes for the 1st property for refIndexA in refIndexesA for refIndexB in refIndexesB return { correct: yes indexA: classIndexA indexB: classIndexB } if ( refIndexA is refIndexB or (refIndexA < refIndexB and classIndexA < classIndexB) or (refIndexA > refIndexB and classIndexA > classIndexB) ) # Loop around the properties for the 2nd property (for comparison) # Comparing the same properties # 1st property is placed before the 2nd one in reference and in current component # 1st property is placed after the 2nd one in reference and in current component # We did not find any correct match between reference and current component correct: no indexA: refIndexA indexB: refIndexB ###* # Check properties order from a properties list and store the eventual errors # @param {Array} properties Array containing all the properties. ### checkPropsOrder = (properties) -> propertiesInfos = properties.map (node) -> name: getPropertyName node getter: node.kind is 'get' setter: node.kind is 'set' static: node.static instanceVariable: not node.static and node.type is 'ClassProperty' and node.value and not astUtil.isFunctionLikeExpression node.value instanceMethod: not node.static and node.type is 'ClassProperty' and node.value and astUtil.isFunctionLikeExpression node.value typeAnnotation: !!node.typeAnnotation and node.value is null # Loop around the properties for propA, i in propertiesInfos # Loop around the properties a second time (for comparison) for propB, k in propertiesInfos continue if i is k # Compare the properties order order = comparePropsOrder propertiesInfos, propA, propB # Continue to next comparison is order is correct continue if order.correct is yes # Store an error if the order is incorrect storeError node: properties[i] index: order.indexA , node: properties[k] index: order.indexB 'Program:exit': -> for own _, component of components.list() properties = astUtil.getComponentProperties component.node checkPropsOrder properties reportErrors() defaultConfig }
137909
###* # @fileoverview Enforce component methods order # @author <NAME> ### 'use strict' {has} = require 'lodash' util = require 'util' Components = require '../util/react/Components' astUtil = require '../util/react/ast' docsUrl = require 'eslint-plugin-react/lib/util/docsUrl' defaultConfig = order: ['static-methods', 'lifecycle', 'everything-else', 'render'] groups: lifecycle: [ 'displayName' 'propTypes' 'contextTypes' 'childContextTypes' 'mixins' 'statics' 'defaultProps' 'constructor' 'getDefaultProps' 'state' 'getInitialState' 'getChildContext' 'getDerivedStateFromProps' 'componentWillMount' 'UNSAFE_componentWillMount' 'componentDidMount' 'componentWillReceiveProps' 'UNSAFE_componentWillReceiveProps' 'shouldComponentUpdate' 'componentWillUpdate' 'UNSAFE_componentWillUpdate' 'getSnapshotBeforeUpdate' 'componentDidUpdate' 'componentDidCatch' 'componentWillUnmount' ] ###* # Get the methods order from the default config and the user config # @param {Object} userConfig The user configuration. # @returns {Array} Methods order ### getMethodsOrder = (userConfig) -> userConfig or= {} groups = util._extend defaultConfig.groups, userConfig.groups order = userConfig.order or defaultConfig.order config = [] for entry in order if has groups, entry config = config.concat groups[entry] else config.push entry config # ------------------------------------------------------------------------------ # Rule Definition # ------------------------------------------------------------------------------ module.exports = { meta: docs: description: 'Enforce component methods order' category: 'Stylistic Issues' recommended: no url: docsUrl 'sort-comp' schema: [ type: 'object' properties: order: type: 'array' items: type: 'string' groups: type: 'object' patternProperties: '^.*$': type: 'array' items: type: 'string' additionalProperties: no ] create: Components.detect (context, components) -> errors = {} MISPOSITION_MESSAGE = '{{propA}} should be placed {{position}} {{propB}}' methodsOrder = getMethodsOrder context.options[0] # -------------------------------------------------------------------------- # Public # -------------------------------------------------------------------------- regExpRegExp = /\/(.*)\/([g|y|i|m]*)/ ###* # Get indexes of the matching patterns in methods order configuration # @param {Object} method - Method metadata. # @returns {Array} The matching patterns indexes. Return [Infinity] if there is no match. ### getRefPropIndexes = (method) -> methodGroupIndexes = [] methodsOrder.forEach (currentGroup, groupIndex) -> if currentGroup is 'getters' if method.getter then methodGroupIndexes.push groupIndex else if currentGroup is 'setters' if method.setter then methodGroupIndexes.push groupIndex else if currentGroup is 'type-annotations' if method.typeAnnotation then methodGroupIndexes.push groupIndex else if currentGroup is 'static-methods' if method.static then methodGroupIndexes.push groupIndex else if currentGroup is 'instance-variables' if method.instanceVariable then methodGroupIndexes.push groupIndex else if currentGroup is 'instance-methods' if method.instanceMethod then methodGroupIndexes.push groupIndex else if currentGroup in [ 'displayName' 'propTypes' 'contextTypes' 'childContextTypes' 'mixins' 'statics' 'defaultProps' 'constructor' 'getDefaultProps' 'state' 'getInitialState' 'getChildContext' 'getDerivedStateFromProps' 'componentWillMount' 'UNSAFE_componentWillMount' 'componentDidMount' 'componentWillReceiveProps' 'UNSAFE_componentWillReceiveProps' 'shouldComponentUpdate' 'componentWillUpdate' 'UNSAFE_componentWillUpdate' 'getSnapshotBeforeUpdate' 'componentDidUpdate' 'componentDidCatch' 'componentWillUnmount' 'render' ] methodGroupIndexes.push groupIndex if currentGroup is method.name else # Is the group a regex? isRegExp = currentGroup.match regExpRegExp if isRegExp isMatching = new RegExp(isRegExp[1], isRegExp[2]).test method.name methodGroupIndexes.push groupIndex if isMatching else if currentGroup is method.name methodGroupIndexes.push groupIndex # No matching pattern, return 'everything-else' index if methodGroupIndexes.length is 0 everythingElseIndex = methodsOrder.indexOf 'everything-else' unless everythingElseIndex is -1 methodGroupIndexes.push everythingElseIndex else # No matching pattern and no 'everything-else' group methodGroupIndexes.push Infinity methodGroupIndexes ###* # Get properties name # @param {Object} node - Property. # @returns {String} Property name. ### getPropertyName = (node) -> return 'getter functions' if node.kind is 'get' return 'setter functions' if node.kind is 'set' astUtil.getPropertyName node ###* # Store a new error in the error list # @param {Object} propA - Mispositioned property. # @param {Object} propB - Reference property. ### storeError = (propA, propB) -> # Initialize the error object if needed unless errors[propA.index] errors[propA.index] = node: propA.node score: 0 closest: distance: Infinity ref: node: null index: 0 # Increment the prop score errors[propA.index].score++ # Stop here if we already have pushed another node at this position return unless ( getPropertyName(errors[propA.index].node) is getPropertyName propA.node ) # Stop here if we already have a closer reference return if ( Math.abs(propA.index - propB.index) > errors[propA.index].closest.distance ) # Update the closest reference errors[propA.index].closest.distance = Math.abs propA.index - propB.index errors[propA.index].closest.ref.node = propB.node errors[propA.index].closest.ref.index = propB.index ###* # Dedupe errors, only keep the ones with the highest score and delete the others ### dedupeErrors = -> for own i, error of errors {index} = error.closest.ref continue unless errors[index] if error.score > errors[index].score delete errors[index] else delete errors[i] ###* # Report errors ### reportErrors = -> dedupeErrors() for own i, error of errors nodeA = error.node nodeB = error.closest.ref.node indexA = i indexB = error.closest.ref.index context.report node: nodeA message: MISPOSITION_MESSAGE data: propA: getPropertyName nodeA propB: getPropertyName nodeB position: if indexA < indexB then 'before' else 'after' ###* # Compare two properties and find out if they are in the right order # @param {Array} propertiesInfos Array containing all the properties metadata. # @param {Object} propA First property name and metadata # @param {Object} propB Second property name. # @returns {Object} Object containing a correct true/false flag and the correct indexes for the two properties. ### comparePropsOrder = (propertiesInfos, propA, propB) -> # Get references indexes (the correct position) for given properties refIndexesA = getRefPropIndexes propA refIndexesB = getRefPropIndexes propB # Get current indexes for given properties classIndexA = propertiesInfos.indexOf propA classIndexB = propertiesInfos.indexOf propB # Loop around the references indexes for the 1st property for refIndexA in refIndexesA for refIndexB in refIndexesB return { correct: yes indexA: classIndexA indexB: classIndexB } if ( refIndexA is refIndexB or (refIndexA < refIndexB and classIndexA < classIndexB) or (refIndexA > refIndexB and classIndexA > classIndexB) ) # Loop around the properties for the 2nd property (for comparison) # Comparing the same properties # 1st property is placed before the 2nd one in reference and in current component # 1st property is placed after the 2nd one in reference and in current component # We did not find any correct match between reference and current component correct: no indexA: refIndexA indexB: refIndexB ###* # Check properties order from a properties list and store the eventual errors # @param {Array} properties Array containing all the properties. ### checkPropsOrder = (properties) -> propertiesInfos = properties.map (node) -> name: getPropertyName node getter: node.kind is 'get' setter: node.kind is 'set' static: node.static instanceVariable: not node.static and node.type is 'ClassProperty' and node.value and not astUtil.isFunctionLikeExpression node.value instanceMethod: not node.static and node.type is 'ClassProperty' and node.value and astUtil.isFunctionLikeExpression node.value typeAnnotation: !!node.typeAnnotation and node.value is null # Loop around the properties for propA, i in propertiesInfos # Loop around the properties a second time (for comparison) for propB, k in propertiesInfos continue if i is k # Compare the properties order order = comparePropsOrder propertiesInfos, propA, propB # Continue to next comparison is order is correct continue if order.correct is yes # Store an error if the order is incorrect storeError node: properties[i] index: order.indexA , node: properties[k] index: order.indexB 'Program:exit': -> for own _, component of components.list() properties = astUtil.getComponentProperties component.node checkPropsOrder properties reportErrors() defaultConfig }
true
###* # @fileoverview Enforce component methods order # @author PI:NAME:<NAME>END_PI ### 'use strict' {has} = require 'lodash' util = require 'util' Components = require '../util/react/Components' astUtil = require '../util/react/ast' docsUrl = require 'eslint-plugin-react/lib/util/docsUrl' defaultConfig = order: ['static-methods', 'lifecycle', 'everything-else', 'render'] groups: lifecycle: [ 'displayName' 'propTypes' 'contextTypes' 'childContextTypes' 'mixins' 'statics' 'defaultProps' 'constructor' 'getDefaultProps' 'state' 'getInitialState' 'getChildContext' 'getDerivedStateFromProps' 'componentWillMount' 'UNSAFE_componentWillMount' 'componentDidMount' 'componentWillReceiveProps' 'UNSAFE_componentWillReceiveProps' 'shouldComponentUpdate' 'componentWillUpdate' 'UNSAFE_componentWillUpdate' 'getSnapshotBeforeUpdate' 'componentDidUpdate' 'componentDidCatch' 'componentWillUnmount' ] ###* # Get the methods order from the default config and the user config # @param {Object} userConfig The user configuration. # @returns {Array} Methods order ### getMethodsOrder = (userConfig) -> userConfig or= {} groups = util._extend defaultConfig.groups, userConfig.groups order = userConfig.order or defaultConfig.order config = [] for entry in order if has groups, entry config = config.concat groups[entry] else config.push entry config # ------------------------------------------------------------------------------ # Rule Definition # ------------------------------------------------------------------------------ module.exports = { meta: docs: description: 'Enforce component methods order' category: 'Stylistic Issues' recommended: no url: docsUrl 'sort-comp' schema: [ type: 'object' properties: order: type: 'array' items: type: 'string' groups: type: 'object' patternProperties: '^.*$': type: 'array' items: type: 'string' additionalProperties: no ] create: Components.detect (context, components) -> errors = {} MISPOSITION_MESSAGE = '{{propA}} should be placed {{position}} {{propB}}' methodsOrder = getMethodsOrder context.options[0] # -------------------------------------------------------------------------- # Public # -------------------------------------------------------------------------- regExpRegExp = /\/(.*)\/([g|y|i|m]*)/ ###* # Get indexes of the matching patterns in methods order configuration # @param {Object} method - Method metadata. # @returns {Array} The matching patterns indexes. Return [Infinity] if there is no match. ### getRefPropIndexes = (method) -> methodGroupIndexes = [] methodsOrder.forEach (currentGroup, groupIndex) -> if currentGroup is 'getters' if method.getter then methodGroupIndexes.push groupIndex else if currentGroup is 'setters' if method.setter then methodGroupIndexes.push groupIndex else if currentGroup is 'type-annotations' if method.typeAnnotation then methodGroupIndexes.push groupIndex else if currentGroup is 'static-methods' if method.static then methodGroupIndexes.push groupIndex else if currentGroup is 'instance-variables' if method.instanceVariable then methodGroupIndexes.push groupIndex else if currentGroup is 'instance-methods' if method.instanceMethod then methodGroupIndexes.push groupIndex else if currentGroup in [ 'displayName' 'propTypes' 'contextTypes' 'childContextTypes' 'mixins' 'statics' 'defaultProps' 'constructor' 'getDefaultProps' 'state' 'getInitialState' 'getChildContext' 'getDerivedStateFromProps' 'componentWillMount' 'UNSAFE_componentWillMount' 'componentDidMount' 'componentWillReceiveProps' 'UNSAFE_componentWillReceiveProps' 'shouldComponentUpdate' 'componentWillUpdate' 'UNSAFE_componentWillUpdate' 'getSnapshotBeforeUpdate' 'componentDidUpdate' 'componentDidCatch' 'componentWillUnmount' 'render' ] methodGroupIndexes.push groupIndex if currentGroup is method.name else # Is the group a regex? isRegExp = currentGroup.match regExpRegExp if isRegExp isMatching = new RegExp(isRegExp[1], isRegExp[2]).test method.name methodGroupIndexes.push groupIndex if isMatching else if currentGroup is method.name methodGroupIndexes.push groupIndex # No matching pattern, return 'everything-else' index if methodGroupIndexes.length is 0 everythingElseIndex = methodsOrder.indexOf 'everything-else' unless everythingElseIndex is -1 methodGroupIndexes.push everythingElseIndex else # No matching pattern and no 'everything-else' group methodGroupIndexes.push Infinity methodGroupIndexes ###* # Get properties name # @param {Object} node - Property. # @returns {String} Property name. ### getPropertyName = (node) -> return 'getter functions' if node.kind is 'get' return 'setter functions' if node.kind is 'set' astUtil.getPropertyName node ###* # Store a new error in the error list # @param {Object} propA - Mispositioned property. # @param {Object} propB - Reference property. ### storeError = (propA, propB) -> # Initialize the error object if needed unless errors[propA.index] errors[propA.index] = node: propA.node score: 0 closest: distance: Infinity ref: node: null index: 0 # Increment the prop score errors[propA.index].score++ # Stop here if we already have pushed another node at this position return unless ( getPropertyName(errors[propA.index].node) is getPropertyName propA.node ) # Stop here if we already have a closer reference return if ( Math.abs(propA.index - propB.index) > errors[propA.index].closest.distance ) # Update the closest reference errors[propA.index].closest.distance = Math.abs propA.index - propB.index errors[propA.index].closest.ref.node = propB.node errors[propA.index].closest.ref.index = propB.index ###* # Dedupe errors, only keep the ones with the highest score and delete the others ### dedupeErrors = -> for own i, error of errors {index} = error.closest.ref continue unless errors[index] if error.score > errors[index].score delete errors[index] else delete errors[i] ###* # Report errors ### reportErrors = -> dedupeErrors() for own i, error of errors nodeA = error.node nodeB = error.closest.ref.node indexA = i indexB = error.closest.ref.index context.report node: nodeA message: MISPOSITION_MESSAGE data: propA: getPropertyName nodeA propB: getPropertyName nodeB position: if indexA < indexB then 'before' else 'after' ###* # Compare two properties and find out if they are in the right order # @param {Array} propertiesInfos Array containing all the properties metadata. # @param {Object} propA First property name and metadata # @param {Object} propB Second property name. # @returns {Object} Object containing a correct true/false flag and the correct indexes for the two properties. ### comparePropsOrder = (propertiesInfos, propA, propB) -> # Get references indexes (the correct position) for given properties refIndexesA = getRefPropIndexes propA refIndexesB = getRefPropIndexes propB # Get current indexes for given properties classIndexA = propertiesInfos.indexOf propA classIndexB = propertiesInfos.indexOf propB # Loop around the references indexes for the 1st property for refIndexA in refIndexesA for refIndexB in refIndexesB return { correct: yes indexA: classIndexA indexB: classIndexB } if ( refIndexA is refIndexB or (refIndexA < refIndexB and classIndexA < classIndexB) or (refIndexA > refIndexB and classIndexA > classIndexB) ) # Loop around the properties for the 2nd property (for comparison) # Comparing the same properties # 1st property is placed before the 2nd one in reference and in current component # 1st property is placed after the 2nd one in reference and in current component # We did not find any correct match between reference and current component correct: no indexA: refIndexA indexB: refIndexB ###* # Check properties order from a properties list and store the eventual errors # @param {Array} properties Array containing all the properties. ### checkPropsOrder = (properties) -> propertiesInfos = properties.map (node) -> name: getPropertyName node getter: node.kind is 'get' setter: node.kind is 'set' static: node.static instanceVariable: not node.static and node.type is 'ClassProperty' and node.value and not astUtil.isFunctionLikeExpression node.value instanceMethod: not node.static and node.type is 'ClassProperty' and node.value and astUtil.isFunctionLikeExpression node.value typeAnnotation: !!node.typeAnnotation and node.value is null # Loop around the properties for propA, i in propertiesInfos # Loop around the properties a second time (for comparison) for propB, k in propertiesInfos continue if i is k # Compare the properties order order = comparePropsOrder propertiesInfos, propA, propB # Continue to next comparison is order is correct continue if order.correct is yes # Store an error if the order is incorrect storeError node: properties[i] index: order.indexA , node: properties[k] index: order.indexB 'Program:exit': -> for own _, component of components.list() properties = astUtil.getComponentProperties component.node checkPropsOrder properties reportErrors() defaultConfig }
[ { "context": "tion = {}\n configuration[nerfed + \"username\"] = \"username\"\n configuration[nerfed + \"_password\"] = new Buff", "end": 848, "score": 0.9993885159492493, "start": 840, "tag": "USERNAME", "value": "username" }, { "context": " configuration[nerfed + \"_password\"] ...
deps/npm/node_modules/npm-registry-client/test/fetch-not-authed.coffee
lxe/io.coffee
0
resolve = require("path").resolve createReadStream = require("graceful-fs").createReadStream readFileSync = require("graceful-fs").readFileSync tap = require("tap") cat = require("concat-stream") server = require("./lib/server.js") common = require("./lib/common.js") tgz = resolve(__dirname, "./fixtures/underscore/1.3.3/package.tgz") tap.test "basic fetch with scoped always-auth disabled", (t) -> server.expect "/underscore/-/underscore-1.3.3.tgz", (req, res) -> t.equal req.method, "GET", "got expected method" t.notOk req.headers.authorization, "received no auth header" res.writeHead 200, "content-type": "application/x-tar" "content-encoding": "gzip" createReadStream(tgz).pipe res return nerfed = "//localhost:" + server.port + "/:" configuration = {} configuration[nerfed + "username"] = "username" configuration[nerfed + "_password"] = new Buffer("%1234@asdf%").toString("base64") configuration[nerfed + "email"] = "i@izs.me" configuration[nerfed + "always-auth"] = false client = common.freshClient(configuration) client.fetch "http://localhost:1337/underscore/-/underscore-1.3.3.tgz", null, (er, res) -> t.ifError er, "loaded successfully" sink = cat((data) -> t.deepEqual data, readFileSync(tgz) t.end() return ) res.on "error", (error) -> t.ifError error, "no errors on stream" return res.pipe sink return return
65065
resolve = require("path").resolve createReadStream = require("graceful-fs").createReadStream readFileSync = require("graceful-fs").readFileSync tap = require("tap") cat = require("concat-stream") server = require("./lib/server.js") common = require("./lib/common.js") tgz = resolve(__dirname, "./fixtures/underscore/1.3.3/package.tgz") tap.test "basic fetch with scoped always-auth disabled", (t) -> server.expect "/underscore/-/underscore-1.3.3.tgz", (req, res) -> t.equal req.method, "GET", "got expected method" t.notOk req.headers.authorization, "received no auth header" res.writeHead 200, "content-type": "application/x-tar" "content-encoding": "gzip" createReadStream(tgz).pipe res return nerfed = "//localhost:" + server.port + "/:" configuration = {} configuration[nerfed + "username"] = "username" configuration[nerfed + "_password"] = new Buffer("<PASSWORD>%").toString("base64") configuration[nerfed + "email"] = "<EMAIL>" configuration[nerfed + "always-auth"] = false client = common.freshClient(configuration) client.fetch "http://localhost:1337/underscore/-/underscore-1.3.3.tgz", null, (er, res) -> t.ifError er, "loaded successfully" sink = cat((data) -> t.deepEqual data, readFileSync(tgz) t.end() return ) res.on "error", (error) -> t.ifError error, "no errors on stream" return res.pipe sink return return
true
resolve = require("path").resolve createReadStream = require("graceful-fs").createReadStream readFileSync = require("graceful-fs").readFileSync tap = require("tap") cat = require("concat-stream") server = require("./lib/server.js") common = require("./lib/common.js") tgz = resolve(__dirname, "./fixtures/underscore/1.3.3/package.tgz") tap.test "basic fetch with scoped always-auth disabled", (t) -> server.expect "/underscore/-/underscore-1.3.3.tgz", (req, res) -> t.equal req.method, "GET", "got expected method" t.notOk req.headers.authorization, "received no auth header" res.writeHead 200, "content-type": "application/x-tar" "content-encoding": "gzip" createReadStream(tgz).pipe res return nerfed = "//localhost:" + server.port + "/:" configuration = {} configuration[nerfed + "username"] = "username" configuration[nerfed + "_password"] = new Buffer("PI:PASSWORD:<PASSWORD>END_PI%").toString("base64") configuration[nerfed + "email"] = "PI:EMAIL:<EMAIL>END_PI" configuration[nerfed + "always-auth"] = false client = common.freshClient(configuration) client.fetch "http://localhost:1337/underscore/-/underscore-1.3.3.tgz", null, (er, res) -> t.ifError er, "loaded successfully" sink = cat((data) -> t.deepEqual data, readFileSync(tgz) t.end() return ) res.on "error", (error) -> t.ifError error, "no errors on stream" return res.pipe sink return return
[ { "context": "sToken', (done) ->\n args =\n accessToken: 'myAccessToken'\n projectKey: 'myProjectKey'\n\n utils.ensu", "end": 2434, "score": 0.9489749670028687, "start": 2421, "tag": "KEY", "value": "myAccessToken" }, { "context": "ject_key: 'myProjectKey'\n ...
src/spec/utils.spec.coffee
celeste-horgan/sphere-order-export
3
_ = require 'underscore' tmp = require 'tmp' packageJson = require '../package' utils = require '../lib/utils' tmpDir = tmp.dirSync() describe 'Utils', -> it '#getFileName should return a fileName based on arguments', -> fileName = utils.getFileName(false, 'orders') expect(fileName).toBe 'orders.csv' fileName = utils.getFileName(false, 'orders', '1234') expect(fileName).toBe 'orders.csv' fileName = utils.getFileName(true, 'orders', '1234') expect(fileName).toBe 'orders_1234.csv' it '#getClientOptions should return a simple client options object', -> credentials = config: project_key: 'project-key' access_token: 'access-token' args = timeout: 100 res = utils.getClientOptions(credentials, args) expect(res).toEqual config: project_key: 'project-key' access_token: 'access-token' user_agent: "#{packageJson.name} - #{packageJson.version}" timeout: 100 it '#getClientOptions should return a complex client options object', -> credentials = config: project_key: 'project-key' access_token: 'access-token' args = timeout: 100 sphereHost: 'host' sphereProtocol: 'http' sphereAuthHost: '123' sphereAuthProtocol: 'https' res = utils.getClientOptions(credentials, args) expect(res).toEqual config: project_key: 'project-key' access_token: 'access-token' user_agent: "#{packageJson.name} - #{packageJson.version}" host: 'host' timeout: 100 protocol: 'http' oauth_host: '123' oauth_protocol: 'https' rejectUnauthorized: false it '#getDefaultOptions should return an optimist object', -> argv = utils.getDefaultOptions() expect(argv.help).toBeDefined() expect(argv.help()).toContain('Usage:') it '#getLogger should return a logger instance', -> args = projectKey: 'myProjectKey' logDir: tmpDir.name logger = utils.getLogger(args) expect(logger.additionalFields.project_key).toBe('myProjectKey') expect(logger.error).toBeDefined() expect(logger.info).toBeDefined() expect(logger.debug).toBeDefined() expect(logger.warn).toBeDefined() expect(logger.debug).toBeDefined() expect(logger.trace).toBeDefined() it '#ensureCredentials should return credentials with accessToken', (done) -> args = accessToken: 'myAccessToken' projectKey: 'myProjectKey' utils.ensureCredentials args .then (credentials) -> expect(credentials).toEqual config: project_key: 'myProjectKey' access_token: 'myAccessToken' done() .catch (e) -> done (e or 'Undefined error') it '#ensureCredentials should return credentials from env variables', (done) -> args = projectKey: 'myProjectKey' process.env.SPHERE_PROJECT_KEY = args.projectKey process.env.SPHERE_CLIENT_ID = 'myProjectId' process.env.SPHERE_CLIENT_SECRET = 'myProjectSecret' utils.ensureCredentials args .then (credentials) -> expect(credentials).toEqual config: project_key: 'myProjectKey' client_id: 'myProjectId' client_secret: 'myProjectSecret' done() .catch (e) -> done (e or 'Undefined error')
224964
_ = require 'underscore' tmp = require 'tmp' packageJson = require '../package' utils = require '../lib/utils' tmpDir = tmp.dirSync() describe 'Utils', -> it '#getFileName should return a fileName based on arguments', -> fileName = utils.getFileName(false, 'orders') expect(fileName).toBe 'orders.csv' fileName = utils.getFileName(false, 'orders', '1234') expect(fileName).toBe 'orders.csv' fileName = utils.getFileName(true, 'orders', '1234') expect(fileName).toBe 'orders_1234.csv' it '#getClientOptions should return a simple client options object', -> credentials = config: project_key: 'project-key' access_token: 'access-token' args = timeout: 100 res = utils.getClientOptions(credentials, args) expect(res).toEqual config: project_key: 'project-key' access_token: 'access-token' user_agent: "#{packageJson.name} - #{packageJson.version}" timeout: 100 it '#getClientOptions should return a complex client options object', -> credentials = config: project_key: 'project-key' access_token: 'access-token' args = timeout: 100 sphereHost: 'host' sphereProtocol: 'http' sphereAuthHost: '123' sphereAuthProtocol: 'https' res = utils.getClientOptions(credentials, args) expect(res).toEqual config: project_key: 'project-key' access_token: 'access-token' user_agent: "#{packageJson.name} - #{packageJson.version}" host: 'host' timeout: 100 protocol: 'http' oauth_host: '123' oauth_protocol: 'https' rejectUnauthorized: false it '#getDefaultOptions should return an optimist object', -> argv = utils.getDefaultOptions() expect(argv.help).toBeDefined() expect(argv.help()).toContain('Usage:') it '#getLogger should return a logger instance', -> args = projectKey: 'myProjectKey' logDir: tmpDir.name logger = utils.getLogger(args) expect(logger.additionalFields.project_key).toBe('myProjectKey') expect(logger.error).toBeDefined() expect(logger.info).toBeDefined() expect(logger.debug).toBeDefined() expect(logger.warn).toBeDefined() expect(logger.debug).toBeDefined() expect(logger.trace).toBeDefined() it '#ensureCredentials should return credentials with accessToken', (done) -> args = accessToken: '<KEY>' projectKey: 'myProjectKey' utils.ensureCredentials args .then (credentials) -> expect(credentials).toEqual config: project_key: 'myProjectKey' access_token: '<KEY>' done() .catch (e) -> done (e or 'Undefined error') it '#ensureCredentials should return credentials from env variables', (done) -> args = projectKey: 'myProjectKey' process.env.SPHERE_PROJECT_KEY = args.projectKey process.env.SPHERE_CLIENT_ID = 'myProjectId' process.env.SPHERE_CLIENT_SECRET = 'myProjectSecret' utils.ensureCredentials args .then (credentials) -> expect(credentials).toEqual config: project_key: 'myProjectKey' client_id: 'myProjectId' client_secret: 'my<KEY>' done() .catch (e) -> done (e or 'Undefined error')
true
_ = require 'underscore' tmp = require 'tmp' packageJson = require '../package' utils = require '../lib/utils' tmpDir = tmp.dirSync() describe 'Utils', -> it '#getFileName should return a fileName based on arguments', -> fileName = utils.getFileName(false, 'orders') expect(fileName).toBe 'orders.csv' fileName = utils.getFileName(false, 'orders', '1234') expect(fileName).toBe 'orders.csv' fileName = utils.getFileName(true, 'orders', '1234') expect(fileName).toBe 'orders_1234.csv' it '#getClientOptions should return a simple client options object', -> credentials = config: project_key: 'project-key' access_token: 'access-token' args = timeout: 100 res = utils.getClientOptions(credentials, args) expect(res).toEqual config: project_key: 'project-key' access_token: 'access-token' user_agent: "#{packageJson.name} - #{packageJson.version}" timeout: 100 it '#getClientOptions should return a complex client options object', -> credentials = config: project_key: 'project-key' access_token: 'access-token' args = timeout: 100 sphereHost: 'host' sphereProtocol: 'http' sphereAuthHost: '123' sphereAuthProtocol: 'https' res = utils.getClientOptions(credentials, args) expect(res).toEqual config: project_key: 'project-key' access_token: 'access-token' user_agent: "#{packageJson.name} - #{packageJson.version}" host: 'host' timeout: 100 protocol: 'http' oauth_host: '123' oauth_protocol: 'https' rejectUnauthorized: false it '#getDefaultOptions should return an optimist object', -> argv = utils.getDefaultOptions() expect(argv.help).toBeDefined() expect(argv.help()).toContain('Usage:') it '#getLogger should return a logger instance', -> args = projectKey: 'myProjectKey' logDir: tmpDir.name logger = utils.getLogger(args) expect(logger.additionalFields.project_key).toBe('myProjectKey') expect(logger.error).toBeDefined() expect(logger.info).toBeDefined() expect(logger.debug).toBeDefined() expect(logger.warn).toBeDefined() expect(logger.debug).toBeDefined() expect(logger.trace).toBeDefined() it '#ensureCredentials should return credentials with accessToken', (done) -> args = accessToken: 'PI:KEY:<KEY>END_PI' projectKey: 'myProjectKey' utils.ensureCredentials args .then (credentials) -> expect(credentials).toEqual config: project_key: 'myProjectKey' access_token: 'PI:KEY:<KEY>END_PI' done() .catch (e) -> done (e or 'Undefined error') it '#ensureCredentials should return credentials from env variables', (done) -> args = projectKey: 'myProjectKey' process.env.SPHERE_PROJECT_KEY = args.projectKey process.env.SPHERE_CLIENT_ID = 'myProjectId' process.env.SPHERE_CLIENT_SECRET = 'myProjectSecret' utils.ensureCredentials args .then (credentials) -> expect(credentials).toEqual config: project_key: 'myProjectKey' client_id: 'myProjectId' client_secret: 'myPI:KEY:<KEY>END_PI' done() .catch (e) -> done (e or 'Undefined error')