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": "{ cid: 'c2', eid: 'e1', type: 'character', name: 'Link' }\n { cid: 'c3', eid: 'e1', type: 'bbox', shape:",
"end": 741,
"score": 0.9056156277656555,
"start": 737,
"tag": "NAME",
"value": "Link"
},
{
"context": "{ cid: 'c6', eid: 'e2', type: 'character', name: 'Tektike' ... | spec/search/object_store_search_spec.coffee | dcrosby42/metroid-clone | 5 | # Finder = require '../../src/javascript/search/immutable_object_finder'
Immutable = require 'immutable'
ExpectHelpers = require '../helpers/expect_helpers'
expectIs = ExpectHelpers.expectIs
ObjectStore = require '../../src/javascript/search/object_store'
ObjectStoreSearch = require '../../src/javascript/search/object_store_search'
util = require 'util'
chai = require('chai')
expect = chai.expect
assert = chai.assert
imm = Immutable.fromJS
immset = (xs...) -> Immutable.Set(xs)
Set = Immutable.Set
Map = Immutable.Map
List = Immutable.List
jsonFmt = (immobj) -> JSON.stringify(immobj.toJS(),null,4)
zeldaObjects = imm [
{ cid: 'c1', eid: 'e1', type: 'tag', value: 'hero' }
{ cid: 'c2', eid: 'e1', type: 'character', name: 'Link' }
{ cid: 'c3', eid: 'e1', type: 'bbox', shape: [1,2,3,4] }
{ cid: 'c4', eid: 'e1', type: 'inventory', stuff: 'items' }
{ cid: 'c5', eid: 'e2', type: 'tag', value: 'enemy' }
{ cid: 'c6', eid: 'e2', type: 'character', name: 'Tektike' }
{ cid: 'c7', eid: 'e2', type: 'bbox', shape: [3,4,5,6] }
{ cid: 'c8', eid: 'e2', type: 'digger', status: 'burrowing' }
{ cid: 'c9', eid: 'e1', type: 'hat', color: 'green' }
{ cid: 'c10', eid: 'e99', extraneous: 'hat', type: 'other-thing', sha: 'zam' }
]
describe "ObjectStoreSearch", ->
indices = imm([
['eid']
['type']
['eid','type']
])
store = ObjectStore.create('cid', indices)
store = ObjectStore.addObjects(store, zeldaObjects)
describe "convertMatchesToIndexLookups", ->
cases = [
[
"a single-field match that aligns with single-field index"
{ match: { type: 'character' } }
{ lookup: { index: ['type'], keypath: ['character'] } }
]
[
"another single-field match that aligns with single-field index"
{ match: { eid: '123' } }
{ lookup: { index: ['eid'], keypath: ['123'] } }
]
[
"a multi-field match that aligns with multi-field index"
{ match: { eid: '123', type: 'weapon'} }
{ lookup: { index: ['eid','type'], keypath: ['123','weapon'] } }
]
[
"a multi-field match, plus others, that aligns with multi-field index"
{ match: { eid: '123', type: 'weapon', other: 'info' } }
{ match: { other: 'info' }, lookup: { index: ['eid','type'], keypath: ['123','weapon'] } }
]
[
"a match where no fields are indexed"
{ match: { main: 'stuff', other: 'info' } }
{ match: { main: 'stuff', other: 'info' } }
]
]
makeTest = ([desc,input,expected]) ->
->
res = ObjectStoreSearch.convertMatchesToIndexLookups(imm(input), indices)
expectIs res, imm(expected)
it "transforms filter with #{c[0]}", makeTest(c) for c in cases
describe "search", ->
cases = [
[
"simple type-based match on 'tag'"
[ { as: 'tag', match: { type: 'tag' } } ]
[ {tag:'c1'},{tag:'c5'} ]
]
[
"simple type-based match on 'character'"
[ { as: 'character', match: { type: 'character' } } ]
[ { character: 'c2' }, { character: 'c6' } ]
]
[
"indexed lookup on type=character"
[ { as: 'character', lookup: { index: ['type'], keypath:['character']}}]
[ { character: 'c2' }, { character: 'c6' } ]
]
[
"multi-filter match, joined using character.eid placeholder in second match"
[
{ as: 'character', match: { type: 'character' } }
{ as: 'bbox', match: { type: 'bbox', eid: ['character','eid'] } }
]
[ { character: 'c2', bbox: 'c3' }, { character: 'c6', bbox: 'c7' } ]
]
[
"multi-filter indexed lookup, joined with character.eid placeholder in second keypath"
[
{ as: 'character', lookup: { index: ['type'], keypath:['character']}}
{ as: 'bbox', lookup: { index: ['eid','type'], keypath:[['character','eid'],'bbox']}}
]
[ { character: 'c2', bbox: 'c3' }, { character: 'c6', bbox: 'c7' } ]
]
[
"multi-filter indexed lookup AND match, filtering results by name=Link"
[
{ as: 'character', match: { name: 'Link' }, lookup: { index: ['type'], keypath:['character']}}
{ as: 'bbox', lookup: { index: ['eid','type'], keypath:[['character','eid'],'bbox']}}
]
[ { character: 'c2', bbox: 'c3' } ]
]
[
"multi-filter match, 'inner joined' using character.eid placeholder in second match"
[
{ as: 'character', match: { type: 'character' } }
{ as: 'hat', match: { type: 'hat', eid: ['character','eid'] } }
]
[ { character: 'c2', hat: 'c9' } ]
]
[
"multi-filter match, 'outer joined' using character.eid placeholder in second match"
[
{ as: 'character', match: { type: 'character' } }
{ as: 'hat', match: { type: 'hat', eid: ['character','eid'] }, optional: true }
]
[ { character: 'c2', hat: 'c9' }, {character: 'c6', hat: null } ]
]
[
"multi-filter indexed lookup, 'outer joined' using character.eid placeholder in second match"
[
{ as: 'character', lookup: { index:['type'],keypath:['character'] } }
{ as: 'hat', lookup:{index:['eid','type'],keypath:[['character','eid'],'hat']}, optional: true }
]
[ { character: 'c2', hat: 'c9' }, {character: 'c6', hat: null } ]
]
[
"multi-filter indexed lookup, 'outer joined', with further results beyond a missing optional"
[
{ as: 'character', lookup: { index:['type'],keypath:['character'] } }
{ as: 'hat', lookup:{index:['eid','type'],keypath:[['character','eid'],'hat']}, optional: true }
{ as: 'tag', lookup:{index:['eid','type'],keypath:[['character','eid'],'tag']}, optional: true }
]
[ { character: 'c2', hat: 'c9', tag: 'c1' }, {character: 'c6', hat: null, tag: 'c5'} ]
]
]
makeDesc = (c) -> "testing #{c[0]}"
makeTest = ([desc,filters,expected]) ->
->
res = ObjectStoreSearch.search(store, imm(filters))
expectedResults = Set(imm(expected).map (thing) ->
imm(thing).map((v) -> store.get('data').get(v,null)))
expectIs Set(res), expectedResults
it makeDesc(c), makeTest(c) for c in cases
| 157400 | # Finder = require '../../src/javascript/search/immutable_object_finder'
Immutable = require 'immutable'
ExpectHelpers = require '../helpers/expect_helpers'
expectIs = ExpectHelpers.expectIs
ObjectStore = require '../../src/javascript/search/object_store'
ObjectStoreSearch = require '../../src/javascript/search/object_store_search'
util = require 'util'
chai = require('chai')
expect = chai.expect
assert = chai.assert
imm = Immutable.fromJS
immset = (xs...) -> Immutable.Set(xs)
Set = Immutable.Set
Map = Immutable.Map
List = Immutable.List
jsonFmt = (immobj) -> JSON.stringify(immobj.toJS(),null,4)
zeldaObjects = imm [
{ cid: 'c1', eid: 'e1', type: 'tag', value: 'hero' }
{ cid: 'c2', eid: 'e1', type: 'character', name: '<NAME>' }
{ cid: 'c3', eid: 'e1', type: 'bbox', shape: [1,2,3,4] }
{ cid: 'c4', eid: 'e1', type: 'inventory', stuff: 'items' }
{ cid: 'c5', eid: 'e2', type: 'tag', value: 'enemy' }
{ cid: 'c6', eid: 'e2', type: 'character', name: '<NAME>' }
{ cid: 'c7', eid: 'e2', type: 'bbox', shape: [3,4,5,6] }
{ cid: 'c8', eid: 'e2', type: 'digger', status: 'burrowing' }
{ cid: 'c9', eid: 'e1', type: 'hat', color: 'green' }
{ cid: 'c10', eid: 'e99', extraneous: 'hat', type: 'other-thing', sha: 'zam' }
]
describe "ObjectStoreSearch", ->
indices = imm([
['eid']
['type']
['eid','type']
])
store = ObjectStore.create('cid', indices)
store = ObjectStore.addObjects(store, zeldaObjects)
describe "convertMatchesToIndexLookups", ->
cases = [
[
"a single-field match that aligns with single-field index"
{ match: { type: 'character' } }
{ lookup: { index: ['type'], keypath: ['character'] } }
]
[
"another single-field match that aligns with single-field index"
{ match: { eid: '123' } }
{ lookup: { index: ['eid'], keypath: ['123'] } }
]
[
"a multi-field match that aligns with multi-field index"
{ match: { eid: '123', type: 'weapon'} }
{ lookup: { index: ['eid','type'], keypath: ['123','weapon'] } }
]
[
"a multi-field match, plus others, that aligns with multi-field index"
{ match: { eid: '123', type: 'weapon', other: 'info' } }
{ match: { other: 'info' }, lookup: { index: ['eid','type'], keypath: ['123','weapon'] } }
]
[
"a match where no fields are indexed"
{ match: { main: 'stuff', other: 'info' } }
{ match: { main: 'stuff', other: 'info' } }
]
]
makeTest = ([desc,input,expected]) ->
->
res = ObjectStoreSearch.convertMatchesToIndexLookups(imm(input), indices)
expectIs res, imm(expected)
it "transforms filter with #{c[0]}", makeTest(c) for c in cases
describe "search", ->
cases = [
[
"simple type-based match on 'tag'"
[ { as: 'tag', match: { type: 'tag' } } ]
[ {tag:'c1'},{tag:'c5'} ]
]
[
"simple type-based match on 'character'"
[ { as: 'character', match: { type: 'character' } } ]
[ { character: 'c2' }, { character: 'c6' } ]
]
[
"indexed lookup on type=character"
[ { as: 'character', lookup: { index: ['type'], keypath:['character']}}]
[ { character: 'c2' }, { character: 'c6' } ]
]
[
"multi-filter match, joined using character.eid placeholder in second match"
[
{ as: 'character', match: { type: 'character' } }
{ as: 'bbox', match: { type: 'bbox', eid: ['character','eid'] } }
]
[ { character: 'c2', bbox: 'c3' }, { character: 'c6', bbox: 'c7' } ]
]
[
"multi-filter indexed lookup, joined with character.eid placeholder in second keypath"
[
{ as: 'character', lookup: { index: ['type'], keypath:['character']}}
{ as: 'bbox', lookup: { index: ['eid','type'], keypath:[['character','eid'],'bbox']}}
]
[ { character: 'c2', bbox: 'c3' }, { character: 'c6', bbox: 'c7' } ]
]
[
"multi-filter indexed lookup AND match, filtering results by name=Link"
[
{ as: 'character', match: { name: 'Link' }, lookup: { index: ['type'], keypath:['character']}}
{ as: 'bbox', lookup: { index: ['eid','type'], keypath:[['character','eid'],'bbox']}}
]
[ { character: 'c2', bbox: 'c3' } ]
]
[
"multi-filter match, 'inner joined' using character.eid placeholder in second match"
[
{ as: 'character', match: { type: 'character' } }
{ as: 'hat', match: { type: 'hat', eid: ['character','eid'] } }
]
[ { character: 'c2', hat: 'c9' } ]
]
[
"multi-filter match, 'outer joined' using character.eid placeholder in second match"
[
{ as: 'character', match: { type: 'character' } }
{ as: 'hat', match: { type: 'hat', eid: ['character','eid'] }, optional: true }
]
[ { character: 'c2', hat: 'c9' }, {character: 'c6', hat: null } ]
]
[
"multi-filter indexed lookup, 'outer joined' using character.eid placeholder in second match"
[
{ as: 'character', lookup: { index:['type'],keypath:['character'] } }
{ as: 'hat', lookup:{index:['eid','type'],keypath:[['character','eid'],'hat']}, optional: true }
]
[ { character: 'c2', hat: 'c9' }, {character: 'c6', hat: null } ]
]
[
"multi-filter indexed lookup, 'outer joined', with further results beyond a missing optional"
[
{ as: 'character', lookup: { index:['type'],keypath:['character'] } }
{ as: 'hat', lookup:{index:['eid','type'],keypath:[['character','eid'],'hat']}, optional: true }
{ as: 'tag', lookup:{index:['eid','type'],keypath:[['character','eid'],'tag']}, optional: true }
]
[ { character: 'c2', hat: 'c9', tag: 'c1' }, {character: 'c6', hat: null, tag: 'c5'} ]
]
]
makeDesc = (c) -> "testing #{c[0]}"
makeTest = ([desc,filters,expected]) ->
->
res = ObjectStoreSearch.search(store, imm(filters))
expectedResults = Set(imm(expected).map (thing) ->
imm(thing).map((v) -> store.get('data').get(v,null)))
expectIs Set(res), expectedResults
it makeDesc(c), makeTest(c) for c in cases
| true | # Finder = require '../../src/javascript/search/immutable_object_finder'
Immutable = require 'immutable'
ExpectHelpers = require '../helpers/expect_helpers'
expectIs = ExpectHelpers.expectIs
ObjectStore = require '../../src/javascript/search/object_store'
ObjectStoreSearch = require '../../src/javascript/search/object_store_search'
util = require 'util'
chai = require('chai')
expect = chai.expect
assert = chai.assert
imm = Immutable.fromJS
immset = (xs...) -> Immutable.Set(xs)
Set = Immutable.Set
Map = Immutable.Map
List = Immutable.List
jsonFmt = (immobj) -> JSON.stringify(immobj.toJS(),null,4)
zeldaObjects = imm [
{ cid: 'c1', eid: 'e1', type: 'tag', value: 'hero' }
{ cid: 'c2', eid: 'e1', type: 'character', name: 'PI:NAME:<NAME>END_PI' }
{ cid: 'c3', eid: 'e1', type: 'bbox', shape: [1,2,3,4] }
{ cid: 'c4', eid: 'e1', type: 'inventory', stuff: 'items' }
{ cid: 'c5', eid: 'e2', type: 'tag', value: 'enemy' }
{ cid: 'c6', eid: 'e2', type: 'character', name: 'PI:NAME:<NAME>END_PI' }
{ cid: 'c7', eid: 'e2', type: 'bbox', shape: [3,4,5,6] }
{ cid: 'c8', eid: 'e2', type: 'digger', status: 'burrowing' }
{ cid: 'c9', eid: 'e1', type: 'hat', color: 'green' }
{ cid: 'c10', eid: 'e99', extraneous: 'hat', type: 'other-thing', sha: 'zam' }
]
describe "ObjectStoreSearch", ->
indices = imm([
['eid']
['type']
['eid','type']
])
store = ObjectStore.create('cid', indices)
store = ObjectStore.addObjects(store, zeldaObjects)
describe "convertMatchesToIndexLookups", ->
cases = [
[
"a single-field match that aligns with single-field index"
{ match: { type: 'character' } }
{ lookup: { index: ['type'], keypath: ['character'] } }
]
[
"another single-field match that aligns with single-field index"
{ match: { eid: '123' } }
{ lookup: { index: ['eid'], keypath: ['123'] } }
]
[
"a multi-field match that aligns with multi-field index"
{ match: { eid: '123', type: 'weapon'} }
{ lookup: { index: ['eid','type'], keypath: ['123','weapon'] } }
]
[
"a multi-field match, plus others, that aligns with multi-field index"
{ match: { eid: '123', type: 'weapon', other: 'info' } }
{ match: { other: 'info' }, lookup: { index: ['eid','type'], keypath: ['123','weapon'] } }
]
[
"a match where no fields are indexed"
{ match: { main: 'stuff', other: 'info' } }
{ match: { main: 'stuff', other: 'info' } }
]
]
makeTest = ([desc,input,expected]) ->
->
res = ObjectStoreSearch.convertMatchesToIndexLookups(imm(input), indices)
expectIs res, imm(expected)
it "transforms filter with #{c[0]}", makeTest(c) for c in cases
describe "search", ->
cases = [
[
"simple type-based match on 'tag'"
[ { as: 'tag', match: { type: 'tag' } } ]
[ {tag:'c1'},{tag:'c5'} ]
]
[
"simple type-based match on 'character'"
[ { as: 'character', match: { type: 'character' } } ]
[ { character: 'c2' }, { character: 'c6' } ]
]
[
"indexed lookup on type=character"
[ { as: 'character', lookup: { index: ['type'], keypath:['character']}}]
[ { character: 'c2' }, { character: 'c6' } ]
]
[
"multi-filter match, joined using character.eid placeholder in second match"
[
{ as: 'character', match: { type: 'character' } }
{ as: 'bbox', match: { type: 'bbox', eid: ['character','eid'] } }
]
[ { character: 'c2', bbox: 'c3' }, { character: 'c6', bbox: 'c7' } ]
]
[
"multi-filter indexed lookup, joined with character.eid placeholder in second keypath"
[
{ as: 'character', lookup: { index: ['type'], keypath:['character']}}
{ as: 'bbox', lookup: { index: ['eid','type'], keypath:[['character','eid'],'bbox']}}
]
[ { character: 'c2', bbox: 'c3' }, { character: 'c6', bbox: 'c7' } ]
]
[
"multi-filter indexed lookup AND match, filtering results by name=Link"
[
{ as: 'character', match: { name: 'Link' }, lookup: { index: ['type'], keypath:['character']}}
{ as: 'bbox', lookup: { index: ['eid','type'], keypath:[['character','eid'],'bbox']}}
]
[ { character: 'c2', bbox: 'c3' } ]
]
[
"multi-filter match, 'inner joined' using character.eid placeholder in second match"
[
{ as: 'character', match: { type: 'character' } }
{ as: 'hat', match: { type: 'hat', eid: ['character','eid'] } }
]
[ { character: 'c2', hat: 'c9' } ]
]
[
"multi-filter match, 'outer joined' using character.eid placeholder in second match"
[
{ as: 'character', match: { type: 'character' } }
{ as: 'hat', match: { type: 'hat', eid: ['character','eid'] }, optional: true }
]
[ { character: 'c2', hat: 'c9' }, {character: 'c6', hat: null } ]
]
[
"multi-filter indexed lookup, 'outer joined' using character.eid placeholder in second match"
[
{ as: 'character', lookup: { index:['type'],keypath:['character'] } }
{ as: 'hat', lookup:{index:['eid','type'],keypath:[['character','eid'],'hat']}, optional: true }
]
[ { character: 'c2', hat: 'c9' }, {character: 'c6', hat: null } ]
]
[
"multi-filter indexed lookup, 'outer joined', with further results beyond a missing optional"
[
{ as: 'character', lookup: { index:['type'],keypath:['character'] } }
{ as: 'hat', lookup:{index:['eid','type'],keypath:[['character','eid'],'hat']}, optional: true }
{ as: 'tag', lookup:{index:['eid','type'],keypath:[['character','eid'],'tag']}, optional: true }
]
[ { character: 'c2', hat: 'c9', tag: 'c1' }, {character: 'c6', hat: null, tag: 'c5'} ]
]
]
makeDesc = (c) -> "testing #{c[0]}"
makeTest = ([desc,filters,expected]) ->
->
res = ObjectStoreSearch.search(store, imm(filters))
expectedResults = Set(imm(expected).map (thing) ->
imm(thing).map((v) -> store.get('data').get(v,null)))
expectIs Set(res), expectedResults
it makeDesc(c), makeTest(c) for c in cases
|
[
{
"context": " =\n id: '54276766fd4f50996aeca2b8'\n author_id: '4d8cd73191a5c50ce210002a'\n author:\n id: \"506999f123c3980002000342\"\n ",
"end": 828,
"score": 0.9533002972602844,
"start": 804,
"tag": "PASSWORD",
"value": "4d8cd73191a5c50ce210002a"
},
{
"context": "id: '4d8c... | src/mobile/test/helpers/fixtures.coffee | kanaabe/force | 1 | moment = require 'moment'
@vertical =
id: '55356a9deca560a0137aa4b7'
title: 'Vennice Biennalez'
description: 'The coolest biennale'
slug: 'vennice-biennale'
partner_logo_url: 'http://gemini.herokuapp.com/123/miaart-banner.jpg'
thumbnail_url: 'http://gemini.herokuapp.com/123/miaart-banner.jpg'
featured_links: [{ title: 'foo', thumbnail_url: 'bar.jpg', url: 'foo.com' }]
@section =
id: '55356a9deca560a0137aa4b7'
title: 'Vennice Biennalez'
description: 'The coolest biennale'
slug: 'vennice-biennale'
partner_logo_url: 'http://gemini.herokuapp.com/123/miaart-banner.jpg'
thumbnail_url: 'http://gemini.herokuapp.com/123/miaart-banner.jpg'
featured_links: [{ title: 'foo', thumbnail_url: 'bar.jpg', url: 'foo.com' }]
@article =
id: '54276766fd4f50996aeca2b8'
author_id: '4d8cd73191a5c50ce210002a'
author:
id: "506999f123c3980002000342"
name: "Elena Soboleva"
thumbnail_title: 'Top Ten Booths at miart 2014',
thumbnail_teaser: 'Look here! Before the lines start forming...',
thumbnail_image: 'http://kitten.com',
tags: ['Fair Coverage', 'Magazine']
title: 'Top Ten Booths',
lead_paragraph: '<p>Just before the lines start forming</p>...',
published: true,
published_at: moment().format(),
updated_at: moment().format(),
is_super_article: false
super_article:
related_articles: []
sections: [
{
type: 'slideshow',
items: [
{ type: 'artwork', id: '54276766fd4f50996aeca2b8' }
{ type: 'image', url: '', caption: '' }
{ type: 'video', url: '', caption: '' }
]
}
{
type: 'text',
body: '<p><h1>10. Lisson Gallery</h1></p><p>Mia Bergeron merges the <em>personal</em> and <em>universal</em>...',
}
{
type: 'image_collection',
ids: ['5321b73dc9dc2458c4000196', '5321b71c275b24bcaa0001a5'],
layout: 'overflow_fillwidth'
images: [
{
type: 'image',
url: 'http://gemini.herokuapp.com/123/miaart-banner.jpg'
},
{
type: 'artwork'
id: '570faa047622dd65850017e2'
slug: "govinda-sah-azad-in-between-1",
date: "2015",
title: "In Between",
image: "https://d32dm0rphc51dk.cloudfront.net/zjr8iMxGUQAVU83wi_oXaQ/larger.jpg",
partner: {
name: "October Gallery",
slug: "october-gallery"
}
artists: [
{
name: "Govinda Sah 'Azad'",
slug: "govinda-sah-azad"
},
{
name: "Andy Warhol",
slug: "andy-warhol"
}
]
}
]
}
{
type: 'text',
body: 'Check out this video art:',
}
{
type: 'video',
url: 'http://youtu.be/yYjLrJRuMnY',
caption: 'Doug and Claire get sucked into a marathon of Battlestar Galactica from Season 2 of Portlandia on IFC.',
cover_image_url: 'https://artsy.net/video_cover_image.jpg'
}
]
featured_artist_ids: ['5086df098523e60002000012']
featured_artwork_ids: ['5321b71c275b24bcaa0001a5']
gravity_id: '502a6debe8b6470002000004'
contributing_authors: []
section_ids: []
| 96940 | moment = require 'moment'
@vertical =
id: '55356a9deca560a0137aa4b7'
title: 'Vennice Biennalez'
description: 'The coolest biennale'
slug: 'vennice-biennale'
partner_logo_url: 'http://gemini.herokuapp.com/123/miaart-banner.jpg'
thumbnail_url: 'http://gemini.herokuapp.com/123/miaart-banner.jpg'
featured_links: [{ title: 'foo', thumbnail_url: 'bar.jpg', url: 'foo.com' }]
@section =
id: '55356a9deca560a0137aa4b7'
title: 'Vennice Biennalez'
description: 'The coolest biennale'
slug: 'vennice-biennale'
partner_logo_url: 'http://gemini.herokuapp.com/123/miaart-banner.jpg'
thumbnail_url: 'http://gemini.herokuapp.com/123/miaart-banner.jpg'
featured_links: [{ title: 'foo', thumbnail_url: 'bar.jpg', url: 'foo.com' }]
@article =
id: '54276766fd4f50996aeca2b8'
author_id: '<PASSWORD>'
author:
id: "5<PASSWORD>"
name: "<NAME>"
thumbnail_title: 'Top Ten Booths at miart 2014',
thumbnail_teaser: 'Look here! Before the lines start forming...',
thumbnail_image: 'http://kitten.com',
tags: ['Fair Coverage', 'Magazine']
title: 'Top Ten Booths',
lead_paragraph: '<p>Just before the lines start forming</p>...',
published: true,
published_at: moment().format(),
updated_at: moment().format(),
is_super_article: false
super_article:
related_articles: []
sections: [
{
type: 'slideshow',
items: [
{ type: 'artwork', id: '54276766fd4f50996aeca2b8' }
{ type: 'image', url: '', caption: '' }
{ type: 'video', url: '', caption: '' }
]
}
{
type: 'text',
body: '<p><h1>10. Lisson Gallery</h1></p><p><NAME> merges the <em>personal</em> and <em>universal</em>...',
}
{
type: 'image_collection',
ids: ['5321b73dc9dc2458c4000196', '5321b71c275b24bcaa0001a5'],
layout: 'overflow_fillwidth'
images: [
{
type: 'image',
url: 'http://gemini.herokuapp.com/123/miaart-banner.jpg'
},
{
type: 'artwork'
id: '570faa047622dd65850017e2'
slug: "govinda-sah-azad-in-between-1",
date: "2015",
title: "In Between",
image: "https://d32dm0rphc51dk.cloudfront.net/zjr8iMxGUQAVU83wi_oXaQ/larger.jpg",
partner: {
name: "October Gallery",
slug: "october-gallery"
}
artists: [
{
name: "<NAME> '<NAME>'",
slug: "govinda-sah-azad"
},
{
name: "<NAME>",
slug: "andy-warhol"
}
]
}
]
}
{
type: 'text',
body: 'Check out this video art:',
}
{
type: 'video',
url: 'http://youtu.be/yYjLrJRuMnY',
caption: '<NAME> and <NAME> get sucked into a marathon of Battlestar Galactica from Season 2 of Portlandia on IFC.',
cover_image_url: 'https://artsy.net/video_cover_image.jpg'
}
]
featured_artist_ids: ['5086df098523e60002000012']
featured_artwork_ids: ['5321b71c275b24bcaa0001a5']
gravity_id: '502a6debe8b6470002000004'
contributing_authors: []
section_ids: []
| true | moment = require 'moment'
@vertical =
id: '55356a9deca560a0137aa4b7'
title: 'Vennice Biennalez'
description: 'The coolest biennale'
slug: 'vennice-biennale'
partner_logo_url: 'http://gemini.herokuapp.com/123/miaart-banner.jpg'
thumbnail_url: 'http://gemini.herokuapp.com/123/miaart-banner.jpg'
featured_links: [{ title: 'foo', thumbnail_url: 'bar.jpg', url: 'foo.com' }]
@section =
id: '55356a9deca560a0137aa4b7'
title: 'Vennice Biennalez'
description: 'The coolest biennale'
slug: 'vennice-biennale'
partner_logo_url: 'http://gemini.herokuapp.com/123/miaart-banner.jpg'
thumbnail_url: 'http://gemini.herokuapp.com/123/miaart-banner.jpg'
featured_links: [{ title: 'foo', thumbnail_url: 'bar.jpg', url: 'foo.com' }]
@article =
id: '54276766fd4f50996aeca2b8'
author_id: 'PI:PASSWORD:<PASSWORD>END_PI'
author:
id: "5PI:PASSWORD:<PASSWORD>END_PI"
name: "PI:NAME:<NAME>END_PI"
thumbnail_title: 'Top Ten Booths at miart 2014',
thumbnail_teaser: 'Look here! Before the lines start forming...',
thumbnail_image: 'http://kitten.com',
tags: ['Fair Coverage', 'Magazine']
title: 'Top Ten Booths',
lead_paragraph: '<p>Just before the lines start forming</p>...',
published: true,
published_at: moment().format(),
updated_at: moment().format(),
is_super_article: false
super_article:
related_articles: []
sections: [
{
type: 'slideshow',
items: [
{ type: 'artwork', id: '54276766fd4f50996aeca2b8' }
{ type: 'image', url: '', caption: '' }
{ type: 'video', url: '', caption: '' }
]
}
{
type: 'text',
body: '<p><h1>10. Lisson Gallery</h1></p><p>PI:NAME:<NAME>END_PI merges the <em>personal</em> and <em>universal</em>...',
}
{
type: 'image_collection',
ids: ['5321b73dc9dc2458c4000196', '5321b71c275b24bcaa0001a5'],
layout: 'overflow_fillwidth'
images: [
{
type: 'image',
url: 'http://gemini.herokuapp.com/123/miaart-banner.jpg'
},
{
type: 'artwork'
id: '570faa047622dd65850017e2'
slug: "govinda-sah-azad-in-between-1",
date: "2015",
title: "In Between",
image: "https://d32dm0rphc51dk.cloudfront.net/zjr8iMxGUQAVU83wi_oXaQ/larger.jpg",
partner: {
name: "October Gallery",
slug: "october-gallery"
}
artists: [
{
name: "PI:NAME:<NAME>END_PI 'PI:NAME:<NAME>END_PI'",
slug: "govinda-sah-azad"
},
{
name: "PI:NAME:<NAME>END_PI",
slug: "andy-warhol"
}
]
}
]
}
{
type: 'text',
body: 'Check out this video art:',
}
{
type: 'video',
url: 'http://youtu.be/yYjLrJRuMnY',
caption: 'PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI get sucked into a marathon of Battlestar Galactica from Season 2 of Portlandia on IFC.',
cover_image_url: 'https://artsy.net/video_cover_image.jpg'
}
]
featured_artist_ids: ['5086df098523e60002000012']
featured_artwork_ids: ['5321b71c275b24bcaa0001a5']
gravity_id: '502a6debe8b6470002000004'
contributing_authors: []
section_ids: []
|
[
{
"context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission",
"end": 18,
"score": 0.9991887211799622,
"start": 12,
"tag": "NAME",
"value": "Joyent"
}
] | test/simple/test-net-server-close.coffee | lxe/io.coffee | 0 | # Copyright Joyent, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
common = require("../common")
assert = require("assert")
net = require("net")
events = []
sockets = []
process.on "exit", ->
assert.equal server.connections, 0
assert.equal events.length, 3
# Expect to see one server event and two client events. The order of the
# events is undefined because they arrive on the same event loop tick.
assert.equal events.join(" ").match(/server/g).length, 1
assert.equal events.join(" ").match(/client/g).length, 2
return
server = net.createServer((c) ->
c.on "close", ->
events.push "client"
return
sockets.push c
if sockets.length is 2
server.close()
sockets.forEach (c) ->
c.destroy()
return
return
)
server.on "close", ->
events.push "server"
return
server.listen common.PORT, ->
net.createConnection common.PORT
net.createConnection common.PORT
return
| 214097 | # Copyright <NAME>, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
common = require("../common")
assert = require("assert")
net = require("net")
events = []
sockets = []
process.on "exit", ->
assert.equal server.connections, 0
assert.equal events.length, 3
# Expect to see one server event and two client events. The order of the
# events is undefined because they arrive on the same event loop tick.
assert.equal events.join(" ").match(/server/g).length, 1
assert.equal events.join(" ").match(/client/g).length, 2
return
server = net.createServer((c) ->
c.on "close", ->
events.push "client"
return
sockets.push c
if sockets.length is 2
server.close()
sockets.forEach (c) ->
c.destroy()
return
return
)
server.on "close", ->
events.push "server"
return
server.listen common.PORT, ->
net.createConnection common.PORT
net.createConnection common.PORT
return
| true | # Copyright PI:NAME:<NAME>END_PI, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
common = require("../common")
assert = require("assert")
net = require("net")
events = []
sockets = []
process.on "exit", ->
assert.equal server.connections, 0
assert.equal events.length, 3
# Expect to see one server event and two client events. The order of the
# events is undefined because they arrive on the same event loop tick.
assert.equal events.join(" ").match(/server/g).length, 1
assert.equal events.join(" ").match(/client/g).length, 2
return
server = net.createServer((c) ->
c.on "close", ->
events.push "client"
return
sockets.push c
if sockets.length is 2
server.close()
sockets.forEach (c) ->
c.destroy()
return
return
)
server.on "close", ->
events.push "server"
return
server.listen common.PORT, ->
net.createConnection common.PORT
net.createConnection common.PORT
return
|
[
{
"context": "m\"\n\t\t\tclsiCookie:\n\t\t\t\tttl:Math.random()\n\t\t\t\tkey: \"coooookie\"\n\t\t@requires = \n\t\t\t\"../../infrastructure/RedisWra",
"end": 778,
"score": 0.9990467429161072,
"start": 769,
"tag": "KEY",
"value": "coooookie"
}
] | test/unit/coffee/Compile/ClsiCookieManagerTests.coffee | davidmehren/web-sharelatex | 0 | sinon = require('sinon')
chai = require('chai')
assert = chai.assert
should = chai.should()
expect = chai.expect
modulePath = "../../../../app/js/Features/Compile/ClsiCookieManager.js"
SandboxedModule = require('sandboxed-module')
realRequst = require("request")
describe "ClsiCookieManager", ->
beforeEach ->
self = @
@redisMulti =
set:sinon.stub()
get:sinon.stub()
expire:sinon.stub()
exec:sinon.stub()
@redis =
auth:->
get:sinon.stub()
multi: -> return self.redisMulti
@project_id = "123423431321"
@request =
get: sinon.stub()
cookie:realRequst.cookie
jar: realRequst.jar
@settings =
redis:
web:"redis.something"
apis:
clsi:
url: "http://clsi.example.com"
clsiCookie:
ttl:Math.random()
key: "coooookie"
@requires =
"../../infrastructure/RedisWrapper": @RedisWrapper =
client: => @redis
"settings-sharelatex": @settings
"request": @request
"logger-sharelatex": @logger = { log: sinon.stub(), error: sinon.stub(), warn: sinon.stub() }
@ClsiCookieManager = SandboxedModule.require modulePath, requires:@requires
describe "getServerId", ->
it "should call get for the key", (done)->
@redis.get.callsArgWith(1, null, "clsi-7")
@ClsiCookieManager._getServerId @project_id, (err, serverId)=>
@redis.get.calledWith("clsiserver:#{@project_id}").should.equal true
serverId.should.equal "clsi-7"
done()
it "should _populateServerIdViaRequest if no key is found", (done)->
@ClsiCookieManager._populateServerIdViaRequest = sinon.stub().callsArgWith(1)
@redis.get.callsArgWith(1, null)
@ClsiCookieManager._getServerId @project_id, (err, serverId)=>
@ClsiCookieManager._populateServerIdViaRequest.calledWith(@project_id).should.equal true
done()
it "should _populateServerIdViaRequest if no key is blank", (done)->
@ClsiCookieManager._populateServerIdViaRequest = sinon.stub().callsArgWith(1)
@redis.get.callsArgWith(1, null, "")
@ClsiCookieManager._getServerId @project_id, (err, serverId)=>
@ClsiCookieManager._populateServerIdViaRequest.calledWith(@project_id).should.equal true
done()
describe "_populateServerIdViaRequest", ->
beforeEach ->
@response = "some data"
@request.get.callsArgWith(1, null, @response)
@ClsiCookieManager.setServerId = sinon.stub().callsArgWith(2, null, "clsi-9")
it "should make a request to the clsi", (done)->
@ClsiCookieManager._populateServerIdViaRequest @project_id, (err, serverId)=>
args = @ClsiCookieManager.setServerId.args[0]
args[0].should.equal @project_id
args[1].should.deep.equal @response
done()
it "should return the server id", (done)->
@ClsiCookieManager._populateServerIdViaRequest @project_id, (err, serverId)=>
serverId.should.equal "clsi-9"
done()
describe "setServerId", ->
beforeEach ->
@response = "dsadsakj"
@ClsiCookieManager._parseServerIdFromResponse = sinon.stub().returns("clsi-8")
@redisMulti.exec.callsArgWith(0)
it "should set the server id with a ttl", (done)->
@ClsiCookieManager.setServerId @project_id, @response, (err)=>
@redisMulti.set.calledWith("clsiserver:#{@project_id}", "clsi-8").should.equal true
@redisMulti.expire.calledWith("clsiserver:#{@project_id}", @settings.clsiCookie.ttl).should.equal true
done()
it "should return the server id", (done)->
@ClsiCookieManager.setServerId @project_id, @response, (err, serverId)=>
serverId.should.equal "clsi-8"
done()
it "should not set the server id if clsiCookies are not enabled", (done)->
delete @settings.clsiCookie.key
@ClsiCookieManager = SandboxedModule.require modulePath, requires:@requires
@ClsiCookieManager.setServerId @project_id, @response, (err, serverId)=>
@redisMulti.exec.called.should.equal false
done()
it "should not set the server id there is no server id in the response", (done)->
@ClsiCookieManager._parseServerIdFromResponse = sinon.stub().returns(null)
@ClsiCookieManager.setServerId @project_id, @response, (err, serverId)=>
@redisMulti.exec.called.should.equal false
done()
it "should also set in the secondary if secondary redis is enabled", (done) ->
@redisSecondaryMulti =
set:sinon.stub()
expire:sinon.stub()
exec:sinon.stub()
@redis_secondary =
multi: => @redisSecondaryMulti
@settings.redis.clsi_cookie_secondary = {}
@RedisWrapper.client = sinon.stub()
@RedisWrapper.client.withArgs("clsi_cookie").returns(@redis)
@RedisWrapper.client.withArgs("clsi_cookie_secondary").returns(@redis_secondary)
@ClsiCookieManager = SandboxedModule.require modulePath, requires:@requires
@ClsiCookieManager._parseServerIdFromResponse = sinon.stub().returns("clsi-8")
@ClsiCookieManager.setServerId @project_id, @response, (err, serverId)=>
@redisSecondaryMulti.set.calledWith("clsiserver:#{@project_id}", "clsi-8").should.equal true
@redisSecondaryMulti.expire.calledWith("clsiserver:#{@project_id}", @settings.clsiCookie.ttl).should.equal true
done()
describe "getCookieJar", ->
beforeEach ->
@ClsiCookieManager._getServerId = sinon.stub().callsArgWith(1, null, "clsi-11")
it "should return a jar with the cookie set populated from redis", (done)->
@ClsiCookieManager.getCookieJar @project_id, (err, jar)=>
jar._jar.store.idx["clsi.example.com"]["/"][@settings.clsiCookie.key].key.should.equal
jar._jar.store.idx["clsi.example.com"]["/"][@settings.clsiCookie.key].value.should.equal "clsi-11"
done()
it "should return empty cookie jar if clsiCookies are not enabled", (done)->
delete @settings.clsiCookie.key
@ClsiCookieManager = SandboxedModule.require modulePath, requires:@requires
@ClsiCookieManager.getCookieJar @project_id, (err, jar)->
assert.deepEqual jar, realRequst.jar()
done()
| 145598 | sinon = require('sinon')
chai = require('chai')
assert = chai.assert
should = chai.should()
expect = chai.expect
modulePath = "../../../../app/js/Features/Compile/ClsiCookieManager.js"
SandboxedModule = require('sandboxed-module')
realRequst = require("request")
describe "ClsiCookieManager", ->
beforeEach ->
self = @
@redisMulti =
set:sinon.stub()
get:sinon.stub()
expire:sinon.stub()
exec:sinon.stub()
@redis =
auth:->
get:sinon.stub()
multi: -> return self.redisMulti
@project_id = "123423431321"
@request =
get: sinon.stub()
cookie:realRequst.cookie
jar: realRequst.jar
@settings =
redis:
web:"redis.something"
apis:
clsi:
url: "http://clsi.example.com"
clsiCookie:
ttl:Math.random()
key: "<KEY>"
@requires =
"../../infrastructure/RedisWrapper": @RedisWrapper =
client: => @redis
"settings-sharelatex": @settings
"request": @request
"logger-sharelatex": @logger = { log: sinon.stub(), error: sinon.stub(), warn: sinon.stub() }
@ClsiCookieManager = SandboxedModule.require modulePath, requires:@requires
describe "getServerId", ->
it "should call get for the key", (done)->
@redis.get.callsArgWith(1, null, "clsi-7")
@ClsiCookieManager._getServerId @project_id, (err, serverId)=>
@redis.get.calledWith("clsiserver:#{@project_id}").should.equal true
serverId.should.equal "clsi-7"
done()
it "should _populateServerIdViaRequest if no key is found", (done)->
@ClsiCookieManager._populateServerIdViaRequest = sinon.stub().callsArgWith(1)
@redis.get.callsArgWith(1, null)
@ClsiCookieManager._getServerId @project_id, (err, serverId)=>
@ClsiCookieManager._populateServerIdViaRequest.calledWith(@project_id).should.equal true
done()
it "should _populateServerIdViaRequest if no key is blank", (done)->
@ClsiCookieManager._populateServerIdViaRequest = sinon.stub().callsArgWith(1)
@redis.get.callsArgWith(1, null, "")
@ClsiCookieManager._getServerId @project_id, (err, serverId)=>
@ClsiCookieManager._populateServerIdViaRequest.calledWith(@project_id).should.equal true
done()
describe "_populateServerIdViaRequest", ->
beforeEach ->
@response = "some data"
@request.get.callsArgWith(1, null, @response)
@ClsiCookieManager.setServerId = sinon.stub().callsArgWith(2, null, "clsi-9")
it "should make a request to the clsi", (done)->
@ClsiCookieManager._populateServerIdViaRequest @project_id, (err, serverId)=>
args = @ClsiCookieManager.setServerId.args[0]
args[0].should.equal @project_id
args[1].should.deep.equal @response
done()
it "should return the server id", (done)->
@ClsiCookieManager._populateServerIdViaRequest @project_id, (err, serverId)=>
serverId.should.equal "clsi-9"
done()
describe "setServerId", ->
beforeEach ->
@response = "dsadsakj"
@ClsiCookieManager._parseServerIdFromResponse = sinon.stub().returns("clsi-8")
@redisMulti.exec.callsArgWith(0)
it "should set the server id with a ttl", (done)->
@ClsiCookieManager.setServerId @project_id, @response, (err)=>
@redisMulti.set.calledWith("clsiserver:#{@project_id}", "clsi-8").should.equal true
@redisMulti.expire.calledWith("clsiserver:#{@project_id}", @settings.clsiCookie.ttl).should.equal true
done()
it "should return the server id", (done)->
@ClsiCookieManager.setServerId @project_id, @response, (err, serverId)=>
serverId.should.equal "clsi-8"
done()
it "should not set the server id if clsiCookies are not enabled", (done)->
delete @settings.clsiCookie.key
@ClsiCookieManager = SandboxedModule.require modulePath, requires:@requires
@ClsiCookieManager.setServerId @project_id, @response, (err, serverId)=>
@redisMulti.exec.called.should.equal false
done()
it "should not set the server id there is no server id in the response", (done)->
@ClsiCookieManager._parseServerIdFromResponse = sinon.stub().returns(null)
@ClsiCookieManager.setServerId @project_id, @response, (err, serverId)=>
@redisMulti.exec.called.should.equal false
done()
it "should also set in the secondary if secondary redis is enabled", (done) ->
@redisSecondaryMulti =
set:sinon.stub()
expire:sinon.stub()
exec:sinon.stub()
@redis_secondary =
multi: => @redisSecondaryMulti
@settings.redis.clsi_cookie_secondary = {}
@RedisWrapper.client = sinon.stub()
@RedisWrapper.client.withArgs("clsi_cookie").returns(@redis)
@RedisWrapper.client.withArgs("clsi_cookie_secondary").returns(@redis_secondary)
@ClsiCookieManager = SandboxedModule.require modulePath, requires:@requires
@ClsiCookieManager._parseServerIdFromResponse = sinon.stub().returns("clsi-8")
@ClsiCookieManager.setServerId @project_id, @response, (err, serverId)=>
@redisSecondaryMulti.set.calledWith("clsiserver:#{@project_id}", "clsi-8").should.equal true
@redisSecondaryMulti.expire.calledWith("clsiserver:#{@project_id}", @settings.clsiCookie.ttl).should.equal true
done()
describe "getCookieJar", ->
beforeEach ->
@ClsiCookieManager._getServerId = sinon.stub().callsArgWith(1, null, "clsi-11")
it "should return a jar with the cookie set populated from redis", (done)->
@ClsiCookieManager.getCookieJar @project_id, (err, jar)=>
jar._jar.store.idx["clsi.example.com"]["/"][@settings.clsiCookie.key].key.should.equal
jar._jar.store.idx["clsi.example.com"]["/"][@settings.clsiCookie.key].value.should.equal "clsi-11"
done()
it "should return empty cookie jar if clsiCookies are not enabled", (done)->
delete @settings.clsiCookie.key
@ClsiCookieManager = SandboxedModule.require modulePath, requires:@requires
@ClsiCookieManager.getCookieJar @project_id, (err, jar)->
assert.deepEqual jar, realRequst.jar()
done()
| true | sinon = require('sinon')
chai = require('chai')
assert = chai.assert
should = chai.should()
expect = chai.expect
modulePath = "../../../../app/js/Features/Compile/ClsiCookieManager.js"
SandboxedModule = require('sandboxed-module')
realRequst = require("request")
describe "ClsiCookieManager", ->
beforeEach ->
self = @
@redisMulti =
set:sinon.stub()
get:sinon.stub()
expire:sinon.stub()
exec:sinon.stub()
@redis =
auth:->
get:sinon.stub()
multi: -> return self.redisMulti
@project_id = "123423431321"
@request =
get: sinon.stub()
cookie:realRequst.cookie
jar: realRequst.jar
@settings =
redis:
web:"redis.something"
apis:
clsi:
url: "http://clsi.example.com"
clsiCookie:
ttl:Math.random()
key: "PI:KEY:<KEY>END_PI"
@requires =
"../../infrastructure/RedisWrapper": @RedisWrapper =
client: => @redis
"settings-sharelatex": @settings
"request": @request
"logger-sharelatex": @logger = { log: sinon.stub(), error: sinon.stub(), warn: sinon.stub() }
@ClsiCookieManager = SandboxedModule.require modulePath, requires:@requires
describe "getServerId", ->
it "should call get for the key", (done)->
@redis.get.callsArgWith(1, null, "clsi-7")
@ClsiCookieManager._getServerId @project_id, (err, serverId)=>
@redis.get.calledWith("clsiserver:#{@project_id}").should.equal true
serverId.should.equal "clsi-7"
done()
it "should _populateServerIdViaRequest if no key is found", (done)->
@ClsiCookieManager._populateServerIdViaRequest = sinon.stub().callsArgWith(1)
@redis.get.callsArgWith(1, null)
@ClsiCookieManager._getServerId @project_id, (err, serverId)=>
@ClsiCookieManager._populateServerIdViaRequest.calledWith(@project_id).should.equal true
done()
it "should _populateServerIdViaRequest if no key is blank", (done)->
@ClsiCookieManager._populateServerIdViaRequest = sinon.stub().callsArgWith(1)
@redis.get.callsArgWith(1, null, "")
@ClsiCookieManager._getServerId @project_id, (err, serverId)=>
@ClsiCookieManager._populateServerIdViaRequest.calledWith(@project_id).should.equal true
done()
describe "_populateServerIdViaRequest", ->
beforeEach ->
@response = "some data"
@request.get.callsArgWith(1, null, @response)
@ClsiCookieManager.setServerId = sinon.stub().callsArgWith(2, null, "clsi-9")
it "should make a request to the clsi", (done)->
@ClsiCookieManager._populateServerIdViaRequest @project_id, (err, serverId)=>
args = @ClsiCookieManager.setServerId.args[0]
args[0].should.equal @project_id
args[1].should.deep.equal @response
done()
it "should return the server id", (done)->
@ClsiCookieManager._populateServerIdViaRequest @project_id, (err, serverId)=>
serverId.should.equal "clsi-9"
done()
describe "setServerId", ->
beforeEach ->
@response = "dsadsakj"
@ClsiCookieManager._parseServerIdFromResponse = sinon.stub().returns("clsi-8")
@redisMulti.exec.callsArgWith(0)
it "should set the server id with a ttl", (done)->
@ClsiCookieManager.setServerId @project_id, @response, (err)=>
@redisMulti.set.calledWith("clsiserver:#{@project_id}", "clsi-8").should.equal true
@redisMulti.expire.calledWith("clsiserver:#{@project_id}", @settings.clsiCookie.ttl).should.equal true
done()
it "should return the server id", (done)->
@ClsiCookieManager.setServerId @project_id, @response, (err, serverId)=>
serverId.should.equal "clsi-8"
done()
it "should not set the server id if clsiCookies are not enabled", (done)->
delete @settings.clsiCookie.key
@ClsiCookieManager = SandboxedModule.require modulePath, requires:@requires
@ClsiCookieManager.setServerId @project_id, @response, (err, serverId)=>
@redisMulti.exec.called.should.equal false
done()
it "should not set the server id there is no server id in the response", (done)->
@ClsiCookieManager._parseServerIdFromResponse = sinon.stub().returns(null)
@ClsiCookieManager.setServerId @project_id, @response, (err, serverId)=>
@redisMulti.exec.called.should.equal false
done()
it "should also set in the secondary if secondary redis is enabled", (done) ->
@redisSecondaryMulti =
set:sinon.stub()
expire:sinon.stub()
exec:sinon.stub()
@redis_secondary =
multi: => @redisSecondaryMulti
@settings.redis.clsi_cookie_secondary = {}
@RedisWrapper.client = sinon.stub()
@RedisWrapper.client.withArgs("clsi_cookie").returns(@redis)
@RedisWrapper.client.withArgs("clsi_cookie_secondary").returns(@redis_secondary)
@ClsiCookieManager = SandboxedModule.require modulePath, requires:@requires
@ClsiCookieManager._parseServerIdFromResponse = sinon.stub().returns("clsi-8")
@ClsiCookieManager.setServerId @project_id, @response, (err, serverId)=>
@redisSecondaryMulti.set.calledWith("clsiserver:#{@project_id}", "clsi-8").should.equal true
@redisSecondaryMulti.expire.calledWith("clsiserver:#{@project_id}", @settings.clsiCookie.ttl).should.equal true
done()
describe "getCookieJar", ->
beforeEach ->
@ClsiCookieManager._getServerId = sinon.stub().callsArgWith(1, null, "clsi-11")
it "should return a jar with the cookie set populated from redis", (done)->
@ClsiCookieManager.getCookieJar @project_id, (err, jar)=>
jar._jar.store.idx["clsi.example.com"]["/"][@settings.clsiCookie.key].key.should.equal
jar._jar.store.idx["clsi.example.com"]["/"][@settings.clsiCookie.key].value.should.equal "clsi-11"
done()
it "should return empty cookie jar if clsiCookies are not enabled", (done)->
delete @settings.clsiCookie.key
@ClsiCookieManager = SandboxedModule.require modulePath, requires:@requires
@ClsiCookieManager.getCookieJar @project_id, (err, jar)->
assert.deepEqual jar, realRequst.jar()
done()
|
[
{
"context": "n array of objects\npeopleArray = [\n {\n name: \"Paul\"\n age: 43\n },\n {\n name: \"Sue\"\n age: 39",
"end": 1602,
"score": 0.9995990991592407,
"start": 1598,
"tag": "NAME",
"value": "Paul"
},
{
"context": "\n name: \"Paul\"\n age: 43\n },\n {\n... | banas-coffeescript/part-two.coffee | trevorfenner/programming-paradigms-example-code | 2 | # ---------- ARRAYS ----------
# Arrays can contain multiple data types
randArray = ["word", false, 1234, 1.234]
csOutput.insertAdjacentHTML('beforeend', "Index 2 : #{randArray[2]}<br>")
# Get the last 2 indexes
csOutput.insertAdjacentHTML('beforeend', "Last 2 : #{randArray[2..3]}<br>")
# Defines an array with a range from 1 to 10
oneTo10 = [1..10]
# You can go backwards as well
tenTo1 = [10..1]
# Combine Arrays
combinedArray = oneTo10.concat tenTo1
# Push one tenTo1 onto the end of oneTo10
# ... is called a Splat and you use it to indicate that you want to
# "soak up" a list of arguments, or all the values in the array
oneTo10.push tenTo1...
# Use a for loop to cycle through the array
for x in oneTo10
csOutput.insertAdjacentHTML('beforeend', "#{x}<br>")
# Convert an array into a String
csOutput.insertAdjacentHTML('beforeend', "#{oneTo10.toString()}<br>")
# Filter out all odds by saving elements that return true for the condition
evensOnly = oneTo10.filter (x) -> x % 2 == 0
csOutput.insertAdjacentHTML('beforeend', "#{evensOnly.toString()}<br>")
# Get the maximum value in the array
csOutput.insertAdjacentHTML('beforeend', "Max : #{Math.max oneTo10...}<br>")
# Get the minimum value in the array
csOutput.insertAdjacentHTML('beforeend', "Min : #{Math.min oneTo10...}<br>")
# Sum items in an array
sumOfArray = oneTo10.reduce (x,y) -> x+y
csOutput.insertAdjacentHTML('beforeend', "Sum : #{sumOfArray}<br>")
# Reverse an Array
csOutput.insertAdjacentHTML('beforeend', "Reverse : #{tenTo1.reverse()}<br>")
# Create an array of objects
peopleArray = [
{
name: "Paul"
age: 43
},
{
name: "Sue"
age: 39
},
]
# Access item by key in array
csOutput.insertAdjacentHTML('beforeend', "First Name : #{peopleArray[0].name}<br>")
# ---------- LOOPING ----------
# Already covered how to cycle through an array
for x in oneTo10
csOutput.insertAdjacentHTML('beforeend', "#{x}<br>")
# We can use the guard when to print out only odd numbers
for x in oneTo10 when x%2 isnt 0
csOutput.insertAdjacentHTML('beforeend', "#{x}<br>")
# We can cycle trough a range of numbers and print out the evens
for x in [50..100] when x%2 is 0
csOutput.insertAdjacentHTML('beforeend', "#{x}<br>")
# We can skip certain values using by
for x in [20..40] by 2
csOutput.insertAdjacentHTML('beforeend', "#{x}<br>")
# We can access indexes
employees = [
"Doug"
"Sue"
"Paul"
]
for employee, employeeIndex in employees
csOutput.insertAdjacentHTML('beforeend', "Index: " +
employeeIndex + " Employee: " + employee + "<br>")
# We can search for a value with in
if "Doug" in employees
csOutput.insertAdjacentHTML('beforeend', "I Found Doug<br>")
# Let's count from 100 to 110 with a while loop
i = 100
while (i += 1) <= 110
csOutput.insertAdjacentHTML('beforeend', "i = #{i}<br>")
# You can use a while loop to cycle until 0 is reached
monkeys = 10
while monkeys -= 1
csOutput.insertAdjacentHTML('beforeend',
"#{monkeys} little monkeys, jumping on the bed. One fell off and bumped his head.<br>")
# There is no Do While loop but it can be emulated
# Loop as long as x != 5
x = 0
loop
csOutput.insertAdjacentHTML('beforeend', "#{++x}<br>")
break unless x != 5
# ---------- FUNCTIONS ----------
# With functions always move your functions above calling them in code
# You define the function name with an equal followed by attributes and ->
helloFunc = (name) ->
return "Hello #{name}"
csOutput.insertAdjacentHTML('beforeend', "#{helloFunc("Derek")}<br>")
# A function with no attributes
getRandNum = ->
return Math.floor(Math.random() * 100) + 1
csOutput.insertAdjacentHTML('beforeend', "Random Number : #{getRandNum()}<br>")
# You can receive an undefined number of values with vars...
sumNums = (vars...) ->
sum = 0
for x in vars
sum += x
return sum
csOutput.insertAdjacentHTML('beforeend',
"Sum : #{sumNums(1,2,3,4,5)}<br>")
# The last expression in a function is returned by default
# You can define default argument values
movieRank = (stars = 1) ->
if stars <= 2
"Bad"
else
"Good"
csOutput.insertAdjacentHTML('beforeend',
"Movie Rank : #{movieRank()}<br>")
# Recursive function that calculates a factorial
factorial = (x) ->
return 0 if x < 0
return 1 if x == 0 or x == 1
return x * factorial(x - 1)
csOutput.insertAdjacentHTML('beforeend',
"Factorial of 4 : #{factorial(4)}<br>")
# 1st: num = 4 * factorial(3) = 4 * 6 = 24
# 2nd: num = 3 * factorial(2) = 3 * 2 = 6
# 3rd: num = 2 * factorial(1) = 2 * 1 = 2
# ---------- OBJECTS ----------
derek = {name: "Derek", age: 41, street: "123 Main St"}
csOutput.insertAdjacentHTML('beforeend', "Name : #{derek.name}<br>")
# How we add an object property
derek.state = "Pennsylvania"
# Cycle through an object
for x, y of derek
csOutput.insertAdjacentHTML('beforeend', x + " is " + y + "<br>")
# ---------- CLASSES ----------
class Animal
# List properties along with their default values
name: "No Name"
height: 0
weight: 0
sound: "No Sound"
# Define a static property that is shared by all objects
@numOfAnimals: 0
# Static methods also start with @
@getNumOfAnimals: () ->
Animal.numOfAnimals
# The constructor is called when the object is created
# If we use @ with attributes the value is automatically assigned
constructor: (name = "No Name", @height = 0, @weight = 0) ->
# @ is like this in other languages
@name = name
# You access static properties using the class name
Animal.numOfAnimals++
# A class function
makeSound: ->
"says #{@sound}"
# Use @ to reference the objects properties
# Use @ to call ofther methods of this object
getInfo: ->
"#{@name} is #{@height} cm and weighs #{@weight} kg and #{@makeSound()}"
# Create an Animal object
grover = new Animal()
# Assign values to the Animal object
grover.name = "Grover"
grover.height = 60
grover.weight = 35
grover.sound = "Woof"
csOutput.insertAdjacentHTML('beforeend',
"#{grover.getInfo()}<br>")
# You can attach new object methods outside of the class
Animal::isItBig = ->
if @height >= 45
"Yes"
else
"No"
csOutput.insertAdjacentHTML('beforeend',
"Is Grover Big #{grover.isItBig()}<br>")
csOutput.insertAdjacentHTML('beforeend',
"Number of Animals #{Animal.getNumOfAnimals()}<br>")
# ---------- INHERITANCE ----------
# CoffeeScript makes inheritance very easy to implement
# Each class that extends another receives all its properties and methods
class Dog extends Animal
sound2: "No Sound"
constructor: (name = "No Name", height = 0, weight = 0) ->
# When super is called in the constructor CS calls the super classes
# constructor
super(name, height, weight)
# You override methods by declaring one with the same name
# CS is smart enough to know you are calling the Animal version
# of makeSound when you just type super
makeSound: ->
super + " and #{@sound2}"
sparky = new Dog("Sparky")
sparky.sound = "Wooooof"
sparky.sound2 = "Grrrrr"
csOutput.insertAdjacentHTML('beforeend',
"#{sparky.getInfo()}<br>") | 171036 | # ---------- ARRAYS ----------
# Arrays can contain multiple data types
randArray = ["word", false, 1234, 1.234]
csOutput.insertAdjacentHTML('beforeend', "Index 2 : #{randArray[2]}<br>")
# Get the last 2 indexes
csOutput.insertAdjacentHTML('beforeend', "Last 2 : #{randArray[2..3]}<br>")
# Defines an array with a range from 1 to 10
oneTo10 = [1..10]
# You can go backwards as well
tenTo1 = [10..1]
# Combine Arrays
combinedArray = oneTo10.concat tenTo1
# Push one tenTo1 onto the end of oneTo10
# ... is called a Splat and you use it to indicate that you want to
# "soak up" a list of arguments, or all the values in the array
oneTo10.push tenTo1...
# Use a for loop to cycle through the array
for x in oneTo10
csOutput.insertAdjacentHTML('beforeend', "#{x}<br>")
# Convert an array into a String
csOutput.insertAdjacentHTML('beforeend', "#{oneTo10.toString()}<br>")
# Filter out all odds by saving elements that return true for the condition
evensOnly = oneTo10.filter (x) -> x % 2 == 0
csOutput.insertAdjacentHTML('beforeend', "#{evensOnly.toString()}<br>")
# Get the maximum value in the array
csOutput.insertAdjacentHTML('beforeend', "Max : #{Math.max oneTo10...}<br>")
# Get the minimum value in the array
csOutput.insertAdjacentHTML('beforeend', "Min : #{Math.min oneTo10...}<br>")
# Sum items in an array
sumOfArray = oneTo10.reduce (x,y) -> x+y
csOutput.insertAdjacentHTML('beforeend', "Sum : #{sumOfArray}<br>")
# Reverse an Array
csOutput.insertAdjacentHTML('beforeend', "Reverse : #{tenTo1.reverse()}<br>")
# Create an array of objects
peopleArray = [
{
name: "<NAME>"
age: 43
},
{
name: "<NAME>"
age: 39
},
]
# Access item by key in array
csOutput.insertAdjacentHTML('beforeend', "First Name : #{peopleArray[0].name}<br>")
# ---------- LOOPING ----------
# Already covered how to cycle through an array
for x in oneTo10
csOutput.insertAdjacentHTML('beforeend', "#{x}<br>")
# We can use the guard when to print out only odd numbers
for x in oneTo10 when x%2 isnt 0
csOutput.insertAdjacentHTML('beforeend', "#{x}<br>")
# We can cycle trough a range of numbers and print out the evens
for x in [50..100] when x%2 is 0
csOutput.insertAdjacentHTML('beforeend', "#{x}<br>")
# We can skip certain values using by
for x in [20..40] by 2
csOutput.insertAdjacentHTML('beforeend', "#{x}<br>")
# We can access indexes
employees = [
"<NAME>"
"<NAME>"
"<NAME>"
]
for employee, employeeIndex in employees
csOutput.insertAdjacentHTML('beforeend', "Index: " +
employeeIndex + " Employee: " + employee + "<br>")
# We can search for a value with in
if "Doug" in employees
csOutput.insertAdjacentHTML('beforeend', "I Found Doug<br>")
# Let's count from 100 to 110 with a while loop
i = 100
while (i += 1) <= 110
csOutput.insertAdjacentHTML('beforeend', "i = #{i}<br>")
# You can use a while loop to cycle until 0 is reached
monkeys = 10
while monkeys -= 1
csOutput.insertAdjacentHTML('beforeend',
"#{monkeys} little monkeys, jumping on the bed. One fell off and bumped his head.<br>")
# There is no Do While loop but it can be emulated
# Loop as long as x != 5
x = 0
loop
csOutput.insertAdjacentHTML('beforeend', "#{++x}<br>")
break unless x != 5
# ---------- FUNCTIONS ----------
# With functions always move your functions above calling them in code
# You define the function name with an equal followed by attributes and ->
helloFunc = (name) ->
return "Hello #{name}"
csOutput.insertAdjacentHTML('beforeend', "#{helloFunc("<NAME>")}<br>")
# A function with no attributes
getRandNum = ->
return Math.floor(Math.random() * 100) + 1
csOutput.insertAdjacentHTML('beforeend', "Random Number : #{getRandNum()}<br>")
# You can receive an undefined number of values with vars...
sumNums = (vars...) ->
sum = 0
for x in vars
sum += x
return sum
csOutput.insertAdjacentHTML('beforeend',
"Sum : #{sumNums(1,2,3,4,5)}<br>")
# The last expression in a function is returned by default
# You can define default argument values
movieRank = (stars = 1) ->
if stars <= 2
"Bad"
else
"Good"
csOutput.insertAdjacentHTML('beforeend',
"Movie Rank : #{movieRank()}<br>")
# Recursive function that calculates a factorial
factorial = (x) ->
return 0 if x < 0
return 1 if x == 0 or x == 1
return x * factorial(x - 1)
csOutput.insertAdjacentHTML('beforeend',
"Factorial of 4 : #{factorial(4)}<br>")
# 1st: num = 4 * factorial(3) = 4 * 6 = 24
# 2nd: num = 3 * factorial(2) = 3 * 2 = 6
# 3rd: num = 2 * factorial(1) = 2 * 1 = 2
# ---------- OBJECTS ----------
derek = {name: "<NAME>", age: 41, street: "123 Main St"}
csOutput.insertAdjacentHTML('beforeend', "Name : #{derek.name}<br>")
# How we add an object property
derek.state = "Pennsylvania"
# Cycle through an object
for x, y of derek
csOutput.insertAdjacentHTML('beforeend', x + " is " + y + "<br>")
# ---------- CLASSES ----------
class Animal
# List properties along with their default values
name: "No Name"
height: 0
weight: 0
sound: "No Sound"
# Define a static property that is shared by all objects
@numOfAnimals: 0
# Static methods also start with @
@getNumOfAnimals: () ->
Animal.numOfAnimals
# The constructor is called when the object is created
# If we use @ with attributes the value is automatically assigned
constructor: (name = "No Name", @height = 0, @weight = 0) ->
# @ is like this in other languages
@name = name
# You access static properties using the class name
Animal.numOfAnimals++
# A class function
makeSound: ->
"says #{@sound}"
# Use @ to reference the objects properties
# Use @ to call ofther methods of this object
getInfo: ->
"#{@name} is #{@height} cm and weighs #{@weight} kg and #{@makeSound()}"
# Create an Animal object
grover = new Animal()
# Assign values to the Animal object
grover.name = "<NAME>"
grover.height = 60
grover.weight = 35
grover.sound = "Woof"
csOutput.insertAdjacentHTML('beforeend',
"#{grover.getInfo()}<br>")
# You can attach new object methods outside of the class
Animal::isItBig = ->
if @height >= 45
"Yes"
else
"No"
csOutput.insertAdjacentHTML('beforeend',
"Is Grover Big #{grover.isItBig()}<br>")
csOutput.insertAdjacentHTML('beforeend',
"Number of Animals #{Animal.getNumOfAnimals()}<br>")
# ---------- INHERITANCE ----------
# CoffeeScript makes inheritance very easy to implement
# Each class that extends another receives all its properties and methods
class Dog extends Animal
sound2: "No Sound"
constructor: (name = "<NAME>", height = 0, weight = 0) ->
# When super is called in the constructor CS calls the super classes
# constructor
super(name, height, weight)
# You override methods by declaring one with the same name
# CS is smart enough to know you are calling the Animal version
# of makeSound when you just type super
makeSound: ->
super + " and #{@sound2}"
sparky = new Dog("Sparky")
sparky.sound = "Wooooof"
sparky.sound2 = "Grrrrr"
csOutput.insertAdjacentHTML('beforeend',
"#{sparky.getInfo()}<br>") | true | # ---------- ARRAYS ----------
# Arrays can contain multiple data types
randArray = ["word", false, 1234, 1.234]
csOutput.insertAdjacentHTML('beforeend', "Index 2 : #{randArray[2]}<br>")
# Get the last 2 indexes
csOutput.insertAdjacentHTML('beforeend', "Last 2 : #{randArray[2..3]}<br>")
# Defines an array with a range from 1 to 10
oneTo10 = [1..10]
# You can go backwards as well
tenTo1 = [10..1]
# Combine Arrays
combinedArray = oneTo10.concat tenTo1
# Push one tenTo1 onto the end of oneTo10
# ... is called a Splat and you use it to indicate that you want to
# "soak up" a list of arguments, or all the values in the array
oneTo10.push tenTo1...
# Use a for loop to cycle through the array
for x in oneTo10
csOutput.insertAdjacentHTML('beforeend', "#{x}<br>")
# Convert an array into a String
csOutput.insertAdjacentHTML('beforeend', "#{oneTo10.toString()}<br>")
# Filter out all odds by saving elements that return true for the condition
evensOnly = oneTo10.filter (x) -> x % 2 == 0
csOutput.insertAdjacentHTML('beforeend', "#{evensOnly.toString()}<br>")
# Get the maximum value in the array
csOutput.insertAdjacentHTML('beforeend', "Max : #{Math.max oneTo10...}<br>")
# Get the minimum value in the array
csOutput.insertAdjacentHTML('beforeend', "Min : #{Math.min oneTo10...}<br>")
# Sum items in an array
sumOfArray = oneTo10.reduce (x,y) -> x+y
csOutput.insertAdjacentHTML('beforeend', "Sum : #{sumOfArray}<br>")
# Reverse an Array
csOutput.insertAdjacentHTML('beforeend', "Reverse : #{tenTo1.reverse()}<br>")
# Create an array of objects
peopleArray = [
{
name: "PI:NAME:<NAME>END_PI"
age: 43
},
{
name: "PI:NAME:<NAME>END_PI"
age: 39
},
]
# Access item by key in array
csOutput.insertAdjacentHTML('beforeend', "First Name : #{peopleArray[0].name}<br>")
# ---------- LOOPING ----------
# Already covered how to cycle through an array
for x in oneTo10
csOutput.insertAdjacentHTML('beforeend', "#{x}<br>")
# We can use the guard when to print out only odd numbers
for x in oneTo10 when x%2 isnt 0
csOutput.insertAdjacentHTML('beforeend', "#{x}<br>")
# We can cycle trough a range of numbers and print out the evens
for x in [50..100] when x%2 is 0
csOutput.insertAdjacentHTML('beforeend', "#{x}<br>")
# We can skip certain values using by
for x in [20..40] by 2
csOutput.insertAdjacentHTML('beforeend', "#{x}<br>")
# We can access indexes
employees = [
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
]
for employee, employeeIndex in employees
csOutput.insertAdjacentHTML('beforeend', "Index: " +
employeeIndex + " Employee: " + employee + "<br>")
# We can search for a value with in
if "Doug" in employees
csOutput.insertAdjacentHTML('beforeend', "I Found Doug<br>")
# Let's count from 100 to 110 with a while loop
i = 100
while (i += 1) <= 110
csOutput.insertAdjacentHTML('beforeend', "i = #{i}<br>")
# You can use a while loop to cycle until 0 is reached
monkeys = 10
while monkeys -= 1
csOutput.insertAdjacentHTML('beforeend',
"#{monkeys} little monkeys, jumping on the bed. One fell off and bumped his head.<br>")
# There is no Do While loop but it can be emulated
# Loop as long as x != 5
x = 0
loop
csOutput.insertAdjacentHTML('beforeend', "#{++x}<br>")
break unless x != 5
# ---------- FUNCTIONS ----------
# With functions always move your functions above calling them in code
# You define the function name with an equal followed by attributes and ->
helloFunc = (name) ->
return "Hello #{name}"
csOutput.insertAdjacentHTML('beforeend', "#{helloFunc("PI:NAME:<NAME>END_PI")}<br>")
# A function with no attributes
getRandNum = ->
return Math.floor(Math.random() * 100) + 1
csOutput.insertAdjacentHTML('beforeend', "Random Number : #{getRandNum()}<br>")
# You can receive an undefined number of values with vars...
sumNums = (vars...) ->
sum = 0
for x in vars
sum += x
return sum
csOutput.insertAdjacentHTML('beforeend',
"Sum : #{sumNums(1,2,3,4,5)}<br>")
# The last expression in a function is returned by default
# You can define default argument values
movieRank = (stars = 1) ->
if stars <= 2
"Bad"
else
"Good"
csOutput.insertAdjacentHTML('beforeend',
"Movie Rank : #{movieRank()}<br>")
# Recursive function that calculates a factorial
factorial = (x) ->
return 0 if x < 0
return 1 if x == 0 or x == 1
return x * factorial(x - 1)
csOutput.insertAdjacentHTML('beforeend',
"Factorial of 4 : #{factorial(4)}<br>")
# 1st: num = 4 * factorial(3) = 4 * 6 = 24
# 2nd: num = 3 * factorial(2) = 3 * 2 = 6
# 3rd: num = 2 * factorial(1) = 2 * 1 = 2
# ---------- OBJECTS ----------
derek = {name: "PI:NAME:<NAME>END_PI", age: 41, street: "123 Main St"}
csOutput.insertAdjacentHTML('beforeend', "Name : #{derek.name}<br>")
# How we add an object property
derek.state = "Pennsylvania"
# Cycle through an object
for x, y of derek
csOutput.insertAdjacentHTML('beforeend', x + " is " + y + "<br>")
# ---------- CLASSES ----------
class Animal
# List properties along with their default values
name: "No Name"
height: 0
weight: 0
sound: "No Sound"
# Define a static property that is shared by all objects
@numOfAnimals: 0
# Static methods also start with @
@getNumOfAnimals: () ->
Animal.numOfAnimals
# The constructor is called when the object is created
# If we use @ with attributes the value is automatically assigned
constructor: (name = "No Name", @height = 0, @weight = 0) ->
# @ is like this in other languages
@name = name
# You access static properties using the class name
Animal.numOfAnimals++
# A class function
makeSound: ->
"says #{@sound}"
# Use @ to reference the objects properties
# Use @ to call ofther methods of this object
getInfo: ->
"#{@name} is #{@height} cm and weighs #{@weight} kg and #{@makeSound()}"
# Create an Animal object
grover = new Animal()
# Assign values to the Animal object
grover.name = "PI:NAME:<NAME>END_PI"
grover.height = 60
grover.weight = 35
grover.sound = "Woof"
csOutput.insertAdjacentHTML('beforeend',
"#{grover.getInfo()}<br>")
# You can attach new object methods outside of the class
Animal::isItBig = ->
if @height >= 45
"Yes"
else
"No"
csOutput.insertAdjacentHTML('beforeend',
"Is Grover Big #{grover.isItBig()}<br>")
csOutput.insertAdjacentHTML('beforeend',
"Number of Animals #{Animal.getNumOfAnimals()}<br>")
# ---------- INHERITANCE ----------
# CoffeeScript makes inheritance very easy to implement
# Each class that extends another receives all its properties and methods
class Dog extends Animal
sound2: "No Sound"
constructor: (name = "PI:NAME:<NAME>END_PI", height = 0, weight = 0) ->
# When super is called in the constructor CS calls the super classes
# constructor
super(name, height, weight)
# You override methods by declaring one with the same name
# CS is smart enough to know you are calling the Animal version
# of makeSound when you just type super
makeSound: ->
super + " and #{@sound2}"
sparky = new Dog("Sparky")
sparky.sound = "Wooooof"
sparky.sound2 = "Grrrrr"
csOutput.insertAdjacentHTML('beforeend',
"#{sparky.getInfo()}<br>") |
[
{
"context": "describe 'okv :', ->\n weirdKeyName = ' $#%!@&'\n\n it \"builds a simple object, with weird keyNa",
"end": 45,
"score": 0.5894271731376648,
"start": 41,
"tag": "KEY",
"value": "#%!@"
}
] | source/spec/objects/okv-spec.coffee | anodynos/uBerscore | 1 | describe 'okv :', ->
weirdKeyName = ' $#%!@&'
it "builds a simple object, with weird keyName", ->
expect(
_B.okv {},
"foo_#{weirdKeyName}", 8
"bar#{weirdKeyName}", 'some bar'
).to.deep.equal
"foo_ $#%!@&": 8
"bar $#%!@&": 'some bar'
describe "build a more invloved object", ->#
o = theO = {}
o = _B.okv o,
"foo_#{weirdKeyName}", 8
bar = "bar#{weirdKeyName}", 'some bar' # note we store key name
o[bar] = _B.okv {},
"nestedBar#{weirdKeyName}", "This is a secret bar"
"anotherBar#{weirdKeyName}", "Many bars, no foo"
it "the object passed, is the object returned", ->
expect(o).to.equal theO
it "o is build, then part of it augmented", ->
expect(o).to.deep.equal
"foo_ $#%!@&": 8,
"bar $#%!@&":
"nestedBar $#%!@&": "This is a secret bar",
"anotherBar $#%!@&": "Many bars, no foo"
it "add nested weird keyd bars on existing key, with ignored reduntan key", ->
_B.okv o[bar],
"newbar#{weirdKeyName}", "a new bar!"
'bar' + ("#{i}" for i in [1,2,3]).join('-'), "ther weirest bar!",
'reduntantKey'
expect(o).to.deep.equal
"foo_ $#%!@&": 8,
"bar $#%!@&":
"nestedBar $#%!@&": "This is a secret bar",
"anotherBar $#%!@&": "Many bars, no foo"
"newbar $#%!@&": "a new bar!"
"bar1-2-3": "ther weirest bar!"
describe "passing a string instead of obj as 1st param & toString objects as keys", ->
it "creates a new object, when 1st param is a String, which becomes the 1st key", ->
o = _B.okv 'some' + 'property', {a:'value'}
expect(o).to.deep.equal 'someproperty': {a:'value'}
it "key is an object, converted toString", ->
objectWithToString =
prop: 'a property of an object'
toString:-> @prop + ' that becomes a String'
o = _B.okv {}, objectWithToString, {a:'value'}
expect(o).to.deep.equal 'a property of an object that becomes a String': {a:'value'}
| 113531 | describe 'okv :', ->
weirdKeyName = ' $<KEY>&'
it "builds a simple object, with weird keyName", ->
expect(
_B.okv {},
"foo_#{weirdKeyName}", 8
"bar#{weirdKeyName}", 'some bar'
).to.deep.equal
"foo_ $#%!@&": 8
"bar $#%!@&": 'some bar'
describe "build a more invloved object", ->#
o = theO = {}
o = _B.okv o,
"foo_#{weirdKeyName}", 8
bar = "bar#{weirdKeyName}", 'some bar' # note we store key name
o[bar] = _B.okv {},
"nestedBar#{weirdKeyName}", "This is a secret bar"
"anotherBar#{weirdKeyName}", "Many bars, no foo"
it "the object passed, is the object returned", ->
expect(o).to.equal theO
it "o is build, then part of it augmented", ->
expect(o).to.deep.equal
"foo_ $#%!@&": 8,
"bar $#%!@&":
"nestedBar $#%!@&": "This is a secret bar",
"anotherBar $#%!@&": "Many bars, no foo"
it "add nested weird keyd bars on existing key, with ignored reduntan key", ->
_B.okv o[bar],
"newbar#{weirdKeyName}", "a new bar!"
'bar' + ("#{i}" for i in [1,2,3]).join('-'), "ther weirest bar!",
'reduntantKey'
expect(o).to.deep.equal
"foo_ $#%!@&": 8,
"bar $#%!@&":
"nestedBar $#%!@&": "This is a secret bar",
"anotherBar $#%!@&": "Many bars, no foo"
"newbar $#%!@&": "a new bar!"
"bar1-2-3": "ther weirest bar!"
describe "passing a string instead of obj as 1st param & toString objects as keys", ->
it "creates a new object, when 1st param is a String, which becomes the 1st key", ->
o = _B.okv 'some' + 'property', {a:'value'}
expect(o).to.deep.equal 'someproperty': {a:'value'}
it "key is an object, converted toString", ->
objectWithToString =
prop: 'a property of an object'
toString:-> @prop + ' that becomes a String'
o = _B.okv {}, objectWithToString, {a:'value'}
expect(o).to.deep.equal 'a property of an object that becomes a String': {a:'value'}
| true | describe 'okv :', ->
weirdKeyName = ' $PI:KEY:<KEY>END_PI&'
it "builds a simple object, with weird keyName", ->
expect(
_B.okv {},
"foo_#{weirdKeyName}", 8
"bar#{weirdKeyName}", 'some bar'
).to.deep.equal
"foo_ $#%!@&": 8
"bar $#%!@&": 'some bar'
describe "build a more invloved object", ->#
o = theO = {}
o = _B.okv o,
"foo_#{weirdKeyName}", 8
bar = "bar#{weirdKeyName}", 'some bar' # note we store key name
o[bar] = _B.okv {},
"nestedBar#{weirdKeyName}", "This is a secret bar"
"anotherBar#{weirdKeyName}", "Many bars, no foo"
it "the object passed, is the object returned", ->
expect(o).to.equal theO
it "o is build, then part of it augmented", ->
expect(o).to.deep.equal
"foo_ $#%!@&": 8,
"bar $#%!@&":
"nestedBar $#%!@&": "This is a secret bar",
"anotherBar $#%!@&": "Many bars, no foo"
it "add nested weird keyd bars on existing key, with ignored reduntan key", ->
_B.okv o[bar],
"newbar#{weirdKeyName}", "a new bar!"
'bar' + ("#{i}" for i in [1,2,3]).join('-'), "ther weirest bar!",
'reduntantKey'
expect(o).to.deep.equal
"foo_ $#%!@&": 8,
"bar $#%!@&":
"nestedBar $#%!@&": "This is a secret bar",
"anotherBar $#%!@&": "Many bars, no foo"
"newbar $#%!@&": "a new bar!"
"bar1-2-3": "ther weirest bar!"
describe "passing a string instead of obj as 1st param & toString objects as keys", ->
it "creates a new object, when 1st param is a String, which becomes the 1st key", ->
o = _B.okv 'some' + 'property', {a:'value'}
expect(o).to.deep.equal 'someproperty': {a:'value'}
it "key is an object, converted toString", ->
objectWithToString =
prop: 'a property of an object'
toString:-> @prop + ' that becomes a String'
o = _B.okv {}, objectWithToString, {a:'value'}
expect(o).to.deep.equal 'a property of an object that becomes a String': {a:'value'}
|
[
{
"context": "es\n###\nOLD_PRODUCT =\n id: '123'\n name:\n en: 'SAPPHIRE'\n de: 'Hoo'\n slug:\n en: 'sapphire136612644",
"end": 232,
"score": 0.8771794438362122,
"start": 224,
"tag": "NAME",
"value": "SAPPHIRE"
},
{
"context": "=\n id: '123'\n name:\n en: 'SAPPHIRE'\... | src/spec/sync/utils/product.spec.coffee | commercetools/sphere-node-sdk | 13 | _ = require 'underscore'
_.mixin require 'underscore-mixins'
ProductUtils = require '../../../lib/sync/utils/product'
###
Match different product attributes and variant prices
###
OLD_PRODUCT =
id: '123'
name:
en: 'SAPPHIRE'
de: 'Hoo'
slug:
en: 'sapphire1366126441922'
description:
en: 'Sample description'
masterVariant:
id: 1
prices: [
{ id: 'p-1', value: { currencyCode: 'EUR', centAmount: 1 } }
{ id: 'p-2', value: { currencyCode: 'EUR', centAmount: 7 } }
]
variants: [
{
id: 2
prices: [
{ id: 'p-3', value: { currencyCode: 'USD', centAmount: 3 } }
]
},
{
id: 3
prices: [
{ id: 'p-4', value: { currencyCode: 'EUR', centAmount: 2100 }, country: 'DE' }
{ id: 'p-5', value: { currencyCode: 'EUR', centAmount: 2200 }, customerGroup: { id: '123', typeId: 'customer-group' } }
]
},
{
id: 4
prices: [
{ id: 'p-6', value: { currencyCode: 'YEN', centAmount: 7777 } }
]
},
{
id: 5
prices: []
}
]
NEW_PRODUCT =
id: '123'
name:
en: 'Foo'
it: 'Boo'
slug:
en: 'foo'
it: 'boo'
masterVariant:
id: 1
prices: [
{ value: { currencyCode: 'EUR', centAmount: 2 } }
{ value: { currencyCode: 'USD', centAmount: 7 } }
]
variants: [
{
id: 2
prices: [
{ value: { currencyCode: 'USD', centAmount: 3 } }
]
},
{
id: 3
prices: [
{ value: { currencyCode: 'EUR', centAmount: 2100 }, country: 'CH' }
{ value: { currencyCode: 'EUR', centAmount: 2200 }, customerGroup: { id: '987', typeId: 'customer-group' } }
]
},
{
id: 4
prices: []
},
{
id: 5
prices: [
{ value: { currencyCode: 'EUR', centAmount: 999 } }
]
}
]
###
Match all different attributes types
###
OLD_ALL_ATTRIBUTES =
id: '123'
masterVariant:
id: 1
attributes: [
{ name: 'foo', value: 'bar' } # text
{ name: 'dog', value: {en: 'Dog', de: 'Hund', es: 'perro' } } # ltext
{ name: 'num', value: 50 } # number
{ name: 'count', value: { label: 'One', key: 'one' } } # enum
{ name: 'size', value: { label: {en: 'Size'}, key: 'medium' } } # lenum
{ name: 'color', value: { label: {en: 'Color'}, key: 'red' } } # lenum
{ name: 'cost', value: { centAmount: 990, currencyCode: 'EUR' } } # money
]
NEW_ALL_ATTRIBUTES =
id: '123'
masterVariant:
id: 1
attributes: [
{ name: 'foo', value: 'qux' } # text
{ name: 'dog', value: {en: 'Doggy', it: 'Cane', es: 'perro' } } # ltext
{ name: 'num', value: 100 } # number
{ name: 'count', value: 'two' } # enum
{ name: 'size', value: 'small' } # lenum
{ name: 'color', value: 'blue' } # lenum
{ name: 'cost', value: { centAmount: 550, currencyCode: 'EUR' } } # money
]
describe 'ProductUtils', ->
beforeEach ->
@utils = new ProductUtils
describe ':: diff', ->
it 'should diff nothing', ->
delta = @utils.diff({id: '123', masterVariant: { id: 1 }}, {id: '123', masterVariant: { id: 1 }})
expect(delta).not.toBeDefined()
it 'should use SKU to compare variants', ->
OLD =
id: 'xyz'
masterVariant: {
id: 1
sku: 'mySKU1'
}
variants: [
{ id: 3, sku: 'mySKU2' }
]
NEW =
id: 'xyz'
masterVariant: {
id: 1,
sku: 'mySKU2'
}
variants: [
{ id: 2, sku: 'mySKU1' }
]
delta = @utils.diff(OLD, NEW)
expected_delta =
masterVariant:
sku: [ 'mySKU1', 'mySKU2' ]
_MATCH_CRITERIA: [ 'mySKU1', 'mySKU2' ]
variants:
0: [
{
id: 2
sku: 'mySKU1'
_MATCH_CRITERIA: 'mySKU1'
_NEW_ARRAY_INDEX: '0'
}
]
_t: 'a'
_0: [
{
id: 3
sku: 'mySKU2'
_MATCH_CRITERIA: 'mySKU2'
_EXISTING_ARRAY_INDEX: '0'
},
0,
0
]
expect(delta).toEqual expected_delta
it 'should throw an Error if variant has no ID nor SKU', ->
OLD =
id: 'xyz'
variants: [
{attributes: [foo: 'bar']}
]
NEW =
id: 'xyz'
masterVariant:
attributes: [foo: 'bar']
expect(=> @utils.diff(OLD, NEW)).toThrow new Error 'A variant must either have an ID or an SKU.'
it 'should diff basic attributes (name, slug, description, searchKeywords)', ->
OLD =
id: '123'
name:
en: 'Foo'
de: 'Hoo'
slug:
en: 'foo'
description:
en: 'Sample'
searchKeywords:
en: [ {text: 'old'}, {text: 'keywords'} ]
de: [ {text: 'alte'}, {text: 'schlagwoerter'} ]
masterVariant:
id: 1
NEW =
id: '123'
name:
en: 'Boo'
slug:
en: 'boo'
description:
en: 'Sample'
it: 'Esempio'
searchKeywords:
en: [ {text: 'new'}, {text: 'keywords'} ]
it: [ {text: 'veccie'}, {text: 'parole'} ]
masterVariant:
id: 1
delta = @utils.diff(OLD, NEW)
expected_delta =
name:
en: ['Foo', 'Boo']
de: ['Hoo', 0, 0 ]
slug:
en: ['foo', 'boo']
description:
it: ['Esempio']
searchKeywords:
en : 0 : [ { text : 'new' } ], 1 : [ { text : 'keywords' } ], _t : 'a', _0 : [ { text : 'old' }, 0, 0 ], _1 : [ { text : 'keywords' }, 0, 0 ]
de : [ [ { text : 'alte' }, { text : 'schlagwoerter' } ], 0, 0 ]
it: [[ {text: 'veccie'}, {text: 'parole'} ]]
expect(delta).toEqual expected_delta
it 'should diff missing attribute', ->
delta = @utils.diff(OLD_PRODUCT, NEW_PRODUCT)
expected_delta =
name:
en: ['SAPPHIRE', 'Foo'] # changed
de: ['Hoo', 0, 0]
it: ['Boo']
slug:
en: ['sapphire1366126441922', 'foo']
it: ['boo']
description: [en: 'Sample description', 0, 0] # deleted
masterVariant:
prices:
0:
id: ['p-1', 0,0]
value:
centAmount: [1, 2]
1:
id: ['p-2', 0,0]
value:
currencyCode: ['EUR', 'USD']
_t: 'a'
variants:
0:
prices:
0:
id: ['p-3', 0, 0]
_t: 'a'
_EXISTING_ARRAY_INDEX: ['0', 0, 0],
_NEW_ARRAY_INDEX: ['0']
1:
prices:
0:
id: ['p-4', 0, 0],
country: ['DE', 'CH']
1:
id: ['p-5', 0, 0],
customerGroup:
id: ['123', '987']
_t: 'a'
_EXISTING_ARRAY_INDEX: ['1', 0, 0],
_NEW_ARRAY_INDEX: ['1']
2:
prices:
_t: 'a',
_0: [{
id: 'p-6',
value:
currencyCode: 'YEN',
centAmount: 7777
_MATCH_CRITERIA: '0'
}, 0, 0]
_EXISTING_ARRAY_INDEX: ['2', 0, 0],
_NEW_ARRAY_INDEX: ['2']
3:
prices:
0: [{
value:
currencyCode: 'EUR',
centAmount: 999
_MATCH_CRITERIA: '0'
}],
_t: 'a'
_EXISTING_ARRAY_INDEX: ['3', 0, 0],
_NEW_ARRAY_INDEX: ['3']
_t: 'a'
expect(delta).toEqual expected_delta
it 'should diff different attribute types', ->
delta = @utils.diff(OLD_ALL_ATTRIBUTES, NEW_ALL_ATTRIBUTES)
expected_delta =
masterVariant:
attributes:
0: { value: ['bar', 'qux'] }
1:
value:
en: ['Dog', 'Doggy']
it: ['Cane']
de: ['Hund', 0, 0]
2: { value: [50, 100] }
3: { value: ['one', 'two'] }
4: { value: ['medium', 'small'] }
5: { value: ['red', 'blue'] }
6: { value: { centAmount: [990, 550] } }
_t: 'a'
expect(delta).toEqual expected_delta
it 'should patch enums', ->
EXISTING_ENUM_ATTRIBUTES =
id: 'enum-101'
masterVariant:
id: 1
attributes: [
{ name: 'count', value: { label: 'My Key', key: 'myKey' } } # enum
{ name: 'size', value: { label: { en: 'Size' }, key: 'big' } } # lenum
{ name: 'color', value: { label: { de: 'Farbe' }, key: 'red' } } # lenum
]
variants: [
{ id: 2, attributes: [
{ name: 'tags', value: [ { label: { en: 'Tags1' }, key: 'tag1' } ] } # lenum
]}
]
NEW_ENUM_ATTRIBUTES =
id: 'enum-101'
masterVariant:
id: 1
attributes: [
{ name: 'count', value: 'myKey' } # enum - unchanged
{ name: 'size', value: 'small' } # lenum - changed key
# color is removed
]
variants: [
{ id: 2, attributes: [
{ name: 'tags', value: [ { label: { en: 'Tags2' }, key: 'tag2' } ] } # lenum
]}
]
delta = @utils.diff(EXISTING_ENUM_ATTRIBUTES, NEW_ENUM_ATTRIBUTES)
expected_delta =
masterVariant:
attributes:
1: { value: ['big', 'small'] }
_t: 'a'
_2: [ { name: 'color', value: 'red'}, 0, 0 ]
variants:
0:
attributes:
0:
value:
0: ['tag2']
_t: 'a'
_0: ['tag1', 0, 0]
_t: 'a'
_NEW_ARRAY_INDEX: ['0']
_EXISTING_ARRAY_INDEX: ['0', 0, 0]
_t: 'a'
expect(delta).toEqual expected_delta
describe ':: buildRemoveVariantActions', ->
it 'should throw an error when removing a variant without id and sku', ->
oldVariants = [
{
# no id or sku
key: 'newVar'
}
]
newVariants = []
expect( () => @utils.buildRemoveVariantActions(newVariants, oldVariants))
.toThrow new Error('ProductSync does need at least one of "id" or "sku" to generate a remove action')
it 'should throw an error when removing a variant without id and sku', ->
oldVariants = [
{
# no id - use sku in removeVariant action
sku: 'newVar'
}
]
newVariants = []
actions = @utils.buildRemoveVariantActions(newVariants, oldVariants)
expect(actions).toEqual([
{ action: 'removeVariant', sku: 'newVar' }
])
describe ':: findVariantInList', ->
it 'should find variant using sku', ->
oldVariants = [
{
id: 1
sku: 'sku1'
},
{
id: 2
sku: 'sku2'
}
]
newVariant = {
id: 2,
sku: 'sku1'
}
actions = @utils.findVariantInList(newVariant, oldVariants)
expect(actions).toEqual({
id: 1
sku: 'sku1'
})
it 'should find variant using id', ->
oldVariants = [
{
id: 1
sku: 'sku1'
},
{
id: 2,
key: 'key'
}
]
newVariant = {
id: 2,
}
actions = @utils.findVariantInList(newVariant, oldVariants)
expect(actions).toEqual({
id: 2
key: 'key'
})
it 'should find variant using key', ->
oldVariants = [
{
id: 1
sku: 'key1'
},
{
id: 2,
key: 'key2'
}
]
newVariant = {
id: 1,
key: 'key2',
}
actions = @utils.findVariantInList(newVariant, oldVariants)
expect(actions).toEqual({
id: 2
key: 'key2'
})
it 'should not find an unknown variant', ->
oldVariants = [
{
id: 1
sku: 'key1'
},
{
id: 2,
key: 'key2'
}
]
newVariant = {
id: 29,
key: 'key3',
}
actions = @utils.findVariantInList(newVariant, oldVariants)
expect(actions).toEqual(undefined)
it 'should not find variant if sku does not match', ->
variant = {
id: 1,
sku: 3
}
variantList = [
{
id: 1,
sku: 'sku1'
},
{
id: 21,
sku: 'sku2'
}
]
foundVariant = @utils.findVariantInList(variant, variantList, 'sku')
expect(foundVariant).not.toBeDefined()
it 'should match variants with sku', ->
variant = {
id: 2,
sku: 'sku2'
}
variantList = [
{
id: 1,
sku: 'sku1'
},
{
id: 3,
sku: 'sku2'
}
]
foundVariant = @utils.findVariantInList(variant, variantList, 'sku')
expect(foundVariant).toEqual({ id: 3, sku: 'sku2' })
it 'should match variants with keys', ->
variant = {
id: 2,
key: 'key2'
}
variantList = [
{
id: 1,
key: 'key1'
},
{
id: 3,
key: 'key2'
}
]
foundVariant = @utils.findVariantInList(variant, variantList, 'key')
expect(foundVariant).toEqual({ id: 3, key: 'key2' })
it 'should match variants with ids', ->
variant = {
id: 2
}
variantList = [
{
id: 1
},
{
id: 2
}
]
foundVariant = @utils.findVariantInList(variant, variantList, 'id')
expect(foundVariant).toEqual({ id: 2 })
describe ':: buildVariantPriceActions', ->
it 'should return an empty array when no price diff is provided', ->
actions = @utils.buildVariantPriceActions(null, {}, {})
expect(actions).toEqual []
describe ':: buildChangeMasterVariantAction', ->
it 'should throw an error when changing a masterVariant without id and sku', ->
newMasterVariant =
key: 'newVar'
oldMasterVariant =
key: 'oldVar'
expect( () => @utils.buildChangeMasterVariantAction(newMasterVariant, oldMasterVariant))
.toThrow new Error('ProductSync needs at least one of "id" or "sku" to generate "changeMasterVariant" update action')
describe ':: buildVariantBaseAction', ->
it 'should build update actions for variant base properties', ->
oldVariant =
id: '123'
newVariant =
id: '123'
sku: 'sku123'
key: 'key123'
delta = @utils.diff oldVariant, newVariant
update = @utils.buildVariantBaseAction(delta, oldVariant)
expected_update = [
{ action : 'setSku', variantId : '123', sku : 'sku123' }
{ action : 'setProductVariantKey', variantId : '123', key : 'key123' }
]
expect(update).toEqual expected_update
describe ':: _buildAddExternalImageAction', ->
it 'should not process an undefined image when adding', ->
update = @utils._buildAddExternalImageAction({}, null)
expect(update).toEqual undefined
describe ':: _buildRemoveImageAction', ->
it 'should not process an undefined image when removing', ->
update = @utils._buildRemoveImageAction({}, null)
expect(update).toEqual undefined
describe ':: actionsMapBase', ->
it 'should diff if basic attribute is undefined', ->
OLD =
key: 'oldKey'
id: '123'
name:
en: 'Foo'
slug:
en: 'foo'
masterVariant:
id: 1
NEW =
key: 'newKey'
id: '123'
name:
de: 'Boo'
slug:
en: 'boo'
description:
en: 'Sample'
it: 'Esempio'
searchKeywords:
en: [ {text: 'new'}, {text: 'keyword'} ]
masterVariant:
id: 1
delta = @utils.diff OLD, NEW
update = @utils.actionsMapBase(delta, OLD)
expected_update = [
{ action: 'setKey', key: 'newKey' }
{ action: 'changeName', name: {en: undefined, de: 'Boo'} }
{ action: 'changeSlug', slug: {en: 'boo'} }
{ action: 'setDescription', description: {en: 'Sample', it: 'Esempio'} }
{ action: 'setSearchKeywords', searchKeywords: {en: [ {text: 'new'}, {text: 'keyword'} ]} }
]
expect(update).toEqual expected_update
it 'should diff long text', ->
OLD =
id: '123'
name:
en: '`Churchill` talked about climbing a wall which is leaning toward you and kissing a woman who is leaning away from you.'
slug:
en: 'churchill-talked-about-climbing-a-wall-which-is-leaning-toward-you-and-kissing-a-woman-who-is-leaning-away-from-you'
description:
en: 'There are two things that are more difficult than making an after-dinner speech: climbing a wall which is leaning toward you and kissing a girl who is leaning away from you.'
masterVariant:
id: 1
NEW =
id: '123'
name:
en: '`Churchill` talked about climbing a BIG wall which WAS leaning toward you and kissing a woman who WAS leaning away from you.'
slug:
en: 'churchill-talked-about-climbing-a-big-wall-which-was-leaning-toward-you-and-kissing-a-woman-who-was-leaning-away-from-you'
description:
en: 'There are three things that are more difficult than making an after-dinner speech: climbing a mountain which is leaning toward you and slapping a girl who is leaning away from you.'
masterVariant:
id: 1
delta = @utils.diff OLD, NEW
update = @utils.actionsMapBase(delta, OLD)
expected_update = [
{ action: 'changeName', name: {en: NEW.name.en} }
{ action: 'changeSlug', slug: {en: NEW.slug.en} }
{ action: 'setDescription', description: {en: NEW.description.en} }
]
expect(update).toEqual expected_update
it 'should diff meta attributes', ->
OLD =
id: '123'
metaTitle:
en: 'A title'
metaDescription:
en: 'A description'
metaKeywords:
en: 'foo, bar'
masterVariant:
id: 1
NEW =
id: '123'
metaTitle:
en: 'A new title'
metaDescription:
en: 'A new description'
metaKeywords:
en: 'foo, bar, qux'
masterVariant:
id: 1
delta = @utils.diff OLD, NEW
update = @utils.actionsMapBase(delta, OLD)
expected_update = [
{
action: 'setMetaTitle'
metaTitle: {en: 'A new title'}
}
{
action: 'setMetaDescription'
metaDescription: {en: 'A new description'}
}
{
action: 'setMetaKeywords'
metaKeywords: {en: 'foo, bar, qux'}
}
]
expect(update).toEqual expected_update
it 'should transform setCategoryOrderHint actions correctly', ->
OLD =
id: '123'
masterVariant:
id: 1
categoryOrderHints:
abc: '0.9'
NEW =
id: '123'
masterVariant:
id: 1
categoryOrderHints:
abc: '0.3'
anotherCategoryId: '0.1'
delta = @utils.diff OLD, NEW
update = @utils.actionsMapCategoryOrderHints(delta, OLD)
expected_update = [
{
action: 'setCategoryOrderHint'
categoryId: 'abc'
orderHint: '0.3'
}, {
action: 'setCategoryOrderHint'
categoryId: 'anotherCategoryId'
orderHint: '0.1'
},
]
expect(update).toEqual expected_update
it 'should generate a setCategoryOrderHint action to unset order hints', ->
OLD =
id: '123'
masterVariant:
id: 1
categoryOrderHints:
abc: '0.9'
anotherCategoryId: '0.5'
categoryId: '0.5'
NEW =
id: '123'
masterVariant:
id: 1
categoryOrderHints:
abc: null
anotherCategoryId: '0'
categoryId: ''
delta = @utils.diff OLD, NEW
update = @utils.actionsMapCategoryOrderHints(delta, OLD)
expected_update = [
{
action: 'setCategoryOrderHint'
categoryId: 'abc',
orderHint: undefined,
},
{
action: 'setCategoryOrderHint'
categoryId: 'anotherCategoryId',
orderHint: '0',
}
{
action: 'setCategoryOrderHint'
categoryId: 'categoryId',
orderHint: undefined,
}
]
expect(update).toEqual expected_update
it 'should should not create an action if categoryOrderHint is empty', ->
OLD =
id: '123'
categoryOrderHints: {}
metaTitle:
en: 'A title'
masterVariant:
id: 1
NEW =
id: '123'
metaTitle:
en: 'A new title'
masterVariant:
id: 1
delta = @utils.diff OLD, NEW
update = @utils.actionsMapBase(delta, OLD)
expected_update = [
{
action: 'setMetaTitle'
metaTitle: {en: 'A new title'}
}
]
expect(update).toEqual expected_update
describe ':: actionsMapAttributes', ->
it 'should create update action for attribute', ->
_oldVariant = {
id: 3, attributes: [{ name: 'foo', value: 'bar' }]
}
_newVariant = {
id: 3, attributes: [{ name: 'foo', value: 'CHANGED' }]
}
diff = @utils.diff _oldVariant, _newVariant
update = @utils.buildVariantAttributesActions diff.attributes, _oldVariant, _newVariant
expected_update = [
{ action: 'setAttribute', variantId: 3, name: 'foo', value: 'CHANGED' }
]
expect(update).toEqual expected_update
it 'should build attribute update actions for all types', ->
oldVariant = OLD_ALL_ATTRIBUTES.masterVariant
newVariant = NEW_ALL_ATTRIBUTES.masterVariant
diff = @utils.diff oldVariant, newVariant
update = @utils.buildVariantAttributesActions diff.attributes, oldVariant, newVariant
expected_update =
[
{ action: 'setAttribute', variantId: 1, name: 'foo', value: 'qux' }
{ action: 'setAttribute', variantId: 1, name: 'dog', value: {en: 'Doggy', it: 'Cane', de: undefined, es: 'perro'} }
{ action: 'setAttribute', variantId: 1, name: 'num', value: 100 }
{ action: 'setAttribute', variantId: 1, name: 'count', value: 'two' }
{ action: 'setAttribute', variantId: 1, name: 'size', value: 'small' }
{ action: 'setAttribute', variantId: 1, name: 'color', value: 'blue' }
{ action: 'setAttribute', variantId: 1, name: 'cost', value: { centAmount: 550, currencyCode: 'EUR' } }
]
expect(update).toEqual expected_update
it 'should build actions for attributes with long text as values', ->
newVariant =
id: 1
sku: 'HARJPUL101601202'
attributes: [
{
name: 'images',
value: '//dceroyf7rfc0x.cloudfront.net/product/images/390x520/a/arj/po/HARJPUL101601-1.jpg;//dceroyf7rfc0x.cloudfront.net/product/images/390x520/a/arj/po/HARJPUL101601-2.jpg;//dceroyf7rfc0x.cloudfront.net/product/images/390x520/a/arj/po/HARJPUL101601-4.jpg;//dceroyf7rfc0x.cloudfront.net/product/images/390x520/a/arj/po/HARJPUL101601-5.jpg'
},
{
name: 'textAttribute',
value: '[{"textAttributeValue":{"fr-CH":"","de-CH":"","it-CH":"","de-DE":"<p><strong>Some random text to make this longer than the value that was in jsondiffpatch.textDiff.minLength = 300. This should be now a correctly formatted JSON. However, after jsondiffpatch, it will be changed into a different string”</p>","en-GB":"","es-ES":"","fr-FR":""}}]'
},
{
name: 'localized_images',
value: {
en: '//dceroyf7rfc0x.cloudfront.net/product/images/390x520/a/arj/po/HARJPUL101601-1.jpg;//dceroyf7rfc0x.cloudfront.net/product/images/390x520/a/arj/po/HARJPUL101601-2.jpg;//dceroyf7rfc0x.cloudfront.net/product/images/390x520/a/arj/po/HARJPUL101601-4.jpg;//dceroyf7rfc0x.cloudfront.net/product/images/390x520/a/arj/po/HARJPUL101601-5.jpg'
}
}
]
prices: []
images: []
oldVariant =
id: 1
sku: 'HARJPUL101601202'
attributes: [
{
name: 'images',
value: 'http://images.luxodo.com/html/zoom/luxodo/p-HARJPUL101601-1/2000/2000/p-HARJPUL101601-1.jpg;http://images.luxodo.com/html/zoom/luxodo/p-HARJPUL101601-2/2000/2000/p-HARJPUL101601-2.jpg;http://images.luxodo.com/html/zoom/luxodo/p-HARJPUL101601-4/2000/2000/p-HARJPUL101601-4.jpg;http://images.luxodo.com/html/zoom/luxodo/p-HARJPUL101601-5/2000/2000/p-HARJPUL101601-5.jpg'
},
{
name: 'textAttribute',
value: '[{"textAttributeValue":{"fr-CH":"","de-CH":"","it-CH":"","de-DE":"<p><strong>Some random text to make this longer than the value that was in jsondiffpatch.textDiff.minLength = 300. Also this will be badly formatted JSON”</p>","en-GB":"","es-ES":"","fr-FR":""fr-CH":"","fr-FR": "","it-IT": "","nl-NL": "","ru-RU": ""},"testberichte_video": ""}]'
},
{
name: 'localized_images',
value: {
en: 'http://images.luxodo.com/html/zoom/luxodo/p-HARJPUL101601-1/2000/2000/p-HARJPUL101601-1.jpg;http://images.luxodo.com/html/zoom/luxodo/p-HARJPUL101601-2/2000/2000/p-HARJPUL101601-2.jpg;http://images.luxodo.com/html/zoom/luxodo/p-HARJPUL101601-4/2000/2000/p-HARJPUL101601-4.jpg;http://images.luxodo.com/html/zoom/luxodo/p-HARJPUL101601-5/2000/2000/p-HARJPUL101601-5.jpg'
}
}
]
prices: []
images: []
diff = @utils.diff oldVariant, newVariant
update = @utils.buildVariantAttributesActions diff.attributes, oldVariant, newVariant
expected_update =
[
{ action: 'setAttribute', sku: 'HARJPUL101601202', name: 'images', value: '//dceroyf7rfc0x.cloudfront.net/product/images/390x520/a/arj/po/HARJPUL101601-1.jpg;//dceroyf7rfc0x.cloudfront.net/product/images/390x520/a/arj/po/HARJPUL101601-2.jpg;//dceroyf7rfc0x.cloudfront.net/product/images/390x520/a/arj/po/HARJPUL101601-4.jpg;//dceroyf7rfc0x.cloudfront.net/product/images/390x520/a/arj/po/HARJPUL101601-5.jpg' },
{ action: 'setAttribute', sku: 'HARJPUL101601202', name: 'textAttribute', value: '[{"textAttributeValue":{"fr-CH":"","de-CH":"","it-CH":"","de-DE":"<p><strong>Some random text to make this longer than the value that was in jsondiffpatch.textDiff.minLength = 300. This should be now a correctly formatted JSON. However, after jsondiffpatch, it will be changed into a different string”</p>","en-GB":"","es-ES":"","fr-FR":""}}]' },
{ action: 'setAttribute', sku: 'HARJPUL101601202', name: 'localized_images', value: { en: '//dceroyf7rfc0x.cloudfront.net/product/images/390x520/a/arj/po/HARJPUL101601-1.jpg;//dceroyf7rfc0x.cloudfront.net/product/images/390x520/a/arj/po/HARJPUL101601-2.jpg;//dceroyf7rfc0x.cloudfront.net/product/images/390x520/a/arj/po/HARJPUL101601-4.jpg;//dceroyf7rfc0x.cloudfront.net/product/images/390x520/a/arj/po/HARJPUL101601-5.jpg' } }
]
expect(update).toEqual expected_update
it 'should not create update action if attribute is not changed', ->
oldVariant =
sku: 'TEST MASTER VARIANT'
attributes: [
{
name: 'test_attribute',
value: [
{
label: {
'de': 'schwarz'
},
key: 'SW'
},
{
label: {
'de': 'grün'
},
key: 'GN'
}
]
}
]
newVariant =
sku: 'TEST MASTER VARIANT'
attributes: [
{
'name': 'test_attribute',
'value': [
{
'label': {
'de': 'grün'
},
'key': 'GN'
},
{
'label': {
'de': 'schwarz'
},
'key': 'SW'
}
]
}
]
diff = @utils.diff oldVariant, newVariant
update = @utils.buildVariantAttributesActions diff.attributes, oldVariant, newVariant
expect(update.length).toBe(0)
it 'should create update action if attribute value item is removed', ->
newVariant =
sku: 'TEST MASTER VARIANT'
attributes: [
{
'name': 'test_attribute',
'value': [
'a', 'b'
]
}
]
oldVariant =
sku: 'TEST MASTER VARIANT'
attributes: [
{
name: 'test_attribute',
value: [
'a', 'b', 'c'
]
}
]
diff = @utils.diff oldVariant, newVariant
update = @utils.buildVariantAttributesActions diff.attributes, oldVariant, newVariant
expect(update.length).toBe(1)
expect(update[0].action).toBe 'setAttribute'
expect(update[0].name).toBe 'test_attribute'
expect(update[0].value).toEqual [ 'a', 'b' ]
it 'should create update action if attribute value item is added', ->
newVariant =
sku: 'TEST MASTER VARIANT'
attributes: [
{
'name': 'test_attribute',
'value': [
'a', 'b', 'c'
]
}
]
oldVariant =
sku: 'TEST MASTER VARIANT'
attributes: [
{
name: 'test_attribute',
value: [
'a', 'b'
]
}
]
diff = @utils.diff oldVariant, newVariant
update = @utils.buildVariantAttributesActions diff.attributes, oldVariant, newVariant
expect(update.length).toBe(1)
expect(update[0].action).toBe 'setAttribute'
expect(update[0].name).toBe 'test_attribute'
expect(update[0].value).toEqual [ 'a', 'b', 'c' ]
describe ':: actionsMapReferences', ->
describe ':: tax-category', ->
beforeEach ->
@utils = new ProductUtils
@OLD_REFERENCE =
id: '123'
taxCategory:
typeId: 'tax-category'
id: 'tax-de'
masterVariant:
id: 1
@NEW_REFERENCE =
id: '123'
taxCategory:
typeId: 'tax-category'
id: 'tax-us'
masterVariant:
id: 1
it 'should build action to change tax-category', ->
delta = @utils.diff @OLD_REFERENCE, @NEW_REFERENCE
update = @utils.actionsMapReferences delta, @NEW_REFERENCE, @OLD_REFERENCE
expected_update = [
{ action: 'setTaxCategory', taxCategory: { typeId: 'tax-category', id: 'tax-us' } }
]
expect(update).toEqual expected_update
it 'should build action to delete tax-category', ->
delete @NEW_REFERENCE.taxCategory
delta = @utils.diff @OLD_REFERENCE, @NEW_REFERENCE
update = @utils.actionsMapReferences delta, @NEW_REFERENCE, @OLD_REFERENCE
expected_update = [
{ action: 'setTaxCategory' }
]
expect(update).toEqual expected_update
it 'should build action to add tax-category', ->
delete @OLD_REFERENCE.taxCategory
delta = @utils.diff @OLD_REFERENCE, @NEW_REFERENCE
update = @utils.actionsMapReferences delta, @NEW_REFERENCE, @OLD_REFERENCE
expected_update = [
{ action: 'setTaxCategory', taxCategory: { typeId: 'tax-category', id: 'tax-us' } }
]
expect(update).toEqual expected_update
describe ':: state', ->
beforeEach ->
@utils = new ProductUtils
@OLD_REFERENCE =
id: '123'
state:
typeId: 'state'
id: 'old-state-id'
masterVariant:
id: 1
@NEW_REFERENCE =
id: '123'
state:
typeId: 'state'
id: 'new-state-id'
masterVariant:
id: 1
it 'should build a transitionState action for the initial state', ->
oldRef = _.extend({}, @OLD_REFERENCE, { state: null })
delta = @utils.diff oldRef, @NEW_REFERENCE
actual = @utils.actionsMapReferences(
delta, @NEW_REFERENCE, oldRef
)
expected = [{
action: 'transitionState',
state: { typeId: 'state', id: 'new-state-id' }
}]
expect(actual).toEqual(expected)
it 'should not build a transitionState action if no state is provided
even if the product already has a state', ->
# test with { state: null }
newRef = _.extend({}, @NEW_REFERENCE, { state: null })
delta = @utils.diff @OLD_REFERENCE, newRef
actual = @utils.actionsMapReferences(
delta, newRef, @OLD_REFERENCE
)
expected = []
expect(actual).toEqual(expected)
# test without state
delete newRef.state
delta = @utils.diff @OLD_REFERENCE, newRef
actual = @utils.actionsMapReferences(
delta, newRef, @OLD_REFERENCE
)
expected = []
expect(actual).toEqual(expected)
it 'should build a transitionState action for a state change', ->
delta = @utils.diff @OLD_REFERENCE, @NEW_REFERENCE
actual = @utils.actionsMapReferences(
delta, @NEW_REFERENCE, @OLD_REFERENCE
)
expected = [{
action: 'transitionState',
state: { typeId: 'state', id: 'new-state-id' }
}]
expect(actual).toEqual(expected)
describe ':: actionsMapCategories (category)', ->
beforeEach ->
@utils = new ProductUtils
@OLD_REFERENCE =
id: '123'
categories: [
{ typeId: 'category', id: 'cat1' }
{ typeId: 'category', id: 'cat2' }
]
masterVariant:
id: 1
@NEW_REFERENCE =
id: '123'
categories: [
{ typeId: 'category', id: 'cat1' }
{ typeId: 'category', id: 'cat3' }
]
masterVariant:
id: 1
it 'should build actions to change category', ->
delta = @utils.diff @OLD_REFERENCE, @NEW_REFERENCE
update = @utils.actionsMapCategories delta, @OLD_REFERENCE, @NEW_REFERENCE
expected_update = [
{ action: 'removeFromCategory', category: { typeId: 'category', id: 'cat2' } }
{ action: 'addToCategory', category: { typeId: 'category', id: 'cat3' } }
]
expect(update).toEqual expected_update
it 'should ignore changes in ordering of category references', ->
before =
id: '123'
categories: [
{ typeId: 'category', id: 'cat1' }
{ typeId: 'category', id: 'cat2' }
]
masterVariant:
id: 1
after =
id: '123'
categories: [
{ typeId: 'category', id: 'cat2' }
{ typeId: 'category', id: 'cat1' }
]
masterVariant:
id: 1
delta = @utils.diff before, after
update = @utils.actionsMapCategories delta, before, after
expect(update).toEqual []
| 122244 | _ = require 'underscore'
_.mixin require 'underscore-mixins'
ProductUtils = require '../../../lib/sync/utils/product'
###
Match different product attributes and variant prices
###
OLD_PRODUCT =
id: '123'
name:
en: '<NAME>'
de: '<NAME>'
slug:
en: 'sapphire1366126441922'
description:
en: 'Sample description'
masterVariant:
id: 1
prices: [
{ id: 'p-1', value: { currencyCode: 'EUR', centAmount: 1 } }
{ id: 'p-2', value: { currencyCode: 'EUR', centAmount: 7 } }
]
variants: [
{
id: 2
prices: [
{ id: 'p-3', value: { currencyCode: 'USD', centAmount: 3 } }
]
},
{
id: 3
prices: [
{ id: 'p-4', value: { currencyCode: 'EUR', centAmount: 2100 }, country: 'DE' }
{ id: 'p-5', value: { currencyCode: 'EUR', centAmount: 2200 }, customerGroup: { id: '123', typeId: 'customer-group' } }
]
},
{
id: 4
prices: [
{ id: 'p-6', value: { currencyCode: 'YEN', centAmount: 7777 } }
]
},
{
id: 5
prices: []
}
]
NEW_PRODUCT =
id: '123'
name:
en: 'Foo'
it: 'Boo'
slug:
en: 'foo'
it: 'boo'
masterVariant:
id: 1
prices: [
{ value: { currencyCode: 'EUR', centAmount: 2 } }
{ value: { currencyCode: 'USD', centAmount: 7 } }
]
variants: [
{
id: 2
prices: [
{ value: { currencyCode: 'USD', centAmount: 3 } }
]
},
{
id: 3
prices: [
{ value: { currencyCode: 'EUR', centAmount: 2100 }, country: 'CH' }
{ value: { currencyCode: 'EUR', centAmount: 2200 }, customerGroup: { id: '987', typeId: 'customer-group' } }
]
},
{
id: 4
prices: []
},
{
id: 5
prices: [
{ value: { currencyCode: 'EUR', centAmount: 999 } }
]
}
]
###
Match all different attributes types
###
OLD_ALL_ATTRIBUTES =
id: '123'
masterVariant:
id: 1
attributes: [
{ name: 'foo', value: 'bar' } # text
{ name: 'dog', value: {en: 'Dog', de: 'Hund', es: 'perro' } } # ltext
{ name: 'num', value: 50 } # number
{ name: 'count', value: { label: 'One', key: 'one' } } # enum
{ name: 'size', value: { label: {en: 'Size'}, key: 'medium' } } # lenum
{ name: 'color', value: { label: {en: 'Color'}, key: 'red' } } # lenum
{ name: 'cost', value: { centAmount: 990, currencyCode: 'EUR' } } # money
]
NEW_ALL_ATTRIBUTES =
id: '123'
masterVariant:
id: 1
attributes: [
{ name: 'foo', value: 'qux' } # text
{ name: 'dog', value: {en: 'Doggy', it: 'Cane', es: 'perro' } } # ltext
{ name: 'num', value: 100 } # number
{ name: 'count', value: 'two' } # enum
{ name: 'size', value: 'small' } # lenum
{ name: 'color', value: 'blue' } # lenum
{ name: 'cost', value: { centAmount: 550, currencyCode: 'EUR' } } # money
]
describe 'ProductUtils', ->
beforeEach ->
@utils = new ProductUtils
describe ':: diff', ->
it 'should diff nothing', ->
delta = @utils.diff({id: '123', masterVariant: { id: 1 }}, {id: '123', masterVariant: { id: 1 }})
expect(delta).not.toBeDefined()
it 'should use SKU to compare variants', ->
OLD =
id: 'xyz'
masterVariant: {
id: 1
sku: 'mySKU1'
}
variants: [
{ id: 3, sku: 'mySKU2' }
]
NEW =
id: 'xyz'
masterVariant: {
id: 1,
sku: 'mySKU2'
}
variants: [
{ id: 2, sku: 'mySKU1' }
]
delta = @utils.diff(OLD, NEW)
expected_delta =
masterVariant:
sku: [ 'mySKU1', 'mySKU2' ]
_MATCH_CRITERIA: [ 'mySKU1', 'mySKU2' ]
variants:
0: [
{
id: 2
sku: 'mySKU1'
_MATCH_CRITERIA: 'mySKU1'
_NEW_ARRAY_INDEX: '0'
}
]
_t: 'a'
_0: [
{
id: 3
sku: 'mySKU2'
_MATCH_CRITERIA: 'mySKU2'
_EXISTING_ARRAY_INDEX: '0'
},
0,
0
]
expect(delta).toEqual expected_delta
it 'should throw an Error if variant has no ID nor SKU', ->
OLD =
id: 'xyz'
variants: [
{attributes: [foo: 'bar']}
]
NEW =
id: 'xyz'
masterVariant:
attributes: [foo: 'bar']
expect(=> @utils.diff(OLD, NEW)).toThrow new Error 'A variant must either have an ID or an SKU.'
it 'should diff basic attributes (name, slug, description, searchKeywords)', ->
OLD =
id: '123'
name:
en: '<NAME>'
de: '<NAME>oo'
slug:
en: 'foo'
description:
en: 'Sample'
searchKeywords:
en: [ {text: 'old'}, {text: 'keywords'} ]
de: [ {text: 'alte'}, {text: 'schlagwoerter'} ]
masterVariant:
id: 1
NEW =
id: '123'
name:
en: 'Boo'
slug:
en: 'boo'
description:
en: 'Sample'
it: 'Esempio'
searchKeywords:
en: [ {text: 'new'}, {text: 'keywords'} ]
it: [ {text: 'veccie'}, {text: 'parole'} ]
masterVariant:
id: 1
delta = @utils.diff(OLD, NEW)
expected_delta =
name:
en: ['Foo', 'Boo']
de: ['Hoo', 0, 0 ]
slug:
en: ['foo', 'boo']
description:
it: ['Esempio']
searchKeywords:
en : 0 : [ { text : 'new' } ], 1 : [ { text : 'keywords' } ], _t : 'a', _0 : [ { text : 'old' }, 0, 0 ], _1 : [ { text : 'keywords' }, 0, 0 ]
de : [ [ { text : 'alte' }, { text : 'schlagwoerter' } ], 0, 0 ]
it: [[ {text: 'veccie'}, {text: 'parole'} ]]
expect(delta).toEqual expected_delta
it 'should diff missing attribute', ->
delta = @utils.diff(OLD_PRODUCT, NEW_PRODUCT)
expected_delta =
name:
en: ['<NAME>', '<NAME>'] # changed
de: ['Hoo', 0, 0]
it: ['Boo']
slug:
en: ['sapphire1366126441922', 'foo']
it: ['boo']
description: [en: 'Sample description', 0, 0] # deleted
masterVariant:
prices:
0:
id: ['p-1', 0,0]
value:
centAmount: [1, 2]
1:
id: ['p-2', 0,0]
value:
currencyCode: ['EUR', 'USD']
_t: 'a'
variants:
0:
prices:
0:
id: ['p-3', 0, 0]
_t: 'a'
_EXISTING_ARRAY_INDEX: ['0', 0, 0],
_NEW_ARRAY_INDEX: ['0']
1:
prices:
0:
id: ['p-4', 0, 0],
country: ['DE', 'CH']
1:
id: ['p-5', 0, 0],
customerGroup:
id: ['123', '987']
_t: 'a'
_EXISTING_ARRAY_INDEX: ['1', 0, 0],
_NEW_ARRAY_INDEX: ['1']
2:
prices:
_t: 'a',
_0: [{
id: 'p-6',
value:
currencyCode: 'YEN',
centAmount: 7777
_MATCH_CRITERIA: '0'
}, 0, 0]
_EXISTING_ARRAY_INDEX: ['2', 0, 0],
_NEW_ARRAY_INDEX: ['2']
3:
prices:
0: [{
value:
currencyCode: 'EUR',
centAmount: 999
_MATCH_CRITERIA: '0'
}],
_t: 'a'
_EXISTING_ARRAY_INDEX: ['3', 0, 0],
_NEW_ARRAY_INDEX: ['3']
_t: 'a'
expect(delta).toEqual expected_delta
it 'should diff different attribute types', ->
delta = @utils.diff(OLD_ALL_ATTRIBUTES, NEW_ALL_ATTRIBUTES)
expected_delta =
masterVariant:
attributes:
0: { value: ['bar', 'qux'] }
1:
value:
en: ['Dog', 'Doggy']
it: ['Cane']
de: ['Hund', 0, 0]
2: { value: [50, 100] }
3: { value: ['one', 'two'] }
4: { value: ['medium', 'small'] }
5: { value: ['red', 'blue'] }
6: { value: { centAmount: [990, 550] } }
_t: 'a'
expect(delta).toEqual expected_delta
it 'should patch enums', ->
EXISTING_ENUM_ATTRIBUTES =
id: 'enum-101'
masterVariant:
id: 1
attributes: [
{ name: 'count', value: { label: 'My Key', key: '<KEY>Key' } } # enum
{ name: 'size', value: { label: { en: 'Size' }, key: '<KEY>' } } # lenum
{ name: 'color', value: { label: { de: 'Farbe' }, key: 'red' } } # lenum
]
variants: [
{ id: 2, attributes: [
{ name: 'tags', value: [ { label: { en: 'Tags1' }, key: 'tag1' } ] } # lenum
]}
]
NEW_ENUM_ATTRIBUTES =
id: 'enum-101'
masterVariant:
id: 1
attributes: [
{ name: 'count', value: 'myKey' } # enum - unchanged
{ name: 'size', value: 'small' } # lenum - changed key
# color is removed
]
variants: [
{ id: 2, attributes: [
{ name: 'tags', value: [ { label: { en: 'Tags2' }, key: '<KEY>2' } ] } # lenum
]}
]
delta = @utils.diff(EXISTING_ENUM_ATTRIBUTES, NEW_ENUM_ATTRIBUTES)
expected_delta =
masterVariant:
attributes:
1: { value: ['big', 'small'] }
_t: 'a'
_2: [ { name: 'color', value: 'red'}, 0, 0 ]
variants:
0:
attributes:
0:
value:
0: ['tag2']
_t: 'a'
_0: ['tag1', 0, 0]
_t: 'a'
_NEW_ARRAY_INDEX: ['0']
_EXISTING_ARRAY_INDEX: ['0', 0, 0]
_t: 'a'
expect(delta).toEqual expected_delta
describe ':: buildRemoveVariantActions', ->
it 'should throw an error when removing a variant without id and sku', ->
oldVariants = [
{
# no id or sku
key: 'newVar'
}
]
newVariants = []
expect( () => @utils.buildRemoveVariantActions(newVariants, oldVariants))
.toThrow new Error('ProductSync does need at least one of "id" or "sku" to generate a remove action')
it 'should throw an error when removing a variant without id and sku', ->
oldVariants = [
{
# no id - use sku in removeVariant action
sku: 'newVar'
}
]
newVariants = []
actions = @utils.buildRemoveVariantActions(newVariants, oldVariants)
expect(actions).toEqual([
{ action: 'removeVariant', sku: 'newVar' }
])
describe ':: findVariantInList', ->
it 'should find variant using sku', ->
oldVariants = [
{
id: 1
sku: 'sku1'
},
{
id: 2
sku: 'sku2'
}
]
newVariant = {
id: 2,
sku: 'sku1'
}
actions = @utils.findVariantInList(newVariant, oldVariants)
expect(actions).toEqual({
id: 1
sku: 'sku1'
})
it 'should find variant using id', ->
oldVariants = [
{
id: 1
sku: 'sku1'
},
{
id: 2,
key: 'key'
}
]
newVariant = {
id: 2,
}
actions = @utils.findVariantInList(newVariant, oldVariants)
expect(actions).toEqual({
id: 2
key: 'key'
})
it 'should find variant using key', ->
oldVariants = [
{
id: 1
sku: 'key1'
},
{
id: 2,
key: 'key2'
}
]
newVariant = {
id: 1,
key: 'key2',
}
actions = @utils.findVariantInList(newVariant, oldVariants)
expect(actions).toEqual({
id: 2
key: 'key2'
})
it 'should not find an unknown variant', ->
oldVariants = [
{
id: 1
sku: 'key1'
},
{
id: 2,
key: 'key2'
}
]
newVariant = {
id: 29,
key: 'key3',
}
actions = @utils.findVariantInList(newVariant, oldVariants)
expect(actions).toEqual(undefined)
it 'should not find variant if sku does not match', ->
variant = {
id: 1,
sku: 3
}
variantList = [
{
id: 1,
sku: 'sku1'
},
{
id: 21,
sku: 'sku2'
}
]
foundVariant = @utils.findVariantInList(variant, variantList, 'sku')
expect(foundVariant).not.toBeDefined()
it 'should match variants with sku', ->
variant = {
id: 2,
sku: 'sku2'
}
variantList = [
{
id: 1,
sku: 'sku1'
},
{
id: 3,
sku: 'sku2'
}
]
foundVariant = @utils.findVariantInList(variant, variantList, 'sku')
expect(foundVariant).toEqual({ id: 3, sku: 'sku2' })
it 'should match variants with keys', ->
variant = {
id: 2,
key: 'key2'
}
variantList = [
{
id: 1,
key: 'key1'
},
{
id: 3,
key: 'key2'
}
]
foundVariant = @utils.findVariantInList(variant, variantList, 'key')
expect(foundVariant).toEqual({ id: 3, key: 'key2' })
it 'should match variants with ids', ->
variant = {
id: 2
}
variantList = [
{
id: 1
},
{
id: 2
}
]
foundVariant = @utils.findVariantInList(variant, variantList, 'id')
expect(foundVariant).toEqual({ id: 2 })
describe ':: buildVariantPriceActions', ->
it 'should return an empty array when no price diff is provided', ->
actions = @utils.buildVariantPriceActions(null, {}, {})
expect(actions).toEqual []
describe ':: buildChangeMasterVariantAction', ->
it 'should throw an error when changing a masterVariant without id and sku', ->
newMasterVariant =
key: 'newVar'
oldMasterVariant =
key: 'oldVar'
expect( () => @utils.buildChangeMasterVariantAction(newMasterVariant, oldMasterVariant))
.toThrow new Error('ProductSync needs at least one of "id" or "sku" to generate "changeMasterVariant" update action')
describe ':: buildVariantBaseAction', ->
it 'should build update actions for variant base properties', ->
oldVariant =
id: '123'
newVariant =
id: '123'
sku: 'sku123'
key: 'key<KEY>'
delta = @utils.diff oldVariant, newVariant
update = @utils.buildVariantBaseAction(delta, oldVariant)
expected_update = [
{ action : 'setSku', variantId : '123', sku : 'sku123' }
{ action : 'setProductVariantKey', variantId : '123', key : '<KEY>' }
]
expect(update).toEqual expected_update
describe ':: _buildAddExternalImageAction', ->
it 'should not process an undefined image when adding', ->
update = @utils._buildAddExternalImageAction({}, null)
expect(update).toEqual undefined
describe ':: _buildRemoveImageAction', ->
it 'should not process an undefined image when removing', ->
update = @utils._buildRemoveImageAction({}, null)
expect(update).toEqual undefined
describe ':: actionsMapBase', ->
it 'should diff if basic attribute is undefined', ->
OLD =
key: 'oldKey'
id: '123'
name:
en: 'Foo'
slug:
en: 'foo'
masterVariant:
id: 1
NEW =
key: 'newKey'
id: '123'
name:
de: '<NAME>'
slug:
en: 'boo'
description:
en: 'Sample'
it: 'Esempio'
searchKeywords:
en: [ {text: 'new'}, {text: 'keyword'} ]
masterVariant:
id: 1
delta = @utils.diff OLD, NEW
update = @utils.actionsMapBase(delta, OLD)
expected_update = [
{ action: 'setKey', key: 'newKey' }
{ action: 'changeName', name: {en: undefined, de: 'B<NAME>'} }
{ action: 'changeSlug', slug: {en: 'boo'} }
{ action: 'setDescription', description: {en: 'Sample', it: 'Esempio'} }
{ action: 'setSearchKeywords', searchKeywords: {en: [ {text: 'new'}, {text: 'keyword'} ]} }
]
expect(update).toEqual expected_update
it 'should diff long text', ->
OLD =
id: '123'
name:
en: '`<NAME>` talked about climbing a wall which is leaning toward you and kissing a woman who is leaning away from you.'
slug:
en: 'churchill-talked-about-climbing-a-wall-which-is-leaning-toward-you-and-kissing-a-woman-who-is-leaning-away-from-you'
description:
en: 'There are two things that are more difficult than making an after-dinner speech: climbing a wall which is leaning toward you and kissing a girl who is leaning away from you.'
masterVariant:
id: 1
NEW =
id: '123'
name:
en: '`<NAME>` talked about climbing a BIG wall which WAS leaning toward you and kissing a woman who WAS leaning away from you.'
slug:
en: 'churchill-talked-about-climbing-a-big-wall-which-was-leaning-toward-you-and-kissing-a-woman-who-was-leaning-away-from-you'
description:
en: 'There are three things that are more difficult than making an after-dinner speech: climbing a mountain which is leaning toward you and slapping a girl who is leaning away from you.'
masterVariant:
id: 1
delta = @utils.diff OLD, NEW
update = @utils.actionsMapBase(delta, OLD)
expected_update = [
{ action: 'changeName', name: {en: NEW.name.en} }
{ action: 'changeSlug', slug: {en: NEW.slug.en} }
{ action: 'setDescription', description: {en: NEW.description.en} }
]
expect(update).toEqual expected_update
it 'should diff meta attributes', ->
OLD =
id: '123'
metaTitle:
en: 'A title'
metaDescription:
en: 'A description'
metaKeywords:
en: 'foo, bar'
masterVariant:
id: 1
NEW =
id: '123'
metaTitle:
en: 'A new title'
metaDescription:
en: 'A new description'
metaKeywords:
en: 'foo, bar, qux'
masterVariant:
id: 1
delta = @utils.diff OLD, NEW
update = @utils.actionsMapBase(delta, OLD)
expected_update = [
{
action: 'setMetaTitle'
metaTitle: {en: 'A new title'}
}
{
action: 'setMetaDescription'
metaDescription: {en: 'A new description'}
}
{
action: 'setMetaKeywords'
metaKeywords: {en: 'foo, bar, qux'}
}
]
expect(update).toEqual expected_update
it 'should transform setCategoryOrderHint actions correctly', ->
OLD =
id: '123'
masterVariant:
id: 1
categoryOrderHints:
abc: '0.9'
NEW =
id: '123'
masterVariant:
id: 1
categoryOrderHints:
abc: '0.3'
anotherCategoryId: '0.1'
delta = @utils.diff OLD, NEW
update = @utils.actionsMapCategoryOrderHints(delta, OLD)
expected_update = [
{
action: 'setCategoryOrderHint'
categoryId: 'abc'
orderHint: '0.3'
}, {
action: 'setCategoryOrderHint'
categoryId: 'anotherCategoryId'
orderHint: '0.1'
},
]
expect(update).toEqual expected_update
it 'should generate a setCategoryOrderHint action to unset order hints', ->
OLD =
id: '123'
masterVariant:
id: 1
categoryOrderHints:
abc: '0.9'
anotherCategoryId: '0.5'
categoryId: '0.5'
NEW =
id: '123'
masterVariant:
id: 1
categoryOrderHints:
abc: null
anotherCategoryId: '0'
categoryId: ''
delta = @utils.diff OLD, NEW
update = @utils.actionsMapCategoryOrderHints(delta, OLD)
expected_update = [
{
action: 'setCategoryOrderHint'
categoryId: 'abc',
orderHint: undefined,
},
{
action: 'setCategoryOrderHint'
categoryId: 'anotherCategoryId',
orderHint: '0',
}
{
action: 'setCategoryOrderHint'
categoryId: 'categoryId',
orderHint: undefined,
}
]
expect(update).toEqual expected_update
it 'should should not create an action if categoryOrderHint is empty', ->
OLD =
id: '123'
categoryOrderHints: {}
metaTitle:
en: 'A title'
masterVariant:
id: 1
NEW =
id: '123'
metaTitle:
en: 'A new title'
masterVariant:
id: 1
delta = @utils.diff OLD, NEW
update = @utils.actionsMapBase(delta, OLD)
expected_update = [
{
action: 'setMetaTitle'
metaTitle: {en: 'A new title'}
}
]
expect(update).toEqual expected_update
describe ':: actionsMapAttributes', ->
it 'should create update action for attribute', ->
_oldVariant = {
id: 3, attributes: [{ name: 'foo', value: 'bar' }]
}
_newVariant = {
id: 3, attributes: [{ name: 'foo', value: 'CHANGED' }]
}
diff = @utils.diff _oldVariant, _newVariant
update = @utils.buildVariantAttributesActions diff.attributes, _oldVariant, _newVariant
expected_update = [
{ action: 'setAttribute', variantId: 3, name: 'foo', value: 'CHANGED' }
]
expect(update).toEqual expected_update
it 'should build attribute update actions for all types', ->
oldVariant = OLD_ALL_ATTRIBUTES.masterVariant
newVariant = NEW_ALL_ATTRIBUTES.masterVariant
diff = @utils.diff oldVariant, newVariant
update = @utils.buildVariantAttributesActions diff.attributes, oldVariant, newVariant
expected_update =
[
{ action: 'setAttribute', variantId: 1, name: 'foo', value: 'qux' }
{ action: 'setAttribute', variantId: 1, name: 'dog', value: {en: 'Doggy', it: 'Cane', de: undefined, es: 'perro'} }
{ action: 'setAttribute', variantId: 1, name: 'num', value: 100 }
{ action: 'setAttribute', variantId: 1, name: 'count', value: 'two' }
{ action: 'setAttribute', variantId: 1, name: 'size', value: 'small' }
{ action: 'setAttribute', variantId: 1, name: 'color', value: 'blue' }
{ action: 'setAttribute', variantId: 1, name: 'cost', value: { centAmount: 550, currencyCode: 'EUR' } }
]
expect(update).toEqual expected_update
it 'should build actions for attributes with long text as values', ->
newVariant =
id: 1
sku: 'HARJPUL101601202'
attributes: [
{
name: 'images',
value: '//dceroyf7rfc0x.cloudfront.net/product/images/390x520/a/arj/po/HARJPUL101601-1.jpg;//dceroyf7rfc0x.cloudfront.net/product/images/390x520/a/arj/po/HARJPUL101601-2.jpg;//dceroyf7rfc0x.cloudfront.net/product/images/390x520/a/arj/po/HARJPUL101601-4.jpg;//dceroyf7rfc0x.cloudfront.net/product/images/390x520/a/arj/po/HARJPUL101601-5.jpg'
},
{
name: 'textAttribute',
value: '[{"textAttributeValue":{"fr-CH":"","de-CH":"","it-CH":"","de-DE":"<p><strong>Some random text to make this longer than the value that was in jsondiffpatch.textDiff.minLength = 300. This should be now a correctly formatted JSON. However, after jsondiffpatch, it will be changed into a different string”</p>","en-GB":"","es-ES":"","fr-FR":""}}]'
},
{
name: 'localized_images',
value: {
en: '//dceroyf7rfc0x.cloudfront.net/product/images/390x520/a/arj/po/HARJPUL101601-1.jpg;//dceroyf7rfc0x.cloudfront.net/product/images/390x520/a/arj/po/HARJPUL101601-2.jpg;//dceroyf7rfc0x.cloudfront.net/product/images/390x520/a/arj/po/HARJPUL101601-4.jpg;//dceroyf7rfc0x.cloudfront.net/product/images/390x520/a/arj/po/HARJPUL101601-5.jpg'
}
}
]
prices: []
images: []
oldVariant =
id: 1
sku: 'HARJPUL101601202'
attributes: [
{
name: 'images',
value: 'http://images.luxodo.com/html/zoom/luxodo/p-HARJPUL101601-1/2000/2000/p-HARJPUL101601-1.jpg;http://images.luxodo.com/html/zoom/luxodo/p-HARJPUL101601-2/2000/2000/p-HARJPUL101601-2.jpg;http://images.luxodo.com/html/zoom/luxodo/p-HARJPUL101601-4/2000/2000/p-HARJPUL101601-4.jpg;http://images.luxodo.com/html/zoom/luxodo/p-HARJPUL101601-5/2000/2000/p-HARJPUL101601-5.jpg'
},
{
name: 'textAttribute',
value: '[{"textAttributeValue":{"fr-CH":"","de-CH":"","it-CH":"","de-DE":"<p><strong>Some random text to make this longer than the value that was in jsondiffpatch.textDiff.minLength = 300. Also this will be badly formatted JSON”</p>","en-GB":"","es-ES":"","fr-FR":""fr-CH":"","fr-FR": "","it-IT": "","nl-NL": "","ru-RU": ""},"testberichte_video": ""}]'
},
{
name: 'localized_images',
value: {
en: 'http://images.luxodo.com/html/zoom/luxodo/p-HARJPUL101601-1/2000/2000/p-HARJPUL101601-1.jpg;http://images.luxodo.com/html/zoom/luxodo/p-HARJPUL101601-2/2000/2000/p-HARJPUL101601-2.jpg;http://images.luxodo.com/html/zoom/luxodo/p-HARJPUL101601-4/2000/2000/p-HARJPUL101601-4.jpg;http://images.luxodo.com/html/zoom/luxodo/p-HARJPUL101601-5/2000/2000/p-HARJPUL101601-5.jpg'
}
}
]
prices: []
images: []
diff = @utils.diff oldVariant, newVariant
update = @utils.buildVariantAttributesActions diff.attributes, oldVariant, newVariant
expected_update =
[
{ action: 'setAttribute', sku: 'HARJPUL101601202', name: 'images', value: '//dceroyf7rfc0x.cloudfront.net/product/images/390x520/a/arj/po/HARJPUL101601-1.jpg;//dceroyf7rfc0x.cloudfront.net/product/images/390x520/a/arj/po/HARJPUL101601-2.jpg;//dceroyf7rfc0x.cloudfront.net/product/images/390x520/a/arj/po/HARJPUL101601-4.jpg;//dceroyf7rfc0x.cloudfront.net/product/images/390x520/a/arj/po/HARJPUL101601-5.jpg' },
{ action: 'setAttribute', sku: 'HARJPUL101601202', name: 'textAttribute', value: '[{"textAttributeValue":{"fr-CH":"","de-CH":"","it-CH":"","de-DE":"<p><strong>Some random text to make this longer than the value that was in jsondiffpatch.textDiff.minLength = 300. This should be now a correctly formatted JSON. However, after jsondiffpatch, it will be changed into a different string”</p>","en-GB":"","es-ES":"","fr-FR":""}}]' },
{ action: 'setAttribute', sku: 'HARJPUL101601202', name: 'localized_images', value: { en: '//dceroyf7rfc0x.cloudfront.net/product/images/390x520/a/arj/po/HARJPUL101601-1.jpg;//dceroyf7rfc0x.cloudfront.net/product/images/390x520/a/arj/po/HARJPUL101601-2.jpg;//dceroyf7rfc0x.cloudfront.net/product/images/390x520/a/arj/po/HARJPUL101601-4.jpg;//dceroyf7rfc0x.cloudfront.net/product/images/390x520/a/arj/po/HARJPUL101601-5.jpg' } }
]
expect(update).toEqual expected_update
it 'should not create update action if attribute is not changed', ->
oldVariant =
sku: 'TEST MASTER VARIANT'
attributes: [
{
name: 'test_attribute',
value: [
{
label: {
'de': 'schwarz'
},
key: 'SW'
},
{
label: {
'de': 'grün'
},
key: 'GN'
}
]
}
]
newVariant =
sku: 'TEST MASTER VARIANT'
attributes: [
{
'name': 'test_attribute',
'value': [
{
'label': {
'de': 'grün'
},
'key': 'GN'
},
{
'label': {
'de': 'schwarz'
},
'key': 'SW'
}
]
}
]
diff = @utils.diff oldVariant, newVariant
update = @utils.buildVariantAttributesActions diff.attributes, oldVariant, newVariant
expect(update.length).toBe(0)
it 'should create update action if attribute value item is removed', ->
newVariant =
sku: 'TEST MASTER VARIANT'
attributes: [
{
'name': 'test_attribute',
'value': [
'a', 'b'
]
}
]
oldVariant =
sku: 'TEST MASTER VARIANT'
attributes: [
{
name: 'test_attribute',
value: [
'a', 'b', 'c'
]
}
]
diff = @utils.diff oldVariant, newVariant
update = @utils.buildVariantAttributesActions diff.attributes, oldVariant, newVariant
expect(update.length).toBe(1)
expect(update[0].action).toBe 'setAttribute'
expect(update[0].name).toBe 'test_attribute'
expect(update[0].value).toEqual [ 'a', 'b' ]
it 'should create update action if attribute value item is added', ->
newVariant =
sku: 'TEST MASTER VARIANT'
attributes: [
{
'name': 'test_attribute',
'value': [
'a', 'b', 'c'
]
}
]
oldVariant =
sku: 'TEST MASTER VARIANT'
attributes: [
{
name: 'test_attribute',
value: [
'a', 'b'
]
}
]
diff = @utils.diff oldVariant, newVariant
update = @utils.buildVariantAttributesActions diff.attributes, oldVariant, newVariant
expect(update.length).toBe(1)
expect(update[0].action).toBe 'setAttribute'
expect(update[0].name).toBe 'test_attribute'
expect(update[0].value).toEqual [ 'a', 'b', 'c' ]
describe ':: actionsMapReferences', ->
describe ':: tax-category', ->
beforeEach ->
@utils = new ProductUtils
@OLD_REFERENCE =
id: '123'
taxCategory:
typeId: 'tax-category'
id: 'tax-de'
masterVariant:
id: 1
@NEW_REFERENCE =
id: '123'
taxCategory:
typeId: 'tax-category'
id: 'tax-us'
masterVariant:
id: 1
it 'should build action to change tax-category', ->
delta = @utils.diff @OLD_REFERENCE, @NEW_REFERENCE
update = @utils.actionsMapReferences delta, @NEW_REFERENCE, @OLD_REFERENCE
expected_update = [
{ action: 'setTaxCategory', taxCategory: { typeId: 'tax-category', id: 'tax-us' } }
]
expect(update).toEqual expected_update
it 'should build action to delete tax-category', ->
delete @NEW_REFERENCE.taxCategory
delta = @utils.diff @OLD_REFERENCE, @NEW_REFERENCE
update = @utils.actionsMapReferences delta, @NEW_REFERENCE, @OLD_REFERENCE
expected_update = [
{ action: 'setTaxCategory' }
]
expect(update).toEqual expected_update
it 'should build action to add tax-category', ->
delete @OLD_REFERENCE.taxCategory
delta = @utils.diff @OLD_REFERENCE, @NEW_REFERENCE
update = @utils.actionsMapReferences delta, @NEW_REFERENCE, @OLD_REFERENCE
expected_update = [
{ action: 'setTaxCategory', taxCategory: { typeId: 'tax-category', id: 'tax-us' } }
]
expect(update).toEqual expected_update
describe ':: state', ->
beforeEach ->
@utils = new ProductUtils
@OLD_REFERENCE =
id: '123'
state:
typeId: 'state'
id: 'old-state-id'
masterVariant:
id: 1
@NEW_REFERENCE =
id: '123'
state:
typeId: 'state'
id: 'new-state-id'
masterVariant:
id: 1
it 'should build a transitionState action for the initial state', ->
oldRef = _.extend({}, @OLD_REFERENCE, { state: null })
delta = @utils.diff oldRef, @NEW_REFERENCE
actual = @utils.actionsMapReferences(
delta, @NEW_REFERENCE, oldRef
)
expected = [{
action: 'transitionState',
state: { typeId: 'state', id: 'new-state-id' }
}]
expect(actual).toEqual(expected)
it 'should not build a transitionState action if no state is provided
even if the product already has a state', ->
# test with { state: null }
newRef = _.extend({}, @NEW_REFERENCE, { state: null })
delta = @utils.diff @OLD_REFERENCE, newRef
actual = @utils.actionsMapReferences(
delta, newRef, @OLD_REFERENCE
)
expected = []
expect(actual).toEqual(expected)
# test without state
delete newRef.state
delta = @utils.diff @OLD_REFERENCE, newRef
actual = @utils.actionsMapReferences(
delta, newRef, @OLD_REFERENCE
)
expected = []
expect(actual).toEqual(expected)
it 'should build a transitionState action for a state change', ->
delta = @utils.diff @OLD_REFERENCE, @NEW_REFERENCE
actual = @utils.actionsMapReferences(
delta, @NEW_REFERENCE, @OLD_REFERENCE
)
expected = [{
action: 'transitionState',
state: { typeId: 'state', id: 'new-state-id' }
}]
expect(actual).toEqual(expected)
describe ':: actionsMapCategories (category)', ->
beforeEach ->
@utils = new ProductUtils
@OLD_REFERENCE =
id: '123'
categories: [
{ typeId: 'category', id: 'cat1' }
{ typeId: 'category', id: 'cat2' }
]
masterVariant:
id: 1
@NEW_REFERENCE =
id: '123'
categories: [
{ typeId: 'category', id: 'cat1' }
{ typeId: 'category', id: 'cat3' }
]
masterVariant:
id: 1
it 'should build actions to change category', ->
delta = @utils.diff @OLD_REFERENCE, @NEW_REFERENCE
update = @utils.actionsMapCategories delta, @OLD_REFERENCE, @NEW_REFERENCE
expected_update = [
{ action: 'removeFromCategory', category: { typeId: 'category', id: 'cat2' } }
{ action: 'addToCategory', category: { typeId: 'category', id: 'cat3' } }
]
expect(update).toEqual expected_update
it 'should ignore changes in ordering of category references', ->
before =
id: '123'
categories: [
{ typeId: 'category', id: 'cat1' }
{ typeId: 'category', id: 'cat2' }
]
masterVariant:
id: 1
after =
id: '123'
categories: [
{ typeId: 'category', id: 'cat2' }
{ typeId: 'category', id: 'cat1' }
]
masterVariant:
id: 1
delta = @utils.diff before, after
update = @utils.actionsMapCategories delta, before, after
expect(update).toEqual []
| true | _ = require 'underscore'
_.mixin require 'underscore-mixins'
ProductUtils = require '../../../lib/sync/utils/product'
###
Match different product attributes and variant prices
###
OLD_PRODUCT =
id: '123'
name:
en: 'PI:NAME:<NAME>END_PI'
de: 'PI:NAME:<NAME>END_PI'
slug:
en: 'sapphire1366126441922'
description:
en: 'Sample description'
masterVariant:
id: 1
prices: [
{ id: 'p-1', value: { currencyCode: 'EUR', centAmount: 1 } }
{ id: 'p-2', value: { currencyCode: 'EUR', centAmount: 7 } }
]
variants: [
{
id: 2
prices: [
{ id: 'p-3', value: { currencyCode: 'USD', centAmount: 3 } }
]
},
{
id: 3
prices: [
{ id: 'p-4', value: { currencyCode: 'EUR', centAmount: 2100 }, country: 'DE' }
{ id: 'p-5', value: { currencyCode: 'EUR', centAmount: 2200 }, customerGroup: { id: '123', typeId: 'customer-group' } }
]
},
{
id: 4
prices: [
{ id: 'p-6', value: { currencyCode: 'YEN', centAmount: 7777 } }
]
},
{
id: 5
prices: []
}
]
NEW_PRODUCT =
id: '123'
name:
en: 'Foo'
it: 'Boo'
slug:
en: 'foo'
it: 'boo'
masterVariant:
id: 1
prices: [
{ value: { currencyCode: 'EUR', centAmount: 2 } }
{ value: { currencyCode: 'USD', centAmount: 7 } }
]
variants: [
{
id: 2
prices: [
{ value: { currencyCode: 'USD', centAmount: 3 } }
]
},
{
id: 3
prices: [
{ value: { currencyCode: 'EUR', centAmount: 2100 }, country: 'CH' }
{ value: { currencyCode: 'EUR', centAmount: 2200 }, customerGroup: { id: '987', typeId: 'customer-group' } }
]
},
{
id: 4
prices: []
},
{
id: 5
prices: [
{ value: { currencyCode: 'EUR', centAmount: 999 } }
]
}
]
###
Match all different attributes types
###
OLD_ALL_ATTRIBUTES =
id: '123'
masterVariant:
id: 1
attributes: [
{ name: 'foo', value: 'bar' } # text
{ name: 'dog', value: {en: 'Dog', de: 'Hund', es: 'perro' } } # ltext
{ name: 'num', value: 50 } # number
{ name: 'count', value: { label: 'One', key: 'one' } } # enum
{ name: 'size', value: { label: {en: 'Size'}, key: 'medium' } } # lenum
{ name: 'color', value: { label: {en: 'Color'}, key: 'red' } } # lenum
{ name: 'cost', value: { centAmount: 990, currencyCode: 'EUR' } } # money
]
NEW_ALL_ATTRIBUTES =
id: '123'
masterVariant:
id: 1
attributes: [
{ name: 'foo', value: 'qux' } # text
{ name: 'dog', value: {en: 'Doggy', it: 'Cane', es: 'perro' } } # ltext
{ name: 'num', value: 100 } # number
{ name: 'count', value: 'two' } # enum
{ name: 'size', value: 'small' } # lenum
{ name: 'color', value: 'blue' } # lenum
{ name: 'cost', value: { centAmount: 550, currencyCode: 'EUR' } } # money
]
describe 'ProductUtils', ->
beforeEach ->
@utils = new ProductUtils
describe ':: diff', ->
it 'should diff nothing', ->
delta = @utils.diff({id: '123', masterVariant: { id: 1 }}, {id: '123', masterVariant: { id: 1 }})
expect(delta).not.toBeDefined()
it 'should use SKU to compare variants', ->
OLD =
id: 'xyz'
masterVariant: {
id: 1
sku: 'mySKU1'
}
variants: [
{ id: 3, sku: 'mySKU2' }
]
NEW =
id: 'xyz'
masterVariant: {
id: 1,
sku: 'mySKU2'
}
variants: [
{ id: 2, sku: 'mySKU1' }
]
delta = @utils.diff(OLD, NEW)
expected_delta =
masterVariant:
sku: [ 'mySKU1', 'mySKU2' ]
_MATCH_CRITERIA: [ 'mySKU1', 'mySKU2' ]
variants:
0: [
{
id: 2
sku: 'mySKU1'
_MATCH_CRITERIA: 'mySKU1'
_NEW_ARRAY_INDEX: '0'
}
]
_t: 'a'
_0: [
{
id: 3
sku: 'mySKU2'
_MATCH_CRITERIA: 'mySKU2'
_EXISTING_ARRAY_INDEX: '0'
},
0,
0
]
expect(delta).toEqual expected_delta
it 'should throw an Error if variant has no ID nor SKU', ->
OLD =
id: 'xyz'
variants: [
{attributes: [foo: 'bar']}
]
NEW =
id: 'xyz'
masterVariant:
attributes: [foo: 'bar']
expect(=> @utils.diff(OLD, NEW)).toThrow new Error 'A variant must either have an ID or an SKU.'
it 'should diff basic attributes (name, slug, description, searchKeywords)', ->
OLD =
id: '123'
name:
en: 'PI:NAME:<NAME>END_PI'
de: 'PI:NAME:<NAME>END_PIoo'
slug:
en: 'foo'
description:
en: 'Sample'
searchKeywords:
en: [ {text: 'old'}, {text: 'keywords'} ]
de: [ {text: 'alte'}, {text: 'schlagwoerter'} ]
masterVariant:
id: 1
NEW =
id: '123'
name:
en: 'Boo'
slug:
en: 'boo'
description:
en: 'Sample'
it: 'Esempio'
searchKeywords:
en: [ {text: 'new'}, {text: 'keywords'} ]
it: [ {text: 'veccie'}, {text: 'parole'} ]
masterVariant:
id: 1
delta = @utils.diff(OLD, NEW)
expected_delta =
name:
en: ['Foo', 'Boo']
de: ['Hoo', 0, 0 ]
slug:
en: ['foo', 'boo']
description:
it: ['Esempio']
searchKeywords:
en : 0 : [ { text : 'new' } ], 1 : [ { text : 'keywords' } ], _t : 'a', _0 : [ { text : 'old' }, 0, 0 ], _1 : [ { text : 'keywords' }, 0, 0 ]
de : [ [ { text : 'alte' }, { text : 'schlagwoerter' } ], 0, 0 ]
it: [[ {text: 'veccie'}, {text: 'parole'} ]]
expect(delta).toEqual expected_delta
it 'should diff missing attribute', ->
delta = @utils.diff(OLD_PRODUCT, NEW_PRODUCT)
expected_delta =
name:
en: ['PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI'] # changed
de: ['Hoo', 0, 0]
it: ['Boo']
slug:
en: ['sapphire1366126441922', 'foo']
it: ['boo']
description: [en: 'Sample description', 0, 0] # deleted
masterVariant:
prices:
0:
id: ['p-1', 0,0]
value:
centAmount: [1, 2]
1:
id: ['p-2', 0,0]
value:
currencyCode: ['EUR', 'USD']
_t: 'a'
variants:
0:
prices:
0:
id: ['p-3', 0, 0]
_t: 'a'
_EXISTING_ARRAY_INDEX: ['0', 0, 0],
_NEW_ARRAY_INDEX: ['0']
1:
prices:
0:
id: ['p-4', 0, 0],
country: ['DE', 'CH']
1:
id: ['p-5', 0, 0],
customerGroup:
id: ['123', '987']
_t: 'a'
_EXISTING_ARRAY_INDEX: ['1', 0, 0],
_NEW_ARRAY_INDEX: ['1']
2:
prices:
_t: 'a',
_0: [{
id: 'p-6',
value:
currencyCode: 'YEN',
centAmount: 7777
_MATCH_CRITERIA: '0'
}, 0, 0]
_EXISTING_ARRAY_INDEX: ['2', 0, 0],
_NEW_ARRAY_INDEX: ['2']
3:
prices:
0: [{
value:
currencyCode: 'EUR',
centAmount: 999
_MATCH_CRITERIA: '0'
}],
_t: 'a'
_EXISTING_ARRAY_INDEX: ['3', 0, 0],
_NEW_ARRAY_INDEX: ['3']
_t: 'a'
expect(delta).toEqual expected_delta
it 'should diff different attribute types', ->
delta = @utils.diff(OLD_ALL_ATTRIBUTES, NEW_ALL_ATTRIBUTES)
expected_delta =
masterVariant:
attributes:
0: { value: ['bar', 'qux'] }
1:
value:
en: ['Dog', 'Doggy']
it: ['Cane']
de: ['Hund', 0, 0]
2: { value: [50, 100] }
3: { value: ['one', 'two'] }
4: { value: ['medium', 'small'] }
5: { value: ['red', 'blue'] }
6: { value: { centAmount: [990, 550] } }
_t: 'a'
expect(delta).toEqual expected_delta
it 'should patch enums', ->
EXISTING_ENUM_ATTRIBUTES =
id: 'enum-101'
masterVariant:
id: 1
attributes: [
{ name: 'count', value: { label: 'My Key', key: 'PI:KEY:<KEY>END_PIKey' } } # enum
{ name: 'size', value: { label: { en: 'Size' }, key: 'PI:KEY:<KEY>END_PI' } } # lenum
{ name: 'color', value: { label: { de: 'Farbe' }, key: 'red' } } # lenum
]
variants: [
{ id: 2, attributes: [
{ name: 'tags', value: [ { label: { en: 'Tags1' }, key: 'tag1' } ] } # lenum
]}
]
NEW_ENUM_ATTRIBUTES =
id: 'enum-101'
masterVariant:
id: 1
attributes: [
{ name: 'count', value: 'myKey' } # enum - unchanged
{ name: 'size', value: 'small' } # lenum - changed key
# color is removed
]
variants: [
{ id: 2, attributes: [
{ name: 'tags', value: [ { label: { en: 'Tags2' }, key: 'PI:KEY:<KEY>END_PI2' } ] } # lenum
]}
]
delta = @utils.diff(EXISTING_ENUM_ATTRIBUTES, NEW_ENUM_ATTRIBUTES)
expected_delta =
masterVariant:
attributes:
1: { value: ['big', 'small'] }
_t: 'a'
_2: [ { name: 'color', value: 'red'}, 0, 0 ]
variants:
0:
attributes:
0:
value:
0: ['tag2']
_t: 'a'
_0: ['tag1', 0, 0]
_t: 'a'
_NEW_ARRAY_INDEX: ['0']
_EXISTING_ARRAY_INDEX: ['0', 0, 0]
_t: 'a'
expect(delta).toEqual expected_delta
describe ':: buildRemoveVariantActions', ->
it 'should throw an error when removing a variant without id and sku', ->
oldVariants = [
{
# no id or sku
key: 'newVar'
}
]
newVariants = []
expect( () => @utils.buildRemoveVariantActions(newVariants, oldVariants))
.toThrow new Error('ProductSync does need at least one of "id" or "sku" to generate a remove action')
it 'should throw an error when removing a variant without id and sku', ->
oldVariants = [
{
# no id - use sku in removeVariant action
sku: 'newVar'
}
]
newVariants = []
actions = @utils.buildRemoveVariantActions(newVariants, oldVariants)
expect(actions).toEqual([
{ action: 'removeVariant', sku: 'newVar' }
])
describe ':: findVariantInList', ->
it 'should find variant using sku', ->
oldVariants = [
{
id: 1
sku: 'sku1'
},
{
id: 2
sku: 'sku2'
}
]
newVariant = {
id: 2,
sku: 'sku1'
}
actions = @utils.findVariantInList(newVariant, oldVariants)
expect(actions).toEqual({
id: 1
sku: 'sku1'
})
it 'should find variant using id', ->
oldVariants = [
{
id: 1
sku: 'sku1'
},
{
id: 2,
key: 'key'
}
]
newVariant = {
id: 2,
}
actions = @utils.findVariantInList(newVariant, oldVariants)
expect(actions).toEqual({
id: 2
key: 'key'
})
it 'should find variant using key', ->
oldVariants = [
{
id: 1
sku: 'key1'
},
{
id: 2,
key: 'key2'
}
]
newVariant = {
id: 1,
key: 'key2',
}
actions = @utils.findVariantInList(newVariant, oldVariants)
expect(actions).toEqual({
id: 2
key: 'key2'
})
it 'should not find an unknown variant', ->
oldVariants = [
{
id: 1
sku: 'key1'
},
{
id: 2,
key: 'key2'
}
]
newVariant = {
id: 29,
key: 'key3',
}
actions = @utils.findVariantInList(newVariant, oldVariants)
expect(actions).toEqual(undefined)
it 'should not find variant if sku does not match', ->
variant = {
id: 1,
sku: 3
}
variantList = [
{
id: 1,
sku: 'sku1'
},
{
id: 21,
sku: 'sku2'
}
]
foundVariant = @utils.findVariantInList(variant, variantList, 'sku')
expect(foundVariant).not.toBeDefined()
it 'should match variants with sku', ->
variant = {
id: 2,
sku: 'sku2'
}
variantList = [
{
id: 1,
sku: 'sku1'
},
{
id: 3,
sku: 'sku2'
}
]
foundVariant = @utils.findVariantInList(variant, variantList, 'sku')
expect(foundVariant).toEqual({ id: 3, sku: 'sku2' })
it 'should match variants with keys', ->
variant = {
id: 2,
key: 'key2'
}
variantList = [
{
id: 1,
key: 'key1'
},
{
id: 3,
key: 'key2'
}
]
foundVariant = @utils.findVariantInList(variant, variantList, 'key')
expect(foundVariant).toEqual({ id: 3, key: 'key2' })
it 'should match variants with ids', ->
variant = {
id: 2
}
variantList = [
{
id: 1
},
{
id: 2
}
]
foundVariant = @utils.findVariantInList(variant, variantList, 'id')
expect(foundVariant).toEqual({ id: 2 })
describe ':: buildVariantPriceActions', ->
it 'should return an empty array when no price diff is provided', ->
actions = @utils.buildVariantPriceActions(null, {}, {})
expect(actions).toEqual []
describe ':: buildChangeMasterVariantAction', ->
it 'should throw an error when changing a masterVariant without id and sku', ->
newMasterVariant =
key: 'newVar'
oldMasterVariant =
key: 'oldVar'
expect( () => @utils.buildChangeMasterVariantAction(newMasterVariant, oldMasterVariant))
.toThrow new Error('ProductSync needs at least one of "id" or "sku" to generate "changeMasterVariant" update action')
describe ':: buildVariantBaseAction', ->
it 'should build update actions for variant base properties', ->
oldVariant =
id: '123'
newVariant =
id: '123'
sku: 'sku123'
key: 'keyPI:KEY:<KEY>END_PI'
delta = @utils.diff oldVariant, newVariant
update = @utils.buildVariantBaseAction(delta, oldVariant)
expected_update = [
{ action : 'setSku', variantId : '123', sku : 'sku123' }
{ action : 'setProductVariantKey', variantId : '123', key : 'PI:KEY:<KEY>END_PI' }
]
expect(update).toEqual expected_update
describe ':: _buildAddExternalImageAction', ->
it 'should not process an undefined image when adding', ->
update = @utils._buildAddExternalImageAction({}, null)
expect(update).toEqual undefined
describe ':: _buildRemoveImageAction', ->
it 'should not process an undefined image when removing', ->
update = @utils._buildRemoveImageAction({}, null)
expect(update).toEqual undefined
describe ':: actionsMapBase', ->
it 'should diff if basic attribute is undefined', ->
OLD =
key: 'oldKey'
id: '123'
name:
en: 'Foo'
slug:
en: 'foo'
masterVariant:
id: 1
NEW =
key: 'newKey'
id: '123'
name:
de: 'PI:NAME:<NAME>END_PI'
slug:
en: 'boo'
description:
en: 'Sample'
it: 'Esempio'
searchKeywords:
en: [ {text: 'new'}, {text: 'keyword'} ]
masterVariant:
id: 1
delta = @utils.diff OLD, NEW
update = @utils.actionsMapBase(delta, OLD)
expected_update = [
{ action: 'setKey', key: 'newKey' }
{ action: 'changeName', name: {en: undefined, de: 'BPI:NAME:<NAME>END_PI'} }
{ action: 'changeSlug', slug: {en: 'boo'} }
{ action: 'setDescription', description: {en: 'Sample', it: 'Esempio'} }
{ action: 'setSearchKeywords', searchKeywords: {en: [ {text: 'new'}, {text: 'keyword'} ]} }
]
expect(update).toEqual expected_update
it 'should diff long text', ->
OLD =
id: '123'
name:
en: '`PI:NAME:<NAME>END_PI` talked about climbing a wall which is leaning toward you and kissing a woman who is leaning away from you.'
slug:
en: 'churchill-talked-about-climbing-a-wall-which-is-leaning-toward-you-and-kissing-a-woman-who-is-leaning-away-from-you'
description:
en: 'There are two things that are more difficult than making an after-dinner speech: climbing a wall which is leaning toward you and kissing a girl who is leaning away from you.'
masterVariant:
id: 1
NEW =
id: '123'
name:
en: '`PI:NAME:<NAME>END_PI` talked about climbing a BIG wall which WAS leaning toward you and kissing a woman who WAS leaning away from you.'
slug:
en: 'churchill-talked-about-climbing-a-big-wall-which-was-leaning-toward-you-and-kissing-a-woman-who-was-leaning-away-from-you'
description:
en: 'There are three things that are more difficult than making an after-dinner speech: climbing a mountain which is leaning toward you and slapping a girl who is leaning away from you.'
masterVariant:
id: 1
delta = @utils.diff OLD, NEW
update = @utils.actionsMapBase(delta, OLD)
expected_update = [
{ action: 'changeName', name: {en: NEW.name.en} }
{ action: 'changeSlug', slug: {en: NEW.slug.en} }
{ action: 'setDescription', description: {en: NEW.description.en} }
]
expect(update).toEqual expected_update
it 'should diff meta attributes', ->
OLD =
id: '123'
metaTitle:
en: 'A title'
metaDescription:
en: 'A description'
metaKeywords:
en: 'foo, bar'
masterVariant:
id: 1
NEW =
id: '123'
metaTitle:
en: 'A new title'
metaDescription:
en: 'A new description'
metaKeywords:
en: 'foo, bar, qux'
masterVariant:
id: 1
delta = @utils.diff OLD, NEW
update = @utils.actionsMapBase(delta, OLD)
expected_update = [
{
action: 'setMetaTitle'
metaTitle: {en: 'A new title'}
}
{
action: 'setMetaDescription'
metaDescription: {en: 'A new description'}
}
{
action: 'setMetaKeywords'
metaKeywords: {en: 'foo, bar, qux'}
}
]
expect(update).toEqual expected_update
it 'should transform setCategoryOrderHint actions correctly', ->
OLD =
id: '123'
masterVariant:
id: 1
categoryOrderHints:
abc: '0.9'
NEW =
id: '123'
masterVariant:
id: 1
categoryOrderHints:
abc: '0.3'
anotherCategoryId: '0.1'
delta = @utils.diff OLD, NEW
update = @utils.actionsMapCategoryOrderHints(delta, OLD)
expected_update = [
{
action: 'setCategoryOrderHint'
categoryId: 'abc'
orderHint: '0.3'
}, {
action: 'setCategoryOrderHint'
categoryId: 'anotherCategoryId'
orderHint: '0.1'
},
]
expect(update).toEqual expected_update
it 'should generate a setCategoryOrderHint action to unset order hints', ->
OLD =
id: '123'
masterVariant:
id: 1
categoryOrderHints:
abc: '0.9'
anotherCategoryId: '0.5'
categoryId: '0.5'
NEW =
id: '123'
masterVariant:
id: 1
categoryOrderHints:
abc: null
anotherCategoryId: '0'
categoryId: ''
delta = @utils.diff OLD, NEW
update = @utils.actionsMapCategoryOrderHints(delta, OLD)
expected_update = [
{
action: 'setCategoryOrderHint'
categoryId: 'abc',
orderHint: undefined,
},
{
action: 'setCategoryOrderHint'
categoryId: 'anotherCategoryId',
orderHint: '0',
}
{
action: 'setCategoryOrderHint'
categoryId: 'categoryId',
orderHint: undefined,
}
]
expect(update).toEqual expected_update
it 'should should not create an action if categoryOrderHint is empty', ->
OLD =
id: '123'
categoryOrderHints: {}
metaTitle:
en: 'A title'
masterVariant:
id: 1
NEW =
id: '123'
metaTitle:
en: 'A new title'
masterVariant:
id: 1
delta = @utils.diff OLD, NEW
update = @utils.actionsMapBase(delta, OLD)
expected_update = [
{
action: 'setMetaTitle'
metaTitle: {en: 'A new title'}
}
]
expect(update).toEqual expected_update
describe ':: actionsMapAttributes', ->
it 'should create update action for attribute', ->
_oldVariant = {
id: 3, attributes: [{ name: 'foo', value: 'bar' }]
}
_newVariant = {
id: 3, attributes: [{ name: 'foo', value: 'CHANGED' }]
}
diff = @utils.diff _oldVariant, _newVariant
update = @utils.buildVariantAttributesActions diff.attributes, _oldVariant, _newVariant
expected_update = [
{ action: 'setAttribute', variantId: 3, name: 'foo', value: 'CHANGED' }
]
expect(update).toEqual expected_update
it 'should build attribute update actions for all types', ->
oldVariant = OLD_ALL_ATTRIBUTES.masterVariant
newVariant = NEW_ALL_ATTRIBUTES.masterVariant
diff = @utils.diff oldVariant, newVariant
update = @utils.buildVariantAttributesActions diff.attributes, oldVariant, newVariant
expected_update =
[
{ action: 'setAttribute', variantId: 1, name: 'foo', value: 'qux' }
{ action: 'setAttribute', variantId: 1, name: 'dog', value: {en: 'Doggy', it: 'Cane', de: undefined, es: 'perro'} }
{ action: 'setAttribute', variantId: 1, name: 'num', value: 100 }
{ action: 'setAttribute', variantId: 1, name: 'count', value: 'two' }
{ action: 'setAttribute', variantId: 1, name: 'size', value: 'small' }
{ action: 'setAttribute', variantId: 1, name: 'color', value: 'blue' }
{ action: 'setAttribute', variantId: 1, name: 'cost', value: { centAmount: 550, currencyCode: 'EUR' } }
]
expect(update).toEqual expected_update
it 'should build actions for attributes with long text as values', ->
newVariant =
id: 1
sku: 'HARJPUL101601202'
attributes: [
{
name: 'images',
value: '//dceroyf7rfc0x.cloudfront.net/product/images/390x520/a/arj/po/HARJPUL101601-1.jpg;//dceroyf7rfc0x.cloudfront.net/product/images/390x520/a/arj/po/HARJPUL101601-2.jpg;//dceroyf7rfc0x.cloudfront.net/product/images/390x520/a/arj/po/HARJPUL101601-4.jpg;//dceroyf7rfc0x.cloudfront.net/product/images/390x520/a/arj/po/HARJPUL101601-5.jpg'
},
{
name: 'textAttribute',
value: '[{"textAttributeValue":{"fr-CH":"","de-CH":"","it-CH":"","de-DE":"<p><strong>Some random text to make this longer than the value that was in jsondiffpatch.textDiff.minLength = 300. This should be now a correctly formatted JSON. However, after jsondiffpatch, it will be changed into a different string”</p>","en-GB":"","es-ES":"","fr-FR":""}}]'
},
{
name: 'localized_images',
value: {
en: '//dceroyf7rfc0x.cloudfront.net/product/images/390x520/a/arj/po/HARJPUL101601-1.jpg;//dceroyf7rfc0x.cloudfront.net/product/images/390x520/a/arj/po/HARJPUL101601-2.jpg;//dceroyf7rfc0x.cloudfront.net/product/images/390x520/a/arj/po/HARJPUL101601-4.jpg;//dceroyf7rfc0x.cloudfront.net/product/images/390x520/a/arj/po/HARJPUL101601-5.jpg'
}
}
]
prices: []
images: []
oldVariant =
id: 1
sku: 'HARJPUL101601202'
attributes: [
{
name: 'images',
value: 'http://images.luxodo.com/html/zoom/luxodo/p-HARJPUL101601-1/2000/2000/p-HARJPUL101601-1.jpg;http://images.luxodo.com/html/zoom/luxodo/p-HARJPUL101601-2/2000/2000/p-HARJPUL101601-2.jpg;http://images.luxodo.com/html/zoom/luxodo/p-HARJPUL101601-4/2000/2000/p-HARJPUL101601-4.jpg;http://images.luxodo.com/html/zoom/luxodo/p-HARJPUL101601-5/2000/2000/p-HARJPUL101601-5.jpg'
},
{
name: 'textAttribute',
value: '[{"textAttributeValue":{"fr-CH":"","de-CH":"","it-CH":"","de-DE":"<p><strong>Some random text to make this longer than the value that was in jsondiffpatch.textDiff.minLength = 300. Also this will be badly formatted JSON”</p>","en-GB":"","es-ES":"","fr-FR":""fr-CH":"","fr-FR": "","it-IT": "","nl-NL": "","ru-RU": ""},"testberichte_video": ""}]'
},
{
name: 'localized_images',
value: {
en: 'http://images.luxodo.com/html/zoom/luxodo/p-HARJPUL101601-1/2000/2000/p-HARJPUL101601-1.jpg;http://images.luxodo.com/html/zoom/luxodo/p-HARJPUL101601-2/2000/2000/p-HARJPUL101601-2.jpg;http://images.luxodo.com/html/zoom/luxodo/p-HARJPUL101601-4/2000/2000/p-HARJPUL101601-4.jpg;http://images.luxodo.com/html/zoom/luxodo/p-HARJPUL101601-5/2000/2000/p-HARJPUL101601-5.jpg'
}
}
]
prices: []
images: []
diff = @utils.diff oldVariant, newVariant
update = @utils.buildVariantAttributesActions diff.attributes, oldVariant, newVariant
expected_update =
[
{ action: 'setAttribute', sku: 'HARJPUL101601202', name: 'images', value: '//dceroyf7rfc0x.cloudfront.net/product/images/390x520/a/arj/po/HARJPUL101601-1.jpg;//dceroyf7rfc0x.cloudfront.net/product/images/390x520/a/arj/po/HARJPUL101601-2.jpg;//dceroyf7rfc0x.cloudfront.net/product/images/390x520/a/arj/po/HARJPUL101601-4.jpg;//dceroyf7rfc0x.cloudfront.net/product/images/390x520/a/arj/po/HARJPUL101601-5.jpg' },
{ action: 'setAttribute', sku: 'HARJPUL101601202', name: 'textAttribute', value: '[{"textAttributeValue":{"fr-CH":"","de-CH":"","it-CH":"","de-DE":"<p><strong>Some random text to make this longer than the value that was in jsondiffpatch.textDiff.minLength = 300. This should be now a correctly formatted JSON. However, after jsondiffpatch, it will be changed into a different string”</p>","en-GB":"","es-ES":"","fr-FR":""}}]' },
{ action: 'setAttribute', sku: 'HARJPUL101601202', name: 'localized_images', value: { en: '//dceroyf7rfc0x.cloudfront.net/product/images/390x520/a/arj/po/HARJPUL101601-1.jpg;//dceroyf7rfc0x.cloudfront.net/product/images/390x520/a/arj/po/HARJPUL101601-2.jpg;//dceroyf7rfc0x.cloudfront.net/product/images/390x520/a/arj/po/HARJPUL101601-4.jpg;//dceroyf7rfc0x.cloudfront.net/product/images/390x520/a/arj/po/HARJPUL101601-5.jpg' } }
]
expect(update).toEqual expected_update
it 'should not create update action if attribute is not changed', ->
oldVariant =
sku: 'TEST MASTER VARIANT'
attributes: [
{
name: 'test_attribute',
value: [
{
label: {
'de': 'schwarz'
},
key: 'SW'
},
{
label: {
'de': 'grün'
},
key: 'GN'
}
]
}
]
newVariant =
sku: 'TEST MASTER VARIANT'
attributes: [
{
'name': 'test_attribute',
'value': [
{
'label': {
'de': 'grün'
},
'key': 'GN'
},
{
'label': {
'de': 'schwarz'
},
'key': 'SW'
}
]
}
]
diff = @utils.diff oldVariant, newVariant
update = @utils.buildVariantAttributesActions diff.attributes, oldVariant, newVariant
expect(update.length).toBe(0)
it 'should create update action if attribute value item is removed', ->
newVariant =
sku: 'TEST MASTER VARIANT'
attributes: [
{
'name': 'test_attribute',
'value': [
'a', 'b'
]
}
]
oldVariant =
sku: 'TEST MASTER VARIANT'
attributes: [
{
name: 'test_attribute',
value: [
'a', 'b', 'c'
]
}
]
diff = @utils.diff oldVariant, newVariant
update = @utils.buildVariantAttributesActions diff.attributes, oldVariant, newVariant
expect(update.length).toBe(1)
expect(update[0].action).toBe 'setAttribute'
expect(update[0].name).toBe 'test_attribute'
expect(update[0].value).toEqual [ 'a', 'b' ]
it 'should create update action if attribute value item is added', ->
newVariant =
sku: 'TEST MASTER VARIANT'
attributes: [
{
'name': 'test_attribute',
'value': [
'a', 'b', 'c'
]
}
]
oldVariant =
sku: 'TEST MASTER VARIANT'
attributes: [
{
name: 'test_attribute',
value: [
'a', 'b'
]
}
]
diff = @utils.diff oldVariant, newVariant
update = @utils.buildVariantAttributesActions diff.attributes, oldVariant, newVariant
expect(update.length).toBe(1)
expect(update[0].action).toBe 'setAttribute'
expect(update[0].name).toBe 'test_attribute'
expect(update[0].value).toEqual [ 'a', 'b', 'c' ]
describe ':: actionsMapReferences', ->
describe ':: tax-category', ->
beforeEach ->
@utils = new ProductUtils
@OLD_REFERENCE =
id: '123'
taxCategory:
typeId: 'tax-category'
id: 'tax-de'
masterVariant:
id: 1
@NEW_REFERENCE =
id: '123'
taxCategory:
typeId: 'tax-category'
id: 'tax-us'
masterVariant:
id: 1
it 'should build action to change tax-category', ->
delta = @utils.diff @OLD_REFERENCE, @NEW_REFERENCE
update = @utils.actionsMapReferences delta, @NEW_REFERENCE, @OLD_REFERENCE
expected_update = [
{ action: 'setTaxCategory', taxCategory: { typeId: 'tax-category', id: 'tax-us' } }
]
expect(update).toEqual expected_update
it 'should build action to delete tax-category', ->
delete @NEW_REFERENCE.taxCategory
delta = @utils.diff @OLD_REFERENCE, @NEW_REFERENCE
update = @utils.actionsMapReferences delta, @NEW_REFERENCE, @OLD_REFERENCE
expected_update = [
{ action: 'setTaxCategory' }
]
expect(update).toEqual expected_update
it 'should build action to add tax-category', ->
delete @OLD_REFERENCE.taxCategory
delta = @utils.diff @OLD_REFERENCE, @NEW_REFERENCE
update = @utils.actionsMapReferences delta, @NEW_REFERENCE, @OLD_REFERENCE
expected_update = [
{ action: 'setTaxCategory', taxCategory: { typeId: 'tax-category', id: 'tax-us' } }
]
expect(update).toEqual expected_update
describe ':: state', ->
beforeEach ->
@utils = new ProductUtils
@OLD_REFERENCE =
id: '123'
state:
typeId: 'state'
id: 'old-state-id'
masterVariant:
id: 1
@NEW_REFERENCE =
id: '123'
state:
typeId: 'state'
id: 'new-state-id'
masterVariant:
id: 1
it 'should build a transitionState action for the initial state', ->
oldRef = _.extend({}, @OLD_REFERENCE, { state: null })
delta = @utils.diff oldRef, @NEW_REFERENCE
actual = @utils.actionsMapReferences(
delta, @NEW_REFERENCE, oldRef
)
expected = [{
action: 'transitionState',
state: { typeId: 'state', id: 'new-state-id' }
}]
expect(actual).toEqual(expected)
it 'should not build a transitionState action if no state is provided
even if the product already has a state', ->
# test with { state: null }
newRef = _.extend({}, @NEW_REFERENCE, { state: null })
delta = @utils.diff @OLD_REFERENCE, newRef
actual = @utils.actionsMapReferences(
delta, newRef, @OLD_REFERENCE
)
expected = []
expect(actual).toEqual(expected)
# test without state
delete newRef.state
delta = @utils.diff @OLD_REFERENCE, newRef
actual = @utils.actionsMapReferences(
delta, newRef, @OLD_REFERENCE
)
expected = []
expect(actual).toEqual(expected)
it 'should build a transitionState action for a state change', ->
delta = @utils.diff @OLD_REFERENCE, @NEW_REFERENCE
actual = @utils.actionsMapReferences(
delta, @NEW_REFERENCE, @OLD_REFERENCE
)
expected = [{
action: 'transitionState',
state: { typeId: 'state', id: 'new-state-id' }
}]
expect(actual).toEqual(expected)
describe ':: actionsMapCategories (category)', ->
beforeEach ->
@utils = new ProductUtils
@OLD_REFERENCE =
id: '123'
categories: [
{ typeId: 'category', id: 'cat1' }
{ typeId: 'category', id: 'cat2' }
]
masterVariant:
id: 1
@NEW_REFERENCE =
id: '123'
categories: [
{ typeId: 'category', id: 'cat1' }
{ typeId: 'category', id: 'cat3' }
]
masterVariant:
id: 1
it 'should build actions to change category', ->
delta = @utils.diff @OLD_REFERENCE, @NEW_REFERENCE
update = @utils.actionsMapCategories delta, @OLD_REFERENCE, @NEW_REFERENCE
expected_update = [
{ action: 'removeFromCategory', category: { typeId: 'category', id: 'cat2' } }
{ action: 'addToCategory', category: { typeId: 'category', id: 'cat3' } }
]
expect(update).toEqual expected_update
it 'should ignore changes in ordering of category references', ->
before =
id: '123'
categories: [
{ typeId: 'category', id: 'cat1' }
{ typeId: 'category', id: 'cat2' }
]
masterVariant:
id: 1
after =
id: '123'
categories: [
{ typeId: 'category', id: 'cat2' }
{ typeId: 'category', id: 'cat1' }
]
masterVariant:
id: 1
delta = @utils.diff before, after
update = @utils.actionsMapCategories delta, before, after
expect(update).toEqual []
|
[
{
"context": "ons'\n\n defaults: ->\n email: null\n password: null\n rememberMe: false\n\n validate: (attributes) -",
"end": 216,
"score": 0.6747621297836304,
"start": 212,
"tag": "PASSWORD",
"value": "null"
}
] | source/NuGet/coffeescript/content/Scripts/application/models/session.coffee | kazimanzurrashid/AspNetMvcBackboneJsSpa | 22 | exports = @
App = exports.Application or= {}
Models = App.Models or= {}
class Models.Session extends Backbone.Model
urlRoot: -> App.serverUrlPrefix + '/sessions'
defaults: ->
email: null
password: null
rememberMe: false
validate: (attributes) ->
Validation = Models.Validation
errors = {}
unless attributes.email
Validation.addError errors, 'email', 'Email is required.'
unless attributes.password
Validation.addError errors, 'password', 'Password is required.'
if _(errors).isEmpty() then undefined else errors | 159878 | exports = @
App = exports.Application or= {}
Models = App.Models or= {}
class Models.Session extends Backbone.Model
urlRoot: -> App.serverUrlPrefix + '/sessions'
defaults: ->
email: null
password: <PASSWORD>
rememberMe: false
validate: (attributes) ->
Validation = Models.Validation
errors = {}
unless attributes.email
Validation.addError errors, 'email', 'Email is required.'
unless attributes.password
Validation.addError errors, 'password', 'Password is required.'
if _(errors).isEmpty() then undefined else errors | true | exports = @
App = exports.Application or= {}
Models = App.Models or= {}
class Models.Session extends Backbone.Model
urlRoot: -> App.serverUrlPrefix + '/sessions'
defaults: ->
email: null
password: PI:PASSWORD:<PASSWORD>END_PI
rememberMe: false
validate: (attributes) ->
Validation = Models.Validation
errors = {}
unless attributes.email
Validation.addError errors, 'email', 'Email is required.'
unless attributes.password
Validation.addError errors, 'password', 'Password is required.'
if _(errors).isEmpty() then undefined else errors |
[
{
"context": "lass Line extends LinkedList.Node\n @DATA_KEY : 'line'\n\n constructor: (@doc, @node) ->\n @formats = ",
"end": 342,
"score": 0.8725918531417847,
"start": 338,
"tag": "KEY",
"value": "line"
}
] | src/core/line.coffee | KentZheng/testingflow | 0 | _ = require('lodash')
Delta = require('rich-text/lib/delta')
dom = require('../lib/dom')
Format = require('./format')
Leaf = require('./leaf')
Line = require('./line')
LinkedList = require('../lib/linked-list')
Normalizer = require('./normalizer')
class Line extends LinkedList.Node
@DATA_KEY : 'line'
constructor: (@doc, @node) ->
@formats = {}
this.rebuild()
super(@node)
buildLeaves: (node, formats) ->
_.each(dom(node).childNodes(), (node) =>
node = @doc.normalizer.normalizeNode(node)
nodeFormats = _.clone(formats)
# TODO: optimize
_.each(@doc.formats, (format, name) ->
# format.value() also checks match() but existing bug in tandem-core requires check anyways
nodeFormats[name] = format.value(node) if !format.isType(Format.types.LINE) and format.match(node)
)
if Leaf.isLeafNode(node)
@leaves.append(new Leaf(node, nodeFormats))
else
this.buildLeaves(node, nodeFormats)
)
deleteText: (offset, length) ->
return unless length > 0
[leaf, offset] = this.findLeafAt(offset)
while leaf? and length > 0
deleteLength = Math.min(length, leaf.length - offset)
leaf.deleteText(offset, deleteLength)
length -= deleteLength
leaf = leaf.next
offset = 0
this.rebuild()
findLeaf: (leafNode) ->
return if leafNode? then dom(leafNode).data(Leaf.DATA_KEY) else undefined
findLeafAt: (offset, inclusive = false) ->
# TODO exact same code as findLineAt
return [@leaves.last, @leaves.last.length] if offset >= @length - 1
leaf = @leaves.first
while leaf?
if offset < leaf.length or (offset == leaf.length and inclusive)
return [leaf, offset]
offset -= leaf.length
leaf = leaf.next
return [@leaves.last, offset - @leaves.last.length] # Should never occur unless length calculation is off
format: (name, value) ->
if _.isObject(name)
formats = name
else
formats = {}
formats[name] = value
_.each(formats, (value, name) =>
format = @doc.formats[name]
return unless format?
# TODO reassigning @node might be dangerous...
if format.isType(Format.types.LINE)
if format.config.exclude and @formats[format.config.exclude]
excludeFormat = @doc.formats[format.config.exclude]
if excludeFormat?
@node = excludeFormat.remove(@node)
delete @formats[format.config.exclude]
@node = format.add(@node, value)
if value
@formats[name] = value
else
delete @formats[name]
)
this.resetContent()
formatText: (offset, length, name, value) ->
[leaf, leafOffset] = this.findLeafAt(offset)
format = @doc.formats[name]
return unless format? and format.config.type != Format.types.LINE
while leaf? and length > 0
nextLeaf = leaf.next
# Make sure we need to change leaf format
if (value and leaf.formats[name] != value) or (!value and leaf.formats[name]?)
targetNode = leaf.node
# Identify node to modify
if leaf.formats[name]?
dom(targetNode).splitBefore(@node)
while !format.match(targetNode)
targetNode = targetNode.parentNode
dom(targetNode).split(leaf.length)
# Isolate target node
if leafOffset > 0
[leftNode, targetNode] = dom(targetNode).split(leafOffset)
if leaf.length > leafOffset + length # leaf.length does not update with split()
[targetNode, rightNode] = dom(targetNode).split(length)
format.add(targetNode, value)
length -= leaf.length - leafOffset
leafOffset = 0
leaf = nextLeaf
this.rebuild()
_insert: (offset, node, formats) ->
[leaf, leafOffset] = this.findLeafAt(offset)
node = _.reduce(formats, (node, value, name) =>
format = @doc.formats[name]
node = format.add(node, value) if format?
return node
, node)
[prevNode, nextNode] = dom(leaf.node).split(leafOffset)
nextNode = dom(nextNode).splitBefore(@node).get() if nextNode
@node.insertBefore(node, nextNode)
this.rebuild()
insertEmbed: (offset, attributes) ->
[leaf, leafOffset] = this.findLeafAt(offset)
[prevNode, nextNode] = dom(leaf.node).split(leafOffset)
formatName = _.find(Object.keys(attributes), (name) =>
return @doc.formats[name].isType(Format.types.EMBED)
)
node = @doc.formats[formatName].add({}, attributes[formatName]) # TODO fix {} hack
attributes = _.clone(attributes)
delete attributes[formatName]
this._insert(offset, node, attributes)
insertText: (offset, text, formats = {}) ->
return unless text.length > 0
[leaf, leafOffset] = this.findLeafAt(offset)
if _.isEqual(leaf.formats, formats)
leaf.insertText(leafOffset, text)
this.resetContent()
else
this._insert(offset, document.createTextNode(text), formats)
optimize: ->
Normalizer.optimizeLine(@node)
this.rebuild()
rebuild: (force = false) ->
if !force and @outerHTML? and @outerHTML == @node.outerHTML
if _.all(@leaves.toArray(), (leaf) =>
return dom(leaf.node).isAncestor(@node)
)
return false
@node = @doc.normalizer.normalizeNode(@node)
if dom(@node).length() == 0 and !@node.querySelector(dom.DEFAULT_BREAK_TAG)
@node.appendChild(document.createElement(dom.DEFAULT_BREAK_TAG))
@leaves = new LinkedList()
@formats = _.reduce(@doc.formats, (formats, format, name) =>
if format.isType(Format.types.LINE)
if format.match(@node)
formats[name] = format.value(@node)
else
delete formats[name]
return formats
, @formats)
this.buildLeaves(@node, {})
this.resetContent()
return true
resetContent: ->
dom(@node).data(Line.DATA_KEY, this)
@outerHTML = @node.outerHTML
@length = 1
@delta = new Delta()
_.each(@leaves.toArray(), (leaf) =>
@length += leaf.length
# TODO use constant for embed type
if dom.EMBED_TAGS[leaf.node.tagName]?
@delta.insert(1, leaf.formats)
else
@delta.insert(leaf.text, leaf.formats)
)
@delta.insert('\n', @formats)
module.exports = Line
| 220666 | _ = require('lodash')
Delta = require('rich-text/lib/delta')
dom = require('../lib/dom')
Format = require('./format')
Leaf = require('./leaf')
Line = require('./line')
LinkedList = require('../lib/linked-list')
Normalizer = require('./normalizer')
class Line extends LinkedList.Node
@DATA_KEY : '<KEY>'
constructor: (@doc, @node) ->
@formats = {}
this.rebuild()
super(@node)
buildLeaves: (node, formats) ->
_.each(dom(node).childNodes(), (node) =>
node = @doc.normalizer.normalizeNode(node)
nodeFormats = _.clone(formats)
# TODO: optimize
_.each(@doc.formats, (format, name) ->
# format.value() also checks match() but existing bug in tandem-core requires check anyways
nodeFormats[name] = format.value(node) if !format.isType(Format.types.LINE) and format.match(node)
)
if Leaf.isLeafNode(node)
@leaves.append(new Leaf(node, nodeFormats))
else
this.buildLeaves(node, nodeFormats)
)
deleteText: (offset, length) ->
return unless length > 0
[leaf, offset] = this.findLeafAt(offset)
while leaf? and length > 0
deleteLength = Math.min(length, leaf.length - offset)
leaf.deleteText(offset, deleteLength)
length -= deleteLength
leaf = leaf.next
offset = 0
this.rebuild()
findLeaf: (leafNode) ->
return if leafNode? then dom(leafNode).data(Leaf.DATA_KEY) else undefined
findLeafAt: (offset, inclusive = false) ->
# TODO exact same code as findLineAt
return [@leaves.last, @leaves.last.length] if offset >= @length - 1
leaf = @leaves.first
while leaf?
if offset < leaf.length or (offset == leaf.length and inclusive)
return [leaf, offset]
offset -= leaf.length
leaf = leaf.next
return [@leaves.last, offset - @leaves.last.length] # Should never occur unless length calculation is off
format: (name, value) ->
if _.isObject(name)
formats = name
else
formats = {}
formats[name] = value
_.each(formats, (value, name) =>
format = @doc.formats[name]
return unless format?
# TODO reassigning @node might be dangerous...
if format.isType(Format.types.LINE)
if format.config.exclude and @formats[format.config.exclude]
excludeFormat = @doc.formats[format.config.exclude]
if excludeFormat?
@node = excludeFormat.remove(@node)
delete @formats[format.config.exclude]
@node = format.add(@node, value)
if value
@formats[name] = value
else
delete @formats[name]
)
this.resetContent()
formatText: (offset, length, name, value) ->
[leaf, leafOffset] = this.findLeafAt(offset)
format = @doc.formats[name]
return unless format? and format.config.type != Format.types.LINE
while leaf? and length > 0
nextLeaf = leaf.next
# Make sure we need to change leaf format
if (value and leaf.formats[name] != value) or (!value and leaf.formats[name]?)
targetNode = leaf.node
# Identify node to modify
if leaf.formats[name]?
dom(targetNode).splitBefore(@node)
while !format.match(targetNode)
targetNode = targetNode.parentNode
dom(targetNode).split(leaf.length)
# Isolate target node
if leafOffset > 0
[leftNode, targetNode] = dom(targetNode).split(leafOffset)
if leaf.length > leafOffset + length # leaf.length does not update with split()
[targetNode, rightNode] = dom(targetNode).split(length)
format.add(targetNode, value)
length -= leaf.length - leafOffset
leafOffset = 0
leaf = nextLeaf
this.rebuild()
_insert: (offset, node, formats) ->
[leaf, leafOffset] = this.findLeafAt(offset)
node = _.reduce(formats, (node, value, name) =>
format = @doc.formats[name]
node = format.add(node, value) if format?
return node
, node)
[prevNode, nextNode] = dom(leaf.node).split(leafOffset)
nextNode = dom(nextNode).splitBefore(@node).get() if nextNode
@node.insertBefore(node, nextNode)
this.rebuild()
insertEmbed: (offset, attributes) ->
[leaf, leafOffset] = this.findLeafAt(offset)
[prevNode, nextNode] = dom(leaf.node).split(leafOffset)
formatName = _.find(Object.keys(attributes), (name) =>
return @doc.formats[name].isType(Format.types.EMBED)
)
node = @doc.formats[formatName].add({}, attributes[formatName]) # TODO fix {} hack
attributes = _.clone(attributes)
delete attributes[formatName]
this._insert(offset, node, attributes)
insertText: (offset, text, formats = {}) ->
return unless text.length > 0
[leaf, leafOffset] = this.findLeafAt(offset)
if _.isEqual(leaf.formats, formats)
leaf.insertText(leafOffset, text)
this.resetContent()
else
this._insert(offset, document.createTextNode(text), formats)
optimize: ->
Normalizer.optimizeLine(@node)
this.rebuild()
rebuild: (force = false) ->
if !force and @outerHTML? and @outerHTML == @node.outerHTML
if _.all(@leaves.toArray(), (leaf) =>
return dom(leaf.node).isAncestor(@node)
)
return false
@node = @doc.normalizer.normalizeNode(@node)
if dom(@node).length() == 0 and !@node.querySelector(dom.DEFAULT_BREAK_TAG)
@node.appendChild(document.createElement(dom.DEFAULT_BREAK_TAG))
@leaves = new LinkedList()
@formats = _.reduce(@doc.formats, (formats, format, name) =>
if format.isType(Format.types.LINE)
if format.match(@node)
formats[name] = format.value(@node)
else
delete formats[name]
return formats
, @formats)
this.buildLeaves(@node, {})
this.resetContent()
return true
resetContent: ->
dom(@node).data(Line.DATA_KEY, this)
@outerHTML = @node.outerHTML
@length = 1
@delta = new Delta()
_.each(@leaves.toArray(), (leaf) =>
@length += leaf.length
# TODO use constant for embed type
if dom.EMBED_TAGS[leaf.node.tagName]?
@delta.insert(1, leaf.formats)
else
@delta.insert(leaf.text, leaf.formats)
)
@delta.insert('\n', @formats)
module.exports = Line
| true | _ = require('lodash')
Delta = require('rich-text/lib/delta')
dom = require('../lib/dom')
Format = require('./format')
Leaf = require('./leaf')
Line = require('./line')
LinkedList = require('../lib/linked-list')
Normalizer = require('./normalizer')
class Line extends LinkedList.Node
@DATA_KEY : 'PI:KEY:<KEY>END_PI'
constructor: (@doc, @node) ->
@formats = {}
this.rebuild()
super(@node)
buildLeaves: (node, formats) ->
_.each(dom(node).childNodes(), (node) =>
node = @doc.normalizer.normalizeNode(node)
nodeFormats = _.clone(formats)
# TODO: optimize
_.each(@doc.formats, (format, name) ->
# format.value() also checks match() but existing bug in tandem-core requires check anyways
nodeFormats[name] = format.value(node) if !format.isType(Format.types.LINE) and format.match(node)
)
if Leaf.isLeafNode(node)
@leaves.append(new Leaf(node, nodeFormats))
else
this.buildLeaves(node, nodeFormats)
)
deleteText: (offset, length) ->
return unless length > 0
[leaf, offset] = this.findLeafAt(offset)
while leaf? and length > 0
deleteLength = Math.min(length, leaf.length - offset)
leaf.deleteText(offset, deleteLength)
length -= deleteLength
leaf = leaf.next
offset = 0
this.rebuild()
findLeaf: (leafNode) ->
return if leafNode? then dom(leafNode).data(Leaf.DATA_KEY) else undefined
findLeafAt: (offset, inclusive = false) ->
# TODO exact same code as findLineAt
return [@leaves.last, @leaves.last.length] if offset >= @length - 1
leaf = @leaves.first
while leaf?
if offset < leaf.length or (offset == leaf.length and inclusive)
return [leaf, offset]
offset -= leaf.length
leaf = leaf.next
return [@leaves.last, offset - @leaves.last.length] # Should never occur unless length calculation is off
format: (name, value) ->
if _.isObject(name)
formats = name
else
formats = {}
formats[name] = value
_.each(formats, (value, name) =>
format = @doc.formats[name]
return unless format?
# TODO reassigning @node might be dangerous...
if format.isType(Format.types.LINE)
if format.config.exclude and @formats[format.config.exclude]
excludeFormat = @doc.formats[format.config.exclude]
if excludeFormat?
@node = excludeFormat.remove(@node)
delete @formats[format.config.exclude]
@node = format.add(@node, value)
if value
@formats[name] = value
else
delete @formats[name]
)
this.resetContent()
formatText: (offset, length, name, value) ->
[leaf, leafOffset] = this.findLeafAt(offset)
format = @doc.formats[name]
return unless format? and format.config.type != Format.types.LINE
while leaf? and length > 0
nextLeaf = leaf.next
# Make sure we need to change leaf format
if (value and leaf.formats[name] != value) or (!value and leaf.formats[name]?)
targetNode = leaf.node
# Identify node to modify
if leaf.formats[name]?
dom(targetNode).splitBefore(@node)
while !format.match(targetNode)
targetNode = targetNode.parentNode
dom(targetNode).split(leaf.length)
# Isolate target node
if leafOffset > 0
[leftNode, targetNode] = dom(targetNode).split(leafOffset)
if leaf.length > leafOffset + length # leaf.length does not update with split()
[targetNode, rightNode] = dom(targetNode).split(length)
format.add(targetNode, value)
length -= leaf.length - leafOffset
leafOffset = 0
leaf = nextLeaf
this.rebuild()
_insert: (offset, node, formats) ->
[leaf, leafOffset] = this.findLeafAt(offset)
node = _.reduce(formats, (node, value, name) =>
format = @doc.formats[name]
node = format.add(node, value) if format?
return node
, node)
[prevNode, nextNode] = dom(leaf.node).split(leafOffset)
nextNode = dom(nextNode).splitBefore(@node).get() if nextNode
@node.insertBefore(node, nextNode)
this.rebuild()
insertEmbed: (offset, attributes) ->
[leaf, leafOffset] = this.findLeafAt(offset)
[prevNode, nextNode] = dom(leaf.node).split(leafOffset)
formatName = _.find(Object.keys(attributes), (name) =>
return @doc.formats[name].isType(Format.types.EMBED)
)
node = @doc.formats[formatName].add({}, attributes[formatName]) # TODO fix {} hack
attributes = _.clone(attributes)
delete attributes[formatName]
this._insert(offset, node, attributes)
insertText: (offset, text, formats = {}) ->
return unless text.length > 0
[leaf, leafOffset] = this.findLeafAt(offset)
if _.isEqual(leaf.formats, formats)
leaf.insertText(leafOffset, text)
this.resetContent()
else
this._insert(offset, document.createTextNode(text), formats)
optimize: ->
Normalizer.optimizeLine(@node)
this.rebuild()
rebuild: (force = false) ->
if !force and @outerHTML? and @outerHTML == @node.outerHTML
if _.all(@leaves.toArray(), (leaf) =>
return dom(leaf.node).isAncestor(@node)
)
return false
@node = @doc.normalizer.normalizeNode(@node)
if dom(@node).length() == 0 and !@node.querySelector(dom.DEFAULT_BREAK_TAG)
@node.appendChild(document.createElement(dom.DEFAULT_BREAK_TAG))
@leaves = new LinkedList()
@formats = _.reduce(@doc.formats, (formats, format, name) =>
if format.isType(Format.types.LINE)
if format.match(@node)
formats[name] = format.value(@node)
else
delete formats[name]
return formats
, @formats)
this.buildLeaves(@node, {})
this.resetContent()
return true
resetContent: ->
dom(@node).data(Line.DATA_KEY, this)
@outerHTML = @node.outerHTML
@length = 1
@delta = new Delta()
_.each(@leaves.toArray(), (leaf) =>
@length += leaf.length
# TODO use constant for embed type
if dom.EMBED_TAGS[leaf.node.tagName]?
@delta.insert(1, leaf.formats)
else
@delta.insert(leaf.text, leaf.formats)
)
@delta.insert('\n', @formats)
module.exports = Line
|
[
{
"context": " window.pubnub = PUBNUB.init\n publish_key: 'pub-c-7070d569-77ab-48d3-97ca-c0c3f7ab6403'\n subscribe_key: 'sub-c-49a2a468-ced1-11e2-a",
"end": 1431,
"score": 0.9997469782829285,
"start": 1389,
"tag": "KEY",
"value": "pub-c-7070d569-77ab-48d3-97ca-c0c3f7ab6403"
},
... | app/scripts/main.coffee | ndsclaramaria/sky.github.io | 35 | class GooglePlusClient
constructor: (@token) ->
@baseUrl = 'https://www.googleapis.com/plus/v1'
getCurrentUser: (callback) ->
req =
url: @baseUrl + '/people/me'
data:
access_token: @token
v: 3.0
alt: 'json'
'max-results': 10000
$.ajax(req).done callback
getContacts: (callback) ->
req =
url: @baseUrl + '/people/me/people/visible'
data:
access_token: @token
v: 3.0
alt: 'json'
'max-results': 10000
$.ajax(req).done callback
navigator.getUserMedia = navigator.getUserMedia or
navigator.webkitGetUserMedia or
navigator.mozGetUserMedia
$(document).ready () ->
# Pages
# ================
pages =
login: document.querySelector '#page-login'
caller: document.querySelector '#page-caller'
# Globals
# =================
window.pubnub = null
uuid = null
currentCall = null
myStream = null
plusClient = null
# Login
# ================
document.querySelector('#login').addEventListener 'click', (event) ->
uuid = document.querySelector('#userid').value
login "guest-#{uuid}"
login = (name) ->
uuid = name
if plusClient?
# Get the current list of contacts
plusClient.getContacts (result) ->
# result.items
window.pubnub = PUBNUB.init
publish_key: 'pub-c-7070d569-77ab-48d3-97ca-c0c3f7ab6403'
subscribe_key: 'sub-c-49a2a468-ced1-11e2-a5be-02ee2ddab7fe'
uuid: name
pubnub.onNewConnection (uuid) ->
unless not myStream
publishStream uuid
pages.login.className = pages.login.className.replace 'active', ''
pages.caller.className += ' active'
$(document).trigger 'pubnub:ready'
window.signinCallback = (authResult) ->
if authResult['access_token']
# Update the app to reflect a signed in user
# Hide the sign-in button
$('#signinButton').hide()
# Create the google plus client
plusClient = new GooglePlusClient authResult['access_token']
# Get the user ID from google plus
plusClient.getCurrentUser (result) ->
# displayName
# gender
# id
# image
name = result.displayName.split(' ')
name = name[0] + ' ' + name[1].charAt(0) + '.'
login "#{result.id}-#{name}"
else if authResult['error']
# Update to reflect signed out user
# Possible Values:
# "user_signed_out" - User is signed out
# "access_denied" - User denied access to your app
# "immediate_failed" - Could not automatically log in to the user
console.log "Sign-in state: #{authResult['error']}"
# User List
# ==================
userTemplate = _.template $("#user-item-template").text()
userList = $("#user-list")
$(document).on 'pubnub:ready', (event) ->
pubnub.subscribe
channel: 'phonebook'
callback: (message) ->
# Do nothing
presence: (data) ->
# {
# action: "join"/"leave"
# timestamp: 12345
# uuid: "Dan"
# occupancy: 2
# }
if data.action is "join" and data.uuid isnt uuid
newItem = userTemplate
name: data.uuid.split('-')[1]
id: data.uuid
userList.append newItem
else if data.action is "leave" and data.uuid isnt uuid
item = userList.find "li[data-user=\"#{data.uuid}\"]"
item.remove()
# Answering
# =================
caller = ''
modalAnswer = $ '#answer-modal'
modalAnswer.modal({ show: false })
publishStream = (uuid) ->
pubnub.publish
user: uuid
stream: myStream
pubnub.subscribe
user: uuid
stream: (bad, event) ->
document.querySelector('#call-video').src = URL.createObjectURL(event.stream)
disconnect: (uuid, pc) ->
document.querySelector('#call-video').src = ''
$(document).trigger "call:end"
connect: (uuid, pc) ->
# Do nothing
answer = (otherUuid) ->
if currentCall? and currentCall isnt otherUuid
hangUp()
currentCall = otherUuid
publishStream otherUuid
$(document).trigger "call:start", otherUuid
pubnub.publish
channel: 'answer'
message:
caller: caller
callee: uuid
$(document).on 'pubnub:ready', (event) =>
pubnub.subscribe
channel: 'call'
callback: (data) ->
if data.callee is uuid
caller = data.caller
onCalling data.caller
pubnub.subscribe
channel: 'answer'
callback: (data) ->
if data.caller is uuid
if data.callee isnt currentCall
hangUp()
currentCall = data.callee
publishStream data.callee
$(document).trigger "call:start", data.callee
onCalling = (caller) ->
caller = caller.split('-')[1]
modalAnswer.find('.caller').text "#{caller} is calling..."
modalAnswer.modal 'show'
modalAnswer.find('.btn-primary').on 'click', (event) ->
answer caller
modalAnswer.modal 'hide'
# Calling
# =================
modalCalling = $ '#calling-modal'
modalCalling.modal({ show: false })
$('#user-list').on 'click', 'a[data-user]', (event) ->
otherUuid = $(event.target).data 'user'
currentCall = otherUuid
name = otherUuid.split('-')[1]
modalCalling.find('.calling').text "Calling #{name}..."
modalCalling.modal 'show'
pubnub.publish
channel: 'call'
message:
caller: uuid
callee: otherUuid
$(document).on 'call:start', () ->
modalCalling.modal 'hide'
# Text Chat
# ================
messageBox = $ '#chat-receive-message'
messageInput = $ '#chat-message'
messageBox.text ''
messageControls = $ '#chat-area'
messageControls.hide()
getCombinedChannel = () ->
if currentCall > uuid
"#{currentCall}-#{uuid}"
else
"#{uuid}-#{currentCall}"
$(document).on "call:start", (event) =>
messageControls.show()
messageBox.text ''
pubnub.subscribe
channel: getCombinedChannel()
callback: (message) ->
messageBox.append "<br />#{message}"
messageBox.scrollTop messageBox[0].scrollHeight
$(document).on "call:end", (event) =>
messageControls.hide()
pubnub.unsubscribe
channel: getCombinedChannel()
messageInput.on 'keydown', (event) =>
if event.keyCode is 13 and currentCall?
pubnub.publish
channel: getCombinedChannel()
message: uuid.split('-')[1] + ": " + messageInput.val()
messageInput.val ''
# Hanging Up
# ================
$('#hang-up').on 'click', (event) ->
hangUp()
hangUp = () ->
pubnub.closeConnection currentCall, () ->
$(document).trigger "call:end"
# Call Status
# ================
videoControls = $ '#video-controls'
timeEl = videoControls.find '#time'
time = 0
timeInterval = null
videoControls.hide()
increment = () ->
time += 1
minutes = Math.floor(time / 60)
seconds = time % 60
if minutes.toString().length is 1 then minutes = "0#{minutes}"
if seconds.toString().length is 1 then seconds = "0#{seconds}"
timeEl.text "#{minutes}:#{seconds}"
$(document).on "call:start", (event) =>
videoControls.show()
time = 0
timeEl.text "00:00"
timeInterval = setInterval increment, 1000
$(document).on "call:end", (event) =>
videoControls.hide()
clearInterval timeInterval
gotStream = (stream) ->
document.querySelector('#self-call-video').src = URL.createObjectURL(stream)
#document.querySelector('#self-call-video').play()
myStream = stream
navigator.getUserMedia {audio: true, video: true}, gotStream, (error) ->
console.log("Error getting user media: ", error)
# Debug
# pages.caller.className += ' active'
# login("Guest" + Math.floor(Math.random() * 100))
# pages.login.className += ' active'
| 224594 | class GooglePlusClient
constructor: (@token) ->
@baseUrl = 'https://www.googleapis.com/plus/v1'
getCurrentUser: (callback) ->
req =
url: @baseUrl + '/people/me'
data:
access_token: @token
v: 3.0
alt: 'json'
'max-results': 10000
$.ajax(req).done callback
getContacts: (callback) ->
req =
url: @baseUrl + '/people/me/people/visible'
data:
access_token: @token
v: 3.0
alt: 'json'
'max-results': 10000
$.ajax(req).done callback
navigator.getUserMedia = navigator.getUserMedia or
navigator.webkitGetUserMedia or
navigator.mozGetUserMedia
$(document).ready () ->
# Pages
# ================
pages =
login: document.querySelector '#page-login'
caller: document.querySelector '#page-caller'
# Globals
# =================
window.pubnub = null
uuid = null
currentCall = null
myStream = null
plusClient = null
# Login
# ================
document.querySelector('#login').addEventListener 'click', (event) ->
uuid = document.querySelector('#userid').value
login "guest-#{uuid}"
login = (name) ->
uuid = name
if plusClient?
# Get the current list of contacts
plusClient.getContacts (result) ->
# result.items
window.pubnub = PUBNUB.init
publish_key: '<KEY>'
subscribe_key: '<KEY>'
uuid: name
pubnub.onNewConnection (uuid) ->
unless not myStream
publishStream uuid
pages.login.className = pages.login.className.replace 'active', ''
pages.caller.className += ' active'
$(document).trigger 'pubnub:ready'
window.signinCallback = (authResult) ->
if authResult['access_token']
# Update the app to reflect a signed in user
# Hide the sign-in button
$('#signinButton').hide()
# Create the google plus client
plusClient = new GooglePlusClient authResult['access_token']
# Get the user ID from google plus
plusClient.getCurrentUser (result) ->
# displayName
# gender
# id
# image
name = result.displayName.split(' ')
name = name[0] + ' ' + name[1].charAt(0) + '.'
login "#{result.id}-#{name}"
else if authResult['error']
# Update to reflect signed out user
# Possible Values:
# "user_signed_out" - User is signed out
# "access_denied" - User denied access to your app
# "immediate_failed" - Could not automatically log in to the user
console.log "Sign-in state: #{authResult['error']}"
# User List
# ==================
userTemplate = _.template $("#user-item-template").text()
userList = $("#user-list")
$(document).on 'pubnub:ready', (event) ->
pubnub.subscribe
channel: 'phonebook'
callback: (message) ->
# Do nothing
presence: (data) ->
# {
# action: "join"/"leave"
# timestamp: 12345
# uuid: "Dan"
# occupancy: 2
# }
if data.action is "join" and data.uuid isnt uuid
newItem = userTemplate
name: data.uuid.split('-')[1]
id: data.uuid
userList.append newItem
else if data.action is "leave" and data.uuid isnt uuid
item = userList.find "li[data-user=\"#{data.uuid}\"]"
item.remove()
# Answering
# =================
caller = ''
modalAnswer = $ '#answer-modal'
modalAnswer.modal({ show: false })
publishStream = (uuid) ->
pubnub.publish
user: uuid
stream: myStream
pubnub.subscribe
user: uuid
stream: (bad, event) ->
document.querySelector('#call-video').src = URL.createObjectURL(event.stream)
disconnect: (uuid, pc) ->
document.querySelector('#call-video').src = ''
$(document).trigger "call:end"
connect: (uuid, pc) ->
# Do nothing
answer = (otherUuid) ->
if currentCall? and currentCall isnt otherUuid
hangUp()
currentCall = otherUuid
publishStream otherUuid
$(document).trigger "call:start", otherUuid
pubnub.publish
channel: 'answer'
message:
caller: caller
callee: uuid
$(document).on 'pubnub:ready', (event) =>
pubnub.subscribe
channel: 'call'
callback: (data) ->
if data.callee is uuid
caller = data.caller
onCalling data.caller
pubnub.subscribe
channel: 'answer'
callback: (data) ->
if data.caller is uuid
if data.callee isnt currentCall
hangUp()
currentCall = data.callee
publishStream data.callee
$(document).trigger "call:start", data.callee
onCalling = (caller) ->
caller = caller.split('-')[1]
modalAnswer.find('.caller').text "#{caller} is calling..."
modalAnswer.modal 'show'
modalAnswer.find('.btn-primary').on 'click', (event) ->
answer caller
modalAnswer.modal 'hide'
# Calling
# =================
modalCalling = $ '#calling-modal'
modalCalling.modal({ show: false })
$('#user-list').on 'click', 'a[data-user]', (event) ->
otherUuid = $(event.target).data 'user'
currentCall = otherUuid
name = otherUuid.split('-')[1]
modalCalling.find('.calling').text "Calling #{name}..."
modalCalling.modal 'show'
pubnub.publish
channel: 'call'
message:
caller: uuid
callee: otherUuid
$(document).on 'call:start', () ->
modalCalling.modal 'hide'
# Text Chat
# ================
messageBox = $ '#chat-receive-message'
messageInput = $ '#chat-message'
messageBox.text ''
messageControls = $ '#chat-area'
messageControls.hide()
getCombinedChannel = () ->
if currentCall > uuid
"#{currentCall}-#{uuid}"
else
"#{uuid}-#{currentCall}"
$(document).on "call:start", (event) =>
messageControls.show()
messageBox.text ''
pubnub.subscribe
channel: getCombinedChannel()
callback: (message) ->
messageBox.append "<br />#{message}"
messageBox.scrollTop messageBox[0].scrollHeight
$(document).on "call:end", (event) =>
messageControls.hide()
pubnub.unsubscribe
channel: getCombinedChannel()
messageInput.on 'keydown', (event) =>
if event.keyCode is 13 and currentCall?
pubnub.publish
channel: getCombinedChannel()
message: uuid.split('-')[1] + ": " + messageInput.val()
messageInput.val ''
# Hanging Up
# ================
$('#hang-up').on 'click', (event) ->
hangUp()
hangUp = () ->
pubnub.closeConnection currentCall, () ->
$(document).trigger "call:end"
# Call Status
# ================
videoControls = $ '#video-controls'
timeEl = videoControls.find '#time'
time = 0
timeInterval = null
videoControls.hide()
increment = () ->
time += 1
minutes = Math.floor(time / 60)
seconds = time % 60
if minutes.toString().length is 1 then minutes = "0#{minutes}"
if seconds.toString().length is 1 then seconds = "0#{seconds}"
timeEl.text "#{minutes}:#{seconds}"
$(document).on "call:start", (event) =>
videoControls.show()
time = 0
timeEl.text "00:00"
timeInterval = setInterval increment, 1000
$(document).on "call:end", (event) =>
videoControls.hide()
clearInterval timeInterval
gotStream = (stream) ->
document.querySelector('#self-call-video').src = URL.createObjectURL(stream)
#document.querySelector('#self-call-video').play()
myStream = stream
navigator.getUserMedia {audio: true, video: true}, gotStream, (error) ->
console.log("Error getting user media: ", error)
# Debug
# pages.caller.className += ' active'
# login("Guest" + Math.floor(Math.random() * 100))
# pages.login.className += ' active'
| true | class GooglePlusClient
constructor: (@token) ->
@baseUrl = 'https://www.googleapis.com/plus/v1'
getCurrentUser: (callback) ->
req =
url: @baseUrl + '/people/me'
data:
access_token: @token
v: 3.0
alt: 'json'
'max-results': 10000
$.ajax(req).done callback
getContacts: (callback) ->
req =
url: @baseUrl + '/people/me/people/visible'
data:
access_token: @token
v: 3.0
alt: 'json'
'max-results': 10000
$.ajax(req).done callback
navigator.getUserMedia = navigator.getUserMedia or
navigator.webkitGetUserMedia or
navigator.mozGetUserMedia
$(document).ready () ->
# Pages
# ================
pages =
login: document.querySelector '#page-login'
caller: document.querySelector '#page-caller'
# Globals
# =================
window.pubnub = null
uuid = null
currentCall = null
myStream = null
plusClient = null
# Login
# ================
document.querySelector('#login').addEventListener 'click', (event) ->
uuid = document.querySelector('#userid').value
login "guest-#{uuid}"
login = (name) ->
uuid = name
if plusClient?
# Get the current list of contacts
plusClient.getContacts (result) ->
# result.items
window.pubnub = PUBNUB.init
publish_key: 'PI:KEY:<KEY>END_PI'
subscribe_key: 'PI:KEY:<KEY>END_PI'
uuid: name
pubnub.onNewConnection (uuid) ->
unless not myStream
publishStream uuid
pages.login.className = pages.login.className.replace 'active', ''
pages.caller.className += ' active'
$(document).trigger 'pubnub:ready'
window.signinCallback = (authResult) ->
if authResult['access_token']
# Update the app to reflect a signed in user
# Hide the sign-in button
$('#signinButton').hide()
# Create the google plus client
plusClient = new GooglePlusClient authResult['access_token']
# Get the user ID from google plus
plusClient.getCurrentUser (result) ->
# displayName
# gender
# id
# image
name = result.displayName.split(' ')
name = name[0] + ' ' + name[1].charAt(0) + '.'
login "#{result.id}-#{name}"
else if authResult['error']
# Update to reflect signed out user
# Possible Values:
# "user_signed_out" - User is signed out
# "access_denied" - User denied access to your app
# "immediate_failed" - Could not automatically log in to the user
console.log "Sign-in state: #{authResult['error']}"
# User List
# ==================
userTemplate = _.template $("#user-item-template").text()
userList = $("#user-list")
$(document).on 'pubnub:ready', (event) ->
pubnub.subscribe
channel: 'phonebook'
callback: (message) ->
# Do nothing
presence: (data) ->
# {
# action: "join"/"leave"
# timestamp: 12345
# uuid: "Dan"
# occupancy: 2
# }
if data.action is "join" and data.uuid isnt uuid
newItem = userTemplate
name: data.uuid.split('-')[1]
id: data.uuid
userList.append newItem
else if data.action is "leave" and data.uuid isnt uuid
item = userList.find "li[data-user=\"#{data.uuid}\"]"
item.remove()
# Answering
# =================
caller = ''
modalAnswer = $ '#answer-modal'
modalAnswer.modal({ show: false })
publishStream = (uuid) ->
pubnub.publish
user: uuid
stream: myStream
pubnub.subscribe
user: uuid
stream: (bad, event) ->
document.querySelector('#call-video').src = URL.createObjectURL(event.stream)
disconnect: (uuid, pc) ->
document.querySelector('#call-video').src = ''
$(document).trigger "call:end"
connect: (uuid, pc) ->
# Do nothing
answer = (otherUuid) ->
if currentCall? and currentCall isnt otherUuid
hangUp()
currentCall = otherUuid
publishStream otherUuid
$(document).trigger "call:start", otherUuid
pubnub.publish
channel: 'answer'
message:
caller: caller
callee: uuid
$(document).on 'pubnub:ready', (event) =>
pubnub.subscribe
channel: 'call'
callback: (data) ->
if data.callee is uuid
caller = data.caller
onCalling data.caller
pubnub.subscribe
channel: 'answer'
callback: (data) ->
if data.caller is uuid
if data.callee isnt currentCall
hangUp()
currentCall = data.callee
publishStream data.callee
$(document).trigger "call:start", data.callee
onCalling = (caller) ->
caller = caller.split('-')[1]
modalAnswer.find('.caller').text "#{caller} is calling..."
modalAnswer.modal 'show'
modalAnswer.find('.btn-primary').on 'click', (event) ->
answer caller
modalAnswer.modal 'hide'
# Calling
# =================
modalCalling = $ '#calling-modal'
modalCalling.modal({ show: false })
$('#user-list').on 'click', 'a[data-user]', (event) ->
otherUuid = $(event.target).data 'user'
currentCall = otherUuid
name = otherUuid.split('-')[1]
modalCalling.find('.calling').text "Calling #{name}..."
modalCalling.modal 'show'
pubnub.publish
channel: 'call'
message:
caller: uuid
callee: otherUuid
$(document).on 'call:start', () ->
modalCalling.modal 'hide'
# Text Chat
# ================
messageBox = $ '#chat-receive-message'
messageInput = $ '#chat-message'
messageBox.text ''
messageControls = $ '#chat-area'
messageControls.hide()
getCombinedChannel = () ->
if currentCall > uuid
"#{currentCall}-#{uuid}"
else
"#{uuid}-#{currentCall}"
$(document).on "call:start", (event) =>
messageControls.show()
messageBox.text ''
pubnub.subscribe
channel: getCombinedChannel()
callback: (message) ->
messageBox.append "<br />#{message}"
messageBox.scrollTop messageBox[0].scrollHeight
$(document).on "call:end", (event) =>
messageControls.hide()
pubnub.unsubscribe
channel: getCombinedChannel()
messageInput.on 'keydown', (event) =>
if event.keyCode is 13 and currentCall?
pubnub.publish
channel: getCombinedChannel()
message: uuid.split('-')[1] + ": " + messageInput.val()
messageInput.val ''
# Hanging Up
# ================
$('#hang-up').on 'click', (event) ->
hangUp()
hangUp = () ->
pubnub.closeConnection currentCall, () ->
$(document).trigger "call:end"
# Call Status
# ================
videoControls = $ '#video-controls'
timeEl = videoControls.find '#time'
time = 0
timeInterval = null
videoControls.hide()
increment = () ->
time += 1
minutes = Math.floor(time / 60)
seconds = time % 60
if minutes.toString().length is 1 then minutes = "0#{minutes}"
if seconds.toString().length is 1 then seconds = "0#{seconds}"
timeEl.text "#{minutes}:#{seconds}"
$(document).on "call:start", (event) =>
videoControls.show()
time = 0
timeEl.text "00:00"
timeInterval = setInterval increment, 1000
$(document).on "call:end", (event) =>
videoControls.hide()
clearInterval timeInterval
gotStream = (stream) ->
document.querySelector('#self-call-video').src = URL.createObjectURL(stream)
#document.querySelector('#self-call-video').play()
myStream = stream
navigator.getUserMedia {audio: true, video: true}, gotStream, (error) ->
console.log("Error getting user media: ", error)
# Debug
# pages.caller.className += ' active'
# login("Guest" + Math.floor(Math.random() * 100))
# pages.login.className += ' active'
|
[
{
"context": "must be at least 3 characters'\n password: 'must be present'\n\n assert.calledWith(form.username.$setValid",
"end": 611,
"score": 0.9992044568061829,
"start": 596,
"tag": "PASSWORD",
"value": "must be present"
},
{
"context": "must be at least 3 characters'\... | tests/js/util-test.coffee | RichardLitt/h | 0 | assert = chai.assert
sinon.assert.expose(assert, prefix: '')
describe 'h.helpers.formHelpers', ->
formHelpers = null
beforeEach module('h.helpers.formHelpers')
beforeEach inject (_formHelpers_) ->
formHelpers = _formHelpers_
describe '.applyValidationErrors', ->
form = null
beforeEach ->
form =
username: {$setValidity: sinon.spy()}
password: {$setValidity: sinon.spy()}
it 'invalidates the "response" input for each error', ->
formHelpers.applyValidationErrors form,
username: 'must be at least 3 characters'
password: 'must be present'
assert.calledWith(form.username.$setValidity, 'response', false)
assert.calledWith(form.password.$setValidity, 'response', false)
it 'adds an error message to each input controller', ->
formHelpers.applyValidationErrors form,
username: 'must be at least 3 characters'
password: 'must be present'
assert.equal(form.username.responseErrorMessage, 'must be at least 3 characters')
assert.equal(form.password.responseErrorMessage, 'must be present')
| 50924 | assert = chai.assert
sinon.assert.expose(assert, prefix: '')
describe 'h.helpers.formHelpers', ->
formHelpers = null
beforeEach module('h.helpers.formHelpers')
beforeEach inject (_formHelpers_) ->
formHelpers = _formHelpers_
describe '.applyValidationErrors', ->
form = null
beforeEach ->
form =
username: {$setValidity: sinon.spy()}
password: {$setValidity: sinon.spy()}
it 'invalidates the "response" input for each error', ->
formHelpers.applyValidationErrors form,
username: 'must be at least 3 characters'
password: '<PASSWORD>'
assert.calledWith(form.username.$setValidity, 'response', false)
assert.calledWith(form.password.$setValidity, 'response', false)
it 'adds an error message to each input controller', ->
formHelpers.applyValidationErrors form,
username: 'must be at least 3 characters'
password: '<PASSWORD>'
assert.equal(form.username.responseErrorMessage, 'must be at least 3 characters')
assert.equal(form.password.responseErrorMessage, 'must be present')
| true | assert = chai.assert
sinon.assert.expose(assert, prefix: '')
describe 'h.helpers.formHelpers', ->
formHelpers = null
beforeEach module('h.helpers.formHelpers')
beforeEach inject (_formHelpers_) ->
formHelpers = _formHelpers_
describe '.applyValidationErrors', ->
form = null
beforeEach ->
form =
username: {$setValidity: sinon.spy()}
password: {$setValidity: sinon.spy()}
it 'invalidates the "response" input for each error', ->
formHelpers.applyValidationErrors form,
username: 'must be at least 3 characters'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
assert.calledWith(form.username.$setValidity, 'response', false)
assert.calledWith(form.password.$setValidity, 'response', false)
it 'adds an error message to each input controller', ->
formHelpers.applyValidationErrors form,
username: 'must be at least 3 characters'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
assert.equal(form.username.responseErrorMessage, 'must be at least 3 characters')
assert.equal(form.password.responseErrorMessage, 'must be present')
|
[
{
"context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission",
"end": 18,
"score": 0.9992863535881042,
"start": 12,
"tag": "NAME",
"value": "Joyent"
}
] | test/simple/test-fs-write-buffer.coffee | lxe/io.coffee | 0 | # Copyright Joyent, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
common = require("../common")
assert = require("assert")
path = require("path")
Buffer = require("buffer").Buffer
fs = require("fs")
filename = path.join(common.tmpDir, "write.txt")
expected = new Buffer("hello")
openCalled = 0
writeCalled = 0
fs.open filename, "w", 0644, (err, fd) ->
openCalled++
throw err if err
fs.write fd, expected, 0, expected.length, null, (err, written) ->
writeCalled++
throw err if err
assert.equal expected.length, written
fs.closeSync fd
found = fs.readFileSync(filename, "utf8")
assert.deepEqual expected.toString(), found
fs.unlinkSync filename
return
return
process.on "exit", ->
assert.equal 1, openCalled
assert.equal 1, writeCalled
return
| 77414 | # Copyright <NAME>, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
common = require("../common")
assert = require("assert")
path = require("path")
Buffer = require("buffer").Buffer
fs = require("fs")
filename = path.join(common.tmpDir, "write.txt")
expected = new Buffer("hello")
openCalled = 0
writeCalled = 0
fs.open filename, "w", 0644, (err, fd) ->
openCalled++
throw err if err
fs.write fd, expected, 0, expected.length, null, (err, written) ->
writeCalled++
throw err if err
assert.equal expected.length, written
fs.closeSync fd
found = fs.readFileSync(filename, "utf8")
assert.deepEqual expected.toString(), found
fs.unlinkSync filename
return
return
process.on "exit", ->
assert.equal 1, openCalled
assert.equal 1, writeCalled
return
| true | # Copyright PI:NAME:<NAME>END_PI, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
common = require("../common")
assert = require("assert")
path = require("path")
Buffer = require("buffer").Buffer
fs = require("fs")
filename = path.join(common.tmpDir, "write.txt")
expected = new Buffer("hello")
openCalled = 0
writeCalled = 0
fs.open filename, "w", 0644, (err, fd) ->
openCalled++
throw err if err
fs.write fd, expected, 0, expected.length, null, (err, written) ->
writeCalled++
throw err if err
assert.equal expected.length, written
fs.closeSync fd
found = fs.readFileSync(filename, "utf8")
assert.deepEqual expected.toString(), found
fs.unlinkSync filename
return
return
process.on "exit", ->
assert.equal 1, openCalled
assert.equal 1, writeCalled
return
|
[
{
"context": "# Copyright (C) 2014 Yusuke Suzuki <utatane.tea@gmail.com>\n#\n# Redistribution and us",
"end": 34,
"score": 0.9998287558555603,
"start": 21,
"tag": "NAME",
"value": "Yusuke Suzuki"
},
{
"context": "# Copyright (C) 2014 Yusuke Suzuki <utatane.tea@gmail.com>\n#\n# Redist... | node_modules/escope/gulpfile.coffee | lovecrossyou/simplewebpack-demo | 3 | # Copyright (C) 2014 Yusuke Suzuki <utatane.tea@gmail.com>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> 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.
gulp = require('gulp')
mocha = require('gulp-mocha')
jshint = require('gulp-jshint')
require('coffee-script/register')
TEST = [
'test/*.coffee'
]
LINT = [
'Gruntfile.js'
'escope.js'
]
gulp.task 'test', ->
return gulp.src(TEST)
.pipe(mocha(
reporter: 'spec'
))
gulp.task 'lint', ->
return gulp.src(LINT).pipe(jshint('.jshintrc'))
gulp.task 'travis', [ 'lint', 'test' ]
gulp.task 'default', [ 'travis' ]
| 162948 | # Copyright (C) 2014 <NAME> <<EMAIL>>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> 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.
gulp = require('gulp')
mocha = require('gulp-mocha')
jshint = require('gulp-jshint')
require('coffee-script/register')
TEST = [
'test/*.coffee'
]
LINT = [
'Gruntfile.js'
'escope.js'
]
gulp.task 'test', ->
return gulp.src(TEST)
.pipe(mocha(
reporter: 'spec'
))
gulp.task 'lint', ->
return gulp.src(LINT).pipe(jshint('.jshintrc'))
gulp.task 'travis', [ 'lint', 'test' ]
gulp.task 'default', [ 'travis' ]
| true | # Copyright (C) 2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> 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.
gulp = require('gulp')
mocha = require('gulp-mocha')
jshint = require('gulp-jshint')
require('coffee-script/register')
TEST = [
'test/*.coffee'
]
LINT = [
'Gruntfile.js'
'escope.js'
]
gulp.task 'test', ->
return gulp.src(TEST)
.pipe(mocha(
reporter: 'spec'
))
gulp.task 'lint', ->
return gulp.src(LINT).pipe(jshint('.jshintrc'))
gulp.task 'travis', [ 'lint', 'test' ]
gulp.task 'default', [ 'travis' ]
|
[
{
"context": " id: $scope.trxList.id\n contact_name: contactName\n }))\n $scope.trxList.totalRecords",
"end": 2052,
"score": 0.9991509914398193,
"start": 2041,
"tag": "NAME",
"value": "contactName"
}
] | src/components/widgets-layouts/custom/accounts-invoices-list/accounts-invoices-list.directive.coffee | maestrano/impac-angular | 7 | module = angular.module('impac.components.widgets.accounts-invoices-list', [])
module.controller('WidgetAccountsInvoicesListCtrl', ($scope, $q, ImpacRoutes, BoltResources) ->
# == Context and Helpers ========================================================================
w = $scope.widget
bolts = ImpacRoutes.bolts()
bolt_path = _.find(bolts, { name: 'finance', provider: 'maestrano' }).path
w.sortParamater = '-due_date'
$scope.trxList = {
display: false,
resources: 'invoices',
overdue: 'all',
transactions: [],
params:
include: 'contact'
fields:
contacts: 'name'
sort: w.sortParamater
currency: w.metadata.currency
filter:
'status.not': 'FORECAST'
}
# Widget Settings --------------------------------------
$scope.orgDeferred = $q.defer()
settingsPromises = [$scope.orgDeferred.promise]
# Widget specific methods
$scope.trxList.show = ->
$scope.trxList.display = true
$scope.trxList.hide = ->
$scope.trxList.display = false
$scope.trxList.fetch = (currentPage = 1) ->
params = angular.merge(
$scope.trxList.params, {
metadata: _.pick(w.metadata, 'organization_ids')
page: { number: currentPage }
currency: w.metadata.currency
include: 'contact'
fields: { contacts: 'name' }
}
)
BoltResources.index(bolt_path, $scope.trxList.resources, params).then(
(response) ->
# Clear transactions list and replace by newly fetched ones
_.remove($scope.trxList.transactions, -> true)
for trx in response.data.data
contactName = ''
if trx.relationships && trx.relationships.contact && trx.relationships.contact.data
contactName = _.find(response.data.included, (includedContact) ->
includedContact.id == trx.relationships.contact.data.id
).attributes.name
$scope.trxList.transactions.push(angular.merge(trx.attributes, {
id: $scope.trxList.id
contact_name: contactName
}))
$scope.trxList.totalRecords = response.data.meta.record_count
).finally(-> $scope.trxList.show())
$scope.trxList.changeResourcesType = (resourcesType) ->
return if resourcesType == $scope.trxList.resources
$scope.trxList.resources = resourcesType
$scope.trxList.fetch()
$scope.trxList.changeOverdueFilter = (overdueFilter) ->
return if overdueFilter == $scope.trxList.overdue
$scope.trxList.overdue = overdueFilter
$scope.trxList.params.filter.balance = 'gt 0' if overdueFilter == 'overdue'
delete $scope.trxList.params.filter.balance if overdueFilter == 'all'
$scope.trxList.fetch()
$scope.trxList.changeQuery = (query) ->
$scope.trxList.params.filter.query_data = query
$scope.trxList.fetch()
# --------------------------------------
w.initContext = ->
$scope.trxList.fetch()
# Widget is ready: can trigger the "wait for settings to be ready"
# --------------------------------------
$scope.widgetDeferred.resolve(settingsPromises)
)
module.directive('widgetAccountsInvoicesList', ->
return {
restrict: 'A',
controller: 'WidgetAccountsInvoicesListCtrl'
}
)
| 183946 | module = angular.module('impac.components.widgets.accounts-invoices-list', [])
module.controller('WidgetAccountsInvoicesListCtrl', ($scope, $q, ImpacRoutes, BoltResources) ->
# == Context and Helpers ========================================================================
w = $scope.widget
bolts = ImpacRoutes.bolts()
bolt_path = _.find(bolts, { name: 'finance', provider: 'maestrano' }).path
w.sortParamater = '-due_date'
$scope.trxList = {
display: false,
resources: 'invoices',
overdue: 'all',
transactions: [],
params:
include: 'contact'
fields:
contacts: 'name'
sort: w.sortParamater
currency: w.metadata.currency
filter:
'status.not': 'FORECAST'
}
# Widget Settings --------------------------------------
$scope.orgDeferred = $q.defer()
settingsPromises = [$scope.orgDeferred.promise]
# Widget specific methods
$scope.trxList.show = ->
$scope.trxList.display = true
$scope.trxList.hide = ->
$scope.trxList.display = false
$scope.trxList.fetch = (currentPage = 1) ->
params = angular.merge(
$scope.trxList.params, {
metadata: _.pick(w.metadata, 'organization_ids')
page: { number: currentPage }
currency: w.metadata.currency
include: 'contact'
fields: { contacts: 'name' }
}
)
BoltResources.index(bolt_path, $scope.trxList.resources, params).then(
(response) ->
# Clear transactions list and replace by newly fetched ones
_.remove($scope.trxList.transactions, -> true)
for trx in response.data.data
contactName = ''
if trx.relationships && trx.relationships.contact && trx.relationships.contact.data
contactName = _.find(response.data.included, (includedContact) ->
includedContact.id == trx.relationships.contact.data.id
).attributes.name
$scope.trxList.transactions.push(angular.merge(trx.attributes, {
id: $scope.trxList.id
contact_name: <NAME>
}))
$scope.trxList.totalRecords = response.data.meta.record_count
).finally(-> $scope.trxList.show())
$scope.trxList.changeResourcesType = (resourcesType) ->
return if resourcesType == $scope.trxList.resources
$scope.trxList.resources = resourcesType
$scope.trxList.fetch()
$scope.trxList.changeOverdueFilter = (overdueFilter) ->
return if overdueFilter == $scope.trxList.overdue
$scope.trxList.overdue = overdueFilter
$scope.trxList.params.filter.balance = 'gt 0' if overdueFilter == 'overdue'
delete $scope.trxList.params.filter.balance if overdueFilter == 'all'
$scope.trxList.fetch()
$scope.trxList.changeQuery = (query) ->
$scope.trxList.params.filter.query_data = query
$scope.trxList.fetch()
# --------------------------------------
w.initContext = ->
$scope.trxList.fetch()
# Widget is ready: can trigger the "wait for settings to be ready"
# --------------------------------------
$scope.widgetDeferred.resolve(settingsPromises)
)
module.directive('widgetAccountsInvoicesList', ->
return {
restrict: 'A',
controller: 'WidgetAccountsInvoicesListCtrl'
}
)
| true | module = angular.module('impac.components.widgets.accounts-invoices-list', [])
module.controller('WidgetAccountsInvoicesListCtrl', ($scope, $q, ImpacRoutes, BoltResources) ->
# == Context and Helpers ========================================================================
w = $scope.widget
bolts = ImpacRoutes.bolts()
bolt_path = _.find(bolts, { name: 'finance', provider: 'maestrano' }).path
w.sortParamater = '-due_date'
$scope.trxList = {
display: false,
resources: 'invoices',
overdue: 'all',
transactions: [],
params:
include: 'contact'
fields:
contacts: 'name'
sort: w.sortParamater
currency: w.metadata.currency
filter:
'status.not': 'FORECAST'
}
# Widget Settings --------------------------------------
$scope.orgDeferred = $q.defer()
settingsPromises = [$scope.orgDeferred.promise]
# Widget specific methods
$scope.trxList.show = ->
$scope.trxList.display = true
$scope.trxList.hide = ->
$scope.trxList.display = false
$scope.trxList.fetch = (currentPage = 1) ->
params = angular.merge(
$scope.trxList.params, {
metadata: _.pick(w.metadata, 'organization_ids')
page: { number: currentPage }
currency: w.metadata.currency
include: 'contact'
fields: { contacts: 'name' }
}
)
BoltResources.index(bolt_path, $scope.trxList.resources, params).then(
(response) ->
# Clear transactions list and replace by newly fetched ones
_.remove($scope.trxList.transactions, -> true)
for trx in response.data.data
contactName = ''
if trx.relationships && trx.relationships.contact && trx.relationships.contact.data
contactName = _.find(response.data.included, (includedContact) ->
includedContact.id == trx.relationships.contact.data.id
).attributes.name
$scope.trxList.transactions.push(angular.merge(trx.attributes, {
id: $scope.trxList.id
contact_name: PI:NAME:<NAME>END_PI
}))
$scope.trxList.totalRecords = response.data.meta.record_count
).finally(-> $scope.trxList.show())
$scope.trxList.changeResourcesType = (resourcesType) ->
return if resourcesType == $scope.trxList.resources
$scope.trxList.resources = resourcesType
$scope.trxList.fetch()
$scope.trxList.changeOverdueFilter = (overdueFilter) ->
return if overdueFilter == $scope.trxList.overdue
$scope.trxList.overdue = overdueFilter
$scope.trxList.params.filter.balance = 'gt 0' if overdueFilter == 'overdue'
delete $scope.trxList.params.filter.balance if overdueFilter == 'all'
$scope.trxList.fetch()
$scope.trxList.changeQuery = (query) ->
$scope.trxList.params.filter.query_data = query
$scope.trxList.fetch()
# --------------------------------------
w.initContext = ->
$scope.trxList.fetch()
# Widget is ready: can trigger the "wait for settings to be ready"
# --------------------------------------
$scope.widgetDeferred.resolve(settingsPromises)
)
module.directive('widgetAccountsInvoicesList', ->
return {
restrict: 'A',
controller: 'WidgetAccountsInvoicesListCtrl'
}
)
|
[
{
"context": "@state =\n key : if globals.os is 'mac' then '⌘ + C' else 'Ctrl + C'\n\n\n onCMDClick: ->\n\n codebloc",
"end": 567,
"score": 0.9259670972824097,
"start": 562,
"tag": "KEY",
"value": "⌘ + C"
},
{
"context": " key : if globals.os is 'mac' then '⌘ + C' else 'Ctr... | client/home/lib/utilities/components/kdcli/container.coffee | lionheart1022/koding | 0 | kd = require 'kd'
React = require 'app/react'
globals = require 'globals'
whoami = require 'app/util/whoami'
Tracker = require 'app/util/tracker'
copyToClipboard = require 'app/util/copyToClipboard'
View = require './view'
TeamFlux = require 'app/flux/teams'
KDReactorMixin = require 'app/flux/base/reactormixin'
module.exports = class KDCliContainer extends React.Component
getDataBindings: ->
return {
otaToken: TeamFlux.getters.otaToken
}
constructor: (props) ->
super props
@state =
key : if globals.os is 'mac' then '⌘ + C' else 'Ctrl + C'
onCMDClick: ->
codeblock = @refs.view.refs.codeblock
copyToClipboard codeblock
Tracker.track Tracker.KD_INSTALLED
render: ->
<View
ref='view'
copyKey={@state.key}
cmd={@state.otaToken}
onCMDClick={@bound 'onCMDClick'} />
KDCliContainer.include [KDReactorMixin]
| 95582 | kd = require 'kd'
React = require 'app/react'
globals = require 'globals'
whoami = require 'app/util/whoami'
Tracker = require 'app/util/tracker'
copyToClipboard = require 'app/util/copyToClipboard'
View = require './view'
TeamFlux = require 'app/flux/teams'
KDReactorMixin = require 'app/flux/base/reactormixin'
module.exports = class KDCliContainer extends React.Component
getDataBindings: ->
return {
otaToken: TeamFlux.getters.otaToken
}
constructor: (props) ->
super props
@state =
key : if globals.os is 'mac' then '<KEY>' else '<KEY>'
onCMDClick: ->
codeblock = @refs.view.refs.codeblock
copyToClipboard codeblock
Tracker.track Tracker.KD_INSTALLED
render: ->
<View
ref='view'
copyKey={@state.key}
cmd={@state.otaToken}
onCMDClick={@bound 'onCMDClick'} />
KDCliContainer.include [KDReactorMixin]
| true | kd = require 'kd'
React = require 'app/react'
globals = require 'globals'
whoami = require 'app/util/whoami'
Tracker = require 'app/util/tracker'
copyToClipboard = require 'app/util/copyToClipboard'
View = require './view'
TeamFlux = require 'app/flux/teams'
KDReactorMixin = require 'app/flux/base/reactormixin'
module.exports = class KDCliContainer extends React.Component
getDataBindings: ->
return {
otaToken: TeamFlux.getters.otaToken
}
constructor: (props) ->
super props
@state =
key : if globals.os is 'mac' then 'PI:KEY:<KEY>END_PI' else 'PI:KEY:<KEY>END_PI'
onCMDClick: ->
codeblock = @refs.view.refs.codeblock
copyToClipboard codeblock
Tracker.track Tracker.KD_INSTALLED
render: ->
<View
ref='view'
copyKey={@state.key}
cmd={@state.otaToken}
onCMDClick={@bound 'onCMDClick'} />
KDCliContainer.include [KDReactorMixin]
|
[
{
"context": "\n @items = [{\n name: 'Гра'\n torrent_file_url: 'game url'\n ",
"end": 895,
"score": 0.9477983713150024,
"start": 892,
"tag": "NAME",
"value": "Гра"
}
] | spec/adapters/pslan/parser_spec.coffee | dnesteryuk/hubot-torrent | 2 | Buffer = require('buffer').Buffer
Iconv = require('iconv').Iconv
Parser = require('../../../lib/hubot-torrent/adapters/pslan/parser')
sharedSet = require('./../../support/shared_tests/parser')
describe 'Adapters.Pslan.Parser', ->
wrapHtml = (body) ->
"<html><head></head><body>#{body}</body></html>"
wrapRes = (rows) ->
rows = for i, row of rows
"<tr>
<td></td>
<td><a href=\"#{row.torrent_file_url}\"><b>#{row.name}</b></a></td>
<td></td>
<td></td>
<td>#{row.size}<br></td>
<td><b><a><font>#{row.seeds}</font></a></b></td>
</tr>"
"<table id=\"highlighted\">#{rows.join('')}</table>"
describe '#parse', ->
sharedSet.call(this, Parser, wrapHtml, wrapRes)
describe 'when there are Ukranian items', ->
beforeEach ->
tracker = 'test'
@items = [{
name: 'Гра'
torrent_file_url: 'game url'
size: '10'
seeds: 1
tracker: tracker
}]
html = wrapHtml(wrapRes(@items))
iconv = new Iconv('utf-8', 'windows-1251')
html = iconv.convert(html).toString('binary')
@parser = new Parser(html, tracker)
it 'returns an array with names converted to UTF8', (done) ->
promise = @parser.parse()
promise.done(
(r) =>
expect(r).toEqual(@items)
done()
)
describe 'when an error appears while parsing the page', ->
beforeEach ->
html = wrapHtml()
@parser = new Parser('', 'test')
xit 'returns error', (done) ->
promise = @parser.parse()
promise.done(
(r) =>
console.info('dsa')
done()
)
| 20046 | Buffer = require('buffer').Buffer
Iconv = require('iconv').Iconv
Parser = require('../../../lib/hubot-torrent/adapters/pslan/parser')
sharedSet = require('./../../support/shared_tests/parser')
describe 'Adapters.Pslan.Parser', ->
wrapHtml = (body) ->
"<html><head></head><body>#{body}</body></html>"
wrapRes = (rows) ->
rows = for i, row of rows
"<tr>
<td></td>
<td><a href=\"#{row.torrent_file_url}\"><b>#{row.name}</b></a></td>
<td></td>
<td></td>
<td>#{row.size}<br></td>
<td><b><a><font>#{row.seeds}</font></a></b></td>
</tr>"
"<table id=\"highlighted\">#{rows.join('')}</table>"
describe '#parse', ->
sharedSet.call(this, Parser, wrapHtml, wrapRes)
describe 'when there are Ukranian items', ->
beforeEach ->
tracker = 'test'
@items = [{
name: '<NAME>'
torrent_file_url: 'game url'
size: '10'
seeds: 1
tracker: tracker
}]
html = wrapHtml(wrapRes(@items))
iconv = new Iconv('utf-8', 'windows-1251')
html = iconv.convert(html).toString('binary')
@parser = new Parser(html, tracker)
it 'returns an array with names converted to UTF8', (done) ->
promise = @parser.parse()
promise.done(
(r) =>
expect(r).toEqual(@items)
done()
)
describe 'when an error appears while parsing the page', ->
beforeEach ->
html = wrapHtml()
@parser = new Parser('', 'test')
xit 'returns error', (done) ->
promise = @parser.parse()
promise.done(
(r) =>
console.info('dsa')
done()
)
| true | Buffer = require('buffer').Buffer
Iconv = require('iconv').Iconv
Parser = require('../../../lib/hubot-torrent/adapters/pslan/parser')
sharedSet = require('./../../support/shared_tests/parser')
describe 'Adapters.Pslan.Parser', ->
wrapHtml = (body) ->
"<html><head></head><body>#{body}</body></html>"
wrapRes = (rows) ->
rows = for i, row of rows
"<tr>
<td></td>
<td><a href=\"#{row.torrent_file_url}\"><b>#{row.name}</b></a></td>
<td></td>
<td></td>
<td>#{row.size}<br></td>
<td><b><a><font>#{row.seeds}</font></a></b></td>
</tr>"
"<table id=\"highlighted\">#{rows.join('')}</table>"
describe '#parse', ->
sharedSet.call(this, Parser, wrapHtml, wrapRes)
describe 'when there are Ukranian items', ->
beforeEach ->
tracker = 'test'
@items = [{
name: 'PI:NAME:<NAME>END_PI'
torrent_file_url: 'game url'
size: '10'
seeds: 1
tracker: tracker
}]
html = wrapHtml(wrapRes(@items))
iconv = new Iconv('utf-8', 'windows-1251')
html = iconv.convert(html).toString('binary')
@parser = new Parser(html, tracker)
it 'returns an array with names converted to UTF8', (done) ->
promise = @parser.parse()
promise.done(
(r) =>
expect(r).toEqual(@items)
done()
)
describe 'when an error appears while parsing the page', ->
beforeEach ->
html = wrapHtml()
@parser = new Parser('', 'test')
xit 'returns error', (done) ->
promise = @parser.parse()
promise.done(
(r) =>
console.info('dsa')
done()
)
|
[
{
"context": "rn {\n userId: @userId\n name: @name\n link: @_getFileLink()\n ",
"end": 1118,
"score": 0.9014167189598083,
"start": 1118,
"tag": "NAME",
"value": ""
},
{
"context": " {\n userId: @userId\n name: @name\n ... | src/server/file/model.coffee | LaPingvino/rizzoma | 88 | Model = require('../common/model').Model
{
REDIRECT_URL
THUMBNAIL_REDIRECT_URL
} = require('./constants')
THUMBNAIL_NAME = 'thumbnail'
class FileModel extends Model
constructor: (@id, @userId, @path, @name, @size, @mimeType, @status, @uploaded = Date.now()) ->
###
Модель файла, прикрепленнного к блипу.
@param path: string - путь к файлу в хранилище
@param name: string - имя файла в хранилище
###
super('file')
@removed = no
@linkNotFound = no
@thumbnail = null #флаг, показывающий, есть ли миниатюра у файла.
getStorageFilePath: () ->
###
Возвращает URL файла в хранилище.
###
return "#{@path}#{encodeURIComponent(@name)}"
getStorageThumbnailPath: () ->
###
Возвращает URL миниатюры файла в хранилище.
###
return "#{@path}#{encodeURIComponent(THUMBNAIL_NAME)}"
getInfo: () ->
###
Возвращает информацию о файле дл передачи на клиент.
@returns: object
###
return {
userId: @userId
name: @name
link: @_getFileLink()
thumbnail: @_getThumbnailLink()
mime: @mimeType
size: @size
removed: @removed
}
setTumbnail: () ->
###
Устанавливает флаг "у файла есть миниатюра".
###
@thumbnail = true
_getFileLink: () ->
###
Возвращает локальный URL по которому доступен файл.
###
return "#{REDIRECT_URL}#{@id}"
_getThumbnailLink: () ->
###
Возвращает локальный URL по которому доступна миниатюра файла.
###
return "#{THUMBNAIL_REDIRECT_URL}#{@id}" if @thumbnail
exports.FileModel = FileModel | 106600 | Model = require('../common/model').Model
{
REDIRECT_URL
THUMBNAIL_REDIRECT_URL
} = require('./constants')
THUMBNAIL_NAME = 'thumbnail'
class FileModel extends Model
constructor: (@id, @userId, @path, @name, @size, @mimeType, @status, @uploaded = Date.now()) ->
###
Модель файла, прикрепленнного к блипу.
@param path: string - путь к файлу в хранилище
@param name: string - имя файла в хранилище
###
super('file')
@removed = no
@linkNotFound = no
@thumbnail = null #флаг, показывающий, есть ли миниатюра у файла.
getStorageFilePath: () ->
###
Возвращает URL файла в хранилище.
###
return "#{@path}#{encodeURIComponent(@name)}"
getStorageThumbnailPath: () ->
###
Возвращает URL миниатюры файла в хранилище.
###
return "#{@path}#{encodeURIComponent(THUMBNAIL_NAME)}"
getInfo: () ->
###
Возвращает информацию о файле дл передачи на клиент.
@returns: object
###
return {
userId: @userId
name:<NAME> @<NAME>
link: @_getFileLink()
thumbnail: @_getThumbnailLink()
mime: @mimeType
size: @size
removed: @removed
}
setTumbnail: () ->
###
Устанавливает флаг "у файла есть миниатюра".
###
@thumbnail = true
_getFileLink: () ->
###
Возвращает локальный URL по которому доступен файл.
###
return "#{REDIRECT_URL}#{@id}"
_getThumbnailLink: () ->
###
Возвращает локальный URL по которому доступна миниатюра файла.
###
return "#{THUMBNAIL_REDIRECT_URL}#{@id}" if @thumbnail
exports.FileModel = FileModel | true | Model = require('../common/model').Model
{
REDIRECT_URL
THUMBNAIL_REDIRECT_URL
} = require('./constants')
THUMBNAIL_NAME = 'thumbnail'
class FileModel extends Model
constructor: (@id, @userId, @path, @name, @size, @mimeType, @status, @uploaded = Date.now()) ->
###
Модель файла, прикрепленнного к блипу.
@param path: string - путь к файлу в хранилище
@param name: string - имя файла в хранилище
###
super('file')
@removed = no
@linkNotFound = no
@thumbnail = null #флаг, показывающий, есть ли миниатюра у файла.
getStorageFilePath: () ->
###
Возвращает URL файла в хранилище.
###
return "#{@path}#{encodeURIComponent(@name)}"
getStorageThumbnailPath: () ->
###
Возвращает URL миниатюры файла в хранилище.
###
return "#{@path}#{encodeURIComponent(THUMBNAIL_NAME)}"
getInfo: () ->
###
Возвращает информацию о файле дл передачи на клиент.
@returns: object
###
return {
userId: @userId
name:PI:NAME:<NAME>END_PI @PI:NAME:<NAME>END_PI
link: @_getFileLink()
thumbnail: @_getThumbnailLink()
mime: @mimeType
size: @size
removed: @removed
}
setTumbnail: () ->
###
Устанавливает флаг "у файла есть миниатюра".
###
@thumbnail = true
_getFileLink: () ->
###
Возвращает локальный URL по которому доступен файл.
###
return "#{REDIRECT_URL}#{@id}"
_getThumbnailLink: () ->
###
Возвращает локальный URL по которому доступна миниатюра файла.
###
return "#{THUMBNAIL_REDIRECT_URL}#{@id}" if @thumbnail
exports.FileModel = FileModel |
[
{
"context": "ss interoperability\n# Based on https://github.com/balupton/es6-javascript-class-interop\n# Helper functions t",
"end": 16237,
"score": 0.9959796071052551,
"start": 16229,
"tag": "USERNAME",
"value": "balupton"
},
{
"context": "'yo', 'buddy'\n eq i.greeting, 'yo'\n eq... | test/classes.coffee | takeratta/coffeescript | 0 | # Classes
# -------
# * Class Definition
# * Class Instantiation
# * Inheritance and Super
# * ES2015+ Class Interoperability
test "classes with a four-level inheritance chain", ->
class Base
func: (string) ->
"zero/#{string}"
@static: (string) ->
"static/#{string}"
class FirstChild extends Base
func: (string) ->
super('one/') + string
SecondChild = class extends FirstChild
func: (string) ->
super('two/') + string
thirdCtor = ->
@array = [1, 2, 3]
class ThirdChild extends SecondChild
constructor: ->
super()
thirdCtor.call this
# Gratuitous comment for testing.
func: (string) ->
super('three/') + string
result = (new ThirdChild).func 'four'
ok result is 'zero/one/two/three/four'
ok Base.static('word') is 'static/word'
ok (new ThirdChild).array.join(' ') is '1 2 3'
test "constructors with inheritance and super", ->
identity = (f) -> f
class TopClass
constructor: (arg) ->
@prop = 'top-' + arg
class SuperClass extends TopClass
constructor: (arg) ->
identity super 'super-' + arg
class SubClass extends SuperClass
constructor: ->
identity super 'sub'
ok (new SubClass).prop is 'top-super-sub'
test "'super' with accessors", ->
class Base
m: -> 4
n: -> 5
o: -> 6
name = 'o'
class A extends Base
m: -> super()
n: -> super.n()
"#{name}": -> super()
p: -> super[name]()
a = new A
eq 4, a.m()
eq 5, a.n()
eq 6, a.o()
eq 6, a.p()
test "soaked 'super' invocation", ->
class Base
method: -> 2
class A extends Base
method: -> super?()
noMethod: -> super?()
a = new A
eq 2, a.method()
eq undefined, a.noMethod()
name = 'noMethod'
class B extends Base
"#{'method'}": -> super?()
"#{'noMethod'}": -> super?() ? super['method']()
b = new B
eq 2, b.method()
eq 2, b.noMethod()
test "'@' referring to the current instance, and not being coerced into a call", ->
class ClassName
amI: ->
@ instanceof ClassName
obj = new ClassName
ok obj.amI()
test "super() calls in constructors of classes that are defined as object properties", ->
class Hive
constructor: (name) -> @name = name
class Hive.Bee extends Hive
constructor: (name) -> super name
maya = new Hive.Bee 'Maya'
ok maya.name is 'Maya'
test "classes with JS-keyword properties", ->
class Class
class: 'class'
name: -> @class
instance = new Class
ok instance.class is 'class'
ok instance.name() is 'class'
test "Classes with methods that are pre-bound to the instance, or statically, to the class", ->
class Dog
constructor: (name) ->
@name = name
bark: =>
"#{@name} woofs!"
@static = =>
new this('Dog')
spark = new Dog('Spark')
fido = new Dog('Fido')
fido.bark = spark.bark
ok fido.bark() is 'Spark woofs!'
obj = func: Dog.static
ok obj.func().name is 'Dog'
test "a bound function in a bound function", ->
class Mini
num: 10
generate: =>
for i in [1..3]
=>
@num
m = new Mini
eq (func() for func in m.generate()).join(' '), '10 10 10'
test "contructor called with varargs", ->
class Connection
constructor: (one, two, three) ->
[@one, @two, @three] = [one, two, three]
out: ->
"#{@one}-#{@two}-#{@three}"
list = [3, 2, 1]
conn = new Connection list...
ok conn instanceof Connection
ok conn.out() is '3-2-1'
test "calling super and passing along all arguments", ->
class Parent
method: (args...) -> @args = args
class Child extends Parent
method: -> super arguments...
c = new Child
c.method 1, 2, 3, 4
ok c.args.join(' ') is '1 2 3 4'
test "classes wrapped in decorators", ->
func = (klass) ->
klass::prop = 'value'
klass
func class Test
prop2: 'value2'
ok (new Test).prop is 'value'
ok (new Test).prop2 is 'value2'
test "anonymous classes", ->
obj =
klass: class
method: -> 'value'
instance = new obj.klass
ok instance.method() is 'value'
test "Implicit objects as static properties", ->
class Static
@static =
one: 1
two: 2
ok Static.static.one is 1
ok Static.static.two is 2
test "nothing classes", ->
c = class
ok c instanceof Function
test "classes with static-level implicit objects", ->
class A
@static = one: 1
two: 2
class B
@static = one: 1,
two: 2
eq A.static.one, 1
eq A.static.two, undefined
eq (new A).two, 2
eq B.static.one, 1
eq B.static.two, 2
eq (new B).two, undefined
test "classes with value'd constructors", ->
counter = 0
classMaker = ->
inner = ++counter
->
@value = inner
class One
constructor: classMaker()
class Two
constructor: classMaker()
eq (new One).value, 1
eq (new Two).value, 2
eq (new One).value, 1
eq (new Two).value, 2
test "executable class bodies", ->
class A
if true
b: 'b'
else
c: 'c'
a = new A
eq a.b, 'b'
eq a.c, undefined
test "#2502: parenthesizing inner object values", ->
class A
category: (type: 'string')
sections: (type: 'number', default: 0)
eq (new A).category.type, 'string'
eq (new A).sections.default, 0
test "conditional prototype property assignment", ->
debug = false
class Person
if debug
age: -> 10
else
age: -> 20
eq (new Person).age(), 20
test "mild metaprogramming", ->
class Base
@attr: (name) ->
@::[name] = (val) ->
if arguments.length > 0
@["_#{name}"] = val
else
@["_#{name}"]
class Robot extends Base
@attr 'power'
@attr 'speed'
robby = new Robot
ok robby.power() is undefined
robby.power 11
robby.speed Infinity
eq robby.power(), 11
eq robby.speed(), Infinity
test "namespaced classes do not reserve their function name in outside scope", ->
one = {}
two = {}
class one.Klass
@label = "one"
class two.Klass
@label = "two"
eq typeof Klass, 'undefined'
eq one.Klass.label, 'one'
eq two.Klass.label, 'two'
test "nested classes", ->
class Outer
constructor: ->
@label = 'outer'
class @Inner
constructor: ->
@label = 'inner'
eq (new Outer).label, 'outer'
eq (new Outer.Inner).label, 'inner'
test "variables in constructor bodies are correctly scoped", ->
class A
x = 1
constructor: ->
x = 10
y = 20
y = 2
captured: ->
{x, y}
a = new A
eq a.captured().x, 10
eq a.captured().y, 2
test "Issue #924: Static methods in nested classes", ->
class A
@B: class
@c = -> 5
eq A.B.c(), 5
test "`class extends this`", ->
class A
func: -> 'A'
B = null
makeClass = ->
B = class extends this
func: -> super() + ' B'
makeClass.call A
eq (new B()).func(), 'A B'
test "ensure that constructors invoked with splats return a new object", ->
args = [1, 2, 3]
Type = (@args) ->
type = new Type args
ok type and type instanceof Type
ok type.args and type.args instanceof Array
ok v is args[i] for v, i in type.args
Type1 = (@a, @b, @c) ->
type1 = new Type1 args...
ok type1 instanceof Type1
eq type1.constructor, Type1
ok type1.a is args[0] and type1.b is args[1] and type1.c is args[2]
# Ensure that constructors invoked with splats cache the function.
called = 0
get = -> if called++ then false else class Type
new (get()) args...
test "`new` shouldn't add extra parens", ->
ok new Date().constructor is Date
test "`new` works against bare function", ->
eq Date, new ->
Date
test "#1182: a subclass should be able to set its constructor to an external function", ->
ctor = ->
@val = 1
return
class A
class B extends A
constructor: ctor
eq (new B).val, 1
test "#1182: external constructors continued", ->
ctor = ->
class A
class B extends A
method: ->
constructor: ctor
ok B::method
test "#1313: misplaced __extends", ->
nonce = {}
class A
class B extends A
prop: nonce
constructor: -> super()
eq nonce, B::prop
test "#1182: execution order needs to be considered as well", ->
counter = 0
makeFn = (n) -> eq n, ++counter; ->
class B extends (makeFn 1)
@B: makeFn 2
constructor: makeFn 3
test "#1182: external constructors with bound functions", ->
fn = ->
{one: 1}
this
class B
class A
constructor: fn
method: => this instanceof A
ok (new A).method.call(new B)
test "#1372: bound class methods with reserved names", ->
class C
delete: =>
ok C::delete
test "#1380: `super` with reserved names", ->
class C
do: -> super()
ok C::do
class B
0: -> super()
ok B::[0]
test "#1464: bound class methods should keep context", ->
nonce = {}
nonce2 = {}
class C
constructor: (@id) ->
@boundStaticColon: => new this(nonce)
@boundStaticEqual= => new this(nonce2)
eq nonce, C.boundStaticColon().id
eq nonce2, C.boundStaticEqual().id
test "#1009: classes with reserved words as determined names", -> (->
eq 'function', typeof (class @for)
ok not /\beval\b/.test (class @eval).toString()
ok not /\barguments\b/.test (class @arguments).toString()
).call {}
test "#1482: classes can extend expressions", ->
id = (x) -> x
nonce = {}
class A then nonce: nonce
class B extends id A
eq nonce, (new B).nonce
test "#1598: super works for static methods too", ->
class Parent
method: ->
'NO'
@method: ->
'yes'
class Child extends Parent
@method: ->
'pass? ' + super()
eq Child.method(), 'pass? yes'
test "#1842: Regression with bound functions within bound class methods", ->
class Store
@bound: =>
do =>
eq this, Store
Store.bound()
# And a fancier case:
class Store
eq this, Store
@bound: =>
do =>
eq this, Store
@unbound: ->
eq this, Store
instance: =>
ok this instanceof Store
Store.bound()
Store.unbound()
(new Store).instance()
test "#1876: Class @A extends A", ->
class A
class @A extends A
ok (new @A) instanceof A
test "#1813: Passing class definitions as expressions", ->
ident = (x) -> x
result = ident class A then x = 1
eq result, A
result = ident class B extends A
x = 1
eq result, B
test "#1966: external constructors should produce their return value", ->
ctor = -> {}
class A then constructor: ctor
ok (new A) not instanceof A
test "#1980: regression with an inherited class with static function members", ->
class A
class B extends A
@static: => 'value'
eq B.static(), 'value'
test "#1534: class then 'use strict'", ->
# [14.1 Directive Prologues and the Use Strict Directive](http://es5.github.com/#x14.1)
nonce = {}
error = 'do -> ok this'
strictTest = "do ->'use strict';#{error}"
return unless (try CoffeeScript.run strictTest, bare: yes catch e then nonce) is nonce
throws -> CoffeeScript.run "class then 'use strict';#{error}", bare: yes
doesNotThrow -> CoffeeScript.run "class then #{error}", bare: yes
doesNotThrow -> CoffeeScript.run "class then #{error};'use strict'", bare: yes
# comments are ignored in the Directive Prologue
comments = ["""
class
### comment ###
'use strict'
#{error}""",
"""
class
### comment 1 ###
### comment 2 ###
'use strict'
#{error}""",
"""
class
### comment 1 ###
### comment 2 ###
'use strict'
#{error}
### comment 3 ###"""
]
throws (-> CoffeeScript.run comment, bare: yes) for comment in comments
# [ES5 §14.1](http://es5.github.com/#x14.1) allows for other directives
directives = ["""
class
'directive 1'
'use strict'
#{error}""",
"""
class
'use strict'
'directive 2'
#{error}""",
"""
class
### comment 1 ###
'directive 1'
'use strict'
#{error}""",
"""
class
### comment 1 ###
'directive 1'
### comment 2 ###
'use strict'
#{error}"""
]
throws (-> CoffeeScript.run directive, bare: yes) for directive in directives
test "#2052: classes should work in strict mode", ->
try
do ->
'use strict'
class A
catch e
ok no
test "directives in class with extends ", ->
strictTest = """
class extends Object
### comment ###
'use strict'
do -> eq this, undefined
"""
CoffeeScript.run strictTest, bare: yes
test "#2630: class bodies can't reference arguments", ->
throws ->
CoffeeScript.compile('class Test then arguments')
# #4320: Don't be too eager when checking, though.
class Test
arguments: 5
eq 5, Test::arguments
test "#2319: fn class n extends o.p [INDENT] x = 123", ->
first = ->
base = onebase: ->
first class OneKeeper extends base.onebase
one = 1
one: -> one
eq new OneKeeper().one(), 1
test "#2599: other typed constructors should be inherited", ->
class Base
constructor: -> return {}
class Derived extends Base
ok (new Derived) not instanceof Derived
ok (new Derived) not instanceof Base
ok (new Base) not instanceof Base
test "extending native objects works with and without defining a constructor", ->
class MyArray extends Array
method: -> 'yes!'
myArray = new MyArray
ok myArray instanceof MyArray
ok 'yes!', myArray.method()
class OverrideArray extends Array
constructor: -> super()
method: -> 'yes!'
overrideArray = new OverrideArray
ok overrideArray instanceof OverrideArray
eq 'yes!', overrideArray.method()
test "#2782: non-alphanumeric-named bound functions", ->
class A
'b:c': =>
'd'
eq (new A)['b:c'](), 'd'
test "#2781: overriding bound functions", ->
class A
a: ->
@b()
b: =>
1
class B extends A
b: =>
2
b = (new A).b
eq b(), 1
b = (new B).b
eq b(), 2
test "#2791: bound function with destructured argument", ->
class Foo
method: ({a}) => 'Bar'
eq (new Foo).method({a: 'Bar'}), 'Bar'
test "#2796: ditto, ditto, ditto", ->
answer = null
outsideMethod = (func) ->
func.call message: 'wrong!'
class Base
constructor: ->
@message = 'right!'
outsideMethod @echo
echo: =>
answer = @message
new Base
eq answer, 'right!'
test "#3063: Class bodies cannot contain pure statements", ->
throws -> CoffeeScript.compile """
class extends S
return if S.f
@f: => this
"""
test "#2949: super in static method with reserved name", ->
class Foo
@static: -> 'baz'
class Bar extends Foo
@static: -> super()
eq Bar.static(), 'baz'
test "#3232: super in static methods (not object-assigned)", ->
class Foo
@baz = -> true
@qux = -> true
class Bar extends Foo
@baz = -> super()
Bar.qux = -> super()
ok Bar.baz()
ok Bar.qux()
test "#1392 calling `super` in methods defined on namespaced classes", ->
class Base
m: -> 5
n: -> 4
namespace =
A: ->
B: ->
class namespace.A extends Base
m: -> super()
eq 5, (new namespace.A).m()
namespace.B::m = namespace.A::m
namespace.A::m = null
eq 5, (new namespace.B).m()
class C
@a: class extends Base
m: -> super()
eq 5, (new C.a).m()
test "#4436 immediately instantiated named class", ->
ok new class Foo
test "dynamic method names", ->
class A
"#{name = 'm'}": -> 1
eq 1, new A().m()
class B extends A
"#{name = 'm'}": -> super()
eq 1, new B().m()
getName = -> 'm'
class C
"#{name = getName()}": -> 1
eq 1, new C().m()
test "dynamic method names and super", ->
class Base
@m: -> 6
m: -> 5
m2: -> 4.5
n: -> 4
name = -> count++; 'n'
count = 0
m = 'm'
class A extends Base
"#{m}": -> super()
"#{name()}": -> super()
m = 'n'
eq 5, (new A).m()
eq 4, (new A).n()
eq 1, count
m = 'm'
m2 = 'm2'
count = 0
class B extends Base
@[name()] = -> super()
"#{m}": -> super()
"#{m2}": -> super()
b = new B
m = m2 = 'n'
eq 6, B.m()
eq 5, b.m()
eq 4.5, b.m2()
eq 1, count
class C extends B
m: -> super()
eq 5, (new C).m()
# ES2015+ class interoperability
# Based on https://github.com/balupton/es6-javascript-class-interop
# Helper functions to generate true ES classes to extend:
getBasicClass = ->
```
class BasicClass {
constructor (greeting) {
this.greeting = greeting || 'hi'
}
}
```
BasicClass
getExtendedClass = (BaseClass) ->
```
class ExtendedClass extends BaseClass {
constructor (greeting, name) {
super(greeting || 'hello')
this.name = name
}
}
```
ExtendedClass
test "can instantiate a basic ES class", ->
BasicClass = getBasicClass()
i = new BasicClass 'howdy!'
eq i.greeting, 'howdy!'
test "can instantiate an extended ES class", ->
BasicClass = getBasicClass()
ExtendedClass = getExtendedClass BasicClass
i = new ExtendedClass 'yo', 'buddy'
eq i.greeting, 'yo'
eq i.name, 'buddy'
test "can extend a basic ES class", ->
BasicClass = getBasicClass()
class ExtendedClass extends BasicClass
constructor: (@name) ->
super()
i = new ExtendedClass 'dude'
eq i.name, 'dude'
test "can extend an extended ES class", ->
BasicClass = getBasicClass()
ExtendedClass = getExtendedClass BasicClass
class ExtendedExtendedClass extends ExtendedClass
constructor: (@value) ->
super()
getDoubledValue: ->
@value * 2
i = new ExtendedExtendedClass 7
eq i.getDoubledValue(), 14
test "CoffeeScript class can be extended in ES", ->
class CoffeeClass
constructor: (@favoriteDrink = 'latte', @size = 'grande') ->
getDrinkOrder: ->
"#{@size} #{@favoriteDrink}"
```
class ECMAScriptClass extends CoffeeClass {
constructor (favoriteDrink) {
super(favoriteDrink);
this.favoriteDrink = this.favoriteDrink + ' with a dash of semicolons';
}
}
```
e = new ECMAScriptClass 'coffee'
eq e.getDrinkOrder(), 'grande coffee with a dash of semicolons'
test "extended CoffeeScript class can be extended in ES", ->
class CoffeeClass
constructor: (@favoriteDrink = 'latte') ->
class CoffeeClassWithDrinkOrder extends CoffeeClass
constructor: (@favoriteDrink, @size = 'grande') ->
super()
getDrinkOrder: ->
"#{@size} #{@favoriteDrink}"
```
class ECMAScriptClass extends CoffeeClassWithDrinkOrder {
constructor (favoriteDrink) {
super(favoriteDrink);
this.favoriteDrink = this.favoriteDrink + ' with a dash of semicolons';
}
}
```
e = new ECMAScriptClass 'coffee'
eq e.getDrinkOrder(), 'grande coffee with a dash of semicolons'
test "`this` access after `super` in extended classes", ->
class Base
class Test extends Base
constructor: (param, @param) ->
eq param, nonce
result = { super: super(), @param, @method }
eq result.super, this
eq result.param, @param
eq result.method, @method
ok result.method isnt Test::method
method: =>
nonce = {}
new Test nonce, {}
test "`@`-params and bound methods with multiple `super` paths (blocks)", ->
nonce = {}
class Base
constructor: (@name) ->
class Test extends Base
constructor: (param, @param) ->
if param
super 'param'
eq @name, 'param'
else
super 'not param'
eq @name, 'not param'
eq @param, nonce
ok @method isnt Test::method
method: =>
new Test true, nonce
new Test false, nonce
test "`@`-params and bound methods with multiple `super` paths (expressions)", ->
nonce = {}
class Base
constructor: (@name) ->
class Test extends Base
constructor: (param, @param) ->
# Contrived example: force each path into an expression with inline assertions
if param
result = (
eq (super 'param'), @;
eq @name, 'param';
eq @param, nonce;
ok @method isnt Test::method
)
else
result = (
eq (super 'not param'), @;
eq @name, 'not param';
eq @param, nonce;
ok @method isnt Test::method
)
method: =>
new Test true, nonce
new Test false, nonce
test "constructor super in arrow functions", ->
class Test extends (class)
constructor: (@param) ->
do => super()
eq @param, nonce
new Test nonce = {}
# TODO Some of these tests use CoffeeScript.compile and CoffeeScript.run when they could use
# regular test mechanics.
# TODO Some of these tests might be better placed in `test/error_messages.coffee`.
# TODO Some of these tests are duplicates.
# Ensure that we always throw if we experience more than one super()
# call in a constructor. This ends up being a runtime error.
# Should be caught at compile time.
test "multiple super calls", ->
throwsA = """
class A
constructor: (@drink) ->
make: -> "Making a #{@drink}"
class MultiSuper extends A
constructor: (drink) ->
super(drink)
super(drink)
@newDrink = drink
new MultiSuper('Late').make()
"""
throws -> CoffeeScript.run throwsA, bare: yes
# Basic test to ensure we can pass @params in a constuctor and
# inheritance works correctly
test "@ params", ->
class A
constructor: (@drink, @shots, @flavor) ->
make: -> "Making a #{@flavor} #{@drink} with #{@shots} shot(s)"
a = new A('Machiato', 2, 'chocolate')
eq a.make(), "Making a chocolate Machiato with 2 shot(s)"
class B extends A
b = new B('Machiato', 2, 'chocolate')
eq b.make(), "Making a chocolate Machiato with 2 shot(s)"
# Ensure we can accept @params with default parameters in a constructor
test "@ params with defaults in a constructor", ->
class A
# Multiple @ params with defaults
constructor: (@drink = 'Americano', @shots = '1', @flavor = 'caramel') ->
make: -> "Making a #{@flavor} #{@drink} with #{@shots} shot(s)"
a = new A()
eq a.make(), "Making a caramel Americano with 1 shot(s)"
# Ensure we can handle default constructors with class params
test "@ params with class params", ->
class Beverage
drink: 'Americano'
shots: '1'
flavor: 'caramel'
class A
# Class creation as a default param with `this`
constructor: (@drink = new Beverage()) ->
a = new A()
eq a.drink.drink, 'Americano'
beverage = new Beverage
class B
# class costruction with a default external param
constructor: (@drink = beverage) ->
b = new B()
eq b.drink.drink, 'Americano'
class C
# Default constructor with anonymous empty class
constructor: (@meta = class) ->
c = new C()
ok c.meta instanceof Function
test "@ params without super, including errors", ->
classA = """
class A
constructor: (@drink) ->
make: -> "Making a #{@drink}"
a = new A('Machiato')
"""
throwsB = """
class B extends A
#implied super
constructor: (@drink) ->
b = new B('Machiato')
"""
throws -> CoffeeScript.compile classA + throwsB, bare: yes
test "@ params super race condition", ->
classA = """
class A
constructor: (@drink) ->
make: -> "Making a #{@drink}"
"""
throwsB = """
class B extends A
constructor: (@params) ->
b = new B('Machiato')
"""
throws -> CoffeeScript.compile classA + throwsB, bare: yes
# Race condition with @ and super
throwsC = """
class C extends A
constructor: (@params) ->
super(@params)
c = new C('Machiato')
"""
throws -> CoffeeScript.compile classA + throwsC, bare: yes
test "@ with super call", ->
class D
make: -> "Making a #{@drink}"
class E extends D
constructor: (@drink) ->
super()
e = new E('Machiato')
eq e.make(), "Making a Machiato"
test "@ with splats and super call", ->
class A
make: -> "Making a #{@drink}"
class B extends A
constructor: (@drink...) ->
super()
B = new B('Machiato')
eq B.make(), "Making a Machiato"
test "super and external constructors", ->
# external constructor with @ param is allowed
ctorA = (@drink) ->
class A
constructor: ctorA
make: -> "Making a #{@drink}"
a = new A('Machiato')
eq a.make(), "Making a Machiato"
# External constructor with super
throwsC = """
class B
constructor: (@drink) ->
make: -> "Making a #{@drink}"
ctorC = (drink) ->
super(drink)
class C extends B
constructor: ctorC
c = new C('Machiato')
"""
throws -> CoffeeScript.compile throwsC, bare: yes
test "bound functions without super", ->
# Bound function with @
# Throw on compile, since bound
# constructors are illegal
throwsA = """
class A
constructor: (drink) =>
@drink = drink
"""
throws -> CoffeeScript.compile throwsA, bare: yes
test "super in a bound function in a constructor", ->
throwsB = """
class A
class B extends A
constructor: do => super
"""
throws -> CoffeeScript.compile throwsB, bare: yes
test "super in a bound function", ->
class A
constructor: (@drink) ->
make: -> "Making a #{@drink}"
class B extends A
make: (@flavor) =>
super() + " with #{@flavor}"
b = new B('Machiato')
eq b.make('vanilla'), "Making a Machiato with vanilla"
# super in a bound function in a bound function
class C extends A
make: (@flavor) =>
func = () =>
super() + " with #{@flavor}"
func()
c = new C('Machiato')
eq c.make('vanilla'), "Making a Machiato with vanilla"
# bound function in a constructor
class D extends A
constructor: (drink) ->
super(drink)
x = =>
eq @drink, "Machiato"
x()
d = new D('Machiato')
eq d.make(), "Making a Machiato"
# duplicate
test "super in a try/catch", ->
classA = """
class A
constructor: (param) ->
throw "" unless param
"""
throwsB = """
class B extends A
constructor: ->
try
super()
"""
throwsC = """
ctor = ->
try
super()
class C extends A
constructor: ctor
"""
throws -> CoffeeScript.run classA + throwsB, bare: yes
throws -> CoffeeScript.run classA + throwsC, bare: yes
test "mixed ES6 and CS6 classes with a four-level inheritance chain", ->
# Extended test
# ES2015+ class interoperability
```
class Base {
constructor (greeting) {
this.greeting = greeting || 'hi';
}
func (string) {
return 'zero/' + string;
}
static staticFunc (string) {
return 'static/' + string;
}
}
```
class FirstChild extends Base
func: (string) ->
super('one/') + string
```
class SecondChild extends FirstChild {
func (string) {
return super.func('two/' + string);
}
}
```
thirdCtor = ->
@array = [1, 2, 3]
class ThirdChild extends SecondChild
constructor: ->
super()
thirdCtor.call this
func: (string) ->
super('three/') + string
result = (new ThirdChild).func 'four'
ok result is 'zero/one/two/three/four'
ok Base.staticFunc('word') is 'static/word'
# exercise extends in a nested class
test "nested classes with super", ->
class Outer
constructor: ->
@label = 'outer'
class @Inner
constructor: ->
@label = 'inner'
class @ExtendedInner extends @Inner
constructor: ->
tmp = super()
@label = tmp.label + ' extended'
@extender: () =>
class ExtendedSelf extends @
constructor: ->
tmp = super()
@label = tmp.label + ' from this'
new ExtendedSelf
eq (new Outer).label, 'outer'
eq (new Outer.Inner).label, 'inner'
eq (new Outer.ExtendedInner).label, 'inner extended'
eq (Outer.extender()).label, 'outer from this'
test "Static methods generate 'static' keywords", ->
compile = """
class CheckStatic
constructor: (@drink) ->
@className: -> 'CheckStatic'
c = new CheckStatic('Machiato')
"""
result = CoffeeScript.compile compile, bare: yes
ok result.match(' static ')
test "Static methods in nested classes", ->
class Outer
@name: -> 'Outer'
class @Inner
@name: -> 'Inner'
eq Outer.name(), 'Outer'
eq Outer.Inner.name(), 'Inner'
test "mixed constructors with inheritance and ES6 super", ->
identity = (f) -> f
class TopClass
constructor: (arg) ->
@prop = 'top-' + arg
```
class SuperClass extends TopClass {
constructor (arg) {
identity(super('super-' + arg));
}
}
```
class SubClass extends SuperClass
constructor: ->
identity super 'sub'
ok (new SubClass).prop is 'top-super-sub'
test "ES6 static class methods can be overriden", ->
class A
@name: -> 'A'
class B extends A
@name: -> 'B'
eq A.name(), 'A'
eq B.name(), 'B'
# If creating static by direct assignment rather than ES6 static keyword
test "ES6 Static methods should set `this` to undefined // ES6 ", ->
class A
@test: ->
eq this, undefined
# Ensure that our object prototypes work with ES6
test "ES6 prototypes can be overriden", ->
class A
className: 'classA'
```
class B {
test () {return "B";};
}
```
b = new B
a = new A
eq a.className, 'classA'
eq b.test(), 'B'
Object.setPrototypeOf(b, a)
eq b.className, 'classA'
# This shouldn't throw,
# as we only change inheritance not object construction
# This may be an issue with ES, rather than CS construction?
#eq b.test(), 'B'
class D extends B
B::test = () -> 'D'
eq (new D).test(), 'D'
# TODO: implement this error check
# test "ES6 conformance to extending non-classes", ->
# A = (@title) ->
# 'Title: ' + @
# class B extends A
# b = new B('caffeinated')
# eq b.title, 'caffeinated'
# # Check inheritance chain
# A::getTitle = () -> @title
# eq b.getTitle(), 'caffeinated'
# throwsC = """
# C = {title: 'invalid'}
# class D extends {}
# """
# # This should catch on compile and message should be "class can only extend classes and functions."
# throws -> CoffeeScript.run throwsC, bare: yes
# TODO: Evaluate future compliance with "strict mode";
# test "Class function environment should be in `strict mode`, ie as if 'use strict' was in use", ->
# class A
# # this might be a meaningless test, since these are likely to be runtime errors and different
# # for every browser. Thoughts?
# constructor: () ->
# # Ivalid: prop reassignment
# @state = {prop: [1], prop: {a: 'a'}}
# # eval reassignment
# @badEval = eval;
# # Should throw, but doesn't
# a = new A
# TODO: new.target needs support Separate issue
# test "ES6 support for new.target (functions and constructors)", ->
# throwsA = """
# class A
# constructor: () ->
# a = new.target.name
# """
# throws -> CoffeeScript.compile throwsA, bare: yes
test "only one method named constructor allowed", ->
throwsA = """
class A
constructor: (@first) ->
constructor: (@last) ->
"""
throws -> CoffeeScript.compile throwsA, bare: yes
test "If the constructor of a child class does not call super,it should return an object.", ->
nonce = {}
class A
class B extends A
constructor: ->
return nonce
eq nonce, new B
test "super can only exist in extended classes", ->
throwsA = """
class A
constructor: (@name) ->
super()
"""
throws -> CoffeeScript.compile throwsA, bare: yes
# --- CS1 classes compatability breaks ---
test "CS6 Class extends a CS1 compiled class", ->
```
// Generated by CoffeeScript 1.11.1
var BaseCS1, ExtendedCS1,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
BaseCS1 = (function() {
function BaseCS1(drink) {
this.drink = drink;
}
BaseCS1.prototype.make = function() {
return "making a " + this.drink;
};
BaseCS1.className = function() {
return 'BaseCS1';
};
return BaseCS1;
})();
ExtendedCS1 = (function(superClass) {
extend(ExtendedCS1, superClass);
function ExtendedCS1(flavor) {
this.flavor = flavor;
ExtendedCS1.__super__.constructor.call(this, 'cafe ole');
}
ExtendedCS1.prototype.make = function() {
return "making a " + this.drink + " with " + this.flavor;
};
ExtendedCS1.className = function() {
return 'ExtendedCS1';
};
return ExtendedCS1;
})(BaseCS1);
```
class B extends BaseCS1
eq B.className(), 'BaseCS1'
b = new B('machiato')
eq b.make(), "making a machiato"
test "CS6 Class extends an extended CS1 compiled class", ->
```
// Generated by CoffeeScript 1.11.1
var BaseCS1, ExtendedCS1,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
BaseCS1 = (function() {
function BaseCS1(drink) {
this.drink = drink;
}
BaseCS1.prototype.make = function() {
return "making a " + this.drink;
};
BaseCS1.className = function() {
return 'BaseCS1';
};
return BaseCS1;
})();
ExtendedCS1 = (function(superClass) {
extend(ExtendedCS1, superClass);
function ExtendedCS1(flavor) {
this.flavor = flavor;
ExtendedCS1.__super__.constructor.call(this, 'cafe ole');
}
ExtendedCS1.prototype.make = function() {
return "making a " + this.drink + " with " + this.flavor;
};
ExtendedCS1.className = function() {
return 'ExtendedCS1';
};
return ExtendedCS1;
})(BaseCS1);
```
class B extends ExtendedCS1
eq B.className(), 'ExtendedCS1'
b = new B('vanilla')
eq b.make(), "making a cafe ole with vanilla"
test "CS6 Class extends a CS1 compiled class with super()", ->
```
// Generated by CoffeeScript 1.11.1
var BaseCS1, ExtendedCS1,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
BaseCS1 = (function() {
function BaseCS1(drink) {
this.drink = drink;
}
BaseCS1.prototype.make = function() {
return "making a " + this.drink;
};
BaseCS1.className = function() {
return 'BaseCS1';
};
return BaseCS1;
})();
ExtendedCS1 = (function(superClass) {
extend(ExtendedCS1, superClass);
function ExtendedCS1(flavor) {
this.flavor = flavor;
ExtendedCS1.__super__.constructor.call(this, 'cafe ole');
}
ExtendedCS1.prototype.make = function() {
return "making a " + this.drink + " with " + this.flavor;
};
ExtendedCS1.className = function() {
return 'ExtendedCS1';
};
return ExtendedCS1;
})(BaseCS1);
```
class B extends ExtendedCS1
constructor: (@shots) ->
super('caramel')
make: () ->
super() + " and #{@shots} shots of espresso"
eq B.className(), 'ExtendedCS1'
b = new B('three')
eq b.make(), "making a cafe ole with caramel and three shots of espresso"
test 'Bound method called normally before binding is ok', ->
class Base
constructor: ->
@setProp()
eq @derivedBound(), 3
class Derived extends Base
setProp: ->
@prop = 3
derivedBound: =>
@prop
d = new Derived
test 'Bound method called as callback after super() is ok', ->
class Base
class Derived extends Base
constructor: (@prop = 3) ->
super()
f = @derivedBound
eq f(), 3
derivedBound: =>
@prop
d = new Derived
{derivedBound} = d
eq derivedBound(), 3
test 'Bound method of base class called as callback is ok', ->
class Base
constructor: (@prop = 3) ->
f = @baseBound
eq f(), 3
baseBound: =>
@prop
b = new Base
{baseBound} = b
eq baseBound(), 3
test 'Bound method of prop-named class called as callback is ok', ->
Hive = {}
class Hive.Bee
constructor: (@prop = 3) ->
f = @baseBound
eq f(), 3
baseBound: =>
@prop
b = new Hive.Bee
{baseBound} = b
eq baseBound(), 3
test 'Bound method of class with expression base class called as callback is ok', ->
calledB = no
B = ->
throw new Error if calledB
calledB = yes
class
class A extends B()
constructor: (@prop = 3) ->
super()
f = @derivedBound
eq f(), 3
derivedBound: =>
@prop
b = new A
{derivedBound} = b
eq derivedBound(), 3
test 'Bound method of class with expression class name called as callback is ok', ->
calledF = no
obj = {}
B = class
f = ->
throw new Error if calledF
calledF = yes
obj
class f().A extends B
constructor: (@prop = 3) ->
super()
g = @derivedBound
eq g(), 3
derivedBound: =>
@prop
a = new obj.A
{derivedBound} = a
eq derivedBound(), 3
test 'Bound method of anonymous child class called as callback is ok', ->
f = ->
B = class
class extends B
constructor: (@prop = 3) ->
super()
g = @derivedBound
eq g(), 3
derivedBound: =>
@prop
a = new (f())
{derivedBound} = a
eq derivedBound(), 3
test 'Bound method of immediately instantiated class with expression base class called as callback is ok', ->
calledF = no
obj = {}
B = class
f = ->
throw new Error if calledF
calledF = yes
obj
a = new class f().A extends B
constructor: (@prop = 3) ->
super()
g = @derivedBound
eq g(), 3
derivedBound: =>
@prop
{derivedBound} = a
eq derivedBound(), 3
test "#4591: super.x.y, super['x'].y", ->
class A
x:
y: 1
z: -> 2
class B extends A
constructor: ->
super()
@w = super.x.y
@v = super['x'].y
@u = super.x['y']
@t = super.x.z()
@s = super['x'].z()
@r = super.x['z']()
b = new B
eq 1, b.w
eq 1, b.v
eq 1, b.u
eq 2, b.t
eq 2, b.s
eq 2, b.r
test "#4464: backticked expressions in class body", ->
class A
`get x() { return 42; }`
class B
`get x() { return 42; }`
constructor: ->
@y = 84
a = new A
eq 42, a.x
b = new B
eq 42, b.x
eq 84, b.y
test "#4724: backticked expression in a class body with hoisted member", ->
class A
`get x() { return 42; }`
hoisted: 84
a = new A
eq 42, a.x
eq 84, a.hoisted
| 91524 | # Classes
# -------
# * Class Definition
# * Class Instantiation
# * Inheritance and Super
# * ES2015+ Class Interoperability
test "classes with a four-level inheritance chain", ->
class Base
func: (string) ->
"zero/#{string}"
@static: (string) ->
"static/#{string}"
class FirstChild extends Base
func: (string) ->
super('one/') + string
SecondChild = class extends FirstChild
func: (string) ->
super('two/') + string
thirdCtor = ->
@array = [1, 2, 3]
class ThirdChild extends SecondChild
constructor: ->
super()
thirdCtor.call this
# Gratuitous comment for testing.
func: (string) ->
super('three/') + string
result = (new ThirdChild).func 'four'
ok result is 'zero/one/two/three/four'
ok Base.static('word') is 'static/word'
ok (new ThirdChild).array.join(' ') is '1 2 3'
test "constructors with inheritance and super", ->
identity = (f) -> f
class TopClass
constructor: (arg) ->
@prop = 'top-' + arg
class SuperClass extends TopClass
constructor: (arg) ->
identity super 'super-' + arg
class SubClass extends SuperClass
constructor: ->
identity super 'sub'
ok (new SubClass).prop is 'top-super-sub'
test "'super' with accessors", ->
class Base
m: -> 4
n: -> 5
o: -> 6
name = 'o'
class A extends Base
m: -> super()
n: -> super.n()
"#{name}": -> super()
p: -> super[name]()
a = new A
eq 4, a.m()
eq 5, a.n()
eq 6, a.o()
eq 6, a.p()
test "soaked 'super' invocation", ->
class Base
method: -> 2
class A extends Base
method: -> super?()
noMethod: -> super?()
a = new A
eq 2, a.method()
eq undefined, a.noMethod()
name = 'noMethod'
class B extends Base
"#{'method'}": -> super?()
"#{'noMethod'}": -> super?() ? super['method']()
b = new B
eq 2, b.method()
eq 2, b.noMethod()
test "'@' referring to the current instance, and not being coerced into a call", ->
class ClassName
amI: ->
@ instanceof ClassName
obj = new ClassName
ok obj.amI()
test "super() calls in constructors of classes that are defined as object properties", ->
class Hive
constructor: (name) -> @name = name
class Hive.Bee extends Hive
constructor: (name) -> super name
maya = new Hive.Bee 'Maya'
ok maya.name is 'Maya'
test "classes with JS-keyword properties", ->
class Class
class: 'class'
name: -> @class
instance = new Class
ok instance.class is 'class'
ok instance.name() is 'class'
test "Classes with methods that are pre-bound to the instance, or statically, to the class", ->
class Dog
constructor: (name) ->
@name = name
bark: =>
"#{@name} woofs!"
@static = =>
new this('Dog')
spark = new Dog('Spark')
fido = new Dog('Fido')
fido.bark = spark.bark
ok fido.bark() is 'Spark woofs!'
obj = func: Dog.static
ok obj.func().name is 'Dog'
test "a bound function in a bound function", ->
class Mini
num: 10
generate: =>
for i in [1..3]
=>
@num
m = new Mini
eq (func() for func in m.generate()).join(' '), '10 10 10'
test "contructor called with varargs", ->
class Connection
constructor: (one, two, three) ->
[@one, @two, @three] = [one, two, three]
out: ->
"#{@one}-#{@two}-#{@three}"
list = [3, 2, 1]
conn = new Connection list...
ok conn instanceof Connection
ok conn.out() is '3-2-1'
test "calling super and passing along all arguments", ->
class Parent
method: (args...) -> @args = args
class Child extends Parent
method: -> super arguments...
c = new Child
c.method 1, 2, 3, 4
ok c.args.join(' ') is '1 2 3 4'
test "classes wrapped in decorators", ->
func = (klass) ->
klass::prop = 'value'
klass
func class Test
prop2: 'value2'
ok (new Test).prop is 'value'
ok (new Test).prop2 is 'value2'
test "anonymous classes", ->
obj =
klass: class
method: -> 'value'
instance = new obj.klass
ok instance.method() is 'value'
test "Implicit objects as static properties", ->
class Static
@static =
one: 1
two: 2
ok Static.static.one is 1
ok Static.static.two is 2
test "nothing classes", ->
c = class
ok c instanceof Function
test "classes with static-level implicit objects", ->
class A
@static = one: 1
two: 2
class B
@static = one: 1,
two: 2
eq A.static.one, 1
eq A.static.two, undefined
eq (new A).two, 2
eq B.static.one, 1
eq B.static.two, 2
eq (new B).two, undefined
test "classes with value'd constructors", ->
counter = 0
classMaker = ->
inner = ++counter
->
@value = inner
class One
constructor: classMaker()
class Two
constructor: classMaker()
eq (new One).value, 1
eq (new Two).value, 2
eq (new One).value, 1
eq (new Two).value, 2
test "executable class bodies", ->
class A
if true
b: 'b'
else
c: 'c'
a = new A
eq a.b, 'b'
eq a.c, undefined
test "#2502: parenthesizing inner object values", ->
class A
category: (type: 'string')
sections: (type: 'number', default: 0)
eq (new A).category.type, 'string'
eq (new A).sections.default, 0
test "conditional prototype property assignment", ->
debug = false
class Person
if debug
age: -> 10
else
age: -> 20
eq (new Person).age(), 20
test "mild metaprogramming", ->
class Base
@attr: (name) ->
@::[name] = (val) ->
if arguments.length > 0
@["_#{name}"] = val
else
@["_#{name}"]
class Robot extends Base
@attr 'power'
@attr 'speed'
robby = new Robot
ok robby.power() is undefined
robby.power 11
robby.speed Infinity
eq robby.power(), 11
eq robby.speed(), Infinity
test "namespaced classes do not reserve their function name in outside scope", ->
one = {}
two = {}
class one.Klass
@label = "one"
class two.Klass
@label = "two"
eq typeof Klass, 'undefined'
eq one.Klass.label, 'one'
eq two.Klass.label, 'two'
test "nested classes", ->
class Outer
constructor: ->
@label = 'outer'
class @Inner
constructor: ->
@label = 'inner'
eq (new Outer).label, 'outer'
eq (new Outer.Inner).label, 'inner'
test "variables in constructor bodies are correctly scoped", ->
class A
x = 1
constructor: ->
x = 10
y = 20
y = 2
captured: ->
{x, y}
a = new A
eq a.captured().x, 10
eq a.captured().y, 2
test "Issue #924: Static methods in nested classes", ->
class A
@B: class
@c = -> 5
eq A.B.c(), 5
test "`class extends this`", ->
class A
func: -> 'A'
B = null
makeClass = ->
B = class extends this
func: -> super() + ' B'
makeClass.call A
eq (new B()).func(), 'A B'
test "ensure that constructors invoked with splats return a new object", ->
args = [1, 2, 3]
Type = (@args) ->
type = new Type args
ok type and type instanceof Type
ok type.args and type.args instanceof Array
ok v is args[i] for v, i in type.args
Type1 = (@a, @b, @c) ->
type1 = new Type1 args...
ok type1 instanceof Type1
eq type1.constructor, Type1
ok type1.a is args[0] and type1.b is args[1] and type1.c is args[2]
# Ensure that constructors invoked with splats cache the function.
called = 0
get = -> if called++ then false else class Type
new (get()) args...
test "`new` shouldn't add extra parens", ->
ok new Date().constructor is Date
test "`new` works against bare function", ->
eq Date, new ->
Date
test "#1182: a subclass should be able to set its constructor to an external function", ->
ctor = ->
@val = 1
return
class A
class B extends A
constructor: ctor
eq (new B).val, 1
test "#1182: external constructors continued", ->
ctor = ->
class A
class B extends A
method: ->
constructor: ctor
ok B::method
test "#1313: misplaced __extends", ->
nonce = {}
class A
class B extends A
prop: nonce
constructor: -> super()
eq nonce, B::prop
test "#1182: execution order needs to be considered as well", ->
counter = 0
makeFn = (n) -> eq n, ++counter; ->
class B extends (makeFn 1)
@B: makeFn 2
constructor: makeFn 3
test "#1182: external constructors with bound functions", ->
fn = ->
{one: 1}
this
class B
class A
constructor: fn
method: => this instanceof A
ok (new A).method.call(new B)
test "#1372: bound class methods with reserved names", ->
class C
delete: =>
ok C::delete
test "#1380: `super` with reserved names", ->
class C
do: -> super()
ok C::do
class B
0: -> super()
ok B::[0]
test "#1464: bound class methods should keep context", ->
nonce = {}
nonce2 = {}
class C
constructor: (@id) ->
@boundStaticColon: => new this(nonce)
@boundStaticEqual= => new this(nonce2)
eq nonce, C.boundStaticColon().id
eq nonce2, C.boundStaticEqual().id
test "#1009: classes with reserved words as determined names", -> (->
eq 'function', typeof (class @for)
ok not /\beval\b/.test (class @eval).toString()
ok not /\barguments\b/.test (class @arguments).toString()
).call {}
test "#1482: classes can extend expressions", ->
id = (x) -> x
nonce = {}
class A then nonce: nonce
class B extends id A
eq nonce, (new B).nonce
test "#1598: super works for static methods too", ->
class Parent
method: ->
'NO'
@method: ->
'yes'
class Child extends Parent
@method: ->
'pass? ' + super()
eq Child.method(), 'pass? yes'
test "#1842: Regression with bound functions within bound class methods", ->
class Store
@bound: =>
do =>
eq this, Store
Store.bound()
# And a fancier case:
class Store
eq this, Store
@bound: =>
do =>
eq this, Store
@unbound: ->
eq this, Store
instance: =>
ok this instanceof Store
Store.bound()
Store.unbound()
(new Store).instance()
test "#1876: Class @A extends A", ->
class A
class @A extends A
ok (new @A) instanceof A
test "#1813: Passing class definitions as expressions", ->
ident = (x) -> x
result = ident class A then x = 1
eq result, A
result = ident class B extends A
x = 1
eq result, B
test "#1966: external constructors should produce their return value", ->
ctor = -> {}
class A then constructor: ctor
ok (new A) not instanceof A
test "#1980: regression with an inherited class with static function members", ->
class A
class B extends A
@static: => 'value'
eq B.static(), 'value'
test "#1534: class then 'use strict'", ->
# [14.1 Directive Prologues and the Use Strict Directive](http://es5.github.com/#x14.1)
nonce = {}
error = 'do -> ok this'
strictTest = "do ->'use strict';#{error}"
return unless (try CoffeeScript.run strictTest, bare: yes catch e then nonce) is nonce
throws -> CoffeeScript.run "class then 'use strict';#{error}", bare: yes
doesNotThrow -> CoffeeScript.run "class then #{error}", bare: yes
doesNotThrow -> CoffeeScript.run "class then #{error};'use strict'", bare: yes
# comments are ignored in the Directive Prologue
comments = ["""
class
### comment ###
'use strict'
#{error}""",
"""
class
### comment 1 ###
### comment 2 ###
'use strict'
#{error}""",
"""
class
### comment 1 ###
### comment 2 ###
'use strict'
#{error}
### comment 3 ###"""
]
throws (-> CoffeeScript.run comment, bare: yes) for comment in comments
# [ES5 §14.1](http://es5.github.com/#x14.1) allows for other directives
directives = ["""
class
'directive 1'
'use strict'
#{error}""",
"""
class
'use strict'
'directive 2'
#{error}""",
"""
class
### comment 1 ###
'directive 1'
'use strict'
#{error}""",
"""
class
### comment 1 ###
'directive 1'
### comment 2 ###
'use strict'
#{error}"""
]
throws (-> CoffeeScript.run directive, bare: yes) for directive in directives
test "#2052: classes should work in strict mode", ->
try
do ->
'use strict'
class A
catch e
ok no
test "directives in class with extends ", ->
strictTest = """
class extends Object
### comment ###
'use strict'
do -> eq this, undefined
"""
CoffeeScript.run strictTest, bare: yes
test "#2630: class bodies can't reference arguments", ->
throws ->
CoffeeScript.compile('class Test then arguments')
# #4320: Don't be too eager when checking, though.
class Test
arguments: 5
eq 5, Test::arguments
test "#2319: fn class n extends o.p [INDENT] x = 123", ->
first = ->
base = onebase: ->
first class OneKeeper extends base.onebase
one = 1
one: -> one
eq new OneKeeper().one(), 1
test "#2599: other typed constructors should be inherited", ->
class Base
constructor: -> return {}
class Derived extends Base
ok (new Derived) not instanceof Derived
ok (new Derived) not instanceof Base
ok (new Base) not instanceof Base
test "extending native objects works with and without defining a constructor", ->
class MyArray extends Array
method: -> 'yes!'
myArray = new MyArray
ok myArray instanceof MyArray
ok 'yes!', myArray.method()
class OverrideArray extends Array
constructor: -> super()
method: -> 'yes!'
overrideArray = new OverrideArray
ok overrideArray instanceof OverrideArray
eq 'yes!', overrideArray.method()
test "#2782: non-alphanumeric-named bound functions", ->
class A
'b:c': =>
'd'
eq (new A)['b:c'](), 'd'
test "#2781: overriding bound functions", ->
class A
a: ->
@b()
b: =>
1
class B extends A
b: =>
2
b = (new A).b
eq b(), 1
b = (new B).b
eq b(), 2
test "#2791: bound function with destructured argument", ->
class Foo
method: ({a}) => 'Bar'
eq (new Foo).method({a: 'Bar'}), 'Bar'
test "#2796: ditto, ditto, ditto", ->
answer = null
outsideMethod = (func) ->
func.call message: 'wrong!'
class Base
constructor: ->
@message = 'right!'
outsideMethod @echo
echo: =>
answer = @message
new Base
eq answer, 'right!'
test "#3063: Class bodies cannot contain pure statements", ->
throws -> CoffeeScript.compile """
class extends S
return if S.f
@f: => this
"""
test "#2949: super in static method with reserved name", ->
class Foo
@static: -> 'baz'
class Bar extends Foo
@static: -> super()
eq Bar.static(), 'baz'
test "#3232: super in static methods (not object-assigned)", ->
class Foo
@baz = -> true
@qux = -> true
class Bar extends Foo
@baz = -> super()
Bar.qux = -> super()
ok Bar.baz()
ok Bar.qux()
test "#1392 calling `super` in methods defined on namespaced classes", ->
class Base
m: -> 5
n: -> 4
namespace =
A: ->
B: ->
class namespace.A extends Base
m: -> super()
eq 5, (new namespace.A).m()
namespace.B::m = namespace.A::m
namespace.A::m = null
eq 5, (new namespace.B).m()
class C
@a: class extends Base
m: -> super()
eq 5, (new C.a).m()
test "#4436 immediately instantiated named class", ->
ok new class Foo
test "dynamic method names", ->
class A
"#{name = 'm'}": -> 1
eq 1, new A().m()
class B extends A
"#{name = 'm'}": -> super()
eq 1, new B().m()
getName = -> 'm'
class C
"#{name = getName()}": -> 1
eq 1, new C().m()
test "dynamic method names and super", ->
class Base
@m: -> 6
m: -> 5
m2: -> 4.5
n: -> 4
name = -> count++; 'n'
count = 0
m = 'm'
class A extends Base
"#{m}": -> super()
"#{name()}": -> super()
m = 'n'
eq 5, (new A).m()
eq 4, (new A).n()
eq 1, count
m = 'm'
m2 = 'm2'
count = 0
class B extends Base
@[name()] = -> super()
"#{m}": -> super()
"#{m2}": -> super()
b = new B
m = m2 = 'n'
eq 6, B.m()
eq 5, b.m()
eq 4.5, b.m2()
eq 1, count
class C extends B
m: -> super()
eq 5, (new C).m()
# ES2015+ class interoperability
# Based on https://github.com/balupton/es6-javascript-class-interop
# Helper functions to generate true ES classes to extend:
getBasicClass = ->
```
class BasicClass {
constructor (greeting) {
this.greeting = greeting || 'hi'
}
}
```
BasicClass
getExtendedClass = (BaseClass) ->
```
class ExtendedClass extends BaseClass {
constructor (greeting, name) {
super(greeting || 'hello')
this.name = name
}
}
```
ExtendedClass
test "can instantiate a basic ES class", ->
BasicClass = getBasicClass()
i = new BasicClass 'howdy!'
eq i.greeting, 'howdy!'
test "can instantiate an extended ES class", ->
BasicClass = getBasicClass()
ExtendedClass = getExtendedClass BasicClass
i = new ExtendedClass 'yo', 'buddy'
eq i.greeting, 'yo'
eq i.name, '<NAME>'
test "can extend a basic ES class", ->
BasicClass = getBasicClass()
class ExtendedClass extends BasicClass
constructor: (@name) ->
super()
i = new ExtendedClass 'dude'
eq i.name, '<NAME>'
test "can extend an extended ES class", ->
BasicClass = getBasicClass()
ExtendedClass = getExtendedClass BasicClass
class ExtendedExtendedClass extends ExtendedClass
constructor: (@value) ->
super()
getDoubledValue: ->
@value * 2
i = new ExtendedExtendedClass 7
eq i.getDoubledValue(), 14
test "CoffeeScript class can be extended in ES", ->
class CoffeeClass
constructor: (@favoriteDrink = 'latte', @size = 'grande') ->
getDrinkOrder: ->
"#{@size} #{@favoriteDrink}"
```
class ECMAScriptClass extends CoffeeClass {
constructor (favoriteDrink) {
super(favoriteDrink);
this.favoriteDrink = this.favoriteDrink + ' with a dash of semicolons';
}
}
```
e = new ECMAScriptClass 'coffee'
eq e.getDrinkOrder(), 'grande coffee with a dash of semicolons'
test "extended CoffeeScript class can be extended in ES", ->
class CoffeeClass
constructor: (@favoriteDrink = 'latte') ->
class CoffeeClassWithDrinkOrder extends CoffeeClass
constructor: (@favoriteDrink, @size = 'grande') ->
super()
getDrinkOrder: ->
"#{@size} #{@favoriteDrink}"
```
class ECMAScriptClass extends CoffeeClassWithDrinkOrder {
constructor (favoriteDrink) {
super(favoriteDrink);
this.favoriteDrink = this.favoriteDrink + ' with a dash of semicolons';
}
}
```
e = new ECMAScriptClass 'coffee'
eq e.getDrinkOrder(), 'grande coffee with a dash of semicolons'
test "`this` access after `super` in extended classes", ->
class Base
class Test extends Base
constructor: (param, @param) ->
eq param, nonce
result = { super: super(), @param, @method }
eq result.super, this
eq result.param, @param
eq result.method, @method
ok result.method isnt Test::method
method: =>
nonce = {}
new Test nonce, {}
test "`@`-params and bound methods with multiple `super` paths (blocks)", ->
nonce = {}
class Base
constructor: (@name) ->
class Test extends Base
constructor: (param, @param) ->
if param
super 'param'
eq @name, 'param'
else
super 'not param'
eq @name, 'not param'
eq @param, nonce
ok @method isnt Test::method
method: =>
new Test true, nonce
new Test false, nonce
test "`@`-params and bound methods with multiple `super` paths (expressions)", ->
nonce = {}
class Base
constructor: (@name) ->
class Test extends Base
constructor: (param, @param) ->
# Contrived example: force each path into an expression with inline assertions
if param
result = (
eq (super 'param'), @;
eq @name, 'param';
eq @param, nonce;
ok @method isnt Test::method
)
else
result = (
eq (super 'not param'), @;
eq @name, 'not param';
eq @param, nonce;
ok @method isnt Test::method
)
method: =>
new Test true, nonce
new Test false, nonce
test "constructor super in arrow functions", ->
class Test extends (class)
constructor: (@param) ->
do => super()
eq @param, nonce
new Test nonce = {}
# TODO Some of these tests use CoffeeScript.compile and CoffeeScript.run when they could use
# regular test mechanics.
# TODO Some of these tests might be better placed in `test/error_messages.coffee`.
# TODO Some of these tests are duplicates.
# Ensure that we always throw if we experience more than one super()
# call in a constructor. This ends up being a runtime error.
# Should be caught at compile time.
test "multiple super calls", ->
throwsA = """
class A
constructor: (@drink) ->
make: -> "Making a #{@drink}"
class MultiSuper extends A
constructor: (drink) ->
super(drink)
super(drink)
@newDrink = drink
new MultiSuper('Late').make()
"""
throws -> CoffeeScript.run throwsA, bare: yes
# Basic test to ensure we can pass @params in a constuctor and
# inheritance works correctly
test "@ params", ->
class A
constructor: (@drink, @shots, @flavor) ->
make: -> "Making a #{@flavor} #{@drink} with #{@shots} shot(s)"
a = new A('Machiato', 2, 'chocolate')
eq a.make(), "Making a chocolate Machiato with 2 shot(s)"
class B extends A
b = new B('Machiato', 2, 'chocolate')
eq b.make(), "Making a chocolate Machiato with 2 shot(s)"
# Ensure we can accept @params with default parameters in a constructor
test "@ params with defaults in a constructor", ->
class A
# Multiple @ params with defaults
constructor: (@drink = 'Americano', @shots = '1', @flavor = 'caramel') ->
make: -> "Making a #{@flavor} #{@drink} with #{@shots} shot(s)"
a = new A()
eq a.make(), "Making a caramel Americano with 1 shot(s)"
# Ensure we can handle default constructors with class params
test "@ params with class params", ->
class Beverage
drink: 'Americano'
shots: '1'
flavor: 'caramel'
class A
# Class creation as a default param with `this`
constructor: (@drink = new Beverage()) ->
a = new A()
eq a.drink.drink, 'Americano'
beverage = new Beverage
class B
# class costruction with a default external param
constructor: (@drink = beverage) ->
b = new B()
eq b.drink.drink, 'Americano'
class C
# Default constructor with anonymous empty class
constructor: (@meta = class) ->
c = new C()
ok c.meta instanceof Function
test "@ params without super, including errors", ->
classA = """
class A
constructor: (@drink) ->
make: -> "Making a #{@drink}"
a = new A('Machiato')
"""
throwsB = """
class B extends A
#implied super
constructor: (@drink) ->
b = new B('Machiato')
"""
throws -> CoffeeScript.compile classA + throwsB, bare: yes
test "@ params super race condition", ->
classA = """
class A
constructor: (@drink) ->
make: -> "Making a #{@drink}"
"""
throwsB = """
class B extends A
constructor: (@params) ->
b = new B('Machiato')
"""
throws -> CoffeeScript.compile classA + throwsB, bare: yes
# Race condition with @ and super
throwsC = """
class C extends A
constructor: (@params) ->
super(@params)
c = new C('Machiato')
"""
throws -> CoffeeScript.compile classA + throwsC, bare: yes
test "@ with super call", ->
class D
make: -> "Making a #{@drink}"
class E extends D
constructor: (@drink) ->
super()
e = new E('Machiato')
eq e.make(), "Making a Machiato"
test "@ with splats and super call", ->
class A
make: -> "Making a #{@drink}"
class B extends A
constructor: (@drink...) ->
super()
B = new B('Machiato')
eq B.make(), "Making a Machiato"
test "super and external constructors", ->
# external constructor with @ param is allowed
ctorA = (@drink) ->
class A
constructor: ctorA
make: -> "Making a #{@drink}"
a = new A('Machiato')
eq a.make(), "Making a Machiato"
# External constructor with super
throwsC = """
class B
constructor: (@drink) ->
make: -> "Making a #{@drink}"
ctorC = (drink) ->
super(drink)
class C extends B
constructor: ctorC
c = new C('Machiato')
"""
throws -> CoffeeScript.compile throwsC, bare: yes
test "bound functions without super", ->
# Bound function with @
# Throw on compile, since bound
# constructors are illegal
throwsA = """
class A
constructor: (drink) =>
@drink = drink
"""
throws -> CoffeeScript.compile throwsA, bare: yes
test "super in a bound function in a constructor", ->
throwsB = """
class A
class B extends A
constructor: do => super
"""
throws -> CoffeeScript.compile throwsB, bare: yes
test "super in a bound function", ->
class A
constructor: (@drink) ->
make: -> "Making a #{@drink}"
class B extends A
make: (@flavor) =>
super() + " with #{@flavor}"
b = new B('Machiato')
eq b.make('vanilla'), "Making a Machiato with vanilla"
# super in a bound function in a bound function
class C extends A
make: (@flavor) =>
func = () =>
super() + " with #{@flavor}"
func()
c = new C('Machiato')
eq c.make('vanilla'), "Making a Machiato with vanilla"
# bound function in a constructor
class D extends A
constructor: (drink) ->
super(drink)
x = =>
eq @drink, "Machiato"
x()
d = new D('Machiato')
eq d.make(), "Making a Machiato"
# duplicate
test "super in a try/catch", ->
classA = """
class A
constructor: (param) ->
throw "" unless param
"""
throwsB = """
class B extends A
constructor: ->
try
super()
"""
throwsC = """
ctor = ->
try
super()
class C extends A
constructor: ctor
"""
throws -> CoffeeScript.run classA + throwsB, bare: yes
throws -> CoffeeScript.run classA + throwsC, bare: yes
test "mixed ES6 and CS6 classes with a four-level inheritance chain", ->
# Extended test
# ES2015+ class interoperability
```
class Base {
constructor (greeting) {
this.greeting = greeting || 'hi';
}
func (string) {
return 'zero/' + string;
}
static staticFunc (string) {
return 'static/' + string;
}
}
```
class FirstChild extends Base
func: (string) ->
super('one/') + string
```
class SecondChild extends FirstChild {
func (string) {
return super.func('two/' + string);
}
}
```
thirdCtor = ->
@array = [1, 2, 3]
class ThirdChild extends SecondChild
constructor: ->
super()
thirdCtor.call this
func: (string) ->
super('three/') + string
result = (new ThirdChild).func 'four'
ok result is 'zero/one/two/three/four'
ok Base.staticFunc('word') is 'static/word'
# exercise extends in a nested class
test "nested classes with super", ->
class Outer
constructor: ->
@label = 'outer'
class @Inner
constructor: ->
@label = 'inner'
class @ExtendedInner extends @Inner
constructor: ->
tmp = super()
@label = tmp.label + ' extended'
@extender: () =>
class ExtendedSelf extends @
constructor: ->
tmp = super()
@label = tmp.label + ' from this'
new ExtendedSelf
eq (new Outer).label, 'outer'
eq (new Outer.Inner).label, 'inner'
eq (new Outer.ExtendedInner).label, 'inner extended'
eq (Outer.extender()).label, 'outer from this'
test "Static methods generate 'static' keywords", ->
compile = """
class CheckStatic
constructor: (@drink) ->
@className: -> 'CheckStatic'
c = new CheckStatic('Machiato')
"""
result = CoffeeScript.compile compile, bare: yes
ok result.match(' static ')
test "Static methods in nested classes", ->
class Outer
@name: -> 'Outer'
class @Inner
@name: -> 'Inner'
eq Outer.name(), 'Outer'
eq Outer.Inner.name(), 'Inner'
test "mixed constructors with inheritance and ES6 super", ->
identity = (f) -> f
class TopClass
constructor: (arg) ->
@prop = 'top-' + arg
```
class SuperClass extends TopClass {
constructor (arg) {
identity(super('super-' + arg));
}
}
```
class SubClass extends SuperClass
constructor: ->
identity super 'sub'
ok (new SubClass).prop is 'top-super-sub'
test "ES6 static class methods can be overriden", ->
class A
@name: -> 'A'
class B extends A
@name: -> 'B'
eq A.name(), 'A'
eq B.name(), 'B'
# If creating static by direct assignment rather than ES6 static keyword
test "ES6 Static methods should set `this` to undefined // ES6 ", ->
class A
@test: ->
eq this, undefined
# Ensure that our object prototypes work with ES6
test "ES6 prototypes can be overriden", ->
class A
className: 'classA'
```
class B {
test () {return "B";};
}
```
b = new B
a = new A
eq a.className, 'classA'
eq b.test(), 'B'
Object.setPrototypeOf(b, a)
eq b.className, 'classA'
# This shouldn't throw,
# as we only change inheritance not object construction
# This may be an issue with ES, rather than CS construction?
#eq b.test(), 'B'
class D extends B
B::test = () -> 'D'
eq (new D).test(), 'D'
# TODO: implement this error check
# test "ES6 conformance to extending non-classes", ->
# A = (@title) ->
# 'Title: ' + @
# class B extends A
# b = new B('caffeinated')
# eq b.title, 'caffeinated'
# # Check inheritance chain
# A::getTitle = () -> @title
# eq b.getTitle(), 'caffeinated'
# throwsC = """
# C = {title: 'invalid'}
# class D extends {}
# """
# # This should catch on compile and message should be "class can only extend classes and functions."
# throws -> CoffeeScript.run throwsC, bare: yes
# TODO: Evaluate future compliance with "strict mode";
# test "Class function environment should be in `strict mode`, ie as if 'use strict' was in use", ->
# class A
# # this might be a meaningless test, since these are likely to be runtime errors and different
# # for every browser. Thoughts?
# constructor: () ->
# # Ivalid: prop reassignment
# @state = {prop: [1], prop: {a: 'a'}}
# # eval reassignment
# @badEval = eval;
# # Should throw, but doesn't
# a = new A
# TODO: new.target needs support Separate issue
# test "ES6 support for new.target (functions and constructors)", ->
# throwsA = """
# class A
# constructor: () ->
# a = new.target.name
# """
# throws -> CoffeeScript.compile throwsA, bare: yes
test "only one method named constructor allowed", ->
throwsA = """
class A
constructor: (@first) ->
constructor: (@last) ->
"""
throws -> CoffeeScript.compile throwsA, bare: yes
test "If the constructor of a child class does not call super,it should return an object.", ->
nonce = {}
class A
class B extends A
constructor: ->
return nonce
eq nonce, new B
test "super can only exist in extended classes", ->
throwsA = """
class A
constructor: (@name) ->
super()
"""
throws -> CoffeeScript.compile throwsA, bare: yes
# --- CS1 classes compatability breaks ---
test "CS6 Class extends a CS1 compiled class", ->
```
// Generated by CoffeeScript 1.11.1
var BaseCS1, ExtendedCS1,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
BaseCS1 = (function() {
function BaseCS1(drink) {
this.drink = drink;
}
BaseCS1.prototype.make = function() {
return "making a " + this.drink;
};
BaseCS1.className = function() {
return 'BaseCS1';
};
return BaseCS1;
})();
ExtendedCS1 = (function(superClass) {
extend(ExtendedCS1, superClass);
function ExtendedCS1(flavor) {
this.flavor = flavor;
ExtendedCS1.__super__.constructor.call(this, 'cafe ole');
}
ExtendedCS1.prototype.make = function() {
return "making a " + this.drink + " with " + this.flavor;
};
ExtendedCS1.className = function() {
return 'ExtendedCS1';
};
return ExtendedCS1;
})(BaseCS1);
```
class B extends BaseCS1
eq B.className(), 'BaseCS1'
b = new B('machiato')
eq b.make(), "making a machiato"
test "CS6 Class extends an extended CS1 compiled class", ->
```
// Generated by CoffeeScript 1.11.1
var BaseCS1, ExtendedCS1,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
BaseCS1 = (function() {
function BaseCS1(drink) {
this.drink = drink;
}
BaseCS1.prototype.make = function() {
return "making a " + this.drink;
};
BaseCS1.className = function() {
return 'BaseCS1';
};
return BaseCS1;
})();
ExtendedCS1 = (function(superClass) {
extend(ExtendedCS1, superClass);
function ExtendedCS1(flavor) {
this.flavor = flavor;
ExtendedCS1.__super__.constructor.call(this, 'cafe ole');
}
ExtendedCS1.prototype.make = function() {
return "making a " + this.drink + " with " + this.flavor;
};
ExtendedCS1.className = function() {
return 'ExtendedCS1';
};
return ExtendedCS1;
})(BaseCS1);
```
class B extends ExtendedCS1
eq B.className(), 'ExtendedCS1'
b = new B('vanilla')
eq b.make(), "making a cafe ole with vanilla"
test "CS6 Class extends a CS1 compiled class with super()", ->
```
// Generated by CoffeeScript 1.11.1
var BaseCS1, ExtendedCS1,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
BaseCS1 = (function() {
function BaseCS1(drink) {
this.drink = drink;
}
BaseCS1.prototype.make = function() {
return "making a " + this.drink;
};
BaseCS1.className = function() {
return 'BaseCS1';
};
return BaseCS1;
})();
ExtendedCS1 = (function(superClass) {
extend(ExtendedCS1, superClass);
function ExtendedCS1(flavor) {
this.flavor = flavor;
ExtendedCS1.__super__.constructor.call(this, 'cafe ole');
}
ExtendedCS1.prototype.make = function() {
return "making a " + this.drink + " with " + this.flavor;
};
ExtendedCS1.className = function() {
return 'ExtendedCS1';
};
return ExtendedCS1;
})(BaseCS1);
```
class B extends ExtendedCS1
constructor: (@shots) ->
super('caramel')
make: () ->
super() + " and #{@shots} shots of espresso"
eq B.className(), 'ExtendedCS1'
b = new B('three')
eq b.make(), "making a cafe ole with caramel and three shots of espresso"
test 'Bound method called normally before binding is ok', ->
class Base
constructor: ->
@setProp()
eq @derivedBound(), 3
class Derived extends Base
setProp: ->
@prop = 3
derivedBound: =>
@prop
d = new Derived
test 'Bound method called as callback after super() is ok', ->
class Base
class Derived extends Base
constructor: (@prop = 3) ->
super()
f = @derivedBound
eq f(), 3
derivedBound: =>
@prop
d = new Derived
{derivedBound} = d
eq derivedBound(), 3
test 'Bound method of base class called as callback is ok', ->
class Base
constructor: (@prop = 3) ->
f = @baseBound
eq f(), 3
baseBound: =>
@prop
b = new Base
{baseBound} = b
eq baseBound(), 3
test 'Bound method of prop-named class called as callback is ok', ->
Hive = {}
class Hive.Bee
constructor: (@prop = 3) ->
f = @baseBound
eq f(), 3
baseBound: =>
@prop
b = new Hive.Bee
{baseBound} = b
eq baseBound(), 3
test 'Bound method of class with expression base class called as callback is ok', ->
calledB = no
B = ->
throw new Error if calledB
calledB = yes
class
class A extends B()
constructor: (@prop = 3) ->
super()
f = @derivedBound
eq f(), 3
derivedBound: =>
@prop
b = new A
{derivedBound} = b
eq derivedBound(), 3
test 'Bound method of class with expression class name called as callback is ok', ->
calledF = no
obj = {}
B = class
f = ->
throw new Error if calledF
calledF = yes
obj
class f().A extends B
constructor: (@prop = 3) ->
super()
g = @derivedBound
eq g(), 3
derivedBound: =>
@prop
a = new obj.A
{derivedBound} = a
eq derivedBound(), 3
test 'Bound method of anonymous child class called as callback is ok', ->
f = ->
B = class
class extends B
constructor: (@prop = 3) ->
super()
g = @derivedBound
eq g(), 3
derivedBound: =>
@prop
a = new (f())
{derivedBound} = a
eq derivedBound(), 3
test 'Bound method of immediately instantiated class with expression base class called as callback is ok', ->
calledF = no
obj = {}
B = class
f = ->
throw new Error if calledF
calledF = yes
obj
a = new class f().A extends B
constructor: (@prop = 3) ->
super()
g = @derivedBound
eq g(), 3
derivedBound: =>
@prop
{derivedBound} = a
eq derivedBound(), 3
test "#4591: super.x.y, super['x'].y", ->
class A
x:
y: 1
z: -> 2
class B extends A
constructor: ->
super()
@w = super.x.y
@v = super['x'].y
@u = super.x['y']
@t = super.x.z()
@s = super['x'].z()
@r = super.x['z']()
b = new B
eq 1, b.w
eq 1, b.v
eq 1, b.u
eq 2, b.t
eq 2, b.s
eq 2, b.r
test "#4464: backticked expressions in class body", ->
class A
`get x() { return 42; }`
class B
`get x() { return 42; }`
constructor: ->
@y = 84
a = new A
eq 42, a.x
b = new B
eq 42, b.x
eq 84, b.y
test "#4724: backticked expression in a class body with hoisted member", ->
class A
`get x() { return 42; }`
hoisted: 84
a = new A
eq 42, a.x
eq 84, a.hoisted
| true | # Classes
# -------
# * Class Definition
# * Class Instantiation
# * Inheritance and Super
# * ES2015+ Class Interoperability
test "classes with a four-level inheritance chain", ->
class Base
func: (string) ->
"zero/#{string}"
@static: (string) ->
"static/#{string}"
class FirstChild extends Base
func: (string) ->
super('one/') + string
SecondChild = class extends FirstChild
func: (string) ->
super('two/') + string
thirdCtor = ->
@array = [1, 2, 3]
class ThirdChild extends SecondChild
constructor: ->
super()
thirdCtor.call this
# Gratuitous comment for testing.
func: (string) ->
super('three/') + string
result = (new ThirdChild).func 'four'
ok result is 'zero/one/two/three/four'
ok Base.static('word') is 'static/word'
ok (new ThirdChild).array.join(' ') is '1 2 3'
test "constructors with inheritance and super", ->
identity = (f) -> f
class TopClass
constructor: (arg) ->
@prop = 'top-' + arg
class SuperClass extends TopClass
constructor: (arg) ->
identity super 'super-' + arg
class SubClass extends SuperClass
constructor: ->
identity super 'sub'
ok (new SubClass).prop is 'top-super-sub'
test "'super' with accessors", ->
class Base
m: -> 4
n: -> 5
o: -> 6
name = 'o'
class A extends Base
m: -> super()
n: -> super.n()
"#{name}": -> super()
p: -> super[name]()
a = new A
eq 4, a.m()
eq 5, a.n()
eq 6, a.o()
eq 6, a.p()
test "soaked 'super' invocation", ->
class Base
method: -> 2
class A extends Base
method: -> super?()
noMethod: -> super?()
a = new A
eq 2, a.method()
eq undefined, a.noMethod()
name = 'noMethod'
class B extends Base
"#{'method'}": -> super?()
"#{'noMethod'}": -> super?() ? super['method']()
b = new B
eq 2, b.method()
eq 2, b.noMethod()
test "'@' referring to the current instance, and not being coerced into a call", ->
class ClassName
amI: ->
@ instanceof ClassName
obj = new ClassName
ok obj.amI()
test "super() calls in constructors of classes that are defined as object properties", ->
class Hive
constructor: (name) -> @name = name
class Hive.Bee extends Hive
constructor: (name) -> super name
maya = new Hive.Bee 'Maya'
ok maya.name is 'Maya'
test "classes with JS-keyword properties", ->
class Class
class: 'class'
name: -> @class
instance = new Class
ok instance.class is 'class'
ok instance.name() is 'class'
test "Classes with methods that are pre-bound to the instance, or statically, to the class", ->
class Dog
constructor: (name) ->
@name = name
bark: =>
"#{@name} woofs!"
@static = =>
new this('Dog')
spark = new Dog('Spark')
fido = new Dog('Fido')
fido.bark = spark.bark
ok fido.bark() is 'Spark woofs!'
obj = func: Dog.static
ok obj.func().name is 'Dog'
test "a bound function in a bound function", ->
class Mini
num: 10
generate: =>
for i in [1..3]
=>
@num
m = new Mini
eq (func() for func in m.generate()).join(' '), '10 10 10'
test "contructor called with varargs", ->
class Connection
constructor: (one, two, three) ->
[@one, @two, @three] = [one, two, three]
out: ->
"#{@one}-#{@two}-#{@three}"
list = [3, 2, 1]
conn = new Connection list...
ok conn instanceof Connection
ok conn.out() is '3-2-1'
test "calling super and passing along all arguments", ->
class Parent
method: (args...) -> @args = args
class Child extends Parent
method: -> super arguments...
c = new Child
c.method 1, 2, 3, 4
ok c.args.join(' ') is '1 2 3 4'
test "classes wrapped in decorators", ->
func = (klass) ->
klass::prop = 'value'
klass
func class Test
prop2: 'value2'
ok (new Test).prop is 'value'
ok (new Test).prop2 is 'value2'
test "anonymous classes", ->
obj =
klass: class
method: -> 'value'
instance = new obj.klass
ok instance.method() is 'value'
test "Implicit objects as static properties", ->
class Static
@static =
one: 1
two: 2
ok Static.static.one is 1
ok Static.static.two is 2
test "nothing classes", ->
c = class
ok c instanceof Function
test "classes with static-level implicit objects", ->
class A
@static = one: 1
two: 2
class B
@static = one: 1,
two: 2
eq A.static.one, 1
eq A.static.two, undefined
eq (new A).two, 2
eq B.static.one, 1
eq B.static.two, 2
eq (new B).two, undefined
test "classes with value'd constructors", ->
counter = 0
classMaker = ->
inner = ++counter
->
@value = inner
class One
constructor: classMaker()
class Two
constructor: classMaker()
eq (new One).value, 1
eq (new Two).value, 2
eq (new One).value, 1
eq (new Two).value, 2
test "executable class bodies", ->
class A
if true
b: 'b'
else
c: 'c'
a = new A
eq a.b, 'b'
eq a.c, undefined
test "#2502: parenthesizing inner object values", ->
class A
category: (type: 'string')
sections: (type: 'number', default: 0)
eq (new A).category.type, 'string'
eq (new A).sections.default, 0
test "conditional prototype property assignment", ->
debug = false
class Person
if debug
age: -> 10
else
age: -> 20
eq (new Person).age(), 20
test "mild metaprogramming", ->
class Base
@attr: (name) ->
@::[name] = (val) ->
if arguments.length > 0
@["_#{name}"] = val
else
@["_#{name}"]
class Robot extends Base
@attr 'power'
@attr 'speed'
robby = new Robot
ok robby.power() is undefined
robby.power 11
robby.speed Infinity
eq robby.power(), 11
eq robby.speed(), Infinity
test "namespaced classes do not reserve their function name in outside scope", ->
one = {}
two = {}
class one.Klass
@label = "one"
class two.Klass
@label = "two"
eq typeof Klass, 'undefined'
eq one.Klass.label, 'one'
eq two.Klass.label, 'two'
test "nested classes", ->
class Outer
constructor: ->
@label = 'outer'
class @Inner
constructor: ->
@label = 'inner'
eq (new Outer).label, 'outer'
eq (new Outer.Inner).label, 'inner'
test "variables in constructor bodies are correctly scoped", ->
class A
x = 1
constructor: ->
x = 10
y = 20
y = 2
captured: ->
{x, y}
a = new A
eq a.captured().x, 10
eq a.captured().y, 2
test "Issue #924: Static methods in nested classes", ->
class A
@B: class
@c = -> 5
eq A.B.c(), 5
test "`class extends this`", ->
class A
func: -> 'A'
B = null
makeClass = ->
B = class extends this
func: -> super() + ' B'
makeClass.call A
eq (new B()).func(), 'A B'
test "ensure that constructors invoked with splats return a new object", ->
args = [1, 2, 3]
Type = (@args) ->
type = new Type args
ok type and type instanceof Type
ok type.args and type.args instanceof Array
ok v is args[i] for v, i in type.args
Type1 = (@a, @b, @c) ->
type1 = new Type1 args...
ok type1 instanceof Type1
eq type1.constructor, Type1
ok type1.a is args[0] and type1.b is args[1] and type1.c is args[2]
# Ensure that constructors invoked with splats cache the function.
called = 0
get = -> if called++ then false else class Type
new (get()) args...
test "`new` shouldn't add extra parens", ->
ok new Date().constructor is Date
test "`new` works against bare function", ->
eq Date, new ->
Date
test "#1182: a subclass should be able to set its constructor to an external function", ->
ctor = ->
@val = 1
return
class A
class B extends A
constructor: ctor
eq (new B).val, 1
test "#1182: external constructors continued", ->
ctor = ->
class A
class B extends A
method: ->
constructor: ctor
ok B::method
test "#1313: misplaced __extends", ->
nonce = {}
class A
class B extends A
prop: nonce
constructor: -> super()
eq nonce, B::prop
test "#1182: execution order needs to be considered as well", ->
counter = 0
makeFn = (n) -> eq n, ++counter; ->
class B extends (makeFn 1)
@B: makeFn 2
constructor: makeFn 3
test "#1182: external constructors with bound functions", ->
fn = ->
{one: 1}
this
class B
class A
constructor: fn
method: => this instanceof A
ok (new A).method.call(new B)
test "#1372: bound class methods with reserved names", ->
class C
delete: =>
ok C::delete
test "#1380: `super` with reserved names", ->
class C
do: -> super()
ok C::do
class B
0: -> super()
ok B::[0]
test "#1464: bound class methods should keep context", ->
nonce = {}
nonce2 = {}
class C
constructor: (@id) ->
@boundStaticColon: => new this(nonce)
@boundStaticEqual= => new this(nonce2)
eq nonce, C.boundStaticColon().id
eq nonce2, C.boundStaticEqual().id
test "#1009: classes with reserved words as determined names", -> (->
eq 'function', typeof (class @for)
ok not /\beval\b/.test (class @eval).toString()
ok not /\barguments\b/.test (class @arguments).toString()
).call {}
test "#1482: classes can extend expressions", ->
id = (x) -> x
nonce = {}
class A then nonce: nonce
class B extends id A
eq nonce, (new B).nonce
test "#1598: super works for static methods too", ->
class Parent
method: ->
'NO'
@method: ->
'yes'
class Child extends Parent
@method: ->
'pass? ' + super()
eq Child.method(), 'pass? yes'
test "#1842: Regression with bound functions within bound class methods", ->
class Store
@bound: =>
do =>
eq this, Store
Store.bound()
# And a fancier case:
class Store
eq this, Store
@bound: =>
do =>
eq this, Store
@unbound: ->
eq this, Store
instance: =>
ok this instanceof Store
Store.bound()
Store.unbound()
(new Store).instance()
test "#1876: Class @A extends A", ->
class A
class @A extends A
ok (new @A) instanceof A
test "#1813: Passing class definitions as expressions", ->
ident = (x) -> x
result = ident class A then x = 1
eq result, A
result = ident class B extends A
x = 1
eq result, B
test "#1966: external constructors should produce their return value", ->
ctor = -> {}
class A then constructor: ctor
ok (new A) not instanceof A
test "#1980: regression with an inherited class with static function members", ->
class A
class B extends A
@static: => 'value'
eq B.static(), 'value'
test "#1534: class then 'use strict'", ->
# [14.1 Directive Prologues and the Use Strict Directive](http://es5.github.com/#x14.1)
nonce = {}
error = 'do -> ok this'
strictTest = "do ->'use strict';#{error}"
return unless (try CoffeeScript.run strictTest, bare: yes catch e then nonce) is nonce
throws -> CoffeeScript.run "class then 'use strict';#{error}", bare: yes
doesNotThrow -> CoffeeScript.run "class then #{error}", bare: yes
doesNotThrow -> CoffeeScript.run "class then #{error};'use strict'", bare: yes
# comments are ignored in the Directive Prologue
comments = ["""
class
### comment ###
'use strict'
#{error}""",
"""
class
### comment 1 ###
### comment 2 ###
'use strict'
#{error}""",
"""
class
### comment 1 ###
### comment 2 ###
'use strict'
#{error}
### comment 3 ###"""
]
throws (-> CoffeeScript.run comment, bare: yes) for comment in comments
# [ES5 §14.1](http://es5.github.com/#x14.1) allows for other directives
directives = ["""
class
'directive 1'
'use strict'
#{error}""",
"""
class
'use strict'
'directive 2'
#{error}""",
"""
class
### comment 1 ###
'directive 1'
'use strict'
#{error}""",
"""
class
### comment 1 ###
'directive 1'
### comment 2 ###
'use strict'
#{error}"""
]
throws (-> CoffeeScript.run directive, bare: yes) for directive in directives
test "#2052: classes should work in strict mode", ->
try
do ->
'use strict'
class A
catch e
ok no
test "directives in class with extends ", ->
strictTest = """
class extends Object
### comment ###
'use strict'
do -> eq this, undefined
"""
CoffeeScript.run strictTest, bare: yes
test "#2630: class bodies can't reference arguments", ->
throws ->
CoffeeScript.compile('class Test then arguments')
# #4320: Don't be too eager when checking, though.
class Test
arguments: 5
eq 5, Test::arguments
test "#2319: fn class n extends o.p [INDENT] x = 123", ->
first = ->
base = onebase: ->
first class OneKeeper extends base.onebase
one = 1
one: -> one
eq new OneKeeper().one(), 1
test "#2599: other typed constructors should be inherited", ->
class Base
constructor: -> return {}
class Derived extends Base
ok (new Derived) not instanceof Derived
ok (new Derived) not instanceof Base
ok (new Base) not instanceof Base
test "extending native objects works with and without defining a constructor", ->
class MyArray extends Array
method: -> 'yes!'
myArray = new MyArray
ok myArray instanceof MyArray
ok 'yes!', myArray.method()
class OverrideArray extends Array
constructor: -> super()
method: -> 'yes!'
overrideArray = new OverrideArray
ok overrideArray instanceof OverrideArray
eq 'yes!', overrideArray.method()
test "#2782: non-alphanumeric-named bound functions", ->
class A
'b:c': =>
'd'
eq (new A)['b:c'](), 'd'
test "#2781: overriding bound functions", ->
class A
a: ->
@b()
b: =>
1
class B extends A
b: =>
2
b = (new A).b
eq b(), 1
b = (new B).b
eq b(), 2
test "#2791: bound function with destructured argument", ->
class Foo
method: ({a}) => 'Bar'
eq (new Foo).method({a: 'Bar'}), 'Bar'
test "#2796: ditto, ditto, ditto", ->
answer = null
outsideMethod = (func) ->
func.call message: 'wrong!'
class Base
constructor: ->
@message = 'right!'
outsideMethod @echo
echo: =>
answer = @message
new Base
eq answer, 'right!'
test "#3063: Class bodies cannot contain pure statements", ->
throws -> CoffeeScript.compile """
class extends S
return if S.f
@f: => this
"""
test "#2949: super in static method with reserved name", ->
class Foo
@static: -> 'baz'
class Bar extends Foo
@static: -> super()
eq Bar.static(), 'baz'
test "#3232: super in static methods (not object-assigned)", ->
class Foo
@baz = -> true
@qux = -> true
class Bar extends Foo
@baz = -> super()
Bar.qux = -> super()
ok Bar.baz()
ok Bar.qux()
test "#1392 calling `super` in methods defined on namespaced classes", ->
class Base
m: -> 5
n: -> 4
namespace =
A: ->
B: ->
class namespace.A extends Base
m: -> super()
eq 5, (new namespace.A).m()
namespace.B::m = namespace.A::m
namespace.A::m = null
eq 5, (new namespace.B).m()
class C
@a: class extends Base
m: -> super()
eq 5, (new C.a).m()
test "#4436 immediately instantiated named class", ->
ok new class Foo
test "dynamic method names", ->
class A
"#{name = 'm'}": -> 1
eq 1, new A().m()
class B extends A
"#{name = 'm'}": -> super()
eq 1, new B().m()
getName = -> 'm'
class C
"#{name = getName()}": -> 1
eq 1, new C().m()
test "dynamic method names and super", ->
class Base
@m: -> 6
m: -> 5
m2: -> 4.5
n: -> 4
name = -> count++; 'n'
count = 0
m = 'm'
class A extends Base
"#{m}": -> super()
"#{name()}": -> super()
m = 'n'
eq 5, (new A).m()
eq 4, (new A).n()
eq 1, count
m = 'm'
m2 = 'm2'
count = 0
class B extends Base
@[name()] = -> super()
"#{m}": -> super()
"#{m2}": -> super()
b = new B
m = m2 = 'n'
eq 6, B.m()
eq 5, b.m()
eq 4.5, b.m2()
eq 1, count
class C extends B
m: -> super()
eq 5, (new C).m()
# ES2015+ class interoperability
# Based on https://github.com/balupton/es6-javascript-class-interop
# Helper functions to generate true ES classes to extend:
getBasicClass = ->
```
class BasicClass {
constructor (greeting) {
this.greeting = greeting || 'hi'
}
}
```
BasicClass
getExtendedClass = (BaseClass) ->
```
class ExtendedClass extends BaseClass {
constructor (greeting, name) {
super(greeting || 'hello')
this.name = name
}
}
```
ExtendedClass
test "can instantiate a basic ES class", ->
BasicClass = getBasicClass()
i = new BasicClass 'howdy!'
eq i.greeting, 'howdy!'
test "can instantiate an extended ES class", ->
BasicClass = getBasicClass()
ExtendedClass = getExtendedClass BasicClass
i = new ExtendedClass 'yo', 'buddy'
eq i.greeting, 'yo'
eq i.name, 'PI:NAME:<NAME>END_PI'
test "can extend a basic ES class", ->
BasicClass = getBasicClass()
class ExtendedClass extends BasicClass
constructor: (@name) ->
super()
i = new ExtendedClass 'dude'
eq i.name, 'PI:NAME:<NAME>END_PI'
test "can extend an extended ES class", ->
BasicClass = getBasicClass()
ExtendedClass = getExtendedClass BasicClass
class ExtendedExtendedClass extends ExtendedClass
constructor: (@value) ->
super()
getDoubledValue: ->
@value * 2
i = new ExtendedExtendedClass 7
eq i.getDoubledValue(), 14
test "CoffeeScript class can be extended in ES", ->
class CoffeeClass
constructor: (@favoriteDrink = 'latte', @size = 'grande') ->
getDrinkOrder: ->
"#{@size} #{@favoriteDrink}"
```
class ECMAScriptClass extends CoffeeClass {
constructor (favoriteDrink) {
super(favoriteDrink);
this.favoriteDrink = this.favoriteDrink + ' with a dash of semicolons';
}
}
```
e = new ECMAScriptClass 'coffee'
eq e.getDrinkOrder(), 'grande coffee with a dash of semicolons'
test "extended CoffeeScript class can be extended in ES", ->
class CoffeeClass
constructor: (@favoriteDrink = 'latte') ->
class CoffeeClassWithDrinkOrder extends CoffeeClass
constructor: (@favoriteDrink, @size = 'grande') ->
super()
getDrinkOrder: ->
"#{@size} #{@favoriteDrink}"
```
class ECMAScriptClass extends CoffeeClassWithDrinkOrder {
constructor (favoriteDrink) {
super(favoriteDrink);
this.favoriteDrink = this.favoriteDrink + ' with a dash of semicolons';
}
}
```
e = new ECMAScriptClass 'coffee'
eq e.getDrinkOrder(), 'grande coffee with a dash of semicolons'
test "`this` access after `super` in extended classes", ->
class Base
class Test extends Base
constructor: (param, @param) ->
eq param, nonce
result = { super: super(), @param, @method }
eq result.super, this
eq result.param, @param
eq result.method, @method
ok result.method isnt Test::method
method: =>
nonce = {}
new Test nonce, {}
test "`@`-params and bound methods with multiple `super` paths (blocks)", ->
nonce = {}
class Base
constructor: (@name) ->
class Test extends Base
constructor: (param, @param) ->
if param
super 'param'
eq @name, 'param'
else
super 'not param'
eq @name, 'not param'
eq @param, nonce
ok @method isnt Test::method
method: =>
new Test true, nonce
new Test false, nonce
test "`@`-params and bound methods with multiple `super` paths (expressions)", ->
nonce = {}
class Base
constructor: (@name) ->
class Test extends Base
constructor: (param, @param) ->
# Contrived example: force each path into an expression with inline assertions
if param
result = (
eq (super 'param'), @;
eq @name, 'param';
eq @param, nonce;
ok @method isnt Test::method
)
else
result = (
eq (super 'not param'), @;
eq @name, 'not param';
eq @param, nonce;
ok @method isnt Test::method
)
method: =>
new Test true, nonce
new Test false, nonce
test "constructor super in arrow functions", ->
class Test extends (class)
constructor: (@param) ->
do => super()
eq @param, nonce
new Test nonce = {}
# TODO Some of these tests use CoffeeScript.compile and CoffeeScript.run when they could use
# regular test mechanics.
# TODO Some of these tests might be better placed in `test/error_messages.coffee`.
# TODO Some of these tests are duplicates.
# Ensure that we always throw if we experience more than one super()
# call in a constructor. This ends up being a runtime error.
# Should be caught at compile time.
test "multiple super calls", ->
throwsA = """
class A
constructor: (@drink) ->
make: -> "Making a #{@drink}"
class MultiSuper extends A
constructor: (drink) ->
super(drink)
super(drink)
@newDrink = drink
new MultiSuper('Late').make()
"""
throws -> CoffeeScript.run throwsA, bare: yes
# Basic test to ensure we can pass @params in a constuctor and
# inheritance works correctly
test "@ params", ->
class A
constructor: (@drink, @shots, @flavor) ->
make: -> "Making a #{@flavor} #{@drink} with #{@shots} shot(s)"
a = new A('Machiato', 2, 'chocolate')
eq a.make(), "Making a chocolate Machiato with 2 shot(s)"
class B extends A
b = new B('Machiato', 2, 'chocolate')
eq b.make(), "Making a chocolate Machiato with 2 shot(s)"
# Ensure we can accept @params with default parameters in a constructor
test "@ params with defaults in a constructor", ->
class A
# Multiple @ params with defaults
constructor: (@drink = 'Americano', @shots = '1', @flavor = 'caramel') ->
make: -> "Making a #{@flavor} #{@drink} with #{@shots} shot(s)"
a = new A()
eq a.make(), "Making a caramel Americano with 1 shot(s)"
# Ensure we can handle default constructors with class params
test "@ params with class params", ->
class Beverage
drink: 'Americano'
shots: '1'
flavor: 'caramel'
class A
# Class creation as a default param with `this`
constructor: (@drink = new Beverage()) ->
a = new A()
eq a.drink.drink, 'Americano'
beverage = new Beverage
class B
# class costruction with a default external param
constructor: (@drink = beverage) ->
b = new B()
eq b.drink.drink, 'Americano'
class C
# Default constructor with anonymous empty class
constructor: (@meta = class) ->
c = new C()
ok c.meta instanceof Function
test "@ params without super, including errors", ->
classA = """
class A
constructor: (@drink) ->
make: -> "Making a #{@drink}"
a = new A('Machiato')
"""
throwsB = """
class B extends A
#implied super
constructor: (@drink) ->
b = new B('Machiato')
"""
throws -> CoffeeScript.compile classA + throwsB, bare: yes
test "@ params super race condition", ->
classA = """
class A
constructor: (@drink) ->
make: -> "Making a #{@drink}"
"""
throwsB = """
class B extends A
constructor: (@params) ->
b = new B('Machiato')
"""
throws -> CoffeeScript.compile classA + throwsB, bare: yes
# Race condition with @ and super
throwsC = """
class C extends A
constructor: (@params) ->
super(@params)
c = new C('Machiato')
"""
throws -> CoffeeScript.compile classA + throwsC, bare: yes
test "@ with super call", ->
class D
make: -> "Making a #{@drink}"
class E extends D
constructor: (@drink) ->
super()
e = new E('Machiato')
eq e.make(), "Making a Machiato"
test "@ with splats and super call", ->
class A
make: -> "Making a #{@drink}"
class B extends A
constructor: (@drink...) ->
super()
B = new B('Machiato')
eq B.make(), "Making a Machiato"
test "super and external constructors", ->
# external constructor with @ param is allowed
ctorA = (@drink) ->
class A
constructor: ctorA
make: -> "Making a #{@drink}"
a = new A('Machiato')
eq a.make(), "Making a Machiato"
# External constructor with super
throwsC = """
class B
constructor: (@drink) ->
make: -> "Making a #{@drink}"
ctorC = (drink) ->
super(drink)
class C extends B
constructor: ctorC
c = new C('Machiato')
"""
throws -> CoffeeScript.compile throwsC, bare: yes
test "bound functions without super", ->
# Bound function with @
# Throw on compile, since bound
# constructors are illegal
throwsA = """
class A
constructor: (drink) =>
@drink = drink
"""
throws -> CoffeeScript.compile throwsA, bare: yes
test "super in a bound function in a constructor", ->
throwsB = """
class A
class B extends A
constructor: do => super
"""
throws -> CoffeeScript.compile throwsB, bare: yes
test "super in a bound function", ->
class A
constructor: (@drink) ->
make: -> "Making a #{@drink}"
class B extends A
make: (@flavor) =>
super() + " with #{@flavor}"
b = new B('Machiato')
eq b.make('vanilla'), "Making a Machiato with vanilla"
# super in a bound function in a bound function
class C extends A
make: (@flavor) =>
func = () =>
super() + " with #{@flavor}"
func()
c = new C('Machiato')
eq c.make('vanilla'), "Making a Machiato with vanilla"
# bound function in a constructor
class D extends A
constructor: (drink) ->
super(drink)
x = =>
eq @drink, "Machiato"
x()
d = new D('Machiato')
eq d.make(), "Making a Machiato"
# duplicate
test "super in a try/catch", ->
classA = """
class A
constructor: (param) ->
throw "" unless param
"""
throwsB = """
class B extends A
constructor: ->
try
super()
"""
throwsC = """
ctor = ->
try
super()
class C extends A
constructor: ctor
"""
throws -> CoffeeScript.run classA + throwsB, bare: yes
throws -> CoffeeScript.run classA + throwsC, bare: yes
test "mixed ES6 and CS6 classes with a four-level inheritance chain", ->
# Extended test
# ES2015+ class interoperability
```
class Base {
constructor (greeting) {
this.greeting = greeting || 'hi';
}
func (string) {
return 'zero/' + string;
}
static staticFunc (string) {
return 'static/' + string;
}
}
```
class FirstChild extends Base
func: (string) ->
super('one/') + string
```
class SecondChild extends FirstChild {
func (string) {
return super.func('two/' + string);
}
}
```
thirdCtor = ->
@array = [1, 2, 3]
class ThirdChild extends SecondChild
constructor: ->
super()
thirdCtor.call this
func: (string) ->
super('three/') + string
result = (new ThirdChild).func 'four'
ok result is 'zero/one/two/three/four'
ok Base.staticFunc('word') is 'static/word'
# exercise extends in a nested class
test "nested classes with super", ->
class Outer
constructor: ->
@label = 'outer'
class @Inner
constructor: ->
@label = 'inner'
class @ExtendedInner extends @Inner
constructor: ->
tmp = super()
@label = tmp.label + ' extended'
@extender: () =>
class ExtendedSelf extends @
constructor: ->
tmp = super()
@label = tmp.label + ' from this'
new ExtendedSelf
eq (new Outer).label, 'outer'
eq (new Outer.Inner).label, 'inner'
eq (new Outer.ExtendedInner).label, 'inner extended'
eq (Outer.extender()).label, 'outer from this'
test "Static methods generate 'static' keywords", ->
compile = """
class CheckStatic
constructor: (@drink) ->
@className: -> 'CheckStatic'
c = new CheckStatic('Machiato')
"""
result = CoffeeScript.compile compile, bare: yes
ok result.match(' static ')
test "Static methods in nested classes", ->
class Outer
@name: -> 'Outer'
class @Inner
@name: -> 'Inner'
eq Outer.name(), 'Outer'
eq Outer.Inner.name(), 'Inner'
test "mixed constructors with inheritance and ES6 super", ->
identity = (f) -> f
class TopClass
constructor: (arg) ->
@prop = 'top-' + arg
```
class SuperClass extends TopClass {
constructor (arg) {
identity(super('super-' + arg));
}
}
```
class SubClass extends SuperClass
constructor: ->
identity super 'sub'
ok (new SubClass).prop is 'top-super-sub'
test "ES6 static class methods can be overriden", ->
class A
@name: -> 'A'
class B extends A
@name: -> 'B'
eq A.name(), 'A'
eq B.name(), 'B'
# If creating static by direct assignment rather than ES6 static keyword
test "ES6 Static methods should set `this` to undefined // ES6 ", ->
class A
@test: ->
eq this, undefined
# Ensure that our object prototypes work with ES6
test "ES6 prototypes can be overriden", ->
class A
className: 'classA'
```
class B {
test () {return "B";};
}
```
b = new B
a = new A
eq a.className, 'classA'
eq b.test(), 'B'
Object.setPrototypeOf(b, a)
eq b.className, 'classA'
# This shouldn't throw,
# as we only change inheritance not object construction
# This may be an issue with ES, rather than CS construction?
#eq b.test(), 'B'
class D extends B
B::test = () -> 'D'
eq (new D).test(), 'D'
# TODO: implement this error check
# test "ES6 conformance to extending non-classes", ->
# A = (@title) ->
# 'Title: ' + @
# class B extends A
# b = new B('caffeinated')
# eq b.title, 'caffeinated'
# # Check inheritance chain
# A::getTitle = () -> @title
# eq b.getTitle(), 'caffeinated'
# throwsC = """
# C = {title: 'invalid'}
# class D extends {}
# """
# # This should catch on compile and message should be "class can only extend classes and functions."
# throws -> CoffeeScript.run throwsC, bare: yes
# TODO: Evaluate future compliance with "strict mode";
# test "Class function environment should be in `strict mode`, ie as if 'use strict' was in use", ->
# class A
# # this might be a meaningless test, since these are likely to be runtime errors and different
# # for every browser. Thoughts?
# constructor: () ->
# # Ivalid: prop reassignment
# @state = {prop: [1], prop: {a: 'a'}}
# # eval reassignment
# @badEval = eval;
# # Should throw, but doesn't
# a = new A
# TODO: new.target needs support Separate issue
# test "ES6 support for new.target (functions and constructors)", ->
# throwsA = """
# class A
# constructor: () ->
# a = new.target.name
# """
# throws -> CoffeeScript.compile throwsA, bare: yes
test "only one method named constructor allowed", ->
throwsA = """
class A
constructor: (@first) ->
constructor: (@last) ->
"""
throws -> CoffeeScript.compile throwsA, bare: yes
test "If the constructor of a child class does not call super,it should return an object.", ->
nonce = {}
class A
class B extends A
constructor: ->
return nonce
eq nonce, new B
test "super can only exist in extended classes", ->
throwsA = """
class A
constructor: (@name) ->
super()
"""
throws -> CoffeeScript.compile throwsA, bare: yes
# --- CS1 classes compatability breaks ---
test "CS6 Class extends a CS1 compiled class", ->
```
// Generated by CoffeeScript 1.11.1
var BaseCS1, ExtendedCS1,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
BaseCS1 = (function() {
function BaseCS1(drink) {
this.drink = drink;
}
BaseCS1.prototype.make = function() {
return "making a " + this.drink;
};
BaseCS1.className = function() {
return 'BaseCS1';
};
return BaseCS1;
})();
ExtendedCS1 = (function(superClass) {
extend(ExtendedCS1, superClass);
function ExtendedCS1(flavor) {
this.flavor = flavor;
ExtendedCS1.__super__.constructor.call(this, 'cafe ole');
}
ExtendedCS1.prototype.make = function() {
return "making a " + this.drink + " with " + this.flavor;
};
ExtendedCS1.className = function() {
return 'ExtendedCS1';
};
return ExtendedCS1;
})(BaseCS1);
```
class B extends BaseCS1
eq B.className(), 'BaseCS1'
b = new B('machiato')
eq b.make(), "making a machiato"
test "CS6 Class extends an extended CS1 compiled class", ->
```
// Generated by CoffeeScript 1.11.1
var BaseCS1, ExtendedCS1,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
BaseCS1 = (function() {
function BaseCS1(drink) {
this.drink = drink;
}
BaseCS1.prototype.make = function() {
return "making a " + this.drink;
};
BaseCS1.className = function() {
return 'BaseCS1';
};
return BaseCS1;
})();
ExtendedCS1 = (function(superClass) {
extend(ExtendedCS1, superClass);
function ExtendedCS1(flavor) {
this.flavor = flavor;
ExtendedCS1.__super__.constructor.call(this, 'cafe ole');
}
ExtendedCS1.prototype.make = function() {
return "making a " + this.drink + " with " + this.flavor;
};
ExtendedCS1.className = function() {
return 'ExtendedCS1';
};
return ExtendedCS1;
})(BaseCS1);
```
class B extends ExtendedCS1
eq B.className(), 'ExtendedCS1'
b = new B('vanilla')
eq b.make(), "making a cafe ole with vanilla"
test "CS6 Class extends a CS1 compiled class with super()", ->
```
// Generated by CoffeeScript 1.11.1
var BaseCS1, ExtendedCS1,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
BaseCS1 = (function() {
function BaseCS1(drink) {
this.drink = drink;
}
BaseCS1.prototype.make = function() {
return "making a " + this.drink;
};
BaseCS1.className = function() {
return 'BaseCS1';
};
return BaseCS1;
})();
ExtendedCS1 = (function(superClass) {
extend(ExtendedCS1, superClass);
function ExtendedCS1(flavor) {
this.flavor = flavor;
ExtendedCS1.__super__.constructor.call(this, 'cafe ole');
}
ExtendedCS1.prototype.make = function() {
return "making a " + this.drink + " with " + this.flavor;
};
ExtendedCS1.className = function() {
return 'ExtendedCS1';
};
return ExtendedCS1;
})(BaseCS1);
```
class B extends ExtendedCS1
constructor: (@shots) ->
super('caramel')
make: () ->
super() + " and #{@shots} shots of espresso"
eq B.className(), 'ExtendedCS1'
b = new B('three')
eq b.make(), "making a cafe ole with caramel and three shots of espresso"
test 'Bound method called normally before binding is ok', ->
class Base
constructor: ->
@setProp()
eq @derivedBound(), 3
class Derived extends Base
setProp: ->
@prop = 3
derivedBound: =>
@prop
d = new Derived
test 'Bound method called as callback after super() is ok', ->
class Base
class Derived extends Base
constructor: (@prop = 3) ->
super()
f = @derivedBound
eq f(), 3
derivedBound: =>
@prop
d = new Derived
{derivedBound} = d
eq derivedBound(), 3
test 'Bound method of base class called as callback is ok', ->
class Base
constructor: (@prop = 3) ->
f = @baseBound
eq f(), 3
baseBound: =>
@prop
b = new Base
{baseBound} = b
eq baseBound(), 3
test 'Bound method of prop-named class called as callback is ok', ->
Hive = {}
class Hive.Bee
constructor: (@prop = 3) ->
f = @baseBound
eq f(), 3
baseBound: =>
@prop
b = new Hive.Bee
{baseBound} = b
eq baseBound(), 3
test 'Bound method of class with expression base class called as callback is ok', ->
calledB = no
B = ->
throw new Error if calledB
calledB = yes
class
class A extends B()
constructor: (@prop = 3) ->
super()
f = @derivedBound
eq f(), 3
derivedBound: =>
@prop
b = new A
{derivedBound} = b
eq derivedBound(), 3
test 'Bound method of class with expression class name called as callback is ok', ->
calledF = no
obj = {}
B = class
f = ->
throw new Error if calledF
calledF = yes
obj
class f().A extends B
constructor: (@prop = 3) ->
super()
g = @derivedBound
eq g(), 3
derivedBound: =>
@prop
a = new obj.A
{derivedBound} = a
eq derivedBound(), 3
test 'Bound method of anonymous child class called as callback is ok', ->
f = ->
B = class
class extends B
constructor: (@prop = 3) ->
super()
g = @derivedBound
eq g(), 3
derivedBound: =>
@prop
a = new (f())
{derivedBound} = a
eq derivedBound(), 3
test 'Bound method of immediately instantiated class with expression base class called as callback is ok', ->
calledF = no
obj = {}
B = class
f = ->
throw new Error if calledF
calledF = yes
obj
a = new class f().A extends B
constructor: (@prop = 3) ->
super()
g = @derivedBound
eq g(), 3
derivedBound: =>
@prop
{derivedBound} = a
eq derivedBound(), 3
test "#4591: super.x.y, super['x'].y", ->
class A
x:
y: 1
z: -> 2
class B extends A
constructor: ->
super()
@w = super.x.y
@v = super['x'].y
@u = super.x['y']
@t = super.x.z()
@s = super['x'].z()
@r = super.x['z']()
b = new B
eq 1, b.w
eq 1, b.v
eq 1, b.u
eq 2, b.t
eq 2, b.s
eq 2, b.r
test "#4464: backticked expressions in class body", ->
class A
`get x() { return 42; }`
class B
`get x() { return 42; }`
constructor: ->
@y = 84
a = new A
eq 42, a.x
b = new B
eq 42, b.x
eq 84, b.y
test "#4724: backticked expression in a class body with hoisted member", ->
class A
`get x() { return 42; }`
hoisted: 84
a = new A
eq 42, a.x
eq 84, a.hoisted
|
[
{
"context": "g strict\", ->\n qs2mongo.parse query: name: [\"juan\", \"jacobs\"]\n .filters.should.eql\n nam",
"end": 5133,
"score": 0.8291997909545898,
"start": 5129,
"tag": "NAME",
"value": "juan"
},
{
"context": "\", ->\n qs2mongo.parse query: name: [\"juan\... | src/qs2mongo.spec.coffee | Parsimotion/qs2mongo | 0 | _ = require("lodash")
should = require("should")
Qs2Mongo = require("./qs2mongo")
{ ObjectId } = require("mongodb")
Manual = require("./schemas/manual")
{ qs2mongo, req, multigetReq, multigetObjectIdReq, aDate, dateReq, aNumber, numberReq, anObjectId, objectIdReq } = {}
describe "Qs2Mongo", ->
beforeEach ->
req =
query:
aField: "aValue"
anotherField: "anotherValue"
"fields,joinedByOr": "theOrValue"
aBooleanField: "false"
attributes:"aField,anotherField"
limit: "10"
offset: "20"
multigetReq = query: ids: ["unId","otroId"].join()
aDate = new Date("1999/01/02")
dateReq = query: aDateField: aDate.toISOString()
aNumber = 42
numberReq = query: aNumberField: aNumber.toString()
anObjectId = "5919e3f5b89e9defa593734d"
objectIdReq = query: anObjectIdField: anObjectId
multigetObjectIdReq = query: ids: anObjectId
schema = new Manual
filterableBooleans: ["aBooleanField"]
filterableDates: ["aDateField"]
filterableNumbers: ["aNumberField"]
filterableObjectIds: ["anObjectIdField"]
qs2mongo = new Qs2Mongo {
schema
defaultSort: "_id"
}
it "should build everything in a query string", ->
qs2mongo.parse req
.should.eql
filters:
aField: /aValue/i
anotherField: /anotherValue/i
aBooleanField: false
$or: [
{ fields:/theOrValue/i }
{ joinedByOr: /theOrValue/i }
]
projection:
aField:1
anotherField:1
options:
limit: 10
offset: 20
sort:
_id: 1
it "When used as middleware should set mongo property in req object", (done)->
qs2mongo.middleware req, _, ->
req.mongo.should.eql
filters:
aField: /aValue/i
anotherField: /anotherValue/i
aBooleanField: false
$or: [
{ fields:/theOrValue/i }
{ joinedByOr: /theOrValue/i }
]
projection:
aField:1
anotherField:1
options:
limit: 10
offset: 20
sort:
_id: 1
done()
describe "Projection", ->
it "should build projection", ->
qs2mongo.parse req
.projection.should.eql
aField:1
anotherField:1
describe "Options", ->
describe "Sort", ->
it "should build options without any sort", ->
qs2mongo.defaultSort = null
{ options } = qs2mongo.parse req
should.not.exist options.sort
it "should build options with default sort", ->
qs2mongo.parse req
.options.sort.should.eql
_id: 1
it "should build options with ascending sort", ->
sort = "aField"
_.assign req.query, { sort }
qs2mongo.parse req
.options.sort.should.eql
aField: 1
it "should build options with descending sort", ->
sort = "-aField"
_.assign req.query, { sort }
qs2mongo.parse req
.options.sort.should.eql
aField: -1
describe "Limit and offset", ->
it "should build options with limit and offset when valid", ->
qs2mongo.defaultSort = "_id"
qs2mongo.parse req
.options.should.containDeep
limit: 10
offset: 20
it "should build options without limit and offset options", ->
delete req.query.limit
delete req.query.offset
{ options } = qs2mongo.parse req
should.not.exist options.limit
should.not.exist options.offset
describe "Filters", ->
it "should attach multiple filters to one field if not using strict", ->
from = new Date("2017/06/03")
to = new Date("2017/07/02")
qs2mongo.parse
query:
aDateField__gte: from.toISOString()
aDateField__lt: to.toISOString()
.filters.should.eql
aDateField: { $gte: from, $lt: to }
it "should attach multiple filters to one field if using strict", ->
from = new Date("2017/06/03")
to = new Date("2017/07/02")
qs2mongo.parse
query:
aDateField__gte: from.toISOString()
aDateField__lt: to.toISOString()
, strict: true
.filters.should.eql
aDateField: { $gte: from, $lt: to }
it "should build filters with like ignore case if not using strict", ->
qs2mongo.parse req
.filters.should.eql
aField: /aValue/i
anotherField: /anotherValue/i
aBooleanField: false
$or: [
{ fields:/theOrValue/i }
{ joinedByOr: /theOrValue/i }
]
it "should build filters with equal if using strict", ->
qs2mongo.parse req, strict: true
.filters.should.eql
aField: "aValue"
anotherField: "anotherValue"
aBooleanField: false
$or: [
{ fields: "theOrValue" }
{ joinedByOr: "theOrValue" }
]
it "should get multiple values in regex as and if not using strict", ->
qs2mongo.parse query: name: ["juan", "jacobs"]
.filters.should.eql
name: /^(?=.*?juan)(?=.*?jacobs)/i
it "should get date filters as dates", ->
qs2mongo.parse dateReq, strict: true
.filters.should.eql
aDateField: aDate
it "should get date filters as dates if not strict", ->
qs2mongo.parse dateReq
.filters.should.eql
aDateField: aDate
it "should get number filters as numbers", ->
qs2mongo.parse numberReq, strict: true
.filters.should.eql
aNumberField: aNumber
it "should get objectid filters as objectids", ->
qs2mongo.parse objectIdReq, strict: true
.filters.should.eql
anObjectIdField: new ObjectId anObjectId
it "should get objectid filters as objectids without strict", ->
qs2mongo.parse objectIdReq
.filters.should.eql
anObjectIdField: new ObjectId anObjectId
describe "Multiget", ->
it "should build multiget filters using strict", ->
qs2mongo.parse multigetReq, strict: true
.filters.should.eql
_id: $in: ["unId","otroId"]
it "should build multiget filters without using strict", ->
qs2mongo.parse multigetReq
.filters.should.eql
_id: $in: ["unId","otroId"]
it "should build multiget filters using a custom property", ->
qs2mongo.multigetIdField = "custom_id"
qs2mongo.parse multigetReq
.filters.should.eql
custom_id: $in: ["unId","otroId"]
it "should build multiget filters casting to proper type", ->
qs2mongo.multigetIdField = "anObjectIdField"
qs2mongo.parse multigetObjectIdReq
.filters.should.eql
anObjectIdField: $in: [ new ObjectId anObjectId ]
describe "Operators", ->
it "should build filters with operator", ->
qs2mongo.parse query: aField__gt: "23"
.filters.should.eql
aField: $gt: "23"
it "should build filters with mixed operators", ->
qs2mongo.parse
query:
aField__gt: "23"
anotherField__lt: "42"
yetAnotherField: "aValue"
.filters.should.eql
aField: $gt: "23"
anotherField: $lt: "42"
yetAnotherField: /aValue/i
it "should build filters with date operator", ->
qs2mongo.parse {query: aDateField__gt: aDate.toISOString()}, strict: true
.filters.should.eql
aDateField: $gt: aDate
it "should build filters with date operator without strict", ->
qs2mongo.parse {query: aDateField__gt: aDate.toISOString()}
.filters.should.eql
aDateField: $gt: aDate
describe "$in Operator", ->
it "should build filters without strict", ->
qs2mongo.parse {query: aField__in: "a,b,c"}
.filters.should.eql
aField: $in: ["a","b","c"]
it "should build filters with strict", ->
qs2mongo.parse {query: aField__in: "a,b,c"}, strict:true
.filters.should.eql
aField: $in: ["a","b","c"]
it "should correctly build single item number filter with strict", ->
qs2mongo.parse {query: aNumberField__in: "1"}, strict:true
.filters.should.eql aNumberField: $in: [1]
it "should correctly build single item number filter without strict", ->
qs2mongo.parse {query: aNumberField__in: "1"}
.filters.should.eql aNumberField: $in: [1]
describe "type casting", ->
it "should cast $in operands to number when field es numeric without strict", ->
qs2mongo.parse {query: aNumberField__in: "1,2,3"}
.filters.should.eql
aNumberField: $in: [1,2,3]
it "should not cast $in operands to number when field is not numeric without strict", ->
qs2mongo.parse {query: aField__in: "1,2,3"}
.filters.should.eql
aField: $in: ["1","2","3"]
it "should cast $in operands to number when field is numeric", ->
qs2mongo.parse {query: aNumberField__in: "1,2,3"}, strict: true
.filters.should.eql
aNumberField: $in: [1,2,3]
it "should not cast $in operands to number when field is not numeric", ->
qs2mongo.parse {query: aField__in: "1,2,3"}, strict: true
.filters.should.eql
aField: $in: ["1","2","3"]
it "should cast each $or operand to its right type without strict", ->
qs2mongo.parse {query: "aField,aNumberField": "123"}
.filters.should.eql
$or: [{aField:/123/i}, {aNumberField:123}]
it "should cast each $or operand to its right type", ->
qs2mongo.parse {query: "aField,aNumberField": "123"}, strict: true
.filters.should.eql
$or: [{aField:"123"}, {aNumberField:123}]
it "should omit filter if operand has value outside its domain in $or operand ", ->
qs2mongo.parse {query: "aField,aNumberField": "asdf"}, strict: true
.filters.should.eql
$or: [{aField:"asdf"}]
it "should omit filter if date operand has value outside its domain in $or operand ", ->
qs2mongo.parse {query: "aField,aDateField,anObjectIdField": "asdf"}, strict: true
.filters.should.eql
$or: [{aField:"asdf"}]
it "should omit filter if date operand has value outside its domain in $or operand ", ->
qs2mongo.parse {query: "aField,aDateField,anObjectIdField": anObjectId}, strict: true
.filters.should.eql
$or: [{aField:anObjectId}, { anObjectIdField: new ObjectId anObjectId }]
it "should omit filter if operand has value outside its domain in $or operand without strict", ->
qs2mongo.parse {query: "aField,aNumberField": "asdf"}
.filters.should.eql
$or: [{aField:/asdf/i}]
| 3991 | _ = require("lodash")
should = require("should")
Qs2Mongo = require("./qs2mongo")
{ ObjectId } = require("mongodb")
Manual = require("./schemas/manual")
{ qs2mongo, req, multigetReq, multigetObjectIdReq, aDate, dateReq, aNumber, numberReq, anObjectId, objectIdReq } = {}
describe "Qs2Mongo", ->
beforeEach ->
req =
query:
aField: "aValue"
anotherField: "anotherValue"
"fields,joinedByOr": "theOrValue"
aBooleanField: "false"
attributes:"aField,anotherField"
limit: "10"
offset: "20"
multigetReq = query: ids: ["unId","otroId"].join()
aDate = new Date("1999/01/02")
dateReq = query: aDateField: aDate.toISOString()
aNumber = 42
numberReq = query: aNumberField: aNumber.toString()
anObjectId = "5919e3f5b89e9defa593734d"
objectIdReq = query: anObjectIdField: anObjectId
multigetObjectIdReq = query: ids: anObjectId
schema = new Manual
filterableBooleans: ["aBooleanField"]
filterableDates: ["aDateField"]
filterableNumbers: ["aNumberField"]
filterableObjectIds: ["anObjectIdField"]
qs2mongo = new Qs2Mongo {
schema
defaultSort: "_id"
}
it "should build everything in a query string", ->
qs2mongo.parse req
.should.eql
filters:
aField: /aValue/i
anotherField: /anotherValue/i
aBooleanField: false
$or: [
{ fields:/theOrValue/i }
{ joinedByOr: /theOrValue/i }
]
projection:
aField:1
anotherField:1
options:
limit: 10
offset: 20
sort:
_id: 1
it "When used as middleware should set mongo property in req object", (done)->
qs2mongo.middleware req, _, ->
req.mongo.should.eql
filters:
aField: /aValue/i
anotherField: /anotherValue/i
aBooleanField: false
$or: [
{ fields:/theOrValue/i }
{ joinedByOr: /theOrValue/i }
]
projection:
aField:1
anotherField:1
options:
limit: 10
offset: 20
sort:
_id: 1
done()
describe "Projection", ->
it "should build projection", ->
qs2mongo.parse req
.projection.should.eql
aField:1
anotherField:1
describe "Options", ->
describe "Sort", ->
it "should build options without any sort", ->
qs2mongo.defaultSort = null
{ options } = qs2mongo.parse req
should.not.exist options.sort
it "should build options with default sort", ->
qs2mongo.parse req
.options.sort.should.eql
_id: 1
it "should build options with ascending sort", ->
sort = "aField"
_.assign req.query, { sort }
qs2mongo.parse req
.options.sort.should.eql
aField: 1
it "should build options with descending sort", ->
sort = "-aField"
_.assign req.query, { sort }
qs2mongo.parse req
.options.sort.should.eql
aField: -1
describe "Limit and offset", ->
it "should build options with limit and offset when valid", ->
qs2mongo.defaultSort = "_id"
qs2mongo.parse req
.options.should.containDeep
limit: 10
offset: 20
it "should build options without limit and offset options", ->
delete req.query.limit
delete req.query.offset
{ options } = qs2mongo.parse req
should.not.exist options.limit
should.not.exist options.offset
describe "Filters", ->
it "should attach multiple filters to one field if not using strict", ->
from = new Date("2017/06/03")
to = new Date("2017/07/02")
qs2mongo.parse
query:
aDateField__gte: from.toISOString()
aDateField__lt: to.toISOString()
.filters.should.eql
aDateField: { $gte: from, $lt: to }
it "should attach multiple filters to one field if using strict", ->
from = new Date("2017/06/03")
to = new Date("2017/07/02")
qs2mongo.parse
query:
aDateField__gte: from.toISOString()
aDateField__lt: to.toISOString()
, strict: true
.filters.should.eql
aDateField: { $gte: from, $lt: to }
it "should build filters with like ignore case if not using strict", ->
qs2mongo.parse req
.filters.should.eql
aField: /aValue/i
anotherField: /anotherValue/i
aBooleanField: false
$or: [
{ fields:/theOrValue/i }
{ joinedByOr: /theOrValue/i }
]
it "should build filters with equal if using strict", ->
qs2mongo.parse req, strict: true
.filters.should.eql
aField: "aValue"
anotherField: "anotherValue"
aBooleanField: false
$or: [
{ fields: "theOrValue" }
{ joinedByOr: "theOrValue" }
]
it "should get multiple values in regex as and if not using strict", ->
qs2mongo.parse query: name: ["<NAME>", "<NAME>"]
.filters.should.eql
name: /^(?=.*?juan)(?=.*?jacobs)/i
it "should get date filters as dates", ->
qs2mongo.parse dateReq, strict: true
.filters.should.eql
aDateField: aDate
it "should get date filters as dates if not strict", ->
qs2mongo.parse dateReq
.filters.should.eql
aDateField: aDate
it "should get number filters as numbers", ->
qs2mongo.parse numberReq, strict: true
.filters.should.eql
aNumberField: aNumber
it "should get objectid filters as objectids", ->
qs2mongo.parse objectIdReq, strict: true
.filters.should.eql
anObjectIdField: new ObjectId anObjectId
it "should get objectid filters as objectids without strict", ->
qs2mongo.parse objectIdReq
.filters.should.eql
anObjectIdField: new ObjectId anObjectId
describe "Multiget", ->
it "should build multiget filters using strict", ->
qs2mongo.parse multigetReq, strict: true
.filters.should.eql
_id: $in: ["unId","otroId"]
it "should build multiget filters without using strict", ->
qs2mongo.parse multigetReq
.filters.should.eql
_id: $in: ["unId","otroId"]
it "should build multiget filters using a custom property", ->
qs2mongo.multigetIdField = "custom_id"
qs2mongo.parse multigetReq
.filters.should.eql
custom_id: $in: ["unId","otroId"]
it "should build multiget filters casting to proper type", ->
qs2mongo.multigetIdField = "anObjectIdField"
qs2mongo.parse multigetObjectIdReq
.filters.should.eql
anObjectIdField: $in: [ new ObjectId anObjectId ]
describe "Operators", ->
it "should build filters with operator", ->
qs2mongo.parse query: aField__gt: "23"
.filters.should.eql
aField: $gt: "23"
it "should build filters with mixed operators", ->
qs2mongo.parse
query:
aField__gt: "23"
anotherField__lt: "42"
yetAnotherField: "aValue"
.filters.should.eql
aField: $gt: "23"
anotherField: $lt: "42"
yetAnotherField: /aValue/i
it "should build filters with date operator", ->
qs2mongo.parse {query: aDateField__gt: aDate.toISOString()}, strict: true
.filters.should.eql
aDateField: $gt: aDate
it "should build filters with date operator without strict", ->
qs2mongo.parse {query: aDateField__gt: aDate.toISOString()}
.filters.should.eql
aDateField: $gt: aDate
describe "$in Operator", ->
it "should build filters without strict", ->
qs2mongo.parse {query: aField__in: "a,b,c"}
.filters.should.eql
aField: $in: ["a","b","c"]
it "should build filters with strict", ->
qs2mongo.parse {query: aField__in: "a,b,c"}, strict:true
.filters.should.eql
aField: $in: ["a","b","c"]
it "should correctly build single item number filter with strict", ->
qs2mongo.parse {query: aNumberField__in: "1"}, strict:true
.filters.should.eql aNumberField: $in: [1]
it "should correctly build single item number filter without strict", ->
qs2mongo.parse {query: aNumberField__in: "1"}
.filters.should.eql aNumberField: $in: [1]
describe "type casting", ->
it "should cast $in operands to number when field es numeric without strict", ->
qs2mongo.parse {query: aNumberField__in: "1,2,3"}
.filters.should.eql
aNumberField: $in: [1,2,3]
it "should not cast $in operands to number when field is not numeric without strict", ->
qs2mongo.parse {query: aField__in: "1,2,3"}
.filters.should.eql
aField: $in: ["1","2","3"]
it "should cast $in operands to number when field is numeric", ->
qs2mongo.parse {query: aNumberField__in: "1,2,3"}, strict: true
.filters.should.eql
aNumberField: $in: [1,2,3]
it "should not cast $in operands to number when field is not numeric", ->
qs2mongo.parse {query: aField__in: "1,2,3"}, strict: true
.filters.should.eql
aField: $in: ["1","2","3"]
it "should cast each $or operand to its right type without strict", ->
qs2mongo.parse {query: "aField,aNumberField": "123"}
.filters.should.eql
$or: [{aField:/123/i}, {aNumberField:123}]
it "should cast each $or operand to its right type", ->
qs2mongo.parse {query: "aField,aNumberField": "123"}, strict: true
.filters.should.eql
$or: [{aField:"123"}, {aNumberField:123}]
it "should omit filter if operand has value outside its domain in $or operand ", ->
qs2mongo.parse {query: "aField,aNumberField": "asdf"}, strict: true
.filters.should.eql
$or: [{aField:"asdf"}]
it "should omit filter if date operand has value outside its domain in $or operand ", ->
qs2mongo.parse {query: "aField,aDateField,anObjectIdField": "asdf"}, strict: true
.filters.should.eql
$or: [{aField:"asdf"}]
it "should omit filter if date operand has value outside its domain in $or operand ", ->
qs2mongo.parse {query: "aField,aDateField,anObjectIdField": anObjectId}, strict: true
.filters.should.eql
$or: [{aField:anObjectId}, { anObjectIdField: new ObjectId anObjectId }]
it "should omit filter if operand has value outside its domain in $or operand without strict", ->
qs2mongo.parse {query: "aField,aNumberField": "asdf"}
.filters.should.eql
$or: [{aField:/asdf/i}]
| true | _ = require("lodash")
should = require("should")
Qs2Mongo = require("./qs2mongo")
{ ObjectId } = require("mongodb")
Manual = require("./schemas/manual")
{ qs2mongo, req, multigetReq, multigetObjectIdReq, aDate, dateReq, aNumber, numberReq, anObjectId, objectIdReq } = {}
describe "Qs2Mongo", ->
beforeEach ->
req =
query:
aField: "aValue"
anotherField: "anotherValue"
"fields,joinedByOr": "theOrValue"
aBooleanField: "false"
attributes:"aField,anotherField"
limit: "10"
offset: "20"
multigetReq = query: ids: ["unId","otroId"].join()
aDate = new Date("1999/01/02")
dateReq = query: aDateField: aDate.toISOString()
aNumber = 42
numberReq = query: aNumberField: aNumber.toString()
anObjectId = "5919e3f5b89e9defa593734d"
objectIdReq = query: anObjectIdField: anObjectId
multigetObjectIdReq = query: ids: anObjectId
schema = new Manual
filterableBooleans: ["aBooleanField"]
filterableDates: ["aDateField"]
filterableNumbers: ["aNumberField"]
filterableObjectIds: ["anObjectIdField"]
qs2mongo = new Qs2Mongo {
schema
defaultSort: "_id"
}
it "should build everything in a query string", ->
qs2mongo.parse req
.should.eql
filters:
aField: /aValue/i
anotherField: /anotherValue/i
aBooleanField: false
$or: [
{ fields:/theOrValue/i }
{ joinedByOr: /theOrValue/i }
]
projection:
aField:1
anotherField:1
options:
limit: 10
offset: 20
sort:
_id: 1
it "When used as middleware should set mongo property in req object", (done)->
qs2mongo.middleware req, _, ->
req.mongo.should.eql
filters:
aField: /aValue/i
anotherField: /anotherValue/i
aBooleanField: false
$or: [
{ fields:/theOrValue/i }
{ joinedByOr: /theOrValue/i }
]
projection:
aField:1
anotherField:1
options:
limit: 10
offset: 20
sort:
_id: 1
done()
describe "Projection", ->
it "should build projection", ->
qs2mongo.parse req
.projection.should.eql
aField:1
anotherField:1
describe "Options", ->
describe "Sort", ->
it "should build options without any sort", ->
qs2mongo.defaultSort = null
{ options } = qs2mongo.parse req
should.not.exist options.sort
it "should build options with default sort", ->
qs2mongo.parse req
.options.sort.should.eql
_id: 1
it "should build options with ascending sort", ->
sort = "aField"
_.assign req.query, { sort }
qs2mongo.parse req
.options.sort.should.eql
aField: 1
it "should build options with descending sort", ->
sort = "-aField"
_.assign req.query, { sort }
qs2mongo.parse req
.options.sort.should.eql
aField: -1
describe "Limit and offset", ->
it "should build options with limit and offset when valid", ->
qs2mongo.defaultSort = "_id"
qs2mongo.parse req
.options.should.containDeep
limit: 10
offset: 20
it "should build options without limit and offset options", ->
delete req.query.limit
delete req.query.offset
{ options } = qs2mongo.parse req
should.not.exist options.limit
should.not.exist options.offset
describe "Filters", ->
it "should attach multiple filters to one field if not using strict", ->
from = new Date("2017/06/03")
to = new Date("2017/07/02")
qs2mongo.parse
query:
aDateField__gte: from.toISOString()
aDateField__lt: to.toISOString()
.filters.should.eql
aDateField: { $gte: from, $lt: to }
it "should attach multiple filters to one field if using strict", ->
from = new Date("2017/06/03")
to = new Date("2017/07/02")
qs2mongo.parse
query:
aDateField__gte: from.toISOString()
aDateField__lt: to.toISOString()
, strict: true
.filters.should.eql
aDateField: { $gte: from, $lt: to }
it "should build filters with like ignore case if not using strict", ->
qs2mongo.parse req
.filters.should.eql
aField: /aValue/i
anotherField: /anotherValue/i
aBooleanField: false
$or: [
{ fields:/theOrValue/i }
{ joinedByOr: /theOrValue/i }
]
it "should build filters with equal if using strict", ->
qs2mongo.parse req, strict: true
.filters.should.eql
aField: "aValue"
anotherField: "anotherValue"
aBooleanField: false
$or: [
{ fields: "theOrValue" }
{ joinedByOr: "theOrValue" }
]
it "should get multiple values in regex as and if not using strict", ->
qs2mongo.parse query: name: ["PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI"]
.filters.should.eql
name: /^(?=.*?juan)(?=.*?jacobs)/i
it "should get date filters as dates", ->
qs2mongo.parse dateReq, strict: true
.filters.should.eql
aDateField: aDate
it "should get date filters as dates if not strict", ->
qs2mongo.parse dateReq
.filters.should.eql
aDateField: aDate
it "should get number filters as numbers", ->
qs2mongo.parse numberReq, strict: true
.filters.should.eql
aNumberField: aNumber
it "should get objectid filters as objectids", ->
qs2mongo.parse objectIdReq, strict: true
.filters.should.eql
anObjectIdField: new ObjectId anObjectId
it "should get objectid filters as objectids without strict", ->
qs2mongo.parse objectIdReq
.filters.should.eql
anObjectIdField: new ObjectId anObjectId
describe "Multiget", ->
it "should build multiget filters using strict", ->
qs2mongo.parse multigetReq, strict: true
.filters.should.eql
_id: $in: ["unId","otroId"]
it "should build multiget filters without using strict", ->
qs2mongo.parse multigetReq
.filters.should.eql
_id: $in: ["unId","otroId"]
it "should build multiget filters using a custom property", ->
qs2mongo.multigetIdField = "custom_id"
qs2mongo.parse multigetReq
.filters.should.eql
custom_id: $in: ["unId","otroId"]
it "should build multiget filters casting to proper type", ->
qs2mongo.multigetIdField = "anObjectIdField"
qs2mongo.parse multigetObjectIdReq
.filters.should.eql
anObjectIdField: $in: [ new ObjectId anObjectId ]
describe "Operators", ->
it "should build filters with operator", ->
qs2mongo.parse query: aField__gt: "23"
.filters.should.eql
aField: $gt: "23"
it "should build filters with mixed operators", ->
qs2mongo.parse
query:
aField__gt: "23"
anotherField__lt: "42"
yetAnotherField: "aValue"
.filters.should.eql
aField: $gt: "23"
anotherField: $lt: "42"
yetAnotherField: /aValue/i
it "should build filters with date operator", ->
qs2mongo.parse {query: aDateField__gt: aDate.toISOString()}, strict: true
.filters.should.eql
aDateField: $gt: aDate
it "should build filters with date operator without strict", ->
qs2mongo.parse {query: aDateField__gt: aDate.toISOString()}
.filters.should.eql
aDateField: $gt: aDate
describe "$in Operator", ->
it "should build filters without strict", ->
qs2mongo.parse {query: aField__in: "a,b,c"}
.filters.should.eql
aField: $in: ["a","b","c"]
it "should build filters with strict", ->
qs2mongo.parse {query: aField__in: "a,b,c"}, strict:true
.filters.should.eql
aField: $in: ["a","b","c"]
it "should correctly build single item number filter with strict", ->
qs2mongo.parse {query: aNumberField__in: "1"}, strict:true
.filters.should.eql aNumberField: $in: [1]
it "should correctly build single item number filter without strict", ->
qs2mongo.parse {query: aNumberField__in: "1"}
.filters.should.eql aNumberField: $in: [1]
describe "type casting", ->
it "should cast $in operands to number when field es numeric without strict", ->
qs2mongo.parse {query: aNumberField__in: "1,2,3"}
.filters.should.eql
aNumberField: $in: [1,2,3]
it "should not cast $in operands to number when field is not numeric without strict", ->
qs2mongo.parse {query: aField__in: "1,2,3"}
.filters.should.eql
aField: $in: ["1","2","3"]
it "should cast $in operands to number when field is numeric", ->
qs2mongo.parse {query: aNumberField__in: "1,2,3"}, strict: true
.filters.should.eql
aNumberField: $in: [1,2,3]
it "should not cast $in operands to number when field is not numeric", ->
qs2mongo.parse {query: aField__in: "1,2,3"}, strict: true
.filters.should.eql
aField: $in: ["1","2","3"]
it "should cast each $or operand to its right type without strict", ->
qs2mongo.parse {query: "aField,aNumberField": "123"}
.filters.should.eql
$or: [{aField:/123/i}, {aNumberField:123}]
it "should cast each $or operand to its right type", ->
qs2mongo.parse {query: "aField,aNumberField": "123"}, strict: true
.filters.should.eql
$or: [{aField:"123"}, {aNumberField:123}]
it "should omit filter if operand has value outside its domain in $or operand ", ->
qs2mongo.parse {query: "aField,aNumberField": "asdf"}, strict: true
.filters.should.eql
$or: [{aField:"asdf"}]
it "should omit filter if date operand has value outside its domain in $or operand ", ->
qs2mongo.parse {query: "aField,aDateField,anObjectIdField": "asdf"}, strict: true
.filters.should.eql
$or: [{aField:"asdf"}]
it "should omit filter if date operand has value outside its domain in $or operand ", ->
qs2mongo.parse {query: "aField,aDateField,anObjectIdField": anObjectId}, strict: true
.filters.should.eql
$or: [{aField:anObjectId}, { anObjectIdField: new ObjectId anObjectId }]
it "should omit filter if operand has value outside its domain in $or operand without strict", ->
qs2mongo.parse {query: "aField,aNumberField": "asdf"}
.filters.should.eql
$or: [{aField:/asdf/i}]
|
[
{
"context": "d authentication creds\n ipc.send 'password:validate', 'null', (result) =>\n if result\n ",
"end": 5730,
"score": 0.6594139933586121,
"start": 5722,
"tag": "PASSWORD",
"value": "validate"
}
] | src/renderer/coffee/listeners/state.coffee | s1090709/vessel | 101 | define (require, exports, module) ->
$ = require 'jquery'
Backbone = require 'backbone'
Listener = require 'listener'
environment = require 'cs!utils/environment'
ipc = require 'cs!utils/ipc'
# Coordinate UI actions based upon state requirements
#
class State extends Listener
events:
'application:status': 'onApplicationStatus'
'auth:password': 'onAuthPassword'
'cloud-config:built': 'onCloudConfigBuilt'
'docker:started': 'onDockerStarted'
'docker:container:request:start': 'onDockerStartRequest'
'docker:container:request:stop': 'onDockerStopRequest'
'docker:containers:updated': 'onDockerContainers'
'environment:build:request': 'onBuildRequest'
'environment:build:complete': 'onBuildComplete'
'error': 'onError'
'timers:pause': 'pauseTimer'
'timers:resume': 'startTimer'
'vagrant:log': 'onVagrantLog'
'vagrant:request:halt': 'onVagrantHalt'
'vagrant:request:update': 'onVagrantUpdate'
'vagrant:request:up': 'onVagrantUp'
'vagrant:up:error': 'onVagrantUpError'
vagrantSteps: [
'Bringing machine'
'Importing base box'
'Machine booted and ready!'
'Configuring and enabling network'
'Exporting NFS shared folders'
'Mounting NFS shared folders'
'Running provisioner: file'
'Running provisioner: shell'
]
_dirty: false
_refreshTimer: null
_singleAction: null
_state: null
initialize: ->
@_setState 'initializing'
@_deferreds =
config: $.Deferred()
containers: $.Deferred()
images: $.Deferred()
vagrant: $.Deferred()
$.when(@_deferreds.config.promise(),
@_deferreds.containers.promise(),
@_deferreds.images.promise(),
@_deferreds.vagrant.promise()).done () =>
@_onInitialized()
@_listeners =
build: arguments[0].build
config: arguments[0].config
docker: arguments[0].docker
vagrant: arguments[0].vagrant
@config = @_listeners.config.model
@containers = @_listeners.docker.containers
@images = @_listeners.docker.images
@vagrant = @_listeners.vagrant.model
@listenTo @_listeners.build, 'dirty', () =>
@_onBuildEvent()
@listenToOnce @_listeners.config, 'loaded', () =>
@_onConfigLoaded()
@listenTo @_listeners.config, 'dirty', (model) =>
if @_state isnt 'initializing'
@_onConfigDirty()
@listenTo @_listeners.config, 'saved', (model) =>
@_setState 'saved'
@_dirty = false
@_toggleFooterButtons()
Backbone.trigger 'modal:status:hide'
@listenTo @_listeners.docker, 'images:change', (collection) =>
@_onImagesChange(collection)
@listenTo @_listeners.vagrant, 'change', (model) =>
@_onVagrantChange(model)
onApplicationStatus: (status, args...) =>
switch status
when 'container:started'
if @_singleAction is true
@_singleAction = null
Backbone.trigger 'modal:status:hide'
when 'container:stopped'
if @_singleAction is true
@_singleAction = null
Backbone.trigger 'modal:status:hide'
onAuthPassword: (value) =>
if @_vagrantRunning() is true
@_vagrantDestroy()
else
@_vagrantUp()
onBuildComplete: ->
Backbone.trigger 'configuration:save'
onBuildRequest: =>
@_setState 'build:start'
Backbone.trigger 'modal:status:show', 'build:start', true, true
Backbone.trigger 'environment:build'
onCloudConfigBuilt: =>
Backbone.trigger 'modal:status:step'
@_setState 'vagrant:starting'
Backbone.trigger 'vagrant:up'
onDockerContainers: =>
if @_state is 'initializing'
@_deferreds.containers.resolve()
onDockerStartRequest: (name) =>
@_singleAction = true
@_stopRefreshTimer()
Backbone.trigger 'modal:status:show', 'docker:start', false, true
Backbone.trigger 'docker:container:start', name
onDockerStopRequest: (name) =>
@_singleAction = true
Backbone.trigger 'modal:status:show', 'docker:stop', false, true
Backbone.trigger 'docker:container:stop', name
onDockerStarted: =>
@_setState 'running'
@_startRefreshTimer()
@_toggleFooterButtons()
Backbone.trigger 'modal:status:hide'
onError: (reason) =>
switch reason
when 'image:create'
if @_singleAction
@single_action = null
Backbone.trigger 'modal:status:hide'
onVagrantHalt: =>
@_stopRefreshTimer()
# If the password is set, assume it's corrent and start the build
if @config.get('password')?
@_vagrantDestroy()
else
# Dont show dialog if sudo has cached authentication creds
ipc.send 'password:validate', 'null', (result) =>
if result
@_vagrantDestroy()
else
Backbone.trigger 'modal:dialog:auth:show'
onVagrantLog: (message) =>
for step in @vagrantSteps
if message.indexOf(step) > -1
Backbone.trigger 'modal:status:step'
break
onVagrantUp: =>
@_stopRefreshTimer()
# If the password is set, assume it's corrent and start the build
if @config.get('password')?
@_vagrantUp()
else
# Dont show dialog if sudo has cached authentication creds
ipc.send 'password:validate', 'null', (result) =>
if result
@_vagrantUp()
else
Backbone.trigger 'modal:dialog:auth:show'
onVagrantUpdate: =>
@_stopRefreshTimer()
@_setState 'vagrant:updating'
Backbone.trigger 'modal:status:show', 'updating', false, true, true
Backbone.trigger 'vagrant:box:update'
onVagrantUpError: =>
@_setState 'vagrant:error'
@_toggleFooterButtons()
Backbone.trigger 'modal:status:hide'
Backbone.trigger 'error', 'vagrant:start'
pauseTimer: () ->
@_stopRefreshTimer()
resumeTimer: () ->
@_startRefreshTimer()
_onConfigDirty: () ->
if @_state isnt 'initializing'
@_dirty = true
@_setState 'build:required'
@_toggleFooterButtons()
_onConfigLoaded: () ->
@_deferreds.config.resolve()
network = @_listeners.config.vagrant.get 'network'
Backbone.trigger 'application:ready'
Backbone.trigger 'docker:config', network.get 'ip'
Backbone.trigger 'vagrant:status'
_onImagesChange: (collection) ->
if @_state is 'initializing'
@_deferreds.images.resolve()
_onInitialized: ->
@_setState 'initialized'
if not @_listeners.config.containers.configured()
$('a[href="#containers"]').click()
Backbone.trigger 'render:ui'
Backbone.trigger 'modal:status:hide'
_onVagrantChange: (model) ->
switch @_state
when 'initializing'
switch model.get 'state'
when 'running'
@_deferreds.vagrant.resolve()
Backbone.trigger 'docker:status'
else
@_deferreds.containers.resolve()
@_deferreds.images.resolve()
@_deferreds.vagrant.resolve()
when 'vagrant:starting'
Backbone.trigger 'modal:status:hideLogs'
Backbone.trigger 'modal:status:step'
Backbone.trigger 'docker:start'
when 'vagrant:updating'
@_setState 'updated'
Backbone.trigger 'modal:status:hide'
when 'vagrant:stopping'
@_setState 'stopped'
Backbone.trigger 'docker:reset'
Backbone.trigger 'modal:status:hide'
@_toggleFooterButtons()
_setState: (state) ->
if state isnt @_state
@_state = state
Backbone.trigger 'application:state', @_state
_startRefreshTimer: ->
if not @_refreshTimer?
@_refreshTimer = setInterval () =>
Backbone.trigger 'vagrant:status', () =>
if @_vagrantRunning()
Backbone.trigger 'docker:status'
, 15000
_stopRefreshTimer: ->
if @_refreshTimer?
clearInterval @_refreshTimer
@_refreshTimer = null
_toggleFooterButtons: ->
build = @_state is 'build:required'
outdated = @vagrant.get 'outdated'
power = @_state isnt 'build:required'
isUp = @_vagrantRunning()
Backbone.trigger 'footer:buttons:toggle', build, outdated, power, isUp
_vagrantDestroy: ->
@_setState 'vagrant:stopping'
Backbone.trigger 'modal:status:show', 'stopping', false, true, true
Backbone.trigger 'vagrant:halt'
_vagrantRunning: ->
@vagrant.get('state') is 'running'
_vagrantUp: ->
containers = @config.get('containers')
containerCount = containers.byStartOrder().length
steps = 4 + @vagrantSteps.length + containerCount
Backbone.trigger 'modal:status:steps', steps
Backbone.trigger 'modal:status:show', 'starting', true, true, true
Backbone.trigger 'cloud-config:build'
State
| 8576 | define (require, exports, module) ->
$ = require 'jquery'
Backbone = require 'backbone'
Listener = require 'listener'
environment = require 'cs!utils/environment'
ipc = require 'cs!utils/ipc'
# Coordinate UI actions based upon state requirements
#
class State extends Listener
events:
'application:status': 'onApplicationStatus'
'auth:password': 'onAuthPassword'
'cloud-config:built': 'onCloudConfigBuilt'
'docker:started': 'onDockerStarted'
'docker:container:request:start': 'onDockerStartRequest'
'docker:container:request:stop': 'onDockerStopRequest'
'docker:containers:updated': 'onDockerContainers'
'environment:build:request': 'onBuildRequest'
'environment:build:complete': 'onBuildComplete'
'error': 'onError'
'timers:pause': 'pauseTimer'
'timers:resume': 'startTimer'
'vagrant:log': 'onVagrantLog'
'vagrant:request:halt': 'onVagrantHalt'
'vagrant:request:update': 'onVagrantUpdate'
'vagrant:request:up': 'onVagrantUp'
'vagrant:up:error': 'onVagrantUpError'
vagrantSteps: [
'Bringing machine'
'Importing base box'
'Machine booted and ready!'
'Configuring and enabling network'
'Exporting NFS shared folders'
'Mounting NFS shared folders'
'Running provisioner: file'
'Running provisioner: shell'
]
_dirty: false
_refreshTimer: null
_singleAction: null
_state: null
initialize: ->
@_setState 'initializing'
@_deferreds =
config: $.Deferred()
containers: $.Deferred()
images: $.Deferred()
vagrant: $.Deferred()
$.when(@_deferreds.config.promise(),
@_deferreds.containers.promise(),
@_deferreds.images.promise(),
@_deferreds.vagrant.promise()).done () =>
@_onInitialized()
@_listeners =
build: arguments[0].build
config: arguments[0].config
docker: arguments[0].docker
vagrant: arguments[0].vagrant
@config = @_listeners.config.model
@containers = @_listeners.docker.containers
@images = @_listeners.docker.images
@vagrant = @_listeners.vagrant.model
@listenTo @_listeners.build, 'dirty', () =>
@_onBuildEvent()
@listenToOnce @_listeners.config, 'loaded', () =>
@_onConfigLoaded()
@listenTo @_listeners.config, 'dirty', (model) =>
if @_state isnt 'initializing'
@_onConfigDirty()
@listenTo @_listeners.config, 'saved', (model) =>
@_setState 'saved'
@_dirty = false
@_toggleFooterButtons()
Backbone.trigger 'modal:status:hide'
@listenTo @_listeners.docker, 'images:change', (collection) =>
@_onImagesChange(collection)
@listenTo @_listeners.vagrant, 'change', (model) =>
@_onVagrantChange(model)
onApplicationStatus: (status, args...) =>
switch status
when 'container:started'
if @_singleAction is true
@_singleAction = null
Backbone.trigger 'modal:status:hide'
when 'container:stopped'
if @_singleAction is true
@_singleAction = null
Backbone.trigger 'modal:status:hide'
onAuthPassword: (value) =>
if @_vagrantRunning() is true
@_vagrantDestroy()
else
@_vagrantUp()
onBuildComplete: ->
Backbone.trigger 'configuration:save'
onBuildRequest: =>
@_setState 'build:start'
Backbone.trigger 'modal:status:show', 'build:start', true, true
Backbone.trigger 'environment:build'
onCloudConfigBuilt: =>
Backbone.trigger 'modal:status:step'
@_setState 'vagrant:starting'
Backbone.trigger 'vagrant:up'
onDockerContainers: =>
if @_state is 'initializing'
@_deferreds.containers.resolve()
onDockerStartRequest: (name) =>
@_singleAction = true
@_stopRefreshTimer()
Backbone.trigger 'modal:status:show', 'docker:start', false, true
Backbone.trigger 'docker:container:start', name
onDockerStopRequest: (name) =>
@_singleAction = true
Backbone.trigger 'modal:status:show', 'docker:stop', false, true
Backbone.trigger 'docker:container:stop', name
onDockerStarted: =>
@_setState 'running'
@_startRefreshTimer()
@_toggleFooterButtons()
Backbone.trigger 'modal:status:hide'
onError: (reason) =>
switch reason
when 'image:create'
if @_singleAction
@single_action = null
Backbone.trigger 'modal:status:hide'
onVagrantHalt: =>
@_stopRefreshTimer()
# If the password is set, assume it's corrent and start the build
if @config.get('password')?
@_vagrantDestroy()
else
# Dont show dialog if sudo has cached authentication creds
ipc.send 'password:validate', 'null', (result) =>
if result
@_vagrantDestroy()
else
Backbone.trigger 'modal:dialog:auth:show'
onVagrantLog: (message) =>
for step in @vagrantSteps
if message.indexOf(step) > -1
Backbone.trigger 'modal:status:step'
break
onVagrantUp: =>
@_stopRefreshTimer()
# If the password is set, assume it's corrent and start the build
if @config.get('password')?
@_vagrantUp()
else
# Dont show dialog if sudo has cached authentication creds
ipc.send 'password:<PASSWORD>', 'null', (result) =>
if result
@_vagrantUp()
else
Backbone.trigger 'modal:dialog:auth:show'
onVagrantUpdate: =>
@_stopRefreshTimer()
@_setState 'vagrant:updating'
Backbone.trigger 'modal:status:show', 'updating', false, true, true
Backbone.trigger 'vagrant:box:update'
onVagrantUpError: =>
@_setState 'vagrant:error'
@_toggleFooterButtons()
Backbone.trigger 'modal:status:hide'
Backbone.trigger 'error', 'vagrant:start'
pauseTimer: () ->
@_stopRefreshTimer()
resumeTimer: () ->
@_startRefreshTimer()
_onConfigDirty: () ->
if @_state isnt 'initializing'
@_dirty = true
@_setState 'build:required'
@_toggleFooterButtons()
_onConfigLoaded: () ->
@_deferreds.config.resolve()
network = @_listeners.config.vagrant.get 'network'
Backbone.trigger 'application:ready'
Backbone.trigger 'docker:config', network.get 'ip'
Backbone.trigger 'vagrant:status'
_onImagesChange: (collection) ->
if @_state is 'initializing'
@_deferreds.images.resolve()
_onInitialized: ->
@_setState 'initialized'
if not @_listeners.config.containers.configured()
$('a[href="#containers"]').click()
Backbone.trigger 'render:ui'
Backbone.trigger 'modal:status:hide'
_onVagrantChange: (model) ->
switch @_state
when 'initializing'
switch model.get 'state'
when 'running'
@_deferreds.vagrant.resolve()
Backbone.trigger 'docker:status'
else
@_deferreds.containers.resolve()
@_deferreds.images.resolve()
@_deferreds.vagrant.resolve()
when 'vagrant:starting'
Backbone.trigger 'modal:status:hideLogs'
Backbone.trigger 'modal:status:step'
Backbone.trigger 'docker:start'
when 'vagrant:updating'
@_setState 'updated'
Backbone.trigger 'modal:status:hide'
when 'vagrant:stopping'
@_setState 'stopped'
Backbone.trigger 'docker:reset'
Backbone.trigger 'modal:status:hide'
@_toggleFooterButtons()
_setState: (state) ->
if state isnt @_state
@_state = state
Backbone.trigger 'application:state', @_state
_startRefreshTimer: ->
if not @_refreshTimer?
@_refreshTimer = setInterval () =>
Backbone.trigger 'vagrant:status', () =>
if @_vagrantRunning()
Backbone.trigger 'docker:status'
, 15000
_stopRefreshTimer: ->
if @_refreshTimer?
clearInterval @_refreshTimer
@_refreshTimer = null
_toggleFooterButtons: ->
build = @_state is 'build:required'
outdated = @vagrant.get 'outdated'
power = @_state isnt 'build:required'
isUp = @_vagrantRunning()
Backbone.trigger 'footer:buttons:toggle', build, outdated, power, isUp
_vagrantDestroy: ->
@_setState 'vagrant:stopping'
Backbone.trigger 'modal:status:show', 'stopping', false, true, true
Backbone.trigger 'vagrant:halt'
_vagrantRunning: ->
@vagrant.get('state') is 'running'
_vagrantUp: ->
containers = @config.get('containers')
containerCount = containers.byStartOrder().length
steps = 4 + @vagrantSteps.length + containerCount
Backbone.trigger 'modal:status:steps', steps
Backbone.trigger 'modal:status:show', 'starting', true, true, true
Backbone.trigger 'cloud-config:build'
State
| true | define (require, exports, module) ->
$ = require 'jquery'
Backbone = require 'backbone'
Listener = require 'listener'
environment = require 'cs!utils/environment'
ipc = require 'cs!utils/ipc'
# Coordinate UI actions based upon state requirements
#
class State extends Listener
events:
'application:status': 'onApplicationStatus'
'auth:password': 'onAuthPassword'
'cloud-config:built': 'onCloudConfigBuilt'
'docker:started': 'onDockerStarted'
'docker:container:request:start': 'onDockerStartRequest'
'docker:container:request:stop': 'onDockerStopRequest'
'docker:containers:updated': 'onDockerContainers'
'environment:build:request': 'onBuildRequest'
'environment:build:complete': 'onBuildComplete'
'error': 'onError'
'timers:pause': 'pauseTimer'
'timers:resume': 'startTimer'
'vagrant:log': 'onVagrantLog'
'vagrant:request:halt': 'onVagrantHalt'
'vagrant:request:update': 'onVagrantUpdate'
'vagrant:request:up': 'onVagrantUp'
'vagrant:up:error': 'onVagrantUpError'
vagrantSteps: [
'Bringing machine'
'Importing base box'
'Machine booted and ready!'
'Configuring and enabling network'
'Exporting NFS shared folders'
'Mounting NFS shared folders'
'Running provisioner: file'
'Running provisioner: shell'
]
_dirty: false
_refreshTimer: null
_singleAction: null
_state: null
initialize: ->
@_setState 'initializing'
@_deferreds =
config: $.Deferred()
containers: $.Deferred()
images: $.Deferred()
vagrant: $.Deferred()
$.when(@_deferreds.config.promise(),
@_deferreds.containers.promise(),
@_deferreds.images.promise(),
@_deferreds.vagrant.promise()).done () =>
@_onInitialized()
@_listeners =
build: arguments[0].build
config: arguments[0].config
docker: arguments[0].docker
vagrant: arguments[0].vagrant
@config = @_listeners.config.model
@containers = @_listeners.docker.containers
@images = @_listeners.docker.images
@vagrant = @_listeners.vagrant.model
@listenTo @_listeners.build, 'dirty', () =>
@_onBuildEvent()
@listenToOnce @_listeners.config, 'loaded', () =>
@_onConfigLoaded()
@listenTo @_listeners.config, 'dirty', (model) =>
if @_state isnt 'initializing'
@_onConfigDirty()
@listenTo @_listeners.config, 'saved', (model) =>
@_setState 'saved'
@_dirty = false
@_toggleFooterButtons()
Backbone.trigger 'modal:status:hide'
@listenTo @_listeners.docker, 'images:change', (collection) =>
@_onImagesChange(collection)
@listenTo @_listeners.vagrant, 'change', (model) =>
@_onVagrantChange(model)
onApplicationStatus: (status, args...) =>
switch status
when 'container:started'
if @_singleAction is true
@_singleAction = null
Backbone.trigger 'modal:status:hide'
when 'container:stopped'
if @_singleAction is true
@_singleAction = null
Backbone.trigger 'modal:status:hide'
onAuthPassword: (value) =>
if @_vagrantRunning() is true
@_vagrantDestroy()
else
@_vagrantUp()
onBuildComplete: ->
Backbone.trigger 'configuration:save'
onBuildRequest: =>
@_setState 'build:start'
Backbone.trigger 'modal:status:show', 'build:start', true, true
Backbone.trigger 'environment:build'
onCloudConfigBuilt: =>
Backbone.trigger 'modal:status:step'
@_setState 'vagrant:starting'
Backbone.trigger 'vagrant:up'
onDockerContainers: =>
if @_state is 'initializing'
@_deferreds.containers.resolve()
onDockerStartRequest: (name) =>
@_singleAction = true
@_stopRefreshTimer()
Backbone.trigger 'modal:status:show', 'docker:start', false, true
Backbone.trigger 'docker:container:start', name
onDockerStopRequest: (name) =>
@_singleAction = true
Backbone.trigger 'modal:status:show', 'docker:stop', false, true
Backbone.trigger 'docker:container:stop', name
onDockerStarted: =>
@_setState 'running'
@_startRefreshTimer()
@_toggleFooterButtons()
Backbone.trigger 'modal:status:hide'
onError: (reason) =>
switch reason
when 'image:create'
if @_singleAction
@single_action = null
Backbone.trigger 'modal:status:hide'
onVagrantHalt: =>
@_stopRefreshTimer()
# If the password is set, assume it's corrent and start the build
if @config.get('password')?
@_vagrantDestroy()
else
# Dont show dialog if sudo has cached authentication creds
ipc.send 'password:validate', 'null', (result) =>
if result
@_vagrantDestroy()
else
Backbone.trigger 'modal:dialog:auth:show'
onVagrantLog: (message) =>
for step in @vagrantSteps
if message.indexOf(step) > -1
Backbone.trigger 'modal:status:step'
break
onVagrantUp: =>
@_stopRefreshTimer()
# If the password is set, assume it's corrent and start the build
if @config.get('password')?
@_vagrantUp()
else
# Dont show dialog if sudo has cached authentication creds
ipc.send 'password:PI:PASSWORD:<PASSWORD>END_PI', 'null', (result) =>
if result
@_vagrantUp()
else
Backbone.trigger 'modal:dialog:auth:show'
onVagrantUpdate: =>
@_stopRefreshTimer()
@_setState 'vagrant:updating'
Backbone.trigger 'modal:status:show', 'updating', false, true, true
Backbone.trigger 'vagrant:box:update'
onVagrantUpError: =>
@_setState 'vagrant:error'
@_toggleFooterButtons()
Backbone.trigger 'modal:status:hide'
Backbone.trigger 'error', 'vagrant:start'
pauseTimer: () ->
@_stopRefreshTimer()
resumeTimer: () ->
@_startRefreshTimer()
_onConfigDirty: () ->
if @_state isnt 'initializing'
@_dirty = true
@_setState 'build:required'
@_toggleFooterButtons()
_onConfigLoaded: () ->
@_deferreds.config.resolve()
network = @_listeners.config.vagrant.get 'network'
Backbone.trigger 'application:ready'
Backbone.trigger 'docker:config', network.get 'ip'
Backbone.trigger 'vagrant:status'
_onImagesChange: (collection) ->
if @_state is 'initializing'
@_deferreds.images.resolve()
_onInitialized: ->
@_setState 'initialized'
if not @_listeners.config.containers.configured()
$('a[href="#containers"]').click()
Backbone.trigger 'render:ui'
Backbone.trigger 'modal:status:hide'
_onVagrantChange: (model) ->
switch @_state
when 'initializing'
switch model.get 'state'
when 'running'
@_deferreds.vagrant.resolve()
Backbone.trigger 'docker:status'
else
@_deferreds.containers.resolve()
@_deferreds.images.resolve()
@_deferreds.vagrant.resolve()
when 'vagrant:starting'
Backbone.trigger 'modal:status:hideLogs'
Backbone.trigger 'modal:status:step'
Backbone.trigger 'docker:start'
when 'vagrant:updating'
@_setState 'updated'
Backbone.trigger 'modal:status:hide'
when 'vagrant:stopping'
@_setState 'stopped'
Backbone.trigger 'docker:reset'
Backbone.trigger 'modal:status:hide'
@_toggleFooterButtons()
_setState: (state) ->
if state isnt @_state
@_state = state
Backbone.trigger 'application:state', @_state
_startRefreshTimer: ->
if not @_refreshTimer?
@_refreshTimer = setInterval () =>
Backbone.trigger 'vagrant:status', () =>
if @_vagrantRunning()
Backbone.trigger 'docker:status'
, 15000
_stopRefreshTimer: ->
if @_refreshTimer?
clearInterval @_refreshTimer
@_refreshTimer = null
_toggleFooterButtons: ->
build = @_state is 'build:required'
outdated = @vagrant.get 'outdated'
power = @_state isnt 'build:required'
isUp = @_vagrantRunning()
Backbone.trigger 'footer:buttons:toggle', build, outdated, power, isUp
_vagrantDestroy: ->
@_setState 'vagrant:stopping'
Backbone.trigger 'modal:status:show', 'stopping', false, true, true
Backbone.trigger 'vagrant:halt'
_vagrantRunning: ->
@vagrant.get('state') is 'running'
_vagrantUp: ->
containers = @config.get('containers')
containerCount = containers.byStartOrder().length
steps = 4 + @vagrantSteps.length + containerCount
Backbone.trigger 'modal:status:steps', steps
Backbone.trigger 'modal:status:show', 'starting', true, true, true
Backbone.trigger 'cloud-config:build'
State
|
[
{
"context": " rich text editing jQuery UI widget\n# (c) 2011 Henri Bergius, IKS Consortium\n# Hallo may be freely distrib",
"end": 79,
"score": 0.9998458027839661,
"start": 66,
"tag": "NAME",
"value": "Henri Bergius"
}
] | src/client/hallo/hallo/plugins/toolbarlinebreak.coffee | HansPinckaers/ShareJS-editor | 4 | # Hallo - a rich text editing jQuery UI widget
# (c) 2011 Henri Bergius, IKS Consortium
# Hallo may be freely distributed under the MIT license
#
# ------------------------------------------------------
#
# Hallo linebreak plugin
# (c) 2011 Liip AG, Switzerland
# This plugin may be freely distributed under the MIT license.
#
# The linebreak plugin allows linebreaks between editor buttons by
# wrapping each row in a div.
# It requires that all widgets have an id consisting of the uuid and
# the name for the surrounding element
# (<span id=\"#{@options.uuid}-" + widget.widgetName + "\">)
#
# The only option is 'breakAfter', which should be an array of
# widgetnames after which a linebreak should be inserted
# Make sure to add this option _after_ all the plugins that output
# toolbar icons when passing in the hallo options!
((jQuery) ->
jQuery.widget "Liip.hallotoolbarlinebreak",
options:
editable: null
toolbar: null
uuid: ""
breakAfter: [] # array of widgetnames after which a linebreak should occur
_create: ->
buttonsets = jQuery('.ui-buttonset', @options.toolbar)
queuedButtonsets = jQuery()
rowcounter = 0
for row in @options.breakAfter
rowcounter++
for buttonset in buttonsets
queuedButtonsets = jQuery(queuedButtonsets).add(jQuery(buttonset))
if jQuery(buttonset).hasClass row
queuedButtonsets.wrapAll('<div class="halloButtonrow halloButtonrow-' + rowcounter + '" />')
buttonsets = buttonsets.not(queuedButtonsets)
queuedButtonsets = jQuery()
break
if buttonsets.length > 0
rowcounter++
buttonsets.wrapAll('<div class="halloButtonrow halloButtonrow-' + rowcounter + '" />')
_init: ->
)(jQuery)
| 79451 | # Hallo - a rich text editing jQuery UI widget
# (c) 2011 <NAME>, IKS Consortium
# Hallo may be freely distributed under the MIT license
#
# ------------------------------------------------------
#
# Hallo linebreak plugin
# (c) 2011 Liip AG, Switzerland
# This plugin may be freely distributed under the MIT license.
#
# The linebreak plugin allows linebreaks between editor buttons by
# wrapping each row in a div.
# It requires that all widgets have an id consisting of the uuid and
# the name for the surrounding element
# (<span id=\"#{@options.uuid}-" + widget.widgetName + "\">)
#
# The only option is 'breakAfter', which should be an array of
# widgetnames after which a linebreak should be inserted
# Make sure to add this option _after_ all the plugins that output
# toolbar icons when passing in the hallo options!
((jQuery) ->
jQuery.widget "Liip.hallotoolbarlinebreak",
options:
editable: null
toolbar: null
uuid: ""
breakAfter: [] # array of widgetnames after which a linebreak should occur
_create: ->
buttonsets = jQuery('.ui-buttonset', @options.toolbar)
queuedButtonsets = jQuery()
rowcounter = 0
for row in @options.breakAfter
rowcounter++
for buttonset in buttonsets
queuedButtonsets = jQuery(queuedButtonsets).add(jQuery(buttonset))
if jQuery(buttonset).hasClass row
queuedButtonsets.wrapAll('<div class="halloButtonrow halloButtonrow-' + rowcounter + '" />')
buttonsets = buttonsets.not(queuedButtonsets)
queuedButtonsets = jQuery()
break
if buttonsets.length > 0
rowcounter++
buttonsets.wrapAll('<div class="halloButtonrow halloButtonrow-' + rowcounter + '" />')
_init: ->
)(jQuery)
| true | # Hallo - a rich text editing jQuery UI widget
# (c) 2011 PI:NAME:<NAME>END_PI, IKS Consortium
# Hallo may be freely distributed under the MIT license
#
# ------------------------------------------------------
#
# Hallo linebreak plugin
# (c) 2011 Liip AG, Switzerland
# This plugin may be freely distributed under the MIT license.
#
# The linebreak plugin allows linebreaks between editor buttons by
# wrapping each row in a div.
# It requires that all widgets have an id consisting of the uuid and
# the name for the surrounding element
# (<span id=\"#{@options.uuid}-" + widget.widgetName + "\">)
#
# The only option is 'breakAfter', which should be an array of
# widgetnames after which a linebreak should be inserted
# Make sure to add this option _after_ all the plugins that output
# toolbar icons when passing in the hallo options!
((jQuery) ->
jQuery.widget "Liip.hallotoolbarlinebreak",
options:
editable: null
toolbar: null
uuid: ""
breakAfter: [] # array of widgetnames after which a linebreak should occur
_create: ->
buttonsets = jQuery('.ui-buttonset', @options.toolbar)
queuedButtonsets = jQuery()
rowcounter = 0
for row in @options.breakAfter
rowcounter++
for buttonset in buttonsets
queuedButtonsets = jQuery(queuedButtonsets).add(jQuery(buttonset))
if jQuery(buttonset).hasClass row
queuedButtonsets.wrapAll('<div class="halloButtonrow halloButtonrow-' + rowcounter + '" />')
buttonsets = buttonsets.not(queuedButtonsets)
queuedButtonsets = jQuery()
break
if buttonsets.length > 0
rowcounter++
buttonsets.wrapAll('<div class="halloButtonrow halloButtonrow-' + rowcounter + '" />')
_init: ->
)(jQuery)
|
[
{
"context": "when\nusing a data provider, for example).\n\n@author Roelof Roos (https://github.com/roelofr)\n###\n\nJUnitNode = req",
"end": 136,
"score": 0.9998941421508789,
"start": 125,
"tag": "NAME",
"value": "Roelof Roos"
},
{
"context": "xample).\n\n@author Roelof Roos (https:... | lib/models/junit-test.coffee | roelofr/php-report | 0 | ###
Contains a test, can be either a single test or a test with subcases (when
using a data provider, for example).
@author Roelof Roos (https://github.com/roelofr)
###
JUnitNode = require './junit-node'
module.exports =
class Test extends JUnitNode
class: null
line: null
tests: null
multiple: false
msg:
fail: null
error: null
constructor: (node) ->
super node
# Get proper name (method) and class
if node.attr 'class'
@class = node.attr('class').value()
else if (commaPos = @name.indexOf '::') != -1
@class = @name.substr 0, commaPos
@name = @name.substr commaPos + 2
# Test suites contain subtests, which we should flag
@multiple = node.name() == 'testsuite'
if @multiple
@multiple = true
tests = []
for test in node.find 'testcase'
tests.push(new Test test)
@tests = tests
# Get failure and error, if any
@msg.fail = node.get('failure')?.text()
@msg.error = node.get('error')?.text()
isMultiple: ->
return Boolean(@multiple)
getTests: ->
return @tests
getClass: ->
return @class
getFailureMessage: ->
return @msg.fail
getErrorMessage: ->
return @msg.error
| 224539 | ###
Contains a test, can be either a single test or a test with subcases (when
using a data provider, for example).
@author <NAME> (https://github.com/roelofr)
###
JUnitNode = require './junit-node'
module.exports =
class Test extends JUnitNode
class: null
line: null
tests: null
multiple: false
msg:
fail: null
error: null
constructor: (node) ->
super node
# Get proper name (method) and class
if node.attr 'class'
@class = node.attr('class').value()
else if (commaPos = @name.indexOf '::') != -1
@class = @name.substr 0, commaPos
@name = @name.substr commaPos + 2
# Test suites contain subtests, which we should flag
@multiple = node.name() == 'testsuite'
if @multiple
@multiple = true
tests = []
for test in node.find 'testcase'
tests.push(new Test test)
@tests = tests
# Get failure and error, if any
@msg.fail = node.get('failure')?.text()
@msg.error = node.get('error')?.text()
isMultiple: ->
return Boolean(@multiple)
getTests: ->
return @tests
getClass: ->
return @class
getFailureMessage: ->
return @msg.fail
getErrorMessage: ->
return @msg.error
| true | ###
Contains a test, can be either a single test or a test with subcases (when
using a data provider, for example).
@author PI:NAME:<NAME>END_PI (https://github.com/roelofr)
###
JUnitNode = require './junit-node'
module.exports =
class Test extends JUnitNode
class: null
line: null
tests: null
multiple: false
msg:
fail: null
error: null
constructor: (node) ->
super node
# Get proper name (method) and class
if node.attr 'class'
@class = node.attr('class').value()
else if (commaPos = @name.indexOf '::') != -1
@class = @name.substr 0, commaPos
@name = @name.substr commaPos + 2
# Test suites contain subtests, which we should flag
@multiple = node.name() == 'testsuite'
if @multiple
@multiple = true
tests = []
for test in node.find 'testcase'
tests.push(new Test test)
@tests = tests
# Get failure and error, if any
@msg.fail = node.get('failure')?.text()
@msg.error = node.get('error')?.text()
isMultiple: ->
return Boolean(@multiple)
getTests: ->
return @tests
getClass: ->
return @class
getFailureMessage: ->
return @msg.fail
getErrorMessage: ->
return @msg.error
|
[
{
"context": "me, socket\n socket.username = data.username\n socket.password = data.password\n ",
"end": 4528,
"score": 0.5258456468582153,
"start": 4520,
"tag": "USERNAME",
"value": "username"
},
{
"context": " = data.username\n socket.pa... | v0.7/server.coffee | KingSann/TinyChat | 1 | express = require "express"
app = express()
http = require("http").Server app
io = require("socket.io") http
fs = require "fs"
md5 = require "md5"
readline = require "readline"
tcdb = require "./tcdb.js"
moment = require "moment"
moment.locale "zh-cn"
# 读取时间
gettime = -> moment().format "YYYY-MM-DD HH:mm:ss"
# 数据库配置
db = tcdb.make()
db_name = "db_tc"
# 名单类,用于处理名单
class Roll
_roll: {}
constructor: (@_roll = {}) ->
insert: (key, val) ->
if not @_roll[key] then @_roll[key] = val else undefined
erase: (key) ->
delete @_roll[key]
get: (key) ->
@_roll[key]
exist: (key, val) ->
@_roll[key] and @_roll[key] is val
# 储物类,用于处理存储
class Cache
_cache: []
constructor: (@_cache = []) ->
insert: (data) ->
@_cache.push data
erase: (data) ->
@_cache = (dt for dt in @_cache when dt isnt data)
exist: (data) ->
data in @_cache
# 用户类,用于存储用户信息以及sockets
class User
@sockets = {}
# 插入一个用户连接
@insert = (name, socket) ->
@sockets[name].insert socket
# 删除一个用户连接
@erase = (name, socket) ->
@sockets[name].erase socket
socket?.disconnect?()
@roll = new Roll()
# 注册一个用户
@register = (name, password) ->
# database => 插入一个用户
db.insert tcdb.mkline "password", password, "user", name
@roll.insert name, password
@sockets[name] ?= new Cache()
# 注销一个用户
@unregister = (name) ->
# database => 删除一个用户
# 还未支持将房间记录中的用户删除
db_remove (tcdb.mkline name, 0, "user"), -> true
sck?.disconnect?() for sck in @sockets[name]._cache if @sockets[name]
@roll.erase name
# 判断一个用户存在性
@exist = (name, password) ->
@roll.exist name, password
# 房间类,用于存储房间信息以及sockets
class Room
@sockets = {}
@roll = new Roll()
# 注册一个房间
@register = (name, password) ->
# database => 插入一个房间
db.insert tcdb.mkline "roompass", password, "room", name
db.insert tcdb.mkline "id_cnt", 0, "room", name, "message"
@roll.insert name, password
@sockets[name] = new Cache()
# 注销一个房间
@unregister = (name) ->
# database => 删除一个房间
db_remove (tcdb.mkline name, 0, "room"), -> true
@roll.erase name
@send name,
"sys message",
time: gettime(),
msg: "房间 #{name} 已被注销",
sck?.isjoin = false for sck in @sockets[name]._cache
delete @sockets[name]
# 判断一个房间存在性
@exist = (name, password) ->
@roll.exist name, password
# 加入一个用户
@join = (name, socket) ->
# database => 查询 返回未读消息
lastseeid = (db.select (tcdb.mkline "lastseeid", 0, "room", name, "joined", socket.username), -> true)[0].lastseeid || 0
res = []
tmp = (db.select (tcdb.mkline "message", 0, "room", name), -> true)[0].message
for key of tmp
if key isnt "id_cnt" && lastseeid <= parseInt(key[3 ..]) + 20 # 返回未读消息+最近20条
tmp2 = {}
tmp2[key] = tmp[key]
res.push tmp2
for obj in res
cc = ""
for key of obj then cc = key
socket.emit "new message",
username: obj[cc].sender,
time: obj[cc].time,
msg: obj[cc].text,
# database => 更新
curid = (db.select (tcdb.mkline "id_cnt", 0, "room", name, "message"), -> true)[0].id_cnt
db.update (tcdb.mkline "lastseeid", 0, "room", name, "joined", socket.username), (lastseeid) -> lastseeid || curid
@sockets[name].insert socket
@send name,
"sys message",
time: gettime(),
msg: "#{socket.username} 加入房间",
# 离开一个用户
@leave = (name, socket) ->
socket.isjoin = false
@sockets[name].erase socket
@send name,
"sys message",
time: gettime(),
msg: "#{socket.username} 离开房间",
# 全体发送消息
@send = (name, ent, data) ->
sck?.emit? ent, data for sck in @sockets[name]._cache
io.on "connection", (socket) ->
# 用户登录
socket.on "login", (data) ->
time = gettime()
if not socket.islogin
if User.exist data.username, data.password
User.insert data.username, socket
socket.username = data.username
socket.password = data.password
socket.islogin = true
socket.emit "login suc"
else
socket.emit "err", time: time, msg: "登录失败",
else
socket.emit "err", time: time, msg: "已经登录",
# 用户加入房间
socket.on "join", (data) ->
time = gettime()
if socket.islogin
if Room.exist data.roomname, data.roompass
socket.emit "join suc"
Room.join data.roomname, socket
socket.roomname = data.roomname
socket.roompass = data.roompass
socket.isjoin = true
else
socket.emit "err", time: time, msg: "加入房间失败",
else
socket.emit "err", time: time, msg: "请先登录",
# 用户发言
socket.on "message", (data) ->
dt = data.msg # 数据
time = gettime() # 时间
if socket.islogin
if socket.isjoin
if "#{dt}" isnt ""
# database => 添加 新消息
curid = (db.update (tcdb.mkline "id_cnt", 0, "room", socket.roomname, "message"), (id) -> id + 1)[0]
db.update (tcdb.mkline "id_#{curid}", 0, "room", socket.roomname, "message"), (lastseeid) ->
sender: socket.username,
time: time,
text: "#{dt}",
# database => 更新 用户lastseeid
db.update (tcdb.mkline "lastseeid", 0, "room", socket.roomname, "joined", socket.username), (lastseeid) -> curid
Room.send socket.roomname,
"new message",
username: socket.username,
time: time,
msg: "#{dt}"
else
socket.emit "err", time: time, msg: "输入不能为空",
else
socket.emit "err", time: time, msg: "请先加入房间",
else
socket.emit "err", time: time, msg: "请先登录",
# 用户断线(离开房间、登出)
socket.on "disconnect", ->
if socket.islogin
Room.leave socket.roomname, socket if socket.isjoin
User.erase socket.username, socket
exit = ->
db.close()
process.exit 0
### 初始化 ###
try
db.connect db_name
readline.createInterface input: fs.createReadStream "config.txt"
.on "line", (line) ->
[type, name, password] = line.split(" ")
if type is "user"
User.register name, password
else if type is "room"
Room.register name, password
.on "close", () ->
readline.createInterface input: process.stdin
.on "line", (line) ->
try
console.log eval line
catch e
console.log e
app.use "/", express.static "#{__dirname}/TinyChat"
http.listen 8080, -> console.log "listening on port 8080"
# http.listen 2333, -> console.log "listening on port 2333"
catch e
console.log "初始化是产生错误: " + e | 34172 | express = require "express"
app = express()
http = require("http").Server app
io = require("socket.io") http
fs = require "fs"
md5 = require "md5"
readline = require "readline"
tcdb = require "./tcdb.js"
moment = require "moment"
moment.locale "zh-cn"
# 读取时间
gettime = -> moment().format "YYYY-MM-DD HH:mm:ss"
# 数据库配置
db = tcdb.make()
db_name = "db_tc"
# 名单类,用于处理名单
class Roll
_roll: {}
constructor: (@_roll = {}) ->
insert: (key, val) ->
if not @_roll[key] then @_roll[key] = val else undefined
erase: (key) ->
delete @_roll[key]
get: (key) ->
@_roll[key]
exist: (key, val) ->
@_roll[key] and @_roll[key] is val
# 储物类,用于处理存储
class Cache
_cache: []
constructor: (@_cache = []) ->
insert: (data) ->
@_cache.push data
erase: (data) ->
@_cache = (dt for dt in @_cache when dt isnt data)
exist: (data) ->
data in @_cache
# 用户类,用于存储用户信息以及sockets
class User
@sockets = {}
# 插入一个用户连接
@insert = (name, socket) ->
@sockets[name].insert socket
# 删除一个用户连接
@erase = (name, socket) ->
@sockets[name].erase socket
socket?.disconnect?()
@roll = new Roll()
# 注册一个用户
@register = (name, password) ->
# database => 插入一个用户
db.insert tcdb.mkline "password", password, "user", name
@roll.insert name, password
@sockets[name] ?= new Cache()
# 注销一个用户
@unregister = (name) ->
# database => 删除一个用户
# 还未支持将房间记录中的用户删除
db_remove (tcdb.mkline name, 0, "user"), -> true
sck?.disconnect?() for sck in @sockets[name]._cache if @sockets[name]
@roll.erase name
# 判断一个用户存在性
@exist = (name, password) ->
@roll.exist name, password
# 房间类,用于存储房间信息以及sockets
class Room
@sockets = {}
@roll = new Roll()
# 注册一个房间
@register = (name, password) ->
# database => 插入一个房间
db.insert tcdb.mkline "roompass", password, "room", name
db.insert tcdb.mkline "id_cnt", 0, "room", name, "message"
@roll.insert name, password
@sockets[name] = new Cache()
# 注销一个房间
@unregister = (name) ->
# database => 删除一个房间
db_remove (tcdb.mkline name, 0, "room"), -> true
@roll.erase name
@send name,
"sys message",
time: gettime(),
msg: "房间 #{name} 已被注销",
sck?.isjoin = false for sck in @sockets[name]._cache
delete @sockets[name]
# 判断一个房间存在性
@exist = (name, password) ->
@roll.exist name, password
# 加入一个用户
@join = (name, socket) ->
# database => 查询 返回未读消息
lastseeid = (db.select (tcdb.mkline "lastseeid", 0, "room", name, "joined", socket.username), -> true)[0].lastseeid || 0
res = []
tmp = (db.select (tcdb.mkline "message", 0, "room", name), -> true)[0].message
for key of tmp
if key isnt "id_cnt" && lastseeid <= parseInt(key[3 ..]) + 20 # 返回未读消息+最近20条
tmp2 = {}
tmp2[key] = tmp[key]
res.push tmp2
for obj in res
cc = ""
for key of obj then cc = key
socket.emit "new message",
username: obj[cc].sender,
time: obj[cc].time,
msg: obj[cc].text,
# database => 更新
curid = (db.select (tcdb.mkline "id_cnt", 0, "room", name, "message"), -> true)[0].id_cnt
db.update (tcdb.mkline "lastseeid", 0, "room", name, "joined", socket.username), (lastseeid) -> lastseeid || curid
@sockets[name].insert socket
@send name,
"sys message",
time: gettime(),
msg: "#{socket.username} 加入房间",
# 离开一个用户
@leave = (name, socket) ->
socket.isjoin = false
@sockets[name].erase socket
@send name,
"sys message",
time: gettime(),
msg: "#{socket.username} 离开房间",
# 全体发送消息
@send = (name, ent, data) ->
sck?.emit? ent, data for sck in @sockets[name]._cache
io.on "connection", (socket) ->
# 用户登录
socket.on "login", (data) ->
time = gettime()
if not socket.islogin
if User.exist data.username, data.password
User.insert data.username, socket
socket.username = data.username
socket.password = <PASSWORD>
socket.islogin = true
socket.emit "login suc"
else
socket.emit "err", time: time, msg: "登录失败",
else
socket.emit "err", time: time, msg: "已经登录",
# 用户加入房间
socket.on "join", (data) ->
time = gettime()
if socket.islogin
if Room.exist data.roomname, data.roompass
socket.emit "join suc"
Room.join data.roomname, socket
socket.roomname = data.roomname
socket.roompass = data.roompass
socket.isjoin = true
else
socket.emit "err", time: time, msg: "加入房间失败",
else
socket.emit "err", time: time, msg: "请先登录",
# 用户发言
socket.on "message", (data) ->
dt = data.msg # 数据
time = gettime() # 时间
if socket.islogin
if socket.isjoin
if "#{dt}" isnt ""
# database => 添加 新消息
curid = (db.update (tcdb.mkline "id_cnt", 0, "room", socket.roomname, "message"), (id) -> id + 1)[0]
db.update (tcdb.mkline "id_#{curid}", 0, "room", socket.roomname, "message"), (lastseeid) ->
sender: socket.username,
time: time,
text: "#{dt}",
# database => 更新 用户lastseeid
db.update (tcdb.mkline "lastseeid", 0, "room", socket.roomname, "joined", socket.username), (lastseeid) -> curid
Room.send socket.roomname,
"new message",
username: socket.username,
time: time,
msg: "#{dt}"
else
socket.emit "err", time: time, msg: "输入不能为空",
else
socket.emit "err", time: time, msg: "请先加入房间",
else
socket.emit "err", time: time, msg: "请先登录",
# 用户断线(离开房间、登出)
socket.on "disconnect", ->
if socket.islogin
Room.leave socket.roomname, socket if socket.isjoin
User.erase socket.username, socket
exit = ->
db.close()
process.exit 0
### 初始化 ###
try
db.connect db_name
readline.createInterface input: fs.createReadStream "config.txt"
.on "line", (line) ->
[type, name, password] = line.split(" ")
if type is "user"
User.register name, password
else if type is "room"
Room.register name, password
.on "close", () ->
readline.createInterface input: process.stdin
.on "line", (line) ->
try
console.log eval line
catch e
console.log e
app.use "/", express.static "#{__dirname}/TinyChat"
http.listen 8080, -> console.log "listening on port 8080"
# http.listen 2333, -> console.log "listening on port 2333"
catch e
console.log "初始化是产生错误: " + e | true | express = require "express"
app = express()
http = require("http").Server app
io = require("socket.io") http
fs = require "fs"
md5 = require "md5"
readline = require "readline"
tcdb = require "./tcdb.js"
moment = require "moment"
moment.locale "zh-cn"
# 读取时间
gettime = -> moment().format "YYYY-MM-DD HH:mm:ss"
# 数据库配置
db = tcdb.make()
db_name = "db_tc"
# 名单类,用于处理名单
class Roll
_roll: {}
constructor: (@_roll = {}) ->
insert: (key, val) ->
if not @_roll[key] then @_roll[key] = val else undefined
erase: (key) ->
delete @_roll[key]
get: (key) ->
@_roll[key]
exist: (key, val) ->
@_roll[key] and @_roll[key] is val
# 储物类,用于处理存储
class Cache
_cache: []
constructor: (@_cache = []) ->
insert: (data) ->
@_cache.push data
erase: (data) ->
@_cache = (dt for dt in @_cache when dt isnt data)
exist: (data) ->
data in @_cache
# 用户类,用于存储用户信息以及sockets
class User
@sockets = {}
# 插入一个用户连接
@insert = (name, socket) ->
@sockets[name].insert socket
# 删除一个用户连接
@erase = (name, socket) ->
@sockets[name].erase socket
socket?.disconnect?()
@roll = new Roll()
# 注册一个用户
@register = (name, password) ->
# database => 插入一个用户
db.insert tcdb.mkline "password", password, "user", name
@roll.insert name, password
@sockets[name] ?= new Cache()
# 注销一个用户
@unregister = (name) ->
# database => 删除一个用户
# 还未支持将房间记录中的用户删除
db_remove (tcdb.mkline name, 0, "user"), -> true
sck?.disconnect?() for sck in @sockets[name]._cache if @sockets[name]
@roll.erase name
# 判断一个用户存在性
@exist = (name, password) ->
@roll.exist name, password
# 房间类,用于存储房间信息以及sockets
class Room
@sockets = {}
@roll = new Roll()
# 注册一个房间
@register = (name, password) ->
# database => 插入一个房间
db.insert tcdb.mkline "roompass", password, "room", name
db.insert tcdb.mkline "id_cnt", 0, "room", name, "message"
@roll.insert name, password
@sockets[name] = new Cache()
# 注销一个房间
@unregister = (name) ->
# database => 删除一个房间
db_remove (tcdb.mkline name, 0, "room"), -> true
@roll.erase name
@send name,
"sys message",
time: gettime(),
msg: "房间 #{name} 已被注销",
sck?.isjoin = false for sck in @sockets[name]._cache
delete @sockets[name]
# 判断一个房间存在性
@exist = (name, password) ->
@roll.exist name, password
# 加入一个用户
@join = (name, socket) ->
# database => 查询 返回未读消息
lastseeid = (db.select (tcdb.mkline "lastseeid", 0, "room", name, "joined", socket.username), -> true)[0].lastseeid || 0
res = []
tmp = (db.select (tcdb.mkline "message", 0, "room", name), -> true)[0].message
for key of tmp
if key isnt "id_cnt" && lastseeid <= parseInt(key[3 ..]) + 20 # 返回未读消息+最近20条
tmp2 = {}
tmp2[key] = tmp[key]
res.push tmp2
for obj in res
cc = ""
for key of obj then cc = key
socket.emit "new message",
username: obj[cc].sender,
time: obj[cc].time,
msg: obj[cc].text,
# database => 更新
curid = (db.select (tcdb.mkline "id_cnt", 0, "room", name, "message"), -> true)[0].id_cnt
db.update (tcdb.mkline "lastseeid", 0, "room", name, "joined", socket.username), (lastseeid) -> lastseeid || curid
@sockets[name].insert socket
@send name,
"sys message",
time: gettime(),
msg: "#{socket.username} 加入房间",
# 离开一个用户
@leave = (name, socket) ->
socket.isjoin = false
@sockets[name].erase socket
@send name,
"sys message",
time: gettime(),
msg: "#{socket.username} 离开房间",
# 全体发送消息
@send = (name, ent, data) ->
sck?.emit? ent, data for sck in @sockets[name]._cache
io.on "connection", (socket) ->
# 用户登录
socket.on "login", (data) ->
time = gettime()
if not socket.islogin
if User.exist data.username, data.password
User.insert data.username, socket
socket.username = data.username
socket.password = PI:PASSWORD:<PASSWORD>END_PI
socket.islogin = true
socket.emit "login suc"
else
socket.emit "err", time: time, msg: "登录失败",
else
socket.emit "err", time: time, msg: "已经登录",
# 用户加入房间
socket.on "join", (data) ->
time = gettime()
if socket.islogin
if Room.exist data.roomname, data.roompass
socket.emit "join suc"
Room.join data.roomname, socket
socket.roomname = data.roomname
socket.roompass = data.roompass
socket.isjoin = true
else
socket.emit "err", time: time, msg: "加入房间失败",
else
socket.emit "err", time: time, msg: "请先登录",
# 用户发言
socket.on "message", (data) ->
dt = data.msg # 数据
time = gettime() # 时间
if socket.islogin
if socket.isjoin
if "#{dt}" isnt ""
# database => 添加 新消息
curid = (db.update (tcdb.mkline "id_cnt", 0, "room", socket.roomname, "message"), (id) -> id + 1)[0]
db.update (tcdb.mkline "id_#{curid}", 0, "room", socket.roomname, "message"), (lastseeid) ->
sender: socket.username,
time: time,
text: "#{dt}",
# database => 更新 用户lastseeid
db.update (tcdb.mkline "lastseeid", 0, "room", socket.roomname, "joined", socket.username), (lastseeid) -> curid
Room.send socket.roomname,
"new message",
username: socket.username,
time: time,
msg: "#{dt}"
else
socket.emit "err", time: time, msg: "输入不能为空",
else
socket.emit "err", time: time, msg: "请先加入房间",
else
socket.emit "err", time: time, msg: "请先登录",
# 用户断线(离开房间、登出)
socket.on "disconnect", ->
if socket.islogin
Room.leave socket.roomname, socket if socket.isjoin
User.erase socket.username, socket
exit = ->
db.close()
process.exit 0
### 初始化 ###
try
db.connect db_name
readline.createInterface input: fs.createReadStream "config.txt"
.on "line", (line) ->
[type, name, password] = line.split(" ")
if type is "user"
User.register name, password
else if type is "room"
Room.register name, password
.on "close", () ->
readline.createInterface input: process.stdin
.on "line", (line) ->
try
console.log eval line
catch e
console.log e
app.use "/", express.static "#{__dirname}/TinyChat"
http.listen 8080, -> console.log "listening on port 8080"
# http.listen 2333, -> console.log "listening on port 2333"
catch e
console.log "初始化是产生错误: " + e |
[
{
"context": "h.random()*6) # type de syllogisme\n [A,B,C] = [\"machin\",\"truc\",\"chose\"] # les catégories socioprofessio",
"end": 130,
"score": 0.9922347664833069,
"start": 124,
"tag": "NAME",
"value": "machin"
},
{
"context": ")*6) # type de syllogisme\n [A,B,C] = [\"machin... | js/logic6.coffee | AlainBusser/LogicGame | 1 | # A: prémisse
# B : intermédiaire
# C : conclusion
type = Math.floor(Math.random()*6) # type de syllogisme
[A,B,C] = ["machin","truc","chose"] # les catégories socioprofessionnelles
trad = ["non-",""]
[s1,s2,s3,s4] = ["Tout","est","Tout","est"]
############################## fabrication des syllogismes et de leurs solutions ##########
faireQCM = ->
$(".sA").text " #{A} "
$(".sB").text " #{B} "
$(".sC").text " #{C} "
$(".sxB").text " #{B} "
$(".sxC").text " #{C} "
resoudreSyll()
resoudreSyll = ->
solution = "On ne peut pas conclure"
if s1 is "Tout"
if s2 is "est"
if s3 is "Tout"
if s4 is "est"
$(".sxB").text " #{B} "
$(".sxC").text " #{C} "
solution = "Tout #{A} est #{C}"
else
solution = "Le deuxième verbe n'est pas bon"
else
if s3 is "Aucun" and s4 is "n'est"
$(".sxB").text " #{C} "
$(".sxC").text " #{B} "
solution = "Aucun #{A}s n'est #{C}"
else
solution = "Le premier verbe n'est pas bon"
if s1 is "Quelque"
if s2 is "est"
if s3 is "Tout"
if s4 is "est"
$(".sxB").text " #{B} "
$(".sxC").text " #{C} "
solution = "Quelque #{A} est #{C}"
else
solution = "Le deuxième verbe n'est pas bon"
else
if s3 is "Aucun" and s4 is "n'est"
$(".sxB").text " #{C} "
$(".sxC").text " #{B} "
solution = "Quelque #{C} n'est pas #{A}"
else
solution = "Le premier verbe n'est pas bon"
if s3 is "Tout"
if s4 is "est"
if s1 is "Aucun"
if s2 is "n'est"
$(".sxB").text " #{C} "
$(".sxC").text " #{B} "
solution = "Aucun #{A} n'est #{C}"
else
solution = "Le premier verbe n'est pas bon"
else
if s1 is "Quelque" and s2 is "n'est pas"
$(".sxB").text " #{C} "
$(".sxC").text " #{B} "
solution = "Quelque #{A} n'est pas #{C}"
else
solution = "Le deuxième verbe n'est pas bon"
solution += "."
$("#sorsyl").text solution
######################### maintenant qu'on a un DOM on peut y aller #######################
$ ->
faireQCM()
# pour qu'on puisse bouger les jetons
$('.jeton').draggable
snap: false
# entrée d'un texte (catégorie)
$("#eA").on "change", ->
A = $("#eA").val()
faireQCM()
$("#eB").on "change", ->
B = $("#eB").val()
faireQCM()
$("#eC").on "change", ->
C = $("#eC").val()
faireQCM()
# gestion des jetons: Des cas ambigüs subsistent, pas grave
$('.cellule').droppable
accept: ".jeton"
tolerance: "intersect"
drop: (event,ui) ->
diagnostic = $(this).attr("id").split("prem")[1]
diagnostic = diagnostic.split("conc")
debut = parseInt diagnostic[0]
diagnostic = diagnostic[1].split("mid")
milieu = parseInt diagnostic[1]
fin = parseInt diagnostic[0]
if ui.draggable.hasClass 'gris'
if debut>1 or fin>1
textsortie = "N'auriez-vous pas plutôt dû utiliser un jeton rouge ?"
else
if milieu is 1
textsortie = "Vous venez de coder le fait qu'aucun #{trad[debut]}#{A} #{trad[fin]}#{C} n'est #{B}"
else
textsortie = "Vous venez de coder le fait que tous les #{trad[debut]}#{A}s #{trad[fin]}#{C}s sont #{B}s"
else
if debut<=1 and fin<=1
textsortie = "N'auriez-vous pas plutôt dû utiliser un jeton gris ?"
else
if debut>1
textsortie = "Vous venez de coder le fait que quelques #{trad[fin]}#{C}s ne sont pas des #{B}s"
else
textsortie = "Vous venez de coder le fait que quelques #{trad[debut]}#{A}s ne sont pas des #{B}s"
$('#sortie').text textsortie
true
# calculateur de syllogismes par disjonction des cas
$('#choixA').selectmenu
change: (event,data)->
s1 = data.item.value
resoudreSyll()
$('#verbe1').selectmenu
change: (event,data)->
s2 = data.item.value
resoudreSyll()
$('#choixB').selectmenu
change: (event,data)->
s3 = data.item.value
resoudreSyll()
$('#verbe2').selectmenu
change: (event,data)->
s4 = data.item.value
resoudreSyll()
| 152042 | # A: prémisse
# B : intermédiaire
# C : conclusion
type = Math.floor(Math.random()*6) # type de syllogisme
[A,B,C] = ["<NAME>","<NAME>","<NAME>"] # les catégories socioprofessionnelles
trad = ["non-",""]
[s1,s2,s3,s4] = ["Tout","est","Tout","est"]
############################## fabrication des syllogismes et de leurs solutions ##########
faireQCM = ->
$(".sA").text " #{A} "
$(".sB").text " #{B} "
$(".sC").text " #{C} "
$(".sxB").text " #{B} "
$(".sxC").text " #{C} "
resoudreSyll()
resoudreSyll = ->
solution = "On ne peut pas conclure"
if s1 is "Tout"
if s2 is "est"
if s3 is "Tout"
if s4 is "est"
$(".sxB").text " #{B} "
$(".sxC").text " #{C} "
solution = "Tout #{A} est #{C}"
else
solution = "Le deuxième verbe n'est pas bon"
else
if s3 is "Aucun" and s4 is "n'est"
$(".sxB").text " #{C} "
$(".sxC").text " #{B} "
solution = "Aucun #{A}s n'est #{C}"
else
solution = "Le premier verbe n'est pas bon"
if s1 is "Quelque"
if s2 is "est"
if s3 is "Tout"
if s4 is "est"
$(".sxB").text " #{B} "
$(".sxC").text " #{C} "
solution = "Quelque #{A} est #{C}"
else
solution = "Le deuxième verbe n'est pas bon"
else
if s3 is "Aucun" and s4 is "n'est"
$(".sxB").text " #{C} "
$(".sxC").text " #{B} "
solution = "Quelque #{C} n'est pas #{A}"
else
solution = "Le premier verbe n'est pas bon"
if s3 is "Tout"
if s4 is "est"
if s1 is "Aucun"
if s2 is "n'est"
$(".sxB").text " #{C} "
$(".sxC").text " #{B} "
solution = "Aucun #{A} n'est #{C}"
else
solution = "Le premier verbe n'est pas bon"
else
if s1 is "Quelque" and s2 is "n'est pas"
$(".sxB").text " #{C} "
$(".sxC").text " #{B} "
solution = "Quelque #{A} n'est pas #{C}"
else
solution = "Le deuxième verbe n'est pas bon"
solution += "."
$("#sorsyl").text solution
######################### maintenant qu'on a un DOM on peut y aller #######################
$ ->
faireQCM()
# pour qu'on puisse bouger les jetons
$('.jeton').draggable
snap: false
# entrée d'un texte (catégorie)
$("#eA").on "change", ->
A = $("#eA").val()
faireQCM()
$("#eB").on "change", ->
B = $("#eB").val()
faireQCM()
$("#eC").on "change", ->
C = $("#eC").val()
faireQCM()
# gestion des jetons: Des cas ambigüs subsistent, pas grave
$('.cellule').droppable
accept: ".jeton"
tolerance: "intersect"
drop: (event,ui) ->
diagnostic = $(this).attr("id").split("prem")[1]
diagnostic = diagnostic.split("conc")
debut = parseInt diagnostic[0]
diagnostic = diagnostic[1].split("mid")
milieu = parseInt diagnostic[1]
fin = parseInt diagnostic[0]
if ui.draggable.hasClass 'gris'
if debut>1 or fin>1
textsortie = "N'auriez-vous pas plutôt dû utiliser un jeton rouge ?"
else
if milieu is 1
textsortie = "Vous venez de coder le fait qu'aucun #{trad[debut]}#{A} #{trad[fin]}#{C} n'est #{B}"
else
textsortie = "Vous venez de coder le fait que tous les #{trad[debut]}#{A}s #{trad[fin]}#{C}s sont #{B}s"
else
if debut<=1 and fin<=1
textsortie = "N'auriez-vous pas plutôt dû utiliser un jeton gris ?"
else
if debut>1
textsortie = "Vous venez de coder le fait que quelques #{trad[fin]}#{C}s ne sont pas des #{B}s"
else
textsortie = "Vous venez de coder le fait que quelques #{trad[debut]}#{A}s ne sont pas des #{B}s"
$('#sortie').text textsortie
true
# calculateur de syllogismes par disjonction des cas
$('#choixA').selectmenu
change: (event,data)->
s1 = data.item.value
resoudreSyll()
$('#verbe1').selectmenu
change: (event,data)->
s2 = data.item.value
resoudreSyll()
$('#choixB').selectmenu
change: (event,data)->
s3 = data.item.value
resoudreSyll()
$('#verbe2').selectmenu
change: (event,data)->
s4 = data.item.value
resoudreSyll()
| true | # A: prémisse
# B : intermédiaire
# C : conclusion
type = Math.floor(Math.random()*6) # type de syllogisme
[A,B,C] = ["PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI"] # les catégories socioprofessionnelles
trad = ["non-",""]
[s1,s2,s3,s4] = ["Tout","est","Tout","est"]
############################## fabrication des syllogismes et de leurs solutions ##########
faireQCM = ->
$(".sA").text " #{A} "
$(".sB").text " #{B} "
$(".sC").text " #{C} "
$(".sxB").text " #{B} "
$(".sxC").text " #{C} "
resoudreSyll()
resoudreSyll = ->
solution = "On ne peut pas conclure"
if s1 is "Tout"
if s2 is "est"
if s3 is "Tout"
if s4 is "est"
$(".sxB").text " #{B} "
$(".sxC").text " #{C} "
solution = "Tout #{A} est #{C}"
else
solution = "Le deuxième verbe n'est pas bon"
else
if s3 is "Aucun" and s4 is "n'est"
$(".sxB").text " #{C} "
$(".sxC").text " #{B} "
solution = "Aucun #{A}s n'est #{C}"
else
solution = "Le premier verbe n'est pas bon"
if s1 is "Quelque"
if s2 is "est"
if s3 is "Tout"
if s4 is "est"
$(".sxB").text " #{B} "
$(".sxC").text " #{C} "
solution = "Quelque #{A} est #{C}"
else
solution = "Le deuxième verbe n'est pas bon"
else
if s3 is "Aucun" and s4 is "n'est"
$(".sxB").text " #{C} "
$(".sxC").text " #{B} "
solution = "Quelque #{C} n'est pas #{A}"
else
solution = "Le premier verbe n'est pas bon"
if s3 is "Tout"
if s4 is "est"
if s1 is "Aucun"
if s2 is "n'est"
$(".sxB").text " #{C} "
$(".sxC").text " #{B} "
solution = "Aucun #{A} n'est #{C}"
else
solution = "Le premier verbe n'est pas bon"
else
if s1 is "Quelque" and s2 is "n'est pas"
$(".sxB").text " #{C} "
$(".sxC").text " #{B} "
solution = "Quelque #{A} n'est pas #{C}"
else
solution = "Le deuxième verbe n'est pas bon"
solution += "."
$("#sorsyl").text solution
######################### maintenant qu'on a un DOM on peut y aller #######################
$ ->
faireQCM()
# pour qu'on puisse bouger les jetons
$('.jeton').draggable
snap: false
# entrée d'un texte (catégorie)
$("#eA").on "change", ->
A = $("#eA").val()
faireQCM()
$("#eB").on "change", ->
B = $("#eB").val()
faireQCM()
$("#eC").on "change", ->
C = $("#eC").val()
faireQCM()
# gestion des jetons: Des cas ambigüs subsistent, pas grave
$('.cellule').droppable
accept: ".jeton"
tolerance: "intersect"
drop: (event,ui) ->
diagnostic = $(this).attr("id").split("prem")[1]
diagnostic = diagnostic.split("conc")
debut = parseInt diagnostic[0]
diagnostic = diagnostic[1].split("mid")
milieu = parseInt diagnostic[1]
fin = parseInt diagnostic[0]
if ui.draggable.hasClass 'gris'
if debut>1 or fin>1
textsortie = "N'auriez-vous pas plutôt dû utiliser un jeton rouge ?"
else
if milieu is 1
textsortie = "Vous venez de coder le fait qu'aucun #{trad[debut]}#{A} #{trad[fin]}#{C} n'est #{B}"
else
textsortie = "Vous venez de coder le fait que tous les #{trad[debut]}#{A}s #{trad[fin]}#{C}s sont #{B}s"
else
if debut<=1 and fin<=1
textsortie = "N'auriez-vous pas plutôt dû utiliser un jeton gris ?"
else
if debut>1
textsortie = "Vous venez de coder le fait que quelques #{trad[fin]}#{C}s ne sont pas des #{B}s"
else
textsortie = "Vous venez de coder le fait que quelques #{trad[debut]}#{A}s ne sont pas des #{B}s"
$('#sortie').text textsortie
true
# calculateur de syllogismes par disjonction des cas
$('#choixA').selectmenu
change: (event,data)->
s1 = data.item.value
resoudreSyll()
$('#verbe1').selectmenu
change: (event,data)->
s2 = data.item.value
resoudreSyll()
$('#choixB').selectmenu
change: (event,data)->
s3 = data.item.value
resoudreSyll()
$('#verbe2').selectmenu
change: (event,data)->
s4 = data.item.value
resoudreSyll()
|
[
{
"context": "OG_LEVEL='error'\n process.env.UNTAPPD_API_KEY='foobar1'\n process.env.UNTAPPD_API_SECRET='foobar2'\n ",
"end": 471,
"score": 0.9968811869621277,
"start": 464,
"tag": "KEY",
"value": "foobar1"
},
{
"context": "KEY='foobar1'\n process.env.UNTAPPD_API_SECRET='f... | test/untappd-friends-slack_test.coffee | stephenyeargin/hubot-untappd | 5 | Helper = require('hubot-test-helper')
chai = require 'chai'
nock = require 'nock'
expect = chai.expect
helper = new Helper [
'adapters/slack.coffee',
'../src/untappd-friends.coffee'
]
# Alter time as test runs
originalDateNow = Date.now
mockDateNow = () ->
return Date.parse('Tue Mar 30 2018 14:10:00 GMT-0500 (CDT)')
describe 'hubot-untappd-friends for slack', ->
beforeEach ->
process.env.HUBOT_LOG_LEVEL='error'
process.env.UNTAPPD_API_KEY='foobar1'
process.env.UNTAPPD_API_SECRET='foobar2'
process.env.UNTAPPD_API_ACCESS_TOKEN='foobar3'
process.env.UNTAPPD_MAX_COUNT=2
Date.now = mockDateNow
nock.disableNetConnect()
@room = helper.createRoom()
afterEach ->
delete process.env.HUBOT_LOG_LEVEL
delete process.env.UNTAPPD_API_KEY
delete process.env.UNTAPPD_API_SECRET
delete process.env.UNTAPPD_API_ACCESS_TOKEN
delete process.env.UNTAPPD_MAX_COUNT
Date.now = originalDateNow
nock.cleanAll()
@room.destroy()
# hubot untappd
it 'responds with the latest activity from your friends', (done) ->
nock('https://api.untappd.com')
.get('/v4/checkin/recent')
.query(
limit: 2,
access_token: 'foobar3',
)
.replyWithFile(200, __dirname + '/fixtures/checkin-recent.json')
selfRoom = @room
selfRoom.user.say('alice', '@hubot untappd')
setTimeout(() ->
try
expect(selfRoom.messages).to.eql [
['alice', '@hubot untappd']
[
'hubot',
{
"attachments": [
{
"author_name": "an hour ago at 49 Çukurcuma",
"color": "#7CD197",
"fallback": "heath (heathseals) was drinking Blonde Ale (Blonde Ale - 5%) by Gara Guzu Brewery at 49 Çukurcuma - an hour ago",
"footer": "Earned the Beer Foodie (Level 44) badge and 2 more",
"footer_icon": "https://untappd.akamaized.net/badges/bdg_BeerFoodie_sm.jpg",
"thumb_url": "https://untappd.akamaized.net/site/beer_logos/beer-764911_07c43_sm.jpeg",
"title": "heath (heathseals) was drinking Blonde Ale by Gara Guzu Brewery",
"title_link": "https://untappd.com/user/heathseals/checkin/578981788"
},
{
"author_name": "8 hours ago at DERALIYE OTTOMAN CUISINE",
"color": "#7CD197",
"fallback": "heath (heathseals) was drinking Efes Pilsen (Pilsner - Other - 5%) by Anadolu Efes at DERALIYE OTTOMAN CUISINE - 8 hours ago",
"footer": "Earned the Beer Connoisseur (Level 8) badge",
"footer_icon": "https://untappd.akamaized.net/badges/bdg_connoiseur_sm.jpg",
"thumb_url": "https://untappd.akamaized.net/site/beer_logos/beer-EfesPilsener_17259.jpeg",
"title": "heath (heathseals) was drinking Efes Pilsen by Anadolu Efes",
"title_link": "https://untappd.com/user/heathseals/checkin/578869664"
}
],
"unfurl_links": false
}
]
]
done()
catch err
done err
return
, 1000)
# hubot untappd badges
it 'responds with the latest badge activity from your friends', (done) ->
nock('https://api.untappd.com')
.get('/v4/checkin/recent')
.query(
limit: 2,
access_token: 'foobar3',
)
.replyWithFile(200, __dirname + '/fixtures/checkin-recent.json')
selfRoom = @room
selfRoom.user.say('alice', '@hubot untappd badges')
setTimeout(() ->
try
expect(selfRoom.messages).to.eql [
['alice', '@hubot untappd badges']
[
'hubot',
{
"attachments": [
{
"author_name": "an hour ago at 49 Çukurcuma",
"color": "#7CD197",
"fallback": "heath (heathseals) earned the Beer Foodie (Level 44) Badge after drinking a Blonde Ale at 49 Çukurcuma - an hour ago",
"footer": "Blonde Ale",
"footer_icon": "https://untappd.akamaized.net/site/beer_logos/beer-764911_07c43_sm.jpeg",
"thumb_url": "https://untappd.akamaized.net/badges/bdg_BeerFoodie_sm.jpg",
"title": "heath (heathseals) earned the Beer Foodie (Level 44) Badge",
"title_link": "https://untappd.com/user/heathseals/checkin/578981788"
},
{
"author_name": "an hour ago at 49 Çukurcuma",
"color": "#7CD197",
"fallback": "heath (heathseals) earned the 99 Bottles (Level 38) Badge after drinking a Blonde Ale at 49 Çukurcuma - an hour ago",
"footer": "Blonde Ale",
"footer_icon": "https://untappd.akamaized.net/site/beer_logos/beer-764911_07c43_sm.jpeg",
"thumb_url": "https://untappd.akamaized.net/badges/bdg_99Bottles_sm.jpg",
"title": "heath (heathseals) earned the 99 Bottles (Level 38) Badge",
"title_link": "https://untappd.com/user/heathseals/checkin/578981788"
},
{
"author_name": "an hour ago at 49 Çukurcuma",
"color": "#7CD197",
"fallback": "heath (heathseals) earned the Pizza & Brew (Level 4) Badge after drinking a Blonde Ale at 49 Çukurcuma - an hour ago",
"footer": "Blonde Ale",
"footer_icon": "https://untappd.akamaized.net/site/beer_logos/beer-764911_07c43_sm.jpeg",
"thumb_url": "https://untappd.akamaized.net/badges/bdg_PizzaAndBrew_sm.jpg",
"title": "heath (heathseals) earned the Pizza & Brew (Level 4) Badge",
"title_link": "https://untappd.com/user/heathseals/checkin/578981788"
},
{
"author_name": "8 hours ago at DERALIYE OTTOMAN CUISINE",
"color": "#7CD197",
"fallback": "heath (heathseals) earned the Beer Connoisseur (Level 8) Badge after drinking a Efes Pilsen at DERALIYE OTTOMAN CUISINE - 8 hours ago",
"footer": "Efes Pilsen",
"footer_icon": "https://untappd.akamaized.net/site/beer_logos/beer-EfesPilsener_17259.jpeg",
"thumb_url": "https://untappd.akamaized.net/badges/bdg_connoiseur_sm.jpg",
"title": "heath (heathseals) earned the Beer Connoisseur (Level 8) Badge",
"title_link": "https://untappd.com/user/heathseals/checkin/578869664"
}
],
"unfurl_links": false
}
]
]
done()
catch err
done err
return
, 1000)
| 6144 | Helper = require('hubot-test-helper')
chai = require 'chai'
nock = require 'nock'
expect = chai.expect
helper = new Helper [
'adapters/slack.coffee',
'../src/untappd-friends.coffee'
]
# Alter time as test runs
originalDateNow = Date.now
mockDateNow = () ->
return Date.parse('Tue Mar 30 2018 14:10:00 GMT-0500 (CDT)')
describe 'hubot-untappd-friends for slack', ->
beforeEach ->
process.env.HUBOT_LOG_LEVEL='error'
process.env.UNTAPPD_API_KEY='<KEY>'
process.env.UNTAPPD_API_SECRET='<KEY>'
process.env.UNTAPPD_API_ACCESS_TOKEN='<KEY>'
process.env.UNTAPPD_MAX_COUNT=2
Date.now = mockDateNow
nock.disableNetConnect()
@room = helper.createRoom()
afterEach ->
delete process.env.HUBOT_LOG_LEVEL
delete process.env.UNTAPPD_API_KEY
delete process.env.UNTAPPD_API_SECRET
delete process.env.UNTAPPD_API_ACCESS_TOKEN
delete process.env.UNTAPPD_MAX_COUNT
Date.now = originalDateNow
nock.cleanAll()
@room.destroy()
# hubot untappd
it 'responds with the latest activity from your friends', (done) ->
nock('https://api.untappd.com')
.get('/v4/checkin/recent')
.query(
limit: 2,
access_token: '<KEY>',
)
.replyWithFile(200, __dirname + '/fixtures/checkin-recent.json')
selfRoom = @room
selfRoom.user.say('alice', '@hubot untappd')
setTimeout(() ->
try
expect(selfRoom.messages).to.eql [
['alice', '@hubot untappd']
[
'hubot',
{
"attachments": [
{
"author_name": "an hour ago at 49 Çukurcuma",
"color": "#7CD197",
"fallback": "heath (heathseals) was drinking Blonde Ale (Blonde Ale - 5%) by Gara Guzu Brewery at 49 Çukurcuma - an hour ago",
"footer": "Earned the Beer Foodie (Level 44) badge and 2 more",
"footer_icon": "https://untappd.akamaized.net/badges/bdg_BeerFoodie_sm.jpg",
"thumb_url": "https://untappd.akamaized.net/site/beer_logos/beer-764911_07c43_sm.jpeg",
"title": "heath (heathseals) was drinking Blonde Ale by Gara Guzu Brewery",
"title_link": "https://untappd.com/user/heathseals/checkin/578981788"
},
{
"author_name": "8 hours ago at DERALIYE OTTOMAN CUISINE",
"color": "#7CD197",
"fallback": "heath (heathseals) was drinking Efes Pilsen (Pilsner - Other - 5%) by <NAME> at DERALIYE OTTOMAN CUISINE - 8 hours ago",
"footer": "Earned the Beer Connoisseur (Level 8) badge",
"footer_icon": "https://untappd.akamaized.net/badges/bdg_connoiseur_sm.jpg",
"thumb_url": "https://untappd.akamaized.net/site/beer_logos/beer-EfesPilsener_17259.jpeg",
"title": "heath (heathseals) was drinking Efes Pilsen by <NAME>",
"title_link": "https://untappd.com/user/heathseals/checkin/578869664"
}
],
"unfurl_links": false
}
]
]
done()
catch err
done err
return
, 1000)
# hubot untappd badges
it 'responds with the latest badge activity from your friends', (done) ->
nock('https://api.untappd.com')
.get('/v4/checkin/recent')
.query(
limit: 2,
access_token: '<KEY>',
)
.replyWithFile(200, __dirname + '/fixtures/checkin-recent.json')
selfRoom = @room
selfRoom.user.say('alice', '@hubot untappd badges')
setTimeout(() ->
try
expect(selfRoom.messages).to.eql [
['alice', '@hubot untappd badges']
[
'hubot',
{
"attachments": [
{
"author_name": "an hour ago at 49 Çukurcuma",
"color": "#7CD197",
"fallback": "heath (heathseals) earned the Beer Foodie (Level 44) Badge after drinking a Blonde Ale at 49 Çukurcuma - an hour ago",
"footer": "Blonde Ale",
"footer_icon": "https://untappd.akamaized.net/site/beer_logos/beer-764911_07c43_sm.jpeg",
"thumb_url": "https://untappd.akamaized.net/badges/bdg_BeerFoodie_sm.jpg",
"title": "heath (heathseals) earned the Beer Foodie (Level 44) Badge",
"title_link": "https://untappd.com/user/heathseals/checkin/578981788"
},
{
"author_name": "an hour ago at 49 Çukurcuma",
"color": "#7CD197",
"fallback": "heath (heathseals) earned the 99 Bottles (Level 38) Badge after drinking a Blonde Ale at 49 Çukurcuma - an hour ago",
"footer": "Blonde Ale",
"footer_icon": "https://untappd.akamaized.net/site/beer_logos/beer-764911_07c43_sm.jpeg",
"thumb_url": "https://untappd.akamaized.net/badges/bdg_99Bottles_sm.jpg",
"title": "heath (heathseals) earned the 99 Bottles (Level 38) Badge",
"title_link": "https://untappd.com/user/heathseals/checkin/578981788"
},
{
"author_name": "an hour ago at 49 Çukurcuma",
"color": "#7CD197",
"fallback": "heath (heathseals) earned the Pizza & Brew (Level 4) Badge after drinking a Blonde Ale at 49 Çukurcuma - an hour ago",
"footer": "Blonde Ale",
"footer_icon": "https://untappd.akamaized.net/site/beer_logos/beer-764911_07c43_sm.jpeg",
"thumb_url": "https://untappd.akamaized.net/badges/bdg_PizzaAndBrew_sm.jpg",
"title": "heath (heathseals) earned the Pizza & Brew (Level 4) Badge",
"title_link": "https://untappd.com/user/heathseals/checkin/578981788"
},
{
"author_name": "8 hours ago at DERALIYE OTTOMAN CUISINE",
"color": "#7CD197",
"fallback": "heath (heathseals) earned the Beer Connoisseur (Level 8) Badge after drinking a Efes Pilsen at DERALIYE OTTOMAN CUISINE - 8 hours ago",
"footer": "<NAME> Pilsen",
"footer_icon": "https://untappd.akamaized.net/site/beer_logos/beer-EfesPilsener_17259.jpeg",
"thumb_url": "https://untappd.akamaized.net/badges/bdg_connoiseur_sm.jpg",
"title": "heath (heathseals) earned the Beer Connoisseur (Level 8) Badge",
"title_link": "https://untappd.com/user/heathseals/checkin/578869664"
}
],
"unfurl_links": false
}
]
]
done()
catch err
done err
return
, 1000)
| true | Helper = require('hubot-test-helper')
chai = require 'chai'
nock = require 'nock'
expect = chai.expect
helper = new Helper [
'adapters/slack.coffee',
'../src/untappd-friends.coffee'
]
# Alter time as test runs
originalDateNow = Date.now
mockDateNow = () ->
return Date.parse('Tue Mar 30 2018 14:10:00 GMT-0500 (CDT)')
describe 'hubot-untappd-friends for slack', ->
beforeEach ->
process.env.HUBOT_LOG_LEVEL='error'
process.env.UNTAPPD_API_KEY='PI:KEY:<KEY>END_PI'
process.env.UNTAPPD_API_SECRET='PI:KEY:<KEY>END_PI'
process.env.UNTAPPD_API_ACCESS_TOKEN='PI:KEY:<KEY>END_PI'
process.env.UNTAPPD_MAX_COUNT=2
Date.now = mockDateNow
nock.disableNetConnect()
@room = helper.createRoom()
afterEach ->
delete process.env.HUBOT_LOG_LEVEL
delete process.env.UNTAPPD_API_KEY
delete process.env.UNTAPPD_API_SECRET
delete process.env.UNTAPPD_API_ACCESS_TOKEN
delete process.env.UNTAPPD_MAX_COUNT
Date.now = originalDateNow
nock.cleanAll()
@room.destroy()
# hubot untappd
it 'responds with the latest activity from your friends', (done) ->
nock('https://api.untappd.com')
.get('/v4/checkin/recent')
.query(
limit: 2,
access_token: 'PI:KEY:<KEY>END_PI',
)
.replyWithFile(200, __dirname + '/fixtures/checkin-recent.json')
selfRoom = @room
selfRoom.user.say('alice', '@hubot untappd')
setTimeout(() ->
try
expect(selfRoom.messages).to.eql [
['alice', '@hubot untappd']
[
'hubot',
{
"attachments": [
{
"author_name": "an hour ago at 49 Çukurcuma",
"color": "#7CD197",
"fallback": "heath (heathseals) was drinking Blonde Ale (Blonde Ale - 5%) by Gara Guzu Brewery at 49 Çukurcuma - an hour ago",
"footer": "Earned the Beer Foodie (Level 44) badge and 2 more",
"footer_icon": "https://untappd.akamaized.net/badges/bdg_BeerFoodie_sm.jpg",
"thumb_url": "https://untappd.akamaized.net/site/beer_logos/beer-764911_07c43_sm.jpeg",
"title": "heath (heathseals) was drinking Blonde Ale by Gara Guzu Brewery",
"title_link": "https://untappd.com/user/heathseals/checkin/578981788"
},
{
"author_name": "8 hours ago at DERALIYE OTTOMAN CUISINE",
"color": "#7CD197",
"fallback": "heath (heathseals) was drinking Efes Pilsen (Pilsner - Other - 5%) by PI:NAME:<NAME>END_PI at DERALIYE OTTOMAN CUISINE - 8 hours ago",
"footer": "Earned the Beer Connoisseur (Level 8) badge",
"footer_icon": "https://untappd.akamaized.net/badges/bdg_connoiseur_sm.jpg",
"thumb_url": "https://untappd.akamaized.net/site/beer_logos/beer-EfesPilsener_17259.jpeg",
"title": "heath (heathseals) was drinking Efes Pilsen by PI:NAME:<NAME>END_PI",
"title_link": "https://untappd.com/user/heathseals/checkin/578869664"
}
],
"unfurl_links": false
}
]
]
done()
catch err
done err
return
, 1000)
# hubot untappd badges
it 'responds with the latest badge activity from your friends', (done) ->
nock('https://api.untappd.com')
.get('/v4/checkin/recent')
.query(
limit: 2,
access_token: 'PI:PASSWORD:<KEY>END_PI',
)
.replyWithFile(200, __dirname + '/fixtures/checkin-recent.json')
selfRoom = @room
selfRoom.user.say('alice', '@hubot untappd badges')
setTimeout(() ->
try
expect(selfRoom.messages).to.eql [
['alice', '@hubot untappd badges']
[
'hubot',
{
"attachments": [
{
"author_name": "an hour ago at 49 Çukurcuma",
"color": "#7CD197",
"fallback": "heath (heathseals) earned the Beer Foodie (Level 44) Badge after drinking a Blonde Ale at 49 Çukurcuma - an hour ago",
"footer": "Blonde Ale",
"footer_icon": "https://untappd.akamaized.net/site/beer_logos/beer-764911_07c43_sm.jpeg",
"thumb_url": "https://untappd.akamaized.net/badges/bdg_BeerFoodie_sm.jpg",
"title": "heath (heathseals) earned the Beer Foodie (Level 44) Badge",
"title_link": "https://untappd.com/user/heathseals/checkin/578981788"
},
{
"author_name": "an hour ago at 49 Çukurcuma",
"color": "#7CD197",
"fallback": "heath (heathseals) earned the 99 Bottles (Level 38) Badge after drinking a Blonde Ale at 49 Çukurcuma - an hour ago",
"footer": "Blonde Ale",
"footer_icon": "https://untappd.akamaized.net/site/beer_logos/beer-764911_07c43_sm.jpeg",
"thumb_url": "https://untappd.akamaized.net/badges/bdg_99Bottles_sm.jpg",
"title": "heath (heathseals) earned the 99 Bottles (Level 38) Badge",
"title_link": "https://untappd.com/user/heathseals/checkin/578981788"
},
{
"author_name": "an hour ago at 49 Çukurcuma",
"color": "#7CD197",
"fallback": "heath (heathseals) earned the Pizza & Brew (Level 4) Badge after drinking a Blonde Ale at 49 Çukurcuma - an hour ago",
"footer": "Blonde Ale",
"footer_icon": "https://untappd.akamaized.net/site/beer_logos/beer-764911_07c43_sm.jpeg",
"thumb_url": "https://untappd.akamaized.net/badges/bdg_PizzaAndBrew_sm.jpg",
"title": "heath (heathseals) earned the Pizza & Brew (Level 4) Badge",
"title_link": "https://untappd.com/user/heathseals/checkin/578981788"
},
{
"author_name": "8 hours ago at DERALIYE OTTOMAN CUISINE",
"color": "#7CD197",
"fallback": "heath (heathseals) earned the Beer Connoisseur (Level 8) Badge after drinking a Efes Pilsen at DERALIYE OTTOMAN CUISINE - 8 hours ago",
"footer": "PI:NAME:<NAME>END_PI Pilsen",
"footer_icon": "https://untappd.akamaized.net/site/beer_logos/beer-EfesPilsener_17259.jpeg",
"thumb_url": "https://untappd.akamaized.net/badges/bdg_connoiseur_sm.jpg",
"title": "heath (heathseals) earned the Beer Connoisseur (Level 8) Badge",
"title_link": "https://untappd.com/user/heathseals/checkin/578869664"
}
],
"unfurl_links": false
}
]
]
done()
catch err
done err
return
, 1000)
|
[
{
"context": "'Derechos'\n Role: 'Rol'\n Roles: 'Rols'\n name: 'Nombre'\n Logout: 'Salir'\n Register: 'Registrar'\n\n off",
"end": 126,
"score": 0.953011155128479,
"start": 120,
"tag": "NAME",
"value": "Nombre"
}
] | client/app/scripts/components/auth/auth.es.coffee | softwarerero/protothril | 0 | T9n.map "es",
Admin: 'Administración'
Right: 'Derecho'
Rights: 'Derechos'
Role: 'Rol'
Roles: 'Rols'
name: 'Nombre'
Logout: 'Salir'
Register: 'Registrar'
offerRegistration: '* Si no tenés un usuario puedes registrarte aquí.'
'invalid token': 'Los datos de acceso son incorrectos'
'You are logged in successfully': '¡Bienvenidos!'
'You are logged out successfully': '¡Hasta lluego!'
registration:
duplicate_user: 'Usuario ya existe'
success: 'Felicidades! Vas a recibir un email para confirmar tus datos.'
notfound: 'Yo siento. No he encontrado ninguna registración.'
notconfirmed: 'El email no esta confirmado todavía'
complete: 'Tu usuario está activado'
| 154058 | T9n.map "es",
Admin: 'Administración'
Right: 'Derecho'
Rights: 'Derechos'
Role: 'Rol'
Roles: 'Rols'
name: '<NAME>'
Logout: 'Salir'
Register: 'Registrar'
offerRegistration: '* Si no tenés un usuario puedes registrarte aquí.'
'invalid token': 'Los datos de acceso son incorrectos'
'You are logged in successfully': '¡Bienvenidos!'
'You are logged out successfully': '¡Hasta lluego!'
registration:
duplicate_user: 'Usuario ya existe'
success: 'Felicidades! Vas a recibir un email para confirmar tus datos.'
notfound: 'Yo siento. No he encontrado ninguna registración.'
notconfirmed: 'El email no esta confirmado todavía'
complete: 'Tu usuario está activado'
| true | T9n.map "es",
Admin: 'Administración'
Right: 'Derecho'
Rights: 'Derechos'
Role: 'Rol'
Roles: 'Rols'
name: 'PI:NAME:<NAME>END_PI'
Logout: 'Salir'
Register: 'Registrar'
offerRegistration: '* Si no tenés un usuario puedes registrarte aquí.'
'invalid token': 'Los datos de acceso son incorrectos'
'You are logged in successfully': '¡Bienvenidos!'
'You are logged out successfully': '¡Hasta lluego!'
registration:
duplicate_user: 'Usuario ya existe'
success: 'Felicidades! Vas a recibir un email para confirmar tus datos.'
notfound: 'Yo siento. No he encontrado ninguna registración.'
notconfirmed: 'El email no esta confirmado todavía'
complete: 'Tu usuario está activado'
|
[
{
"context": "username|screenname|login/i)\n fakeKey = 'userName'\n else if name.match(/domain|url/)\n ",
"end": 2273,
"score": 0.984256386756897,
"start": 2265,
"tag": "KEY",
"value": "userName"
},
{
"context": "itConfig.user.name then gitConfig.user.name else ... | node_modules/tower/packages/tower-generator/server/resources.coffee | MagicPower2/Power | 1 | _ = Tower._
fs = require 'fs'
# @mixin
Tower.GeneratorResources =
generate: (type) ->
options =
program: @program
app: @app
user: @user
model: @model
view: @view
controller: @controller
destinationRoot: @destinationRoot
generator = @constructor.buildGenerator(type)
generator = new generator(options)
generator.run()
nodeModule: (name, options = {}) ->
locals: ->
model: @model
view: @view
controller: @controller
app: @app
user: @user
_: _
printCoffeeOptions: (options = {}) ->
result = []
for key, value of options
unless typeof value == 'undefined'
value = switch _.kind(value)
when 'NaN', 'null'
'null'
when 'array', 'string', 'integer', 'float', 'number', 'boolean'
JSON.stringify(value)
result.push("#{key}: #{value}".replace(/"/g, "'"))
result.join(', ')
buildAttribute: (name, type = 'string', options = {}) ->
unless options.hasOwnProperty('default')
defaultValue = switch type.toLowerCase()
when 'integer' then 0
when 'array' then []
else
undefined
options.default = defaultValue unless typeof defaultValue == 'undefined'
attribute =
name: name
options: options
type: switch type.toLowerCase()
when 'text' then 'string'
when 'currency' then 'decimal'
else
type
humanName: _.humanize(name)
fieldType: switch type
when 'float', 'decimal', 'integer', 'number'
, 'string', 'time', 'date', 'text', 'boolean'
, 'currency', 'array', 'geo'
type
else
'string'
value: switch type
when 'integer' then 0
when 'array' then []
else
"A #{name}"
# @todo a more robust guesser for mapping common property names to dummy data
switch type.toLowerCase()
when 'string'
fakeKey = null
if name.match(/email/i)
fakeKey = 'email'
else if name.match(/username|screenname|login/i)
fakeKey = 'userName'
else if name.match(/domain|url/)
fakeKey = 'domainName'
else if name.match(/^(firstName|lastName)$/)
fakeKey = RegExp.$1
else if name.match(/^(name|fullName)$/)
fakeKey = 'fullName'
else if name.match('phone')
fakeKey = 'phone'
else if name.match(/text|content|body/)
fakeKey = 'paragraph'
else if name.match(/title/)
fakeKey = 'words'
attribute.fakeKey = fakeKey if fakeKey
when 'boolean'
attribute.fakeKey = 'boolean'
attribute
buildRelation: (type, className, options) ->
relation =
name: _.camelize(className, true)
type: type
humanName: _.humanize(className)
relation.options = options if _.isPresent(options)
relation
buildModel: (name, appNamespace, argv = []) ->
namespaces = name.split('/')
name = namespaces.pop()
name = _.camelize(name, true)
className = _.camelize(name)
classNamePlural = _.pluralize(className)
namespacedClassName = "#{appNamespace}.#{className}"
namePlural = _.pluralize(name)
paramName = _.parameterize(name)
paramNamePlural = _.parameterize(namePlural)
humanName = _.humanize(className)
humanNamePlural = _.pluralize(humanName)
attributes = []
relations =
belongsTo: []
hasOne: []
hasMany: []
argv.splice(0, 3)
for pair in argv
# tower generate scaffold post belongsTo:user
# belongsTo:inReplyToPost[type:post]
rawOptions = null
if pair.match(/\[/)
pair = pair.replace /([^\[]+)\[(.+)/, (_, $1, $2) ->
rawOptions = $2
pair = $1
else
[pair, rawOptions] = pair.split(/\[/)
pair = pair.split(':')
key = pair[0]
isRelation = !!key.match(/(belongsTo|hasMany|hasOne)/)
if pair.length > 1
type = pair[1]
else
# try and guess
type = if key.match(/count$/i)
'Integer'
else if key.match(/At$/)
'Date'
else
'String'
type = _.camelize(type || 'String', true)
options = {}
unless _.isBlank(rawOptions)
rawOptions = rawOptions.replace(/\]$/, '').split(/,\s*/)
for rawOption in rawOptions
[optionKey, optionValue] = rawOption = rawOption.split(':')
if rawOption.length == 1
optionValue = optionKey
if isRelation
optionKey = 'type'
else
optionKey = 'default'
optionValue = _.camelize(optionValue) if optionKey == 'type'
try
options[optionKey] = JSON.parse(optionValue)
catch error
options[optionKey] = optionValue
rawOptions = null
if isRelation
relations[key].push @buildRelation(key, _.camelize(type), options)
else
attributes.push @buildAttribute(key, _.camelize(type), options)
name: name
namespace: appNamespace
className: className
classNamePlural: classNamePlural
namespacedClassName: namespacedClassName
namePlural: namePlural
paramName: paramName
paramNamePlural: paramNamePlural
humanName: humanName
humanNamePlural: humanNamePlural
attributes: attributes
relations: relations
namespacedDirectory: namespaces.join('/')
viewDirectory: namespaces.join('/') + "/#{namePlural}"
namespaced: _.map(namespaces, (n) -> _.camelize(n)).join('.')
buildApp: (name = @appName) ->
@program.namespace ||= Tower.namespace()
name: name
namespace: _.camelize(@program.namespace)
paramName: _.parameterize(name)
paramNamePlural: _.parameterize(_.pluralize(name))
session: @generateRandom('hex')
year: (new Date).getFullYear()
directory: name
isStatic: true
buildView: (name) ->
name = _.map(name.split('/'), (n) -> _.camelize(n, true)).join('/')
namespace: name
directory: _.pluralize(name)
buildController: (name) ->
namespaces = name.split('/')
className = _.pluralize(_.camelize(namespaces[namespaces.length - 1])) + 'Controller'
if namespaces.length > 1
namespaces = namespaces[0..-2]
directory = _.map(namespaces, (n) -> _.camelize(n, true)).join('/')
namespace = @app.namespace + '.' + _.map(namespaces, (n) -> _.camelize(n)).join('.')
else
namespace = @app.namespace
directory = ''
namespace: namespace
className: className
directory: directory
name: _.camelize(className, true)
namespaced: directory != ''
generateRandom: (code = 'hex') ->
crypto = require('crypto')
uuid = require('node-uuid')
hash = crypto.createHash('sha1')
hash.update(uuid.v4())
hash.digest(code)
# automatically parse this stuff out from ~/.gitconfig
buildUser: (callback) ->
gitFile = "#{process.env.HOME}/.gitconfig"
gitConfig = {}
user = {}
try
if fs.existsSync(gitFile)
lines = fs.readFileSync(gitFile, 'utf-8').split('\n')
for line in lines
if line.charAt(0) != '#' && line.match(/\S/)
if line.match(/^\[(.*)\]$/)
variable = RegExp.$1
else
line = line.split('=')
key = line[0].trim()
value = line[1].trim()
gitConfig[variable] ||= {}
gitConfig[variable][key] = value
# @todo refactor to underscore.blank
user.name = if gitConfig.user && gitConfig.user.name then gitConfig.user.name else 'username'
user.email = if gitConfig.user && gitConfig.user.email then gitConfig.user.email else 'user@example.com'
user.username = if gitConfig.github && gitConfig.github.user then gitConfig.github.user else 'User'
catch error
@
user.name ||= 'username'
user.email ||= 'user@example.com'
user.username ||= 'User'
user.database = 'mongodb'
callback(user) if callback
user
module.exports = Tower.GeneratorResources
| 148740 | _ = Tower._
fs = require 'fs'
# @mixin
Tower.GeneratorResources =
generate: (type) ->
options =
program: @program
app: @app
user: @user
model: @model
view: @view
controller: @controller
destinationRoot: @destinationRoot
generator = @constructor.buildGenerator(type)
generator = new generator(options)
generator.run()
nodeModule: (name, options = {}) ->
locals: ->
model: @model
view: @view
controller: @controller
app: @app
user: @user
_: _
printCoffeeOptions: (options = {}) ->
result = []
for key, value of options
unless typeof value == 'undefined'
value = switch _.kind(value)
when 'NaN', 'null'
'null'
when 'array', 'string', 'integer', 'float', 'number', 'boolean'
JSON.stringify(value)
result.push("#{key}: #{value}".replace(/"/g, "'"))
result.join(', ')
buildAttribute: (name, type = 'string', options = {}) ->
unless options.hasOwnProperty('default')
defaultValue = switch type.toLowerCase()
when 'integer' then 0
when 'array' then []
else
undefined
options.default = defaultValue unless typeof defaultValue == 'undefined'
attribute =
name: name
options: options
type: switch type.toLowerCase()
when 'text' then 'string'
when 'currency' then 'decimal'
else
type
humanName: _.humanize(name)
fieldType: switch type
when 'float', 'decimal', 'integer', 'number'
, 'string', 'time', 'date', 'text', 'boolean'
, 'currency', 'array', 'geo'
type
else
'string'
value: switch type
when 'integer' then 0
when 'array' then []
else
"A #{name}"
# @todo a more robust guesser for mapping common property names to dummy data
switch type.toLowerCase()
when 'string'
fakeKey = null
if name.match(/email/i)
fakeKey = 'email'
else if name.match(/username|screenname|login/i)
fakeKey = '<KEY>'
else if name.match(/domain|url/)
fakeKey = 'domainName'
else if name.match(/^(firstName|lastName)$/)
fakeKey = RegExp.$1
else if name.match(/^(name|fullName)$/)
fakeKey = 'fullName'
else if name.match('phone')
fakeKey = 'phone'
else if name.match(/text|content|body/)
fakeKey = 'paragraph'
else if name.match(/title/)
fakeKey = 'words'
attribute.fakeKey = fakeKey if fakeKey
when 'boolean'
attribute.fakeKey = 'boolean'
attribute
buildRelation: (type, className, options) ->
relation =
name: _.camelize(className, true)
type: type
humanName: _.humanize(className)
relation.options = options if _.isPresent(options)
relation
buildModel: (name, appNamespace, argv = []) ->
namespaces = name.split('/')
name = namespaces.pop()
name = _.camelize(name, true)
className = _.camelize(name)
classNamePlural = _.pluralize(className)
namespacedClassName = "#{appNamespace}.#{className}"
namePlural = _.pluralize(name)
paramName = _.parameterize(name)
paramNamePlural = _.parameterize(namePlural)
humanName = _.humanize(className)
humanNamePlural = _.pluralize(humanName)
attributes = []
relations =
belongsTo: []
hasOne: []
hasMany: []
argv.splice(0, 3)
for pair in argv
# tower generate scaffold post belongsTo:user
# belongsTo:inReplyToPost[type:post]
rawOptions = null
if pair.match(/\[/)
pair = pair.replace /([^\[]+)\[(.+)/, (_, $1, $2) ->
rawOptions = $2
pair = $1
else
[pair, rawOptions] = pair.split(/\[/)
pair = pair.split(':')
key = pair[0]
isRelation = !!key.match(/(belongsTo|hasMany|hasOne)/)
if pair.length > 1
type = pair[1]
else
# try and guess
type = if key.match(/count$/i)
'Integer'
else if key.match(/At$/)
'Date'
else
'String'
type = _.camelize(type || 'String', true)
options = {}
unless _.isBlank(rawOptions)
rawOptions = rawOptions.replace(/\]$/, '').split(/,\s*/)
for rawOption in rawOptions
[optionKey, optionValue] = rawOption = rawOption.split(':')
if rawOption.length == 1
optionValue = optionKey
if isRelation
optionKey = 'type'
else
optionKey = 'default'
optionValue = _.camelize(optionValue) if optionKey == 'type'
try
options[optionKey] = JSON.parse(optionValue)
catch error
options[optionKey] = optionValue
rawOptions = null
if isRelation
relations[key].push @buildRelation(key, _.camelize(type), options)
else
attributes.push @buildAttribute(key, _.camelize(type), options)
name: name
namespace: appNamespace
className: className
classNamePlural: classNamePlural
namespacedClassName: namespacedClassName
namePlural: namePlural
paramName: paramName
paramNamePlural: paramNamePlural
humanName: humanName
humanNamePlural: humanNamePlural
attributes: attributes
relations: relations
namespacedDirectory: namespaces.join('/')
viewDirectory: namespaces.join('/') + "/#{namePlural}"
namespaced: _.map(namespaces, (n) -> _.camelize(n)).join('.')
buildApp: (name = @appName) ->
@program.namespace ||= Tower.namespace()
name: name
namespace: _.camelize(@program.namespace)
paramName: _.parameterize(name)
paramNamePlural: _.parameterize(_.pluralize(name))
session: @generateRandom('hex')
year: (new Date).getFullYear()
directory: name
isStatic: true
buildView: (name) ->
name = _.map(name.split('/'), (n) -> _.camelize(n, true)).join('/')
namespace: name
directory: _.pluralize(name)
buildController: (name) ->
namespaces = name.split('/')
className = _.pluralize(_.camelize(namespaces[namespaces.length - 1])) + 'Controller'
if namespaces.length > 1
namespaces = namespaces[0..-2]
directory = _.map(namespaces, (n) -> _.camelize(n, true)).join('/')
namespace = @app.namespace + '.' + _.map(namespaces, (n) -> _.camelize(n)).join('.')
else
namespace = @app.namespace
directory = ''
namespace: namespace
className: className
directory: directory
name: _.camelize(className, true)
namespaced: directory != ''
generateRandom: (code = 'hex') ->
crypto = require('crypto')
uuid = require('node-uuid')
hash = crypto.createHash('sha1')
hash.update(uuid.v4())
hash.digest(code)
# automatically parse this stuff out from ~/.gitconfig
buildUser: (callback) ->
gitFile = "#{process.env.HOME}/.gitconfig"
gitConfig = {}
user = {}
try
if fs.existsSync(gitFile)
lines = fs.readFileSync(gitFile, 'utf-8').split('\n')
for line in lines
if line.charAt(0) != '#' && line.match(/\S/)
if line.match(/^\[(.*)\]$/)
variable = RegExp.$1
else
line = line.split('=')
key = line[0].trim()
value = line[1].trim()
gitConfig[variable] ||= {}
gitConfig[variable][key] = value
# @todo refactor to underscore.blank
user.name = if gitConfig.user && gitConfig.user.name then gitConfig.user.name else 'username'
user.email = if gitConfig.user && gitConfig.user.email then gitConfig.user.email else '<EMAIL>'
user.username = if gitConfig.github && gitConfig.github.user then gitConfig.github.user else 'User'
catch error
@
user.name ||= 'username'
user.email ||= '<EMAIL>'
user.username ||= 'User'
user.database = 'mongodb'
callback(user) if callback
user
module.exports = Tower.GeneratorResources
| true | _ = Tower._
fs = require 'fs'
# @mixin
Tower.GeneratorResources =
generate: (type) ->
options =
program: @program
app: @app
user: @user
model: @model
view: @view
controller: @controller
destinationRoot: @destinationRoot
generator = @constructor.buildGenerator(type)
generator = new generator(options)
generator.run()
nodeModule: (name, options = {}) ->
locals: ->
model: @model
view: @view
controller: @controller
app: @app
user: @user
_: _
printCoffeeOptions: (options = {}) ->
result = []
for key, value of options
unless typeof value == 'undefined'
value = switch _.kind(value)
when 'NaN', 'null'
'null'
when 'array', 'string', 'integer', 'float', 'number', 'boolean'
JSON.stringify(value)
result.push("#{key}: #{value}".replace(/"/g, "'"))
result.join(', ')
buildAttribute: (name, type = 'string', options = {}) ->
unless options.hasOwnProperty('default')
defaultValue = switch type.toLowerCase()
when 'integer' then 0
when 'array' then []
else
undefined
options.default = defaultValue unless typeof defaultValue == 'undefined'
attribute =
name: name
options: options
type: switch type.toLowerCase()
when 'text' then 'string'
when 'currency' then 'decimal'
else
type
humanName: _.humanize(name)
fieldType: switch type
when 'float', 'decimal', 'integer', 'number'
, 'string', 'time', 'date', 'text', 'boolean'
, 'currency', 'array', 'geo'
type
else
'string'
value: switch type
when 'integer' then 0
when 'array' then []
else
"A #{name}"
# @todo a more robust guesser for mapping common property names to dummy data
switch type.toLowerCase()
when 'string'
fakeKey = null
if name.match(/email/i)
fakeKey = 'email'
else if name.match(/username|screenname|login/i)
fakeKey = 'PI:KEY:<KEY>END_PI'
else if name.match(/domain|url/)
fakeKey = 'domainName'
else if name.match(/^(firstName|lastName)$/)
fakeKey = RegExp.$1
else if name.match(/^(name|fullName)$/)
fakeKey = 'fullName'
else if name.match('phone')
fakeKey = 'phone'
else if name.match(/text|content|body/)
fakeKey = 'paragraph'
else if name.match(/title/)
fakeKey = 'words'
attribute.fakeKey = fakeKey if fakeKey
when 'boolean'
attribute.fakeKey = 'boolean'
attribute
buildRelation: (type, className, options) ->
relation =
name: _.camelize(className, true)
type: type
humanName: _.humanize(className)
relation.options = options if _.isPresent(options)
relation
buildModel: (name, appNamespace, argv = []) ->
namespaces = name.split('/')
name = namespaces.pop()
name = _.camelize(name, true)
className = _.camelize(name)
classNamePlural = _.pluralize(className)
namespacedClassName = "#{appNamespace}.#{className}"
namePlural = _.pluralize(name)
paramName = _.parameterize(name)
paramNamePlural = _.parameterize(namePlural)
humanName = _.humanize(className)
humanNamePlural = _.pluralize(humanName)
attributes = []
relations =
belongsTo: []
hasOne: []
hasMany: []
argv.splice(0, 3)
for pair in argv
# tower generate scaffold post belongsTo:user
# belongsTo:inReplyToPost[type:post]
rawOptions = null
if pair.match(/\[/)
pair = pair.replace /([^\[]+)\[(.+)/, (_, $1, $2) ->
rawOptions = $2
pair = $1
else
[pair, rawOptions] = pair.split(/\[/)
pair = pair.split(':')
key = pair[0]
isRelation = !!key.match(/(belongsTo|hasMany|hasOne)/)
if pair.length > 1
type = pair[1]
else
# try and guess
type = if key.match(/count$/i)
'Integer'
else if key.match(/At$/)
'Date'
else
'String'
type = _.camelize(type || 'String', true)
options = {}
unless _.isBlank(rawOptions)
rawOptions = rawOptions.replace(/\]$/, '').split(/,\s*/)
for rawOption in rawOptions
[optionKey, optionValue] = rawOption = rawOption.split(':')
if rawOption.length == 1
optionValue = optionKey
if isRelation
optionKey = 'type'
else
optionKey = 'default'
optionValue = _.camelize(optionValue) if optionKey == 'type'
try
options[optionKey] = JSON.parse(optionValue)
catch error
options[optionKey] = optionValue
rawOptions = null
if isRelation
relations[key].push @buildRelation(key, _.camelize(type), options)
else
attributes.push @buildAttribute(key, _.camelize(type), options)
name: name
namespace: appNamespace
className: className
classNamePlural: classNamePlural
namespacedClassName: namespacedClassName
namePlural: namePlural
paramName: paramName
paramNamePlural: paramNamePlural
humanName: humanName
humanNamePlural: humanNamePlural
attributes: attributes
relations: relations
namespacedDirectory: namespaces.join('/')
viewDirectory: namespaces.join('/') + "/#{namePlural}"
namespaced: _.map(namespaces, (n) -> _.camelize(n)).join('.')
buildApp: (name = @appName) ->
@program.namespace ||= Tower.namespace()
name: name
namespace: _.camelize(@program.namespace)
paramName: _.parameterize(name)
paramNamePlural: _.parameterize(_.pluralize(name))
session: @generateRandom('hex')
year: (new Date).getFullYear()
directory: name
isStatic: true
buildView: (name) ->
name = _.map(name.split('/'), (n) -> _.camelize(n, true)).join('/')
namespace: name
directory: _.pluralize(name)
buildController: (name) ->
namespaces = name.split('/')
className = _.pluralize(_.camelize(namespaces[namespaces.length - 1])) + 'Controller'
if namespaces.length > 1
namespaces = namespaces[0..-2]
directory = _.map(namespaces, (n) -> _.camelize(n, true)).join('/')
namespace = @app.namespace + '.' + _.map(namespaces, (n) -> _.camelize(n)).join('.')
else
namespace = @app.namespace
directory = ''
namespace: namespace
className: className
directory: directory
name: _.camelize(className, true)
namespaced: directory != ''
generateRandom: (code = 'hex') ->
crypto = require('crypto')
uuid = require('node-uuid')
hash = crypto.createHash('sha1')
hash.update(uuid.v4())
hash.digest(code)
# automatically parse this stuff out from ~/.gitconfig
buildUser: (callback) ->
gitFile = "#{process.env.HOME}/.gitconfig"
gitConfig = {}
user = {}
try
if fs.existsSync(gitFile)
lines = fs.readFileSync(gitFile, 'utf-8').split('\n')
for line in lines
if line.charAt(0) != '#' && line.match(/\S/)
if line.match(/^\[(.*)\]$/)
variable = RegExp.$1
else
line = line.split('=')
key = line[0].trim()
value = line[1].trim()
gitConfig[variable] ||= {}
gitConfig[variable][key] = value
# @todo refactor to underscore.blank
user.name = if gitConfig.user && gitConfig.user.name then gitConfig.user.name else 'username'
user.email = if gitConfig.user && gitConfig.user.email then gitConfig.user.email else 'PI:EMAIL:<EMAIL>END_PI'
user.username = if gitConfig.github && gitConfig.github.user then gitConfig.github.user else 'User'
catch error
@
user.name ||= 'username'
user.email ||= 'PI:EMAIL:<EMAIL>END_PI'
user.username ||= 'User'
user.database = 'mongodb'
callback(user) if callback
user
module.exports = Tower.GeneratorResources
|
[
{
"context": "# Copyright Joyent, Inc. and other Node contributors.\n\n# Permission ",
"end": 18,
"score": 0.9990828633308411,
"start": 12,
"tag": "NAME",
"value": "Joyent"
},
{
"context": "s.getServers()\nassert existing.length\ngoog = [\n \"8.8.8.8\"\n \"8.8.4.4\"\n]\nassert.does... | test/simple/test-dns.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.
noop = ->
common = require("../common")
assert = require("assert")
dns = require("dns")
existing = dns.getServers()
assert existing.length
goog = [
"8.8.8.8"
"8.8.4.4"
]
assert.doesNotThrow ->
dns.setServers goog
return
assert.deepEqual dns.getServers(), goog
assert.throws ->
dns.setServers ["foobar"]
return
assert.deepEqual dns.getServers(), goog
goog6 = [
"2001:4860:4860::8888"
"2001:4860:4860::8844"
]
assert.doesNotThrow ->
dns.setServers goog6
return
assert.deepEqual dns.getServers(), goog6
goog6.push "4.4.4.4"
dns.setServers goog6
assert.deepEqual dns.getServers(), goog6
ports = [
"4.4.4.4:53"
"[2001:4860:4860::8888]:53"
]
portsExpected = [
"4.4.4.4"
"2001:4860:4860::8888"
]
dns.setServers ports
assert.deepEqual dns.getServers(), portsExpected
assert.doesNotThrow ->
dns.setServers []
return
assert.deepEqual dns.getServers(), []
assert.throws (->
dns.resolve "test.com", [], noop
return
), ((err) ->
(err not instanceof TypeError)
), "Unexpected error"
# dns.lookup should accept falsey and string values
assert.throws (->
dns.lookup {}, noop
return
), "invalid arguments: hostname must be a string or falsey"
assert.throws (->
dns.lookup [], noop
return
), "invalid arguments: hostname must be a string or falsey"
assert.throws (->
dns.lookup true, noop
return
), "invalid arguments: hostname must be a string or falsey"
assert.throws (->
dns.lookup 1, noop
return
), "invalid arguments: hostname must be a string or falsey"
assert.throws (->
dns.lookup noop, noop
return
), "invalid arguments: hostname must be a string or falsey"
assert.doesNotThrow ->
dns.lookup "", noop
return
assert.doesNotThrow ->
dns.lookup null, noop
return
assert.doesNotThrow ->
dns.lookup `undefined`, noop
return
assert.doesNotThrow ->
dns.lookup 0, noop
return
assert.doesNotThrow ->
dns.lookup NaN, noop
return
#
# * Make sure that dns.lookup throws if hints does not represent a valid flag.
# * (dns.V4MAPPED | dns.ADDRCONFIG) + 1 is invalid because:
# * - it's different from dns.V4MAPPED and dns.ADDRCONFIG.
# * - it's different from them bitwise ored.
# * - it's different from 0.
# * - it's an odd number different than 1, and thus is invalid, because
# * flags are either === 1 or even.
#
assert.throws ->
dns.lookup "www.google.com",
hints: (dns.V4MAPPED | dns.ADDRCONFIG) + 1
, noop
return
assert.throws (->
dns.lookup "www.google.com"
return
), "invalid arguments: callback must be passed"
assert.throws (->
dns.lookup "www.google.com", 4
return
), "invalid arguments: callback must be passed"
assert.doesNotThrow ->
dns.lookup "www.google.com", 6, noop
return
assert.doesNotThrow ->
dns.lookup "www.google.com", {}, noop
return
assert.doesNotThrow ->
dns.lookup "www.google.com",
family: 4
hints: 0
, noop
return
assert.doesNotThrow ->
dns.lookup "www.google.com",
family: 6
hints: dns.ADDRCONFIG
, noop
return
assert.doesNotThrow ->
dns.lookup "www.google.com",
hints: dns.V4MAPPED
, noop
return
assert.doesNotThrow ->
dns.lookup "www.google.com",
hints: dns.ADDRCONFIG | dns.V4MAPPED
, noop
return
| 172159 | # 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.
noop = ->
common = require("../common")
assert = require("assert")
dns = require("dns")
existing = dns.getServers()
assert existing.length
goog = [
"8.8.8.8"
"8.8.4.4"
]
assert.doesNotThrow ->
dns.setServers goog
return
assert.deepEqual dns.getServers(), goog
assert.throws ->
dns.setServers ["foobar"]
return
assert.deepEqual dns.getServers(), goog
goog6 = [
"fdf8:f53e:61e4::18"
"fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b"
]
assert.doesNotThrow ->
dns.setServers goog6
return
assert.deepEqual dns.getServers(), goog6
goog6.push "172.16.31.10"
dns.setServers goog6
assert.deepEqual dns.getServers(), goog6
ports = [
"172.16.31.10:53"
"[2fdf8:f53e:61e4::18]:53"
]
portsExpected = [
"172.16.31.10"
"fdf8:f53e:61e4::18"
]
dns.setServers ports
assert.deepEqual dns.getServers(), portsExpected
assert.doesNotThrow ->
dns.setServers []
return
assert.deepEqual dns.getServers(), []
assert.throws (->
dns.resolve "test.com", [], noop
return
), ((err) ->
(err not instanceof TypeError)
), "Unexpected error"
# dns.lookup should accept falsey and string values
assert.throws (->
dns.lookup {}, noop
return
), "invalid arguments: hostname must be a string or falsey"
assert.throws (->
dns.lookup [], noop
return
), "invalid arguments: hostname must be a string or falsey"
assert.throws (->
dns.lookup true, noop
return
), "invalid arguments: hostname must be a string or falsey"
assert.throws (->
dns.lookup 1, noop
return
), "invalid arguments: hostname must be a string or falsey"
assert.throws (->
dns.lookup noop, noop
return
), "invalid arguments: hostname must be a string or falsey"
assert.doesNotThrow ->
dns.lookup "", noop
return
assert.doesNotThrow ->
dns.lookup null, noop
return
assert.doesNotThrow ->
dns.lookup `undefined`, noop
return
assert.doesNotThrow ->
dns.lookup 0, noop
return
assert.doesNotThrow ->
dns.lookup NaN, noop
return
#
# * Make sure that dns.lookup throws if hints does not represent a valid flag.
# * (dns.V4MAPPED | dns.ADDRCONFIG) + 1 is invalid because:
# * - it's different from dns.V4MAPPED and dns.ADDRCONFIG.
# * - it's different from them bitwise ored.
# * - it's different from 0.
# * - it's an odd number different than 1, and thus is invalid, because
# * flags are either === 1 or even.
#
assert.throws ->
dns.lookup "www.google.com",
hints: (dns.V4MAPPED | dns.ADDRCONFIG) + 1
, noop
return
assert.throws (->
dns.lookup "www.google.com"
return
), "invalid arguments: callback must be passed"
assert.throws (->
dns.lookup "www.google.com", 4
return
), "invalid arguments: callback must be passed"
assert.doesNotThrow ->
dns.lookup "www.google.com", 6, noop
return
assert.doesNotThrow ->
dns.lookup "www.google.com", {}, noop
return
assert.doesNotThrow ->
dns.lookup "www.google.com",
family: 4
hints: 0
, noop
return
assert.doesNotThrow ->
dns.lookup "www.google.com",
family: 6
hints: dns.ADDRCONFIG
, noop
return
assert.doesNotThrow ->
dns.lookup "www.google.com",
hints: dns.V4MAPPED
, noop
return
assert.doesNotThrow ->
dns.lookup "www.google.com",
hints: dns.ADDRCONFIG | dns.V4MAPPED
, noop
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.
noop = ->
common = require("../common")
assert = require("assert")
dns = require("dns")
existing = dns.getServers()
assert existing.length
goog = [
"8.8.8.8"
"8.8.4.4"
]
assert.doesNotThrow ->
dns.setServers goog
return
assert.deepEqual dns.getServers(), goog
assert.throws ->
dns.setServers ["foobar"]
return
assert.deepEqual dns.getServers(), goog
goog6 = [
"PI:IP_ADDRESS:fdf8:f53e:61e4::18END_PI"
"PI:IP_ADDRESS:fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5bEND_PI"
]
assert.doesNotThrow ->
dns.setServers goog6
return
assert.deepEqual dns.getServers(), goog6
goog6.push "PI:IP_ADDRESS:172.16.31.10END_PI"
dns.setServers goog6
assert.deepEqual dns.getServers(), goog6
ports = [
"PI:IP_ADDRESS:172.16.31.10END_PI:53"
"[2PI:IP_ADDRESS:fdf8:f53e:61e4::18END_PI]:53"
]
portsExpected = [
"PI:IP_ADDRESS:172.16.31.10END_PI"
"PI:IP_ADDRESS:fdf8:f53e:61e4::18END_PI"
]
dns.setServers ports
assert.deepEqual dns.getServers(), portsExpected
assert.doesNotThrow ->
dns.setServers []
return
assert.deepEqual dns.getServers(), []
assert.throws (->
dns.resolve "test.com", [], noop
return
), ((err) ->
(err not instanceof TypeError)
), "Unexpected error"
# dns.lookup should accept falsey and string values
assert.throws (->
dns.lookup {}, noop
return
), "invalid arguments: hostname must be a string or falsey"
assert.throws (->
dns.lookup [], noop
return
), "invalid arguments: hostname must be a string or falsey"
assert.throws (->
dns.lookup true, noop
return
), "invalid arguments: hostname must be a string or falsey"
assert.throws (->
dns.lookup 1, noop
return
), "invalid arguments: hostname must be a string or falsey"
assert.throws (->
dns.lookup noop, noop
return
), "invalid arguments: hostname must be a string or falsey"
assert.doesNotThrow ->
dns.lookup "", noop
return
assert.doesNotThrow ->
dns.lookup null, noop
return
assert.doesNotThrow ->
dns.lookup `undefined`, noop
return
assert.doesNotThrow ->
dns.lookup 0, noop
return
assert.doesNotThrow ->
dns.lookup NaN, noop
return
#
# * Make sure that dns.lookup throws if hints does not represent a valid flag.
# * (dns.V4MAPPED | dns.ADDRCONFIG) + 1 is invalid because:
# * - it's different from dns.V4MAPPED and dns.ADDRCONFIG.
# * - it's different from them bitwise ored.
# * - it's different from 0.
# * - it's an odd number different than 1, and thus is invalid, because
# * flags are either === 1 or even.
#
assert.throws ->
dns.lookup "www.google.com",
hints: (dns.V4MAPPED | dns.ADDRCONFIG) + 1
, noop
return
assert.throws (->
dns.lookup "www.google.com"
return
), "invalid arguments: callback must be passed"
assert.throws (->
dns.lookup "www.google.com", 4
return
), "invalid arguments: callback must be passed"
assert.doesNotThrow ->
dns.lookup "www.google.com", 6, noop
return
assert.doesNotThrow ->
dns.lookup "www.google.com", {}, noop
return
assert.doesNotThrow ->
dns.lookup "www.google.com",
family: 4
hints: 0
, noop
return
assert.doesNotThrow ->
dns.lookup "www.google.com",
family: 6
hints: dns.ADDRCONFIG
, noop
return
assert.doesNotThrow ->
dns.lookup "www.google.com",
hints: dns.V4MAPPED
, noop
return
assert.doesNotThrow ->
dns.lookup "www.google.com",
hints: dns.ADDRCONFIG | dns.V4MAPPED
, noop
return
|
[
{
"context": "st.add \"authorFreq\";\n nameCol.textContent = author; pcCol.textContent = (authFreq[author] / lineCoun",
"end": 2210,
"score": 0.9110380411148071,
"start": 2204,
"tag": "NAME",
"value": "author"
}
] | lib/git-authors-view.coffee | groktools/git-authors | 7 | path = require "path"
{BufferedProcess} = require "atom"
module.exports =
class GitAuthorsView
@message: null,
constructor: (serializedState) ->
# Create root element
@element = @makeHTMLElement('div', 'git-authors')
# Create message element
@message = @makeHTMLElement('div','message',"Getting authors..")
@element.appendChild(@message)
# @getAuthors()
# Returns an object that can be retrieved when package is activated
serialize: ->
# Tear down any state and detach
destroy: ->
@element.remove()
getElement: ->
@element
getAuthors: (panel)->
item = panel.getItem()
currFile = atom.workspace.getActiveTextEditor()?.getPath()
console.log "in getAuthors: #{@message}"
console.log "getting authors..."
lineCount = 0
authFreq = {}
success = (stdout) ->
# console.log stdout
lines = stdout.split('\n')
lineCount += lines.length
authNames = lines.map (l) ->
# console.log "l:#{l}"
if l
nm = l.match(/.+ \((.+) +\d{4}-.+/)
# console.log "nm:#{nm}"
nm[1]
# console.log "authNames: #{authNames.length}"
for name in authNames
# console.log "nm: #{name}"
if name == undefined
continue
if authFreq[name] != undefined
# console.log "incr nm:#{name}"
authFreq[name]++
else
# console.log "adding nm:#{name}"
authFreq[name] = 1
finish = (err) ->
if err !=0
console.log err
panel.getItem().textContent = "Failed to get author list. Something went wrong."
console.log lineCount, authFreq
sortedByFreq = Object.keys(authFreq).sort((a,b) -> authFreq[b]-authFreq[a])
console.log sortedByFreq
panel.getItem().removeChild(panel.getItem().firstChild)
for author in sortedByFreq
# console.log "AA #{author} AA: #{authFreq[author]}"
authLine = document.createElement("div");authLine.classList.add "authLine"
nameCol = document.createElement("div");pcCol = document.createElement("div");
nameCol.classList.add "authorName"; pcCol.classList.add "authorFreq";
nameCol.textContent = author; pcCol.textContent = (authFreq[author] / lineCount * 100).toFixed(2) + "%"
authLine.appendChild nameCol; authLine.appendChild pcCol
panel.getItem().appendChild authLine
failure = (err) ->
console.log err
panel.getItem().textContent = "Failed to get author list. Is this a git repo?"
currFile = atom.workspace.getActiveTextEditor()?.getPath()
new BufferedProcess ({
command: "git",
# args: ["-C", path.dirname(currFile), "blame", "--line-porcelain", currFile]
args: ["-C", path.dirname(currFile), "blame", currFile]
stdout: success,
stderr: failure,
exit: finish
})
makeHTMLElement: (t,s,content) ->
el = document.createElement(t)
el.classList.add(s)
if content != undefined
el.textContent = content
el
| 81912 | path = require "path"
{BufferedProcess} = require "atom"
module.exports =
class GitAuthorsView
@message: null,
constructor: (serializedState) ->
# Create root element
@element = @makeHTMLElement('div', 'git-authors')
# Create message element
@message = @makeHTMLElement('div','message',"Getting authors..")
@element.appendChild(@message)
# @getAuthors()
# Returns an object that can be retrieved when package is activated
serialize: ->
# Tear down any state and detach
destroy: ->
@element.remove()
getElement: ->
@element
getAuthors: (panel)->
item = panel.getItem()
currFile = atom.workspace.getActiveTextEditor()?.getPath()
console.log "in getAuthors: #{@message}"
console.log "getting authors..."
lineCount = 0
authFreq = {}
success = (stdout) ->
# console.log stdout
lines = stdout.split('\n')
lineCount += lines.length
authNames = lines.map (l) ->
# console.log "l:#{l}"
if l
nm = l.match(/.+ \((.+) +\d{4}-.+/)
# console.log "nm:#{nm}"
nm[1]
# console.log "authNames: #{authNames.length}"
for name in authNames
# console.log "nm: #{name}"
if name == undefined
continue
if authFreq[name] != undefined
# console.log "incr nm:#{name}"
authFreq[name]++
else
# console.log "adding nm:#{name}"
authFreq[name] = 1
finish = (err) ->
if err !=0
console.log err
panel.getItem().textContent = "Failed to get author list. Something went wrong."
console.log lineCount, authFreq
sortedByFreq = Object.keys(authFreq).sort((a,b) -> authFreq[b]-authFreq[a])
console.log sortedByFreq
panel.getItem().removeChild(panel.getItem().firstChild)
for author in sortedByFreq
# console.log "AA #{author} AA: #{authFreq[author]}"
authLine = document.createElement("div");authLine.classList.add "authLine"
nameCol = document.createElement("div");pcCol = document.createElement("div");
nameCol.classList.add "authorName"; pcCol.classList.add "authorFreq";
nameCol.textContent = <NAME>; pcCol.textContent = (authFreq[author] / lineCount * 100).toFixed(2) + "%"
authLine.appendChild nameCol; authLine.appendChild pcCol
panel.getItem().appendChild authLine
failure = (err) ->
console.log err
panel.getItem().textContent = "Failed to get author list. Is this a git repo?"
currFile = atom.workspace.getActiveTextEditor()?.getPath()
new BufferedProcess ({
command: "git",
# args: ["-C", path.dirname(currFile), "blame", "--line-porcelain", currFile]
args: ["-C", path.dirname(currFile), "blame", currFile]
stdout: success,
stderr: failure,
exit: finish
})
makeHTMLElement: (t,s,content) ->
el = document.createElement(t)
el.classList.add(s)
if content != undefined
el.textContent = content
el
| true | path = require "path"
{BufferedProcess} = require "atom"
module.exports =
class GitAuthorsView
@message: null,
constructor: (serializedState) ->
# Create root element
@element = @makeHTMLElement('div', 'git-authors')
# Create message element
@message = @makeHTMLElement('div','message',"Getting authors..")
@element.appendChild(@message)
# @getAuthors()
# Returns an object that can be retrieved when package is activated
serialize: ->
# Tear down any state and detach
destroy: ->
@element.remove()
getElement: ->
@element
getAuthors: (panel)->
item = panel.getItem()
currFile = atom.workspace.getActiveTextEditor()?.getPath()
console.log "in getAuthors: #{@message}"
console.log "getting authors..."
lineCount = 0
authFreq = {}
success = (stdout) ->
# console.log stdout
lines = stdout.split('\n')
lineCount += lines.length
authNames = lines.map (l) ->
# console.log "l:#{l}"
if l
nm = l.match(/.+ \((.+) +\d{4}-.+/)
# console.log "nm:#{nm}"
nm[1]
# console.log "authNames: #{authNames.length}"
for name in authNames
# console.log "nm: #{name}"
if name == undefined
continue
if authFreq[name] != undefined
# console.log "incr nm:#{name}"
authFreq[name]++
else
# console.log "adding nm:#{name}"
authFreq[name] = 1
finish = (err) ->
if err !=0
console.log err
panel.getItem().textContent = "Failed to get author list. Something went wrong."
console.log lineCount, authFreq
sortedByFreq = Object.keys(authFreq).sort((a,b) -> authFreq[b]-authFreq[a])
console.log sortedByFreq
panel.getItem().removeChild(panel.getItem().firstChild)
for author in sortedByFreq
# console.log "AA #{author} AA: #{authFreq[author]}"
authLine = document.createElement("div");authLine.classList.add "authLine"
nameCol = document.createElement("div");pcCol = document.createElement("div");
nameCol.classList.add "authorName"; pcCol.classList.add "authorFreq";
nameCol.textContent = PI:NAME:<NAME>END_PI; pcCol.textContent = (authFreq[author] / lineCount * 100).toFixed(2) + "%"
authLine.appendChild nameCol; authLine.appendChild pcCol
panel.getItem().appendChild authLine
failure = (err) ->
console.log err
panel.getItem().textContent = "Failed to get author list. Is this a git repo?"
currFile = atom.workspace.getActiveTextEditor()?.getPath()
new BufferedProcess ({
command: "git",
# args: ["-C", path.dirname(currFile), "blame", "--line-porcelain", currFile]
args: ["-C", path.dirname(currFile), "blame", currFile]
stdout: success,
stderr: failure,
exit: finish
})
makeHTMLElement: (t,s,content) ->
el = document.createElement(t)
el.classList.add(s)
if content != undefined
el.textContent = content
el
|
[
{
"context": "# * http://foundation.zurb.com\n# * Copyright 2012, ZURB\n# * Free to use under the MIT license.\n# * http:/",
"end": 161,
"score": 0.5558185577392578,
"start": 157,
"tag": "NAME",
"value": "ZURB"
}
] | coffee/tooltips.coffee | alejo8591/shurikend | 0 | ###
Inspired in foundation v.3.2
tooltips: tooltips.coffee
###
#
# * jQuery Foundation Tooltips 2.0.2
# * http://foundation.zurb.com
# * Copyright 2012, ZURB
# * Free to use under the MIT license.
# * http://www.opensource.org/licenses/mit-license.php
#
#jslint unparam: true, browser: true, indent: 2
(($, window, undefined_) ->
"use strict"
settings =
bodyHeight: 0
selector: ".has-tip"
additionalInheritableClasses: []
tooltipClass: ".tooltip"
tipTemplate: (selector, content) ->
"<span data-selector=\"" + selector + "\" class=\"" + settings.tooltipClass.substring(1) + "\">" + content + "<span class=\"nub\"></span></span>"
methods =
init: (options) ->
settings = $.extend(settings, options)
# alias the old targetClass option
settings.selector = (if settings.targetClass then settings.targetClass else settings.selector)
@each ->
$body = $("body")
if Modernizr.touch
$body.on "click.tooltip touchstart.tooltip touchend.tooltip", settings.selector, (e) ->
e.preventDefault()
$(settings.tooltipClass).hide()
methods.showOrCreateTip $(this)
$body.on "click.tooltip touchstart.tooltip touchend.tooltip", settings.tooltipClass, (e) ->
e.preventDefault()
$(this).fadeOut 150
else
$body.on "mouseenter.tooltip mouseleave.tooltip", settings.selector, (e) ->
$this = $(this)
if e.type is "mouseenter"
methods.showOrCreateTip $this
else methods.hide $this if e.type is "mouseleave"
$(this).data "tooltips", true
showOrCreateTip: ($target, content) ->
$tip = methods.getTip($target)
if $tip and $tip.length > 0
methods.show $target
else
methods.create $target, content
getTip: ($target) ->
selector = methods.selector($target)
tip = null
tip = $("span[data-selector=" + selector + "]" + settings.tooltipClass) if selector
(if (tip.length > 0) then tip else false)
selector: ($target) ->
id = $target.attr("id")
dataSelector = $target.data("selector")
if id is `undefined` and dataSelector is `undefined`
dataSelector = "tooltip" + Math.random().toString(36).substring(7)
$target.attr "data-selector", dataSelector
(if (id) then id else dataSelector)
create: ($target, content) ->
$tip = $(settings.tipTemplate(methods.selector($target), $("<div>").html((if content then content else $target.attr("title"))).html()))
classes = methods.inheritable_classes($target)
$tip.addClass(classes).appendTo "body"
$tip.append "<span class=\"tap-to-close\">tap to close </span>" if Modernizr.touch
$target.removeAttr "title"
methods.show $target
reposition: (target, tip, classes) ->
width = undefined_
nub = undefined_
nubHeight = undefined_
nubWidth = undefined_
column = undefined_
objPos = undefined_
tip.css("visibility", "hidden").show()
width = target.data("width")
nub = tip.children(".nub")
nubHeight = nub.outerHeight()
nubWidth = nub.outerWidth()
objPos = (obj, top, right, bottom, left, width) ->
obj.css(
top: top
bottom: bottom
left: left
right: right
"max-width": (if (width) then width else "auto")
).end()
objPos tip, (target.offset().top + target.outerHeight() + 10), "auto", "auto", target.offset().left, width
objPos nub, -nubHeight, "auto", "auto", 10
if $(window).width() < 767
if target.data("mobile-width")
tip.width(target.data("mobile-width")).css("left", 15).addClass "tip-override"
else
column = target.closest(".columns")
# if not using Foundation
column = $("body") if column.length < 0
if column.outerWidth()
tip.width(column.outerWidth() - 25).css("left", 15).addClass "tip-override"
else
tmp_width = Math.ceil($(window).width() * 0.9)
tip.width(tmp_width).css("left", 15).addClass "tip-override"
objPos nub, -nubHeight, "auto", "auto", target.offset().left
else
if classes and classes.indexOf("tip-top") > -1
objPos(tip, (target.offset().top - tip.outerHeight() - nubHeight), "auto", "auto", target.offset().left, width).removeClass "tip-override"
objPos nub, "auto", "auto", -nubHeight, "auto"
else if classes and classes.indexOf("tip-left") > -1
objPos(tip, (target.offset().top + (target.outerHeight() / 2) - nubHeight), "auto", "auto", (target.offset().left - tip.outerWidth() - 10), width).removeClass "tip-override"
objPos nub, (tip.outerHeight() / 2) - (nubHeight / 2), -nubHeight, "auto", "auto"
else if classes and classes.indexOf("tip-right") > -1
objPos(tip, (target.offset().top + (target.outerHeight() / 2) - nubHeight), "auto", "auto", (target.offset().left + target.outerWidth() + 10), width).removeClass "tip-override"
objPos nub, (tip.outerHeight() / 2) - (nubHeight / 2), "auto", "auto", -nubHeight
else if classes and classes.indexOf("tip-centered-top") > -1
objPos(tip, (target.offset().top - tip.outerHeight() - nubHeight), "auto", "auto", (target.offset().left + ((target.outerWidth() - tip.outerWidth()) / 2)), width).removeClass "tip-override"
objPos nub, "auto", ((tip.outerWidth() / 2) - (nubHeight / 2)), -nubHeight, "auto"
else if classes and classes.indexOf("tip-centered-bottom") > -1
objPos(tip, (target.offset().top + target.outerHeight() + 10), "auto", "auto", (target.offset().left + ((target.outerWidth() - tip.outerWidth()) / 2)), width).removeClass "tip-override"
objPos nub, -nubHeight, ((tip.outerWidth() / 2) - (nubHeight / 2)), "auto", "auto"
tip.css("visibility", "visible").hide()
inheritable_classes: (target) ->
inheritables = ["tip-top", "tip-left", "tip-bottom", "tip-right", "tip-centered-top", "tip-centered-bottom", "noradius"].concat(settings.additionalInheritableClasses)
classes = target.attr("class")
filtered = (if classes then $.map(classes.split(" "), (el, i) ->
el if $.inArray(el, inheritables) isnt -1
).join(" ") else "")
$.trim filtered
show: ($target) ->
$tip = methods.getTip($target)
methods.reposition $target, $tip, $target.attr("class")
$tip.fadeIn 150
hide: ($target) ->
$tip = methods.getTip($target)
$tip.fadeOut 150
reload: ->
$self = $(this)
(if ($self.data("tooltips")) then $self.Tooltips("destroy").Tooltips("init") else $self.Tooltips("init"))
destroy: ->
@each ->
$(window).off ".tooltip"
$(settings.selector).off ".tooltip"
$(settings.tooltipClass).each((i) ->
$($(settings.selector).get(i)).attr "title", $(this).text()
).remove()
$.fn.Tooltips = (method) ->
if methods[method]
methods[method].apply this, Array::slice.call(arguments, 1)
else if typeof method is "object" or not method
methods.init.apply this, arguments
else
$.error "Method " + method + " does not exist on jQuery.Tooltips"
) jQuery, this
| 171921 | ###
Inspired in foundation v.3.2
tooltips: tooltips.coffee
###
#
# * jQuery Foundation Tooltips 2.0.2
# * http://foundation.zurb.com
# * Copyright 2012, <NAME>
# * Free to use under the MIT license.
# * http://www.opensource.org/licenses/mit-license.php
#
#jslint unparam: true, browser: true, indent: 2
(($, window, undefined_) ->
"use strict"
settings =
bodyHeight: 0
selector: ".has-tip"
additionalInheritableClasses: []
tooltipClass: ".tooltip"
tipTemplate: (selector, content) ->
"<span data-selector=\"" + selector + "\" class=\"" + settings.tooltipClass.substring(1) + "\">" + content + "<span class=\"nub\"></span></span>"
methods =
init: (options) ->
settings = $.extend(settings, options)
# alias the old targetClass option
settings.selector = (if settings.targetClass then settings.targetClass else settings.selector)
@each ->
$body = $("body")
if Modernizr.touch
$body.on "click.tooltip touchstart.tooltip touchend.tooltip", settings.selector, (e) ->
e.preventDefault()
$(settings.tooltipClass).hide()
methods.showOrCreateTip $(this)
$body.on "click.tooltip touchstart.tooltip touchend.tooltip", settings.tooltipClass, (e) ->
e.preventDefault()
$(this).fadeOut 150
else
$body.on "mouseenter.tooltip mouseleave.tooltip", settings.selector, (e) ->
$this = $(this)
if e.type is "mouseenter"
methods.showOrCreateTip $this
else methods.hide $this if e.type is "mouseleave"
$(this).data "tooltips", true
showOrCreateTip: ($target, content) ->
$tip = methods.getTip($target)
if $tip and $tip.length > 0
methods.show $target
else
methods.create $target, content
getTip: ($target) ->
selector = methods.selector($target)
tip = null
tip = $("span[data-selector=" + selector + "]" + settings.tooltipClass) if selector
(if (tip.length > 0) then tip else false)
selector: ($target) ->
id = $target.attr("id")
dataSelector = $target.data("selector")
if id is `undefined` and dataSelector is `undefined`
dataSelector = "tooltip" + Math.random().toString(36).substring(7)
$target.attr "data-selector", dataSelector
(if (id) then id else dataSelector)
create: ($target, content) ->
$tip = $(settings.tipTemplate(methods.selector($target), $("<div>").html((if content then content else $target.attr("title"))).html()))
classes = methods.inheritable_classes($target)
$tip.addClass(classes).appendTo "body"
$tip.append "<span class=\"tap-to-close\">tap to close </span>" if Modernizr.touch
$target.removeAttr "title"
methods.show $target
reposition: (target, tip, classes) ->
width = undefined_
nub = undefined_
nubHeight = undefined_
nubWidth = undefined_
column = undefined_
objPos = undefined_
tip.css("visibility", "hidden").show()
width = target.data("width")
nub = tip.children(".nub")
nubHeight = nub.outerHeight()
nubWidth = nub.outerWidth()
objPos = (obj, top, right, bottom, left, width) ->
obj.css(
top: top
bottom: bottom
left: left
right: right
"max-width": (if (width) then width else "auto")
).end()
objPos tip, (target.offset().top + target.outerHeight() + 10), "auto", "auto", target.offset().left, width
objPos nub, -nubHeight, "auto", "auto", 10
if $(window).width() < 767
if target.data("mobile-width")
tip.width(target.data("mobile-width")).css("left", 15).addClass "tip-override"
else
column = target.closest(".columns")
# if not using Foundation
column = $("body") if column.length < 0
if column.outerWidth()
tip.width(column.outerWidth() - 25).css("left", 15).addClass "tip-override"
else
tmp_width = Math.ceil($(window).width() * 0.9)
tip.width(tmp_width).css("left", 15).addClass "tip-override"
objPos nub, -nubHeight, "auto", "auto", target.offset().left
else
if classes and classes.indexOf("tip-top") > -1
objPos(tip, (target.offset().top - tip.outerHeight() - nubHeight), "auto", "auto", target.offset().left, width).removeClass "tip-override"
objPos nub, "auto", "auto", -nubHeight, "auto"
else if classes and classes.indexOf("tip-left") > -1
objPos(tip, (target.offset().top + (target.outerHeight() / 2) - nubHeight), "auto", "auto", (target.offset().left - tip.outerWidth() - 10), width).removeClass "tip-override"
objPos nub, (tip.outerHeight() / 2) - (nubHeight / 2), -nubHeight, "auto", "auto"
else if classes and classes.indexOf("tip-right") > -1
objPos(tip, (target.offset().top + (target.outerHeight() / 2) - nubHeight), "auto", "auto", (target.offset().left + target.outerWidth() + 10), width).removeClass "tip-override"
objPos nub, (tip.outerHeight() / 2) - (nubHeight / 2), "auto", "auto", -nubHeight
else if classes and classes.indexOf("tip-centered-top") > -1
objPos(tip, (target.offset().top - tip.outerHeight() - nubHeight), "auto", "auto", (target.offset().left + ((target.outerWidth() - tip.outerWidth()) / 2)), width).removeClass "tip-override"
objPos nub, "auto", ((tip.outerWidth() / 2) - (nubHeight / 2)), -nubHeight, "auto"
else if classes and classes.indexOf("tip-centered-bottom") > -1
objPos(tip, (target.offset().top + target.outerHeight() + 10), "auto", "auto", (target.offset().left + ((target.outerWidth() - tip.outerWidth()) / 2)), width).removeClass "tip-override"
objPos nub, -nubHeight, ((tip.outerWidth() / 2) - (nubHeight / 2)), "auto", "auto"
tip.css("visibility", "visible").hide()
inheritable_classes: (target) ->
inheritables = ["tip-top", "tip-left", "tip-bottom", "tip-right", "tip-centered-top", "tip-centered-bottom", "noradius"].concat(settings.additionalInheritableClasses)
classes = target.attr("class")
filtered = (if classes then $.map(classes.split(" "), (el, i) ->
el if $.inArray(el, inheritables) isnt -1
).join(" ") else "")
$.trim filtered
show: ($target) ->
$tip = methods.getTip($target)
methods.reposition $target, $tip, $target.attr("class")
$tip.fadeIn 150
hide: ($target) ->
$tip = methods.getTip($target)
$tip.fadeOut 150
reload: ->
$self = $(this)
(if ($self.data("tooltips")) then $self.Tooltips("destroy").Tooltips("init") else $self.Tooltips("init"))
destroy: ->
@each ->
$(window).off ".tooltip"
$(settings.selector).off ".tooltip"
$(settings.tooltipClass).each((i) ->
$($(settings.selector).get(i)).attr "title", $(this).text()
).remove()
$.fn.Tooltips = (method) ->
if methods[method]
methods[method].apply this, Array::slice.call(arguments, 1)
else if typeof method is "object" or not method
methods.init.apply this, arguments
else
$.error "Method " + method + " does not exist on jQuery.Tooltips"
) jQuery, this
| true | ###
Inspired in foundation v.3.2
tooltips: tooltips.coffee
###
#
# * jQuery Foundation Tooltips 2.0.2
# * http://foundation.zurb.com
# * Copyright 2012, PI:NAME:<NAME>END_PI
# * Free to use under the MIT license.
# * http://www.opensource.org/licenses/mit-license.php
#
#jslint unparam: true, browser: true, indent: 2
(($, window, undefined_) ->
"use strict"
settings =
bodyHeight: 0
selector: ".has-tip"
additionalInheritableClasses: []
tooltipClass: ".tooltip"
tipTemplate: (selector, content) ->
"<span data-selector=\"" + selector + "\" class=\"" + settings.tooltipClass.substring(1) + "\">" + content + "<span class=\"nub\"></span></span>"
methods =
init: (options) ->
settings = $.extend(settings, options)
# alias the old targetClass option
settings.selector = (if settings.targetClass then settings.targetClass else settings.selector)
@each ->
$body = $("body")
if Modernizr.touch
$body.on "click.tooltip touchstart.tooltip touchend.tooltip", settings.selector, (e) ->
e.preventDefault()
$(settings.tooltipClass).hide()
methods.showOrCreateTip $(this)
$body.on "click.tooltip touchstart.tooltip touchend.tooltip", settings.tooltipClass, (e) ->
e.preventDefault()
$(this).fadeOut 150
else
$body.on "mouseenter.tooltip mouseleave.tooltip", settings.selector, (e) ->
$this = $(this)
if e.type is "mouseenter"
methods.showOrCreateTip $this
else methods.hide $this if e.type is "mouseleave"
$(this).data "tooltips", true
showOrCreateTip: ($target, content) ->
$tip = methods.getTip($target)
if $tip and $tip.length > 0
methods.show $target
else
methods.create $target, content
getTip: ($target) ->
selector = methods.selector($target)
tip = null
tip = $("span[data-selector=" + selector + "]" + settings.tooltipClass) if selector
(if (tip.length > 0) then tip else false)
selector: ($target) ->
id = $target.attr("id")
dataSelector = $target.data("selector")
if id is `undefined` and dataSelector is `undefined`
dataSelector = "tooltip" + Math.random().toString(36).substring(7)
$target.attr "data-selector", dataSelector
(if (id) then id else dataSelector)
create: ($target, content) ->
$tip = $(settings.tipTemplate(methods.selector($target), $("<div>").html((if content then content else $target.attr("title"))).html()))
classes = methods.inheritable_classes($target)
$tip.addClass(classes).appendTo "body"
$tip.append "<span class=\"tap-to-close\">tap to close </span>" if Modernizr.touch
$target.removeAttr "title"
methods.show $target
reposition: (target, tip, classes) ->
width = undefined_
nub = undefined_
nubHeight = undefined_
nubWidth = undefined_
column = undefined_
objPos = undefined_
tip.css("visibility", "hidden").show()
width = target.data("width")
nub = tip.children(".nub")
nubHeight = nub.outerHeight()
nubWidth = nub.outerWidth()
objPos = (obj, top, right, bottom, left, width) ->
obj.css(
top: top
bottom: bottom
left: left
right: right
"max-width": (if (width) then width else "auto")
).end()
objPos tip, (target.offset().top + target.outerHeight() + 10), "auto", "auto", target.offset().left, width
objPos nub, -nubHeight, "auto", "auto", 10
if $(window).width() < 767
if target.data("mobile-width")
tip.width(target.data("mobile-width")).css("left", 15).addClass "tip-override"
else
column = target.closest(".columns")
# if not using Foundation
column = $("body") if column.length < 0
if column.outerWidth()
tip.width(column.outerWidth() - 25).css("left", 15).addClass "tip-override"
else
tmp_width = Math.ceil($(window).width() * 0.9)
tip.width(tmp_width).css("left", 15).addClass "tip-override"
objPos nub, -nubHeight, "auto", "auto", target.offset().left
else
if classes and classes.indexOf("tip-top") > -1
objPos(tip, (target.offset().top - tip.outerHeight() - nubHeight), "auto", "auto", target.offset().left, width).removeClass "tip-override"
objPos nub, "auto", "auto", -nubHeight, "auto"
else if classes and classes.indexOf("tip-left") > -1
objPos(tip, (target.offset().top + (target.outerHeight() / 2) - nubHeight), "auto", "auto", (target.offset().left - tip.outerWidth() - 10), width).removeClass "tip-override"
objPos nub, (tip.outerHeight() / 2) - (nubHeight / 2), -nubHeight, "auto", "auto"
else if classes and classes.indexOf("tip-right") > -1
objPos(tip, (target.offset().top + (target.outerHeight() / 2) - nubHeight), "auto", "auto", (target.offset().left + target.outerWidth() + 10), width).removeClass "tip-override"
objPos nub, (tip.outerHeight() / 2) - (nubHeight / 2), "auto", "auto", -nubHeight
else if classes and classes.indexOf("tip-centered-top") > -1
objPos(tip, (target.offset().top - tip.outerHeight() - nubHeight), "auto", "auto", (target.offset().left + ((target.outerWidth() - tip.outerWidth()) / 2)), width).removeClass "tip-override"
objPos nub, "auto", ((tip.outerWidth() / 2) - (nubHeight / 2)), -nubHeight, "auto"
else if classes and classes.indexOf("tip-centered-bottom") > -1
objPos(tip, (target.offset().top + target.outerHeight() + 10), "auto", "auto", (target.offset().left + ((target.outerWidth() - tip.outerWidth()) / 2)), width).removeClass "tip-override"
objPos nub, -nubHeight, ((tip.outerWidth() / 2) - (nubHeight / 2)), "auto", "auto"
tip.css("visibility", "visible").hide()
inheritable_classes: (target) ->
inheritables = ["tip-top", "tip-left", "tip-bottom", "tip-right", "tip-centered-top", "tip-centered-bottom", "noradius"].concat(settings.additionalInheritableClasses)
classes = target.attr("class")
filtered = (if classes then $.map(classes.split(" "), (el, i) ->
el if $.inArray(el, inheritables) isnt -1
).join(" ") else "")
$.trim filtered
show: ($target) ->
$tip = methods.getTip($target)
methods.reposition $target, $tip, $target.attr("class")
$tip.fadeIn 150
hide: ($target) ->
$tip = methods.getTip($target)
$tip.fadeOut 150
reload: ->
$self = $(this)
(if ($self.data("tooltips")) then $self.Tooltips("destroy").Tooltips("init") else $self.Tooltips("init"))
destroy: ->
@each ->
$(window).off ".tooltip"
$(settings.selector).off ".tooltip"
$(settings.tooltipClass).each((i) ->
$($(settings.selector).get(i)).attr "title", $(this).text()
).remove()
$.fn.Tooltips = (method) ->
if methods[method]
methods[method].apply this, Array::slice.call(arguments, 1)
else if typeof method is "object" or not method
methods.init.apply this, arguments
else
$.error "Method " + method + " does not exist on jQuery.Tooltips"
) jQuery, this
|
[
{
"context": ".env.MAIL_URL = 'smtp://postmaster%40tiegushi.com:a7e104e236965118d8f1bd3268f36d8c@smtp.mailgun.org:587'\n #process.env.MAIL_URL = 'smtp://postma",
"end": 264,
"score": 0.9988725781440735,
"start": 215,
"tag": "EMAIL",
"value": "a7e104e236965118d8f1bd3268f36d8c@smtp.mailgu... | hotShareWeb/server/test_email_url.coffee | fay1986/mobile_app_server | 4 |
if Meteor.isServer
Meteor.startup ()->
if (not process.env.MAIL_URL) or process.env.MAIL_URL is ''
console.log "----setup smtp server---"
process.env.MAIL_URL = 'smtp://postmaster%40tiegushi.com:a7e104e236965118d8f1bd3268f36d8c@smtp.mailgun.org:587'
#process.env.MAIL_URL = 'smtp://postmaster%40email.tiegushi.com:1b3e27a9f18007d6fedf46c9faed519a@smtp.mailgun.org:587'
#process.env.MAIL_URL = 'smtp://notify%40mail.tiegushi.com:Actiontec753951@smtpdm.aliyun.com:465'
| 2869 |
if Meteor.isServer
Meteor.startup ()->
if (not process.env.MAIL_URL) or process.env.MAIL_URL is ''
console.log "----setup smtp server---"
process.env.MAIL_URL = 'smtp://postmaster%40tiegushi.com:<EMAIL>:587'
#process.env.MAIL_URL = 'smtp://postmaster%40email.tiegushi.com:<EMAIL>:587'
#process.env.MAIL_URL = 'smtp://notify%40mail.tiegushi.com:<EMAIL>39<EMAIL>:465'
| true |
if Meteor.isServer
Meteor.startup ()->
if (not process.env.MAIL_URL) or process.env.MAIL_URL is ''
console.log "----setup smtp server---"
process.env.MAIL_URL = 'smtp://postmaster%40tiegushi.com:PI:EMAIL:<EMAIL>END_PI:587'
#process.env.MAIL_URL = 'smtp://postmaster%40email.tiegushi.com:PI:EMAIL:<EMAIL>END_PI:587'
#process.env.MAIL_URL = 'smtp://notify%40mail.tiegushi.com:PI:EMAIL:<EMAIL>END_PI39PI:EMAIL:<EMAIL>END_PI:465'
|
[
{
"context": "Enforce <marquee> elements are not used.\n# @author Ethan Cohen\n###\n\n# ------------------------------------------",
"end": 107,
"score": 0.9998591542243958,
"start": 96,
"tag": "NAME",
"value": "Ethan Cohen"
}
] | src/tests/rules/accessible-emoji.coffee | danielbayley/eslint-plugin-coffee | 21 | ### eslint-env jest ###
###*
# @fileoverview Enforce <marquee> elements are not used.
# @author Ethan Cohen
###
# -----------------------------------------------------------------------------
# Requirements
# -----------------------------------------------------------------------------
path = require 'path'
{RuleTester} = require 'eslint'
{
default: parserOptionsMapper
} = require '../eslint-plugin-jsx-a11y-parser-options-mapper'
rule = require 'eslint-plugin-jsx-a11y/lib/rules/accessible-emoji'
# -----------------------------------------------------------------------------
# Tests
# -----------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
expectedError =
message:
'Emojis should be wrapped in <span>, have role="img", and have an accessible description with aria-label or aria-labelledby.'
type: 'JSXOpeningElement'
ruleTester.run 'accessible-emoji', rule,
valid: [
code: '<div />'
,
code: '<span />'
,
code: '<span>No emoji here!</span>'
,
code: '<span role="img" aria-label="Panda face">🐼</span>'
,
code: '<span role="img" aria-label="Snowman">☃</span>'
,
code: '<span role="img" aria-labelledby="id1">🐼</span>'
,
code: '<span role="img" aria-labelledby="id1">☃</span>'
,
code:
'<span role="img" aria-labelledby="id1" aria-label="Snowman">☃</span>'
,
code: '<span>{props.emoji}</span>'
,
code: '<span aria-hidden>{props.emoji}</span>'
,
code: '<span aria-hidden="true">🐼</span>'
,
code: '<span aria-hidden>🐼</span>'
,
code: '<div aria-hidden="true">🐼</div>'
].map parserOptionsMapper
invalid: [
code: '<span>🐼</span>', errors: [expectedError]
,
code: '<span>foo🐼bar</span>', errors: [expectedError]
,
code: '<span>foo 🐼 bar</span>', errors: [expectedError]
,
code: '<i role="img" aria-label="Panda face">🐼</i>'
errors: [expectedError]
,
code: '<i role="img" aria-labelledby="id1">🐼</i>', errors: [expectedError]
,
code: '<Foo>🐼</Foo>', errors: [expectedError]
,
code: '<span aria-hidden="false">🐼</span>', errors: [expectedError]
].map parserOptionsMapper
| 131972 | ### eslint-env jest ###
###*
# @fileoverview Enforce <marquee> elements are not used.
# @author <NAME>
###
# -----------------------------------------------------------------------------
# Requirements
# -----------------------------------------------------------------------------
path = require 'path'
{RuleTester} = require 'eslint'
{
default: parserOptionsMapper
} = require '../eslint-plugin-jsx-a11y-parser-options-mapper'
rule = require 'eslint-plugin-jsx-a11y/lib/rules/accessible-emoji'
# -----------------------------------------------------------------------------
# Tests
# -----------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
expectedError =
message:
'Emojis should be wrapped in <span>, have role="img", and have an accessible description with aria-label or aria-labelledby.'
type: 'JSXOpeningElement'
ruleTester.run 'accessible-emoji', rule,
valid: [
code: '<div />'
,
code: '<span />'
,
code: '<span>No emoji here!</span>'
,
code: '<span role="img" aria-label="Panda face">🐼</span>'
,
code: '<span role="img" aria-label="Snowman">☃</span>'
,
code: '<span role="img" aria-labelledby="id1">🐼</span>'
,
code: '<span role="img" aria-labelledby="id1">☃</span>'
,
code:
'<span role="img" aria-labelledby="id1" aria-label="Snowman">☃</span>'
,
code: '<span>{props.emoji}</span>'
,
code: '<span aria-hidden>{props.emoji}</span>'
,
code: '<span aria-hidden="true">🐼</span>'
,
code: '<span aria-hidden>🐼</span>'
,
code: '<div aria-hidden="true">🐼</div>'
].map parserOptionsMapper
invalid: [
code: '<span>🐼</span>', errors: [expectedError]
,
code: '<span>foo🐼bar</span>', errors: [expectedError]
,
code: '<span>foo 🐼 bar</span>', errors: [expectedError]
,
code: '<i role="img" aria-label="Panda face">🐼</i>'
errors: [expectedError]
,
code: '<i role="img" aria-labelledby="id1">🐼</i>', errors: [expectedError]
,
code: '<Foo>🐼</Foo>', errors: [expectedError]
,
code: '<span aria-hidden="false">🐼</span>', errors: [expectedError]
].map parserOptionsMapper
| true | ### eslint-env jest ###
###*
# @fileoverview Enforce <marquee> elements are not used.
# @author PI:NAME:<NAME>END_PI
###
# -----------------------------------------------------------------------------
# Requirements
# -----------------------------------------------------------------------------
path = require 'path'
{RuleTester} = require 'eslint'
{
default: parserOptionsMapper
} = require '../eslint-plugin-jsx-a11y-parser-options-mapper'
rule = require 'eslint-plugin-jsx-a11y/lib/rules/accessible-emoji'
# -----------------------------------------------------------------------------
# Tests
# -----------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
expectedError =
message:
'Emojis should be wrapped in <span>, have role="img", and have an accessible description with aria-label or aria-labelledby.'
type: 'JSXOpeningElement'
ruleTester.run 'accessible-emoji', rule,
valid: [
code: '<div />'
,
code: '<span />'
,
code: '<span>No emoji here!</span>'
,
code: '<span role="img" aria-label="Panda face">🐼</span>'
,
code: '<span role="img" aria-label="Snowman">☃</span>'
,
code: '<span role="img" aria-labelledby="id1">🐼</span>'
,
code: '<span role="img" aria-labelledby="id1">☃</span>'
,
code:
'<span role="img" aria-labelledby="id1" aria-label="Snowman">☃</span>'
,
code: '<span>{props.emoji}</span>'
,
code: '<span aria-hidden>{props.emoji}</span>'
,
code: '<span aria-hidden="true">🐼</span>'
,
code: '<span aria-hidden>🐼</span>'
,
code: '<div aria-hidden="true">🐼</div>'
].map parserOptionsMapper
invalid: [
code: '<span>🐼</span>', errors: [expectedError]
,
code: '<span>foo🐼bar</span>', errors: [expectedError]
,
code: '<span>foo 🐼 bar</span>', errors: [expectedError]
,
code: '<i role="img" aria-label="Panda face">🐼</i>'
errors: [expectedError]
,
code: '<i role="img" aria-labelledby="id1">🐼</i>', errors: [expectedError]
,
code: '<Foo>🐼</Foo>', errors: [expectedError]
,
code: '<span aria-hidden="false">🐼</span>', errors: [expectedError]
].map parserOptionsMapper
|
[
{
"context": "#############\n#\n#\tMoocita collections\n# Created by Markus on 26/10/2015.\n#\n################################",
"end": 99,
"score": 0.9991944432258606,
"start": 93,
"tag": "NAME",
"value": "Markus"
}
] | server/publications/reviews.coffee | agottschalk10/worklearn | 0 | #######################################################
#
# Moocita collections
# Created by Markus on 26/10/2015.
#
#######################################################
#######################################################
# item header
#######################################################
#######################################################
_review_fields =
fields:
rating: 1
content: 1
owner_id: 1
published: 1
parent_id: 1
solution_id: 1
challenge_id: 1
#######################################################
# reviews
#######################################################
#######################################################
Meteor.publish "my_reviews", () ->
user_id = this.userId
restrict =
owner_id: user_id
filter = filter_visible_documents user_id, restrict
crs = Reviews.find filter, _review_fields
log_publication "Reviews", crs, filter,
_review_fields, "my_reviews", user_id
return crs
#######################################################
Meteor.publish "my_review_by_id", (review_id) ->
check review_id, String
user_id = this.userId
restrict =
_id: review_id
owner_id: user_id
filter = filter_visible_documents user_id, restrict
crs = Reviews.find filter, _review_fields
log_publication "Reviews", crs, filter,
_review_fields, "my_review_by_id", user_id
return crs
#######################################################
Meteor.publish "my_reviews_by_challenge_id", (challenge_id) ->
check challenge_id, String
user_id = this.userId
filter =
challenge_id: challenge_id
owner_id: user_id
crs = Reviews.find filter, _review_fields
log_publication "Reviews", crs, filter,
_review_fields, "reviews_by_solution_id", user_id
return crs
#######################################################
Meteor.publish "reviews_by_solution_id", (solution_id) ->
check solution_id, String
user_id = this.userId
filter =
solution_id: solution_id
published: true
crs = Reviews.find filter, _review_fields
log_publication "Reviews", crs, filter,
_review_fields, "reviews_by_solution_id", user_id
return crs
| 44575 | #######################################################
#
# Moocita collections
# Created by <NAME> on 26/10/2015.
#
#######################################################
#######################################################
# item header
#######################################################
#######################################################
_review_fields =
fields:
rating: 1
content: 1
owner_id: 1
published: 1
parent_id: 1
solution_id: 1
challenge_id: 1
#######################################################
# reviews
#######################################################
#######################################################
Meteor.publish "my_reviews", () ->
user_id = this.userId
restrict =
owner_id: user_id
filter = filter_visible_documents user_id, restrict
crs = Reviews.find filter, _review_fields
log_publication "Reviews", crs, filter,
_review_fields, "my_reviews", user_id
return crs
#######################################################
Meteor.publish "my_review_by_id", (review_id) ->
check review_id, String
user_id = this.userId
restrict =
_id: review_id
owner_id: user_id
filter = filter_visible_documents user_id, restrict
crs = Reviews.find filter, _review_fields
log_publication "Reviews", crs, filter,
_review_fields, "my_review_by_id", user_id
return crs
#######################################################
Meteor.publish "my_reviews_by_challenge_id", (challenge_id) ->
check challenge_id, String
user_id = this.userId
filter =
challenge_id: challenge_id
owner_id: user_id
crs = Reviews.find filter, _review_fields
log_publication "Reviews", crs, filter,
_review_fields, "reviews_by_solution_id", user_id
return crs
#######################################################
Meteor.publish "reviews_by_solution_id", (solution_id) ->
check solution_id, String
user_id = this.userId
filter =
solution_id: solution_id
published: true
crs = Reviews.find filter, _review_fields
log_publication "Reviews", crs, filter,
_review_fields, "reviews_by_solution_id", user_id
return crs
| true | #######################################################
#
# Moocita collections
# Created by PI:NAME:<NAME>END_PI on 26/10/2015.
#
#######################################################
#######################################################
# item header
#######################################################
#######################################################
_review_fields =
fields:
rating: 1
content: 1
owner_id: 1
published: 1
parent_id: 1
solution_id: 1
challenge_id: 1
#######################################################
# reviews
#######################################################
#######################################################
Meteor.publish "my_reviews", () ->
user_id = this.userId
restrict =
owner_id: user_id
filter = filter_visible_documents user_id, restrict
crs = Reviews.find filter, _review_fields
log_publication "Reviews", crs, filter,
_review_fields, "my_reviews", user_id
return crs
#######################################################
Meteor.publish "my_review_by_id", (review_id) ->
check review_id, String
user_id = this.userId
restrict =
_id: review_id
owner_id: user_id
filter = filter_visible_documents user_id, restrict
crs = Reviews.find filter, _review_fields
log_publication "Reviews", crs, filter,
_review_fields, "my_review_by_id", user_id
return crs
#######################################################
Meteor.publish "my_reviews_by_challenge_id", (challenge_id) ->
check challenge_id, String
user_id = this.userId
filter =
challenge_id: challenge_id
owner_id: user_id
crs = Reviews.find filter, _review_fields
log_publication "Reviews", crs, filter,
_review_fields, "reviews_by_solution_id", user_id
return crs
#######################################################
Meteor.publish "reviews_by_solution_id", (solution_id) ->
check solution_id, String
user_id = this.userId
filter =
solution_id: solution_id
published: true
crs = Reviews.find filter, _review_fields
log_publication "Reviews", crs, filter,
_review_fields, "reviews_by_solution_id", user_id
return crs
|
[
{
"context": " :\n name : 'Koding'\n link : 'https://koding.com",
"end": 2986,
"score": 0.9903290867805481,
"start": 2980,
"tag": "NAME",
"value": "Koding"
},
{
"context": "rname :\n label : 'U... | client/app/lib/providers/config.coffee | lionheart1022/koding | 0 | globals = require 'globals'
isProd = globals.config.environment is 'production'
baseURL = globals.config.domains.base
module.exports = globals.config.providers =
custom :
name : 'Custom'
link : "https://#{baseURL}"
title : 'Custom Credential'
color : '#b9c0b8'
description : '''Custom credentials can include meta
credentials for any service'''
listText : """
You're currently using these custom data in your
stack templates, you can change their contents
without touching stack templates.
"""
credentialFields :
credential :
label : 'Credential'
placeholder : 'credential in JSON format'
type : 'textarea'
aws :
name : 'Amazon Web Services'
link : 'https://aws.amazon.com'
title : 'AWS'
color : '#F9A900'
description : 'Amazon Web Services'
advancedFields : [
'subnet', 'sg', 'vpc',
'ami', 'acl', 'cidr_block',
'igw', 'rtb'
]
credentialFields :
access_key :
label : 'Access Key ID'
placeholder : 'aws access key'
attributes :
autocomplete : if isProd then 'off' else 'on'
secret_key :
label : 'Secret Access Key'
placeholder : 'aws secret key'
attributes :
autocomplete : if isProd then 'off' else 'on'
region :
label : 'Region'
type : 'selection'
placeholder : 'Region'
defaultValue : 'us-east-1'
values : [
{ title: 'US East (N. Virginia) (us-east-1)', value: 'us-east-1' }
{ title: 'US West (Oregon) (us-west-2)', value: 'us-west-2' }
{ title: 'US West (N. California) (us-west-1)', value: 'us-west-1' }
{ title: 'EU (Ireland) (eu-west-1)', value: 'eu-west-1' }
{ title: 'EU (Frankfurt) (eu-central-1)', value: 'eu-central-1' }
{ title: 'Asia Pacific (Singapore) (ap-southeast-1)', value: 'ap-southeast-1' }
{ title: 'Asia Pacific (Sydney) (ap-southeast-2)', value: 'ap-southeast-2' }
{ title: 'Asia Pacific (Tokyo) (ap-northeast-1)', value: 'ap-northeast-1' }
{ title: 'South America (Sao Paulo) (sa-east-1)', value: 'sa-east-1' }
]
koding :
name : 'Koding'
link : 'https://koding.com'
title : 'Koding'
color : '#50c157'
description : 'Koding rulez.'
credentialFields : {}
managed :
name : 'Managed VMs'
link : "https://#{baseURL}"
title : 'Managed VM'
color : '#6d119e'
description : 'Use your power.'
credentialFields : {}
google :
name : 'Google Compute Engine'
link : 'https://cloud.google.com/products/compute-engine/'
title : 'Google Cloud'
color : '#357e99'
description : 'Google compute engine'
credentialFields :
projectId :
label : 'Project Id'
placeholder : 'project id in gce'
clientSecretsContent :
label : 'Secrets'
placeholder : 'content of the client_secrets.xxxxx.json'
type : 'textarea'
privateKeyContent :
label : 'Private Key'
placeholder : 'content of the xxxxx-privatekey.pem'
type : 'textarea'
# zone :
# label : "Zone"
# placeholder : "google zone"
# defaultValue : "us-central1-a"
azure :
name : 'Azure'
link : 'https://azure.microsoft.com/'
title : 'Azure'
color : '#ec06be'
description : 'Azure'
credentialFields :
accountId :
label : 'Account Id'
placeholder : 'account id in azure'
secret :
label : 'Secret'
placeholder : 'azure secret'
type : 'password'
digitalocean :
name : 'Digital Ocean'
link : 'https://digitalocean.com'
title : 'Digitalocean'
color : '#7abad7'
description : 'Digitalocean droplets'
credentialFields :
clientId :
label : 'Client Id'
placeholder : 'client id in digitalocean'
apiKey :
label : 'API Key'
placeholder : 'digitalocean api key'
rackspace :
name : 'Rackspace'
link : 'http://www.rackspace.com'
title : 'Rackspace'
color : '#d8deea'
description : 'Rackspace machines'
credentialFields :
username :
label : 'Username'
placeholder : 'username for rackspace'
apiKey :
label : 'API Key'
placeholder : 'rackspace api key'
softlayer :
name : 'Softlayer'
link : 'http://www.softlayer.com'
title : 'Softlayer'
color : '#B52025'
description : 'Softlayer resources'
credentialFields :
username :
label : 'Username'
placeholder : 'username for softlayer'
api_key :
label : 'API Key'
placeholder : 'softlayer api key'
userInput :
name : 'User Input'
title : 'User Input'
listText : '''
Here you can change user input fields that you define
in your stack scripts. When you delete these,
make sure that you update the stack scripts that
these are used in. Otherwise you may experience
unwanted results while building your stacks.
'''
credentialFields : {}
vagrant :
name : 'Vagrant'
link : 'http://www.vagrantup.com'
title : 'Vagrant on Local'
color : '#B52025'
description : 'Local provisioning with Vagrant'
credentialFields :
queryString :
label : 'Kite ID'
placeholder : 'ID for my local machine kite'
| 190430 | globals = require 'globals'
isProd = globals.config.environment is 'production'
baseURL = globals.config.domains.base
module.exports = globals.config.providers =
custom :
name : 'Custom'
link : "https://#{baseURL}"
title : 'Custom Credential'
color : '#b9c0b8'
description : '''Custom credentials can include meta
credentials for any service'''
listText : """
You're currently using these custom data in your
stack templates, you can change their contents
without touching stack templates.
"""
credentialFields :
credential :
label : 'Credential'
placeholder : 'credential in JSON format'
type : 'textarea'
aws :
name : 'Amazon Web Services'
link : 'https://aws.amazon.com'
title : 'AWS'
color : '#F9A900'
description : 'Amazon Web Services'
advancedFields : [
'subnet', 'sg', 'vpc',
'ami', 'acl', 'cidr_block',
'igw', 'rtb'
]
credentialFields :
access_key :
label : 'Access Key ID'
placeholder : 'aws access key'
attributes :
autocomplete : if isProd then 'off' else 'on'
secret_key :
label : 'Secret Access Key'
placeholder : 'aws secret key'
attributes :
autocomplete : if isProd then 'off' else 'on'
region :
label : 'Region'
type : 'selection'
placeholder : 'Region'
defaultValue : 'us-east-1'
values : [
{ title: 'US East (N. Virginia) (us-east-1)', value: 'us-east-1' }
{ title: 'US West (Oregon) (us-west-2)', value: 'us-west-2' }
{ title: 'US West (N. California) (us-west-1)', value: 'us-west-1' }
{ title: 'EU (Ireland) (eu-west-1)', value: 'eu-west-1' }
{ title: 'EU (Frankfurt) (eu-central-1)', value: 'eu-central-1' }
{ title: 'Asia Pacific (Singapore) (ap-southeast-1)', value: 'ap-southeast-1' }
{ title: 'Asia Pacific (Sydney) (ap-southeast-2)', value: 'ap-southeast-2' }
{ title: 'Asia Pacific (Tokyo) (ap-northeast-1)', value: 'ap-northeast-1' }
{ title: 'South America (Sao Paulo) (sa-east-1)', value: 'sa-east-1' }
]
koding :
name : '<NAME>'
link : 'https://koding.com'
title : 'Koding'
color : '#50c157'
description : 'Koding rulez.'
credentialFields : {}
managed :
name : 'Managed VMs'
link : "https://#{baseURL}"
title : 'Managed VM'
color : '#6d119e'
description : 'Use your power.'
credentialFields : {}
google :
name : 'Google Compute Engine'
link : 'https://cloud.google.com/products/compute-engine/'
title : 'Google Cloud'
color : '#357e99'
description : 'Google compute engine'
credentialFields :
projectId :
label : 'Project Id'
placeholder : 'project id in gce'
clientSecretsContent :
label : 'Secrets'
placeholder : 'content of the client_secrets.xxxxx.json'
type : 'textarea'
privateKeyContent :
label : 'Private Key'
placeholder : 'content of the xxxxx-privatekey.pem'
type : 'textarea'
# zone :
# label : "Zone"
# placeholder : "google zone"
# defaultValue : "us-central1-a"
azure :
name : 'Azure'
link : 'https://azure.microsoft.com/'
title : 'Azure'
color : '#ec06be'
description : 'Azure'
credentialFields :
accountId :
label : 'Account Id'
placeholder : 'account id in azure'
secret :
label : 'Secret'
placeholder : 'azure secret'
type : 'password'
digitalocean :
name : 'Digital Ocean'
link : 'https://digitalocean.com'
title : 'Digitalocean'
color : '#7abad7'
description : 'Digitalocean droplets'
credentialFields :
clientId :
label : 'Client Id'
placeholder : 'client id in digitalocean'
apiKey :
label : 'API Key'
placeholder : 'digitalocean api key'
rackspace :
name : 'Rackspace'
link : 'http://www.rackspace.com'
title : 'Rackspace'
color : '#d8deea'
description : 'Rackspace machines'
credentialFields :
username :
label : 'Username'
placeholder : 'username for rackspace'
apiKey :
label : 'API Key'
placeholder : 'rackspace api key'
softlayer :
name : 'Softlayer'
link : 'http://www.softlayer.com'
title : 'Softlayer'
color : '#B52025'
description : 'Softlayer resources'
credentialFields :
username :
label : 'Username'
placeholder : 'username for softlayer'
api_key :
label : 'API Key'
placeholder : 'softlayer api key'
userInput :
name : 'User Input'
title : 'User Input'
listText : '''
Here you can change user input fields that you define
in your stack scripts. When you delete these,
make sure that you update the stack scripts that
these are used in. Otherwise you may experience
unwanted results while building your stacks.
'''
credentialFields : {}
vagrant :
name : 'Vagrant'
link : 'http://www.vagrantup.com'
title : 'Vagrant on Local'
color : '#B52025'
description : 'Local provisioning with Vagrant'
credentialFields :
queryString :
label : 'Kite ID'
placeholder : 'ID for my local machine kite'
| true | globals = require 'globals'
isProd = globals.config.environment is 'production'
baseURL = globals.config.domains.base
module.exports = globals.config.providers =
custom :
name : 'Custom'
link : "https://#{baseURL}"
title : 'Custom Credential'
color : '#b9c0b8'
description : '''Custom credentials can include meta
credentials for any service'''
listText : """
You're currently using these custom data in your
stack templates, you can change their contents
without touching stack templates.
"""
credentialFields :
credential :
label : 'Credential'
placeholder : 'credential in JSON format'
type : 'textarea'
aws :
name : 'Amazon Web Services'
link : 'https://aws.amazon.com'
title : 'AWS'
color : '#F9A900'
description : 'Amazon Web Services'
advancedFields : [
'subnet', 'sg', 'vpc',
'ami', 'acl', 'cidr_block',
'igw', 'rtb'
]
credentialFields :
access_key :
label : 'Access Key ID'
placeholder : 'aws access key'
attributes :
autocomplete : if isProd then 'off' else 'on'
secret_key :
label : 'Secret Access Key'
placeholder : 'aws secret key'
attributes :
autocomplete : if isProd then 'off' else 'on'
region :
label : 'Region'
type : 'selection'
placeholder : 'Region'
defaultValue : 'us-east-1'
values : [
{ title: 'US East (N. Virginia) (us-east-1)', value: 'us-east-1' }
{ title: 'US West (Oregon) (us-west-2)', value: 'us-west-2' }
{ title: 'US West (N. California) (us-west-1)', value: 'us-west-1' }
{ title: 'EU (Ireland) (eu-west-1)', value: 'eu-west-1' }
{ title: 'EU (Frankfurt) (eu-central-1)', value: 'eu-central-1' }
{ title: 'Asia Pacific (Singapore) (ap-southeast-1)', value: 'ap-southeast-1' }
{ title: 'Asia Pacific (Sydney) (ap-southeast-2)', value: 'ap-southeast-2' }
{ title: 'Asia Pacific (Tokyo) (ap-northeast-1)', value: 'ap-northeast-1' }
{ title: 'South America (Sao Paulo) (sa-east-1)', value: 'sa-east-1' }
]
koding :
name : 'PI:NAME:<NAME>END_PI'
link : 'https://koding.com'
title : 'Koding'
color : '#50c157'
description : 'Koding rulez.'
credentialFields : {}
managed :
name : 'Managed VMs'
link : "https://#{baseURL}"
title : 'Managed VM'
color : '#6d119e'
description : 'Use your power.'
credentialFields : {}
google :
name : 'Google Compute Engine'
link : 'https://cloud.google.com/products/compute-engine/'
title : 'Google Cloud'
color : '#357e99'
description : 'Google compute engine'
credentialFields :
projectId :
label : 'Project Id'
placeholder : 'project id in gce'
clientSecretsContent :
label : 'Secrets'
placeholder : 'content of the client_secrets.xxxxx.json'
type : 'textarea'
privateKeyContent :
label : 'Private Key'
placeholder : 'content of the xxxxx-privatekey.pem'
type : 'textarea'
# zone :
# label : "Zone"
# placeholder : "google zone"
# defaultValue : "us-central1-a"
azure :
name : 'Azure'
link : 'https://azure.microsoft.com/'
title : 'Azure'
color : '#ec06be'
description : 'Azure'
credentialFields :
accountId :
label : 'Account Id'
placeholder : 'account id in azure'
secret :
label : 'Secret'
placeholder : 'azure secret'
type : 'password'
digitalocean :
name : 'Digital Ocean'
link : 'https://digitalocean.com'
title : 'Digitalocean'
color : '#7abad7'
description : 'Digitalocean droplets'
credentialFields :
clientId :
label : 'Client Id'
placeholder : 'client id in digitalocean'
apiKey :
label : 'API Key'
placeholder : 'digitalocean api key'
rackspace :
name : 'Rackspace'
link : 'http://www.rackspace.com'
title : 'Rackspace'
color : '#d8deea'
description : 'Rackspace machines'
credentialFields :
username :
label : 'Username'
placeholder : 'username for rackspace'
apiKey :
label : 'API Key'
placeholder : 'rackspace api key'
softlayer :
name : 'Softlayer'
link : 'http://www.softlayer.com'
title : 'Softlayer'
color : '#B52025'
description : 'Softlayer resources'
credentialFields :
username :
label : 'Username'
placeholder : 'username for softlayer'
api_key :
label : 'API Key'
placeholder : 'softlayer api key'
userInput :
name : 'User Input'
title : 'User Input'
listText : '''
Here you can change user input fields that you define
in your stack scripts. When you delete these,
make sure that you update the stack scripts that
these are used in. Otherwise you may experience
unwanted results while building your stacks.
'''
credentialFields : {}
vagrant :
name : 'Vagrant'
link : 'http://www.vagrantup.com'
title : 'Vagrant on Local'
color : '#B52025'
description : 'Local provisioning with Vagrant'
credentialFields :
queryString :
label : 'Kite ID'
placeholder : 'ID for my local machine kite'
|
[
{
"context": "cense.\n###\n\n###*\n@module joukou-api/routes\n@author Isaac Johnston <isaac.johnston@joukou.com>\n@author Juan Morales ",
"end": 626,
"score": 0.9998781085014343,
"start": 612,
"tag": "NAME",
"value": "Isaac Johnston"
},
{
"context": "@module joukou-api/routes\n@autho... | src/routes.coffee | joukou/joukou-api | 0 | "use strict"
###*
Copyright 2014 Joukou Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
###
###*
@module joukou-api/routes
@author Isaac Johnston <isaac.johnston@joukou.com>
@author Juan Morales <juan@joukou.com>
###
agent = require( './agent/routes' )
contact = require( './contact/routes' )
persona = require( './persona/routes' )
runtime = require( './runtime/routes' )
github = require( './github/routes' )
circle = require( './circle/routes' )
module.exports = self =
###*
Registers all routes with the `server`.
@param {joukou-api/server} server
###
registerRoutes: ( server ) ->
agent.registerRoutes( server )
contact.registerRoutes( server )
persona.registerRoutes( server )
runtime.registerRoutes( server )
github.registerRoutes( server )
circle.registerRoutes( server )
server.get( '/', self.index )
###
@api {get} / Joukou API entry point.
@apiName EntryPoint
@apiGroup Joukou
###
index: ( req, res, next ) ->
res.link( '/agent', 'joukou:agent-create', title: 'Create an Agent' )
res.link( '/agent/authenticate', 'joukou:agent-authn', title: 'Authenticate')
res.link( '/contact', 'joukou:contact', title: 'Send a Message to Joukou' )
res.send( 200, {} ) | 159194 | "use strict"
###*
Copyright 2014 Joukou Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
###
###*
@module joukou-api/routes
@author <NAME> <<EMAIL>>
@author <NAME> <<EMAIL>>
###
agent = require( './agent/routes' )
contact = require( './contact/routes' )
persona = require( './persona/routes' )
runtime = require( './runtime/routes' )
github = require( './github/routes' )
circle = require( './circle/routes' )
module.exports = self =
###*
Registers all routes with the `server`.
@param {joukou-api/server} server
###
registerRoutes: ( server ) ->
agent.registerRoutes( server )
contact.registerRoutes( server )
persona.registerRoutes( server )
runtime.registerRoutes( server )
github.registerRoutes( server )
circle.registerRoutes( server )
server.get( '/', self.index )
###
@api {get} / Joukou API entry point.
@apiName EntryPoint
@apiGroup Joukou
###
index: ( req, res, next ) ->
res.link( '/agent', 'joukou:agent-create', title: 'Create an Agent' )
res.link( '/agent/authenticate', 'joukou:agent-authn', title: 'Authenticate')
res.link( '/contact', 'joukou:contact', title: 'Send a Message to Joukou' )
res.send( 200, {} ) | true | "use strict"
###*
Copyright 2014 Joukou Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
###
###*
@module joukou-api/routes
@author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
@author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
###
agent = require( './agent/routes' )
contact = require( './contact/routes' )
persona = require( './persona/routes' )
runtime = require( './runtime/routes' )
github = require( './github/routes' )
circle = require( './circle/routes' )
module.exports = self =
###*
Registers all routes with the `server`.
@param {joukou-api/server} server
###
registerRoutes: ( server ) ->
agent.registerRoutes( server )
contact.registerRoutes( server )
persona.registerRoutes( server )
runtime.registerRoutes( server )
github.registerRoutes( server )
circle.registerRoutes( server )
server.get( '/', self.index )
###
@api {get} / Joukou API entry point.
@apiName EntryPoint
@apiGroup Joukou
###
index: ( req, res, next ) ->
res.link( '/agent', 'joukou:agent-create', title: 'Create an Agent' )
res.link( '/agent/authenticate', 'joukou:agent-authn', title: 'Authenticate')
res.link( '/contact', 'joukou:contact', title: 'Send a Message to Joukou' )
res.send( 200, {} ) |
[
{
"context": "r = @owner\n name = @name\n # @type = Tower.namespaced(",
"end": 1802,
"score": 0.7915821075439453,
"start": 1802,
"tag": "NAME",
"value": ""
}
] | src/tower/model/relation.coffee | vjsingh/tower | 1 | class Tower.Model.Relation extends Tower.Class
# Construct a new relation.
#
# @param [Function] owner Tower.Model class this relation is defined on.
# @param [String] name name of the relation.
# @param [Object] options options hash.
#
# @option options [String] type name of the associated class.
# @option options [Boolean] readonly (false)
# @option options [Boolean] validate (false)
# @option options [Boolean] autosave (false)
# @option options [Boolean] touch (false)
# @option options [Boolean] dependent (false) if true, relationship records
# will be destroyed if the owner record is destroyed.
# @option options [String] inverseOf (undefined)
# @option options [Boolean] polymorphic (false)
# @option options [String] foreignKey Defaults to "#{as}Id" if polymorphic, else "#{singularName}Id"
# @option options [String] foreignType Defaults to "#{as}Type" if polymorphic, otherwise it's undefined
# @option options [Boolean|String] idCache (false)
# @option options [String] idCacheKey Set to the value of the `idCache` option if it's a string,
# otherwise it's `"#{singularTargetName}Ids"`.
# @option options [Boolean] counterCache (false) if true, will increment `relationshipCount` variable
# when relationship is created/destroyed.
# @option options [String] counterCacheKey Set to the value of the `counterCache` option if it's a string,
# otherwise it's `"#{singularTargetName}Count"`.
#
# @see Tower.Model.Relations.ClassMethods#hasMany
constructor: (owner, name, options = {}) ->
@[key] = value for key, value of options
@owner = owner
@name = name
@initialize(options)
initialize: (options) ->
owner = @owner
name = @name
# @type = Tower.namespaced(options.type || Tower.Support.String.camelize(Tower.Support.String.singularize(name)))
@type = options.type || Tower.Support.String.camelize(Tower.Support.String.singularize(name))
@ownerType = Tower.namespaced(owner.name)
@dependent ||= false
@counterCache ||= false
@idCache = false unless @hasOwnProperty("idCache")
@readonly = false unless @hasOwnProperty("readonly")
@validate = false unless @hasOwnProperty("validate")
@autosave = false unless @hasOwnProperty("autosave")
@touch = false unless @hasOwnProperty("touch")
@inverseOf ||= undefined
@polymorphic = options.hasOwnProperty("as") || !!options.polymorphic
@default = false unless @hasOwnProperty("default")
@singularName = Tower.Support.String.camelize(owner.name, true)
@pluralName = Tower.Support.String.pluralize(owner.name) # collectionName?
@singularTargetName = Tower.Support.String.singularize(name)
@pluralTargetName = Tower.Support.String.pluralize(name)
@targetType = @type
# hasMany "posts", foreignKey: "postId", idCacheKey: "postIds"
unless @foreignKey
if @as
@foreignKey = "#{@as}Id"
else
@foreignKey = "#{@singularName}Id"
@foreignType ||= "#{@as}Type" if @polymorphic
if @idCache
if typeof @idCache == "string"
@idCacheKey = @idCache
@idCache = true
else
@idCacheKey = "#{@singularTargetName}Ids"
@owner.field @idCacheKey, type: "Array", default: []
if @counterCache
if typeof @counterCache == "string"
@counterCacheKey = @counterCache
@counterCache = true
else
@counterCacheKey = "#{@singularTargetName}Count"
@owner.field @counterCacheKey, type: "Integer", default: 0
@owner.prototype[name] = ->
@relation(name)
# @return [Tower.Model.Relation.Scope]
scoped: (record) ->
new Tower.Model.Scope(new @constructor.Criteria(model: @klass(), owner: record, relation: @))
# @return [Function]
targetKlass: ->
Tower.constant(@targetType)
# Class for model on the other side of this relationship.
#
# @return [Function]
klass: ->
Tower.constant(@type)
# Relation on the associated object that maps back to this relation.
#
# @return [Tower.Model.Relation]
inverse: (type) ->
return @_inverse if @_inverse
relations = @targetKlass().relations()
if @inverseOf
return relations[@inverseOf]
else
for name, relation of relations
# need a way to check if class extends another class in coffeescript...
return relation if relation.inverseOf == @name
for name, relation of relations
return relation if relation.targetType == @ownerType
null
class @Criteria extends Tower.Model.Criteria
isConstructable: ->
!!!@relation.polymorphic
constructor: (options = {}) ->
super(options)
@owner = options.owner
@relation = options.relation
@records = []
clone: ->
(new @constructor(model: @model, owner: @owner, relation: @relation, records: @records.concat(), instantiate: @instantiate)).merge(@)
setInverseInstance: (record) ->
if record && @invertibleFor(record)
inverse = record.relation(@inverseReflectionFor(record).name)
inverse.target = owner
invertibleFor: (record) ->
true
inverse: (record) ->
_teardown: ->
_.teardown(@, "relation", "records", "owner", "model", "criteria")
for phase in ["Before", "After"]
for action in ["Create", "Update", "Destroy", "Find"]
do (phase, action) =>
Tower.Model.Relation.Criteria::["_run#{phase}#{action}CallbacksOnStore"] = (done) ->
@store["run#{phase}#{action}"](@, done)
require './relation/belongsTo'
require './relation/hasMany'
require './relation/hasManyThrough'
require './relation/hasOne'
module.exports = Tower.Model.Relation
| 149022 | class Tower.Model.Relation extends Tower.Class
# Construct a new relation.
#
# @param [Function] owner Tower.Model class this relation is defined on.
# @param [String] name name of the relation.
# @param [Object] options options hash.
#
# @option options [String] type name of the associated class.
# @option options [Boolean] readonly (false)
# @option options [Boolean] validate (false)
# @option options [Boolean] autosave (false)
# @option options [Boolean] touch (false)
# @option options [Boolean] dependent (false) if true, relationship records
# will be destroyed if the owner record is destroyed.
# @option options [String] inverseOf (undefined)
# @option options [Boolean] polymorphic (false)
# @option options [String] foreignKey Defaults to "#{as}Id" if polymorphic, else "#{singularName}Id"
# @option options [String] foreignType Defaults to "#{as}Type" if polymorphic, otherwise it's undefined
# @option options [Boolean|String] idCache (false)
# @option options [String] idCacheKey Set to the value of the `idCache` option if it's a string,
# otherwise it's `"#{singularTargetName}Ids"`.
# @option options [Boolean] counterCache (false) if true, will increment `relationshipCount` variable
# when relationship is created/destroyed.
# @option options [String] counterCacheKey Set to the value of the `counterCache` option if it's a string,
# otherwise it's `"#{singularTargetName}Count"`.
#
# @see Tower.Model.Relations.ClassMethods#hasMany
constructor: (owner, name, options = {}) ->
@[key] = value for key, value of options
@owner = owner
@name = name
@initialize(options)
initialize: (options) ->
owner = @owner
name =<NAME> @name
# @type = Tower.namespaced(options.type || Tower.Support.String.camelize(Tower.Support.String.singularize(name)))
@type = options.type || Tower.Support.String.camelize(Tower.Support.String.singularize(name))
@ownerType = Tower.namespaced(owner.name)
@dependent ||= false
@counterCache ||= false
@idCache = false unless @hasOwnProperty("idCache")
@readonly = false unless @hasOwnProperty("readonly")
@validate = false unless @hasOwnProperty("validate")
@autosave = false unless @hasOwnProperty("autosave")
@touch = false unless @hasOwnProperty("touch")
@inverseOf ||= undefined
@polymorphic = options.hasOwnProperty("as") || !!options.polymorphic
@default = false unless @hasOwnProperty("default")
@singularName = Tower.Support.String.camelize(owner.name, true)
@pluralName = Tower.Support.String.pluralize(owner.name) # collectionName?
@singularTargetName = Tower.Support.String.singularize(name)
@pluralTargetName = Tower.Support.String.pluralize(name)
@targetType = @type
# hasMany "posts", foreignKey: "postId", idCacheKey: "postIds"
unless @foreignKey
if @as
@foreignKey = "#{@as}Id"
else
@foreignKey = "#{@singularName}Id"
@foreignType ||= "#{@as}Type" if @polymorphic
if @idCache
if typeof @idCache == "string"
@idCacheKey = @idCache
@idCache = true
else
@idCacheKey = "#{@singularTargetName}Ids"
@owner.field @idCacheKey, type: "Array", default: []
if @counterCache
if typeof @counterCache == "string"
@counterCacheKey = @counterCache
@counterCache = true
else
@counterCacheKey = "#{@singularTargetName}Count"
@owner.field @counterCacheKey, type: "Integer", default: 0
@owner.prototype[name] = ->
@relation(name)
# @return [Tower.Model.Relation.Scope]
scoped: (record) ->
new Tower.Model.Scope(new @constructor.Criteria(model: @klass(), owner: record, relation: @))
# @return [Function]
targetKlass: ->
Tower.constant(@targetType)
# Class for model on the other side of this relationship.
#
# @return [Function]
klass: ->
Tower.constant(@type)
# Relation on the associated object that maps back to this relation.
#
# @return [Tower.Model.Relation]
inverse: (type) ->
return @_inverse if @_inverse
relations = @targetKlass().relations()
if @inverseOf
return relations[@inverseOf]
else
for name, relation of relations
# need a way to check if class extends another class in coffeescript...
return relation if relation.inverseOf == @name
for name, relation of relations
return relation if relation.targetType == @ownerType
null
class @Criteria extends Tower.Model.Criteria
isConstructable: ->
!!!@relation.polymorphic
constructor: (options = {}) ->
super(options)
@owner = options.owner
@relation = options.relation
@records = []
clone: ->
(new @constructor(model: @model, owner: @owner, relation: @relation, records: @records.concat(), instantiate: @instantiate)).merge(@)
setInverseInstance: (record) ->
if record && @invertibleFor(record)
inverse = record.relation(@inverseReflectionFor(record).name)
inverse.target = owner
invertibleFor: (record) ->
true
inverse: (record) ->
_teardown: ->
_.teardown(@, "relation", "records", "owner", "model", "criteria")
for phase in ["Before", "After"]
for action in ["Create", "Update", "Destroy", "Find"]
do (phase, action) =>
Tower.Model.Relation.Criteria::["_run#{phase}#{action}CallbacksOnStore"] = (done) ->
@store["run#{phase}#{action}"](@, done)
require './relation/belongsTo'
require './relation/hasMany'
require './relation/hasManyThrough'
require './relation/hasOne'
module.exports = Tower.Model.Relation
| true | class Tower.Model.Relation extends Tower.Class
# Construct a new relation.
#
# @param [Function] owner Tower.Model class this relation is defined on.
# @param [String] name name of the relation.
# @param [Object] options options hash.
#
# @option options [String] type name of the associated class.
# @option options [Boolean] readonly (false)
# @option options [Boolean] validate (false)
# @option options [Boolean] autosave (false)
# @option options [Boolean] touch (false)
# @option options [Boolean] dependent (false) if true, relationship records
# will be destroyed if the owner record is destroyed.
# @option options [String] inverseOf (undefined)
# @option options [Boolean] polymorphic (false)
# @option options [String] foreignKey Defaults to "#{as}Id" if polymorphic, else "#{singularName}Id"
# @option options [String] foreignType Defaults to "#{as}Type" if polymorphic, otherwise it's undefined
# @option options [Boolean|String] idCache (false)
# @option options [String] idCacheKey Set to the value of the `idCache` option if it's a string,
# otherwise it's `"#{singularTargetName}Ids"`.
# @option options [Boolean] counterCache (false) if true, will increment `relationshipCount` variable
# when relationship is created/destroyed.
# @option options [String] counterCacheKey Set to the value of the `counterCache` option if it's a string,
# otherwise it's `"#{singularTargetName}Count"`.
#
# @see Tower.Model.Relations.ClassMethods#hasMany
constructor: (owner, name, options = {}) ->
@[key] = value for key, value of options
@owner = owner
@name = name
@initialize(options)
initialize: (options) ->
owner = @owner
name =PI:NAME:<NAME>END_PI @name
# @type = Tower.namespaced(options.type || Tower.Support.String.camelize(Tower.Support.String.singularize(name)))
@type = options.type || Tower.Support.String.camelize(Tower.Support.String.singularize(name))
@ownerType = Tower.namespaced(owner.name)
@dependent ||= false
@counterCache ||= false
@idCache = false unless @hasOwnProperty("idCache")
@readonly = false unless @hasOwnProperty("readonly")
@validate = false unless @hasOwnProperty("validate")
@autosave = false unless @hasOwnProperty("autosave")
@touch = false unless @hasOwnProperty("touch")
@inverseOf ||= undefined
@polymorphic = options.hasOwnProperty("as") || !!options.polymorphic
@default = false unless @hasOwnProperty("default")
@singularName = Tower.Support.String.camelize(owner.name, true)
@pluralName = Tower.Support.String.pluralize(owner.name) # collectionName?
@singularTargetName = Tower.Support.String.singularize(name)
@pluralTargetName = Tower.Support.String.pluralize(name)
@targetType = @type
# hasMany "posts", foreignKey: "postId", idCacheKey: "postIds"
unless @foreignKey
if @as
@foreignKey = "#{@as}Id"
else
@foreignKey = "#{@singularName}Id"
@foreignType ||= "#{@as}Type" if @polymorphic
if @idCache
if typeof @idCache == "string"
@idCacheKey = @idCache
@idCache = true
else
@idCacheKey = "#{@singularTargetName}Ids"
@owner.field @idCacheKey, type: "Array", default: []
if @counterCache
if typeof @counterCache == "string"
@counterCacheKey = @counterCache
@counterCache = true
else
@counterCacheKey = "#{@singularTargetName}Count"
@owner.field @counterCacheKey, type: "Integer", default: 0
@owner.prototype[name] = ->
@relation(name)
# @return [Tower.Model.Relation.Scope]
scoped: (record) ->
new Tower.Model.Scope(new @constructor.Criteria(model: @klass(), owner: record, relation: @))
# @return [Function]
targetKlass: ->
Tower.constant(@targetType)
# Class for model on the other side of this relationship.
#
# @return [Function]
klass: ->
Tower.constant(@type)
# Relation on the associated object that maps back to this relation.
#
# @return [Tower.Model.Relation]
inverse: (type) ->
return @_inverse if @_inverse
relations = @targetKlass().relations()
if @inverseOf
return relations[@inverseOf]
else
for name, relation of relations
# need a way to check if class extends another class in coffeescript...
return relation if relation.inverseOf == @name
for name, relation of relations
return relation if relation.targetType == @ownerType
null
class @Criteria extends Tower.Model.Criteria
isConstructable: ->
!!!@relation.polymorphic
constructor: (options = {}) ->
super(options)
@owner = options.owner
@relation = options.relation
@records = []
clone: ->
(new @constructor(model: @model, owner: @owner, relation: @relation, records: @records.concat(), instantiate: @instantiate)).merge(@)
setInverseInstance: (record) ->
if record && @invertibleFor(record)
inverse = record.relation(@inverseReflectionFor(record).name)
inverse.target = owner
invertibleFor: (record) ->
true
inverse: (record) ->
_teardown: ->
_.teardown(@, "relation", "records", "owner", "model", "criteria")
for phase in ["Before", "After"]
for action in ["Create", "Update", "Destroy", "Find"]
do (phase, action) =>
Tower.Model.Relation.Criteria::["_run#{phase}#{action}CallbacksOnStore"] = (done) ->
@store["run#{phase}#{action}"](@, done)
require './relation/belongsTo'
require './relation/hasMany'
require './relation/hasManyThrough'
require './relation/hasOne'
module.exports = Tower.Model.Relation
|
[
{
"context": "bot xkcd random - XKCD comic <num>\n#\n# Author:\n# twe4ked\n# Hemanth (fixed the max issue)\n\nmodule.exports",
"end": 266,
"score": 0.9996459484100342,
"start": 259,
"tag": "USERNAME",
"value": "twe4ked"
},
{
"context": "dom - XKCD comic <num>\n#\n# Author:\n# t... | src/scripts/xkcd.coffee | Reelhouse/hubot-scripts | 9 | # Description:
# Grab XKCD comic image urls
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# hubot xkcd [latest]- The latest XKCD comic
# hubot xkcd <num> - XKCD comic <num>
# hubot xkcd random - XKCD comic <num>
#
# Author:
# twe4ked
# Hemanth (fixed the max issue)
module.exports = (robot) ->
robot.respond /xkcd(\s+latest)?$/i, (msg) ->
msg.http("http://xkcd.com/info.0.json")
.get() (err, res, body) ->
if res.statusCode == 404
msg.send 'Comic not found.'
else
object = JSON.parse(body)
msg.send object.title, object.img, object.alt
robot.respond /xkcd\s+(\d+)/i, (msg) ->
num = "#{msg.match[1]}"
msg.http("http://xkcd.com/#{num}/info.0.json")
.get() (err, res, body) ->
if res.statusCode == 404
msg.send 'Comic #{num} not found.'
else
object = JSON.parse(body)
msg.send object.title, object.img, object.alt
robot.respond /xkcd\s+random/i, (msg) ->
msg.http("http://xkcd.com/info.0.json")
.get() (err,res,body) ->
if res.statusCode == 404
max = 0
else
max = JSON.parse(body).num
num = Math.floor((Math.random()*max)+1)
msg.http("http://xkcd.com/#{num}/info.0.json")
.get() (err, res, body) ->
object = JSON.parse(body)
msg.send object.title, object.img, object.alt
| 8138 | # Description:
# Grab XKCD comic image urls
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# hubot xkcd [latest]- The latest XKCD comic
# hubot xkcd <num> - XKCD comic <num>
# hubot xkcd random - XKCD comic <num>
#
# Author:
# twe4ked
# <NAME>th (fixed the max issue)
module.exports = (robot) ->
robot.respond /xkcd(\s+latest)?$/i, (msg) ->
msg.http("http://xkcd.com/info.0.json")
.get() (err, res, body) ->
if res.statusCode == 404
msg.send 'Comic not found.'
else
object = JSON.parse(body)
msg.send object.title, object.img, object.alt
robot.respond /xkcd\s+(\d+)/i, (msg) ->
num = "#{msg.match[1]}"
msg.http("http://xkcd.com/#{num}/info.0.json")
.get() (err, res, body) ->
if res.statusCode == 404
msg.send 'Comic #{num} not found.'
else
object = JSON.parse(body)
msg.send object.title, object.img, object.alt
robot.respond /xkcd\s+random/i, (msg) ->
msg.http("http://xkcd.com/info.0.json")
.get() (err,res,body) ->
if res.statusCode == 404
max = 0
else
max = JSON.parse(body).num
num = Math.floor((Math.random()*max)+1)
msg.http("http://xkcd.com/#{num}/info.0.json")
.get() (err, res, body) ->
object = JSON.parse(body)
msg.send object.title, object.img, object.alt
| true | # Description:
# Grab XKCD comic image urls
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# hubot xkcd [latest]- The latest XKCD comic
# hubot xkcd <num> - XKCD comic <num>
# hubot xkcd random - XKCD comic <num>
#
# Author:
# twe4ked
# PI:NAME:<NAME>END_PIth (fixed the max issue)
module.exports = (robot) ->
robot.respond /xkcd(\s+latest)?$/i, (msg) ->
msg.http("http://xkcd.com/info.0.json")
.get() (err, res, body) ->
if res.statusCode == 404
msg.send 'Comic not found.'
else
object = JSON.parse(body)
msg.send object.title, object.img, object.alt
robot.respond /xkcd\s+(\d+)/i, (msg) ->
num = "#{msg.match[1]}"
msg.http("http://xkcd.com/#{num}/info.0.json")
.get() (err, res, body) ->
if res.statusCode == 404
msg.send 'Comic #{num} not found.'
else
object = JSON.parse(body)
msg.send object.title, object.img, object.alt
robot.respond /xkcd\s+random/i, (msg) ->
msg.http("http://xkcd.com/info.0.json")
.get() (err,res,body) ->
if res.statusCode == 404
max = 0
else
max = JSON.parse(body).num
num = Math.floor((Math.random()*max)+1)
msg.http("http://xkcd.com/#{num}/info.0.json")
.get() (err, res, body) ->
object = JSON.parse(body)
msg.send object.title, object.img, object.alt
|
[
{
"context": "y) ->\n root[key]\n keys = role.split /\\./g\n allgood = false\n if user.roles\n ",
"end": 1810,
"score": 0.6401093006134033,
"start": 1809,
"tag": "KEY",
"value": "g"
}
] | src/ndx-auth.coffee | ndxbxrme/ndx-auth-client | 0 | 'use strict'
module = null
try
module = angular.module 'ndx'
catch e
module = angular.module 'ndx', []
module.provider 'Auth', ->
settings =
redirect: 'dashboard'
config: (args) ->
angular.extend settings, args
$get: ($http, $q, $state, $window, $injector) ->
user = null
loading = false
current = ''
currentParams = null
errorRedirect = ''
errorRedirectParams = null
prev = ''
prevParams = null
userCallbacks = []
sockets = false
socket = null
if $injector.has 'socket'
sockets = true
socket = $injector.get 'socket'
socket.on 'connect', ->
if user
socket.emit 'user', user
genId = (len) ->
output = ''
chars = 'abcdef0123456789'
output = new Date().valueOf().toString(16)
i = output.length
while i++ < len
output += chars[Math.floor(Math.random() * chars.length)]
output
getUserPromise = () ->
loading = true
defer = $q.defer()
if user
defer.resolve user
loading = false
else
$http.post '/api/refresh-login'
.then (data) ->
loading = false
if data and data.data and data.data isnt 'error' and data.status isnt 401
user = data.data
for callback in userCallbacks
try
callback? user
catch e
false
userCallbacks = []
if sockets
socket.emit 'user', user
defer.resolve user
else
user = null
defer.reject {}
, ->
loading = false
user = null
defer.reject {}
defer.promise
hasRole = (role) ->
getKey = (root, key) ->
root[key]
keys = role.split /\./g
allgood = false
if user.roles
root = user.roles
for key in keys
if key is '*'
for k of root
root = root[k]
break
else
root = getKey root, key
if root
allgood = true
else
allgood = false
break
allgood
checkRoles = (role, isAnd) ->
rolesToCheck = []
getRole = (role) ->
type = Object.prototype.toString.call role
if type is '[object Array]'
for r in role
getRole r
else if type is '[object Function]'
r = role req
getRole r
else if type is '[object String]'
if rolesToCheck.indexOf(role) is -1
rolesToCheck.push role
getRole role
truth = if isAnd then true else false
for r in rolesToCheck
if isAnd
truth = truth and hasRole(r)
else
truth = truth or hasRole(r)
truth
getPromise: (role, isAnd) ->
defer = $q.defer()
if Object.prototype.toString.call(role) is '[object Boolean]' and role is false
defer.resolve {}
else
getUserPromise()
.then ->
if role
truth = checkRoles role, isAnd
if truth
defer.resolve user
else
$state.go settings.redirect
defer.reject {}
else
defer.resolve user
, ->
if not role
defer.resolve {}
else
$state.go settings.redirect
defer.reject {}
defer.promise
clearUser: ->
user = null
getUser: ->
user
loggedIn: ->
user or $state.current.name is 'invited' or $state.current.name is 'forgot' or $state.current.name is 'forgotResponse'
loading: ->
loading
checkRoles: (role) ->
if user
checkRoles role
checkAllRoles: (role) ->
if user
checkRoles role, true
isAuthorized: (stateName) ->
if user
if Object.prototype.toString.call(stateName) is '[object Array]'
for sName in stateName
roles = $state.get(sName)?.data?.auth
if not roles
return true
if checkRoles roles
return true
return false
else
roles = $state.get(stateName)?.data?.auth
if not roles
return true
return checkRoles roles
canEdit: (stateName) ->
if user
roles = $state.get(stateName)?.data?.edit or $state.get(stateName)?.data?.auth
checkRoles roles
redirect: settings.redirect
goToNext: ->
if current
$state.go current, currentParams
if current isnt prev or JSON.stringify(currentParams) isnt JSON.stringify(prevParams)
prev = current
prevParams = currentParams
else
if settings.redirect
$state.go settings.redirect
goToErrorRedirect: ->
if errorRedirect
$state.go errorRedirect, errorRedirectParams
errorRedirect = ''
errorRedirectParams = undefined
else
if settings.redirect
$state.go settings.redirect
goToLast: (_default, defaultParams) ->
if prev
$state.go prev, prevParams
else if _default
$state.go _default, defaultParams
else
if settings.redirect
$state.go settings.redirect
logOut: ->
socket.emit 'user', null
user = null
$http.get '/api/logout'
onUser: (func) ->
if user
func? user
else
if userCallbacks.indexOf(func) is -1
userCallbacks.push func
config: (args) ->
angular.extend settings, args
settings: settings
current: (_current, _currentParams) ->
if _current is 'logged-out'
return
if prev isnt current or prevParams isnt currentParams
prev = current
prevParams = Object.assign {}, currentParams
current = _current
currentParams = _currentParams
errorRedirect: (_errorRedirect, _errorRedirectParams) ->
errorRedirect = _errorRedirect
errorRedirectParams = _errorRedirectParams
setPrev: (_prev, _prevParams) ->
prev = _prev
prevParams = _prevParams or null
setTitle: (title) ->
title = title or $state.current.data?.title
document.title = "#{settings.titlePrefix or ''}#{title}#{settings.titleSuffix or ''}"
genId: genId
regenerateAnonId: ->
anonId = genId(24)
localStorage.setItem 'anonId', anonId
$http.defaults.headers.common['Anon-Id'] = anonId
.run ($rootScope, $state, $stateParams, $transitions, $q, $http, Auth) ->
if Auth.settings.anonymousUser
if localStorage
anonId = localStorage.getItem 'anonId'
anonId = anonId or Auth.genId(24)
localStorage.setItem 'anonId', anonId
$http.defaults.headers.common['Anon-Id'] = anonId
root = Object.getPrototypeOf $rootScope
root.auth = Auth
$transitions.onBefore {}, (trans) ->
defer = $q.defer()
data = trans.$to().data or {}
if data.auth
Auth.getPromise data.auth
.then ->
Auth.current trans.$to().name, trans.params()
defer.resolve()
, ->
Auth.errorRedirect trans.$to().name, trans.params()
defer.reject()
else
Auth.getPromise null
.then ->
Auth.current trans.$to().name, trans.params()
defer.resolve()
, ->
Auth.current trans.$to().name, trans.params()
defer.resolve()
defer.promise
$transitions.onStart {}, (trans) ->
title = (trans.$to().data or {}).title or ''
if Auth.settings
if Auth.loggedIn()
Auth.setTitle title
else
Auth.setTitle 'Login'
trans | 203385 | 'use strict'
module = null
try
module = angular.module 'ndx'
catch e
module = angular.module 'ndx', []
module.provider 'Auth', ->
settings =
redirect: 'dashboard'
config: (args) ->
angular.extend settings, args
$get: ($http, $q, $state, $window, $injector) ->
user = null
loading = false
current = ''
currentParams = null
errorRedirect = ''
errorRedirectParams = null
prev = ''
prevParams = null
userCallbacks = []
sockets = false
socket = null
if $injector.has 'socket'
sockets = true
socket = $injector.get 'socket'
socket.on 'connect', ->
if user
socket.emit 'user', user
genId = (len) ->
output = ''
chars = 'abcdef0123456789'
output = new Date().valueOf().toString(16)
i = output.length
while i++ < len
output += chars[Math.floor(Math.random() * chars.length)]
output
getUserPromise = () ->
loading = true
defer = $q.defer()
if user
defer.resolve user
loading = false
else
$http.post '/api/refresh-login'
.then (data) ->
loading = false
if data and data.data and data.data isnt 'error' and data.status isnt 401
user = data.data
for callback in userCallbacks
try
callback? user
catch e
false
userCallbacks = []
if sockets
socket.emit 'user', user
defer.resolve user
else
user = null
defer.reject {}
, ->
loading = false
user = null
defer.reject {}
defer.promise
hasRole = (role) ->
getKey = (root, key) ->
root[key]
keys = role.split /\./<KEY>
allgood = false
if user.roles
root = user.roles
for key in keys
if key is '*'
for k of root
root = root[k]
break
else
root = getKey root, key
if root
allgood = true
else
allgood = false
break
allgood
checkRoles = (role, isAnd) ->
rolesToCheck = []
getRole = (role) ->
type = Object.prototype.toString.call role
if type is '[object Array]'
for r in role
getRole r
else if type is '[object Function]'
r = role req
getRole r
else if type is '[object String]'
if rolesToCheck.indexOf(role) is -1
rolesToCheck.push role
getRole role
truth = if isAnd then true else false
for r in rolesToCheck
if isAnd
truth = truth and hasRole(r)
else
truth = truth or hasRole(r)
truth
getPromise: (role, isAnd) ->
defer = $q.defer()
if Object.prototype.toString.call(role) is '[object Boolean]' and role is false
defer.resolve {}
else
getUserPromise()
.then ->
if role
truth = checkRoles role, isAnd
if truth
defer.resolve user
else
$state.go settings.redirect
defer.reject {}
else
defer.resolve user
, ->
if not role
defer.resolve {}
else
$state.go settings.redirect
defer.reject {}
defer.promise
clearUser: ->
user = null
getUser: ->
user
loggedIn: ->
user or $state.current.name is 'invited' or $state.current.name is 'forgot' or $state.current.name is 'forgotResponse'
loading: ->
loading
checkRoles: (role) ->
if user
checkRoles role
checkAllRoles: (role) ->
if user
checkRoles role, true
isAuthorized: (stateName) ->
if user
if Object.prototype.toString.call(stateName) is '[object Array]'
for sName in stateName
roles = $state.get(sName)?.data?.auth
if not roles
return true
if checkRoles roles
return true
return false
else
roles = $state.get(stateName)?.data?.auth
if not roles
return true
return checkRoles roles
canEdit: (stateName) ->
if user
roles = $state.get(stateName)?.data?.edit or $state.get(stateName)?.data?.auth
checkRoles roles
redirect: settings.redirect
goToNext: ->
if current
$state.go current, currentParams
if current isnt prev or JSON.stringify(currentParams) isnt JSON.stringify(prevParams)
prev = current
prevParams = currentParams
else
if settings.redirect
$state.go settings.redirect
goToErrorRedirect: ->
if errorRedirect
$state.go errorRedirect, errorRedirectParams
errorRedirect = ''
errorRedirectParams = undefined
else
if settings.redirect
$state.go settings.redirect
goToLast: (_default, defaultParams) ->
if prev
$state.go prev, prevParams
else if _default
$state.go _default, defaultParams
else
if settings.redirect
$state.go settings.redirect
logOut: ->
socket.emit 'user', null
user = null
$http.get '/api/logout'
onUser: (func) ->
if user
func? user
else
if userCallbacks.indexOf(func) is -1
userCallbacks.push func
config: (args) ->
angular.extend settings, args
settings: settings
current: (_current, _currentParams) ->
if _current is 'logged-out'
return
if prev isnt current or prevParams isnt currentParams
prev = current
prevParams = Object.assign {}, currentParams
current = _current
currentParams = _currentParams
errorRedirect: (_errorRedirect, _errorRedirectParams) ->
errorRedirect = _errorRedirect
errorRedirectParams = _errorRedirectParams
setPrev: (_prev, _prevParams) ->
prev = _prev
prevParams = _prevParams or null
setTitle: (title) ->
title = title or $state.current.data?.title
document.title = "#{settings.titlePrefix or ''}#{title}#{settings.titleSuffix or ''}"
genId: genId
regenerateAnonId: ->
anonId = genId(24)
localStorage.setItem 'anonId', anonId
$http.defaults.headers.common['Anon-Id'] = anonId
.run ($rootScope, $state, $stateParams, $transitions, $q, $http, Auth) ->
if Auth.settings.anonymousUser
if localStorage
anonId = localStorage.getItem 'anonId'
anonId = anonId or Auth.genId(24)
localStorage.setItem 'anonId', anonId
$http.defaults.headers.common['Anon-Id'] = anonId
root = Object.getPrototypeOf $rootScope
root.auth = Auth
$transitions.onBefore {}, (trans) ->
defer = $q.defer()
data = trans.$to().data or {}
if data.auth
Auth.getPromise data.auth
.then ->
Auth.current trans.$to().name, trans.params()
defer.resolve()
, ->
Auth.errorRedirect trans.$to().name, trans.params()
defer.reject()
else
Auth.getPromise null
.then ->
Auth.current trans.$to().name, trans.params()
defer.resolve()
, ->
Auth.current trans.$to().name, trans.params()
defer.resolve()
defer.promise
$transitions.onStart {}, (trans) ->
title = (trans.$to().data or {}).title or ''
if Auth.settings
if Auth.loggedIn()
Auth.setTitle title
else
Auth.setTitle 'Login'
trans | true | 'use strict'
module = null
try
module = angular.module 'ndx'
catch e
module = angular.module 'ndx', []
module.provider 'Auth', ->
settings =
redirect: 'dashboard'
config: (args) ->
angular.extend settings, args
$get: ($http, $q, $state, $window, $injector) ->
user = null
loading = false
current = ''
currentParams = null
errorRedirect = ''
errorRedirectParams = null
prev = ''
prevParams = null
userCallbacks = []
sockets = false
socket = null
if $injector.has 'socket'
sockets = true
socket = $injector.get 'socket'
socket.on 'connect', ->
if user
socket.emit 'user', user
genId = (len) ->
output = ''
chars = 'abcdef0123456789'
output = new Date().valueOf().toString(16)
i = output.length
while i++ < len
output += chars[Math.floor(Math.random() * chars.length)]
output
getUserPromise = () ->
loading = true
defer = $q.defer()
if user
defer.resolve user
loading = false
else
$http.post '/api/refresh-login'
.then (data) ->
loading = false
if data and data.data and data.data isnt 'error' and data.status isnt 401
user = data.data
for callback in userCallbacks
try
callback? user
catch e
false
userCallbacks = []
if sockets
socket.emit 'user', user
defer.resolve user
else
user = null
defer.reject {}
, ->
loading = false
user = null
defer.reject {}
defer.promise
hasRole = (role) ->
getKey = (root, key) ->
root[key]
keys = role.split /\./PI:KEY:<KEY>END_PI
allgood = false
if user.roles
root = user.roles
for key in keys
if key is '*'
for k of root
root = root[k]
break
else
root = getKey root, key
if root
allgood = true
else
allgood = false
break
allgood
checkRoles = (role, isAnd) ->
rolesToCheck = []
getRole = (role) ->
type = Object.prototype.toString.call role
if type is '[object Array]'
for r in role
getRole r
else if type is '[object Function]'
r = role req
getRole r
else if type is '[object String]'
if rolesToCheck.indexOf(role) is -1
rolesToCheck.push role
getRole role
truth = if isAnd then true else false
for r in rolesToCheck
if isAnd
truth = truth and hasRole(r)
else
truth = truth or hasRole(r)
truth
getPromise: (role, isAnd) ->
defer = $q.defer()
if Object.prototype.toString.call(role) is '[object Boolean]' and role is false
defer.resolve {}
else
getUserPromise()
.then ->
if role
truth = checkRoles role, isAnd
if truth
defer.resolve user
else
$state.go settings.redirect
defer.reject {}
else
defer.resolve user
, ->
if not role
defer.resolve {}
else
$state.go settings.redirect
defer.reject {}
defer.promise
clearUser: ->
user = null
getUser: ->
user
loggedIn: ->
user or $state.current.name is 'invited' or $state.current.name is 'forgot' or $state.current.name is 'forgotResponse'
loading: ->
loading
checkRoles: (role) ->
if user
checkRoles role
checkAllRoles: (role) ->
if user
checkRoles role, true
isAuthorized: (stateName) ->
if user
if Object.prototype.toString.call(stateName) is '[object Array]'
for sName in stateName
roles = $state.get(sName)?.data?.auth
if not roles
return true
if checkRoles roles
return true
return false
else
roles = $state.get(stateName)?.data?.auth
if not roles
return true
return checkRoles roles
canEdit: (stateName) ->
if user
roles = $state.get(stateName)?.data?.edit or $state.get(stateName)?.data?.auth
checkRoles roles
redirect: settings.redirect
goToNext: ->
if current
$state.go current, currentParams
if current isnt prev or JSON.stringify(currentParams) isnt JSON.stringify(prevParams)
prev = current
prevParams = currentParams
else
if settings.redirect
$state.go settings.redirect
goToErrorRedirect: ->
if errorRedirect
$state.go errorRedirect, errorRedirectParams
errorRedirect = ''
errorRedirectParams = undefined
else
if settings.redirect
$state.go settings.redirect
goToLast: (_default, defaultParams) ->
if prev
$state.go prev, prevParams
else if _default
$state.go _default, defaultParams
else
if settings.redirect
$state.go settings.redirect
logOut: ->
socket.emit 'user', null
user = null
$http.get '/api/logout'
onUser: (func) ->
if user
func? user
else
if userCallbacks.indexOf(func) is -1
userCallbacks.push func
config: (args) ->
angular.extend settings, args
settings: settings
current: (_current, _currentParams) ->
if _current is 'logged-out'
return
if prev isnt current or prevParams isnt currentParams
prev = current
prevParams = Object.assign {}, currentParams
current = _current
currentParams = _currentParams
errorRedirect: (_errorRedirect, _errorRedirectParams) ->
errorRedirect = _errorRedirect
errorRedirectParams = _errorRedirectParams
setPrev: (_prev, _prevParams) ->
prev = _prev
prevParams = _prevParams or null
setTitle: (title) ->
title = title or $state.current.data?.title
document.title = "#{settings.titlePrefix or ''}#{title}#{settings.titleSuffix or ''}"
genId: genId
regenerateAnonId: ->
anonId = genId(24)
localStorage.setItem 'anonId', anonId
$http.defaults.headers.common['Anon-Id'] = anonId
.run ($rootScope, $state, $stateParams, $transitions, $q, $http, Auth) ->
if Auth.settings.anonymousUser
if localStorage
anonId = localStorage.getItem 'anonId'
anonId = anonId or Auth.genId(24)
localStorage.setItem 'anonId', anonId
$http.defaults.headers.common['Anon-Id'] = anonId
root = Object.getPrototypeOf $rootScope
root.auth = Auth
$transitions.onBefore {}, (trans) ->
defer = $q.defer()
data = trans.$to().data or {}
if data.auth
Auth.getPromise data.auth
.then ->
Auth.current trans.$to().name, trans.params()
defer.resolve()
, ->
Auth.errorRedirect trans.$to().name, trans.params()
defer.reject()
else
Auth.getPromise null
.then ->
Auth.current trans.$to().name, trans.params()
defer.resolve()
, ->
Auth.current trans.$to().name, trans.params()
defer.resolve()
defer.promise
$transitions.onStart {}, (trans) ->
title = (trans.$to().data or {}).title or ''
if Auth.settings
if Auth.loggedIn()
Auth.setTitle title
else
Auth.setTitle 'Login'
trans |
[
{
"context": "e: 'The Wonderful Wizard of Oz',\n author: 'L. Frank Baum'}, assets)\n testbook.assets.init(done)\n d",
"end": 1800,
"score": 0.999883770942688,
"start": 1787,
"tag": "NAME",
"value": "L. Frank Baum"
},
{
"context": "e: 'The Wonderful Wizard of Oz',\n ... | scripts/test/epub.coffee | baldurbjarnason/bookmaker | 1 | 'use strict'
chai = require 'chai'
should = chai.should()
index = require '../src/index'
Chapter = index.Chapter
Book = index.Book
Assets = index.Assets
zipStream = require('zipstream-contentment')
fs = require 'fs'
exec = require('child_process').exec
testoutline = {
id: 'titlepage',
filename: 'title.html',
title: 'Title Page',
render: true,
template: 'title.hbs',
majornavitem: true,
subChapters: [
{
id: 'nav',
filename: 'index.html',
render: false,
title: 'Table of Contents',
nomanifest: true,
majornavitem: true,
toc: true
},
{
id: 'titlepage',
filename: 'title.html',
title: 'Title Page',
render: true,
template: 'title.hbs',
majornavitem: true
},
{
id: 'titletoc',
filename: 'title.html',
title: 'Contents',
render: true,
template: 'titletoc.hbs',
majornavitem: true,
toc: true
},
{
type: 'md'
body: '# This is Markdown!'
}]
}
testbook = {}
testchapters = [{
type: 'md',
title: 'Markdown',
body: '# header\n\nTest'
},
{
type: 'html',
id: 'htmlexample',
filename: 'htmlexample.html',
title: 'HTML',
arbitraryMeta: 'is arbitrary'
body: '<h1>header</h1><p>Test<br>‘—’“–” </p>'
},
{
type: 'xhtml',
title: 'XHTML',
body: '<h1>header</h1><p>Test<br/></p>'
},
{
type: 'hbs',
title: 'Template',
body: '<h1>{{title}}</h1><p>Test<br>‘—’“–” </p>'
}
]
describe 'EpubChapter',
() ->
beforeEach (done) ->
assets = new Assets("test/files/", "assets/")
testbook = new Book({
title: 'The Wonderful Wizard of Oz',
author: 'L. Frank Baum'}, assets)
testbook.assets.init(done)
describe '#addToZip',
() ->
it 'Returns a promise to add the chapter to zip (test.zip)',
(done) ->
zip = zipStream.createZip({ level: 1 })
out = fs.createWriteStream('test/files/test.zip')
zip.pipe(out)
testbook.addChapter(new Chapter(testchapters[1]))
testbook.chapters[0].addToZip(zip, null, () ->
zip.finalize((written) ->
written.should.equal(540)
done()))
testassets = {}
describe 'EpubAssets',
() ->
beforeEach (done) ->
testassets = new index.Assets('test/files/', 'assets/')
testassets.init(done)
describe '#addTypeToZip',
() ->
it 'Adds all assets of a type to zip',
(done) ->
zip = zipStream.createZip({ level: 1 })
out = fs.createWriteStream('test/files/js.zip')
zip.pipe(out)
testassets.addTypeToZip('js', zip, () ->
zip.finalize((written) ->
written.should.equal(62918)
done()))
describe '#addToZip',
() ->
it 'Adds all assets to zip',
(done) ->
zip = zipStream.createZip({ level: 1 })
out = fs.createWriteStream('test/files/assets.zip')
zip.pipe(out)
testassets.addToZip(zip, () ->
zip.finalize((written) ->
written.should.equal(386001)
done()))
describe '#mangleFonts',
() ->
it 'Adds all mangled fonts to zip',
(done) ->
zip = zipStream.createZip({ level: 1 })
out = fs.createWriteStream('test/files/mangledfonts.zip')
zip.pipe(out)
testassets.mangleFonts(zip, "4FD972A1-EFA8-484F-9AB3-878E817AF30D", () ->
zip.finalize((written) ->
written.should.equal(124787)
done()))
describe 'EpubBook',
() ->
beforeEach (done) ->
assets = new Assets("test/files/", "assets/")
testbook = new Book({
title: 'The Wonderful Wizard of Oz',
author: 'L. Frank Baum',
bookId: "this-is-an-id"
lang: "en"
cover: "assets/cover.jpg"
description: 'foo'
publisher: 'Bar'
subject1: 'Foobar'
version: "1.0"
date: "2013-05-15T00:00:00Z"
copyrightYear: "19watsit"
}, assets)
for chap in testchapters
testbook.addChapter(new Chapter(chap))
testbook.meta.start = testbook.chapters[1]
testbook.assets.init(done)
describe '#addChaptersToZip',
() ->
it 'Adds all chapters to zip (chapters.zip)',
(done) ->
zip = zipStream.createZip({ level: 1 })
out = fs.createWriteStream('test/files/chapters.zip')
zip.pipe(out)
testbook.addChaptersToZip(zip, null, () ->
zip.finalize((written) ->
written.should.equal(2130)
done()))
describe '#toEpub',
() ->
it 'Renders the book to epub',
(done) ->
this.timeout(10000)
out = fs.createWriteStream('test/files/test.epub')
testbook.toEpub(out, null, (err, thing) ->
if err
done(err)
console.log thing
checkReport = (error, stdout, stderr) =>
if error
done error
if stderr
done stderr
if stdout
console.log stdout
done()
exec('epubcheck test/files/test.epub', checkReport)
, undefined, (notice) -> console.log notice)
| 57846 | 'use strict'
chai = require 'chai'
should = chai.should()
index = require '../src/index'
Chapter = index.Chapter
Book = index.Book
Assets = index.Assets
zipStream = require('zipstream-contentment')
fs = require 'fs'
exec = require('child_process').exec
testoutline = {
id: 'titlepage',
filename: 'title.html',
title: 'Title Page',
render: true,
template: 'title.hbs',
majornavitem: true,
subChapters: [
{
id: 'nav',
filename: 'index.html',
render: false,
title: 'Table of Contents',
nomanifest: true,
majornavitem: true,
toc: true
},
{
id: 'titlepage',
filename: 'title.html',
title: 'Title Page',
render: true,
template: 'title.hbs',
majornavitem: true
},
{
id: 'titletoc',
filename: 'title.html',
title: 'Contents',
render: true,
template: 'titletoc.hbs',
majornavitem: true,
toc: true
},
{
type: 'md'
body: '# This is Markdown!'
}]
}
testbook = {}
testchapters = [{
type: 'md',
title: 'Markdown',
body: '# header\n\nTest'
},
{
type: 'html',
id: 'htmlexample',
filename: 'htmlexample.html',
title: 'HTML',
arbitraryMeta: 'is arbitrary'
body: '<h1>header</h1><p>Test<br>‘—’“–” </p>'
},
{
type: 'xhtml',
title: 'XHTML',
body: '<h1>header</h1><p>Test<br/></p>'
},
{
type: 'hbs',
title: 'Template',
body: '<h1>{{title}}</h1><p>Test<br>‘—’“–” </p>'
}
]
describe 'EpubChapter',
() ->
beforeEach (done) ->
assets = new Assets("test/files/", "assets/")
testbook = new Book({
title: 'The Wonderful Wizard of Oz',
author: '<NAME>'}, assets)
testbook.assets.init(done)
describe '#addToZip',
() ->
it 'Returns a promise to add the chapter to zip (test.zip)',
(done) ->
zip = zipStream.createZip({ level: 1 })
out = fs.createWriteStream('test/files/test.zip')
zip.pipe(out)
testbook.addChapter(new Chapter(testchapters[1]))
testbook.chapters[0].addToZip(zip, null, () ->
zip.finalize((written) ->
written.should.equal(540)
done()))
testassets = {}
describe 'EpubAssets',
() ->
beforeEach (done) ->
testassets = new index.Assets('test/files/', 'assets/')
testassets.init(done)
describe '#addTypeToZip',
() ->
it 'Adds all assets of a type to zip',
(done) ->
zip = zipStream.createZip({ level: 1 })
out = fs.createWriteStream('test/files/js.zip')
zip.pipe(out)
testassets.addTypeToZip('js', zip, () ->
zip.finalize((written) ->
written.should.equal(62918)
done()))
describe '#addToZip',
() ->
it 'Adds all assets to zip',
(done) ->
zip = zipStream.createZip({ level: 1 })
out = fs.createWriteStream('test/files/assets.zip')
zip.pipe(out)
testassets.addToZip(zip, () ->
zip.finalize((written) ->
written.should.equal(386001)
done()))
describe '#mangleFonts',
() ->
it 'Adds all mangled fonts to zip',
(done) ->
zip = zipStream.createZip({ level: 1 })
out = fs.createWriteStream('test/files/mangledfonts.zip')
zip.pipe(out)
testassets.mangleFonts(zip, "4FD972A1-EFA8-484F-9AB3-878E817AF30D", () ->
zip.finalize((written) ->
written.should.equal(124787)
done()))
describe 'EpubBook',
() ->
beforeEach (done) ->
assets = new Assets("test/files/", "assets/")
testbook = new Book({
title: 'The Wonderful Wizard of Oz',
author: '<NAME>',
bookId: "this-is-an-id"
lang: "en"
cover: "assets/cover.jpg"
description: 'foo'
publisher: 'Bar'
subject1: 'Foobar'
version: "1.0"
date: "2013-05-15T00:00:00Z"
copyrightYear: "19watsit"
}, assets)
for chap in testchapters
testbook.addChapter(new Chapter(chap))
testbook.meta.start = testbook.chapters[1]
testbook.assets.init(done)
describe '#addChaptersToZip',
() ->
it 'Adds all chapters to zip (chapters.zip)',
(done) ->
zip = zipStream.createZip({ level: 1 })
out = fs.createWriteStream('test/files/chapters.zip')
zip.pipe(out)
testbook.addChaptersToZip(zip, null, () ->
zip.finalize((written) ->
written.should.equal(2130)
done()))
describe '#toEpub',
() ->
it 'Renders the book to epub',
(done) ->
this.timeout(10000)
out = fs.createWriteStream('test/files/test.epub')
testbook.toEpub(out, null, (err, thing) ->
if err
done(err)
console.log thing
checkReport = (error, stdout, stderr) =>
if error
done error
if stderr
done stderr
if stdout
console.log stdout
done()
exec('epubcheck test/files/test.epub', checkReport)
, undefined, (notice) -> console.log notice)
| true | 'use strict'
chai = require 'chai'
should = chai.should()
index = require '../src/index'
Chapter = index.Chapter
Book = index.Book
Assets = index.Assets
zipStream = require('zipstream-contentment')
fs = require 'fs'
exec = require('child_process').exec
testoutline = {
id: 'titlepage',
filename: 'title.html',
title: 'Title Page',
render: true,
template: 'title.hbs',
majornavitem: true,
subChapters: [
{
id: 'nav',
filename: 'index.html',
render: false,
title: 'Table of Contents',
nomanifest: true,
majornavitem: true,
toc: true
},
{
id: 'titlepage',
filename: 'title.html',
title: 'Title Page',
render: true,
template: 'title.hbs',
majornavitem: true
},
{
id: 'titletoc',
filename: 'title.html',
title: 'Contents',
render: true,
template: 'titletoc.hbs',
majornavitem: true,
toc: true
},
{
type: 'md'
body: '# This is Markdown!'
}]
}
testbook = {}
testchapters = [{
type: 'md',
title: 'Markdown',
body: '# header\n\nTest'
},
{
type: 'html',
id: 'htmlexample',
filename: 'htmlexample.html',
title: 'HTML',
arbitraryMeta: 'is arbitrary'
body: '<h1>header</h1><p>Test<br>‘—’“–” </p>'
},
{
type: 'xhtml',
title: 'XHTML',
body: '<h1>header</h1><p>Test<br/></p>'
},
{
type: 'hbs',
title: 'Template',
body: '<h1>{{title}}</h1><p>Test<br>‘—’“–” </p>'
}
]
describe 'EpubChapter',
() ->
beforeEach (done) ->
assets = new Assets("test/files/", "assets/")
testbook = new Book({
title: 'The Wonderful Wizard of Oz',
author: 'PI:NAME:<NAME>END_PI'}, assets)
testbook.assets.init(done)
describe '#addToZip',
() ->
it 'Returns a promise to add the chapter to zip (test.zip)',
(done) ->
zip = zipStream.createZip({ level: 1 })
out = fs.createWriteStream('test/files/test.zip')
zip.pipe(out)
testbook.addChapter(new Chapter(testchapters[1]))
testbook.chapters[0].addToZip(zip, null, () ->
zip.finalize((written) ->
written.should.equal(540)
done()))
testassets = {}
describe 'EpubAssets',
() ->
beforeEach (done) ->
testassets = new index.Assets('test/files/', 'assets/')
testassets.init(done)
describe '#addTypeToZip',
() ->
it 'Adds all assets of a type to zip',
(done) ->
zip = zipStream.createZip({ level: 1 })
out = fs.createWriteStream('test/files/js.zip')
zip.pipe(out)
testassets.addTypeToZip('js', zip, () ->
zip.finalize((written) ->
written.should.equal(62918)
done()))
describe '#addToZip',
() ->
it 'Adds all assets to zip',
(done) ->
zip = zipStream.createZip({ level: 1 })
out = fs.createWriteStream('test/files/assets.zip')
zip.pipe(out)
testassets.addToZip(zip, () ->
zip.finalize((written) ->
written.should.equal(386001)
done()))
describe '#mangleFonts',
() ->
it 'Adds all mangled fonts to zip',
(done) ->
zip = zipStream.createZip({ level: 1 })
out = fs.createWriteStream('test/files/mangledfonts.zip')
zip.pipe(out)
testassets.mangleFonts(zip, "4FD972A1-EFA8-484F-9AB3-878E817AF30D", () ->
zip.finalize((written) ->
written.should.equal(124787)
done()))
describe 'EpubBook',
() ->
beforeEach (done) ->
assets = new Assets("test/files/", "assets/")
testbook = new Book({
title: 'The Wonderful Wizard of Oz',
author: 'PI:NAME:<NAME>END_PI',
bookId: "this-is-an-id"
lang: "en"
cover: "assets/cover.jpg"
description: 'foo'
publisher: 'Bar'
subject1: 'Foobar'
version: "1.0"
date: "2013-05-15T00:00:00Z"
copyrightYear: "19watsit"
}, assets)
for chap in testchapters
testbook.addChapter(new Chapter(chap))
testbook.meta.start = testbook.chapters[1]
testbook.assets.init(done)
describe '#addChaptersToZip',
() ->
it 'Adds all chapters to zip (chapters.zip)',
(done) ->
zip = zipStream.createZip({ level: 1 })
out = fs.createWriteStream('test/files/chapters.zip')
zip.pipe(out)
testbook.addChaptersToZip(zip, null, () ->
zip.finalize((written) ->
written.should.equal(2130)
done()))
describe '#toEpub',
() ->
it 'Renders the book to epub',
(done) ->
this.timeout(10000)
out = fs.createWriteStream('test/files/test.epub')
testbook.toEpub(out, null, (err, thing) ->
if err
done(err)
console.log thing
checkReport = (error, stdout, stderr) =>
if error
done error
if stderr
done stderr
if stdout
console.log stdout
done()
exec('epubcheck test/files/test.epub', checkReport)
, undefined, (notice) -> console.log notice)
|
[
{
"context": "###\nCopyright 2017 Balena\n\nLicensed under the Apache License, Version 2.0 (",
"end": 25,
"score": 0.9904049038887024,
"start": 19,
"tag": "NAME",
"value": "Balena"
},
{
"context": "mage, new format, according to https://github.com/resin-os/meta-resin/pull/770/files\n... | lib/network.coffee | resin-io-modules/resin-device-init | 3 | ###
Copyright 2017 Balena
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
###
###*
# @module network
###
_ = require('lodash')
path = require('path')
imagefs = require('balena-image-fs')
reconfix = require('reconfix')
Promise = require('bluebird')
utils = require('./utils')
CONNECTIONS_FOLDER = '/system-connections'
getConfigPathDefinition = (manifest, configPath) ->
configPathDefinition = utils.convertFilePathDefinition(manifest.configuration.config)
# Config locations are assumed to be the same as config.json, except the path itself
configPathDefinition.path = configPath
return configPathDefinition
fileNotFoundError = (e) ->
e.code == 'ENOENT'
###*
# @summary Configure network on an ResinOS 1.x image
# @function
# @public
#
# @description
# This function injects network settings into the device.
#
# @param {String} image - path to image
# @param {Object} config - a fully populated config object
# @param {Object} [answers] - configuration options
#
# @returns {Promise<void>}
###
exports.configureOS1Network = (image, manifest, answers) ->
prepareImageOS1NetworkConfig(image, manifest)
.then ->
schema = getOS1ConfigurationSchema(manifest, answers)
if manifest.configuration.config.image
image = path.join(image, manifest.configuration.config.image)
reconfix.writeConfiguration(schema, answers, image)
###*
# @summary Configure network on an ResinOS 2.x image
# @function
# @public
#
# @description
# This function injects network settings into the device.
#
# @param {String} image - path to image
# @param {Object} config - a fully populated config object
# @param {Object} [answers] - configuration options
#
# @returns {Promise<void>}
###
exports.configureOS2Network = (image, manifest, answers) ->
if answers.network != 'wifi'
# For ethernet, we don't need to do anything
# For anything else, we don't know what to do
return
prepareImageOS2WifiConfig(image, manifest)
.then ->
schema = getOS2WifiConfigurationSchema(manifest, answers)
if manifest.configuration.config.image
image = path.join(image, manifest.configuration.config.image)
reconfix.writeConfiguration(schema, answers, image)
prepareImageOS1NetworkConfig = (target, manifest) ->
# This is required because reconfix borks if the child files specified are
# completely undefined when it tries to read (before writing) the config
configFilePath = utils.definitionForImage(target, utils.convertFilePathDefinition(manifest.configuration.config))
imagefs.interact(
configFilePath.image
configFilePath.partition
(_fs) ->
readFileAsync = Promise.promisify(_fs.readFile)
writeFileAsync = Promise.promisify(_fs.writeFile)
return readFileAsync(configFilePath.path, { encoding: 'utf8' })
.catch(fileNotFoundError, -> '{}')
.then(JSON.parse)
.then (contents) ->
contents.files ?= {}
contents.files['network/network.config'] ?= ''
writeFileAsync(configFilePath.path, JSON.stringify(contents))
)
###*
# @summary Prepare the image to ensure the wifi reconfix schema is applyable
# @function
# @private
#
# @description
# Ensure the image has a resin-wifi file ready to configure, based
# on the existing resin-sample.ignore or resin-sample files, if present.
#
# @param {String} target - path to the target image
# @param {Object} manifest - the device type manifest for the image
#
# @returns {Promise<void>}
###
prepareImageOS2WifiConfig = (target, manifest) ->
###
# We need to ensure a template network settings file exists at resin-wifi. To do that:
# * if the `resin-wifi` file exists (previously configured image or downloaded from the UI) we're all good
# * if the `resin-sample` exists, it's copied to resin-sample.ignore
# * if the `resin-sample.ignore` exists, it's copied to `resin-wifi`
# * otherwise, the new file is created from a hardcoded template
###
connectionsFolderDefinition = utils.definitionForImage(target, getConfigPathDefinition(manifest, CONNECTIONS_FOLDER))
imagefs.interact(
connectionsFolderDefinition.image
connectionsFolderDefinition.partition
(_fs) ->
readdirAsync = Promise.promisify(_fs.readdir)
return readdirAsync(connectionsFolderDefinition.path)
)
.then (files) ->
# The required file already exists
if _.includes(files, 'resin-wifi')
return
# Fresh image, new format, according to https://github.com/resin-os/meta-resin/pull/770/files
if _.includes(files, 'resin-sample.ignore')
inputDefinition = utils.definitionForImage(target, getConfigPathDefinition(manifest, "#{CONNECTIONS_FOLDER}/resin-sample.ignore"))
outputDefinition = utils.definitionForImage(target, getConfigPathDefinition(manifest, "#{CONNECTIONS_FOLDER}/resin-wifi"))
return imagefs.interact(
inputDefinition.image
inputDefinition.partition
(_fs) ->
readFileAsync = Promise.promisify(_fs.readFile)
writeFileAsync = Promise.promisify(_fs.writeFile)
return readFileAsync(inputDefinition.path, { encoding: 'utf8' })
.then (contents) ->
return writeFileAsync(outputDefinition.path, contents)
)
# Fresh image, old format
if _.includes(files, 'resin-sample')
inputDefinition = utils.definitionForImage(target, getConfigPathDefinition(manifest, "#{CONNECTIONS_FOLDER}/resin-sample"))
outputDefinition = utils.definitionForImage(target, getConfigPathDefinition(manifest, "#{CONNECTIONS_FOLDER}/resin-wifi"))
return imagefs.interact(
inputDefinition.image
inputDefinition.partition
(_fs) ->
readFileAsync = Promise.promisify(_fs.readFile)
writeFileAsync = Promise.promisify(_fs.writeFile)
return readFileAsync(inputDefinition.path, { encoding: 'utf8' })
.then (contents) ->
return writeFileAsync(outputDefinition.path, contents)
)
# In case there's no file at all (shouldn't happen normally, but the file might have been removed)
definition = utils.definitionForImage(target, getConfigPathDefinition(manifest, "#{CONNECTIONS_FOLDER}/resin-wifi"))
return imagefs.interact(
definition.image
definition.partition
(_fs) ->
writeFileAsync = Promise.promisify(_fs.writeFile)
return writeFileAsync(definition.path, DEFAULT_CONNECTION_FILE)
)
# Taken from https://goo.gl/kr1kCt
DEFAULT_CONNECTION_FILE = '''
[connection]
id=resin-wifi
type=wifi
[wifi]
hidden=true
mode=infrastructure
ssid=My_Wifi_Ssid
[wifi-security]
auth-alg=open
key-mgmt=wpa-psk
psk=super_secret_wifi_password
[ipv4]
method=auto
[ipv6]
addr-gen-mode=stable-privacy
method=auto
'''
getOS1ConfigurationSchema = (manifest, answers) ->
# We could switch between schemas using `choice`, but right now that has different semantics, where
# it wipes the whole of the rest of the file, whereas using a fixed schema does not. We should
# handle this nicer when we move to rust reconfix.
if answers.network == 'wifi'
getOS1WifiConfigurationSchema(manifest)
else
getOS1EthernetConfiguration(manifest)
getOS1EthernetConfiguration = (manifest) ->
mapper: [
{
# This is a hack - if we don't specify any mapping for config.json, then
# the next mapping wipes it completely, leaving only the `files` block.
# `files` here is used just because it's safe - we're about to overwrite it.
domain: [
[ 'config_json', 'files' ]
]
template: {
'files': {}
}
}
{
domain: [
[ 'network_config', 'service_home_ethernet' ]
]
template: {
'service_home_ethernet': {
'Type': 'ethernet'
'Nameservers': '8.8.8.8,8.8.4.4'
}
}
}
]
files:
config_json:
type: 'json'
location:
getConfigPathDefinition(manifest, '/config.json')
network_config:
type: 'ini'
location:
parent: 'config_json'
property: [ 'files', 'network/network.config' ]
getOS1WifiConfigurationSchema = (manifest) ->
mapper: [
{
domain: [
[ 'config_json', 'wifiSsid' ]
[ 'config_json', 'wifiKey' ]
]
template: {
'wifiSsid': '{{wifiSsid}}'
'wifiKey': '{{wifiKey}}'
}
}
{
domain: [
[ 'network_config', 'service_home_ethernet' ]
[ 'network_config', 'service_home_wifi' ]
]
template: {
'service_home_ethernet': {
'Type': 'ethernet'
'Nameservers': '8.8.8.8,8.8.4.4'
}
'service_home_wifi': {
'Hidden': true
'Type': 'wifi'
'Name': '{{wifiSsid}}'
'Passphrase': '{{wifiKey}}'
'Nameservers': '8.8.8.8,8.8.4.4'
}
}
}
]
files:
config_json:
type: 'json'
location:
getConfigPathDefinition(manifest, '/config.json')
network_config:
type: 'ini'
location:
parent: 'config_json'
property: [ 'files', 'network/network.config' ]
getOS2WifiConfigurationSchema = (manifest) ->
mapper: [
{
domain: [
[ 'system_connections', 'resin-wifi', 'wifi' ]
[ 'system_connections', 'resin-wifi', 'wifi-security' ]
]
template: {
'wifi': {
'ssid': '{{wifiSsid}}'
}
'wifi-security': {
'psk': '{{wifiKey}}'
}
}
}
]
files:
system_connections:
fileset: true
type: 'ini'
location:
getConfigPathDefinition(manifest, CONNECTIONS_FOLDER)
| 102412 | ###
Copyright 2017 <NAME>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
###
###*
# @module network
###
_ = require('lodash')
path = require('path')
imagefs = require('balena-image-fs')
reconfix = require('reconfix')
Promise = require('bluebird')
utils = require('./utils')
CONNECTIONS_FOLDER = '/system-connections'
getConfigPathDefinition = (manifest, configPath) ->
configPathDefinition = utils.convertFilePathDefinition(manifest.configuration.config)
# Config locations are assumed to be the same as config.json, except the path itself
configPathDefinition.path = configPath
return configPathDefinition
fileNotFoundError = (e) ->
e.code == 'ENOENT'
###*
# @summary Configure network on an ResinOS 1.x image
# @function
# @public
#
# @description
# This function injects network settings into the device.
#
# @param {String} image - path to image
# @param {Object} config - a fully populated config object
# @param {Object} [answers] - configuration options
#
# @returns {Promise<void>}
###
exports.configureOS1Network = (image, manifest, answers) ->
prepareImageOS1NetworkConfig(image, manifest)
.then ->
schema = getOS1ConfigurationSchema(manifest, answers)
if manifest.configuration.config.image
image = path.join(image, manifest.configuration.config.image)
reconfix.writeConfiguration(schema, answers, image)
###*
# @summary Configure network on an ResinOS 2.x image
# @function
# @public
#
# @description
# This function injects network settings into the device.
#
# @param {String} image - path to image
# @param {Object} config - a fully populated config object
# @param {Object} [answers] - configuration options
#
# @returns {Promise<void>}
###
exports.configureOS2Network = (image, manifest, answers) ->
if answers.network != 'wifi'
# For ethernet, we don't need to do anything
# For anything else, we don't know what to do
return
prepareImageOS2WifiConfig(image, manifest)
.then ->
schema = getOS2WifiConfigurationSchema(manifest, answers)
if manifest.configuration.config.image
image = path.join(image, manifest.configuration.config.image)
reconfix.writeConfiguration(schema, answers, image)
prepareImageOS1NetworkConfig = (target, manifest) ->
# This is required because reconfix borks if the child files specified are
# completely undefined when it tries to read (before writing) the config
configFilePath = utils.definitionForImage(target, utils.convertFilePathDefinition(manifest.configuration.config))
imagefs.interact(
configFilePath.image
configFilePath.partition
(_fs) ->
readFileAsync = Promise.promisify(_fs.readFile)
writeFileAsync = Promise.promisify(_fs.writeFile)
return readFileAsync(configFilePath.path, { encoding: 'utf8' })
.catch(fileNotFoundError, -> '{}')
.then(JSON.parse)
.then (contents) ->
contents.files ?= {}
contents.files['network/network.config'] ?= ''
writeFileAsync(configFilePath.path, JSON.stringify(contents))
)
###*
# @summary Prepare the image to ensure the wifi reconfix schema is applyable
# @function
# @private
#
# @description
# Ensure the image has a resin-wifi file ready to configure, based
# on the existing resin-sample.ignore or resin-sample files, if present.
#
# @param {String} target - path to the target image
# @param {Object} manifest - the device type manifest for the image
#
# @returns {Promise<void>}
###
prepareImageOS2WifiConfig = (target, manifest) ->
###
# We need to ensure a template network settings file exists at resin-wifi. To do that:
# * if the `resin-wifi` file exists (previously configured image or downloaded from the UI) we're all good
# * if the `resin-sample` exists, it's copied to resin-sample.ignore
# * if the `resin-sample.ignore` exists, it's copied to `resin-wifi`
# * otherwise, the new file is created from a hardcoded template
###
connectionsFolderDefinition = utils.definitionForImage(target, getConfigPathDefinition(manifest, CONNECTIONS_FOLDER))
imagefs.interact(
connectionsFolderDefinition.image
connectionsFolderDefinition.partition
(_fs) ->
readdirAsync = Promise.promisify(_fs.readdir)
return readdirAsync(connectionsFolderDefinition.path)
)
.then (files) ->
# The required file already exists
if _.includes(files, 'resin-wifi')
return
# Fresh image, new format, according to https://github.com/resin-os/meta-resin/pull/770/files
if _.includes(files, 'resin-sample.ignore')
inputDefinition = utils.definitionForImage(target, getConfigPathDefinition(manifest, "#{CONNECTIONS_FOLDER}/resin-sample.ignore"))
outputDefinition = utils.definitionForImage(target, getConfigPathDefinition(manifest, "#{CONNECTIONS_FOLDER}/resin-wifi"))
return imagefs.interact(
inputDefinition.image
inputDefinition.partition
(_fs) ->
readFileAsync = Promise.promisify(_fs.readFile)
writeFileAsync = Promise.promisify(_fs.writeFile)
return readFileAsync(inputDefinition.path, { encoding: 'utf8' })
.then (contents) ->
return writeFileAsync(outputDefinition.path, contents)
)
# Fresh image, old format
if _.includes(files, 'resin-sample')
inputDefinition = utils.definitionForImage(target, getConfigPathDefinition(manifest, "#{CONNECTIONS_FOLDER}/resin-sample"))
outputDefinition = utils.definitionForImage(target, getConfigPathDefinition(manifest, "#{CONNECTIONS_FOLDER}/resin-wifi"))
return imagefs.interact(
inputDefinition.image
inputDefinition.partition
(_fs) ->
readFileAsync = Promise.promisify(_fs.readFile)
writeFileAsync = Promise.promisify(_fs.writeFile)
return readFileAsync(inputDefinition.path, { encoding: 'utf8' })
.then (contents) ->
return writeFileAsync(outputDefinition.path, contents)
)
# In case there's no file at all (shouldn't happen normally, but the file might have been removed)
definition = utils.definitionForImage(target, getConfigPathDefinition(manifest, "#{CONNECTIONS_FOLDER}/resin-wifi"))
return imagefs.interact(
definition.image
definition.partition
(_fs) ->
writeFileAsync = Promise.promisify(_fs.writeFile)
return writeFileAsync(definition.path, DEFAULT_CONNECTION_FILE)
)
# Taken from https://goo.gl/kr1kCt
DEFAULT_CONNECTION_FILE = '''
[connection]
id=resin-wifi
type=wifi
[wifi]
hidden=true
mode=infrastructure
ssid=My_Wifi_Ssid
[wifi-security]
auth-alg=open
key-mgmt=wpa-psk
psk=<PASSWORD>
[ipv4]
method=auto
[ipv6]
addr-gen-mode=stable-privacy
method=auto
'''
getOS1ConfigurationSchema = (manifest, answers) ->
# We could switch between schemas using `choice`, but right now that has different semantics, where
# it wipes the whole of the rest of the file, whereas using a fixed schema does not. We should
# handle this nicer when we move to rust reconfix.
if answers.network == 'wifi'
getOS1WifiConfigurationSchema(manifest)
else
getOS1EthernetConfiguration(manifest)
getOS1EthernetConfiguration = (manifest) ->
mapper: [
{
# This is a hack - if we don't specify any mapping for config.json, then
# the next mapping wipes it completely, leaving only the `files` block.
# `files` here is used just because it's safe - we're about to overwrite it.
domain: [
[ 'config_json', 'files' ]
]
template: {
'files': {}
}
}
{
domain: [
[ 'network_config', 'service_home_ethernet' ]
]
template: {
'service_home_ethernet': {
'Type': 'ethernet'
'Nameservers': '8.8.8.8,8.8.4.4'
}
}
}
]
files:
config_json:
type: 'json'
location:
getConfigPathDefinition(manifest, '/config.json')
network_config:
type: 'ini'
location:
parent: 'config_json'
property: [ 'files', 'network/network.config' ]
getOS1WifiConfigurationSchema = (manifest) ->
mapper: [
{
domain: [
[ 'config_json', 'wifiSsid' ]
[ 'config_json', 'wifiKey' ]
]
template: {
'wifiSsid': '{{wifiSsid}}'
'wifiKey': '{{wifiKey}}'
}
}
{
domain: [
[ 'network_config', 'service_home_ethernet' ]
[ 'network_config', 'service_home_wifi' ]
]
template: {
'service_home_ethernet': {
'Type': 'ethernet'
'Nameservers': '8.8.8.8,8.8.4.4'
}
'service_home_wifi': {
'Hidden': true
'Type': 'wifi'
'Name': '{{wifiSsid}}'
'Passphrase': <PASSWORD>}}'
'Nameservers': '8.8.8.8,8.8.4.4'
}
}
}
]
files:
config_json:
type: 'json'
location:
getConfigPathDefinition(manifest, '/config.json')
network_config:
type: 'ini'
location:
parent: 'config_json'
property: [ 'files', 'network/network.config' ]
getOS2WifiConfigurationSchema = (manifest) ->
mapper: [
{
domain: [
[ 'system_connections', 'resin-wifi', 'wifi' ]
[ 'system_connections', 'resin-wifi', 'wifi-security' ]
]
template: {
'wifi': {
'ssid': '{{wifiSsid}}'
}
'wifi-security': {
'psk': '{{wifiKey}}'
}
}
}
]
files:
system_connections:
fileset: true
type: 'ini'
location:
getConfigPathDefinition(manifest, CONNECTIONS_FOLDER)
| true | ###
Copyright 2017 PI:NAME:<NAME>END_PI
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
###
###*
# @module network
###
_ = require('lodash')
path = require('path')
imagefs = require('balena-image-fs')
reconfix = require('reconfix')
Promise = require('bluebird')
utils = require('./utils')
CONNECTIONS_FOLDER = '/system-connections'
getConfigPathDefinition = (manifest, configPath) ->
configPathDefinition = utils.convertFilePathDefinition(manifest.configuration.config)
# Config locations are assumed to be the same as config.json, except the path itself
configPathDefinition.path = configPath
return configPathDefinition
fileNotFoundError = (e) ->
e.code == 'ENOENT'
###*
# @summary Configure network on an ResinOS 1.x image
# @function
# @public
#
# @description
# This function injects network settings into the device.
#
# @param {String} image - path to image
# @param {Object} config - a fully populated config object
# @param {Object} [answers] - configuration options
#
# @returns {Promise<void>}
###
exports.configureOS1Network = (image, manifest, answers) ->
prepareImageOS1NetworkConfig(image, manifest)
.then ->
schema = getOS1ConfigurationSchema(manifest, answers)
if manifest.configuration.config.image
image = path.join(image, manifest.configuration.config.image)
reconfix.writeConfiguration(schema, answers, image)
###*
# @summary Configure network on an ResinOS 2.x image
# @function
# @public
#
# @description
# This function injects network settings into the device.
#
# @param {String} image - path to image
# @param {Object} config - a fully populated config object
# @param {Object} [answers] - configuration options
#
# @returns {Promise<void>}
###
exports.configureOS2Network = (image, manifest, answers) ->
if answers.network != 'wifi'
# For ethernet, we don't need to do anything
# For anything else, we don't know what to do
return
prepareImageOS2WifiConfig(image, manifest)
.then ->
schema = getOS2WifiConfigurationSchema(manifest, answers)
if manifest.configuration.config.image
image = path.join(image, manifest.configuration.config.image)
reconfix.writeConfiguration(schema, answers, image)
prepareImageOS1NetworkConfig = (target, manifest) ->
# This is required because reconfix borks if the child files specified are
# completely undefined when it tries to read (before writing) the config
configFilePath = utils.definitionForImage(target, utils.convertFilePathDefinition(manifest.configuration.config))
imagefs.interact(
configFilePath.image
configFilePath.partition
(_fs) ->
readFileAsync = Promise.promisify(_fs.readFile)
writeFileAsync = Promise.promisify(_fs.writeFile)
return readFileAsync(configFilePath.path, { encoding: 'utf8' })
.catch(fileNotFoundError, -> '{}')
.then(JSON.parse)
.then (contents) ->
contents.files ?= {}
contents.files['network/network.config'] ?= ''
writeFileAsync(configFilePath.path, JSON.stringify(contents))
)
###*
# @summary Prepare the image to ensure the wifi reconfix schema is applyable
# @function
# @private
#
# @description
# Ensure the image has a resin-wifi file ready to configure, based
# on the existing resin-sample.ignore or resin-sample files, if present.
#
# @param {String} target - path to the target image
# @param {Object} manifest - the device type manifest for the image
#
# @returns {Promise<void>}
###
prepareImageOS2WifiConfig = (target, manifest) ->
###
# We need to ensure a template network settings file exists at resin-wifi. To do that:
# * if the `resin-wifi` file exists (previously configured image or downloaded from the UI) we're all good
# * if the `resin-sample` exists, it's copied to resin-sample.ignore
# * if the `resin-sample.ignore` exists, it's copied to `resin-wifi`
# * otherwise, the new file is created from a hardcoded template
###
connectionsFolderDefinition = utils.definitionForImage(target, getConfigPathDefinition(manifest, CONNECTIONS_FOLDER))
imagefs.interact(
connectionsFolderDefinition.image
connectionsFolderDefinition.partition
(_fs) ->
readdirAsync = Promise.promisify(_fs.readdir)
return readdirAsync(connectionsFolderDefinition.path)
)
.then (files) ->
# The required file already exists
if _.includes(files, 'resin-wifi')
return
# Fresh image, new format, according to https://github.com/resin-os/meta-resin/pull/770/files
if _.includes(files, 'resin-sample.ignore')
inputDefinition = utils.definitionForImage(target, getConfigPathDefinition(manifest, "#{CONNECTIONS_FOLDER}/resin-sample.ignore"))
outputDefinition = utils.definitionForImage(target, getConfigPathDefinition(manifest, "#{CONNECTIONS_FOLDER}/resin-wifi"))
return imagefs.interact(
inputDefinition.image
inputDefinition.partition
(_fs) ->
readFileAsync = Promise.promisify(_fs.readFile)
writeFileAsync = Promise.promisify(_fs.writeFile)
return readFileAsync(inputDefinition.path, { encoding: 'utf8' })
.then (contents) ->
return writeFileAsync(outputDefinition.path, contents)
)
# Fresh image, old format
if _.includes(files, 'resin-sample')
inputDefinition = utils.definitionForImage(target, getConfigPathDefinition(manifest, "#{CONNECTIONS_FOLDER}/resin-sample"))
outputDefinition = utils.definitionForImage(target, getConfigPathDefinition(manifest, "#{CONNECTIONS_FOLDER}/resin-wifi"))
return imagefs.interact(
inputDefinition.image
inputDefinition.partition
(_fs) ->
readFileAsync = Promise.promisify(_fs.readFile)
writeFileAsync = Promise.promisify(_fs.writeFile)
return readFileAsync(inputDefinition.path, { encoding: 'utf8' })
.then (contents) ->
return writeFileAsync(outputDefinition.path, contents)
)
# In case there's no file at all (shouldn't happen normally, but the file might have been removed)
definition = utils.definitionForImage(target, getConfigPathDefinition(manifest, "#{CONNECTIONS_FOLDER}/resin-wifi"))
return imagefs.interact(
definition.image
definition.partition
(_fs) ->
writeFileAsync = Promise.promisify(_fs.writeFile)
return writeFileAsync(definition.path, DEFAULT_CONNECTION_FILE)
)
# Taken from https://goo.gl/kr1kCt
DEFAULT_CONNECTION_FILE = '''
[connection]
id=resin-wifi
type=wifi
[wifi]
hidden=true
mode=infrastructure
ssid=My_Wifi_Ssid
[wifi-security]
auth-alg=open
key-mgmt=wpa-psk
psk=PI:PASSWORD:<PASSWORD>END_PI
[ipv4]
method=auto
[ipv6]
addr-gen-mode=stable-privacy
method=auto
'''
getOS1ConfigurationSchema = (manifest, answers) ->
# We could switch between schemas using `choice`, but right now that has different semantics, where
# it wipes the whole of the rest of the file, whereas using a fixed schema does not. We should
# handle this nicer when we move to rust reconfix.
if answers.network == 'wifi'
getOS1WifiConfigurationSchema(manifest)
else
getOS1EthernetConfiguration(manifest)
getOS1EthernetConfiguration = (manifest) ->
mapper: [
{
# This is a hack - if we don't specify any mapping for config.json, then
# the next mapping wipes it completely, leaving only the `files` block.
# `files` here is used just because it's safe - we're about to overwrite it.
domain: [
[ 'config_json', 'files' ]
]
template: {
'files': {}
}
}
{
domain: [
[ 'network_config', 'service_home_ethernet' ]
]
template: {
'service_home_ethernet': {
'Type': 'ethernet'
'Nameservers': '8.8.8.8,8.8.4.4'
}
}
}
]
files:
config_json:
type: 'json'
location:
getConfigPathDefinition(manifest, '/config.json')
network_config:
type: 'ini'
location:
parent: 'config_json'
property: [ 'files', 'network/network.config' ]
getOS1WifiConfigurationSchema = (manifest) ->
mapper: [
{
domain: [
[ 'config_json', 'wifiSsid' ]
[ 'config_json', 'wifiKey' ]
]
template: {
'wifiSsid': '{{wifiSsid}}'
'wifiKey': '{{wifiKey}}'
}
}
{
domain: [
[ 'network_config', 'service_home_ethernet' ]
[ 'network_config', 'service_home_wifi' ]
]
template: {
'service_home_ethernet': {
'Type': 'ethernet'
'Nameservers': '8.8.8.8,8.8.4.4'
}
'service_home_wifi': {
'Hidden': true
'Type': 'wifi'
'Name': '{{wifiSsid}}'
'Passphrase': PI:PASSWORD:<PASSWORD>END_PI}}'
'Nameservers': '8.8.8.8,8.8.4.4'
}
}
}
]
files:
config_json:
type: 'json'
location:
getConfigPathDefinition(manifest, '/config.json')
network_config:
type: 'ini'
location:
parent: 'config_json'
property: [ 'files', 'network/network.config' ]
getOS2WifiConfigurationSchema = (manifest) ->
mapper: [
{
domain: [
[ 'system_connections', 'resin-wifi', 'wifi' ]
[ 'system_connections', 'resin-wifi', 'wifi-security' ]
]
template: {
'wifi': {
'ssid': '{{wifiSsid}}'
}
'wifi-security': {
'psk': '{{wifiKey}}'
}
}
}
]
files:
system_connections:
fileset: true
type: 'ini'
location:
getConfigPathDefinition(manifest, CONNECTIONS_FOLDER)
|
[
{
"context": "st/language-reference.html\n# - https://github.com/diku-dk/futhark-mode/blob/ca22b1e5/futhark-highlight.el\nn",
"end": 148,
"score": 0.9997382760047913,
"start": 141,
"tag": "USERNAME",
"value": "diku-dk"
},
{
"context": "rk-mode/blob/ca22b1e5/futhark-highlight.el\nname... | grammars/futhark.cson | Alhadis/language-etc | 5 | # Direct port of Emacs' `futhark-mode'. Sources:
# - https://futhark.readthedocs.io/en/latest/language-reference.html
# - https://github.com/diku-dk/futhark-mode/blob/ca22b1e5/futhark-highlight.el
name: "Futhark"
scopeName: "source.futhark"
fileTypes: ["fut"]
patterns: [include: "#main"]
firstLineMatch: """(?x)
# Emacs modeline
-\\*-(?i:[ \\t]*(?=[^:;\\s]+[ \\t]*-\\*-)|(?:.*?[ \\t;]|(?<=-\\*-))[ \\t]*mode[ \\t]*:[ \\t]*)
futhark
(?=[ \\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]*=
futhark
(?=$|\\s|:)
"""
repository:
main:
patterns: [
{include: "#typeBinding"}
{include: "#typeParameter"}
{include: "#functionDefinition"}
{include: "#comment"}
{include: "#keywords"}
{include: "#attribute"}
{include: "#numericTypes"}
{include: "#builtInTypes"}
{include: "#booleans"}
{include: "#number"}
{include: "#character"}
{include: "#var"}
{include: "#constructor"}
{include: "#operator"}
{match: "#"} # Inhibit `etc#comment` rule
{match: "'"} # Inhibit `etc#str` rule
{include: "etc#bracket"}
{include: "etc"}
]
typeBinding:
name: "meta.type.binding.futhark"
begin: "(?<![#'])\\b(module\\s+)?(type[~^]?)(?:\\s+([_A-Za-z]['\\w]*))?(?:\\b(?![#'])|(?<=')\\B(?!#))"
end: "=|(?=\\s*(?!--)[^\\s=])"
beginCaptures:
1: name: "storage.modifier.module.futhark"
2: name: "storage.type.decl.futhark"
3: name: "entity.name.type.futhark"
endCaptures:
0: name: "keyword.operator.futhark"
patterns: [
{include: "#comment"}
{include: "#typeParameter"}
]
typeParameter:
name: "entity.name.type.parameter.futhark"
match: "('[~^]?)[_A-Za-z]\\w*\\b(?![#'])"
captures:
1: name: "punctuation.definition.type.parameter.futhark"
functionDefinition:
match: "(?<![#'])\\b(let|entry)(?:\\s+([_A-Za-z]['\\w]*))?(?:\\b(?![#'])|(?<=')\\B(?!#))"
captures:
1: name: "storage.type.var.$1.futhark"
2: name: "entity.name.function.futhark"
comment:
name: "comment.line.double-dash.futhark"
begin: "--"
end: "$"
keywords:
name: "keyword.control.$1.futhark"
match: "(?<![#'])\\b(assert|case|do|else|entry|for|if|import|include|in|let|local|loop|match|module|open|then|unsafe|val|while|with)\\b(?![#'])"
attribute:
name: "meta.attribute.futhark"
match: "(#\\[)([^\\]]*)(\\])"
captures:
1: name: "punctuation.definition.attribute.begin.futhark"
2: name: "storage.modifier.attribute.futhark"
3: name: "punctuation.definition.attribute.end.futhark"
numericTypes:
name: "support.type.numeric.futhark"
match: "(?<![#'])\\b(f32|f64|i16|i32|i64|i8|u16|u32|u64|u8)\\b(?![#'])"
builtInTypes:
patterns: [
{match: "(?<![#'])(bool)\\b(?![#'])", name: "support.type.builtin.futhark"}
{include: "#numericTypes"}
]
booleans:
name: "constant.language.boolean.$1.futhark"
match: "(?<![#'])(true|false)\\b(?![#'])"
number:
name: "constant.numeric.futhark"
match: """(?x) -?
(?:
(?:0[xX])
[0-9a-fA-F]+
(?: \\.[0-9a-fA-F]+)?
(?: [Pp][+-]?[0-9]+)?
|
(?:0[bB])
[0-1_]+
|
[0-9]+
(?:\\.[0-9]+)?
(?:[Ee][+-]?[0-9]+)?
) (?:i8|i16|i32|i64|u8|u16|u32|u64|f32|f64)?
"""
character:
name: "string.quoted.single.character.futhark"
match: "(')[^']?(')"
captures:
1: name: "punctuation.definition.string.begin.futhark"
2: name: "punctuation.definition.string.end.futhark"
var:
name: "variable.other.readwrite.futhark"
match: "(?<![#'])\\b[_A-Za-z]['\\w]*"
constructor:
name: "entity.name.function.constructor.futhark"
match: "(#)['\\w]+"
captures:
1: name: "punctuation.definition.constructor.number-sign.futhark"
operator:
patterns: [{
name: "keyword.operator.futhark"
match: "[-+*/%!<>=&|@]+"
},{
name: "string.interpolated.quoted.backticks.futhark"
match: "(`)[^`]*(`)"
captures:
1: name: "punctuation.definition.string.begin.futhark"
2: name: "punctuation.definition.string.end.futhark"
}]
| 180450 | # Direct port of Emacs' `futhark-mode'. Sources:
# - https://futhark.readthedocs.io/en/latest/language-reference.html
# - https://github.com/diku-dk/futhark-mode/blob/ca22b1e5/futhark-highlight.el
name: "<NAME>uthark"
scopeName: "source.futhark"
fileTypes: ["fut"]
patterns: [include: "#main"]
firstLineMatch: """(?x)
# Emacs modeline
-\\*-(?i:[ \\t]*(?=[^:;\\s]+[ \\t]*-\\*-)|(?:.*?[ \\t;]|(?<=-\\*-))[ \\t]*mode[ \\t]*:[ \\t]*)
futhark
(?=[ \\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]*=
futhark
(?=$|\\s|:)
"""
repository:
main:
patterns: [
{include: "#typeBinding"}
{include: "#typeParameter"}
{include: "#functionDefinition"}
{include: "#comment"}
{include: "#keywords"}
{include: "#attribute"}
{include: "#numericTypes"}
{include: "#builtInTypes"}
{include: "#booleans"}
{include: "#number"}
{include: "#character"}
{include: "#var"}
{include: "#constructor"}
{include: "#operator"}
{match: "#"} # Inhibit `etc#comment` rule
{match: "'"} # Inhibit `etc#str` rule
{include: "etc#bracket"}
{include: "etc"}
]
typeBinding:
name: "meta.type.binding.futhark"
begin: "(?<![#'])\\b(module\\s+)?(type[~^]?)(?:\\s+([_A-Za-z]['\\w]*))?(?:\\b(?![#'])|(?<=')\\B(?!#))"
end: "=|(?=\\s*(?!--)[^\\s=])"
beginCaptures:
1: name: "storage.modifier.module.futhark"
2: name: "storage.type.decl.futhark"
3: name: "entity.name.type.futhark"
endCaptures:
0: name: "keyword.operator.futhark"
patterns: [
{include: "#comment"}
{include: "#typeParameter"}
]
typeParameter:
name: "entity.name.type.parameter.futhark"
match: "('[~^]?)[_A-Za-z]\\w*\\b(?![#'])"
captures:
1: name: "punctuation.definition.type.parameter.futhark"
functionDefinition:
match: "(?<![#'])\\b(let|entry)(?:\\s+([_A-Za-z]['\\w]*))?(?:\\b(?![#'])|(?<=')\\B(?!#))"
captures:
1: name: "storage.type.var.$1.futhark"
2: name: "entity.name.function.futhark"
comment:
name: "comment.line.double-dash.futhark"
begin: "--"
end: "$"
keywords:
name: "keyword.control.$1.futhark"
match: "(?<![#'])\\b(assert|case|do|else|entry|for|if|import|include|in|let|local|loop|match|module|open|then|unsafe|val|while|with)\\b(?![#'])"
attribute:
name: "meta.attribute.futhark"
match: "(#\\[)([^\\]]*)(\\])"
captures:
1: name: "punctuation.definition.attribute.begin.futhark"
2: name: "storage.modifier.attribute.futhark"
3: name: "punctuation.definition.attribute.end.futhark"
numericTypes:
name: "support.type.numeric.futhark"
match: "(?<![#'])\\b(f32|f64|i16|i32|i64|i8|u16|u32|u64|u8)\\b(?![#'])"
builtInTypes:
patterns: [
{match: "(?<![#'])(bool)\\b(?![#'])", name: "support.type.builtin.futhark"}
{include: "#numericTypes"}
]
booleans:
name: "constant.language.boolean.$1.futhark"
match: "(?<![#'])(true|false)\\b(?![#'])"
number:
name: "constant.numeric.futhark"
match: """(?x) -?
(?:
(?:0[xX])
[0-9a-fA-F]+
(?: \\.[0-9a-fA-F]+)?
(?: [Pp][+-]?[0-9]+)?
|
(?:0[bB])
[0-1_]+
|
[0-9]+
(?:\\.[0-9]+)?
(?:[Ee][+-]?[0-9]+)?
) (?:i8|i16|i32|i64|u8|u16|u32|u64|f32|f64)?
"""
character:
name: "string.quoted.single.character.futhark"
match: "(')[^']?(')"
captures:
1: name: "punctuation.definition.string.begin.futhark"
2: name: "punctuation.definition.string.end.futhark"
var:
name: "variable.other.readwrite.futhark"
match: "(?<![#'])\\b[_A-Za-z]['\\w]*"
constructor:
name: "entity.name.function.constructor.futhark"
match: "(#)['\\w]+"
captures:
1: name: "punctuation.definition.constructor.number-sign.futhark"
operator:
patterns: [{
name: "keyword.operator.futhark"
match: "[-+*/%!<>=&|@]+"
},{
name: "string.interpolated.quoted.backticks.futhark"
match: "(`)[^`]*(`)"
captures:
1: name: "punctuation.definition.string.begin.futhark"
2: name: "punctuation.definition.string.end.futhark"
}]
| true | # Direct port of Emacs' `futhark-mode'. Sources:
# - https://futhark.readthedocs.io/en/latest/language-reference.html
# - https://github.com/diku-dk/futhark-mode/blob/ca22b1e5/futhark-highlight.el
name: "PI:NAME:<NAME>END_PIuthark"
scopeName: "source.futhark"
fileTypes: ["fut"]
patterns: [include: "#main"]
firstLineMatch: """(?x)
# Emacs modeline
-\\*-(?i:[ \\t]*(?=[^:;\\s]+[ \\t]*-\\*-)|(?:.*?[ \\t;]|(?<=-\\*-))[ \\t]*mode[ \\t]*:[ \\t]*)
futhark
(?=[ \\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]*=
futhark
(?=$|\\s|:)
"""
repository:
main:
patterns: [
{include: "#typeBinding"}
{include: "#typeParameter"}
{include: "#functionDefinition"}
{include: "#comment"}
{include: "#keywords"}
{include: "#attribute"}
{include: "#numericTypes"}
{include: "#builtInTypes"}
{include: "#booleans"}
{include: "#number"}
{include: "#character"}
{include: "#var"}
{include: "#constructor"}
{include: "#operator"}
{match: "#"} # Inhibit `etc#comment` rule
{match: "'"} # Inhibit `etc#str` rule
{include: "etc#bracket"}
{include: "etc"}
]
typeBinding:
name: "meta.type.binding.futhark"
begin: "(?<![#'])\\b(module\\s+)?(type[~^]?)(?:\\s+([_A-Za-z]['\\w]*))?(?:\\b(?![#'])|(?<=')\\B(?!#))"
end: "=|(?=\\s*(?!--)[^\\s=])"
beginCaptures:
1: name: "storage.modifier.module.futhark"
2: name: "storage.type.decl.futhark"
3: name: "entity.name.type.futhark"
endCaptures:
0: name: "keyword.operator.futhark"
patterns: [
{include: "#comment"}
{include: "#typeParameter"}
]
typeParameter:
name: "entity.name.type.parameter.futhark"
match: "('[~^]?)[_A-Za-z]\\w*\\b(?![#'])"
captures:
1: name: "punctuation.definition.type.parameter.futhark"
functionDefinition:
match: "(?<![#'])\\b(let|entry)(?:\\s+([_A-Za-z]['\\w]*))?(?:\\b(?![#'])|(?<=')\\B(?!#))"
captures:
1: name: "storage.type.var.$1.futhark"
2: name: "entity.name.function.futhark"
comment:
name: "comment.line.double-dash.futhark"
begin: "--"
end: "$"
keywords:
name: "keyword.control.$1.futhark"
match: "(?<![#'])\\b(assert|case|do|else|entry|for|if|import|include|in|let|local|loop|match|module|open|then|unsafe|val|while|with)\\b(?![#'])"
attribute:
name: "meta.attribute.futhark"
match: "(#\\[)([^\\]]*)(\\])"
captures:
1: name: "punctuation.definition.attribute.begin.futhark"
2: name: "storage.modifier.attribute.futhark"
3: name: "punctuation.definition.attribute.end.futhark"
numericTypes:
name: "support.type.numeric.futhark"
match: "(?<![#'])\\b(f32|f64|i16|i32|i64|i8|u16|u32|u64|u8)\\b(?![#'])"
builtInTypes:
patterns: [
{match: "(?<![#'])(bool)\\b(?![#'])", name: "support.type.builtin.futhark"}
{include: "#numericTypes"}
]
booleans:
name: "constant.language.boolean.$1.futhark"
match: "(?<![#'])(true|false)\\b(?![#'])"
number:
name: "constant.numeric.futhark"
match: """(?x) -?
(?:
(?:0[xX])
[0-9a-fA-F]+
(?: \\.[0-9a-fA-F]+)?
(?: [Pp][+-]?[0-9]+)?
|
(?:0[bB])
[0-1_]+
|
[0-9]+
(?:\\.[0-9]+)?
(?:[Ee][+-]?[0-9]+)?
) (?:i8|i16|i32|i64|u8|u16|u32|u64|f32|f64)?
"""
character:
name: "string.quoted.single.character.futhark"
match: "(')[^']?(')"
captures:
1: name: "punctuation.definition.string.begin.futhark"
2: name: "punctuation.definition.string.end.futhark"
var:
name: "variable.other.readwrite.futhark"
match: "(?<![#'])\\b[_A-Za-z]['\\w]*"
constructor:
name: "entity.name.function.constructor.futhark"
match: "(#)['\\w]+"
captures:
1: name: "punctuation.definition.constructor.number-sign.futhark"
operator:
patterns: [{
name: "keyword.operator.futhark"
match: "[-+*/%!<>=&|@]+"
},{
name: "string.interpolated.quoted.backticks.futhark"
match: "(`)[^`]*(`)"
captures:
1: name: "punctuation.definition.string.begin.futhark"
2: name: "punctuation.definition.string.end.futhark"
}]
|
[
{
"context": "###\n Pokemon Go(c) MITM node proxy\n Example by Daniel Gothenborg <daniel@dgw.no>\n\n This will auto-spin PokeStops ",
"end": 66,
"score": 0.9998492002487183,
"start": 49,
"tag": "NAME",
"value": "Daniel Gothenborg"
},
{
"context": ") MITM node proxy\n Example by D... | example.visitPokeStop.coffee | noobcakes4603/tinkering | 393 | ###
Pokemon Go(c) MITM node proxy
Example by Daniel Gothenborg <daniel@dgw.no>
This will auto-spin PokeStops within 30m with no cooldown.
###
PokemonGoMITM = require './lib/pokemon-go-mitm'
LatLon = require('geodesy').LatLonSpherical
forts = null
currentLocation = null
server = new PokemonGoMITM port: 8081
.addRequestHandler "*", (data) ->
currentLocation = new LatLon data.latitude, data.longitude if data.latitude
false
.addResponseHandler "GetMapObjects", (data) ->
forts = []
for cell in data.map_cells
for fort in cell.forts
forts.push fort
false
.addRequestHandler "*", (data, action) ->
if currentLocation and forts
for fort in forts
if fort.type is 'CHECKPOINT'
if not fort.cooldown_complete_timestamp_ms or (parseFloat(new Date().getTime()) - (parseFloat(fort.cooldown_complete_timestamp_ms)-(3600*2*1000))) >= 300000
position = new LatLon fort.latitude, fort.longitude
distance = Math.floor currentLocation.distanceTo position
fort.cooldown_complete_timestamp_ms = new Date().getTime().toString();
if distance < 30
server.craftRequest "FortSearch",
{
fort_id: fort.id,
fort_latitude: fort.latitude,
fort_longitude: fort.longitude,
player_latitude: fort.latitude,
player_longitude: fort.longitude
}
.then (data) ->
if data.result is 'SUCCESS'
console.log "[<-] Items awarded:", data.items_awarded
false | 197533 | ###
Pokemon Go(c) MITM node proxy
Example by <NAME> <<EMAIL>>
This will auto-spin PokeStops within 30m with no cooldown.
###
PokemonGoMITM = require './lib/pokemon-go-mitm'
LatLon = require('geodesy').LatLonSpherical
forts = null
currentLocation = null
server = new PokemonGoMITM port: 8081
.addRequestHandler "*", (data) ->
currentLocation = new LatLon data.latitude, data.longitude if data.latitude
false
.addResponseHandler "GetMapObjects", (data) ->
forts = []
for cell in data.map_cells
for fort in cell.forts
forts.push fort
false
.addRequestHandler "*", (data, action) ->
if currentLocation and forts
for fort in forts
if fort.type is 'CHECKPOINT'
if not fort.cooldown_complete_timestamp_ms or (parseFloat(new Date().getTime()) - (parseFloat(fort.cooldown_complete_timestamp_ms)-(3600*2*1000))) >= 300000
position = new LatLon fort.latitude, fort.longitude
distance = Math.floor currentLocation.distanceTo position
fort.cooldown_complete_timestamp_ms = new Date().getTime().toString();
if distance < 30
server.craftRequest "FortSearch",
{
fort_id: fort.id,
fort_latitude: fort.latitude,
fort_longitude: fort.longitude,
player_latitude: fort.latitude,
player_longitude: fort.longitude
}
.then (data) ->
if data.result is 'SUCCESS'
console.log "[<-] Items awarded:", data.items_awarded
false | true | ###
Pokemon Go(c) MITM node proxy
Example by PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
This will auto-spin PokeStops within 30m with no cooldown.
###
PokemonGoMITM = require './lib/pokemon-go-mitm'
LatLon = require('geodesy').LatLonSpherical
forts = null
currentLocation = null
server = new PokemonGoMITM port: 8081
.addRequestHandler "*", (data) ->
currentLocation = new LatLon data.latitude, data.longitude if data.latitude
false
.addResponseHandler "GetMapObjects", (data) ->
forts = []
for cell in data.map_cells
for fort in cell.forts
forts.push fort
false
.addRequestHandler "*", (data, action) ->
if currentLocation and forts
for fort in forts
if fort.type is 'CHECKPOINT'
if not fort.cooldown_complete_timestamp_ms or (parseFloat(new Date().getTime()) - (parseFloat(fort.cooldown_complete_timestamp_ms)-(3600*2*1000))) >= 300000
position = new LatLon fort.latitude, fort.longitude
distance = Math.floor currentLocation.distanceTo position
fort.cooldown_complete_timestamp_ms = new Date().getTime().toString();
if distance < 30
server.craftRequest "FortSearch",
{
fort_id: fort.id,
fort_latitude: fort.latitude,
fort_longitude: fort.longitude,
player_latitude: fort.latitude,
player_longitude: fort.longitude
}
.then (data) ->
if data.result is 'SUCCESS'
console.log "[<-] Items awarded:", data.items_awarded
false |
[
{
"context": "# Copyright (C) 2013 Yusuke Suzuki <utatane.tea@gmail.com>\n#\n# Redistribution and us",
"end": 34,
"score": 0.999824047088623,
"start": 21,
"tag": "NAME",
"value": "Yusuke Suzuki"
},
{
"context": "# Copyright (C) 2013 Yusuke Suzuki <utatane.tea@gmail.com>\n#\n# Redistr... | client/js/build/test/dumper.coffee | Etraud123/JSpwn | 22 | # Copyright (C) 2013 Yusuke Suzuki <utatane.tea@gmail.com>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> 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.
'use strict'
estraverse = require '..'
module.exports = class Dumper
constructor: ->
@logs = []
log: (str) ->
@logs.push str
result: ->
@logs.join '\n'
@dump: (tree) ->
dumper = new Dumper
estraverse.traverse tree,
enter: (node) ->
dumper.log("enter - #{node.type}")
leave: (node) ->
dumper.log("leave - #{node.type}")
dumper.result()
| 88225 | # Copyright (C) 2013 <NAME> <<EMAIL>>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> 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.
'use strict'
estraverse = require '..'
module.exports = class Dumper
constructor: ->
@logs = []
log: (str) ->
@logs.push str
result: ->
@logs.join '\n'
@dump: (tree) ->
dumper = new Dumper
estraverse.traverse tree,
enter: (node) ->
dumper.log("enter - #{node.type}")
leave: (node) ->
dumper.log("leave - #{node.type}")
dumper.result()
| true | # Copyright (C) 2013 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> 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.
'use strict'
estraverse = require '..'
module.exports = class Dumper
constructor: ->
@logs = []
log: (str) ->
@logs.push str
result: ->
@logs.join '\n'
@dump: (tree) ->
dumper = new Dumper
estraverse.traverse tree,
enter: (node) ->
dumper.log("enter - #{node.type}")
leave: (node) ->
dumper.log("leave - #{node.type}")
dumper.result()
|
[
{
"context": "----\n transbrute:\n docs:\n remote: 'git@github.com:YAndrew91/chaplin.git'\n branch: 'gh-pages'",
"end": 2005,
"score": 0.9998164176940918,
"start": 1991,
"tag": "EMAIL",
"value": "git@github.com"
},
{
"context": "rute:\n docs:\n remot... | Gruntfile.coffee | YAndrew91/chaplin | 0 | module.exports = (grunt) ->
# Utilities
# =========
path = require 'path'
# Package
# =======
pkg = require './package.json'
componentsFolder = 'bower_components'
# Modules
# =======
# TODO: Remove this as soon as uRequire releases 0.3 which will able to
# do this for us in the right order magically.
modules = [
'temp/chaplin/application.js'
'temp/chaplin/mediator.js'
'temp/chaplin/dispatcher.js'
'temp/chaplin/composer.js'
'temp/chaplin/controllers/controller.js'
'temp/chaplin/models/collection.js'
'temp/chaplin/models/model.js'
'temp/chaplin/views/layout.js'
'temp/chaplin/views/view.js'
'temp/chaplin/views/collection_view.js'
'temp/chaplin/lib/route.js'
'temp/chaplin/lib/router.js'
'temp/chaplin/lib/history.js'
'temp/chaplin/lib/event_broker.js'
'temp/chaplin/lib/support.js'
'temp/chaplin/lib/composition.js'
'temp/chaplin/lib/sync_machine.js'
'temp/chaplin/lib/utils.js'
'temp/chaplin.js'
]
# Configuration
# =============
grunt.initConfig
# Package
# -------
pkg: pkg
# Clean
# -----
clean:
build: 'build'
temp: 'temp'
components: componentsFolder
test: ['test/temp*', 'test/coverage']
# Compilation
# -----------
coffee:
compile:
files: [
expand: true
dest: 'temp/'
cwd: 'src'
src: '**/*.coffee'
ext: '.js'
]
test:
files: [
expand: true
dest: 'test/temp/'
cwd: 'test/spec'
src: '**/*.coffee'
ext: '.js'
]
options:
bare: true
# Module conversion
# -----------------
urequire:
AMD:
bundlePath: 'temp/'
outputPath: 'temp/'
options:
forceOverwriteSources: true
relativeType: 'bundle'
# Publishing via Git
# ------------------
transbrute:
docs:
remote: 'git@github.com:YAndrew91/chaplin.git'
branch: 'gh-pages'
files: [
{ expand: true, cwd: 'docs/', src: '**/*' }
]
downloads:
message: "Release #{pkg.version}."
tag: pkg.version
tagMessage: "Version #{pkg.version}."
remote: 'git@github.com:YAndrew91/downloads.git'
branch: 'gh-pages'
files: [
{ expand: true, cwd: 'build/', src: 'chaplin.{js,min.js}' },
{
dest: 'bower.json',
body: {
name: 'chaplin',
repo: 'YAndrew91/downloads',
version: pkg.version,
main: 'chaplin.js',
scripts: ['chaplin.js'],
dependencies: { backbone: '1.x' }
}
},
{
dest: 'component.json',
body: {
name: 'chaplin',
repo: 'YAndrew91/downloads',
version: pkg.version,
main: 'chaplin.js',
scripts: ['chaplin.js'],
dependencies: (obj = {}; obj["#{ componentsFolder }/backbone"] = '1.x'; obj)
}
},
{
dest: 'package.json',
body: {
name: 'chaplin',
version: pkg.version,
description: 'Chaplin.js',
main: 'chaplin.js',
scripts: { test: 'echo "Error: no test specified" && exit 1' },
repository: {
type: 'git', url: 'git://github.com/YAndrew91/downloads.git'
},
author: 'Chaplin team',
license: 'MIT',
bugs: { url: 'https://github.com/chaplinjs/downloads/issues' },
dependencies: { backbone: '~1.1.2', underscore: '~1.6.0' }
}
}
]
# Module naming
# -------------
# TODO: Remove this when uRequire hits 0.3
copy:
universal:
files: [
expand: true
dest: 'temp/'
cwd: 'temp'
src: '**/*.js'
]
options:
processContent: (content, path) ->
name = ///temp/(.*)\.js///.exec(path)[1]
# data = content
data = content.replace /require\('/g, "loader('"
"""
loader.register('#{name}', function(e, r, module) {
#{data}
});
"""
amd:
files: [
expand: true
dest: 'temp/'
cwd: 'temp'
src: '**/*.js'
]
options:
processContent: (content, path) ->
name = ///temp/(.*)\.js///.exec(path)[1]
content.replace ///define\(///, "define('#{name}',"
test:
files: [
expand: true
dest: 'test/temp/'
cwd: 'temp'
src: '**/*.js'
]
beforeInstrument:
files: [
expand: true
dest: 'test/temp-original/'
cwd: 'test/temp'
src: '**/*.js'
]
afterInstrument:
files: [
expand: true
dest: 'test/temp/'
cwd: 'test/temp-original'
src: '**/*.js'
]
# Module concatenation
# --------------------
# TODO: Remove this when uRequire hits 0.3
concat:
universal:
files: [
dest: 'build/<%= pkg.name %>.js'
src: modules
]
options:
separator: ';'
banner: '''
/*!
* Chaplin <%= pkg.version %>
*
* Chaplin may be freely distributed under the MIT license.
* For all details and documentation:
* http://chaplinjs.org
*/
(function(){
var loader = (function() {
var modules = {};
var cache = {};
var dummy = function() {return function() {};};
var initModule = function(name, definition) {
var module = {id: name, exports: {}};
definition(module.exports, dummy(), module);
var exports = cache[name] = module.exports;
return exports;
};
var loader = function(path) {
if (cache.hasOwnProperty(path)) return cache[path];
if (modules.hasOwnProperty(path)) return initModule(path, modules[path]);
throw new Error('Cannot find module "' + path + '"');
};
loader.register = function(bundle, fn) {
modules[bundle] = fn;
};
return loader;
})();
'''
footer: '''
var regDeps = function(Backbone, _) {
loader.register('backbone', function(exports, require, module) {
module.exports = Backbone;
});
loader.register('underscore', function(exports, require, module) {
module.exports = _;
});
};
if (typeof define === 'function' && define.amd) {
define(['backbone', 'underscore'], function(Backbone, _) {
regDeps(Backbone, _);
return loader('chaplin');
});
} else if (typeof module === 'object' && module && module.exports) {
regDeps(require('backbone'), require('underscore'));
module.exports = loader('chaplin');
} else if (typeof require === 'function') {
regDeps(window.Backbone, window._ || window.Backbone.utils);
window.Chaplin = loader('chaplin');
} else {
throw new Error('Chaplin requires Common.js or AMD modules');
}
})();
'''
# Lint
# ----
coffeelint:
source: 'src/**/*.coffee'
grunt: 'Gruntfile.coffee'
# Instrumentation
# ---------------
instrument:
files: [
'test/temp/chaplin.js'
'test/temp/chaplin/**/*.js'
]
options:
basePath: '.'
storeCoverage:
options:
dir : '.'
json : 'coverage.json'
coverageVar : '__coverage__'
makeReport:
src: 'coverage.json'
options:
type: 'html'
dir: 'test/coverage'
# Browser dependencies
# --------------------
bower:
install:
options:
targetDir: "./test/#{ componentsFolder }"
cleanup: true
# Test runner
# -----------
mocha:
index:
src: ['test/index.html']
# options:
# grep: 'autoAttach'
# mocha:
# grep: 'autoAttach'
# Minify
# ------
uglify:
options:
mangle: true
universal:
files:
'build/chaplin.min.js': 'build/chaplin.js'
# Compression
# -----------
compress:
files: [
src: 'build/chaplin.min.js'
dest: 'build/chaplin.min.js.gz'
]
# Watching for changes
# --------------------
watch:
coffee:
files: ['src/**/*.coffee']
tasks: [
'coffee:compile'
'urequire'
'copy:amd'
'copy:test'
'mocha'
]
test:
files: ['test/spec/*.coffee'],
tasks: [
'coffee:test'
'mocha'
]
# Events
# ======
grunt.event.on 'mocha.coverage', (coverage) ->
# This is needed so the coverage reporter will find the coverage variable.
global.__coverage__ = coverage
# Dependencies
# ============
for name of pkg.devDependencies when name.substring(0, 6) is 'grunt-'
grunt.loadNpmTasks name
# Tasks
# =====
# Prepare
# -------
grunt.registerTask 'prepare', [
'clean'
'bower'
'clean:components'
]
# Build
# -----
grunt.registerTask 'build', [
'coffee:compile'
'copy:universal'
'concat:universal'
'uglify'
]
# Lint
# ----
grunt.registerTask 'lint', 'coffeelint'
# Test
# ----
grunt.registerTask 'test', [
'coffee:compile'
'urequire'
'copy:amd'
'copy:test'
'coffee:test'
'mocha'
]
# Coverage
# --------
grunt.registerTask 'cover', [
'coffee:compile'
'urequire'
'copy:amd'
'copy:test'
'coffee:test'
'copy:beforeInstrument'
'instrument'
'mocha'
'storeCoverage'
'copy:afterInstrument'
'makeReport'
]
# Test Watcher
# ------------
grunt.registerTask 'test-watch', [
'test'
'watch'
]
# Releasing
# ---------
grunt.registerTask 'check:versions:component', 'Check that package.json and bower.json versions match', ->
componentVersion = grunt.file.readJSON('bower.json').version
unless componentVersion is pkg.version
grunt.fail.warn "bower.json is version #{componentVersion}, package.json is #{pkg.version}."
else
grunt.log.ok()
grunt.registerTask 'check:versions:changelog', 'Check that CHANGELOG.md is up to date', ->
# Require CHANGELOG.md to contain "Chaplin VERSION (DIGIT"
changelogMd = grunt.file.read('CHANGELOG.md')
unless RegExp("Chaplin #{pkg.version} \\(\\d").test changelogMd
grunt.fail.warn "CHANGELOG.md does not seem to be updated for #{pkg.version}."
else
grunt.log.ok()
grunt.registerTask 'check:versions:docs', 'Check that package.json and docs versions match', ->
template = grunt.file.read path.join('docs', '_layouts', 'default.html')
match = template.match /^version: ((\d+)\.(\d+)\.(\d+)(?:-[\dA-Za-z\-]*)?)$/m
unless match
grunt.fail.warn "Version missing in docs layout."
docsVersion = match[1]
unless docsVersion is pkg.version
grunt.fail.warn "Docs layout is version #{docsVersion}, package.json is #{pkg.version}."
else
grunt.log.ok()
grunt.registerTask 'check:versions', [
'check:versions:component',
'check:versions:changelog',
'check:versions:docs'
]
grunt.registerTask 'release:git', 'Check context, commit and tag for release.', ->
prompt = require 'prompt'
prompt.start()
prompt.message = prompt.delimiter = ''
prompt.colors = false
# Command/query wrapper, turns description object for `spawn` into runner
command = (desc, message) ->
(next) ->
grunt.log.writeln message if message
grunt.util.spawn desc, (err, result, code) -> next(err)
query = (desc) ->
(next) -> grunt.util.spawn desc, (err, result, code) -> next(err, result)
# Help checking input from prompt. Returns a callback that calls the
# original callback `next` only if the input was as expected
checkInput = (expectation, next) ->
(err, input) ->
unless input and input.question is expectation
grunt.fail.warn "Aborted: Expected #{expectation}, got #{input}"
next()
steps = []
continuation = this.async()
# Check for master branch
steps.push query(cmd: 'git', args: ['rev-parse', '--abbrev-ref', 'HEAD'])
steps.push (result, next) ->
result = result.toString().trim()
if result is 'master'
next()
else
prompt.get([
description: "Current branch is #{result}, not master. 'ok' to continue, Ctrl-C to quit."
pattern: /^ok$/, required: true
],
checkInput('ok', next)
)
# List dirty files, ask for confirmation
steps.push query(cmd: 'git', args: ['status', '--porcelain'])
steps.push (result, next) ->
grunt.fail.warn "Nothing to commit." unless result.toString().length
grunt.log.writeln "The following dirty files will be committed:"
grunt.log.writeln result
prompt.get([
description: "Commit these files? 'ok' to continue, Ctrl-C to quit.",
pattern: /^ok$/, required: true
],
checkInput('ok', next)
)
# Commit
steps.push command(cmd: 'git', args: ['commit', '-a', '-m', "Release #{pkg.version}"])
# Tag
steps.push command(cmd: 'git', args: ['tag', '-a', pkg.version, '-m', "Version #{pkg.version}"])
grunt.util.async.waterfall steps, continuation
grunt.registerTask 'release', [
'check:versions',
'release:git',
'build',
'transbrute:docs',
'transbrute:downloads'
]
# Publish Documentation
# ---------------------
grunt.registerTask 'docs:publish', ['check:versions:docs', 'transbrute:docs']
# Default
# -------
grunt.registerTask 'default', [
'lint'
'clean'
'build'
'test'
]
| 124486 | module.exports = (grunt) ->
# Utilities
# =========
path = require 'path'
# Package
# =======
pkg = require './package.json'
componentsFolder = 'bower_components'
# Modules
# =======
# TODO: Remove this as soon as uRequire releases 0.3 which will able to
# do this for us in the right order magically.
modules = [
'temp/chaplin/application.js'
'temp/chaplin/mediator.js'
'temp/chaplin/dispatcher.js'
'temp/chaplin/composer.js'
'temp/chaplin/controllers/controller.js'
'temp/chaplin/models/collection.js'
'temp/chaplin/models/model.js'
'temp/chaplin/views/layout.js'
'temp/chaplin/views/view.js'
'temp/chaplin/views/collection_view.js'
'temp/chaplin/lib/route.js'
'temp/chaplin/lib/router.js'
'temp/chaplin/lib/history.js'
'temp/chaplin/lib/event_broker.js'
'temp/chaplin/lib/support.js'
'temp/chaplin/lib/composition.js'
'temp/chaplin/lib/sync_machine.js'
'temp/chaplin/lib/utils.js'
'temp/chaplin.js'
]
# Configuration
# =============
grunt.initConfig
# Package
# -------
pkg: pkg
# Clean
# -----
clean:
build: 'build'
temp: 'temp'
components: componentsFolder
test: ['test/temp*', 'test/coverage']
# Compilation
# -----------
coffee:
compile:
files: [
expand: true
dest: 'temp/'
cwd: 'src'
src: '**/*.coffee'
ext: '.js'
]
test:
files: [
expand: true
dest: 'test/temp/'
cwd: 'test/spec'
src: '**/*.coffee'
ext: '.js'
]
options:
bare: true
# Module conversion
# -----------------
urequire:
AMD:
bundlePath: 'temp/'
outputPath: 'temp/'
options:
forceOverwriteSources: true
relativeType: 'bundle'
# Publishing via Git
# ------------------
transbrute:
docs:
remote: '<EMAIL>:YAndrew91/chaplin.git'
branch: 'gh-pages'
files: [
{ expand: true, cwd: 'docs/', src: '**/*' }
]
downloads:
message: "Release #{pkg.version}."
tag: pkg.version
tagMessage: "Version #{pkg.version}."
remote: '<EMAIL>:YAndrew91/downloads.git'
branch: 'gh-pages'
files: [
{ expand: true, cwd: 'build/', src: 'chaplin.{js,min.js}' },
{
dest: 'bower.json',
body: {
name: 'chaplin',
repo: 'YAndrew91/downloads',
version: pkg.version,
main: 'chaplin.js',
scripts: ['chaplin.js'],
dependencies: { backbone: '1.x' }
}
},
{
dest: 'component.json',
body: {
name: 'chaplin',
repo: 'YAndrew91/downloads',
version: pkg.version,
main: 'chaplin.js',
scripts: ['chaplin.js'],
dependencies: (obj = {}; obj["#{ componentsFolder }/backbone"] = '1.x'; obj)
}
},
{
dest: 'package.json',
body: {
name: 'chaplin',
version: pkg.version,
description: 'Chaplin.js',
main: 'chaplin.js',
scripts: { test: 'echo "Error: no test specified" && exit 1' },
repository: {
type: 'git', url: 'git://github.com/YAndrew91/downloads.git'
},
author: 'Chaplin team',
license: 'MIT',
bugs: { url: 'https://github.com/chaplinjs/downloads/issues' },
dependencies: { backbone: '~1.1.2', underscore: '~1.6.0' }
}
}
]
# Module naming
# -------------
# TODO: Remove this when uRequire hits 0.3
copy:
universal:
files: [
expand: true
dest: 'temp/'
cwd: 'temp'
src: '**/*.js'
]
options:
processContent: (content, path) ->
name = ///temp/(.*)\.js///.exec(path)[1]
# data = content
data = content.replace /require\('/g, "loader('"
"""
loader.register('#{name}', function(e, r, module) {
#{data}
});
"""
amd:
files: [
expand: true
dest: 'temp/'
cwd: 'temp'
src: '**/*.js'
]
options:
processContent: (content, path) ->
name = ///temp/(.*)\.js///.exec(path)[1]
content.replace ///define\(///, "define('#{name}',"
test:
files: [
expand: true
dest: 'test/temp/'
cwd: 'temp'
src: '**/*.js'
]
beforeInstrument:
files: [
expand: true
dest: 'test/temp-original/'
cwd: 'test/temp'
src: '**/*.js'
]
afterInstrument:
files: [
expand: true
dest: 'test/temp/'
cwd: 'test/temp-original'
src: '**/*.js'
]
# Module concatenation
# --------------------
# TODO: Remove this when uRequire hits 0.3
concat:
universal:
files: [
dest: 'build/<%= pkg.name %>.js'
src: modules
]
options:
separator: ';'
banner: '''
/*!
* Chaplin <%= pkg.version %>
*
* Chaplin may be freely distributed under the MIT license.
* For all details and documentation:
* http://chaplinjs.org
*/
(function(){
var loader = (function() {
var modules = {};
var cache = {};
var dummy = function() {return function() {};};
var initModule = function(name, definition) {
var module = {id: name, exports: {}};
definition(module.exports, dummy(), module);
var exports = cache[name] = module.exports;
return exports;
};
var loader = function(path) {
if (cache.hasOwnProperty(path)) return cache[path];
if (modules.hasOwnProperty(path)) return initModule(path, modules[path]);
throw new Error('Cannot find module "' + path + '"');
};
loader.register = function(bundle, fn) {
modules[bundle] = fn;
};
return loader;
})();
'''
footer: '''
var regDeps = function(Backbone, _) {
loader.register('backbone', function(exports, require, module) {
module.exports = Backbone;
});
loader.register('underscore', function(exports, require, module) {
module.exports = _;
});
};
if (typeof define === 'function' && define.amd) {
define(['backbone', 'underscore'], function(Backbone, _) {
regDeps(Backbone, _);
return loader('chaplin');
});
} else if (typeof module === 'object' && module && module.exports) {
regDeps(require('backbone'), require('underscore'));
module.exports = loader('chaplin');
} else if (typeof require === 'function') {
regDeps(window.Backbone, window._ || window.Backbone.utils);
window.Chaplin = loader('chaplin');
} else {
throw new Error('Chaplin requires Common.js or AMD modules');
}
})();
'''
# Lint
# ----
coffeelint:
source: 'src/**/*.coffee'
grunt: 'Gruntfile.coffee'
# Instrumentation
# ---------------
instrument:
files: [
'test/temp/chaplin.js'
'test/temp/chaplin/**/*.js'
]
options:
basePath: '.'
storeCoverage:
options:
dir : '.'
json : 'coverage.json'
coverageVar : '__coverage__'
makeReport:
src: 'coverage.json'
options:
type: 'html'
dir: 'test/coverage'
# Browser dependencies
# --------------------
bower:
install:
options:
targetDir: "./test/#{ componentsFolder }"
cleanup: true
# Test runner
# -----------
mocha:
index:
src: ['test/index.html']
# options:
# grep: 'autoAttach'
# mocha:
# grep: 'autoAttach'
# Minify
# ------
uglify:
options:
mangle: true
universal:
files:
'build/chaplin.min.js': 'build/chaplin.js'
# Compression
# -----------
compress:
files: [
src: 'build/chaplin.min.js'
dest: 'build/chaplin.min.js.gz'
]
# Watching for changes
# --------------------
watch:
coffee:
files: ['src/**/*.coffee']
tasks: [
'coffee:compile'
'urequire'
'copy:amd'
'copy:test'
'mocha'
]
test:
files: ['test/spec/*.coffee'],
tasks: [
'coffee:test'
'mocha'
]
# Events
# ======
grunt.event.on 'mocha.coverage', (coverage) ->
# This is needed so the coverage reporter will find the coverage variable.
global.__coverage__ = coverage
# Dependencies
# ============
for name of pkg.devDependencies when name.substring(0, 6) is 'grunt-'
grunt.loadNpmTasks name
# Tasks
# =====
# Prepare
# -------
grunt.registerTask 'prepare', [
'clean'
'bower'
'clean:components'
]
# Build
# -----
grunt.registerTask 'build', [
'coffee:compile'
'copy:universal'
'concat:universal'
'uglify'
]
# Lint
# ----
grunt.registerTask 'lint', 'coffeelint'
# Test
# ----
grunt.registerTask 'test', [
'coffee:compile'
'urequire'
'copy:amd'
'copy:test'
'coffee:test'
'mocha'
]
# Coverage
# --------
grunt.registerTask 'cover', [
'coffee:compile'
'urequire'
'copy:amd'
'copy:test'
'coffee:test'
'copy:beforeInstrument'
'instrument'
'mocha'
'storeCoverage'
'copy:afterInstrument'
'makeReport'
]
# Test Watcher
# ------------
grunt.registerTask 'test-watch', [
'test'
'watch'
]
# Releasing
# ---------
grunt.registerTask 'check:versions:component', 'Check that package.json and bower.json versions match', ->
componentVersion = grunt.file.readJSON('bower.json').version
unless componentVersion is pkg.version
grunt.fail.warn "bower.json is version #{componentVersion}, package.json is #{pkg.version}."
else
grunt.log.ok()
grunt.registerTask 'check:versions:changelog', 'Check that CHANGELOG.md is up to date', ->
# Require CHANGELOG.md to contain "Chaplin VERSION (DIGIT"
changelogMd = grunt.file.read('CHANGELOG.md')
unless RegExp("Chaplin #{pkg.version} \\(\\d").test changelogMd
grunt.fail.warn "CHANGELOG.md does not seem to be updated for #{pkg.version}."
else
grunt.log.ok()
grunt.registerTask 'check:versions:docs', 'Check that package.json and docs versions match', ->
template = grunt.file.read path.join('docs', '_layouts', 'default.html')
match = template.match /^version: ((\d+)\.(\d+)\.(\d+)(?:-[\dA-Za-z\-]*)?)$/m
unless match
grunt.fail.warn "Version missing in docs layout."
docsVersion = match[1]
unless docsVersion is pkg.version
grunt.fail.warn "Docs layout is version #{docsVersion}, package.json is #{pkg.version}."
else
grunt.log.ok()
grunt.registerTask 'check:versions', [
'check:versions:component',
'check:versions:changelog',
'check:versions:docs'
]
grunt.registerTask 'release:git', 'Check context, commit and tag for release.', ->
prompt = require 'prompt'
prompt.start()
prompt.message = prompt.delimiter = ''
prompt.colors = false
# Command/query wrapper, turns description object for `spawn` into runner
command = (desc, message) ->
(next) ->
grunt.log.writeln message if message
grunt.util.spawn desc, (err, result, code) -> next(err)
query = (desc) ->
(next) -> grunt.util.spawn desc, (err, result, code) -> next(err, result)
# Help checking input from prompt. Returns a callback that calls the
# original callback `next` only if the input was as expected
checkInput = (expectation, next) ->
(err, input) ->
unless input and input.question is expectation
grunt.fail.warn "Aborted: Expected #{expectation}, got #{input}"
next()
steps = []
continuation = this.async()
# Check for master branch
steps.push query(cmd: 'git', args: ['rev-parse', '--abbrev-ref', 'HEAD'])
steps.push (result, next) ->
result = result.toString().trim()
if result is 'master'
next()
else
prompt.get([
description: "Current branch is #{result}, not master. 'ok' to continue, Ctrl-C to quit."
pattern: /^ok$/, required: true
],
checkInput('ok', next)
)
# List dirty files, ask for confirmation
steps.push query(cmd: 'git', args: ['status', '--porcelain'])
steps.push (result, next) ->
grunt.fail.warn "Nothing to commit." unless result.toString().length
grunt.log.writeln "The following dirty files will be committed:"
grunt.log.writeln result
prompt.get([
description: "Commit these files? 'ok' to continue, Ctrl-C to quit.",
pattern: /^ok$/, required: true
],
checkInput('ok', next)
)
# Commit
steps.push command(cmd: 'git', args: ['commit', '-a', '-m', "Release #{pkg.version}"])
# Tag
steps.push command(cmd: 'git', args: ['tag', '-a', pkg.version, '-m', "Version #{pkg.version}"])
grunt.util.async.waterfall steps, continuation
grunt.registerTask 'release', [
'check:versions',
'release:git',
'build',
'transbrute:docs',
'transbrute:downloads'
]
# Publish Documentation
# ---------------------
grunt.registerTask 'docs:publish', ['check:versions:docs', 'transbrute:docs']
# Default
# -------
grunt.registerTask 'default', [
'lint'
'clean'
'build'
'test'
]
| true | module.exports = (grunt) ->
# Utilities
# =========
path = require 'path'
# Package
# =======
pkg = require './package.json'
componentsFolder = 'bower_components'
# Modules
# =======
# TODO: Remove this as soon as uRequire releases 0.3 which will able to
# do this for us in the right order magically.
modules = [
'temp/chaplin/application.js'
'temp/chaplin/mediator.js'
'temp/chaplin/dispatcher.js'
'temp/chaplin/composer.js'
'temp/chaplin/controllers/controller.js'
'temp/chaplin/models/collection.js'
'temp/chaplin/models/model.js'
'temp/chaplin/views/layout.js'
'temp/chaplin/views/view.js'
'temp/chaplin/views/collection_view.js'
'temp/chaplin/lib/route.js'
'temp/chaplin/lib/router.js'
'temp/chaplin/lib/history.js'
'temp/chaplin/lib/event_broker.js'
'temp/chaplin/lib/support.js'
'temp/chaplin/lib/composition.js'
'temp/chaplin/lib/sync_machine.js'
'temp/chaplin/lib/utils.js'
'temp/chaplin.js'
]
# Configuration
# =============
grunt.initConfig
# Package
# -------
pkg: pkg
# Clean
# -----
clean:
build: 'build'
temp: 'temp'
components: componentsFolder
test: ['test/temp*', 'test/coverage']
# Compilation
# -----------
coffee:
compile:
files: [
expand: true
dest: 'temp/'
cwd: 'src'
src: '**/*.coffee'
ext: '.js'
]
test:
files: [
expand: true
dest: 'test/temp/'
cwd: 'test/spec'
src: '**/*.coffee'
ext: '.js'
]
options:
bare: true
# Module conversion
# -----------------
urequire:
AMD:
bundlePath: 'temp/'
outputPath: 'temp/'
options:
forceOverwriteSources: true
relativeType: 'bundle'
# Publishing via Git
# ------------------
transbrute:
docs:
remote: 'PI:EMAIL:<EMAIL>END_PI:YAndrew91/chaplin.git'
branch: 'gh-pages'
files: [
{ expand: true, cwd: 'docs/', src: '**/*' }
]
downloads:
message: "Release #{pkg.version}."
tag: pkg.version
tagMessage: "Version #{pkg.version}."
remote: 'PI:EMAIL:<EMAIL>END_PI:YAndrew91/downloads.git'
branch: 'gh-pages'
files: [
{ expand: true, cwd: 'build/', src: 'chaplin.{js,min.js}' },
{
dest: 'bower.json',
body: {
name: 'chaplin',
repo: 'YAndrew91/downloads',
version: pkg.version,
main: 'chaplin.js',
scripts: ['chaplin.js'],
dependencies: { backbone: '1.x' }
}
},
{
dest: 'component.json',
body: {
name: 'chaplin',
repo: 'YAndrew91/downloads',
version: pkg.version,
main: 'chaplin.js',
scripts: ['chaplin.js'],
dependencies: (obj = {}; obj["#{ componentsFolder }/backbone"] = '1.x'; obj)
}
},
{
dest: 'package.json',
body: {
name: 'chaplin',
version: pkg.version,
description: 'Chaplin.js',
main: 'chaplin.js',
scripts: { test: 'echo "Error: no test specified" && exit 1' },
repository: {
type: 'git', url: 'git://github.com/YAndrew91/downloads.git'
},
author: 'Chaplin team',
license: 'MIT',
bugs: { url: 'https://github.com/chaplinjs/downloads/issues' },
dependencies: { backbone: '~1.1.2', underscore: '~1.6.0' }
}
}
]
# Module naming
# -------------
# TODO: Remove this when uRequire hits 0.3
copy:
universal:
files: [
expand: true
dest: 'temp/'
cwd: 'temp'
src: '**/*.js'
]
options:
processContent: (content, path) ->
name = ///temp/(.*)\.js///.exec(path)[1]
# data = content
data = content.replace /require\('/g, "loader('"
"""
loader.register('#{name}', function(e, r, module) {
#{data}
});
"""
amd:
files: [
expand: true
dest: 'temp/'
cwd: 'temp'
src: '**/*.js'
]
options:
processContent: (content, path) ->
name = ///temp/(.*)\.js///.exec(path)[1]
content.replace ///define\(///, "define('#{name}',"
test:
files: [
expand: true
dest: 'test/temp/'
cwd: 'temp'
src: '**/*.js'
]
beforeInstrument:
files: [
expand: true
dest: 'test/temp-original/'
cwd: 'test/temp'
src: '**/*.js'
]
afterInstrument:
files: [
expand: true
dest: 'test/temp/'
cwd: 'test/temp-original'
src: '**/*.js'
]
# Module concatenation
# --------------------
# TODO: Remove this when uRequire hits 0.3
concat:
universal:
files: [
dest: 'build/<%= pkg.name %>.js'
src: modules
]
options:
separator: ';'
banner: '''
/*!
* Chaplin <%= pkg.version %>
*
* Chaplin may be freely distributed under the MIT license.
* For all details and documentation:
* http://chaplinjs.org
*/
(function(){
var loader = (function() {
var modules = {};
var cache = {};
var dummy = function() {return function() {};};
var initModule = function(name, definition) {
var module = {id: name, exports: {}};
definition(module.exports, dummy(), module);
var exports = cache[name] = module.exports;
return exports;
};
var loader = function(path) {
if (cache.hasOwnProperty(path)) return cache[path];
if (modules.hasOwnProperty(path)) return initModule(path, modules[path]);
throw new Error('Cannot find module "' + path + '"');
};
loader.register = function(bundle, fn) {
modules[bundle] = fn;
};
return loader;
})();
'''
footer: '''
var regDeps = function(Backbone, _) {
loader.register('backbone', function(exports, require, module) {
module.exports = Backbone;
});
loader.register('underscore', function(exports, require, module) {
module.exports = _;
});
};
if (typeof define === 'function' && define.amd) {
define(['backbone', 'underscore'], function(Backbone, _) {
regDeps(Backbone, _);
return loader('chaplin');
});
} else if (typeof module === 'object' && module && module.exports) {
regDeps(require('backbone'), require('underscore'));
module.exports = loader('chaplin');
} else if (typeof require === 'function') {
regDeps(window.Backbone, window._ || window.Backbone.utils);
window.Chaplin = loader('chaplin');
} else {
throw new Error('Chaplin requires Common.js or AMD modules');
}
})();
'''
# Lint
# ----
coffeelint:
source: 'src/**/*.coffee'
grunt: 'Gruntfile.coffee'
# Instrumentation
# ---------------
instrument:
files: [
'test/temp/chaplin.js'
'test/temp/chaplin/**/*.js'
]
options:
basePath: '.'
storeCoverage:
options:
dir : '.'
json : 'coverage.json'
coverageVar : '__coverage__'
makeReport:
src: 'coverage.json'
options:
type: 'html'
dir: 'test/coverage'
# Browser dependencies
# --------------------
bower:
install:
options:
targetDir: "./test/#{ componentsFolder }"
cleanup: true
# Test runner
# -----------
mocha:
index:
src: ['test/index.html']
# options:
# grep: 'autoAttach'
# mocha:
# grep: 'autoAttach'
# Minify
# ------
uglify:
options:
mangle: true
universal:
files:
'build/chaplin.min.js': 'build/chaplin.js'
# Compression
# -----------
compress:
files: [
src: 'build/chaplin.min.js'
dest: 'build/chaplin.min.js.gz'
]
# Watching for changes
# --------------------
watch:
coffee:
files: ['src/**/*.coffee']
tasks: [
'coffee:compile'
'urequire'
'copy:amd'
'copy:test'
'mocha'
]
test:
files: ['test/spec/*.coffee'],
tasks: [
'coffee:test'
'mocha'
]
# Events
# ======
grunt.event.on 'mocha.coverage', (coverage) ->
# This is needed so the coverage reporter will find the coverage variable.
global.__coverage__ = coverage
# Dependencies
# ============
for name of pkg.devDependencies when name.substring(0, 6) is 'grunt-'
grunt.loadNpmTasks name
# Tasks
# =====
# Prepare
# -------
grunt.registerTask 'prepare', [
'clean'
'bower'
'clean:components'
]
# Build
# -----
grunt.registerTask 'build', [
'coffee:compile'
'copy:universal'
'concat:universal'
'uglify'
]
# Lint
# ----
grunt.registerTask 'lint', 'coffeelint'
# Test
# ----
grunt.registerTask 'test', [
'coffee:compile'
'urequire'
'copy:amd'
'copy:test'
'coffee:test'
'mocha'
]
# Coverage
# --------
grunt.registerTask 'cover', [
'coffee:compile'
'urequire'
'copy:amd'
'copy:test'
'coffee:test'
'copy:beforeInstrument'
'instrument'
'mocha'
'storeCoverage'
'copy:afterInstrument'
'makeReport'
]
# Test Watcher
# ------------
grunt.registerTask 'test-watch', [
'test'
'watch'
]
# Releasing
# ---------
grunt.registerTask 'check:versions:component', 'Check that package.json and bower.json versions match', ->
componentVersion = grunt.file.readJSON('bower.json').version
unless componentVersion is pkg.version
grunt.fail.warn "bower.json is version #{componentVersion}, package.json is #{pkg.version}."
else
grunt.log.ok()
grunt.registerTask 'check:versions:changelog', 'Check that CHANGELOG.md is up to date', ->
# Require CHANGELOG.md to contain "Chaplin VERSION (DIGIT"
changelogMd = grunt.file.read('CHANGELOG.md')
unless RegExp("Chaplin #{pkg.version} \\(\\d").test changelogMd
grunt.fail.warn "CHANGELOG.md does not seem to be updated for #{pkg.version}."
else
grunt.log.ok()
grunt.registerTask 'check:versions:docs', 'Check that package.json and docs versions match', ->
template = grunt.file.read path.join('docs', '_layouts', 'default.html')
match = template.match /^version: ((\d+)\.(\d+)\.(\d+)(?:-[\dA-Za-z\-]*)?)$/m
unless match
grunt.fail.warn "Version missing in docs layout."
docsVersion = match[1]
unless docsVersion is pkg.version
grunt.fail.warn "Docs layout is version #{docsVersion}, package.json is #{pkg.version}."
else
grunt.log.ok()
grunt.registerTask 'check:versions', [
'check:versions:component',
'check:versions:changelog',
'check:versions:docs'
]
grunt.registerTask 'release:git', 'Check context, commit and tag for release.', ->
prompt = require 'prompt'
prompt.start()
prompt.message = prompt.delimiter = ''
prompt.colors = false
# Command/query wrapper, turns description object for `spawn` into runner
command = (desc, message) ->
(next) ->
grunt.log.writeln message if message
grunt.util.spawn desc, (err, result, code) -> next(err)
query = (desc) ->
(next) -> grunt.util.spawn desc, (err, result, code) -> next(err, result)
# Help checking input from prompt. Returns a callback that calls the
# original callback `next` only if the input was as expected
checkInput = (expectation, next) ->
(err, input) ->
unless input and input.question is expectation
grunt.fail.warn "Aborted: Expected #{expectation}, got #{input}"
next()
steps = []
continuation = this.async()
# Check for master branch
steps.push query(cmd: 'git', args: ['rev-parse', '--abbrev-ref', 'HEAD'])
steps.push (result, next) ->
result = result.toString().trim()
if result is 'master'
next()
else
prompt.get([
description: "Current branch is #{result}, not master. 'ok' to continue, Ctrl-C to quit."
pattern: /^ok$/, required: true
],
checkInput('ok', next)
)
# List dirty files, ask for confirmation
steps.push query(cmd: 'git', args: ['status', '--porcelain'])
steps.push (result, next) ->
grunt.fail.warn "Nothing to commit." unless result.toString().length
grunt.log.writeln "The following dirty files will be committed:"
grunt.log.writeln result
prompt.get([
description: "Commit these files? 'ok' to continue, Ctrl-C to quit.",
pattern: /^ok$/, required: true
],
checkInput('ok', next)
)
# Commit
steps.push command(cmd: 'git', args: ['commit', '-a', '-m', "Release #{pkg.version}"])
# Tag
steps.push command(cmd: 'git', args: ['tag', '-a', pkg.version, '-m', "Version #{pkg.version}"])
grunt.util.async.waterfall steps, continuation
grunt.registerTask 'release', [
'check:versions',
'release:git',
'build',
'transbrute:docs',
'transbrute:downloads'
]
# Publish Documentation
# ---------------------
grunt.registerTask 'docs:publish', ['check:versions:docs', 'transbrute:docs']
# Default
# -------
grunt.registerTask 'default', [
'lint'
'clean'
'build'
'test'
]
|
[
{
"context": "t.example.com'\n process.env.ROCKETCHAT_USER = 'user1'\n process.env.ROCKETCHAT_PASSWORD = 'sekret'\n\n",
"end": 515,
"score": 0.9960813522338867,
"start": 510,
"tag": "USERNAME",
"value": "user1"
},
{
"context": " = 'user1'\n process.env.ROCKETCHAT_PASSWORD = ... | test/grafana-rocketchat-test.coffee | Acee11/hubot-grafana | 0 | Helper = require('hubot-test-helper')
chai = require 'chai'
sinon = require 'sinon'
chai.use require 'sinon-chai'
nock = require('nock')
helper = new Helper [
'adapters/rocketchat.coffee',
'./../src/grafana.coffee'
]
expect = chai.expect
describe 'rocketchat', ->
beforeEach ->
process.env.HUBOT_GRAFANA_HOST = 'http://play.grafana.org'
process.env.HUBOT_GRAFANA_API_KEY='xxxxxxxxxxxxxxxxxxxxxxxxx'
process.env.ROCKETCHAT_URL = 'http://chat.example.com'
process.env.ROCKETCHAT_USER = 'user1'
process.env.ROCKETCHAT_PASSWORD = 'sekret'
nock('http://play.grafana.org')
.get('/api/dashboards/db/grafana-play-home')
.replyWithFile(200, __dirname + '/fixtures/v5/dashboard-grafana-play.json')
nock('http://play.grafana.org')
.defaultReplyHeaders({
'Content-Type': 'image/png'
})
.get('/render/dashboard-solo/db/grafana-play-home/')
.query(
panelId: 8,
width: 1000,
height: 500,
from: 'now-6h',
to: 'now'
)
.replyWithFile(200, __dirname + '/fixtures/v5/dashboard-grafana-play.png')
afterEach ->
delete process.env.HUBOT_GRAFANA_HOST
delete process.env.HUBOT_GRAFANA_API_KEY
delete process.env.ROCKETCHAT_URL
delete process.env.ROCKETCHAT_USER
delete process.env.ROCKETCHAT_PASSWORD
nock.cleanAll()
context 'rocketchat upload', ->
beforeEach ->
@room = helper.createRoom()
nock.disableNetConnect()
nock('http://chat.example.com')
.post('/api/v1/login')
.replyWithFile(200, __dirname + '/fixtures/rocketchat/login.json')
nock('http://chat.example.com')
.post('/api/v1/rooms.upload/undefined')
.replyWithFile(200, __dirname + '/fixtures/rocketchat/rooms.upload.json')
afterEach ->
nock.cleanAll()
@room.destroy()
it 'should respond with an uploaded graph', (done) ->
selfRoom = @room
selfRoom.user.say('alice', '@hubot graf db grafana-play-home:panel-8')
setTimeout(() ->
try
expect(selfRoom.messages).to.eql [
['alice', '@hubot graf db grafana-play-home:panel-8']
]
# This would be where the actual image would be returned. There is
# not an easy way to mock that, so we are assuming that the other
# pieces worked as expected if we get to here without errors and nock
# sent all available data.
expect(nock.activeMocks()).to.eql []
done()
catch err
done err
return
, 1000)
context 'rocketchat and s3', ->
beforeEach ->
process.env.HUBOT_GRAFANA_S3_BUCKET='graf'
process.env.HUBOT_GRAFANA_S3_ACCESS_KEY_ID='99999999999999999'
process.env.HUBOT_GRAFANA_S3_SECRET_ACCESS_KEY='9999999999999999999999'
nock.disableNetConnect()
@room = helper.createRoom()
nock('https://graf.s3.amazonaws.com')
.filteringPath(/[a-z0-9]+\.png/g, 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.png')
.put('/grafana/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.png')
.reply(200)
afterEach ->
@room.destroy()
nock.cleanAll()
delete process.env.HUBOT_GRAFANA_S3_BUCKET
delete process.env.HUBOT_GRAFANA_S3_ACCESS_KEY_ID
delete process.env.HUBOT_GRAFANA_S3_SECRET_ACCESS_KEY
it 'should respond with an uploaded graph', (done) ->
selfRoom = @room
selfRoom.user.say('alice', '@hubot graf db grafana-play-home:panel-8')
setTimeout(() ->
try
expect(selfRoom.messages[0]).to.eql [
'alice',
'@hubot graf db grafana-play-home:panel-8'
]
expect(selfRoom.messages[1][1]).to.match(
/What\'s New: https:\/\/graf\.s3\.amazonaws\.com\/grafana\/[a-z0-9]+\.png \- http\:\/\/play\.grafana\.org\/dashboard\/db\/grafana-play-home\/\?panelId\=8&fullscreen&from\=now\-6h&to\=now/
)
expect(nock.activeMocks()).to.be.empty
done()
catch err
done err
return
, 1000)
| 129831 | Helper = require('hubot-test-helper')
chai = require 'chai'
sinon = require 'sinon'
chai.use require 'sinon-chai'
nock = require('nock')
helper = new Helper [
'adapters/rocketchat.coffee',
'./../src/grafana.coffee'
]
expect = chai.expect
describe 'rocketchat', ->
beforeEach ->
process.env.HUBOT_GRAFANA_HOST = 'http://play.grafana.org'
process.env.HUBOT_GRAFANA_API_KEY='xxxxxxxxxxxxxxxxxxxxxxxxx'
process.env.ROCKETCHAT_URL = 'http://chat.example.com'
process.env.ROCKETCHAT_USER = 'user1'
process.env.ROCKETCHAT_PASSWORD = '<PASSWORD>'
nock('http://play.grafana.org')
.get('/api/dashboards/db/grafana-play-home')
.replyWithFile(200, __dirname + '/fixtures/v5/dashboard-grafana-play.json')
nock('http://play.grafana.org')
.defaultReplyHeaders({
'Content-Type': 'image/png'
})
.get('/render/dashboard-solo/db/grafana-play-home/')
.query(
panelId: 8,
width: 1000,
height: 500,
from: 'now-6h',
to: 'now'
)
.replyWithFile(200, __dirname + '/fixtures/v5/dashboard-grafana-play.png')
afterEach ->
delete process.env.HUBOT_GRAFANA_HOST
delete process.env.HUBOT_GRAFANA_API_KEY
delete process.env.ROCKETCHAT_URL
delete process.env.ROCKETCHAT_USER
delete process.env.ROCKETCHAT_PASSWORD
nock.cleanAll()
context 'rocketchat upload', ->
beforeEach ->
@room = helper.createRoom()
nock.disableNetConnect()
nock('http://chat.example.com')
.post('/api/v1/login')
.replyWithFile(200, __dirname + '/fixtures/rocketchat/login.json')
nock('http://chat.example.com')
.post('/api/v1/rooms.upload/undefined')
.replyWithFile(200, __dirname + '/fixtures/rocketchat/rooms.upload.json')
afterEach ->
nock.cleanAll()
@room.destroy()
it 'should respond with an uploaded graph', (done) ->
selfRoom = @room
selfRoom.user.say('alice', '@hubot graf db grafana-play-home:panel-8')
setTimeout(() ->
try
expect(selfRoom.messages).to.eql [
['alice', '@hubot graf db grafana-play-home:panel-8']
]
# This would be where the actual image would be returned. There is
# not an easy way to mock that, so we are assuming that the other
# pieces worked as expected if we get to here without errors and nock
# sent all available data.
expect(nock.activeMocks()).to.eql []
done()
catch err
done err
return
, 1000)
context 'rocketchat and s3', ->
beforeEach ->
process.env.HUBOT_GRAFANA_S3_BUCKET='graf'
process.env.HUBOT_GRAFANA_S3_ACCESS_KEY_ID='<KEY>'
process.env.HUBOT_GRAFANA_S3_SECRET_ACCESS_KEY='<KEY>'
nock.disableNetConnect()
@room = helper.createRoom()
nock('https://graf.s3.amazonaws.com')
.filteringPath(/[a-z0-9]+\.png/g, 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.png')
.put('/grafana/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.png')
.reply(200)
afterEach ->
@room.destroy()
nock.cleanAll()
delete process.env.HUBOT_GRAFANA_S3_BUCKET
delete process.env.HUBOT_GRAFANA_S3_ACCESS_KEY_ID
delete process.env.HUBOT_GRAFANA_S3_SECRET_ACCESS_KEY
it 'should respond with an uploaded graph', (done) ->
selfRoom = @room
selfRoom.user.say('alice', '@hubot graf db grafana-play-home:panel-8')
setTimeout(() ->
try
expect(selfRoom.messages[0]).to.eql [
'alice',
'@hubot graf db grafana-play-home:panel-8'
]
expect(selfRoom.messages[1][1]).to.match(
/What\'s New: https:\/\/graf\.s3\.amazonaws\.com\/grafana\/[a-z0-9]+\.png \- http\:\/\/play\.grafana\.org\/dashboard\/db\/grafana-play-home\/\?panelId\=8&fullscreen&from\=now\-6h&to\=now/
)
expect(nock.activeMocks()).to.be.empty
done()
catch err
done err
return
, 1000)
| true | Helper = require('hubot-test-helper')
chai = require 'chai'
sinon = require 'sinon'
chai.use require 'sinon-chai'
nock = require('nock')
helper = new Helper [
'adapters/rocketchat.coffee',
'./../src/grafana.coffee'
]
expect = chai.expect
describe 'rocketchat', ->
beforeEach ->
process.env.HUBOT_GRAFANA_HOST = 'http://play.grafana.org'
process.env.HUBOT_GRAFANA_API_KEY='xxxxxxxxxxxxxxxxxxxxxxxxx'
process.env.ROCKETCHAT_URL = 'http://chat.example.com'
process.env.ROCKETCHAT_USER = 'user1'
process.env.ROCKETCHAT_PASSWORD = 'PI:PASSWORD:<PASSWORD>END_PI'
nock('http://play.grafana.org')
.get('/api/dashboards/db/grafana-play-home')
.replyWithFile(200, __dirname + '/fixtures/v5/dashboard-grafana-play.json')
nock('http://play.grafana.org')
.defaultReplyHeaders({
'Content-Type': 'image/png'
})
.get('/render/dashboard-solo/db/grafana-play-home/')
.query(
panelId: 8,
width: 1000,
height: 500,
from: 'now-6h',
to: 'now'
)
.replyWithFile(200, __dirname + '/fixtures/v5/dashboard-grafana-play.png')
afterEach ->
delete process.env.HUBOT_GRAFANA_HOST
delete process.env.HUBOT_GRAFANA_API_KEY
delete process.env.ROCKETCHAT_URL
delete process.env.ROCKETCHAT_USER
delete process.env.ROCKETCHAT_PASSWORD
nock.cleanAll()
context 'rocketchat upload', ->
beforeEach ->
@room = helper.createRoom()
nock.disableNetConnect()
nock('http://chat.example.com')
.post('/api/v1/login')
.replyWithFile(200, __dirname + '/fixtures/rocketchat/login.json')
nock('http://chat.example.com')
.post('/api/v1/rooms.upload/undefined')
.replyWithFile(200, __dirname + '/fixtures/rocketchat/rooms.upload.json')
afterEach ->
nock.cleanAll()
@room.destroy()
it 'should respond with an uploaded graph', (done) ->
selfRoom = @room
selfRoom.user.say('alice', '@hubot graf db grafana-play-home:panel-8')
setTimeout(() ->
try
expect(selfRoom.messages).to.eql [
['alice', '@hubot graf db grafana-play-home:panel-8']
]
# This would be where the actual image would be returned. There is
# not an easy way to mock that, so we are assuming that the other
# pieces worked as expected if we get to here without errors and nock
# sent all available data.
expect(nock.activeMocks()).to.eql []
done()
catch err
done err
return
, 1000)
context 'rocketchat and s3', ->
beforeEach ->
process.env.HUBOT_GRAFANA_S3_BUCKET='graf'
process.env.HUBOT_GRAFANA_S3_ACCESS_KEY_ID='PI:KEY:<KEY>END_PI'
process.env.HUBOT_GRAFANA_S3_SECRET_ACCESS_KEY='PI:KEY:<KEY>END_PI'
nock.disableNetConnect()
@room = helper.createRoom()
nock('https://graf.s3.amazonaws.com')
.filteringPath(/[a-z0-9]+\.png/g, 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.png')
.put('/grafana/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.png')
.reply(200)
afterEach ->
@room.destroy()
nock.cleanAll()
delete process.env.HUBOT_GRAFANA_S3_BUCKET
delete process.env.HUBOT_GRAFANA_S3_ACCESS_KEY_ID
delete process.env.HUBOT_GRAFANA_S3_SECRET_ACCESS_KEY
it 'should respond with an uploaded graph', (done) ->
selfRoom = @room
selfRoom.user.say('alice', '@hubot graf db grafana-play-home:panel-8')
setTimeout(() ->
try
expect(selfRoom.messages[0]).to.eql [
'alice',
'@hubot graf db grafana-play-home:panel-8'
]
expect(selfRoom.messages[1][1]).to.match(
/What\'s New: https:\/\/graf\.s3\.amazonaws\.com\/grafana\/[a-z0-9]+\.png \- http\:\/\/play\.grafana\.org\/dashboard\/db\/grafana-play-home\/\?panelId\=8&fullscreen&from\=now\-6h&to\=now/
)
expect(nock.activeMocks()).to.be.empty
done()
catch err
done err
return
, 1000)
|
[
{
"context": "s://gleu.ch\" onClick={TrackEvent.link('Privacy')}>Greg Leuch</a>.</p>\n <p>questions or concerns can be ",
"end": 1320,
"score": 0.9993890523910522,
"start": 1310,
"tag": "NAME",
"value": "Greg Leuch"
}
] | app/assets/javascripts/components/pages/privacy.js.jsx.coffee | gleuch/color-camp | 1 | @ColorPrivacyPage = React.createClass
getInitialState : ->
{ }
componentDidMount : ->
#
componentWillUnmount : ->
#
componentWillUpdate : (p,s)->
#
componentDidUpdate : (p,s)->
#
render : ->
content = `<span>
<section>
<h1>privacy & terms</h1>
<p>as part of the terms of service and privacy policy of this web site and associated applications, browser extensions, and/or content scripts, any user must agree to the following conditions. these conditions may be updated at any time without notice.</p>
<p>your information is not sold or used for any other purpose but to visualize your browisng experience. afterall, this is only an art piece, not a unicorn startup failure.</p>
<p>however, by registering on this web site and/or downloading any application, browser extension, and/or content script developed for the use on this web site, you agree to share information about yourself and web sites you visit. any information you publish will be shared publicly for others to see, and such information cannot and will not be deleted upon request. additionally, your information may be used in other features for this art piece or future works of art in this series by <a href="https://gleu.ch" onClick={TrackEvent.link('Privacy')}>Greg Leuch</a>.</p>
<p>questions or concerns can be directed to <a href={'mailto:' + ColorInitialProps.links.email} onClick={TrackEvent.link('Privacy')}>{ColorInitialProps.links.email}</a>.</p>
<p><em>last updated 11 october, 2015</em></p>
</section>
</span>`
title = 'Privacy & Terms'
`<DocumentTitle title={title}>
<ColorStaticPageDisplay content={content} pageName="signup-login" />
</DocumentTitle>`
| 51502 | @ColorPrivacyPage = React.createClass
getInitialState : ->
{ }
componentDidMount : ->
#
componentWillUnmount : ->
#
componentWillUpdate : (p,s)->
#
componentDidUpdate : (p,s)->
#
render : ->
content = `<span>
<section>
<h1>privacy & terms</h1>
<p>as part of the terms of service and privacy policy of this web site and associated applications, browser extensions, and/or content scripts, any user must agree to the following conditions. these conditions may be updated at any time without notice.</p>
<p>your information is not sold or used for any other purpose but to visualize your browisng experience. afterall, this is only an art piece, not a unicorn startup failure.</p>
<p>however, by registering on this web site and/or downloading any application, browser extension, and/or content script developed for the use on this web site, you agree to share information about yourself and web sites you visit. any information you publish will be shared publicly for others to see, and such information cannot and will not be deleted upon request. additionally, your information may be used in other features for this art piece or future works of art in this series by <a href="https://gleu.ch" onClick={TrackEvent.link('Privacy')}><NAME></a>.</p>
<p>questions or concerns can be directed to <a href={'mailto:' + ColorInitialProps.links.email} onClick={TrackEvent.link('Privacy')}>{ColorInitialProps.links.email}</a>.</p>
<p><em>last updated 11 october, 2015</em></p>
</section>
</span>`
title = 'Privacy & Terms'
`<DocumentTitle title={title}>
<ColorStaticPageDisplay content={content} pageName="signup-login" />
</DocumentTitle>`
| true | @ColorPrivacyPage = React.createClass
getInitialState : ->
{ }
componentDidMount : ->
#
componentWillUnmount : ->
#
componentWillUpdate : (p,s)->
#
componentDidUpdate : (p,s)->
#
render : ->
content = `<span>
<section>
<h1>privacy & terms</h1>
<p>as part of the terms of service and privacy policy of this web site and associated applications, browser extensions, and/or content scripts, any user must agree to the following conditions. these conditions may be updated at any time without notice.</p>
<p>your information is not sold or used for any other purpose but to visualize your browisng experience. afterall, this is only an art piece, not a unicorn startup failure.</p>
<p>however, by registering on this web site and/or downloading any application, browser extension, and/or content script developed for the use on this web site, you agree to share information about yourself and web sites you visit. any information you publish will be shared publicly for others to see, and such information cannot and will not be deleted upon request. additionally, your information may be used in other features for this art piece or future works of art in this series by <a href="https://gleu.ch" onClick={TrackEvent.link('Privacy')}>PI:NAME:<NAME>END_PI</a>.</p>
<p>questions or concerns can be directed to <a href={'mailto:' + ColorInitialProps.links.email} onClick={TrackEvent.link('Privacy')}>{ColorInitialProps.links.email}</a>.</p>
<p><em>last updated 11 october, 2015</em></p>
</section>
</span>`
title = 'Privacy & Terms'
`<DocumentTitle title={title}>
<ColorStaticPageDisplay content={content} pageName="signup-login" />
</DocumentTitle>`
|
[
{
"context": " 8080\nwebIP = process.env.OPENSHIFT_NODEJS_IP || \"192.168.0.100\"\n\n# Base URL\nbaseURL = 'http://' + webIP + ':' + ",
"end": 401,
"score": 0.9997590184211731,
"start": 388,
"tag": "IP_ADDRESS",
"value": "192.168.0.100"
},
{
"context": "for access to PDFs of form sub... | coffee/app.coffee | gavyaggarwal/USDA-EAT-UX-Form | 1 | # Required Modules (all under MIT license)
bodyParser = require('body-parser')
cookieParser = require('cookie-parser')
express = require('express')
fs = require('fs')
moment = require('moment')
serveIndex = require('serve-index')
# Port and IP to use for web server
webPort = process.env.OPENSHIFT_NODEJS_PORT || 8080
webIP = process.env.OPENSHIFT_NODEJS_IP || "192.168.0.100"
# Base URL
baseURL = 'http://' + webIP + ':' + webPort + '/'
# Default username and password for access to PDFs of form submissions
pdfUser = 'USDA'
pdfPass = 'Demo'
# Web Server
webServer = express()
# Express middleware that handles private, school-facing portion of website
schoolHandler = (req, res, next) ->
c = req.cookies
if !c || c.user != pdfUser || c.pass != pdfPass
# Get username/password, checking post, get, cookie for data
b = req.query ? req.body
if b && b.user == pdfUser && b.pass == pdfPass
res.cookie 'user', b.user
res.cookie 'pass', b.pass
res.redirect 307, baseURL + 'schools'
return
else
res.redirect 307, baseURL + 'login.html'
return
# If the base URL or unparseable URL is passed, show the directory listing
if req.url == '/'
index = serveIndex('./pdfs', 'icons': true)
index req, res, res.send
# Otherwise, get the file from the disk and show that
else
path = 'pdfs' + req.url
fs.access path, fs.F_OK, (err) ->
if !err
options =
root: process.cwd()
res.sendFile path, options
else
res.status(404).end()
# Set up web server that servers static content and a private area for schools
webServer.use express.static('./public_html/')
webServer.use bodyParser.urlencoded(extended:true)
webServer.use '/schools', cookieParser(), schoolHandler
# Set up web server to dynamically handle form submissions
webServer.post '/form-submit.json', (req, res) ->
contents = req.body
console.log 'Received Form Submission'
try
data = contents.data.replace(/^data:application\/pdf;base64,/, "");
filename = moment().format 'YYYYMMDD-hhmmss'
count = 0
loop
countStr = if count then count.toString() else ''
try
fs.accessSync('pdfs/' + filename + countStr + '.pdf', fs.F_OK)
count += 1
continue
catch error
filename = 'pdfs/' + filename + countStr + '.pdf'
break
fs.writeFileSync filename, data, 'base64'
console.log "PDF Successfully Generated", filename
catch error
console.log "Error Generating PDF: " + error
res.setHeader 'Content-Type', 'application/json'
res.json {success:true}
# Start Web Server
try
webServer.listen webPort, webIP
console.log 'Web Server Listening on port ' + webPort
catch error
console.log 'Unable to Run Web Server: ' + error
| 143134 | # Required Modules (all under MIT license)
bodyParser = require('body-parser')
cookieParser = require('cookie-parser')
express = require('express')
fs = require('fs')
moment = require('moment')
serveIndex = require('serve-index')
# Port and IP to use for web server
webPort = process.env.OPENSHIFT_NODEJS_PORT || 8080
webIP = process.env.OPENSHIFT_NODEJS_IP || "192.168.0.100"
# Base URL
baseURL = 'http://' + webIP + ':' + webPort + '/'
# Default username and password for access to PDFs of form submissions
pdfUser = 'USDA'
pdfPass = '<PASSWORD>'
# Web Server
webServer = express()
# Express middleware that handles private, school-facing portion of website
schoolHandler = (req, res, next) ->
c = req.cookies
if !c || c.user != pdfUser || c.pass != pdfPass
# Get username/password, checking post, get, cookie for data
b = req.query ? req.body
if b && b.user == pdfUser && b.pass == <PASSWORD>
res.cookie 'user', b.user
res.cookie 'pass', <PASSWORD>
res.redirect 307, baseURL + 'schools'
return
else
res.redirect 307, baseURL + 'login.html'
return
# If the base URL or unparseable URL is passed, show the directory listing
if req.url == '/'
index = serveIndex('./pdfs', 'icons': true)
index req, res, res.send
# Otherwise, get the file from the disk and show that
else
path = 'pdfs' + req.url
fs.access path, fs.F_OK, (err) ->
if !err
options =
root: process.cwd()
res.sendFile path, options
else
res.status(404).end()
# Set up web server that servers static content and a private area for schools
webServer.use express.static('./public_html/')
webServer.use bodyParser.urlencoded(extended:true)
webServer.use '/schools', cookieParser(), schoolHandler
# Set up web server to dynamically handle form submissions
webServer.post '/form-submit.json', (req, res) ->
contents = req.body
console.log 'Received Form Submission'
try
data = contents.data.replace(/^data:application\/pdf;base64,/, "");
filename = moment().format 'YYYYMMDD-hhmmss'
count = 0
loop
countStr = if count then count.toString() else ''
try
fs.accessSync('pdfs/' + filename + countStr + '.pdf', fs.F_OK)
count += 1
continue
catch error
filename = 'pdfs/' + filename + countStr + '.pdf'
break
fs.writeFileSync filename, data, 'base64'
console.log "PDF Successfully Generated", filename
catch error
console.log "Error Generating PDF: " + error
res.setHeader 'Content-Type', 'application/json'
res.json {success:true}
# Start Web Server
try
webServer.listen webPort, webIP
console.log 'Web Server Listening on port ' + webPort
catch error
console.log 'Unable to Run Web Server: ' + error
| true | # Required Modules (all under MIT license)
bodyParser = require('body-parser')
cookieParser = require('cookie-parser')
express = require('express')
fs = require('fs')
moment = require('moment')
serveIndex = require('serve-index')
# Port and IP to use for web server
webPort = process.env.OPENSHIFT_NODEJS_PORT || 8080
webIP = process.env.OPENSHIFT_NODEJS_IP || "192.168.0.100"
# Base URL
baseURL = 'http://' + webIP + ':' + webPort + '/'
# Default username and password for access to PDFs of form submissions
pdfUser = 'USDA'
pdfPass = 'PI:PASSWORD:<PASSWORD>END_PI'
# Web Server
webServer = express()
# Express middleware that handles private, school-facing portion of website
schoolHandler = (req, res, next) ->
c = req.cookies
if !c || c.user != pdfUser || c.pass != pdfPass
# Get username/password, checking post, get, cookie for data
b = req.query ? req.body
if b && b.user == pdfUser && b.pass == PI:PASSWORD:<PASSWORD>END_PI
res.cookie 'user', b.user
res.cookie 'pass', PI:PASSWORD:<PASSWORD>END_PI
res.redirect 307, baseURL + 'schools'
return
else
res.redirect 307, baseURL + 'login.html'
return
# If the base URL or unparseable URL is passed, show the directory listing
if req.url == '/'
index = serveIndex('./pdfs', 'icons': true)
index req, res, res.send
# Otherwise, get the file from the disk and show that
else
path = 'pdfs' + req.url
fs.access path, fs.F_OK, (err) ->
if !err
options =
root: process.cwd()
res.sendFile path, options
else
res.status(404).end()
# Set up web server that servers static content and a private area for schools
webServer.use express.static('./public_html/')
webServer.use bodyParser.urlencoded(extended:true)
webServer.use '/schools', cookieParser(), schoolHandler
# Set up web server to dynamically handle form submissions
webServer.post '/form-submit.json', (req, res) ->
contents = req.body
console.log 'Received Form Submission'
try
data = contents.data.replace(/^data:application\/pdf;base64,/, "");
filename = moment().format 'YYYYMMDD-hhmmss'
count = 0
loop
countStr = if count then count.toString() else ''
try
fs.accessSync('pdfs/' + filename + countStr + '.pdf', fs.F_OK)
count += 1
continue
catch error
filename = 'pdfs/' + filename + countStr + '.pdf'
break
fs.writeFileSync filename, data, 'base64'
console.log "PDF Successfully Generated", filename
catch error
console.log "Error Generating PDF: " + error
res.setHeader 'Content-Type', 'application/json'
res.json {success:true}
# Start Web Server
try
webServer.listen webPort, webIP
console.log 'Web Server Listening on port ' + webPort
catch error
console.log 'Unable to Run Web Server: ' + error
|
[
{
"context": " authorize:\n url: 'https://github.com/login/oauth/authorize'\n method: 'POST'\n tok",
"end": 168,
"score": 0.9942697286605835,
"start": 163,
"tag": "USERNAME",
"value": "login"
},
{
"context": "ST'\n token:\n url: 'https://github.com... | seed/provider.cson | BoLaMN/node-client | 0 | [
{
id: 'github'
name: 'GitHub'
protocolId: 'OAuth2'
url: 'https://github.com'
endpoints:
authorize:
url: 'https://github.com/login/oauth/authorize'
method: 'POST'
token:
url: 'https://github.com/login/oauth/access_token'
method: 'POST'
auth: 'client_secret_post'
user:
url: 'https://api.github.com/user'
method: 'GET'
auth:
header: 'Authorization'
scheme: 'Bearer'
separator: ','
mapping:
id: 'id'
email: 'email'
name: 'name'
website: 'blog'
preferredUsername: 'login'
profile: 'html_url'
picture: 'avatar_url'
}
{
id: 'foursquare'
name: 'foursquare'
protocolId: 'OAuth2'
url: ''
endpoints:
authorize:
url: 'https://foursquare.com/oauth2/authenticate'
method: 'POST'
token:
url: 'https://foursquare.com/oauth2/access_token'
method: 'POST'
auth: 'client_secret_basic'
user:
url: 'https://api.foursquare.com/v2/users/self'
method: 'GET'
auth: query: 'oauth_token'
params: v: '20140308'
mapping:
id: 'response.user.id'
givenName: 'response.user.firstName'
familyName: 'response.user.lastName'
gender: 'response.user.gender'
email: 'response.user.contact.email'
}
{
id: 'google'
name: 'Google'
protocolId: 'OAuth2'
url: 'https://google.com'
endpoints:
authorize:
url: 'https://accounts.google.com/o/oauth2/auth'
method: 'POST'
params:
hd: 'gmail.com'
token:
url: 'https://accounts.google.com/o/oauth2/token'
method: 'POST'
auth: 'client_secret_post'
params:
hd: 'gmail.com'
user:
url: 'https://www.googleapis.com/oauth2/v1/userinfo'
method: 'GET'
auth:
header: 'Authorization'
scheme: 'Bearer'
params:
hd: 'gmail.com'
revoke:
url: 'https://accounts.google.com/o/oauth2/revoke'
method: 'GET'
auth: param: 'token'
params:
hd: 'gmail.com'
mapping:
email: 'email'
emailVerified: 'verified_email'
name: 'name'
givenName: 'given_name'
familyName: 'family_name'
profile: 'link'
picture: 'picture'
gender: 'gender'
locale: 'locale'
}
{
id: 'instagram'
name: 'instagram'
protocolId: 'OAuth2'
url: ''
endpoints:
authorize:
url: 'https://api.instagram.com/oauth/authorize/'
method: 'POST'
token:
url: 'https://api.instagram.com/oauth/access_token'
method: 'POST'
auth: 'client_secret_post'
user:
url: 'https://api.instagram.com/v1/users/self'
method: 'GET'
auth: query: 'access_token'
mapping:
id: 'data.id'
name: 'data.fullname'
preferredUsername: 'data.username'
picture: 'data.profile_picture'
website: 'data.website'
}
{
id: 'linkedin'
name: 'linkedin'
protocolId: 'OAuth2'
url: ''
endpoints:
authorize:
url: 'https://www.linkedin.com/uas/oauth2/authorization'
method: 'POST'
token:
url: 'https://www.linkedin.com/uas/oauth2/accessToken'
method: 'POST'
auth: 'client_secret_post'
user:
url: 'https://api.linkedin.com/v1/people/~:(id,first-name,last-name,picture-url,public-profile-url,email-address)'
method: 'GET'
auth:
header: 'Authorization'
scheme: 'Bearer'
params: format: 'json'
mapping:
id: 'id'
givenName: 'firstName'
familyName: 'lastName'
email: 'emailAddress'
picture: 'pictureUrl'
profile: 'publicProfileUrl'
}
{
id: 'local'
name: 'Enter Email & Password'
protocolId: 'Password'
mapping:
id: 'id'
name: 'name'
}
{
id: 'mailchimp'
name: 'mailchimp'
protocolId: 'OAuth2'
url: ''
endpoints:
authorize:
url: 'https://login.mailchimp.com/oauth2/authorize'
method: 'POST'
token:
url: 'https://login.mailchimp.com/oauth2/token'
method: 'POST'
auth: 'client_secret_post'
user:
url: 'https://login.mailchimp.com/oauth2/metadata'
method: 'GET'
auth:
header: 'Authorization'
scheme: 'Bearer'
mapping: {}
}
{
id: 'reddit'
name: 'reddit'
protocolId: 'OAuth2'
url: ''
endpoints:
authorize:
url: 'https://ssl.reddit.com/api/v1/authorize'
method: 'POST'
token:
url: 'https://ssl.reddit.com/api/v1/access_token'
method: 'POST'
auth: 'client_secret_basic'
user:
url: 'https://oauth.reddit.com/api/v1/me'
method: 'GET'
auth:
header: 'Authorization'
scheme: 'Bearer'
scope: [ 'identity' ]
mapping:
id: 'id'
emailVerified: 'has_verified_email'
preferredUsername: 'name'
}
{
id: 'soundcloud'
name: 'soundcloud'
protocolId: 'OAuth2'
url: ''
endpoints:
authorize:
url: 'https://soundcloud.com/connect'
method: 'POST'
token:
url: 'https://api.soundcloud.com/oauth2/token'
method: 'POST'
auth: 'client_secret_post'
user:
url: 'https://api.soundcloud.com/me.json'
method: 'GET'
auth: query: 'oauth_token'
mapping:
id: 'id'
emailVerified: 'primary_email_confirmed'
name: 'full_name'
givenName: 'first_name'
familyName: 'last_name'
preferredUsername: 'username'
profile: 'permalink_url'
picture: 'avatar_url'
}
{
id: 'twitch'
name: 'Twitch'
protocolId: 'OAuth2'
url: ''
endpoints:
authorize:
url: 'https://api.twitch.tv/kraken/oauth2/authorize'
method: 'POST'
token:
url: 'https://api.twitch.tv/kraken/oauth2/token'
method: 'POST'
auth: 'client_secret_post'
user:
url: 'https://api.twitch.tv/kraken/user'
method: 'GET'
auth:
header: 'Authorization'
scheme: 'OAuth'
mapping:
id: '_id'
name: 'name'
profile: '_links.self'
}
{
id: 'twitter'
name: 'Twitter'
protocolId: 'OAuth'
url: 'https://twitter.com'
oauth_callback: '/connect/twitter/callback'
oauth_signature_method: 'HMAC-SHA1'
endpoints:
credentials:
url: 'https://api.twitter.com/oauth/request_token'
method: 'POST'
header: 'Authorization'
scheme: 'OAuth'
accept: '*/*'
authorization:
url: 'https://api.twitter.com/oauth/authenticate'
token:
url: 'https://api.twitter.com/oauth/access_token'
method: 'POST'
user:
url: 'https://api.twitter.com/1.1/users/show.json'
method: 'GET'
header: 'Authorization'
scheme: 'OAuth'
mapping:
id: 'id'
name: 'name'
preferredUsername: 'screen_name'
profile: 'url'
picture: 'profile_image_url'
twitterId: 'id'
}
{
id: 'wordpress'
name: 'WordPress'
protocolId: 'OAuth2'
url: ''
endpoints:
authorize:
url: 'https://public-api.wordpress.com/oauth2/authorize'
method: 'POST'
token:
url: 'https://public-api.wordpress.com/oauth2/token'
method: 'POST'
auth: 'client_secret_post'
user:
url: 'https://public-api.wordpress.com/rest/v1/me'
method: 'GET'
auth:
header: 'Authorization'
scheme: 'Bearer'
mapping:
id: 'ID'
email: 'email'
emailVerified: 'email_verified'
name: 'display_name'
preferredUsername: 'username'
picture: 'avatar_URL'
profile: 'profile_URL'
}
{
id: 'facebook'
name: 'Facebook'
protocolId: 'OAuth2'
url: 'https://www.facebook.com'
endpoints:
authorize:
url: 'https://www.facebook.com/dialog/oauth'
method: 'POST'
token:
url: 'https://graph.facebook.com/oauth/access_token'
method: 'POST'
auth: 'client_secret_post'
parser: 'x-www-form-urlencoded'
user:
url: 'https://graph.facebook.com/me'
method: 'GET'
auth:
header: 'Authorization'
scheme: 'Bearer'
separator: ','
mapping:
id: 'id'
emailVerified: 'verified'
name: 'name'
givenName: 'first_name'
familyName: 'last_name'
profile: 'link'
gender: 'gender'
locale: 'locale'
}
{
id: 'dropbox'
name: 'Dropbox'
protocolId: 'OAuth2'
url: 'https://www.dropbox.com'
endpoints:
authorize:
url: 'https://www.dropbox.com/1/oauth2/authorize'
method: 'POST'
token:
url: 'https://api.dropbox.com/1/oauth2/token'
method: 'POST'
auth: 'client_secret_basic'
user:
url: 'https://api.dropbox.com/1/account/info'
method: 'GET'
auth:
header: 'Authorization'
scheme: 'Bearer'
mapping:
id: 'uid'
name: 'display_name'
email: 'email'
emailVerified: 'email_verified'
locale: 'country'
}
{
id: 'buffer'
name: 'buffer'
protocolId: 'OAuth2'
url: ''
endpoints:
authorize:
url: 'https://bufferapp.com/oauth2/authorize'
method: 'POST'
token:
url: 'https://api.bufferapp.com/1/oauth2/token.json'
method: 'POST'
auth: 'client_secret_basic'
user:
url: 'https://api.bufferapp.com/1/user.json'
method: 'GET'
auth: query: 'access_token'
mapping:
id: 'id'
name: 'name'
}
{
id: '37signals'
name: '37signals'
protocolId: 'OAuth2'
url: ''
endpoints:
authorize:
url: 'https://launchpad.37signals.com/authorization/new'
method: 'POST'
token:
url: 'https://launchpad.37signals.com/authorization/token'
method: 'POST'
auth: 'client_secret_basic'
user:
url: 'https://launchpad.37signals.com/authorization.json'
method: 'GET'
auth:
header: 'Authorization'
scheme: 'Bearer'
mapping: {}
}
{
id: 'angellist'
name: 'angellist'
protocolId: 'OAuth2'
url: ''
endpoints:
authorize:
url: 'https://angel.co/api/oauth/authorize'
method: 'POST'
token:
url: 'https://angel.co/api/oauth/token'
method: 'POST'
auth: 'client_secret_basic'
user:
url: 'https://api.angel.co/1/me'
method: 'GET'
auth: query: 'access_token'
mapping:
id: 'id'
name: 'name'
picture: 'image'
profile: 'angellist_url'
email: 'email'
website: 'online_bio_url'
}
] | 63114 | [
{
id: 'github'
name: 'GitHub'
protocolId: 'OAuth2'
url: 'https://github.com'
endpoints:
authorize:
url: 'https://github.com/login/oauth/authorize'
method: 'POST'
token:
url: 'https://github.com/login/oauth/access_token'
method: 'POST'
auth: 'client_secret_post'
user:
url: 'https://api.github.com/user'
method: 'GET'
auth:
header: 'Authorization'
scheme: 'Bearer'
separator: ','
mapping:
id: 'id'
email: 'email'
name: 'name'
website: 'blog'
preferredUsername: 'login'
profile: 'html_url'
picture: 'avatar_url'
}
{
id: 'foursquare'
name: 'foursquare'
protocolId: 'OAuth2'
url: ''
endpoints:
authorize:
url: 'https://foursquare.com/oauth2/authenticate'
method: 'POST'
token:
url: 'https://foursquare.com/oauth2/access_token'
method: 'POST'
auth: 'client_secret_basic'
user:
url: 'https://api.foursquare.com/v2/users/self'
method: 'GET'
auth: query: 'oauth_token'
params: v: '20140308'
mapping:
id: 'response.user.id'
givenName: 'response.user.firstName'
familyName: 'response.user.lastName'
gender: 'response.user.gender'
email: 'response.user.contact.email'
}
{
id: 'google'
name: 'Google'
protocolId: 'OAuth2'
url: 'https://google.com'
endpoints:
authorize:
url: 'https://accounts.google.com/o/oauth2/auth'
method: 'POST'
params:
hd: 'gmail.com'
token:
url: 'https://accounts.google.com/o/oauth2/token'
method: 'POST'
auth: 'client_secret_post'
params:
hd: 'gmail.com'
user:
url: 'https://www.googleapis.com/oauth2/v1/userinfo'
method: 'GET'
auth:
header: 'Authorization'
scheme: 'Bearer'
params:
hd: 'gmail.com'
revoke:
url: 'https://accounts.google.com/o/oauth2/revoke'
method: 'GET'
auth: param: 'token'
params:
hd: 'gmail.com'
mapping:
email: 'email'
emailVerified: 'verified_email'
name: 'name'
givenName: 'given_name'
familyName: 'family_name'
profile: 'link'
picture: 'picture'
gender: 'gender'
locale: 'locale'
}
{
id: 'instagram'
name: 'instagram'
protocolId: 'OAuth2'
url: ''
endpoints:
authorize:
url: 'https://api.instagram.com/oauth/authorize/'
method: 'POST'
token:
url: 'https://api.instagram.com/oauth/access_token'
method: 'POST'
auth: 'client_secret_post'
user:
url: 'https://api.instagram.com/v1/users/self'
method: 'GET'
auth: query: 'access_token'
mapping:
id: 'data.id'
name: 'data.fullname'
preferredUsername: 'data.username'
picture: 'data.profile_picture'
website: 'data.website'
}
{
id: 'linkedin'
name: 'linkedin'
protocolId: 'OAuth2'
url: ''
endpoints:
authorize:
url: 'https://www.linkedin.com/uas/oauth2/authorization'
method: 'POST'
token:
url: 'https://www.linkedin.com/uas/oauth2/accessToken'
method: 'POST'
auth: 'client_secret_post'
user:
url: 'https://api.linkedin.com/v1/people/~:(id,first-name,last-name,picture-url,public-profile-url,email-address)'
method: 'GET'
auth:
header: 'Authorization'
scheme: 'Bearer'
params: format: 'json'
mapping:
id: 'id'
givenName: '<NAME>'
familyName: '<NAME>'
email: 'emailAddress'
picture: 'pictureUrl'
profile: 'publicProfileUrl'
}
{
id: 'local'
name: 'Enter Email & Password'
protocolId: 'Password'
mapping:
id: 'id'
name: 'name'
}
{
id: 'mailchimp'
name: 'mailchimp'
protocolId: 'OAuth2'
url: ''
endpoints:
authorize:
url: 'https://login.mailchimp.com/oauth2/authorize'
method: 'POST'
token:
url: 'https://login.mailchimp.com/oauth2/token'
method: 'POST'
auth: 'client_secret_post'
user:
url: 'https://login.mailchimp.com/oauth2/metadata'
method: 'GET'
auth:
header: 'Authorization'
scheme: 'Bearer'
mapping: {}
}
{
id: 'reddit'
name: 'reddit'
protocolId: 'OAuth2'
url: ''
endpoints:
authorize:
url: 'https://ssl.reddit.com/api/v1/authorize'
method: 'POST'
token:
url: 'https://ssl.reddit.com/api/v1/access_token'
method: 'POST'
auth: 'client_secret_basic'
user:
url: 'https://oauth.reddit.com/api/v1/me'
method: 'GET'
auth:
header: 'Authorization'
scheme: 'Bearer'
scope: [ 'identity' ]
mapping:
id: 'id'
emailVerified: 'has_verified_email'
preferredUsername: 'name'
}
{
id: 'soundcloud'
name: 'soundcloud'
protocolId: 'OAuth2'
url: ''
endpoints:
authorize:
url: 'https://soundcloud.com/connect'
method: 'POST'
token:
url: 'https://api.soundcloud.com/oauth2/token'
method: 'POST'
auth: 'client_secret_post'
user:
url: 'https://api.soundcloud.com/me.json'
method: 'GET'
auth: query: 'oauth_token'
mapping:
id: 'id'
emailVerified: 'primary_email_confirmed'
name: '<NAME>'
givenName: '<NAME>'
familyName: '<NAME>'
preferredUsername: 'username'
profile: 'permalink_url'
picture: 'avatar_url'
}
{
id: 'twitch'
name: '<NAME>'
protocolId: 'OAuth2'
url: ''
endpoints:
authorize:
url: 'https://api.twitch.tv/kraken/oauth2/authorize'
method: 'POST'
token:
url: 'https://api.twitch.tv/kraken/oauth2/token'
method: 'POST'
auth: 'client_secret_post'
user:
url: 'https://api.twitch.tv/kraken/user'
method: 'GET'
auth:
header: 'Authorization'
scheme: 'OAuth'
mapping:
id: '_id'
name: 'name'
profile: '_links.self'
}
{
id: 'twitter'
name: '<NAME>'
protocolId: 'OAuth'
url: 'https://twitter.com'
oauth_callback: '/connect/twitter/callback'
oauth_signature_method: 'HMAC-SHA1'
endpoints:
credentials:
url: 'https://api.twitter.com/oauth/request_token'
method: 'POST'
header: 'Authorization'
scheme: 'OAuth'
accept: '*/*'
authorization:
url: 'https://api.twitter.com/oauth/authenticate'
token:
url: 'https://api.twitter.com/oauth/access_token'
method: 'POST'
user:
url: 'https://api.twitter.com/1.1/users/show.json'
method: 'GET'
header: 'Authorization'
scheme: 'OAuth'
mapping:
id: 'id'
name: '<NAME>'
preferredUsername: 'screen_name'
profile: 'url'
picture: 'profile_image_url'
twitterId: 'id'
}
{
id: 'wordpress'
name: 'WordPress'
protocolId: 'OAuth2'
url: ''
endpoints:
authorize:
url: 'https://public-api.wordpress.com/oauth2/authorize'
method: 'POST'
token:
url: 'https://public-api.wordpress.com/oauth2/token'
method: 'POST'
auth: 'client_secret_post'
user:
url: 'https://public-api.wordpress.com/rest/v1/me'
method: 'GET'
auth:
header: 'Authorization'
scheme: 'Bearer'
mapping:
id: 'ID'
email: 'email'
emailVerified: 'email_verified'
name: 'display_name'
preferredUsername: 'username'
picture: 'avatar_URL'
profile: 'profile_URL'
}
{
id: 'facebook'
name: 'Facebook'
protocolId: 'OAuth2'
url: 'https://www.facebook.com'
endpoints:
authorize:
url: 'https://www.facebook.com/dialog/oauth'
method: 'POST'
token:
url: 'https://graph.facebook.com/oauth/access_token'
method: 'POST'
auth: 'client_secret_post'
parser: 'x-www-form-urlencoded'
user:
url: 'https://graph.facebook.com/me'
method: 'GET'
auth:
header: 'Authorization'
scheme: 'Bearer'
separator: ','
mapping:
id: 'id'
emailVerified: 'verified'
name: 'name'
givenName: 'first_name'
familyName: 'last_name'
profile: 'link'
gender: 'gender'
locale: 'locale'
}
{
id: 'dropbox'
name: 'Dropbox'
protocolId: 'OAuth2'
url: 'https://www.dropbox.com'
endpoints:
authorize:
url: 'https://www.dropbox.com/1/oauth2/authorize'
method: 'POST'
token:
url: 'https://api.dropbox.com/1/oauth2/token'
method: 'POST'
auth: 'client_secret_basic'
user:
url: 'https://api.dropbox.com/1/account/info'
method: 'GET'
auth:
header: 'Authorization'
scheme: 'Bearer'
mapping:
id: 'uid'
name: '<NAME>'
email: 'email'
emailVerified: 'email_verified'
locale: 'country'
}
{
id: 'buffer'
name: 'buffer'
protocolId: 'OAuth2'
url: ''
endpoints:
authorize:
url: 'https://bufferapp.com/oauth2/authorize'
method: 'POST'
token:
url: 'https://api.bufferapp.com/1/oauth2/token.json'
method: 'POST'
auth: 'client_secret_basic'
user:
url: 'https://api.bufferapp.com/1/user.json'
method: 'GET'
auth: query: 'access_token'
mapping:
id: 'id'
name: 'name'
}
{
id: '37signals'
name: '37signals'
protocolId: 'OAuth2'
url: ''
endpoints:
authorize:
url: 'https://launchpad.37signals.com/authorization/new'
method: 'POST'
token:
url: 'https://launchpad.37signals.com/authorization/token'
method: 'POST'
auth: 'client_secret_basic'
user:
url: 'https://launchpad.37signals.com/authorization.json'
method: 'GET'
auth:
header: 'Authorization'
scheme: 'Bearer'
mapping: {}
}
{
id: 'angellist'
name: 'angellist'
protocolId: 'OAuth2'
url: ''
endpoints:
authorize:
url: 'https://angel.co/api/oauth/authorize'
method: 'POST'
token:
url: 'https://angel.co/api/oauth/token'
method: 'POST'
auth: 'client_secret_basic'
user:
url: 'https://api.angel.co/1/me'
method: 'GET'
auth: query: 'access_token'
mapping:
id: 'id'
name: 'name'
picture: 'image'
profile: 'angellist_url'
email: 'email'
website: 'online_bio_url'
}
] | true | [
{
id: 'github'
name: 'GitHub'
protocolId: 'OAuth2'
url: 'https://github.com'
endpoints:
authorize:
url: 'https://github.com/login/oauth/authorize'
method: 'POST'
token:
url: 'https://github.com/login/oauth/access_token'
method: 'POST'
auth: 'client_secret_post'
user:
url: 'https://api.github.com/user'
method: 'GET'
auth:
header: 'Authorization'
scheme: 'Bearer'
separator: ','
mapping:
id: 'id'
email: 'email'
name: 'name'
website: 'blog'
preferredUsername: 'login'
profile: 'html_url'
picture: 'avatar_url'
}
{
id: 'foursquare'
name: 'foursquare'
protocolId: 'OAuth2'
url: ''
endpoints:
authorize:
url: 'https://foursquare.com/oauth2/authenticate'
method: 'POST'
token:
url: 'https://foursquare.com/oauth2/access_token'
method: 'POST'
auth: 'client_secret_basic'
user:
url: 'https://api.foursquare.com/v2/users/self'
method: 'GET'
auth: query: 'oauth_token'
params: v: '20140308'
mapping:
id: 'response.user.id'
givenName: 'response.user.firstName'
familyName: 'response.user.lastName'
gender: 'response.user.gender'
email: 'response.user.contact.email'
}
{
id: 'google'
name: 'Google'
protocolId: 'OAuth2'
url: 'https://google.com'
endpoints:
authorize:
url: 'https://accounts.google.com/o/oauth2/auth'
method: 'POST'
params:
hd: 'gmail.com'
token:
url: 'https://accounts.google.com/o/oauth2/token'
method: 'POST'
auth: 'client_secret_post'
params:
hd: 'gmail.com'
user:
url: 'https://www.googleapis.com/oauth2/v1/userinfo'
method: 'GET'
auth:
header: 'Authorization'
scheme: 'Bearer'
params:
hd: 'gmail.com'
revoke:
url: 'https://accounts.google.com/o/oauth2/revoke'
method: 'GET'
auth: param: 'token'
params:
hd: 'gmail.com'
mapping:
email: 'email'
emailVerified: 'verified_email'
name: 'name'
givenName: 'given_name'
familyName: 'family_name'
profile: 'link'
picture: 'picture'
gender: 'gender'
locale: 'locale'
}
{
id: 'instagram'
name: 'instagram'
protocolId: 'OAuth2'
url: ''
endpoints:
authorize:
url: 'https://api.instagram.com/oauth/authorize/'
method: 'POST'
token:
url: 'https://api.instagram.com/oauth/access_token'
method: 'POST'
auth: 'client_secret_post'
user:
url: 'https://api.instagram.com/v1/users/self'
method: 'GET'
auth: query: 'access_token'
mapping:
id: 'data.id'
name: 'data.fullname'
preferredUsername: 'data.username'
picture: 'data.profile_picture'
website: 'data.website'
}
{
id: 'linkedin'
name: 'linkedin'
protocolId: 'OAuth2'
url: ''
endpoints:
authorize:
url: 'https://www.linkedin.com/uas/oauth2/authorization'
method: 'POST'
token:
url: 'https://www.linkedin.com/uas/oauth2/accessToken'
method: 'POST'
auth: 'client_secret_post'
user:
url: 'https://api.linkedin.com/v1/people/~:(id,first-name,last-name,picture-url,public-profile-url,email-address)'
method: 'GET'
auth:
header: 'Authorization'
scheme: 'Bearer'
params: format: 'json'
mapping:
id: 'id'
givenName: 'PI:NAME:<NAME>END_PI'
familyName: 'PI:NAME:<NAME>END_PI'
email: 'emailAddress'
picture: 'pictureUrl'
profile: 'publicProfileUrl'
}
{
id: 'local'
name: 'Enter Email & Password'
protocolId: 'Password'
mapping:
id: 'id'
name: 'name'
}
{
id: 'mailchimp'
name: 'mailchimp'
protocolId: 'OAuth2'
url: ''
endpoints:
authorize:
url: 'https://login.mailchimp.com/oauth2/authorize'
method: 'POST'
token:
url: 'https://login.mailchimp.com/oauth2/token'
method: 'POST'
auth: 'client_secret_post'
user:
url: 'https://login.mailchimp.com/oauth2/metadata'
method: 'GET'
auth:
header: 'Authorization'
scheme: 'Bearer'
mapping: {}
}
{
id: 'reddit'
name: 'reddit'
protocolId: 'OAuth2'
url: ''
endpoints:
authorize:
url: 'https://ssl.reddit.com/api/v1/authorize'
method: 'POST'
token:
url: 'https://ssl.reddit.com/api/v1/access_token'
method: 'POST'
auth: 'client_secret_basic'
user:
url: 'https://oauth.reddit.com/api/v1/me'
method: 'GET'
auth:
header: 'Authorization'
scheme: 'Bearer'
scope: [ 'identity' ]
mapping:
id: 'id'
emailVerified: 'has_verified_email'
preferredUsername: 'name'
}
{
id: 'soundcloud'
name: 'soundcloud'
protocolId: 'OAuth2'
url: ''
endpoints:
authorize:
url: 'https://soundcloud.com/connect'
method: 'POST'
token:
url: 'https://api.soundcloud.com/oauth2/token'
method: 'POST'
auth: 'client_secret_post'
user:
url: 'https://api.soundcloud.com/me.json'
method: 'GET'
auth: query: 'oauth_token'
mapping:
id: 'id'
emailVerified: 'primary_email_confirmed'
name: 'PI:NAME:<NAME>END_PI'
givenName: 'PI:NAME:<NAME>END_PI'
familyName: 'PI:NAME:<NAME>END_PI'
preferredUsername: 'username'
profile: 'permalink_url'
picture: 'avatar_url'
}
{
id: 'twitch'
name: 'PI:NAME:<NAME>END_PI'
protocolId: 'OAuth2'
url: ''
endpoints:
authorize:
url: 'https://api.twitch.tv/kraken/oauth2/authorize'
method: 'POST'
token:
url: 'https://api.twitch.tv/kraken/oauth2/token'
method: 'POST'
auth: 'client_secret_post'
user:
url: 'https://api.twitch.tv/kraken/user'
method: 'GET'
auth:
header: 'Authorization'
scheme: 'OAuth'
mapping:
id: '_id'
name: 'name'
profile: '_links.self'
}
{
id: 'twitter'
name: 'PI:NAME:<NAME>END_PI'
protocolId: 'OAuth'
url: 'https://twitter.com'
oauth_callback: '/connect/twitter/callback'
oauth_signature_method: 'HMAC-SHA1'
endpoints:
credentials:
url: 'https://api.twitter.com/oauth/request_token'
method: 'POST'
header: 'Authorization'
scheme: 'OAuth'
accept: '*/*'
authorization:
url: 'https://api.twitter.com/oauth/authenticate'
token:
url: 'https://api.twitter.com/oauth/access_token'
method: 'POST'
user:
url: 'https://api.twitter.com/1.1/users/show.json'
method: 'GET'
header: 'Authorization'
scheme: 'OAuth'
mapping:
id: 'id'
name: 'PI:NAME:<NAME>END_PI'
preferredUsername: 'screen_name'
profile: 'url'
picture: 'profile_image_url'
twitterId: 'id'
}
{
id: 'wordpress'
name: 'WordPress'
protocolId: 'OAuth2'
url: ''
endpoints:
authorize:
url: 'https://public-api.wordpress.com/oauth2/authorize'
method: 'POST'
token:
url: 'https://public-api.wordpress.com/oauth2/token'
method: 'POST'
auth: 'client_secret_post'
user:
url: 'https://public-api.wordpress.com/rest/v1/me'
method: 'GET'
auth:
header: 'Authorization'
scheme: 'Bearer'
mapping:
id: 'ID'
email: 'email'
emailVerified: 'email_verified'
name: 'display_name'
preferredUsername: 'username'
picture: 'avatar_URL'
profile: 'profile_URL'
}
{
id: 'facebook'
name: 'Facebook'
protocolId: 'OAuth2'
url: 'https://www.facebook.com'
endpoints:
authorize:
url: 'https://www.facebook.com/dialog/oauth'
method: 'POST'
token:
url: 'https://graph.facebook.com/oauth/access_token'
method: 'POST'
auth: 'client_secret_post'
parser: 'x-www-form-urlencoded'
user:
url: 'https://graph.facebook.com/me'
method: 'GET'
auth:
header: 'Authorization'
scheme: 'Bearer'
separator: ','
mapping:
id: 'id'
emailVerified: 'verified'
name: 'name'
givenName: 'first_name'
familyName: 'last_name'
profile: 'link'
gender: 'gender'
locale: 'locale'
}
{
id: 'dropbox'
name: 'Dropbox'
protocolId: 'OAuth2'
url: 'https://www.dropbox.com'
endpoints:
authorize:
url: 'https://www.dropbox.com/1/oauth2/authorize'
method: 'POST'
token:
url: 'https://api.dropbox.com/1/oauth2/token'
method: 'POST'
auth: 'client_secret_basic'
user:
url: 'https://api.dropbox.com/1/account/info'
method: 'GET'
auth:
header: 'Authorization'
scheme: 'Bearer'
mapping:
id: 'uid'
name: 'PI:NAME:<NAME>END_PI'
email: 'email'
emailVerified: 'email_verified'
locale: 'country'
}
{
id: 'buffer'
name: 'buffer'
protocolId: 'OAuth2'
url: ''
endpoints:
authorize:
url: 'https://bufferapp.com/oauth2/authorize'
method: 'POST'
token:
url: 'https://api.bufferapp.com/1/oauth2/token.json'
method: 'POST'
auth: 'client_secret_basic'
user:
url: 'https://api.bufferapp.com/1/user.json'
method: 'GET'
auth: query: 'access_token'
mapping:
id: 'id'
name: 'name'
}
{
id: '37signals'
name: '37signals'
protocolId: 'OAuth2'
url: ''
endpoints:
authorize:
url: 'https://launchpad.37signals.com/authorization/new'
method: 'POST'
token:
url: 'https://launchpad.37signals.com/authorization/token'
method: 'POST'
auth: 'client_secret_basic'
user:
url: 'https://launchpad.37signals.com/authorization.json'
method: 'GET'
auth:
header: 'Authorization'
scheme: 'Bearer'
mapping: {}
}
{
id: 'angellist'
name: 'angellist'
protocolId: 'OAuth2'
url: ''
endpoints:
authorize:
url: 'https://angel.co/api/oauth/authorize'
method: 'POST'
token:
url: 'https://angel.co/api/oauth/token'
method: 'POST'
auth: 'client_secret_basic'
user:
url: 'https://api.angel.co/1/me'
method: 'GET'
auth: query: 'access_token'
mapping:
id: 'id'
name: 'name'
picture: 'image'
profile: 'angellist_url'
email: 'email'
website: 'online_bio_url'
}
] |
[
{
"context": "#\n# Copyright 2014 Carsten Klein\n#\n# Licensed under the Apache License, Version 2.",
"end": 32,
"score": 0.9998635053634644,
"start": 19,
"tag": "NAME",
"value": "Carsten Klein"
}
] | src/macros.coffee | vibejs/vibejs-subclassof | 0 | #
# Copyright 2014 Carsten Klein
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# are we running on Meteor?
if Npm?
assert = Npm.require 'assert'
else
assert = require 'assert'
require './monkeypatch'
require './subclassof'
# guard preventing us from installing twice
unless assert.subclassOf?
assert.subclassOf = (actual, expected, message) ->
if not subclassof actual, expected
actualName = actual?.name || actual
expectedName = expected?.name || expected
assert.fail actual, expected, message || "expected #{actualName} to be a subclass of #{expectedName}", "subclassof", assert.subclassOf
| 13909 | #
# Copyright 2014 <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# are we running on Meteor?
if Npm?
assert = Npm.require 'assert'
else
assert = require 'assert'
require './monkeypatch'
require './subclassof'
# guard preventing us from installing twice
unless assert.subclassOf?
assert.subclassOf = (actual, expected, message) ->
if not subclassof actual, expected
actualName = actual?.name || actual
expectedName = expected?.name || expected
assert.fail actual, expected, message || "expected #{actualName} to be a subclass of #{expectedName}", "subclassof", assert.subclassOf
| true | #
# Copyright 2014 PI:NAME:<NAME>END_PI
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# are we running on Meteor?
if Npm?
assert = Npm.require 'assert'
else
assert = require 'assert'
require './monkeypatch'
require './subclassof'
# guard preventing us from installing twice
unless assert.subclassOf?
assert.subclassOf = (actual, expected, message) ->
if not subclassof actual, expected
actualName = actual?.name || actual
expectedName = expected?.name || expected
assert.fail actual, expected, message || "expected #{actualName} to be a subclass of #{expectedName}", "subclassof", assert.subclassOf
|
[
{
"context": " ( done ) ->\n AgentModel.create(\n email: 'test+persona+routes@joukou.com'\n name: 'test/persona/routes'\n password",
"end": 1036,
"score": 0.9998576045036316,
"start": 1006,
"tag": "EMAIL",
"value": "test+persona+routes@joukou.com"
},
{
"context": " ... | test/persona/routes.coffee | joukou/joukou-api | 0 | ###*
Copyright 2014 Joukou Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
###
assert = require( 'assert' )
chai = require( 'chai' )
should = chai.should()
chai.use( require( 'chai-http' ) )
AgentModel = require( '../../dist/agent/Model' )
PersonaModel = require( '../../dist/persona/Model' )
server = require( '../../dist/server' )
riakpbc = require( '../../dist/riak/pbc' )
describe 'persona/routes', ->
agentKey = null
before ( done ) ->
AgentModel.create(
email: 'test+persona+routes@joukou.com'
name: 'test/persona/routes'
password: 'password'
).then( ( agent ) ->
agent.save()
)
.then( ( agent ) ->
agentKey = agent.getKey()
done()
)
.fail( ( err ) -> done( err ) )
after ( done ) ->
riakpbc.del(
type: 'agent'
bucket: 'agent'
key: agentKey
, ( err, reply ) -> done( err ) )
describe 'POST /persona', ->
specify 'creates a new persona given valid data', ( done ) ->
chai.request( server )
.post( '/persona' )
.req( ( req ) ->
req.set( 'Authorization', "Basic #{new Buffer( "test+persona+routes@joukou.com:password" ).toString( 'base64' )}" )
req.send(
name: 'Joukou Ltd'
)
)
.res( ( res ) ->
res.should.have.status( 201 )
res.headers.location.should.match( /^\/persona\/\w{8}-\w{4}-\w{4}-\w{4}-\w{12}$/ )
personaKey = res.headers.location.match( /^\/persona\/(\w{8}-\w{4}-\w{4}-\w{4}-\w{12})$/ )[ 1 ]
chai.request( server )
.get( res.headers.location )
.req( ( req ) ->
req.set( 'Authorization', "Basic #{new Buffer( "test+persona+routes@joukou.com:password" ).toString( 'base64' )}" )
)
.res( ( res ) ->
res.should.have.status( 200 )
res.body.should.deep.equal(
name: 'Joukou Ltd'
_links:
curies: [
{
name: 'joukou'
templated: true
href: 'https://rels.joukou.com/{rel}'
}
]
self:
href: "/persona/#{personaKey}"
'joukou:agent': [
{
name: 'creator'
href: "/agent/#{agentKey}"
}
]
'joukou:graphs': [
{
title: 'List of Graphs owned by this Persona'
href: "/persona/#{personaKey}/graph"
}
]
'joukou:graph-create': [
{
title: 'Create a Graph owned by this Persona'
href: "/persona/#{personaKey}/graph"
}
]
'joukou:circles': [
{
title: 'List of Circles available to this Persona'
href: "/persona/#{personaKey}/circle"
}
]
)
riakpbc.del(
type: 'persona'
bucket: 'persona'
key: personaKey
, ( err, reply ) -> done( err ) )
)
)
describe 'GET /persona/:personaKey', ->
specify 'responds with 404 NotFound status code if the provided persona key is not valid', ( done ) ->
chai.request( server )
.get( '/persona/7ec23d7d-9522-478c-97a4-2f577335e023' )
.req( ( req ) ->
req.set( 'Authorization', "Basic #{new Buffer( "test+persona+routes@joukou.com:password" ).toString( 'base64' )}" )
)
.res( ( res ) ->
res.should.have.status( 404 )
done()
)
| 138698 | ###*
Copyright 2014 Joukou Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
###
assert = require( 'assert' )
chai = require( 'chai' )
should = chai.should()
chai.use( require( 'chai-http' ) )
AgentModel = require( '../../dist/agent/Model' )
PersonaModel = require( '../../dist/persona/Model' )
server = require( '../../dist/server' )
riakpbc = require( '../../dist/riak/pbc' )
describe 'persona/routes', ->
agentKey = null
before ( done ) ->
AgentModel.create(
email: '<EMAIL>'
name: 'test/persona/routes'
password: '<PASSWORD>'
).then( ( agent ) ->
agent.save()
)
.then( ( agent ) ->
agentKey = agent.getKey()
done()
)
.fail( ( err ) -> done( err ) )
after ( done ) ->
riakpbc.del(
type: 'agent'
bucket: 'agent'
key: agentKey
, ( err, reply ) -> done( err ) )
describe 'POST /persona', ->
specify 'creates a new persona given valid data', ( done ) ->
chai.request( server )
.post( '/persona' )
.req( ( req ) ->
req.set( 'Authorization', "Basic #{new Buffer( "<EMAIL>:password" ).toString( 'base64' )}" )
req.send(
name: 'Joukou Ltd'
)
)
.res( ( res ) ->
res.should.have.status( 201 )
res.headers.location.should.match( /^\/persona\/\w{8}-\w{4}-\w{4}-\w{4}-\w{12}$/ )
personaKey = res.headers.location.match( /^\/persona\/(\w{8}-\w{4}-\w{4}-\w{4}-\w{12})$/ )[ 1 ]
chai.request( server )
.get( res.headers.location )
.req( ( req ) ->
req.set( 'Authorization', "Basic #{new Buffer( "<EMAIL>:password" ).toString( 'base64' )}" )
)
.res( ( res ) ->
res.should.have.status( 200 )
res.body.should.deep.equal(
name: 'Joukou Ltd'
_links:
curies: [
{
name: 'joukou'
templated: true
href: 'https://rels.joukou.com/{rel}'
}
]
self:
href: "/persona/#{personaKey}"
'joukou:agent': [
{
name: 'creator'
href: "/agent/#{agentKey}"
}
]
'joukou:graphs': [
{
title: 'List of Graphs owned by this Persona'
href: "/persona/#{personaKey}/graph"
}
]
'joukou:graph-create': [
{
title: 'Create a Graph owned by this Persona'
href: "/persona/#{personaKey}/graph"
}
]
'joukou:circles': [
{
title: 'List of Circles available to this Persona'
href: "/persona/#{personaKey}/circle"
}
]
)
riakpbc.del(
type: 'persona'
bucket: 'persona'
key: personaKey
, ( err, reply ) -> done( err ) )
)
)
describe 'GET /persona/:personaKey', ->
specify 'responds with 404 NotFound status code if the provided persona key is not valid', ( done ) ->
chai.request( server )
.get( '/persona/7ec23d7d-9522-478c-97a4-2f577335e023' )
.req( ( req ) ->
req.set( 'Authorization', "Basic #{new Buffer( "<EMAIL>:password" ).toString( 'base64' )}" )
)
.res( ( res ) ->
res.should.have.status( 404 )
done()
)
| true | ###*
Copyright 2014 Joukou Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
###
assert = require( 'assert' )
chai = require( 'chai' )
should = chai.should()
chai.use( require( 'chai-http' ) )
AgentModel = require( '../../dist/agent/Model' )
PersonaModel = require( '../../dist/persona/Model' )
server = require( '../../dist/server' )
riakpbc = require( '../../dist/riak/pbc' )
describe 'persona/routes', ->
agentKey = null
before ( done ) ->
AgentModel.create(
email: 'PI:EMAIL:<EMAIL>END_PI'
name: 'test/persona/routes'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
).then( ( agent ) ->
agent.save()
)
.then( ( agent ) ->
agentKey = agent.getKey()
done()
)
.fail( ( err ) -> done( err ) )
after ( done ) ->
riakpbc.del(
type: 'agent'
bucket: 'agent'
key: agentKey
, ( err, reply ) -> done( err ) )
describe 'POST /persona', ->
specify 'creates a new persona given valid data', ( done ) ->
chai.request( server )
.post( '/persona' )
.req( ( req ) ->
req.set( 'Authorization', "Basic #{new Buffer( "PI:EMAIL:<EMAIL>END_PI:password" ).toString( 'base64' )}" )
req.send(
name: 'Joukou Ltd'
)
)
.res( ( res ) ->
res.should.have.status( 201 )
res.headers.location.should.match( /^\/persona\/\w{8}-\w{4}-\w{4}-\w{4}-\w{12}$/ )
personaKey = res.headers.location.match( /^\/persona\/(\w{8}-\w{4}-\w{4}-\w{4}-\w{12})$/ )[ 1 ]
chai.request( server )
.get( res.headers.location )
.req( ( req ) ->
req.set( 'Authorization', "Basic #{new Buffer( "PI:EMAIL:<EMAIL>END_PI:password" ).toString( 'base64' )}" )
)
.res( ( res ) ->
res.should.have.status( 200 )
res.body.should.deep.equal(
name: 'Joukou Ltd'
_links:
curies: [
{
name: 'joukou'
templated: true
href: 'https://rels.joukou.com/{rel}'
}
]
self:
href: "/persona/#{personaKey}"
'joukou:agent': [
{
name: 'creator'
href: "/agent/#{agentKey}"
}
]
'joukou:graphs': [
{
title: 'List of Graphs owned by this Persona'
href: "/persona/#{personaKey}/graph"
}
]
'joukou:graph-create': [
{
title: 'Create a Graph owned by this Persona'
href: "/persona/#{personaKey}/graph"
}
]
'joukou:circles': [
{
title: 'List of Circles available to this Persona'
href: "/persona/#{personaKey}/circle"
}
]
)
riakpbc.del(
type: 'persona'
bucket: 'persona'
key: personaKey
, ( err, reply ) -> done( err ) )
)
)
describe 'GET /persona/:personaKey', ->
specify 'responds with 404 NotFound status code if the provided persona key is not valid', ( done ) ->
chai.request( server )
.get( '/persona/7ec23d7d-9522-478c-97a4-2f577335e023' )
.req( ( req ) ->
req.set( 'Authorization', "Basic #{new Buffer( "PI:EMAIL:<EMAIL>END_PI:password" ).toString( 'base64' )}" )
)
.res( ( res ) ->
res.should.have.status( 404 )
done()
)
|
[
{
"context": " process.env.RUTRACKER_LOGIN\n login_password: process.env.RUTRACKER_PASSWORD\n redirect: 'index.php'\n login: ",
"end": 500,
"score": 0.9228500127792358,
"start": 470,
"tag": "PASSWORD",
"value": "process.env.RUTRACKER_PASSWORD"
}
] | lib/hubot-torrent/adapters/rutracker/authorize_granter.coffee | dnesteryuk/hubot-torrent | 2 | class AuthorizeGranter
_trackerHost: 'rutracker.org'
_pathToLogin: '/forum/login.php'
_requiredEnvVars: [
'RUTRACKER_LOGIN'
'RUTRACKER_PASSWORD'
]
trackerName: ->
'Rutracker'
parseAuthCode: (res) ->
res.headers['set-cookie'][0].match(/bb_data=([\w-\d]+);/)[0].replace(';', '')
authorizeData: ->
querystring = require('querystring')
querystring.stringify(
login_username: process.env.RUTRACKER_LOGIN
login_password: process.env.RUTRACKER_PASSWORD
redirect: 'index.php'
login: 'Вход'
)
authorizeOptions: ->
host: "login.#{@_trackerHost}"
port: 80
method: 'POST'
path: '/forum/login.php'
headers:
'Content-Type': 'application/x-www-form-urlencoded'
'Content-Length': this.authorizeData().length
'Referer': "http://login.#{@_trackerHost}#{@_pathToLogin}"
requiredEnvVars: ->
@_requiredEnvVars
module.exports = AuthorizeGranter | 224831 | class AuthorizeGranter
_trackerHost: 'rutracker.org'
_pathToLogin: '/forum/login.php'
_requiredEnvVars: [
'RUTRACKER_LOGIN'
'RUTRACKER_PASSWORD'
]
trackerName: ->
'Rutracker'
parseAuthCode: (res) ->
res.headers['set-cookie'][0].match(/bb_data=([\w-\d]+);/)[0].replace(';', '')
authorizeData: ->
querystring = require('querystring')
querystring.stringify(
login_username: process.env.RUTRACKER_LOGIN
login_password: <PASSWORD>
redirect: 'index.php'
login: 'Вход'
)
authorizeOptions: ->
host: "login.#{@_trackerHost}"
port: 80
method: 'POST'
path: '/forum/login.php'
headers:
'Content-Type': 'application/x-www-form-urlencoded'
'Content-Length': this.authorizeData().length
'Referer': "http://login.#{@_trackerHost}#{@_pathToLogin}"
requiredEnvVars: ->
@_requiredEnvVars
module.exports = AuthorizeGranter | true | class AuthorizeGranter
_trackerHost: 'rutracker.org'
_pathToLogin: '/forum/login.php'
_requiredEnvVars: [
'RUTRACKER_LOGIN'
'RUTRACKER_PASSWORD'
]
trackerName: ->
'Rutracker'
parseAuthCode: (res) ->
res.headers['set-cookie'][0].match(/bb_data=([\w-\d]+);/)[0].replace(';', '')
authorizeData: ->
querystring = require('querystring')
querystring.stringify(
login_username: process.env.RUTRACKER_LOGIN
login_password: PI:PASSWORD:<PASSWORD>END_PI
redirect: 'index.php'
login: 'Вход'
)
authorizeOptions: ->
host: "login.#{@_trackerHost}"
port: 80
method: 'POST'
path: '/forum/login.php'
headers:
'Content-Type': 'application/x-www-form-urlencoded'
'Content-Length': this.authorizeData().length
'Referer': "http://login.#{@_trackerHost}#{@_pathToLogin}"
requiredEnvVars: ->
@_requiredEnvVars
module.exports = AuthorizeGranter |
[
{
"context": "{@serverPort}\"\n auth:\n username: 'some-uuid'\n password: 'some-token'\n qs:\n ",
"end": 1590,
"score": 0.9938365817070007,
"start": 1581,
"tag": "USERNAME",
"value": "some-uuid"
},
{
"context": " username: 'some-uuid'\n ... | test/integration/meshblu-get-gmail-spec.coffee | octoblu/meshblu-get-gmail | 0 | {beforeEach, afterEach, describe, it} = global
{expect} = require 'chai'
sinon = require 'sinon'
shmock = require '@octoblu/shmock'
request = require 'request'
enableDestroy = require 'server-destroy'
Server = require '../../src/server'
describe 'Connect to GMAIL', ->
beforeEach (done) ->
@logFn = sinon.spy()
@fakeGmail =
messages: sinon.stub()
@fakeStream =
on: sinon.stub()
serverOptions =
port: undefined,
disableLogging: true
logFn: @logFn
fakeGmail: @fakeGmail
@server = new Server serverOptions
@server.run =>
@serverPort = @server.address().port
done()
afterEach ->
@server.destroy()
describe.only 'On GET /email', ->
beforeEach (done) ->
options =
uri: '/email'
baseUrl: "http://localhost:#{@serverPort}"
json: true
qs:
apiKey: 'some-api-key'
max:1
@fakeGmail.messages.yields @fakeStream
@fakeStream.on.yields null
request.get options, (error, @response, @body) =>
done error
it 'should return a 200', ->
expect(@response.statusCode).to.equal 200
xdescribe 'when the service yields an error', ->
beforeEach (done) ->
userAuth = new Buffer('some-uuid:some-token').toString 'base64'
@authDevice = @meshblu
.post '/authenticate'
.set 'Authorization', "Basic #{userAuth}"
.reply 204
options =
uri: '/hello'
baseUrl: "http://localhost:#{@serverPort}"
auth:
username: 'some-uuid'
password: 'some-token'
qs:
hasError: true
json: true
request.get options, (error, @response, @body) =>
done error
it 'should log the error', ->
expect(@logFn).to.have.been.called
it 'should auth and response with 500', ->
expect(@response.statusCode).to.equal 500
| 218345 | {beforeEach, afterEach, describe, it} = global
{expect} = require 'chai'
sinon = require 'sinon'
shmock = require '@octoblu/shmock'
request = require 'request'
enableDestroy = require 'server-destroy'
Server = require '../../src/server'
describe 'Connect to GMAIL', ->
beforeEach (done) ->
@logFn = sinon.spy()
@fakeGmail =
messages: sinon.stub()
@fakeStream =
on: sinon.stub()
serverOptions =
port: undefined,
disableLogging: true
logFn: @logFn
fakeGmail: @fakeGmail
@server = new Server serverOptions
@server.run =>
@serverPort = @server.address().port
done()
afterEach ->
@server.destroy()
describe.only 'On GET /email', ->
beforeEach (done) ->
options =
uri: '/email'
baseUrl: "http://localhost:#{@serverPort}"
json: true
qs:
apiKey: 'some-api-key'
max:1
@fakeGmail.messages.yields @fakeStream
@fakeStream.on.yields null
request.get options, (error, @response, @body) =>
done error
it 'should return a 200', ->
expect(@response.statusCode).to.equal 200
xdescribe 'when the service yields an error', ->
beforeEach (done) ->
userAuth = new Buffer('some-uuid:some-token').toString 'base64'
@authDevice = @meshblu
.post '/authenticate'
.set 'Authorization', "Basic #{userAuth}"
.reply 204
options =
uri: '/hello'
baseUrl: "http://localhost:#{@serverPort}"
auth:
username: 'some-uuid'
password: '<PASSWORD>'
qs:
hasError: true
json: true
request.get options, (error, @response, @body) =>
done error
it 'should log the error', ->
expect(@logFn).to.have.been.called
it 'should auth and response with 500', ->
expect(@response.statusCode).to.equal 500
| true | {beforeEach, afterEach, describe, it} = global
{expect} = require 'chai'
sinon = require 'sinon'
shmock = require '@octoblu/shmock'
request = require 'request'
enableDestroy = require 'server-destroy'
Server = require '../../src/server'
describe 'Connect to GMAIL', ->
beforeEach (done) ->
@logFn = sinon.spy()
@fakeGmail =
messages: sinon.stub()
@fakeStream =
on: sinon.stub()
serverOptions =
port: undefined,
disableLogging: true
logFn: @logFn
fakeGmail: @fakeGmail
@server = new Server serverOptions
@server.run =>
@serverPort = @server.address().port
done()
afterEach ->
@server.destroy()
describe.only 'On GET /email', ->
beforeEach (done) ->
options =
uri: '/email'
baseUrl: "http://localhost:#{@serverPort}"
json: true
qs:
apiKey: 'some-api-key'
max:1
@fakeGmail.messages.yields @fakeStream
@fakeStream.on.yields null
request.get options, (error, @response, @body) =>
done error
it 'should return a 200', ->
expect(@response.statusCode).to.equal 200
xdescribe 'when the service yields an error', ->
beforeEach (done) ->
userAuth = new Buffer('some-uuid:some-token').toString 'base64'
@authDevice = @meshblu
.post '/authenticate'
.set 'Authorization', "Basic #{userAuth}"
.reply 204
options =
uri: '/hello'
baseUrl: "http://localhost:#{@serverPort}"
auth:
username: 'some-uuid'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
qs:
hasError: true
json: true
request.get options, (error, @response, @body) =>
done error
it 'should log the error', ->
expect(@logFn).to.have.been.called
it 'should auth and response with 500', ->
expect(@response.statusCode).to.equal 500
|
[
{
"context": " backbone-orm.js 0.7.14\n Copyright (c) 2013-2016 Vidigami\n License: MIT (http://www.opensource.org/license",
"end": 63,
"score": 0.9998775720596313,
"start": 55,
"tag": "NAME",
"value": "Vidigami"
},
{
"context": "ses/mit-license.php)\n Source: https://github.com/... | src/lib/schema.coffee | dk-dev/backbone-orm | 54 | ###
backbone-orm.js 0.7.14
Copyright (c) 2013-2016 Vidigami
License: MIT (http://www.opensource.org/licenses/mit-license.php)
Source: https://github.com/vidigami/backbone-orm
Dependencies: Backbone.js and Underscore.js.
###
_ = require 'underscore'
Backbone = require 'backbone'
BackboneORM = require '../core'
One = require '../relations/one'
Many = require '../relations/many'
DatabaseURL = require './database_url'
Utils = require './utils'
JSONUtils = require './json_utils'
RELATION_VARIANTS =
'hasOne': 'hasOne'
'has_one': 'hasOne'
'HasOne': 'hasOne'
'belongsTo': 'belongsTo'
'belongs_to': 'belongsTo'
'BelongsTo': 'belongsTo'
'hasMany': 'hasMany'
'has_many': 'hasMany'
'HasMany': 'hasMany'
# @private
module.exports = class Schema
# @nodoc
constructor: (@model_type, @type_overrides={}) ->
@raw = _.clone(_.result(new @model_type(), 'schema') or {})
@fields = {}; @relations = {}; @virtual_accessors = {}
@_parseField('id', @raw.id) if @raw.id
# @nodoc
initialize: ->
return if @is_initialized; @is_initialized = true
# initalize in two steps to break circular dependencies
@_parseField(key, info) for key, info of @raw
relation.initialize() for key, relation of @relations
return
type: (key, type) ->
((@type_overrides[key] or= {})['type'] = type; return @) if arguments.length is 2
(other = key.substr(index+1); key = key.substr(0, index)) if (index = key.indexOf('.')) >= 0 # queries like 'flat.id'
return unless type = @type_overrides[key]?.type or @fields[key]?.type or @relation(key)?.reverse_model_type or @reverseRelation(key)?.model_type
if @virtual_accessors[key]
(console.log "Unexpected other for virtual id key: #{key}.#{other}"; return) if other
return type.schema?().type('id') or type
return if other then type.schema?().type(other) else type
idType: (key) ->
return @type('id') unless key
return type.schema?().type('id') or type if type = @type(key)
field: (key) -> return @fields[key] or @relation(key)
relation: (key) -> return @relations[key] or @virtual_accessors[key]
reverseRelation: (reverse_key) ->
return relation.reverse_relation for key, relation of @relations when relation.reverse_relation and (relation.reverse_relation.join_key is reverse_key)
return null
# column and relationship helpers
columns: ->
columns = _.keys(@fields)
columns.push('id') if not _.find(columns, (column) -> column is 'id')
columns.push(relation.foreign_key) for key, relation of @relations when (relation.type is 'belongsTo') and not relation.isVirtual() and not relation.isEmbedded()
return columns
joinTables: ->
return (relation.join_table for key, relation of @relations when not relation.isVirtual() and relation.join_table)
relatedModels: ->
related_model_types = []
for key, relation of @relations
related_model_types.push(relation.reverse_model_type)
related_model_types.push(relation.join_table) if relation.join_table
return related_model_types
# TO DEPRECATE
allColumns: -> @columns()
allRelations: -> @relatedModels()
# @nodoc
generateBelongsTo: (reverse_model_type) ->
key = BackboneORM.naming_conventions.attribute(reverse_model_type.model_name)
return relation if relation = @relations[key] # already exists
if @raw[key] # not intitialized yet, intialize now
relation = @_parseField(key, @raw[key])
relation.initialize()
return relation
# generate new
relation = @_parseField(key, @raw[key] = ['belongsTo', reverse_model_type, manual_fetch: true])
relation.initialize()
return relation
@joinTableURL: (relation) ->
table_name1 = BackboneORM.naming_conventions.tableName(relation.model_type.model_name)
table_name2 = BackboneORM.naming_conventions.tableName(relation.reverse_relation.model_type.model_name)
return if table_name1.localeCompare(table_name2) < 0 then "#{table_name1}_#{table_name2}" else "#{table_name2}_#{table_name1}"
# @nodoc
generateJoinTable: (relation) ->
schema = {}
schema[relation.join_key] = [type = relation.model_type.schema().type('id'), indexed: true]
schema[relation.reverse_relation.join_key] = [relation.reverse_model_type?.schema().type('id') or type, indexed: true]
url = Schema.joinTableURL(relation)
name = BackboneORM.naming_conventions.modelName(url, true)
try
# @nodoc
class JoinTable extends Backbone.Model
model_name: name
urlRoot: "#{(new DatabaseURL(_.result(new relation.model_type, 'url'))).format({exclude_table: true})}/#{url}"
schema: schema
sync: relation.model_type.createSync(JoinTable)
catch
# @nodoc
class JoinTable extends Backbone.Model
model_name: name
urlRoot: "/#{url}"
schema: schema
sync: relation.model_type.createSync(JoinTable)
return JoinTable
# Internal
# @nodoc
_parseField: (key, info) ->
options = @_fieldInfoToOptions(if _.isFunction(info) then info() else info)
return @fields[key] = options unless options.type
# unrecognized
unless type = RELATION_VARIANTS[options.type]
throw new Error "Unexpected type name is not a string: #{JSONUtils.stringify(options)}" unless _.isString(options.type)
return @fields[key] = options
options.type = type
relation = @relations[key] = if type is 'hasMany' then new Many(@model_type, key, options) else new One(@model_type, key, options)
@virtual_accessors[relation.virtual_id_accessor] = relation if relation.virtual_id_accessor
@virtual_accessors[relation.foreign_key] = relation if type is 'belongsTo'
return relation
# @nodoc
_fieldInfoToOptions: (options) ->
# convert to an object
return {type: options} if _.isString(options)
return options unless _.isArray(options)
# type
result = {}
if _.isString(options[0])
result.type = options[0]
options = options.slice(1)
return result if options.length is 0
# reverse relation
if _.isFunction(options[0])
result.reverse_model_type = options[0]
options = options.slice(1)
# too many options
throw new Error "Unexpected field options array: #{JSONUtils.stringify(options)}" if options.length > 1
# options object
_.extend(result, options[0]) if options.length is 1
return result
| 132646 | ###
backbone-orm.js 0.7.14
Copyright (c) 2013-2016 <NAME>
License: MIT (http://www.opensource.org/licenses/mit-license.php)
Source: https://github.com/vidigami/backbone-orm
Dependencies: Backbone.js and Underscore.js.
###
_ = require 'underscore'
Backbone = require 'backbone'
BackboneORM = require '../core'
One = require '../relations/one'
Many = require '../relations/many'
DatabaseURL = require './database_url'
Utils = require './utils'
JSONUtils = require './json_utils'
RELATION_VARIANTS =
'hasOne': 'hasOne'
'has_one': 'hasOne'
'HasOne': 'hasOne'
'belongsTo': 'belongsTo'
'belongs_to': 'belongsTo'
'BelongsTo': 'belongsTo'
'hasMany': 'hasMany'
'has_many': 'hasMany'
'HasMany': 'hasMany'
# @private
module.exports = class Schema
# @nodoc
constructor: (@model_type, @type_overrides={}) ->
@raw = _.clone(_.result(new @model_type(), 'schema') or {})
@fields = {}; @relations = {}; @virtual_accessors = {}
@_parseField('id', @raw.id) if @raw.id
# @nodoc
initialize: ->
return if @is_initialized; @is_initialized = true
# initalize in two steps to break circular dependencies
@_parseField(key, info) for key, info of @raw
relation.initialize() for key, relation of @relations
return
type: (key, type) ->
((@type_overrides[key] or= {})['type'] = type; return @) if arguments.length is 2
(other = key.substr(index+1); key = key.substr(0, index)) if (index = key.indexOf('.')) >= 0 # queries like 'flat.id'
return unless type = @type_overrides[key]?.type or @fields[key]?.type or @relation(key)?.reverse_model_type or @reverseRelation(key)?.model_type
if @virtual_accessors[key]
(console.log "Unexpected other for virtual id key: #{key}.#{other}"; return) if other
return type.schema?().type('id') or type
return if other then type.schema?().type(other) else type
idType: (key) ->
return @type('id') unless key
return type.schema?().type('id') or type if type = @type(key)
field: (key) -> return @fields[key] or @relation(key)
relation: (key) -> return @relations[key] or @virtual_accessors[key]
reverseRelation: (reverse_key) ->
return relation.reverse_relation for key, relation of @relations when relation.reverse_relation and (relation.reverse_relation.join_key is reverse_key)
return null
# column and relationship helpers
columns: ->
columns = _.keys(@fields)
columns.push('id') if not _.find(columns, (column) -> column is 'id')
columns.push(relation.foreign_key) for key, relation of @relations when (relation.type is 'belongsTo') and not relation.isVirtual() and not relation.isEmbedded()
return columns
joinTables: ->
return (relation.join_table for key, relation of @relations when not relation.isVirtual() and relation.join_table)
relatedModels: ->
related_model_types = []
for key, relation of @relations
related_model_types.push(relation.reverse_model_type)
related_model_types.push(relation.join_table) if relation.join_table
return related_model_types
# TO DEPRECATE
allColumns: -> @columns()
allRelations: -> @relatedModels()
# @nodoc
generateBelongsTo: (reverse_model_type) ->
key = BackboneORM.naming_conventions.attribute(reverse_model_type.model_name)
return relation if relation = @relations[key] # already exists
if @raw[key] # not intitialized yet, intialize now
relation = @_parseField(key, @raw[key])
relation.initialize()
return relation
# generate new
relation = @_parseField(key, @raw[key] = ['belongsTo', reverse_model_type, manual_fetch: true])
relation.initialize()
return relation
@joinTableURL: (relation) ->
table_name1 = BackboneORM.naming_conventions.tableName(relation.model_type.model_name)
table_name2 = BackboneORM.naming_conventions.tableName(relation.reverse_relation.model_type.model_name)
return if table_name1.localeCompare(table_name2) < 0 then "#{table_name1}_#{table_name2}" else "#{table_name2}_#{table_name1}"
# @nodoc
generateJoinTable: (relation) ->
schema = {}
schema[relation.join_key] = [type = relation.model_type.schema().type('id'), indexed: true]
schema[relation.reverse_relation.join_key] = [relation.reverse_model_type?.schema().type('id') or type, indexed: true]
url = Schema.joinTableURL(relation)
name = BackboneORM.naming_conventions.modelName(url, true)
try
# @nodoc
class JoinTable extends Backbone.Model
model_name: name
urlRoot: "#{(new DatabaseURL(_.result(new relation.model_type, 'url'))).format({exclude_table: true})}/#{url}"
schema: schema
sync: relation.model_type.createSync(JoinTable)
catch
# @nodoc
class JoinTable extends Backbone.Model
model_name: name
urlRoot: "/#{url}"
schema: schema
sync: relation.model_type.createSync(JoinTable)
return JoinTable
# Internal
# @nodoc
_parseField: (key, info) ->
options = @_fieldInfoToOptions(if _.isFunction(info) then info() else info)
return @fields[key] = options unless options.type
# unrecognized
unless type = RELATION_VARIANTS[options.type]
throw new Error "Unexpected type name is not a string: #{JSONUtils.stringify(options)}" unless _.isString(options.type)
return @fields[key] = options
options.type = type
relation = @relations[key] = if type is 'hasMany' then new Many(@model_type, key, options) else new One(@model_type, key, options)
@virtual_accessors[relation.virtual_id_accessor] = relation if relation.virtual_id_accessor
@virtual_accessors[relation.foreign_key] = relation if type is 'belongsTo'
return relation
# @nodoc
_fieldInfoToOptions: (options) ->
# convert to an object
return {type: options} if _.isString(options)
return options unless _.isArray(options)
# type
result = {}
if _.isString(options[0])
result.type = options[0]
options = options.slice(1)
return result if options.length is 0
# reverse relation
if _.isFunction(options[0])
result.reverse_model_type = options[0]
options = options.slice(1)
# too many options
throw new Error "Unexpected field options array: #{JSONUtils.stringify(options)}" if options.length > 1
# options object
_.extend(result, options[0]) if options.length is 1
return result
| true | ###
backbone-orm.js 0.7.14
Copyright (c) 2013-2016 PI:NAME:<NAME>END_PI
License: MIT (http://www.opensource.org/licenses/mit-license.php)
Source: https://github.com/vidigami/backbone-orm
Dependencies: Backbone.js and Underscore.js.
###
_ = require 'underscore'
Backbone = require 'backbone'
BackboneORM = require '../core'
One = require '../relations/one'
Many = require '../relations/many'
DatabaseURL = require './database_url'
Utils = require './utils'
JSONUtils = require './json_utils'
RELATION_VARIANTS =
'hasOne': 'hasOne'
'has_one': 'hasOne'
'HasOne': 'hasOne'
'belongsTo': 'belongsTo'
'belongs_to': 'belongsTo'
'BelongsTo': 'belongsTo'
'hasMany': 'hasMany'
'has_many': 'hasMany'
'HasMany': 'hasMany'
# @private
module.exports = class Schema
# @nodoc
constructor: (@model_type, @type_overrides={}) ->
@raw = _.clone(_.result(new @model_type(), 'schema') or {})
@fields = {}; @relations = {}; @virtual_accessors = {}
@_parseField('id', @raw.id) if @raw.id
# @nodoc
initialize: ->
return if @is_initialized; @is_initialized = true
# initalize in two steps to break circular dependencies
@_parseField(key, info) for key, info of @raw
relation.initialize() for key, relation of @relations
return
type: (key, type) ->
((@type_overrides[key] or= {})['type'] = type; return @) if arguments.length is 2
(other = key.substr(index+1); key = key.substr(0, index)) if (index = key.indexOf('.')) >= 0 # queries like 'flat.id'
return unless type = @type_overrides[key]?.type or @fields[key]?.type or @relation(key)?.reverse_model_type or @reverseRelation(key)?.model_type
if @virtual_accessors[key]
(console.log "Unexpected other for virtual id key: #{key}.#{other}"; return) if other
return type.schema?().type('id') or type
return if other then type.schema?().type(other) else type
idType: (key) ->
return @type('id') unless key
return type.schema?().type('id') or type if type = @type(key)
field: (key) -> return @fields[key] or @relation(key)
relation: (key) -> return @relations[key] or @virtual_accessors[key]
reverseRelation: (reverse_key) ->
return relation.reverse_relation for key, relation of @relations when relation.reverse_relation and (relation.reverse_relation.join_key is reverse_key)
return null
# column and relationship helpers
columns: ->
columns = _.keys(@fields)
columns.push('id') if not _.find(columns, (column) -> column is 'id')
columns.push(relation.foreign_key) for key, relation of @relations when (relation.type is 'belongsTo') and not relation.isVirtual() and not relation.isEmbedded()
return columns
joinTables: ->
return (relation.join_table for key, relation of @relations when not relation.isVirtual() and relation.join_table)
relatedModels: ->
related_model_types = []
for key, relation of @relations
related_model_types.push(relation.reverse_model_type)
related_model_types.push(relation.join_table) if relation.join_table
return related_model_types
# TO DEPRECATE
allColumns: -> @columns()
allRelations: -> @relatedModels()
# @nodoc
generateBelongsTo: (reverse_model_type) ->
key = BackboneORM.naming_conventions.attribute(reverse_model_type.model_name)
return relation if relation = @relations[key] # already exists
if @raw[key] # not intitialized yet, intialize now
relation = @_parseField(key, @raw[key])
relation.initialize()
return relation
# generate new
relation = @_parseField(key, @raw[key] = ['belongsTo', reverse_model_type, manual_fetch: true])
relation.initialize()
return relation
@joinTableURL: (relation) ->
table_name1 = BackboneORM.naming_conventions.tableName(relation.model_type.model_name)
table_name2 = BackboneORM.naming_conventions.tableName(relation.reverse_relation.model_type.model_name)
return if table_name1.localeCompare(table_name2) < 0 then "#{table_name1}_#{table_name2}" else "#{table_name2}_#{table_name1}"
# @nodoc
generateJoinTable: (relation) ->
schema = {}
schema[relation.join_key] = [type = relation.model_type.schema().type('id'), indexed: true]
schema[relation.reverse_relation.join_key] = [relation.reverse_model_type?.schema().type('id') or type, indexed: true]
url = Schema.joinTableURL(relation)
name = BackboneORM.naming_conventions.modelName(url, true)
try
# @nodoc
class JoinTable extends Backbone.Model
model_name: name
urlRoot: "#{(new DatabaseURL(_.result(new relation.model_type, 'url'))).format({exclude_table: true})}/#{url}"
schema: schema
sync: relation.model_type.createSync(JoinTable)
catch
# @nodoc
class JoinTable extends Backbone.Model
model_name: name
urlRoot: "/#{url}"
schema: schema
sync: relation.model_type.createSync(JoinTable)
return JoinTable
# Internal
# @nodoc
_parseField: (key, info) ->
options = @_fieldInfoToOptions(if _.isFunction(info) then info() else info)
return @fields[key] = options unless options.type
# unrecognized
unless type = RELATION_VARIANTS[options.type]
throw new Error "Unexpected type name is not a string: #{JSONUtils.stringify(options)}" unless _.isString(options.type)
return @fields[key] = options
options.type = type
relation = @relations[key] = if type is 'hasMany' then new Many(@model_type, key, options) else new One(@model_type, key, options)
@virtual_accessors[relation.virtual_id_accessor] = relation if relation.virtual_id_accessor
@virtual_accessors[relation.foreign_key] = relation if type is 'belongsTo'
return relation
# @nodoc
_fieldInfoToOptions: (options) ->
# convert to an object
return {type: options} if _.isString(options)
return options unless _.isArray(options)
# type
result = {}
if _.isString(options[0])
result.type = options[0]
options = options.slice(1)
return result if options.length is 0
# reverse relation
if _.isFunction(options[0])
result.reverse_model_type = options[0]
options = options.slice(1)
# too many options
throw new Error "Unexpected field options array: #{JSONUtils.stringify(options)}" if options.length > 1
# options object
_.extend(result, options[0]) if options.length is 1
return result
|
[
{
"context": " firstName: potato.String\n default: \"Marcel\"\n lastName: potato.String\n defa",
"end": 197,
"score": 0.9998296499252319,
"start": 191,
"tag": "NAME",
"value": "Marcel"
},
{
"context": " lastName: potato.String\n default: \... | potato/examples/inheritance.coffee | fulmicoton/fulmicoton.github.io | 4 | # One can describes Potato as a composition of
# literal object. Here we extend the potato "Model"
Name = potato.Model
components:
firstName: potato.String
default: "Marcel"
lastName: potato.String
default: "Patulacci"
methods:
toString: ->
@firstName + " " + @lastName
# Use his defined potatoes within other
# objects.
Profile = potato.Potato
components:
name: Name
# Or even define such potatoes inline.
Profile = potato.Potato
components:
name: potato.Potato
components:
firstName: potato.String
lastName: potato.String
# Extend and override stuff (here american name have
# firstnames, lastnames, and middle names)
AmericanName = Name
components:
middleName: potato.String
default: "Robert"
methods:
toString: ->
@firstName + " " + @middleName + " " + @lastName
# Override components m( O_O )m
ItalianName = AmericanName
components:
middleName: potato.String
default: "Roberto"
InheritanceExample = potato.View
template: """
<h1>No demo only code here sorry!</h1>
"""
events:
"": "render": ->
# And obviously free lunch !
potato.log AmericanName.make().toJSON()
potato.log AmericanName.make({ firstName: "Richard" }).toJSON()
| 27908 | # One can describes Potato as a composition of
# literal object. Here we extend the potato "Model"
Name = potato.Model
components:
firstName: potato.String
default: "<NAME>"
lastName: potato.String
default: "<NAME>"
methods:
toString: ->
@firstName + " " + @lastName
# Use his defined potatoes within other
# objects.
Profile = potato.Potato
components:
name: Name
# Or even define such potatoes inline.
Profile = potato.Potato
components:
name: potato.Potato
components:
firstName: potato.String
lastName: potato.String
# Extend and override stuff (here american name have
# firstnames, lastnames, and middle names)
AmericanName = Name
components:
middleName: potato.String
default: "<NAME>"
methods:
toString: ->
@firstName + " " + @middleName + " " + @lastName
# Override components m( O_O )m
ItalianName = AmericanName
components:
middleName: potato.String
default: "<NAME>"
InheritanceExample = potato.View
template: """
<h1>No demo only code here sorry!</h1>
"""
events:
"": "render": ->
# And obviously free lunch !
potato.log AmericanName.make().toJSON()
potato.log AmericanName.make({ firstName: "<NAME>" }).toJSON()
| true | # One can describes Potato as a composition of
# literal object. Here we extend the potato "Model"
Name = potato.Model
components:
firstName: potato.String
default: "PI:NAME:<NAME>END_PI"
lastName: potato.String
default: "PI:NAME:<NAME>END_PI"
methods:
toString: ->
@firstName + " " + @lastName
# Use his defined potatoes within other
# objects.
Profile = potato.Potato
components:
name: Name
# Or even define such potatoes inline.
Profile = potato.Potato
components:
name: potato.Potato
components:
firstName: potato.String
lastName: potato.String
# Extend and override stuff (here american name have
# firstnames, lastnames, and middle names)
AmericanName = Name
components:
middleName: potato.String
default: "PI:NAME:<NAME>END_PI"
methods:
toString: ->
@firstName + " " + @middleName + " " + @lastName
# Override components m( O_O )m
ItalianName = AmericanName
components:
middleName: potato.String
default: "PI:NAME:<NAME>END_PI"
InheritanceExample = potato.View
template: """
<h1>No demo only code here sorry!</h1>
"""
events:
"": "render": ->
# And obviously free lunch !
potato.log AmericanName.make().toJSON()
potato.log AmericanName.make({ firstName: "PI:NAME:<NAME>END_PI" }).toJSON()
|
[
{
"context": "UI autocomplete editor 1.0.0\n\n Copyright (c) 2016 Tomasz Jakub Rup\n\n https://github.com/tomi77/backbone-forms-jquer",
"end": 95,
"score": 0.9998703598976135,
"start": 79,
"tag": "NAME",
"value": "Tomasz Jakub Rup"
},
{
"context": "t (c) 2016 Tomasz Jakub Rup\n\n ... | src/autocomplete.coffee | tomi77/backbone-forms-jquery-ui | 0 | ###
Backbone-Forms jQuery UI autocomplete editor 1.0.0
Copyright (c) 2016 Tomasz Jakub Rup
https://github.com/tomi77/backbone-forms-jquery-ui
Released under the MIT license
###
((root, factory) ->
### istanbul ignore next ###
switch
when typeof define is 'function' and define.amd
define ['underscore', 'backbone', 'backbone-forms', 'jquery-ui/widgets/autocomplete'], factory
when typeof exports is 'object'
require('jquery-ui/widgets/autocomplete')
factory require('underscore'), require('backbone'), require('backbone-forms')
else
factory root._, root.Backbone, root.Backbone.Form
return
) @, (_, Backbone, Form) ->
Form.editors['jqueryui.autocomplete'] = Form.editors.Text.extend
className: 'bbf-jui-autocomplete'
events:
change: 'determineChange'
focus: () ->
@trigger 'focus', @
return
blur: () ->
@trigger 'blur', @
return
autocompleteselect: () ->
setTimeout () =>
@determineChange()
return
, 0
return
initialize: (options) ->
Form.editors.Text::initialize.call @, options
@editorOptions = @schema.editorOptions or {}
@editorOptions.source = @schema.options or []
if @editorOptions.source instanceof Backbone.Collection
@editorOptions.source = @editorOptions.source.map (model) -> model.toString()
return
render: () ->
@$el.autocomplete @editorOptions
Form.editors.Text::render.call @
return
| 44656 | ###
Backbone-Forms jQuery UI autocomplete editor 1.0.0
Copyright (c) 2016 <NAME>
https://github.com/tomi77/backbone-forms-jquery-ui
Released under the MIT license
###
((root, factory) ->
### istanbul ignore next ###
switch
when typeof define is 'function' and define.amd
define ['underscore', 'backbone', 'backbone-forms', 'jquery-ui/widgets/autocomplete'], factory
when typeof exports is 'object'
require('jquery-ui/widgets/autocomplete')
factory require('underscore'), require('backbone'), require('backbone-forms')
else
factory root._, root.Backbone, root.Backbone.Form
return
) @, (_, Backbone, Form) ->
Form.editors['jqueryui.autocomplete'] = Form.editors.Text.extend
className: 'bbf-jui-autocomplete'
events:
change: 'determineChange'
focus: () ->
@trigger 'focus', @
return
blur: () ->
@trigger 'blur', @
return
autocompleteselect: () ->
setTimeout () =>
@determineChange()
return
, 0
return
initialize: (options) ->
Form.editors.Text::initialize.call @, options
@editorOptions = @schema.editorOptions or {}
@editorOptions.source = @schema.options or []
if @editorOptions.source instanceof Backbone.Collection
@editorOptions.source = @editorOptions.source.map (model) -> model.toString()
return
render: () ->
@$el.autocomplete @editorOptions
Form.editors.Text::render.call @
return
| true | ###
Backbone-Forms jQuery UI autocomplete editor 1.0.0
Copyright (c) 2016 PI:NAME:<NAME>END_PI
https://github.com/tomi77/backbone-forms-jquery-ui
Released under the MIT license
###
((root, factory) ->
### istanbul ignore next ###
switch
when typeof define is 'function' and define.amd
define ['underscore', 'backbone', 'backbone-forms', 'jquery-ui/widgets/autocomplete'], factory
when typeof exports is 'object'
require('jquery-ui/widgets/autocomplete')
factory require('underscore'), require('backbone'), require('backbone-forms')
else
factory root._, root.Backbone, root.Backbone.Form
return
) @, (_, Backbone, Form) ->
Form.editors['jqueryui.autocomplete'] = Form.editors.Text.extend
className: 'bbf-jui-autocomplete'
events:
change: 'determineChange'
focus: () ->
@trigger 'focus', @
return
blur: () ->
@trigger 'blur', @
return
autocompleteselect: () ->
setTimeout () =>
@determineChange()
return
, 0
return
initialize: (options) ->
Form.editors.Text::initialize.call @, options
@editorOptions = @schema.editorOptions or {}
@editorOptions.source = @schema.options or []
if @editorOptions.source instanceof Backbone.Collection
@editorOptions.source = @editorOptions.source.map (model) -> model.toString()
return
render: () ->
@$el.autocomplete @editorOptions
Form.editors.Text::render.call @
return
|
[
{
"context": ") ->\n user = new User(req.body)\n user.password = req.body.password\n\n user.save( (error) ->\n\n if er",
"end": 1512,
"score": 0.8469027280807495,
"start": 1509,
"tag": "PASSWORD",
"value": "req"
},
{
"context": "r = new User(req.body)\n user.password = req.bod... | server/controllers/mobileapi/mobileapi.coffee | gertu/gertu | 1 | _ = require 'underscore'
mongoose = require 'mongoose'
User = mongoose.model 'User'
Deal = mongoose.model 'Deal'
Token = mongoose.model 'Token'
Reservation = mongoose.model 'Reservation'
Shop = mongoose.model "Shop"
exports.usersLogin = (req, res) ->
User.findOne({email: req.body.email}).exec( (err, userData) ->
if err? or not userData?
res.status(403).send('Access denied. No such user.')
else
if userData.authenticate(req.body.password)
token = new Token()
token.token = Math.random() * 16
token.user = userData
token.last_access = new Date()
token.save( (err) ->
data = {
email : userData.email,
firstName : userData.firstName,
lastName : userData.lastName,
picture : userData.picture,
radius : userData.radius,
token : token._id,
}
res.status(200).send(JSON.stringify(data)) unless err?
res.status(403).send('Unable to set up token') if err?
)
else
res.status(403).send('Incorrect credentials')
)
exports.usersLogout = (req, res) ->
currentUser = req.currentMobileUser
currentToken = req.currentToken
Token.remove({_id: currentToken._id}).exec( (err) ->
res.status(200).send() unless err?
res.status(403).send('No token found') if err?
)
exports.usersSignUp = (req, res) ->
user = new User(req.body)
user.password = req.body.password
user.save( (error) ->
if error
if error.code is 11000 # email in use (duplicate)
res.status(409).send(JSON.stringify(error.code))
else
res.status(500).send(JSON.stringify(error.code))
else
token = new Token()
token.token = Math.random() * 16
token.user = user
token.last_access = new Date()
token.save( (err) ->
data = {
email : user.email,
firstName : user.firstName,
lastName : user.lastName,
radius : user.radius,
picture : user.picture,
token : token._id
}
res.status(200).send(JSON.stringify(data)) unless err?
res.status(403).send(err) if err?
)
)
exports.usersGetCurrent = (req, res) ->
currentUser = req.currentMobileUser
if currentUser?
data = {
email : currentUser.email,
firstName : currentUser.firstName,
lastName : currentUser.lastName,
radius : currentUser.radius,
picture : currentUser.picture
}
res.
status(200).
send(JSON.stringify(data))
else
res.
status(404).
send()
exports.usersUpdate = (req, res) ->
user = req.currentMobileUser
if user?
User.findOne({_id: user._id}).exec( (err, userData) ->
if err? or not userData?
res.status(403).send('Access denied')
else
userData.firstName = req.body.firstName
userData.lastName = req.body.lastName
userData.email = req.body.email
userData.save (err) ->
if err?
res.
status(500).
send(JSON.stringify(err))
else
req.session.user =
id: userData._id,
name: userData.name,
email: userData.email,
isAuthenticated: true
data = {
email : userData.email,
firstName : userData.firstName,
lastName : userData.lastName,
radius : userData.radius,
picture : userData.picture
}
res.
status(200).
send(JSON.stringify(data))
)
else
res.
status(404).
send()
exports.dealsGetAll = (req, res) ->
Deal.find().sort('-created').populate("shop").limit(10).exec (err, deals) ->
if err
res.status(500).send()
else
for deal in deals
deal.shop.billing_address = null
deal.shop.card = null
deal.shop.hashed_password = null
deal.shop.salt = null
res.status(200).send(JSON.stringify(deals))
exports.dealsGetAllByPositition = (req, res) ->
user = req.currentMobileUser
nearbyDeals = []
userradius = user.radius / 1000
mongoose.connection.db.executeDbCommand
# the mongo collection
geoNear: "shops"
# the geo point
near: [parseFloat(req.body.longitude), parseFloat(req.body.latitude)]
# tell mongo the earth is round, so it calculates based on a spherical location system
spherical: true
# tell mongo how many radians go into one kilometer.
distanceMultiplier: 6371
# tell mongo the max distance in radians to filter out
maxDistance: userradius / 6371
, (err, result) ->
nearshops = result.documents[0].results
nearshopids = []
if nearshops?
for shop in nearshops
nearshopids.push(shop.obj._id)
Deal.find({shop: { $in:nearshopids}}).exec (err,deals) ->
for deal in deals
for shop in nearshops
if deal.shop.equals(shop.obj._id)
nearbyDeals.push(
dist: shop.dis
deal: deal
)
nearbyDeals.sort (a, b) ->
a.dist - b.dist
res.status(200).send(JSON.stringify(nearbyDeals))
exports.dealsGetById = (req, res) ->
id = req.params.id
Deal.findOne({_id: id}).exec (err, deal) ->
if err? or not deal?
res.status(404).send()
else
deal.shop.billing_address = null
deal.shop.card = null
deal.shop.hashed_password = null
deal.shop.salt = null
res.status(200).send(JSON.stringify(deal))
exports.dealsMakeReservationById = (req, res) ->
user = req.currentMobileUser
dealId = req.params.id
Deal.findOne({_id: dealId}).exec( (err, deal) ->
if not error? and deal?
if deal.quantity <= 0
res.status(410).send('No more items allowed for this deal')
else
reservation = new Reservation()
reservation.deal = deal._id
reservation.user = user._id
reservation.save (err) ->
deal.quantity--
deal.save ((err) ->
res.status(200).send(JSON.stringify(reservation)) unless error?
res.status(500).send('Error updateing deal') if error?
)
else
res.status(404).send('Deal not found')
)
exports.dealsAddComment = (req, res) ->
user = req.currentMobileUser
dealId = req.params.id
if req.body.comment? and req.body.rating?
Deal.findOne({_id: dealId}).exec( (err, deal) ->
if deal?
if not deal.comments?
deal.comments = []
deal.comments.push({
author : user,
description : req.body.comment,
writedAt : new Date(),
rating : req.body.rating
})
deal.save()
res.status(200).send(deal)
else
res.status(404).send('Deal not found')
)
else
res.status(400).send('Comments and rating are compulsory')
exports.reservationsGetAll = (req, res) ->
user = req.currentMobileUser
Reservation.find({user: user}).populate('user').exec( (err, reservations) ->
res.status(200).send(JSON.stringify(reservations)) unless err?
res.status(404).send('Deal not found') if err?
)
exports.currentShopInfo = (req, res) ->
shopId = req.params.shopId
Shop.findOne({_id: shopId}).exec( (err, shopdata) ->
if err
res.status(500).send('Application error')
else
res.send JSON.stringify(shopdata.name)
) | 110242 | _ = require 'underscore'
mongoose = require 'mongoose'
User = mongoose.model 'User'
Deal = mongoose.model 'Deal'
Token = mongoose.model 'Token'
Reservation = mongoose.model 'Reservation'
Shop = mongoose.model "Shop"
exports.usersLogin = (req, res) ->
User.findOne({email: req.body.email}).exec( (err, userData) ->
if err? or not userData?
res.status(403).send('Access denied. No such user.')
else
if userData.authenticate(req.body.password)
token = new Token()
token.token = Math.random() * 16
token.user = userData
token.last_access = new Date()
token.save( (err) ->
data = {
email : userData.email,
firstName : userData.firstName,
lastName : userData.lastName,
picture : userData.picture,
radius : userData.radius,
token : token._id,
}
res.status(200).send(JSON.stringify(data)) unless err?
res.status(403).send('Unable to set up token') if err?
)
else
res.status(403).send('Incorrect credentials')
)
exports.usersLogout = (req, res) ->
currentUser = req.currentMobileUser
currentToken = req.currentToken
Token.remove({_id: currentToken._id}).exec( (err) ->
res.status(200).send() unless err?
res.status(403).send('No token found') if err?
)
exports.usersSignUp = (req, res) ->
user = new User(req.body)
user.password = <PASSWORD>.body.<PASSWORD>
user.save( (error) ->
if error
if error.code is 11000 # email in use (duplicate)
res.status(409).send(JSON.stringify(error.code))
else
res.status(500).send(JSON.stringify(error.code))
else
token = new Token()
token.token = Math.random() * 16
token.user = user
token.last_access = new Date()
token.save( (err) ->
data = {
email : user.email,
firstName : user.firstName,
lastName : user.lastName,
radius : user.radius,
picture : user.picture,
token : token._id
}
res.status(200).send(JSON.stringify(data)) unless err?
res.status(403).send(err) if err?
)
)
exports.usersGetCurrent = (req, res) ->
currentUser = req.currentMobileUser
if currentUser?
data = {
email : currentUser.email,
firstName : currentUser.firstName,
lastName : currentUser.lastName,
radius : currentUser.radius,
picture : currentUser.picture
}
res.
status(200).
send(JSON.stringify(data))
else
res.
status(404).
send()
exports.usersUpdate = (req, res) ->
user = req.currentMobileUser
if user?
User.findOne({_id: user._id}).exec( (err, userData) ->
if err? or not userData?
res.status(403).send('Access denied')
else
userData.firstName = req.body.firstName
userData.lastName = req.body.lastName
userData.email = req.body.email
userData.save (err) ->
if err?
res.
status(500).
send(JSON.stringify(err))
else
req.session.user =
id: userData._id,
name: userData.name,
email: userData.email,
isAuthenticated: true
data = {
email : userData.email,
firstName : userData.firstName,
lastName : userData.lastName,
radius : userData.radius,
picture : userData.picture
}
res.
status(200).
send(JSON.stringify(data))
)
else
res.
status(404).
send()
exports.dealsGetAll = (req, res) ->
Deal.find().sort('-created').populate("shop").limit(10).exec (err, deals) ->
if err
res.status(500).send()
else
for deal in deals
deal.shop.billing_address = null
deal.shop.card = null
deal.shop.hashed_password = null
deal.shop.salt = null
res.status(200).send(JSON.stringify(deals))
exports.dealsGetAllByPositition = (req, res) ->
user = req.currentMobileUser
nearbyDeals = []
userradius = user.radius / 1000
mongoose.connection.db.executeDbCommand
# the mongo collection
geoNear: "shops"
# the geo point
near: [parseFloat(req.body.longitude), parseFloat(req.body.latitude)]
# tell mongo the earth is round, so it calculates based on a spherical location system
spherical: true
# tell mongo how many radians go into one kilometer.
distanceMultiplier: 6371
# tell mongo the max distance in radians to filter out
maxDistance: userradius / 6371
, (err, result) ->
nearshops = result.documents[0].results
nearshopids = []
if nearshops?
for shop in nearshops
nearshopids.push(shop.obj._id)
Deal.find({shop: { $in:nearshopids}}).exec (err,deals) ->
for deal in deals
for shop in nearshops
if deal.shop.equals(shop.obj._id)
nearbyDeals.push(
dist: shop.dis
deal: deal
)
nearbyDeals.sort (a, b) ->
a.dist - b.dist
res.status(200).send(JSON.stringify(nearbyDeals))
exports.dealsGetById = (req, res) ->
id = req.params.id
Deal.findOne({_id: id}).exec (err, deal) ->
if err? or not deal?
res.status(404).send()
else
deal.shop.billing_address = null
deal.shop.card = null
deal.shop.hashed_password = <PASSWORD>
deal.shop.salt = null
res.status(200).send(JSON.stringify(deal))
exports.dealsMakeReservationById = (req, res) ->
user = req.currentMobileUser
dealId = req.params.id
Deal.findOne({_id: dealId}).exec( (err, deal) ->
if not error? and deal?
if deal.quantity <= 0
res.status(410).send('No more items allowed for this deal')
else
reservation = new Reservation()
reservation.deal = deal._id
reservation.user = user._id
reservation.save (err) ->
deal.quantity--
deal.save ((err) ->
res.status(200).send(JSON.stringify(reservation)) unless error?
res.status(500).send('Error updateing deal') if error?
)
else
res.status(404).send('Deal not found')
)
exports.dealsAddComment = (req, res) ->
user = req.currentMobileUser
dealId = req.params.id
if req.body.comment? and req.body.rating?
Deal.findOne({_id: dealId}).exec( (err, deal) ->
if deal?
if not deal.comments?
deal.comments = []
deal.comments.push({
author : user,
description : req.body.comment,
writedAt : new Date(),
rating : req.body.rating
})
deal.save()
res.status(200).send(deal)
else
res.status(404).send('Deal not found')
)
else
res.status(400).send('Comments and rating are compulsory')
exports.reservationsGetAll = (req, res) ->
user = req.currentMobileUser
Reservation.find({user: user}).populate('user').exec( (err, reservations) ->
res.status(200).send(JSON.stringify(reservations)) unless err?
res.status(404).send('Deal not found') if err?
)
exports.currentShopInfo = (req, res) ->
shopId = req.params.shopId
Shop.findOne({_id: shopId}).exec( (err, shopdata) ->
if err
res.status(500).send('Application error')
else
res.send JSON.stringify(shopdata.name)
) | true | _ = require 'underscore'
mongoose = require 'mongoose'
User = mongoose.model 'User'
Deal = mongoose.model 'Deal'
Token = mongoose.model 'Token'
Reservation = mongoose.model 'Reservation'
Shop = mongoose.model "Shop"
exports.usersLogin = (req, res) ->
User.findOne({email: req.body.email}).exec( (err, userData) ->
if err? or not userData?
res.status(403).send('Access denied. No such user.')
else
if userData.authenticate(req.body.password)
token = new Token()
token.token = Math.random() * 16
token.user = userData
token.last_access = new Date()
token.save( (err) ->
data = {
email : userData.email,
firstName : userData.firstName,
lastName : userData.lastName,
picture : userData.picture,
radius : userData.radius,
token : token._id,
}
res.status(200).send(JSON.stringify(data)) unless err?
res.status(403).send('Unable to set up token') if err?
)
else
res.status(403).send('Incorrect credentials')
)
exports.usersLogout = (req, res) ->
currentUser = req.currentMobileUser
currentToken = req.currentToken
Token.remove({_id: currentToken._id}).exec( (err) ->
res.status(200).send() unless err?
res.status(403).send('No token found') if err?
)
exports.usersSignUp = (req, res) ->
user = new User(req.body)
user.password = PI:PASSWORD:<PASSWORD>END_PI.body.PI:PASSWORD:<PASSWORD>END_PI
user.save( (error) ->
if error
if error.code is 11000 # email in use (duplicate)
res.status(409).send(JSON.stringify(error.code))
else
res.status(500).send(JSON.stringify(error.code))
else
token = new Token()
token.token = Math.random() * 16
token.user = user
token.last_access = new Date()
token.save( (err) ->
data = {
email : user.email,
firstName : user.firstName,
lastName : user.lastName,
radius : user.radius,
picture : user.picture,
token : token._id
}
res.status(200).send(JSON.stringify(data)) unless err?
res.status(403).send(err) if err?
)
)
exports.usersGetCurrent = (req, res) ->
currentUser = req.currentMobileUser
if currentUser?
data = {
email : currentUser.email,
firstName : currentUser.firstName,
lastName : currentUser.lastName,
radius : currentUser.radius,
picture : currentUser.picture
}
res.
status(200).
send(JSON.stringify(data))
else
res.
status(404).
send()
exports.usersUpdate = (req, res) ->
user = req.currentMobileUser
if user?
User.findOne({_id: user._id}).exec( (err, userData) ->
if err? or not userData?
res.status(403).send('Access denied')
else
userData.firstName = req.body.firstName
userData.lastName = req.body.lastName
userData.email = req.body.email
userData.save (err) ->
if err?
res.
status(500).
send(JSON.stringify(err))
else
req.session.user =
id: userData._id,
name: userData.name,
email: userData.email,
isAuthenticated: true
data = {
email : userData.email,
firstName : userData.firstName,
lastName : userData.lastName,
radius : userData.radius,
picture : userData.picture
}
res.
status(200).
send(JSON.stringify(data))
)
else
res.
status(404).
send()
exports.dealsGetAll = (req, res) ->
Deal.find().sort('-created').populate("shop").limit(10).exec (err, deals) ->
if err
res.status(500).send()
else
for deal in deals
deal.shop.billing_address = null
deal.shop.card = null
deal.shop.hashed_password = null
deal.shop.salt = null
res.status(200).send(JSON.stringify(deals))
exports.dealsGetAllByPositition = (req, res) ->
user = req.currentMobileUser
nearbyDeals = []
userradius = user.radius / 1000
mongoose.connection.db.executeDbCommand
# the mongo collection
geoNear: "shops"
# the geo point
near: [parseFloat(req.body.longitude), parseFloat(req.body.latitude)]
# tell mongo the earth is round, so it calculates based on a spherical location system
spherical: true
# tell mongo how many radians go into one kilometer.
distanceMultiplier: 6371
# tell mongo the max distance in radians to filter out
maxDistance: userradius / 6371
, (err, result) ->
nearshops = result.documents[0].results
nearshopids = []
if nearshops?
for shop in nearshops
nearshopids.push(shop.obj._id)
Deal.find({shop: { $in:nearshopids}}).exec (err,deals) ->
for deal in deals
for shop in nearshops
if deal.shop.equals(shop.obj._id)
nearbyDeals.push(
dist: shop.dis
deal: deal
)
nearbyDeals.sort (a, b) ->
a.dist - b.dist
res.status(200).send(JSON.stringify(nearbyDeals))
exports.dealsGetById = (req, res) ->
id = req.params.id
Deal.findOne({_id: id}).exec (err, deal) ->
if err? or not deal?
res.status(404).send()
else
deal.shop.billing_address = null
deal.shop.card = null
deal.shop.hashed_password = PI:PASSWORD:<PASSWORD>END_PI
deal.shop.salt = null
res.status(200).send(JSON.stringify(deal))
exports.dealsMakeReservationById = (req, res) ->
user = req.currentMobileUser
dealId = req.params.id
Deal.findOne({_id: dealId}).exec( (err, deal) ->
if not error? and deal?
if deal.quantity <= 0
res.status(410).send('No more items allowed for this deal')
else
reservation = new Reservation()
reservation.deal = deal._id
reservation.user = user._id
reservation.save (err) ->
deal.quantity--
deal.save ((err) ->
res.status(200).send(JSON.stringify(reservation)) unless error?
res.status(500).send('Error updateing deal') if error?
)
else
res.status(404).send('Deal not found')
)
exports.dealsAddComment = (req, res) ->
user = req.currentMobileUser
dealId = req.params.id
if req.body.comment? and req.body.rating?
Deal.findOne({_id: dealId}).exec( (err, deal) ->
if deal?
if not deal.comments?
deal.comments = []
deal.comments.push({
author : user,
description : req.body.comment,
writedAt : new Date(),
rating : req.body.rating
})
deal.save()
res.status(200).send(deal)
else
res.status(404).send('Deal not found')
)
else
res.status(400).send('Comments and rating are compulsory')
exports.reservationsGetAll = (req, res) ->
user = req.currentMobileUser
Reservation.find({user: user}).populate('user').exec( (err, reservations) ->
res.status(200).send(JSON.stringify(reservations)) unless err?
res.status(404).send('Deal not found') if err?
)
exports.currentShopInfo = (req, res) ->
shopId = req.params.shopId
Shop.findOne({_id: shopId}).exec( (err, shopdata) ->
if err
res.status(500).send('Application error')
else
res.send JSON.stringify(shopdata.name)
) |
[
{
"context": "123\"\n\t\t@project_id = \"project-id-123\"\n\t\t@token = 'some-token'\n\t\t@AuthenticationController =\n\t\t\tgetLoggedInUser",
"end": 423,
"score": 0.9429019093513489,
"start": 413,
"tag": "PASSWORD",
"value": "some-token"
},
{
"context": "oller =\n\t\t\tgetLoggedInUs... | test/unit/coffee/Authorization/AuthorizationMiddlewareTests.coffee | shyoshyo/web-sharelatex | 1 | sinon = require('sinon')
chai = require('chai')
should = chai.should()
expect = chai.expect
modulePath = "../../../../app/js/Features/Authorization/AuthorizationMiddleware.js"
SandboxedModule = require('sandboxed-module')
Errors = require "../../../../app/js/Features/Errors/Errors.js"
describe "AuthorizationMiddleware", ->
beforeEach ->
@user_id = "user-id-123"
@project_id = "project-id-123"
@token = 'some-token'
@AuthenticationController =
getLoggedInUserId: sinon.stub().returns(@user_id)
isUserLoggedIn: sinon.stub().returns(true)
@AuthorizationMiddleware = SandboxedModule.require modulePath, requires:
"./AuthorizationManager": @AuthorizationManager = {}
"logger-sharelatex": {log: () ->}
"mongojs": ObjectId: @ObjectId = {}
"../Errors/Errors": Errors
'../Authentication/AuthenticationController': @AuthenticationController
"../TokenAccess/TokenAccessHandler": @TokenAccessHandler =
getRequestToken: sinon.stub().returns(@token)
@req = {}
@res = {}
@ObjectId.isValid = sinon.stub()
@ObjectId.isValid.withArgs(@project_id).returns true
@next = sinon.stub()
describe "_getUserId", ->
beforeEach ->
@req = {}
it "should get the user from session", (done) ->
@AuthenticationController.getLoggedInUserId = sinon.stub().returns("1234")
@AuthorizationMiddleware._getUserId @req, (err, user_id) =>
expect(err).to.not.exist
expect(user_id).to.equal "1234"
done()
it "should get oauth_user from request", (done) ->
@AuthenticationController.getLoggedInUserId = sinon.stub().returns(null)
@req.oauth_user = {_id: "5678"}
@AuthorizationMiddleware._getUserId @req, (err, user_id) =>
expect(err).to.not.exist
expect(user_id).to.equal "5678"
done()
it "should fall back to null", (done) ->
@AuthenticationController.getLoggedInUserId = sinon.stub().returns(null)
@req.oauth_user = undefined
@AuthorizationMiddleware._getUserId @req, (err, user_id) =>
expect(err).to.not.exist
expect(user_id).to.equal null
done()
METHODS_TO_TEST = {
"ensureUserCanReadProject": "canUserReadProject"
"ensureUserCanWriteProjectSettings": "canUserWriteProjectSettings"
"ensureUserCanWriteProjectContent": "canUserWriteProjectContent"
"ensureUserCanAdminProject": "canUserAdminProject"
}
for middlewareMethod, managerMethod of METHODS_TO_TEST
do (middlewareMethod, managerMethod) ->
describe middlewareMethod, ->
beforeEach ->
@req.params =
project_id: @project_id
@AuthorizationManager[managerMethod] = sinon.stub()
@AuthorizationMiddleware.redirectToRestricted = sinon.stub()
describe "with missing project_id", ->
beforeEach ->
@req.params = {}
it "should return an error to next", ->
@AuthorizationMiddleware[middlewareMethod] @req, @res, @next
@next.calledWith(new Error()).should.equal true
describe "with logged in user", ->
beforeEach ->
@AuthenticationController.getLoggedInUserId.returns(@user_id)
describe "when user has permission", ->
beforeEach ->
@AuthorizationManager[managerMethod]
.withArgs(@user_id, @project_id, @token)
.yields(null, true)
it "should return next", ->
@AuthorizationMiddleware[middlewareMethod] @req, @res, @next
@next.called.should.equal true
describe "when user doesn't have permission", ->
beforeEach ->
@AuthorizationManager[managerMethod]
.withArgs(@user_id, @project_id, @token)
.yields(null, false)
it "should redirect to redirectToRestricted", ->
@AuthorizationMiddleware[middlewareMethod] @req, @res, @next
@next.called.should.equal false
@AuthorizationMiddleware.redirectToRestricted
.calledWith(@req, @res, @next)
.should.equal true
describe "with anonymous user", ->
describe "when user has permission", ->
beforeEach ->
@AuthenticationController.getLoggedInUserId.returns(null)
@AuthorizationManager[managerMethod]
.withArgs(null, @project_id, @token)
.yields(null, true)
it "should return next", ->
@AuthorizationMiddleware[middlewareMethod] @req, @res, @next
@next.called.should.equal true
describe "when user doesn't have permission", ->
beforeEach ->
@AuthenticationController.getLoggedInUserId.returns(null)
@AuthorizationManager[managerMethod]
.withArgs(null, @project_id, @token)
.yields(null, false)
it "should redirect to redirectToRestricted", ->
@AuthorizationMiddleware[middlewareMethod] @req, @res, @next
@next.called.should.equal false
@AuthorizationMiddleware.redirectToRestricted
.calledWith(@req, @res, @next)
.should.equal true
describe "with malformed project id", ->
beforeEach ->
@req.params =
project_id: "blah"
@ObjectId.isValid = sinon.stub().returns false
it "should return a not found error", (done) ->
@AuthorizationMiddleware[middlewareMethod] @req, @res, (error) ->
error.should.be.instanceof Errors.NotFoundError
done()
describe "ensureUserIsSiteAdmin", ->
beforeEach ->
@AuthorizationManager.isUserSiteAdmin = sinon.stub()
@AuthorizationMiddleware.redirectToRestricted = sinon.stub()
describe "with logged in user", ->
beforeEach ->
@AuthenticationController.getLoggedInUserId.returns(@user_id)
describe "when user has permission", ->
beforeEach ->
@AuthorizationManager.isUserSiteAdmin
.withArgs(@user_id)
.yields(null, true)
it "should return next", ->
@AuthorizationMiddleware.ensureUserIsSiteAdmin @req, @res, @next
@next.called.should.equal true
describe "when user doesn't have permission", ->
beforeEach ->
@AuthorizationManager.isUserSiteAdmin
.withArgs(@user_id)
.yields(null, false)
it "should redirect to redirectToRestricted", ->
@AuthorizationMiddleware.ensureUserIsSiteAdmin @req, @res, @next
@next.called.should.equal false
@AuthorizationMiddleware.redirectToRestricted
.calledWith(@req, @res, @next)
.should.equal true
describe "with anonymous user", ->
describe "when user has permission", ->
beforeEach ->
@AuthenticationController.getLoggedInUserId.returns(null)
@AuthorizationManager.isUserSiteAdmin
.withArgs(null)
.yields(null, true)
it "should return next", ->
@AuthorizationMiddleware.ensureUserIsSiteAdmin @req, @res, @next
@next.called.should.equal true
describe "when user doesn't have permission", ->
beforeEach ->
@AuthenticationController.getLoggedInUserId.returns(null)
@AuthorizationManager.isUserSiteAdmin
.withArgs(null)
.yields(null, false)
it "should redirect to redirectToRestricted", ->
@AuthorizationMiddleware.ensureUserIsSiteAdmin @req, @res, @next
@next.called.should.equal false
@AuthorizationMiddleware.redirectToRestricted
.calledWith(@req, @res, @next)
.should.equal true
describe "ensureUserCanReadMultipleProjects", ->
beforeEach ->
@AuthorizationManager.canUserReadProject = sinon.stub()
@AuthorizationMiddleware.redirectToRestricted = sinon.stub()
@req.query =
project_ids: "project1,project2"
describe "with logged in user", ->
beforeEach ->
@AuthenticationController.getLoggedInUserId.returns(@user_id)
describe "when user has permission to access all projects", ->
beforeEach ->
@AuthorizationManager.canUserReadProject
.withArgs(@user_id, "project1", @token)
.yields(null, true)
@AuthorizationManager.canUserReadProject
.withArgs(@user_id, "project2", @token)
.yields(null, true)
it "should return next", ->
@AuthorizationMiddleware.ensureUserCanReadMultipleProjects @req, @res, @next
@next.called.should.equal true
describe "when user doesn't have permission to access one of the projects", ->
beforeEach ->
@AuthorizationManager.canUserReadProject
.withArgs(@user_id, "project1", @token)
.yields(null, true)
@AuthorizationManager.canUserReadProject
.withArgs(@user_id, "project2", @token)
.yields(null, false)
it "should redirect to redirectToRestricted", ->
@AuthorizationMiddleware.ensureUserCanReadMultipleProjects @req, @res, @next
@next.called.should.equal false
@AuthorizationMiddleware.redirectToRestricted
.calledWith(@req, @res, @next)
.should.equal true
describe "with anonymous user", ->
describe "when user has permission", ->
describe "when user has permission to access all projects", ->
beforeEach ->
@AuthenticationController.getLoggedInUserId.returns(null)
@AuthorizationManager.canUserReadProject
.withArgs(null, "project1", @token)
.yields(null, true)
@AuthorizationManager.canUserReadProject
.withArgs(null, "project2", @token)
.yields(null, true)
it "should return next", ->
@AuthorizationMiddleware.ensureUserCanReadMultipleProjects @req, @res, @next
@next.called.should.equal true
describe "when user doesn't have permission to access one of the projects", ->
beforeEach ->
@AuthenticationController.getLoggedInUserId.returns(null)
@AuthorizationManager.canUserReadProject
.withArgs(null, "project1", @token)
.yields(null, true)
@AuthorizationManager.canUserReadProject
.withArgs(null, "project2", @token)
.yields(null, false)
it "should redirect to redirectToRestricted", ->
@AuthorizationMiddleware.ensureUserCanReadMultipleProjects @req, @res, @next
@next.called.should.equal false
@AuthorizationMiddleware.redirectToRestricted
.calledWith(@req, @res, @next)
.should.equal true
| 186570 | sinon = require('sinon')
chai = require('chai')
should = chai.should()
expect = chai.expect
modulePath = "../../../../app/js/Features/Authorization/AuthorizationMiddleware.js"
SandboxedModule = require('sandboxed-module')
Errors = require "../../../../app/js/Features/Errors/Errors.js"
describe "AuthorizationMiddleware", ->
beforeEach ->
@user_id = "user-id-123"
@project_id = "project-id-123"
@token = '<PASSWORD>'
@AuthenticationController =
getLoggedInUserId: sinon.stub().returns(@user_id)
isUserLoggedIn: sinon.stub().returns(true)
@AuthorizationMiddleware = SandboxedModule.require modulePath, requires:
"./AuthorizationManager": @AuthorizationManager = {}
"logger-sharelatex": {log: () ->}
"mongojs": ObjectId: @ObjectId = {}
"../Errors/Errors": Errors
'../Authentication/AuthenticationController': @AuthenticationController
"../TokenAccess/TokenAccessHandler": @TokenAccessHandler =
getRequestToken: sinon.stub().returns(@token)
@req = {}
@res = {}
@ObjectId.isValid = sinon.stub()
@ObjectId.isValid.withArgs(@project_id).returns true
@next = sinon.stub()
describe "_getUserId", ->
beforeEach ->
@req = {}
it "should get the user from session", (done) ->
@AuthenticationController.getLoggedInUserId = sinon.stub().returns("1234")
@AuthorizationMiddleware._getUserId @req, (err, user_id) =>
expect(err).to.not.exist
expect(user_id).to.equal "1234"
done()
it "should get oauth_user from request", (done) ->
@AuthenticationController.getLoggedInUserId = sinon.stub().returns(null)
@req.oauth_user = {_id: "5678"}
@AuthorizationMiddleware._getUserId @req, (err, user_id) =>
expect(err).to.not.exist
expect(user_id).to.equal "5678"
done()
it "should fall back to null", (done) ->
@AuthenticationController.getLoggedInUserId = sinon.stub().returns(null)
@req.oauth_user = undefined
@AuthorizationMiddleware._getUserId @req, (err, user_id) =>
expect(err).to.not.exist
expect(user_id).to.equal null
done()
METHODS_TO_TEST = {
"ensureUserCanReadProject": "canUserReadProject"
"ensureUserCanWriteProjectSettings": "canUserWriteProjectSettings"
"ensureUserCanWriteProjectContent": "canUserWriteProjectContent"
"ensureUserCanAdminProject": "canUserAdminProject"
}
for middlewareMethod, managerMethod of METHODS_TO_TEST
do (middlewareMethod, managerMethod) ->
describe middlewareMethod, ->
beforeEach ->
@req.params =
project_id: @project_id
@AuthorizationManager[managerMethod] = sinon.stub()
@AuthorizationMiddleware.redirectToRestricted = sinon.stub()
describe "with missing project_id", ->
beforeEach ->
@req.params = {}
it "should return an error to next", ->
@AuthorizationMiddleware[middlewareMethod] @req, @res, @next
@next.calledWith(new Error()).should.equal true
describe "with logged in user", ->
beforeEach ->
@AuthenticationController.getLoggedInUserId.returns(@user_id)
describe "when user has permission", ->
beforeEach ->
@AuthorizationManager[managerMethod]
.withArgs(@user_id, @project_id, @token)
.yields(null, true)
it "should return next", ->
@AuthorizationMiddleware[middlewareMethod] @req, @res, @next
@next.called.should.equal true
describe "when user doesn't have permission", ->
beforeEach ->
@AuthorizationManager[managerMethod]
.withArgs(@user_id, @project_id, @token)
.yields(null, false)
it "should redirect to redirectToRestricted", ->
@AuthorizationMiddleware[middlewareMethod] @req, @res, @next
@next.called.should.equal false
@AuthorizationMiddleware.redirectToRestricted
.calledWith(@req, @res, @next)
.should.equal true
describe "with anonymous user", ->
describe "when user has permission", ->
beforeEach ->
@AuthenticationController.getLoggedInUserId.returns(null)
@AuthorizationManager[managerMethod]
.withArgs(null, @project_id, @token)
.yields(null, true)
it "should return next", ->
@AuthorizationMiddleware[middlewareMethod] @req, @res, @next
@next.called.should.equal true
describe "when user doesn't have permission", ->
beforeEach ->
@AuthenticationController.getLoggedInUserId.returns(null)
@AuthorizationManager[managerMethod]
.withArgs(null, @project_id, @token)
.yields(null, false)
it "should redirect to redirectToRestricted", ->
@AuthorizationMiddleware[middlewareMethod] @req, @res, @next
@next.called.should.equal false
@AuthorizationMiddleware.redirectToRestricted
.calledWith(@req, @res, @next)
.should.equal true
describe "with malformed project id", ->
beforeEach ->
@req.params =
project_id: "blah"
@ObjectId.isValid = sinon.stub().returns false
it "should return a not found error", (done) ->
@AuthorizationMiddleware[middlewareMethod] @req, @res, (error) ->
error.should.be.instanceof Errors.NotFoundError
done()
describe "ensureUserIsSiteAdmin", ->
beforeEach ->
@AuthorizationManager.isUserSiteAdmin = sinon.stub()
@AuthorizationMiddleware.redirectToRestricted = sinon.stub()
describe "with logged in user", ->
beforeEach ->
@AuthenticationController.getLoggedInUserId.returns(@user_id)
describe "when user has permission", ->
beforeEach ->
@AuthorizationManager.isUserSiteAdmin
.withArgs(@user_id)
.yields(null, true)
it "should return next", ->
@AuthorizationMiddleware.ensureUserIsSiteAdmin @req, @res, @next
@next.called.should.equal true
describe "when user doesn't have permission", ->
beforeEach ->
@AuthorizationManager.isUserSiteAdmin
.withArgs(@user_id)
.yields(null, false)
it "should redirect to redirectToRestricted", ->
@AuthorizationMiddleware.ensureUserIsSiteAdmin @req, @res, @next
@next.called.should.equal false
@AuthorizationMiddleware.redirectToRestricted
.calledWith(@req, @res, @next)
.should.equal true
describe "with anonymous user", ->
describe "when user has permission", ->
beforeEach ->
@AuthenticationController.getLoggedInUserId.returns(null)
@AuthorizationManager.isUserSiteAdmin
.withArgs(null)
.yields(null, true)
it "should return next", ->
@AuthorizationMiddleware.ensureUserIsSiteAdmin @req, @res, @next
@next.called.should.equal true
describe "when user doesn't have permission", ->
beforeEach ->
@AuthenticationController.getLoggedInUserId.returns(null)
@AuthorizationManager.isUserSiteAdmin
.withArgs(null)
.yields(null, false)
it "should redirect to redirectToRestricted", ->
@AuthorizationMiddleware.ensureUserIsSiteAdmin @req, @res, @next
@next.called.should.equal false
@AuthorizationMiddleware.redirectToRestricted
.calledWith(@req, @res, @next)
.should.equal true
describe "ensureUserCanReadMultipleProjects", ->
beforeEach ->
@AuthorizationManager.canUserReadProject = sinon.stub()
@AuthorizationMiddleware.redirectToRestricted = sinon.stub()
@req.query =
project_ids: "project1,project2"
describe "with logged in user", ->
beforeEach ->
@AuthenticationController.getLoggedInUserId.returns(@user_id)
describe "when user has permission to access all projects", ->
beforeEach ->
@AuthorizationManager.canUserReadProject
.withArgs(@user_id, "project1", @token)
.yields(null, true)
@AuthorizationManager.canUserReadProject
.withArgs(@user_id, "project2", @token)
.yields(null, true)
it "should return next", ->
@AuthorizationMiddleware.ensureUserCanReadMultipleProjects @req, @res, @next
@next.called.should.equal true
describe "when user doesn't have permission to access one of the projects", ->
beforeEach ->
@AuthorizationManager.canUserReadProject
.withArgs(@user_id, "project1", @token)
.yields(null, true)
@AuthorizationManager.canUserReadProject
.withArgs(@user_id, "project2", @token)
.yields(null, false)
it "should redirect to redirectToRestricted", ->
@AuthorizationMiddleware.ensureUserCanReadMultipleProjects @req, @res, @next
@next.called.should.equal false
@AuthorizationMiddleware.redirectToRestricted
.calledWith(@req, @res, @next)
.should.equal true
describe "with anonymous user", ->
describe "when user has permission", ->
describe "when user has permission to access all projects", ->
beforeEach ->
@AuthenticationController.getLoggedInUserId.returns(null)
@AuthorizationManager.canUserReadProject
.withArgs(null, "project1", @token)
.yields(null, true)
@AuthorizationManager.canUserReadProject
.withArgs(null, "project2", @token)
.yields(null, true)
it "should return next", ->
@AuthorizationMiddleware.ensureUserCanReadMultipleProjects @req, @res, @next
@next.called.should.equal true
describe "when user doesn't have permission to access one of the projects", ->
beforeEach ->
@AuthenticationController.getLoggedInUserId.returns(null)
@AuthorizationManager.canUserReadProject
.withArgs(null, "project1", @token)
.yields(null, true)
@AuthorizationManager.canUserReadProject
.withArgs(null, "project2", @token)
.yields(null, false)
it "should redirect to redirectToRestricted", ->
@AuthorizationMiddleware.ensureUserCanReadMultipleProjects @req, @res, @next
@next.called.should.equal false
@AuthorizationMiddleware.redirectToRestricted
.calledWith(@req, @res, @next)
.should.equal true
| true | sinon = require('sinon')
chai = require('chai')
should = chai.should()
expect = chai.expect
modulePath = "../../../../app/js/Features/Authorization/AuthorizationMiddleware.js"
SandboxedModule = require('sandboxed-module')
Errors = require "../../../../app/js/Features/Errors/Errors.js"
describe "AuthorizationMiddleware", ->
beforeEach ->
@user_id = "user-id-123"
@project_id = "project-id-123"
@token = 'PI:PASSWORD:<PASSWORD>END_PI'
@AuthenticationController =
getLoggedInUserId: sinon.stub().returns(@user_id)
isUserLoggedIn: sinon.stub().returns(true)
@AuthorizationMiddleware = SandboxedModule.require modulePath, requires:
"./AuthorizationManager": @AuthorizationManager = {}
"logger-sharelatex": {log: () ->}
"mongojs": ObjectId: @ObjectId = {}
"../Errors/Errors": Errors
'../Authentication/AuthenticationController': @AuthenticationController
"../TokenAccess/TokenAccessHandler": @TokenAccessHandler =
getRequestToken: sinon.stub().returns(@token)
@req = {}
@res = {}
@ObjectId.isValid = sinon.stub()
@ObjectId.isValid.withArgs(@project_id).returns true
@next = sinon.stub()
describe "_getUserId", ->
beforeEach ->
@req = {}
it "should get the user from session", (done) ->
@AuthenticationController.getLoggedInUserId = sinon.stub().returns("1234")
@AuthorizationMiddleware._getUserId @req, (err, user_id) =>
expect(err).to.not.exist
expect(user_id).to.equal "1234"
done()
it "should get oauth_user from request", (done) ->
@AuthenticationController.getLoggedInUserId = sinon.stub().returns(null)
@req.oauth_user = {_id: "5678"}
@AuthorizationMiddleware._getUserId @req, (err, user_id) =>
expect(err).to.not.exist
expect(user_id).to.equal "5678"
done()
it "should fall back to null", (done) ->
@AuthenticationController.getLoggedInUserId = sinon.stub().returns(null)
@req.oauth_user = undefined
@AuthorizationMiddleware._getUserId @req, (err, user_id) =>
expect(err).to.not.exist
expect(user_id).to.equal null
done()
METHODS_TO_TEST = {
"ensureUserCanReadProject": "canUserReadProject"
"ensureUserCanWriteProjectSettings": "canUserWriteProjectSettings"
"ensureUserCanWriteProjectContent": "canUserWriteProjectContent"
"ensureUserCanAdminProject": "canUserAdminProject"
}
for middlewareMethod, managerMethod of METHODS_TO_TEST
do (middlewareMethod, managerMethod) ->
describe middlewareMethod, ->
beforeEach ->
@req.params =
project_id: @project_id
@AuthorizationManager[managerMethod] = sinon.stub()
@AuthorizationMiddleware.redirectToRestricted = sinon.stub()
describe "with missing project_id", ->
beforeEach ->
@req.params = {}
it "should return an error to next", ->
@AuthorizationMiddleware[middlewareMethod] @req, @res, @next
@next.calledWith(new Error()).should.equal true
describe "with logged in user", ->
beforeEach ->
@AuthenticationController.getLoggedInUserId.returns(@user_id)
describe "when user has permission", ->
beforeEach ->
@AuthorizationManager[managerMethod]
.withArgs(@user_id, @project_id, @token)
.yields(null, true)
it "should return next", ->
@AuthorizationMiddleware[middlewareMethod] @req, @res, @next
@next.called.should.equal true
describe "when user doesn't have permission", ->
beforeEach ->
@AuthorizationManager[managerMethod]
.withArgs(@user_id, @project_id, @token)
.yields(null, false)
it "should redirect to redirectToRestricted", ->
@AuthorizationMiddleware[middlewareMethod] @req, @res, @next
@next.called.should.equal false
@AuthorizationMiddleware.redirectToRestricted
.calledWith(@req, @res, @next)
.should.equal true
describe "with anonymous user", ->
describe "when user has permission", ->
beforeEach ->
@AuthenticationController.getLoggedInUserId.returns(null)
@AuthorizationManager[managerMethod]
.withArgs(null, @project_id, @token)
.yields(null, true)
it "should return next", ->
@AuthorizationMiddleware[middlewareMethod] @req, @res, @next
@next.called.should.equal true
describe "when user doesn't have permission", ->
beforeEach ->
@AuthenticationController.getLoggedInUserId.returns(null)
@AuthorizationManager[managerMethod]
.withArgs(null, @project_id, @token)
.yields(null, false)
it "should redirect to redirectToRestricted", ->
@AuthorizationMiddleware[middlewareMethod] @req, @res, @next
@next.called.should.equal false
@AuthorizationMiddleware.redirectToRestricted
.calledWith(@req, @res, @next)
.should.equal true
describe "with malformed project id", ->
beforeEach ->
@req.params =
project_id: "blah"
@ObjectId.isValid = sinon.stub().returns false
it "should return a not found error", (done) ->
@AuthorizationMiddleware[middlewareMethod] @req, @res, (error) ->
error.should.be.instanceof Errors.NotFoundError
done()
describe "ensureUserIsSiteAdmin", ->
beforeEach ->
@AuthorizationManager.isUserSiteAdmin = sinon.stub()
@AuthorizationMiddleware.redirectToRestricted = sinon.stub()
describe "with logged in user", ->
beforeEach ->
@AuthenticationController.getLoggedInUserId.returns(@user_id)
describe "when user has permission", ->
beforeEach ->
@AuthorizationManager.isUserSiteAdmin
.withArgs(@user_id)
.yields(null, true)
it "should return next", ->
@AuthorizationMiddleware.ensureUserIsSiteAdmin @req, @res, @next
@next.called.should.equal true
describe "when user doesn't have permission", ->
beforeEach ->
@AuthorizationManager.isUserSiteAdmin
.withArgs(@user_id)
.yields(null, false)
it "should redirect to redirectToRestricted", ->
@AuthorizationMiddleware.ensureUserIsSiteAdmin @req, @res, @next
@next.called.should.equal false
@AuthorizationMiddleware.redirectToRestricted
.calledWith(@req, @res, @next)
.should.equal true
describe "with anonymous user", ->
describe "when user has permission", ->
beforeEach ->
@AuthenticationController.getLoggedInUserId.returns(null)
@AuthorizationManager.isUserSiteAdmin
.withArgs(null)
.yields(null, true)
it "should return next", ->
@AuthorizationMiddleware.ensureUserIsSiteAdmin @req, @res, @next
@next.called.should.equal true
describe "when user doesn't have permission", ->
beforeEach ->
@AuthenticationController.getLoggedInUserId.returns(null)
@AuthorizationManager.isUserSiteAdmin
.withArgs(null)
.yields(null, false)
it "should redirect to redirectToRestricted", ->
@AuthorizationMiddleware.ensureUserIsSiteAdmin @req, @res, @next
@next.called.should.equal false
@AuthorizationMiddleware.redirectToRestricted
.calledWith(@req, @res, @next)
.should.equal true
describe "ensureUserCanReadMultipleProjects", ->
beforeEach ->
@AuthorizationManager.canUserReadProject = sinon.stub()
@AuthorizationMiddleware.redirectToRestricted = sinon.stub()
@req.query =
project_ids: "project1,project2"
describe "with logged in user", ->
beforeEach ->
@AuthenticationController.getLoggedInUserId.returns(@user_id)
describe "when user has permission to access all projects", ->
beforeEach ->
@AuthorizationManager.canUserReadProject
.withArgs(@user_id, "project1", @token)
.yields(null, true)
@AuthorizationManager.canUserReadProject
.withArgs(@user_id, "project2", @token)
.yields(null, true)
it "should return next", ->
@AuthorizationMiddleware.ensureUserCanReadMultipleProjects @req, @res, @next
@next.called.should.equal true
describe "when user doesn't have permission to access one of the projects", ->
beforeEach ->
@AuthorizationManager.canUserReadProject
.withArgs(@user_id, "project1", @token)
.yields(null, true)
@AuthorizationManager.canUserReadProject
.withArgs(@user_id, "project2", @token)
.yields(null, false)
it "should redirect to redirectToRestricted", ->
@AuthorizationMiddleware.ensureUserCanReadMultipleProjects @req, @res, @next
@next.called.should.equal false
@AuthorizationMiddleware.redirectToRestricted
.calledWith(@req, @res, @next)
.should.equal true
describe "with anonymous user", ->
describe "when user has permission", ->
describe "when user has permission to access all projects", ->
beforeEach ->
@AuthenticationController.getLoggedInUserId.returns(null)
@AuthorizationManager.canUserReadProject
.withArgs(null, "project1", @token)
.yields(null, true)
@AuthorizationManager.canUserReadProject
.withArgs(null, "project2", @token)
.yields(null, true)
it "should return next", ->
@AuthorizationMiddleware.ensureUserCanReadMultipleProjects @req, @res, @next
@next.called.should.equal true
describe "when user doesn't have permission to access one of the projects", ->
beforeEach ->
@AuthenticationController.getLoggedInUserId.returns(null)
@AuthorizationManager.canUserReadProject
.withArgs(null, "project1", @token)
.yields(null, true)
@AuthorizationManager.canUserReadProject
.withArgs(null, "project2", @token)
.yields(null, false)
it "should redirect to redirectToRestricted", ->
@AuthorizationMiddleware.ensureUserCanReadMultipleProjects @req, @res, @next
@next.called.should.equal false
@AuthorizationMiddleware.redirectToRestricted
.calledWith(@req, @res, @next)
.should.equal true
|
[
{
"context": " --- Contains the base class of a *MODE*\n# Author: Zenathark\n# Mantainer: Zenathark\n#\n# Version 0.0.1\n# Date 2",
"end": 74,
"score": 0.9186640977859497,
"start": 65,
"tag": "NAME",
"value": "Zenathark"
},
{
"context": "class of a *MODE*\n# Author: Zenathark\n# Mant... | lib/mode.coffee | zenathark/wicked-mode | 0 | # state.coffee --- Contains the base class of a *MODE*
# Author: Zenathark
# Mantainer: Zenathark
#
# Version 0.0.1
# Date 2015-11-19
#
# As with vim and emacs, wicked-mode defines *modes* of operation for
# the atom editor. Each mode has its own properies and behavior.
# Also, keybindings must be defined for each mode.
_ = require 'underscore-plus'
name = 'wicked:mode'
log = require('./logger') name
assert = require('chai').assert
# localStorage.debug = '*'
# debug = require('debug')
# debug.disable('test')
# log = debug('test')
# log.log = console.error.bind(console)
module.exports =
# Base class for modes
#
# This is the base class for all modes of wicked-mode. This class is
# heavily inspired on the evil-define-macro of evil-mode for emacs.
#
# Properties:
# * `tag` Mode status line indicator
# * `message` Echo message when changing to mode
# * `cursor` Type of cursor for mode
# * `entry_hook` Functions to run when activating mode
# * `exit_hook` Functions to run when deactivating mode
# * `enable` Modes to enable when mode is enable
#
# Methods:
# * `activateMode` Activate this mode
# * `deactivateMode` Deactivate this mode
# * `activate` If presents, the method is invoked when activating
# mode
# * `deactivate` If presents, the method is invoked when
# deactivating mode
# * `addEntryHook` Adds a function to the entry hooks
# * `addExitHook` Adds a function to the exit hooks
# * `addAllEntryHooks` Adds a list of functions to the entry hook
# * `addAllExitHooks` Adds a list of functions to the exit hook
# * `addEnable` Adds a mode to enable
# * `addAllEnable` Adds a list of modes to enable
#
#
# When mode is activate through `activateMode`, all functions in
# entry-hook are invoked. Also, each mode listed in `enable` is also
# activated in order.
# Because each mode in `enable` is activated before this mode, any
# changes made by the extra mode in `enable` can be potentially overwrited
# by this mode.
# When mode is deactivate through `deactivateMode`, all functions in
# exit-hook are invoked and all modes in `enable` are deactivated in
# order.
class Mode
tag: null
message: null
cursor: null
entry_hook: null
exit_hook: null
enable: null
selector: null
constructor: (@selector, @tag='', @message='', @cursor='.block') ->
@entry_hook = new Set
@exit_hook = new Set
@enable = new Set
activateMode: (editor) ->
log "Activate called"
assert.ok(editor, 'editor is empty')
editor_view = atom.views.getView editor
editor_view.classList.add @selector
@activate editor if @activate?
@entry_hook.forEach (hook) => hook.call this
@enable.forEach (extra) -> extra.activateMode editor
deactivateMode: (editor) ->
log "Activate called"
assert.ok(editor, 'editor is empty')
editor_view = atom.views.getView(editor)
editor_view.classList.remove @selector
@deactivate editor if @deactivate?
@exit_hook.forEach (hook) => hook.call this
@enable.forEach (extra) -> extra.deactivateMode editor
addEntryHook: (f) ->
log "Added entry hook #{f}"
@entry_hook.add f
addExitHook: (f) ->
log "Added exit hook #{f}"
@exit_hook.add f
addAllEntryHooks: (fs) ->
log " Added multiple entry hooks #{fs}"
fs.forEach (i) => @addEntryHook i
addAllExitHooks: (fs) ->
log "Added multiple exit hooks #{fs}"
fs.forEach (i) => @addExitHook i
addEnable: (f) ->
log "Added mode #{f} to extra enable modes"
@enable.add f
| 102062 | # state.coffee --- Contains the base class of a *MODE*
# Author: <NAME>
# Mantainer: <NAME>
#
# Version 0.0.1
# Date 2015-11-19
#
# As with vim and emacs, wicked-mode defines *modes* of operation for
# the atom editor. Each mode has its own properies and behavior.
# Also, keybindings must be defined for each mode.
_ = require 'underscore-plus'
name = 'wicked:mode'
log = require('./logger') name
assert = require('chai').assert
# localStorage.debug = '*'
# debug = require('debug')
# debug.disable('test')
# log = debug('test')
# log.log = console.error.bind(console)
module.exports =
# Base class for modes
#
# This is the base class for all modes of wicked-mode. This class is
# heavily inspired on the evil-define-macro of evil-mode for emacs.
#
# Properties:
# * `tag` Mode status line indicator
# * `message` Echo message when changing to mode
# * `cursor` Type of cursor for mode
# * `entry_hook` Functions to run when activating mode
# * `exit_hook` Functions to run when deactivating mode
# * `enable` Modes to enable when mode is enable
#
# Methods:
# * `activateMode` Activate this mode
# * `deactivateMode` Deactivate this mode
# * `activate` If presents, the method is invoked when activating
# mode
# * `deactivate` If presents, the method is invoked when
# deactivating mode
# * `addEntryHook` Adds a function to the entry hooks
# * `addExitHook` Adds a function to the exit hooks
# * `addAllEntryHooks` Adds a list of functions to the entry hook
# * `addAllExitHooks` Adds a list of functions to the exit hook
# * `addEnable` Adds a mode to enable
# * `addAllEnable` Adds a list of modes to enable
#
#
# When mode is activate through `activateMode`, all functions in
# entry-hook are invoked. Also, each mode listed in `enable` is also
# activated in order.
# Because each mode in `enable` is activated before this mode, any
# changes made by the extra mode in `enable` can be potentially overwrited
# by this mode.
# When mode is deactivate through `deactivateMode`, all functions in
# exit-hook are invoked and all modes in `enable` are deactivated in
# order.
class Mode
tag: null
message: null
cursor: null
entry_hook: null
exit_hook: null
enable: null
selector: null
constructor: (@selector, @tag='', @message='', @cursor='.block') ->
@entry_hook = new Set
@exit_hook = new Set
@enable = new Set
activateMode: (editor) ->
log "Activate called"
assert.ok(editor, 'editor is empty')
editor_view = atom.views.getView editor
editor_view.classList.add @selector
@activate editor if @activate?
@entry_hook.forEach (hook) => hook.call this
@enable.forEach (extra) -> extra.activateMode editor
deactivateMode: (editor) ->
log "Activate called"
assert.ok(editor, 'editor is empty')
editor_view = atom.views.getView(editor)
editor_view.classList.remove @selector
@deactivate editor if @deactivate?
@exit_hook.forEach (hook) => hook.call this
@enable.forEach (extra) -> extra.deactivateMode editor
addEntryHook: (f) ->
log "Added entry hook #{f}"
@entry_hook.add f
addExitHook: (f) ->
log "Added exit hook #{f}"
@exit_hook.add f
addAllEntryHooks: (fs) ->
log " Added multiple entry hooks #{fs}"
fs.forEach (i) => @addEntryHook i
addAllExitHooks: (fs) ->
log "Added multiple exit hooks #{fs}"
fs.forEach (i) => @addExitHook i
addEnable: (f) ->
log "Added mode #{f} to extra enable modes"
@enable.add f
| true | # state.coffee --- Contains the base class of a *MODE*
# Author: PI:NAME:<NAME>END_PI
# Mantainer: PI:NAME:<NAME>END_PI
#
# Version 0.0.1
# Date 2015-11-19
#
# As with vim and emacs, wicked-mode defines *modes* of operation for
# the atom editor. Each mode has its own properies and behavior.
# Also, keybindings must be defined for each mode.
_ = require 'underscore-plus'
name = 'wicked:mode'
log = require('./logger') name
assert = require('chai').assert
# localStorage.debug = '*'
# debug = require('debug')
# debug.disable('test')
# log = debug('test')
# log.log = console.error.bind(console)
module.exports =
# Base class for modes
#
# This is the base class for all modes of wicked-mode. This class is
# heavily inspired on the evil-define-macro of evil-mode for emacs.
#
# Properties:
# * `tag` Mode status line indicator
# * `message` Echo message when changing to mode
# * `cursor` Type of cursor for mode
# * `entry_hook` Functions to run when activating mode
# * `exit_hook` Functions to run when deactivating mode
# * `enable` Modes to enable when mode is enable
#
# Methods:
# * `activateMode` Activate this mode
# * `deactivateMode` Deactivate this mode
# * `activate` If presents, the method is invoked when activating
# mode
# * `deactivate` If presents, the method is invoked when
# deactivating mode
# * `addEntryHook` Adds a function to the entry hooks
# * `addExitHook` Adds a function to the exit hooks
# * `addAllEntryHooks` Adds a list of functions to the entry hook
# * `addAllExitHooks` Adds a list of functions to the exit hook
# * `addEnable` Adds a mode to enable
# * `addAllEnable` Adds a list of modes to enable
#
#
# When mode is activate through `activateMode`, all functions in
# entry-hook are invoked. Also, each mode listed in `enable` is also
# activated in order.
# Because each mode in `enable` is activated before this mode, any
# changes made by the extra mode in `enable` can be potentially overwrited
# by this mode.
# When mode is deactivate through `deactivateMode`, all functions in
# exit-hook are invoked and all modes in `enable` are deactivated in
# order.
class Mode
tag: null
message: null
cursor: null
entry_hook: null
exit_hook: null
enable: null
selector: null
constructor: (@selector, @tag='', @message='', @cursor='.block') ->
@entry_hook = new Set
@exit_hook = new Set
@enable = new Set
activateMode: (editor) ->
log "Activate called"
assert.ok(editor, 'editor is empty')
editor_view = atom.views.getView editor
editor_view.classList.add @selector
@activate editor if @activate?
@entry_hook.forEach (hook) => hook.call this
@enable.forEach (extra) -> extra.activateMode editor
deactivateMode: (editor) ->
log "Activate called"
assert.ok(editor, 'editor is empty')
editor_view = atom.views.getView(editor)
editor_view.classList.remove @selector
@deactivate editor if @deactivate?
@exit_hook.forEach (hook) => hook.call this
@enable.forEach (extra) -> extra.deactivateMode editor
addEntryHook: (f) ->
log "Added entry hook #{f}"
@entry_hook.add f
addExitHook: (f) ->
log "Added exit hook #{f}"
@exit_hook.add f
addAllEntryHooks: (fs) ->
log " Added multiple entry hooks #{fs}"
fs.forEach (i) => @addEntryHook i
addAllExitHooks: (fs) ->
log "Added multiple exit hooks #{fs}"
fs.forEach (i) => @addExitHook i
addEnable: (f) ->
log "Added mode #{f} to extra enable modes"
@enable.add f
|
[
{
"context": "## Copyright (c) 2011, Chris Umbel\n##\n## Permission is hereby granted, free of charg",
"end": 34,
"score": 0.9998074769973755,
"start": 23,
"tag": "NAME",
"value": "Chris Umbel"
},
{
"context": "## THE SOFTWARE.\n##\n## Significant changes made by Stuart Watt, includi... | src/wordnet.coffee | brave/wordnet | 3 | ## Copyright (c) 2011, Chris Umbel
##
## 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.
##
## Significant changes made by Stuart Watt, including:
## (1) - implementation of logic for morphological exceptions
## (2) - using sense offsets as per Perl implementations
## (3) - porting to CoffeeScript for easier validation and better array performance
## (4) - promisification of much of the API
## (5) - move to use wndb-with-exceptions instead of WNdb, to provide morphological exceptions
## (6) - significant improvements in testing
IndexFile = require './index_file'
DataFile = require './data_file'
async = require 'async'
Promise = require 'bluebird'
path = require 'path'
fs = require 'fs'
LRU = require 'lru-cache'
require('es6-shim')
class WordNet
constructor: (options) ->
## For compatibility, if the options are a string, it's just the Wordnet path
if typeof options == 'string'
options = {dataDir: options}
else
options ?= {}
if ! options.dataDir?
try
WNdb = require('wndb-with-exceptions')
catch e
console.error("Please 'npm install wndb-with-exceptions' before using WordNet module or specify a dict directory.")
throw e
options.dataDir = WNdb.path
if ! options.cache
@cache = null
else
if options.cache == true
options.cache = {
max: 2000
}
if typeof options.cache == 'object' and typeof options.cache.get == 'function'
@cache = options.cache
else
@cache = LRU options.cache
@path = options.dataDir
@nounIndex = new IndexFile(@path, 'noun')
@verbIndex = new IndexFile(@path, 'verb')
@adjIndex = new IndexFile(@path, 'adj')
@advIndex = new IndexFile(@path, 'adv')
@nounData = new DataFile(@path, 'noun')
@verbData = new DataFile(@path, 'verb')
@adjData = new DataFile(@path, 'adj')
@advData = new DataFile(@path, 'adv')
@allFiles = [
{index: @nounIndex, data: @nounData, pos: 'n'}
{index: @verbIndex, data: @verbData, pos: 'v'}
{index: @adjIndex, data: @adjData, pos: 'a'}
{index: @advIndex, data: @advData, pos: 'r'}
]
get: (synsetOffset, pos, callback) ->
wordnet = @
if @cache
query = "get:#{synsetOffset}:#{pos}"
if hit = wordnet.cache.get query
if callback.length == 1
return callback.call wordnet, hit
else
return callback.call wordnet, null, hit
dataFile = wordnet.getDataFile(pos)
dataFile.get synsetOffset, (err, result) ->
wordnet.cache.set query, result if query && !err?
if callback.length == 1
callback.call wordnet, result
else
callback.call wordnet, err, result
getAsync: (synsetOffset, pos) ->
wordnet = @
new Promise (resolve, reject) ->
wordnet.get synsetOffset, pos, (err, data) ->
if err?
reject err
else
resolve data
lookup: (input, callback) ->
wordnet = @
[word, pos] = input.split('#')
lword = word.toLowerCase().replace(/\s+/g, '_')
if @cache
query = "lookup:#{input}"
if hit = wordnet.cache.get query
if callback.length == 1
return callback.call wordnet, hit
else
return callback.call wordnet, null, hit
selectedFiles = if ! pos then wordnet.allFiles else wordnet.allFiles.filter (file) -> file.pos == pos
wordnet.lookupFromFiles selectedFiles, [], lword, (err, results) ->
return callback.call wordnet, err if err?
wordnet.cache.set query, results if query
if callback.length == 1
return callback.call wordnet, results
else
return callback.call wordnet, null, results
lookupAsync: (input, callback) ->
wordnet = @
new Promise (resolve, reject) ->
wordnet.lookup input, (err, data) ->
if err?
reject err
else
resolve data
findSense: (input, callback) ->
wordnet = @
[word, pos, senseNumber] = input.split('#')
if @cache
query = "findSense:#{input}"
if hit = wordnet.cache.get query
if callback.length == 1
return callback.call wordnet, hit
else
return callback.call wordnet, null, hit
sense = parseInt(senseNumber)
if Number.isNaN(sense)
throw new Error("Sense number should be an integer")
else if sense < 1
throw new Error("Sense number should be a positive integer")
lword = word.toLowerCase().replace(/\s+/g, '_')
selectedFiles = wordnet.allFiles.filter (file) -> file.pos == pos
wordnet.lookupFromFiles selectedFiles, [], lword, (err, response) ->
return callback.call wordnet, err if err?
result = response[sense - 1]
wordnet.cache.set query, result if query
if callback.length == 1
callback.call wordnet, result
else
callback.call wordnet, null, result
findSenseAsync: (input) ->
wordnet = @
new Promise (resolve, reject) ->
wordnet.findSense input, (err, data) ->
if err?
reject err
else
resolve data
querySense: (input, callback) ->
wordnet = @
[word, pos] = input.split('#')
if @cache
query = "querySense:#{input}"
if hit = wordnet.cache.get query
if callback.length == 1
return callback.call wordnet, hit
else
return callback.call wordnet, null, hit
wordnet.lookup input, (err, results) ->
return callback.call wordnet, err if err?
senseCounts = {}
senses = for sense, i in results
pos = sense.pos
pos = 'a' if pos == 's'
senseCounts[pos] ?= 1
word + "#" + pos + "#" + senseCounts[pos]++
wordnet.cache.set query, senses if query
if callback.length == 1
callback.call wordnet, senses
else
callback.call wordnet, null, senses
querySenseAsync: (input) ->
wordnet = @
new Promise (resolve, reject) ->
wordnet.querySense input, (err, data) ->
if err?
reject err
else
resolve data
lookupFromFiles: (files, results, word, callback) ->
wordnet = @
if files.length == 0
callback.call wordnet, null, results
else
file = files.pop()
file.index.lookup word, (err, record) ->
if record
wordnet.pushResults file.data, results, record.synsetOffset, () ->
wordnet.lookupFromFiles files, results, word, callback
else
wordnet.lookupFromFiles files, results, word, callback
pushResults: (data, results, offsets, callback) ->
wordnet = @
if offsets.length == 0
callback(results)
else
data.get offsets.pop(), (err, record) ->
results.push(record)
wordnet.pushResults(data, results, offsets, callback)
loadResultSynonyms: (synonyms, results, callback) ->
wordnet = this
if results.length > 0
result = results.pop()
wordnet.loadSynonyms synonyms, results, result.ptrs, callback
else
callback(synonyms)
loadSynonyms: (synonyms, results, ptrs, callback) ->
wordnet = this
if ptrs.length > 0
ptr = ptrs.pop()
@get ptr.synsetOffset, ptr.pos, (result) ->
synonyms.push(result)
wordnet.loadSynonyms synonyms, results, ptrs, callback
else
wordnet.loadResultSynonyms synonyms, results, callback
lookupSynonyms: (word, callback) ->
wordnet = this
wordnet.lookup word, (results) ->
wordnet.loadResultSynonyms [], results, callback
getSynonyms: () ->
wordnet = this
callback = if arguments[2] then arguments[2] else arguments[1]
pos = if arguments[0].pos then arguments[0].pos else arguments[1]
synsetOffset = if arguments[0].synsetOffset then arguments[0].synsetOffset else arguments[0]
@get synsetOffset, pos, (result) ->
wordnet.loadSynonyms [], [], result.ptrs, callback
getDataFile: (pos) ->
switch pos
when 'n' then @nounData
when 'v' then @verbData
when 'a', 's' then @adjData
when 'r' then @advData
## Exceptions aren't part of the node.js source, but they are needed to map some of
## the exceptions in derivations. Really, these should be loaded in the constructor, but
## sadly this code is asynchronous and we really don't want to force everything to
## block here. That's why a move to promises would be helpful, because all the dependent
## code is also going to be asynchronous and we can chain when we need to. For now, though,
## we'll handle it with callbacks when needed.
exceptions = [
{name: "noun.exc", pos: 'n'},
{name: "verb.exc", pos: 'v'},
{name: "adj.exc", pos: 'a'},
{name: "adv.exc", pos: 'r'},
]
_loadExceptions = (wordnet, callback) ->
## Flag while loading, so anyone who tries to use it can check and wait until the load
## is complete, instead of multiple loads happening at once.
WordNet::exceptions = 'pending'
loadFile = (exception, callback) ->
fullPath = path.join wordnet.path, exception.name
fs.readFile fullPath, (err, data) ->
return callback(err) if err
temp = {}
lines = data.toString().split("\n")
for line in lines
if line.length > 0
[term1, term2...] = line.split(' ')
temp[term1] ?= []
Array.prototype.push.apply temp[term1], term2
callback null, {pos: exception.pos, data: temp}
async.map exceptions, loadFile, (err, results) ->
exceptions = {}
for result in results
exceptions[result.pos] = result.data
WordNet::exceptions = exceptions
callback()
close: () ->
@nounIndex.close()
@verbIndex.close()
@adjIndex.close()
@advIndex.close()
@nounData.close()
@verbData.close()
@adjData.close()
@advData.close()
## Implementation of validForms. This isn't part of the original node.js Wordnet,
## and has instead been adapted from WordNet::QueryData. This helps to map words
## to WordNet by allowing different forms to be considered. Obviously, it's highly
## specific to English.
unique = (a) ->
found = {}
a.filter (item) ->
if found[item]
false
else
found[item] = true
tokenDetach = (string) ->
[word, pos, sense] = string.split('#')
detach = [word]
length = word.length
switch pos
when 'n'
detach.push word.substring(0, length - 1) if word.endsWith("s")
detach.push word.substring(0, length - 2) if word.endsWith("ses")
detach.push word.substring(0, length - 2) if word.endsWith("xes")
detach.push word.substring(0, length - 2) if word.endsWith("zes")
detach.push word.substring(0, length - 2) if word.endsWith("ches")
detach.push word.substring(0, length - 2) if word.endsWith("shes")
detach.push word.substring(0, length - 3) + "man" if word.endsWith("men")
detach.push word.substring(0, length - 3) + "y" if word.endsWith("ies")
when 'v'
detach.push word.substring(0, length - 1) if word.endsWith("s")
detach.push word.substring(0, length - 3) + "y" if word.endsWith("ies")
detach.push word.substring(0, length - 2) if word.endsWith("es")
detach.push word.substring(0, length - 1) if word.endsWith("ed")
detach.push word.substring(0, length - 2) if word.endsWith("ed")
detach.push word.substring(0, length - 3) + "e" if word.endsWith("ing")
detach.push word.substring(0, length - 3) if word.endsWith("ing")
when 'r'
detach.push word.substring(0, length - 2) if word.endsWith("er")
detach.push word.substring(0, length - 1) if word.endsWith("er")
detach.push word.substring(0, length - 3) if word.endsWith("est")
detach.push word.substring(0, length - 2) if word.endsWith("est")
unique(detach)
_forms = (wordnet, word, pos) ->
lword = word.toLowerCase()
## First check to see if we have an exception set
exception = wordnet.exceptions[pos]?[lword]
return [word].concat(exception) if exception
tokens = word.split(/[ _]/g)
## If a single term, process using tokenDetach
if tokens.length == 1
return tokenDetach(tokens[0] + "#" + pos)
## Otherwise, handle the forms recursively
forms = tokens.map (token) -> _forms(wordnet, token, pos)
## Now generate all possible token sequences (collocations)
rtn = []
index = (0 for token in tokens)
while true
colloc = forms[0][index[0]]
for i in [1..(tokens.length - 1)]
colloc = colloc + '_' + forms[i][index[i]]
rtn.push colloc
i = 0
while i < tokens.length
index[i] = index[i] + 1
if index[i] < forms[i].length
break
else
index[i] = 0
i = i + 1
if i >= tokens.length
break
return rtn
forms = (wordnet, string) ->
[word, pos, sense] = string.split('#')
rtn = _forms(wordnet, word, pos)
(element + "#" + pos for element in rtn)
_validForms = (wordnet, string, callback) ->
[word, pos, sense] = string.split('#')
if ! pos
## No POS, so use a reduce to try them all and concatenate
reducer = (previous, current, next) ->
_validForms wordnet, string + "#" + current, (err, value) ->
if value == undefined
next(null, previous)
else
next(null, previous.concat(value))
async.reduce ['n', 'v', 'a', 'r'], [], reducer, (err, result) ->
callback null, result
else
possibleForms = forms(wordnet, word + "#" + pos)
filteredResults = []
eachFn = (term, done) ->
wordnet.lookup term, (err, data) ->
if err?
return done(err)
filteredResults.push term if data.length > 0
done()
async.each possibleForms, eachFn, (err) ->
callback err, filteredResults
_validFormsWithExceptions = (wordnet, string, callback) ->
if wordnet.exceptions == undefined
_loadExceptions wordnet, () ->
_validFormsWithExceptions(wordnet, string, callback)
else if wordnet.exceptions == 'pending'
setImmediate _validFormsWithExceptions, wordnet, string, callback
else
_validForms(wordnet, string, callback)
validForms: (string, callback) ->
wordnet = @
if @cache
query = "validForms:#{string}"
if hit = wordnet.cache.get query
if callback.length == 1
return callback.call wordnet, hit
else
return callback.call wordnet, null, hit
_validFormsWithExceptions @, string, (err, result) ->
wordnet.cache.set query, result if query
if callback.length == 1
return callback.call wordnet, result
else
return callback.call wordnet, null, result
validFormsAsync: (string) ->
new Promise (resolve, reject) =>
@validForms string, (err, data) ->
if err?
reject err
else
resolve data
module.exports = WordNet
| 88263 | ## Copyright (c) 2011, <NAME>
##
## Permission is hereby granted, free of charge, to any person obtaining a copy
## of this software and associated documentation files (the "Software"), to deal
## in the Software without restriction, including without limitation the rights
## to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
## copies of the Software, and to permit persons to whom the Software is
## furnished to do so, subject to the following conditions:
##
## The above copyright notice and this permission notice shall be included in
## all copies or substantial portions of the Software.
##
## THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
## IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
## FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
## AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
## LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
## OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
## THE SOFTWARE.
##
## Significant changes made by <NAME>, including:
## (1) - implementation of logic for morphological exceptions
## (2) - using sense offsets as per Perl implementations
## (3) - porting to CoffeeScript for easier validation and better array performance
## (4) - promisification of much of the API
## (5) - move to use wndb-with-exceptions instead of WNdb, to provide morphological exceptions
## (6) - significant improvements in testing
IndexFile = require './index_file'
DataFile = require './data_file'
async = require 'async'
Promise = require 'bluebird'
path = require 'path'
fs = require 'fs'
LRU = require 'lru-cache'
require('es6-shim')
class WordNet
constructor: (options) ->
## For compatibility, if the options are a string, it's just the Wordnet path
if typeof options == 'string'
options = {dataDir: options}
else
options ?= {}
if ! options.dataDir?
try
WNdb = require('wndb-with-exceptions')
catch e
console.error("Please 'npm install wndb-with-exceptions' before using WordNet module or specify a dict directory.")
throw e
options.dataDir = WNdb.path
if ! options.cache
@cache = null
else
if options.cache == true
options.cache = {
max: 2000
}
if typeof options.cache == 'object' and typeof options.cache.get == 'function'
@cache = options.cache
else
@cache = LRU options.cache
@path = options.dataDir
@nounIndex = new IndexFile(@path, 'noun')
@verbIndex = new IndexFile(@path, 'verb')
@adjIndex = new IndexFile(@path, 'adj')
@advIndex = new IndexFile(@path, 'adv')
@nounData = new DataFile(@path, 'noun')
@verbData = new DataFile(@path, 'verb')
@adjData = new DataFile(@path, 'adj')
@advData = new DataFile(@path, 'adv')
@allFiles = [
{index: @nounIndex, data: @nounData, pos: 'n'}
{index: @verbIndex, data: @verbData, pos: 'v'}
{index: @adjIndex, data: @adjData, pos: 'a'}
{index: @advIndex, data: @advData, pos: 'r'}
]
get: (synsetOffset, pos, callback) ->
wordnet = @
if @cache
query = "get:#{synsetOffset}:#{pos}"
if hit = wordnet.cache.get query
if callback.length == 1
return callback.call wordnet, hit
else
return callback.call wordnet, null, hit
dataFile = wordnet.getDataFile(pos)
dataFile.get synsetOffset, (err, result) ->
wordnet.cache.set query, result if query && !err?
if callback.length == 1
callback.call wordnet, result
else
callback.call wordnet, err, result
getAsync: (synsetOffset, pos) ->
wordnet = @
new Promise (resolve, reject) ->
wordnet.get synsetOffset, pos, (err, data) ->
if err?
reject err
else
resolve data
lookup: (input, callback) ->
wordnet = @
[word, pos] = input.split('#')
lword = word.toLowerCase().replace(/\s+/g, '_')
if @cache
query = "lookup:#{input}"
if hit = wordnet.cache.get query
if callback.length == 1
return callback.call wordnet, hit
else
return callback.call wordnet, null, hit
selectedFiles = if ! pos then wordnet.allFiles else wordnet.allFiles.filter (file) -> file.pos == pos
wordnet.lookupFromFiles selectedFiles, [], lword, (err, results) ->
return callback.call wordnet, err if err?
wordnet.cache.set query, results if query
if callback.length == 1
return callback.call wordnet, results
else
return callback.call wordnet, null, results
lookupAsync: (input, callback) ->
wordnet = @
new Promise (resolve, reject) ->
wordnet.lookup input, (err, data) ->
if err?
reject err
else
resolve data
findSense: (input, callback) ->
wordnet = @
[word, pos, senseNumber] = input.split('#')
if @cache
query = "findSense:#{input}"
if hit = wordnet.cache.get query
if callback.length == 1
return callback.call wordnet, hit
else
return callback.call wordnet, null, hit
sense = parseInt(senseNumber)
if Number.isNaN(sense)
throw new Error("Sense number should be an integer")
else if sense < 1
throw new Error("Sense number should be a positive integer")
lword = word.toLowerCase().replace(/\s+/g, '_')
selectedFiles = wordnet.allFiles.filter (file) -> file.pos == pos
wordnet.lookupFromFiles selectedFiles, [], lword, (err, response) ->
return callback.call wordnet, err if err?
result = response[sense - 1]
wordnet.cache.set query, result if query
if callback.length == 1
callback.call wordnet, result
else
callback.call wordnet, null, result
findSenseAsync: (input) ->
wordnet = @
new Promise (resolve, reject) ->
wordnet.findSense input, (err, data) ->
if err?
reject err
else
resolve data
querySense: (input, callback) ->
wordnet = @
[word, pos] = input.split('#')
if @cache
query = "querySense:#{input}"
if hit = wordnet.cache.get query
if callback.length == 1
return callback.call wordnet, hit
else
return callback.call wordnet, null, hit
wordnet.lookup input, (err, results) ->
return callback.call wordnet, err if err?
senseCounts = {}
senses = for sense, i in results
pos = sense.pos
pos = 'a' if pos == 's'
senseCounts[pos] ?= 1
word + "#" + pos + "#" + senseCounts[pos]++
wordnet.cache.set query, senses if query
if callback.length == 1
callback.call wordnet, senses
else
callback.call wordnet, null, senses
querySenseAsync: (input) ->
wordnet = @
new Promise (resolve, reject) ->
wordnet.querySense input, (err, data) ->
if err?
reject err
else
resolve data
lookupFromFiles: (files, results, word, callback) ->
wordnet = @
if files.length == 0
callback.call wordnet, null, results
else
file = files.pop()
file.index.lookup word, (err, record) ->
if record
wordnet.pushResults file.data, results, record.synsetOffset, () ->
wordnet.lookupFromFiles files, results, word, callback
else
wordnet.lookupFromFiles files, results, word, callback
pushResults: (data, results, offsets, callback) ->
wordnet = @
if offsets.length == 0
callback(results)
else
data.get offsets.pop(), (err, record) ->
results.push(record)
wordnet.pushResults(data, results, offsets, callback)
loadResultSynonyms: (synonyms, results, callback) ->
wordnet = this
if results.length > 0
result = results.pop()
wordnet.loadSynonyms synonyms, results, result.ptrs, callback
else
callback(synonyms)
loadSynonyms: (synonyms, results, ptrs, callback) ->
wordnet = this
if ptrs.length > 0
ptr = ptrs.pop()
@get ptr.synsetOffset, ptr.pos, (result) ->
synonyms.push(result)
wordnet.loadSynonyms synonyms, results, ptrs, callback
else
wordnet.loadResultSynonyms synonyms, results, callback
lookupSynonyms: (word, callback) ->
wordnet = this
wordnet.lookup word, (results) ->
wordnet.loadResultSynonyms [], results, callback
getSynonyms: () ->
wordnet = this
callback = if arguments[2] then arguments[2] else arguments[1]
pos = if arguments[0].pos then arguments[0].pos else arguments[1]
synsetOffset = if arguments[0].synsetOffset then arguments[0].synsetOffset else arguments[0]
@get synsetOffset, pos, (result) ->
wordnet.loadSynonyms [], [], result.ptrs, callback
getDataFile: (pos) ->
switch pos
when 'n' then @nounData
when 'v' then @verbData
when 'a', 's' then @adjData
when 'r' then @advData
## Exceptions aren't part of the node.js source, but they are needed to map some of
## the exceptions in derivations. Really, these should be loaded in the constructor, but
## sadly this code is asynchronous and we really don't want to force everything to
## block here. That's why a move to promises would be helpful, because all the dependent
## code is also going to be asynchronous and we can chain when we need to. For now, though,
## we'll handle it with callbacks when needed.
exceptions = [
{name: "noun.exc", pos: 'n'},
{name: "verb.exc", pos: 'v'},
{name: "adj.exc", pos: 'a'},
{name: "adv.exc", pos: 'r'},
]
_loadExceptions = (wordnet, callback) ->
## Flag while loading, so anyone who tries to use it can check and wait until the load
## is complete, instead of multiple loads happening at once.
WordNet::exceptions = 'pending'
loadFile = (exception, callback) ->
fullPath = path.join wordnet.path, exception.name
fs.readFile fullPath, (err, data) ->
return callback(err) if err
temp = {}
lines = data.toString().split("\n")
for line in lines
if line.length > 0
[term1, term2...] = line.split(' ')
temp[term1] ?= []
Array.prototype.push.apply temp[term1], term2
callback null, {pos: exception.pos, data: temp}
async.map exceptions, loadFile, (err, results) ->
exceptions = {}
for result in results
exceptions[result.pos] = result.data
WordNet::exceptions = exceptions
callback()
close: () ->
@nounIndex.close()
@verbIndex.close()
@adjIndex.close()
@advIndex.close()
@nounData.close()
@verbData.close()
@adjData.close()
@advData.close()
## Implementation of validForms. This isn't part of the original node.js Wordnet,
## and has instead been adapted from WordNet::QueryData. This helps to map words
## to WordNet by allowing different forms to be considered. Obviously, it's highly
## specific to English.
unique = (a) ->
found = {}
a.filter (item) ->
if found[item]
false
else
found[item] = true
tokenDetach = (string) ->
[word, pos, sense] = string.split('#')
detach = [word]
length = word.length
switch pos
when 'n'
detach.push word.substring(0, length - 1) if word.endsWith("s")
detach.push word.substring(0, length - 2) if word.endsWith("ses")
detach.push word.substring(0, length - 2) if word.endsWith("xes")
detach.push word.substring(0, length - 2) if word.endsWith("zes")
detach.push word.substring(0, length - 2) if word.endsWith("ches")
detach.push word.substring(0, length - 2) if word.endsWith("shes")
detach.push word.substring(0, length - 3) + "man" if word.endsWith("men")
detach.push word.substring(0, length - 3) + "y" if word.endsWith("ies")
when 'v'
detach.push word.substring(0, length - 1) if word.endsWith("s")
detach.push word.substring(0, length - 3) + "y" if word.endsWith("ies")
detach.push word.substring(0, length - 2) if word.endsWith("es")
detach.push word.substring(0, length - 1) if word.endsWith("ed")
detach.push word.substring(0, length - 2) if word.endsWith("ed")
detach.push word.substring(0, length - 3) + "e" if word.endsWith("ing")
detach.push word.substring(0, length - 3) if word.endsWith("ing")
when 'r'
detach.push word.substring(0, length - 2) if word.endsWith("er")
detach.push word.substring(0, length - 1) if word.endsWith("er")
detach.push word.substring(0, length - 3) if word.endsWith("est")
detach.push word.substring(0, length - 2) if word.endsWith("est")
unique(detach)
_forms = (wordnet, word, pos) ->
lword = word.toLowerCase()
## First check to see if we have an exception set
exception = wordnet.exceptions[pos]?[lword]
return [word].concat(exception) if exception
tokens = word.split(/[ _]/g)
## If a single term, process using tokenDetach
if tokens.length == 1
return tokenDetach(tokens[0] + "#" + pos)
## Otherwise, handle the forms recursively
forms = tokens.map (token) -> _forms(wordnet, token, pos)
## Now generate all possible token sequences (collocations)
rtn = []
index = (0 for token in tokens)
while true
colloc = forms[0][index[0]]
for i in [1..(tokens.length - 1)]
colloc = colloc + '_' + forms[i][index[i]]
rtn.push colloc
i = 0
while i < tokens.length
index[i] = index[i] + 1
if index[i] < forms[i].length
break
else
index[i] = 0
i = i + 1
if i >= tokens.length
break
return rtn
forms = (wordnet, string) ->
[word, pos, sense] = string.split('#')
rtn = _forms(wordnet, word, pos)
(element + "#" + pos for element in rtn)
_validForms = (wordnet, string, callback) ->
[word, pos, sense] = string.split('#')
if ! pos
## No POS, so use a reduce to try them all and concatenate
reducer = (previous, current, next) ->
_validForms wordnet, string + "#" + current, (err, value) ->
if value == undefined
next(null, previous)
else
next(null, previous.concat(value))
async.reduce ['n', 'v', 'a', 'r'], [], reducer, (err, result) ->
callback null, result
else
possibleForms = forms(wordnet, word + "#" + pos)
filteredResults = []
eachFn = (term, done) ->
wordnet.lookup term, (err, data) ->
if err?
return done(err)
filteredResults.push term if data.length > 0
done()
async.each possibleForms, eachFn, (err) ->
callback err, filteredResults
_validFormsWithExceptions = (wordnet, string, callback) ->
if wordnet.exceptions == undefined
_loadExceptions wordnet, () ->
_validFormsWithExceptions(wordnet, string, callback)
else if wordnet.exceptions == 'pending'
setImmediate _validFormsWithExceptions, wordnet, string, callback
else
_validForms(wordnet, string, callback)
validForms: (string, callback) ->
wordnet = @
if @cache
query = "validForms:#{string}"
if hit = wordnet.cache.get query
if callback.length == 1
return callback.call wordnet, hit
else
return callback.call wordnet, null, hit
_validFormsWithExceptions @, string, (err, result) ->
wordnet.cache.set query, result if query
if callback.length == 1
return callback.call wordnet, result
else
return callback.call wordnet, null, result
validFormsAsync: (string) ->
new Promise (resolve, reject) =>
@validForms string, (err, data) ->
if err?
reject err
else
resolve data
module.exports = WordNet
| true | ## Copyright (c) 2011, PI:NAME:<NAME>END_PI
##
## Permission is hereby granted, free of charge, to any person obtaining a copy
## of this software and associated documentation files (the "Software"), to deal
## in the Software without restriction, including without limitation the rights
## to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
## copies of the Software, and to permit persons to whom the Software is
## furnished to do so, subject to the following conditions:
##
## The above copyright notice and this permission notice shall be included in
## all copies or substantial portions of the Software.
##
## THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
## IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
## FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
## AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
## LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
## OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
## THE SOFTWARE.
##
## Significant changes made by PI:NAME:<NAME>END_PI, including:
## (1) - implementation of logic for morphological exceptions
## (2) - using sense offsets as per Perl implementations
## (3) - porting to CoffeeScript for easier validation and better array performance
## (4) - promisification of much of the API
## (5) - move to use wndb-with-exceptions instead of WNdb, to provide morphological exceptions
## (6) - significant improvements in testing
IndexFile = require './index_file'
DataFile = require './data_file'
async = require 'async'
Promise = require 'bluebird'
path = require 'path'
fs = require 'fs'
LRU = require 'lru-cache'
require('es6-shim')
class WordNet
constructor: (options) ->
## For compatibility, if the options are a string, it's just the Wordnet path
if typeof options == 'string'
options = {dataDir: options}
else
options ?= {}
if ! options.dataDir?
try
WNdb = require('wndb-with-exceptions')
catch e
console.error("Please 'npm install wndb-with-exceptions' before using WordNet module or specify a dict directory.")
throw e
options.dataDir = WNdb.path
if ! options.cache
@cache = null
else
if options.cache == true
options.cache = {
max: 2000
}
if typeof options.cache == 'object' and typeof options.cache.get == 'function'
@cache = options.cache
else
@cache = LRU options.cache
@path = options.dataDir
@nounIndex = new IndexFile(@path, 'noun')
@verbIndex = new IndexFile(@path, 'verb')
@adjIndex = new IndexFile(@path, 'adj')
@advIndex = new IndexFile(@path, 'adv')
@nounData = new DataFile(@path, 'noun')
@verbData = new DataFile(@path, 'verb')
@adjData = new DataFile(@path, 'adj')
@advData = new DataFile(@path, 'adv')
@allFiles = [
{index: @nounIndex, data: @nounData, pos: 'n'}
{index: @verbIndex, data: @verbData, pos: 'v'}
{index: @adjIndex, data: @adjData, pos: 'a'}
{index: @advIndex, data: @advData, pos: 'r'}
]
get: (synsetOffset, pos, callback) ->
wordnet = @
if @cache
query = "get:#{synsetOffset}:#{pos}"
if hit = wordnet.cache.get query
if callback.length == 1
return callback.call wordnet, hit
else
return callback.call wordnet, null, hit
dataFile = wordnet.getDataFile(pos)
dataFile.get synsetOffset, (err, result) ->
wordnet.cache.set query, result if query && !err?
if callback.length == 1
callback.call wordnet, result
else
callback.call wordnet, err, result
getAsync: (synsetOffset, pos) ->
wordnet = @
new Promise (resolve, reject) ->
wordnet.get synsetOffset, pos, (err, data) ->
if err?
reject err
else
resolve data
lookup: (input, callback) ->
wordnet = @
[word, pos] = input.split('#')
lword = word.toLowerCase().replace(/\s+/g, '_')
if @cache
query = "lookup:#{input}"
if hit = wordnet.cache.get query
if callback.length == 1
return callback.call wordnet, hit
else
return callback.call wordnet, null, hit
selectedFiles = if ! pos then wordnet.allFiles else wordnet.allFiles.filter (file) -> file.pos == pos
wordnet.lookupFromFiles selectedFiles, [], lword, (err, results) ->
return callback.call wordnet, err if err?
wordnet.cache.set query, results if query
if callback.length == 1
return callback.call wordnet, results
else
return callback.call wordnet, null, results
lookupAsync: (input, callback) ->
wordnet = @
new Promise (resolve, reject) ->
wordnet.lookup input, (err, data) ->
if err?
reject err
else
resolve data
findSense: (input, callback) ->
wordnet = @
[word, pos, senseNumber] = input.split('#')
if @cache
query = "findSense:#{input}"
if hit = wordnet.cache.get query
if callback.length == 1
return callback.call wordnet, hit
else
return callback.call wordnet, null, hit
sense = parseInt(senseNumber)
if Number.isNaN(sense)
throw new Error("Sense number should be an integer")
else if sense < 1
throw new Error("Sense number should be a positive integer")
lword = word.toLowerCase().replace(/\s+/g, '_')
selectedFiles = wordnet.allFiles.filter (file) -> file.pos == pos
wordnet.lookupFromFiles selectedFiles, [], lword, (err, response) ->
return callback.call wordnet, err if err?
result = response[sense - 1]
wordnet.cache.set query, result if query
if callback.length == 1
callback.call wordnet, result
else
callback.call wordnet, null, result
findSenseAsync: (input) ->
wordnet = @
new Promise (resolve, reject) ->
wordnet.findSense input, (err, data) ->
if err?
reject err
else
resolve data
querySense: (input, callback) ->
wordnet = @
[word, pos] = input.split('#')
if @cache
query = "querySense:#{input}"
if hit = wordnet.cache.get query
if callback.length == 1
return callback.call wordnet, hit
else
return callback.call wordnet, null, hit
wordnet.lookup input, (err, results) ->
return callback.call wordnet, err if err?
senseCounts = {}
senses = for sense, i in results
pos = sense.pos
pos = 'a' if pos == 's'
senseCounts[pos] ?= 1
word + "#" + pos + "#" + senseCounts[pos]++
wordnet.cache.set query, senses if query
if callback.length == 1
callback.call wordnet, senses
else
callback.call wordnet, null, senses
querySenseAsync: (input) ->
wordnet = @
new Promise (resolve, reject) ->
wordnet.querySense input, (err, data) ->
if err?
reject err
else
resolve data
lookupFromFiles: (files, results, word, callback) ->
wordnet = @
if files.length == 0
callback.call wordnet, null, results
else
file = files.pop()
file.index.lookup word, (err, record) ->
if record
wordnet.pushResults file.data, results, record.synsetOffset, () ->
wordnet.lookupFromFiles files, results, word, callback
else
wordnet.lookupFromFiles files, results, word, callback
pushResults: (data, results, offsets, callback) ->
wordnet = @
if offsets.length == 0
callback(results)
else
data.get offsets.pop(), (err, record) ->
results.push(record)
wordnet.pushResults(data, results, offsets, callback)
loadResultSynonyms: (synonyms, results, callback) ->
wordnet = this
if results.length > 0
result = results.pop()
wordnet.loadSynonyms synonyms, results, result.ptrs, callback
else
callback(synonyms)
loadSynonyms: (synonyms, results, ptrs, callback) ->
wordnet = this
if ptrs.length > 0
ptr = ptrs.pop()
@get ptr.synsetOffset, ptr.pos, (result) ->
synonyms.push(result)
wordnet.loadSynonyms synonyms, results, ptrs, callback
else
wordnet.loadResultSynonyms synonyms, results, callback
lookupSynonyms: (word, callback) ->
wordnet = this
wordnet.lookup word, (results) ->
wordnet.loadResultSynonyms [], results, callback
getSynonyms: () ->
wordnet = this
callback = if arguments[2] then arguments[2] else arguments[1]
pos = if arguments[0].pos then arguments[0].pos else arguments[1]
synsetOffset = if arguments[0].synsetOffset then arguments[0].synsetOffset else arguments[0]
@get synsetOffset, pos, (result) ->
wordnet.loadSynonyms [], [], result.ptrs, callback
getDataFile: (pos) ->
switch pos
when 'n' then @nounData
when 'v' then @verbData
when 'a', 's' then @adjData
when 'r' then @advData
## Exceptions aren't part of the node.js source, but they are needed to map some of
## the exceptions in derivations. Really, these should be loaded in the constructor, but
## sadly this code is asynchronous and we really don't want to force everything to
## block here. That's why a move to promises would be helpful, because all the dependent
## code is also going to be asynchronous and we can chain when we need to. For now, though,
## we'll handle it with callbacks when needed.
exceptions = [
{name: "noun.exc", pos: 'n'},
{name: "verb.exc", pos: 'v'},
{name: "adj.exc", pos: 'a'},
{name: "adv.exc", pos: 'r'},
]
_loadExceptions = (wordnet, callback) ->
## Flag while loading, so anyone who tries to use it can check and wait until the load
## is complete, instead of multiple loads happening at once.
WordNet::exceptions = 'pending'
loadFile = (exception, callback) ->
fullPath = path.join wordnet.path, exception.name
fs.readFile fullPath, (err, data) ->
return callback(err) if err
temp = {}
lines = data.toString().split("\n")
for line in lines
if line.length > 0
[term1, term2...] = line.split(' ')
temp[term1] ?= []
Array.prototype.push.apply temp[term1], term2
callback null, {pos: exception.pos, data: temp}
async.map exceptions, loadFile, (err, results) ->
exceptions = {}
for result in results
exceptions[result.pos] = result.data
WordNet::exceptions = exceptions
callback()
close: () ->
@nounIndex.close()
@verbIndex.close()
@adjIndex.close()
@advIndex.close()
@nounData.close()
@verbData.close()
@adjData.close()
@advData.close()
## Implementation of validForms. This isn't part of the original node.js Wordnet,
## and has instead been adapted from WordNet::QueryData. This helps to map words
## to WordNet by allowing different forms to be considered. Obviously, it's highly
## specific to English.
unique = (a) ->
found = {}
a.filter (item) ->
if found[item]
false
else
found[item] = true
tokenDetach = (string) ->
[word, pos, sense] = string.split('#')
detach = [word]
length = word.length
switch pos
when 'n'
detach.push word.substring(0, length - 1) if word.endsWith("s")
detach.push word.substring(0, length - 2) if word.endsWith("ses")
detach.push word.substring(0, length - 2) if word.endsWith("xes")
detach.push word.substring(0, length - 2) if word.endsWith("zes")
detach.push word.substring(0, length - 2) if word.endsWith("ches")
detach.push word.substring(0, length - 2) if word.endsWith("shes")
detach.push word.substring(0, length - 3) + "man" if word.endsWith("men")
detach.push word.substring(0, length - 3) + "y" if word.endsWith("ies")
when 'v'
detach.push word.substring(0, length - 1) if word.endsWith("s")
detach.push word.substring(0, length - 3) + "y" if word.endsWith("ies")
detach.push word.substring(0, length - 2) if word.endsWith("es")
detach.push word.substring(0, length - 1) if word.endsWith("ed")
detach.push word.substring(0, length - 2) if word.endsWith("ed")
detach.push word.substring(0, length - 3) + "e" if word.endsWith("ing")
detach.push word.substring(0, length - 3) if word.endsWith("ing")
when 'r'
detach.push word.substring(0, length - 2) if word.endsWith("er")
detach.push word.substring(0, length - 1) if word.endsWith("er")
detach.push word.substring(0, length - 3) if word.endsWith("est")
detach.push word.substring(0, length - 2) if word.endsWith("est")
unique(detach)
_forms = (wordnet, word, pos) ->
lword = word.toLowerCase()
## First check to see if we have an exception set
exception = wordnet.exceptions[pos]?[lword]
return [word].concat(exception) if exception
tokens = word.split(/[ _]/g)
## If a single term, process using tokenDetach
if tokens.length == 1
return tokenDetach(tokens[0] + "#" + pos)
## Otherwise, handle the forms recursively
forms = tokens.map (token) -> _forms(wordnet, token, pos)
## Now generate all possible token sequences (collocations)
rtn = []
index = (0 for token in tokens)
while true
colloc = forms[0][index[0]]
for i in [1..(tokens.length - 1)]
colloc = colloc + '_' + forms[i][index[i]]
rtn.push colloc
i = 0
while i < tokens.length
index[i] = index[i] + 1
if index[i] < forms[i].length
break
else
index[i] = 0
i = i + 1
if i >= tokens.length
break
return rtn
forms = (wordnet, string) ->
[word, pos, sense] = string.split('#')
rtn = _forms(wordnet, word, pos)
(element + "#" + pos for element in rtn)
_validForms = (wordnet, string, callback) ->
[word, pos, sense] = string.split('#')
if ! pos
## No POS, so use a reduce to try them all and concatenate
reducer = (previous, current, next) ->
_validForms wordnet, string + "#" + current, (err, value) ->
if value == undefined
next(null, previous)
else
next(null, previous.concat(value))
async.reduce ['n', 'v', 'a', 'r'], [], reducer, (err, result) ->
callback null, result
else
possibleForms = forms(wordnet, word + "#" + pos)
filteredResults = []
eachFn = (term, done) ->
wordnet.lookup term, (err, data) ->
if err?
return done(err)
filteredResults.push term if data.length > 0
done()
async.each possibleForms, eachFn, (err) ->
callback err, filteredResults
_validFormsWithExceptions = (wordnet, string, callback) ->
if wordnet.exceptions == undefined
_loadExceptions wordnet, () ->
_validFormsWithExceptions(wordnet, string, callback)
else if wordnet.exceptions == 'pending'
setImmediate _validFormsWithExceptions, wordnet, string, callback
else
_validForms(wordnet, string, callback)
validForms: (string, callback) ->
wordnet = @
if @cache
query = "validForms:#{string}"
if hit = wordnet.cache.get query
if callback.length == 1
return callback.call wordnet, hit
else
return callback.call wordnet, null, hit
_validFormsWithExceptions @, string, (err, result) ->
wordnet.cache.set query, result if query
if callback.length == 1
return callback.call wordnet, result
else
return callback.call wordnet, null, result
validFormsAsync: (string) ->
new Promise (resolve, reject) =>
@validForms string, (err, data) ->
if err?
reject err
else
resolve data
module.exports = WordNet
|
[
{
"context": "ext(), {\n print_id\n id\n name: name\n story_type: type\n story_points\n ",
"end": 2756,
"score": 0.9959420561790466,
"start": 2752,
"tag": "NAME",
"value": "name"
}
] | js/src/pivy_print.coffee | sudodoki/pivy-print | 1 |
attachAPIHandlers = ->
createAPICard = (project_id, id) ->
extend = (target, other) ->
target = target or {}
for prop of other
target[prop] = other[prop]
target
getAttr = (xml, key) ->
$(xml).find(key).text()
chrome.storage .sync.get 'pivotal_api_key', (result) ->
print_id = "print_story_#{id}"
$.ajax
type: "GET"
dataType: "xml"
beforeSend: (request) ->
request.setRequestHeader("X-TrackerToken", result.pivotal_api_key)
url: "https://www.pivotaltracker.com/services/v3/projects/#{project_id}/stories/#{id}"
success: (cardInfo, status, xhr) ->
story_points = if $(cardInfo).find('estimate').length
' (' + getAttr(cardInfo, 'estimate') + ') '
else
''
toAdd = {}
if params = $('#story_template').data('params')?.split(', ')
for param in params
toAdd[param] = getAttr(cardInfo, param)
console.log toAdd
info = extend(toAdd, {
print_id
id
name: getAttr(cardInfo, 'name')
story_type: getAttr(cardInfo, 'story_type')
story_points
})
console.log info
div = Mustache.render $('#story_template').text(), info
$('#print-area').append(div)
error: (xhr, error, status) ->
if status is 'Unauthorized'
alert 'Either wrong or absent API key. To fix this, click pivy-print icon'
else
alert "Something went wrong. Tell our flying monkeys that. Status: #{status}"
$(document).on 'click', 'header.preview .selector', (e) ->
$this = $(@)
$story = $this.closest('.story')
classInfo = $story.attr('class').split(' ')
project_id = window.location.pathname.match(/projects\/(\d+)/)[1]
id = ($.grep classInfo, (elem) ->
elem.match(/story_\d+/))[0].split('_')[1]
if $this.hasClass('selected')
createAPICard(project_id, id)
else
$("#print_story_#{id}").remove()
attachDOMHandlers = ->
$(document).on 'click', 'header.preview .selector', (e) ->
$this = $(@)
$story = $this.closest('.story')
classInfo = $story.attr('class').split(' ')
id = ($.grep classInfo, (elem) ->
elem.match(/story_\d+/))[0].split('_')[1]
type = ($.grep classInfo, (elem) ->
elem.match(/(?:bug)|(?:chore)|(?:feature)/))[0]
name = $story.find('.story_name').html()
story_points = if (points = $story.find('.meta').text()) isnt '-1' then "(#{points})" else ''
print_id = "print_story_#{id}"
if $this.hasClass('selected')
div = Mustache.render $('#story_template').text(), {
print_id
id
name: name
story_type: type
story_points
}
$('#print-area').append(div)
else
$("##{print_id}").remove()
$ ->
$(document).ready ->
$('head').append("<style id='optional_css' type='text/css'></style>")
$('head').append("<script src='#{ chrome.extension.getURL("js/mustache.js") }'></script>")
$('body').append("<div id='print-area'></div>")
$('body').append("<script type='text/html' id='story_template'></script>")
chrome.storage.sync.get 'additional_params', (result) ->
console.log result.additional_params
# TODO: either remove extra logic or improve.
# if (params = result.additional_params)
if (params = [
'id',
'project_id',
'story_type',
'url',
'current_state',
'description',
'name',
'story_type',
'requested_by',
'owned_by',
'created_at',
'updated_at',
'labels'
])
$('#story_template').data 'params', params.join(', ')
chrome.storage.sync.get 'template', (result) ->
if (template = result.template)
$('#story_template').text(template)
else
$.when($.get(chrome.extension.getURL("default_story.html"))).done (response) ->
$('#story_template').text(response)
chrome.storage.sync.get 'optional_css', (result) ->
if (cssText = result.optional_css)
$('#optional_css').text(cssText)
else
$.when($.get(chrome.extension.getURL("css/default.css"))).done (response) ->
$('#optional_css').text(response)
chrome.storage.sync.get 'pivotal_method', (result) ->
if result.pivotal_method is "API"
attachAPIHandlers()
else
attachDOMHandlers()
$(document).on 'click', '.button.stories.menu', (e) ->
$this = $(@)
unless $('#print').length
$this.find('.items').append("<li id='print' class='item'><span class='disabled'>Print</span></li>")
if $this.find('.count').length
$('#print span').removeClass('disabled')
else
$('#print span').addClass('disabled')
$(document).on 'click', '#print', ->
return if $(@).find('span').hasClass('disabled')
window.print()
| 39352 |
attachAPIHandlers = ->
createAPICard = (project_id, id) ->
extend = (target, other) ->
target = target or {}
for prop of other
target[prop] = other[prop]
target
getAttr = (xml, key) ->
$(xml).find(key).text()
chrome.storage .sync.get 'pivotal_api_key', (result) ->
print_id = "print_story_#{id}"
$.ajax
type: "GET"
dataType: "xml"
beforeSend: (request) ->
request.setRequestHeader("X-TrackerToken", result.pivotal_api_key)
url: "https://www.pivotaltracker.com/services/v3/projects/#{project_id}/stories/#{id}"
success: (cardInfo, status, xhr) ->
story_points = if $(cardInfo).find('estimate').length
' (' + getAttr(cardInfo, 'estimate') + ') '
else
''
toAdd = {}
if params = $('#story_template').data('params')?.split(', ')
for param in params
toAdd[param] = getAttr(cardInfo, param)
console.log toAdd
info = extend(toAdd, {
print_id
id
name: getAttr(cardInfo, 'name')
story_type: getAttr(cardInfo, 'story_type')
story_points
})
console.log info
div = Mustache.render $('#story_template').text(), info
$('#print-area').append(div)
error: (xhr, error, status) ->
if status is 'Unauthorized'
alert 'Either wrong or absent API key. To fix this, click pivy-print icon'
else
alert "Something went wrong. Tell our flying monkeys that. Status: #{status}"
$(document).on 'click', 'header.preview .selector', (e) ->
$this = $(@)
$story = $this.closest('.story')
classInfo = $story.attr('class').split(' ')
project_id = window.location.pathname.match(/projects\/(\d+)/)[1]
id = ($.grep classInfo, (elem) ->
elem.match(/story_\d+/))[0].split('_')[1]
if $this.hasClass('selected')
createAPICard(project_id, id)
else
$("#print_story_#{id}").remove()
attachDOMHandlers = ->
$(document).on 'click', 'header.preview .selector', (e) ->
$this = $(@)
$story = $this.closest('.story')
classInfo = $story.attr('class').split(' ')
id = ($.grep classInfo, (elem) ->
elem.match(/story_\d+/))[0].split('_')[1]
type = ($.grep classInfo, (elem) ->
elem.match(/(?:bug)|(?:chore)|(?:feature)/))[0]
name = $story.find('.story_name').html()
story_points = if (points = $story.find('.meta').text()) isnt '-1' then "(#{points})" else ''
print_id = "print_story_#{id}"
if $this.hasClass('selected')
div = Mustache.render $('#story_template').text(), {
print_id
id
name: <NAME>
story_type: type
story_points
}
$('#print-area').append(div)
else
$("##{print_id}").remove()
$ ->
$(document).ready ->
$('head').append("<style id='optional_css' type='text/css'></style>")
$('head').append("<script src='#{ chrome.extension.getURL("js/mustache.js") }'></script>")
$('body').append("<div id='print-area'></div>")
$('body').append("<script type='text/html' id='story_template'></script>")
chrome.storage.sync.get 'additional_params', (result) ->
console.log result.additional_params
# TODO: either remove extra logic or improve.
# if (params = result.additional_params)
if (params = [
'id',
'project_id',
'story_type',
'url',
'current_state',
'description',
'name',
'story_type',
'requested_by',
'owned_by',
'created_at',
'updated_at',
'labels'
])
$('#story_template').data 'params', params.join(', ')
chrome.storage.sync.get 'template', (result) ->
if (template = result.template)
$('#story_template').text(template)
else
$.when($.get(chrome.extension.getURL("default_story.html"))).done (response) ->
$('#story_template').text(response)
chrome.storage.sync.get 'optional_css', (result) ->
if (cssText = result.optional_css)
$('#optional_css').text(cssText)
else
$.when($.get(chrome.extension.getURL("css/default.css"))).done (response) ->
$('#optional_css').text(response)
chrome.storage.sync.get 'pivotal_method', (result) ->
if result.pivotal_method is "API"
attachAPIHandlers()
else
attachDOMHandlers()
$(document).on 'click', '.button.stories.menu', (e) ->
$this = $(@)
unless $('#print').length
$this.find('.items').append("<li id='print' class='item'><span class='disabled'>Print</span></li>")
if $this.find('.count').length
$('#print span').removeClass('disabled')
else
$('#print span').addClass('disabled')
$(document).on 'click', '#print', ->
return if $(@).find('span').hasClass('disabled')
window.print()
| true |
attachAPIHandlers = ->
createAPICard = (project_id, id) ->
extend = (target, other) ->
target = target or {}
for prop of other
target[prop] = other[prop]
target
getAttr = (xml, key) ->
$(xml).find(key).text()
chrome.storage .sync.get 'pivotal_api_key', (result) ->
print_id = "print_story_#{id}"
$.ajax
type: "GET"
dataType: "xml"
beforeSend: (request) ->
request.setRequestHeader("X-TrackerToken", result.pivotal_api_key)
url: "https://www.pivotaltracker.com/services/v3/projects/#{project_id}/stories/#{id}"
success: (cardInfo, status, xhr) ->
story_points = if $(cardInfo).find('estimate').length
' (' + getAttr(cardInfo, 'estimate') + ') '
else
''
toAdd = {}
if params = $('#story_template').data('params')?.split(', ')
for param in params
toAdd[param] = getAttr(cardInfo, param)
console.log toAdd
info = extend(toAdd, {
print_id
id
name: getAttr(cardInfo, 'name')
story_type: getAttr(cardInfo, 'story_type')
story_points
})
console.log info
div = Mustache.render $('#story_template').text(), info
$('#print-area').append(div)
error: (xhr, error, status) ->
if status is 'Unauthorized'
alert 'Either wrong or absent API key. To fix this, click pivy-print icon'
else
alert "Something went wrong. Tell our flying monkeys that. Status: #{status}"
$(document).on 'click', 'header.preview .selector', (e) ->
$this = $(@)
$story = $this.closest('.story')
classInfo = $story.attr('class').split(' ')
project_id = window.location.pathname.match(/projects\/(\d+)/)[1]
id = ($.grep classInfo, (elem) ->
elem.match(/story_\d+/))[0].split('_')[1]
if $this.hasClass('selected')
createAPICard(project_id, id)
else
$("#print_story_#{id}").remove()
attachDOMHandlers = ->
$(document).on 'click', 'header.preview .selector', (e) ->
$this = $(@)
$story = $this.closest('.story')
classInfo = $story.attr('class').split(' ')
id = ($.grep classInfo, (elem) ->
elem.match(/story_\d+/))[0].split('_')[1]
type = ($.grep classInfo, (elem) ->
elem.match(/(?:bug)|(?:chore)|(?:feature)/))[0]
name = $story.find('.story_name').html()
story_points = if (points = $story.find('.meta').text()) isnt '-1' then "(#{points})" else ''
print_id = "print_story_#{id}"
if $this.hasClass('selected')
div = Mustache.render $('#story_template').text(), {
print_id
id
name: PI:NAME:<NAME>END_PI
story_type: type
story_points
}
$('#print-area').append(div)
else
$("##{print_id}").remove()
$ ->
$(document).ready ->
$('head').append("<style id='optional_css' type='text/css'></style>")
$('head').append("<script src='#{ chrome.extension.getURL("js/mustache.js") }'></script>")
$('body').append("<div id='print-area'></div>")
$('body').append("<script type='text/html' id='story_template'></script>")
chrome.storage.sync.get 'additional_params', (result) ->
console.log result.additional_params
# TODO: either remove extra logic or improve.
# if (params = result.additional_params)
if (params = [
'id',
'project_id',
'story_type',
'url',
'current_state',
'description',
'name',
'story_type',
'requested_by',
'owned_by',
'created_at',
'updated_at',
'labels'
])
$('#story_template').data 'params', params.join(', ')
chrome.storage.sync.get 'template', (result) ->
if (template = result.template)
$('#story_template').text(template)
else
$.when($.get(chrome.extension.getURL("default_story.html"))).done (response) ->
$('#story_template').text(response)
chrome.storage.sync.get 'optional_css', (result) ->
if (cssText = result.optional_css)
$('#optional_css').text(cssText)
else
$.when($.get(chrome.extension.getURL("css/default.css"))).done (response) ->
$('#optional_css').text(response)
chrome.storage.sync.get 'pivotal_method', (result) ->
if result.pivotal_method is "API"
attachAPIHandlers()
else
attachDOMHandlers()
$(document).on 'click', '.button.stories.menu', (e) ->
$this = $(@)
unless $('#print').length
$this.find('.items').append("<li id='print' class='item'><span class='disabled'>Print</span></li>")
if $this.find('.count').length
$('#print span').removeClass('disabled')
else
$('#print span').addClass('disabled')
$(document).on 'click', '#print', ->
return if $(@).find('span').hasClass('disabled')
window.print()
|
[
{
"context": ".10 (darwin)\nComment: https://keybase.io/download\n\nxo0EVr0A8wEEAOouu6kTiwMFfHJ2ZoTiEpOSPxMbUSPowGouDkVYBWCbzMXLMKbX\n84YCQIihsaVvRUTBbdobhO8qD3CFsGWPodmmwjdYYDCGs+KVlH49QfHXjH5epItG\nRG8lel+QpOmGQa1vhOdRorgXz0ROwzJzgAk3qUl/Fm8BUKuxQmXopTBHABEBAAHN\nI1Rlc3QgNiBLZXkgPHRoZW1heCt0ZXN0NkBnbWFpbC5jb2... | test/files/subkey_no_cross_sig.iced | johnnyRose/kbpgp | 1 | {KeyManager} = require '../..'
{bufeq_secure} = require '../../lib/util'
#============================================================================
key_without_cross_sig = """-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: Keybase Go 1.0.10 (darwin)
Comment: https://keybase.io/download
xo0EVr0A8wEEAOouu6kTiwMFfHJ2ZoTiEpOSPxMbUSPowGouDkVYBWCbzMXLMKbX
84YCQIihsaVvRUTBbdobhO8qD3CFsGWPodmmwjdYYDCGs+KVlH49QfHXjH5epItG
RG8lel+QpOmGQa1vhOdRorgXz0ROwzJzgAk3qUl/Fm8BUKuxQmXopTBHABEBAAHN
I1Rlc3QgNiBLZXkgPHRoZW1heCt0ZXN0NkBnbWFpbC5jb20+wrIEEwECACYFAla9
APMJEBXWxhRRsg4TAhsDBgsJCAcDAgYVCAIJCgsEFgIDAQAAMUoEAN5pYfC5DSfB
eYUtMIyzPPQihrJBdONRL8wjDn0d5vAAERddxYhL1OxbsGwQIjNI2EWxbk6vKh3/
qNZiQKqYNavI9V9YBrbVNJ8D6eQpZJogpDDe3WkjfzPKg61vwUFOF2XzcYKHrngg
98Y1ag2w2HiPC1GmgIYyPC116IpIMLOpzo0EVr0A8wEEAKeEhup41f4lN3kG6Mps
959rQturGGbsWD2fCXQ/ryoqkBuGcR7lnmR8UP3NIVIVBGh9kov59njH+4D+/SJ0
Oj4VgDW0rn4EYbenSrDSWaNf9I5mgA8+G/DsaICdsUYf8D2EUWDviKqhh3mSRSoG
jfqWVkxsTTd+E3CE1spjEDg3ABEBAAHCnwQYAQIAEwUCVr0A8wkQFdbGFFGyDhMC
GwwAAAqpBAAPy9cwVyTdEpu34r+284Oq2y11LEBO/TNMUWqztqrxBn8iefBOIUgV
ktbnW1i/H9XFJPhxgF9wGa6hLJYuvfRG3GtSOQixz/oS4jMlwAGK2MmVvTsZi/lg
ulpZAoZk6zMfJRm3BkFhhkp7AB5Okg1pceGikNYOCHcm02okzZO/B86NBFa9AQAB
BACYwrQl6PrgFn5hK+Ue8a7ljXKgMPpk2HpF+cFIL0KM+/JphWrfsSN1EUpVJOBD
DTRAksSA1y+B4X3TuJb1qYey2lBnaB7gUtqrWYmrkottpygT7hZar8JntRsQrvKF
DjFdgJg+/NEi7doGYmkRVA/JIQSqroswgVxZEVPVlZvzZQARAQABwp8EGAECABMF
Ala9AQAJEBXWxhRRsg4TAhsCAABkGgQAEn3sYIiafWr1xg/8TBPd3lFgFAlJnZ84
8gIZx9RGy5AhcbGLq9EezZW8+tHAjFcWL7Ex1bg4dqApoA6SJFfHhxlkNyM9Vrnn
DJVpsnGhwVufOT6SpyDbV31iDVhTSK6jY/EIcW/YDnMguf0Ybexsjv7Er66gygO3
SfvXjnAewcg=
=So85
-----END PGP PUBLIC KEY BLOCK-----"""
key_with_cross_sig = """-----BEGIN PGP PUBLIC KEY BLOCK-----
Comment: GPGTools - https://gpgtools.org
mQENBFa5QKwBCADHqlsggv3b4EWV7WtHVeur84Vm2Xhb+htzcPPZFwpipqF7HV+l
hsYPsY0qEDarcsGYfoRcEh4j9xV3VwrUj7DNwf2s/ZXuni+9hoyAI6FdLn6ep9ju
q5z+R7okfqx70gi4wDQVDmpVT3MaYi7/fd3kqQjRUUIwBysPPXTfBFA8S8ARnp71
bBp+Xz+ESsxmyOjjmCea2H43N3x0d/qVSORo5f32U67z77Nn/ZXKwMqmJNE0+LtM
18icqWJQ3+R+9j3P01geidsHGCaPjW4Lb0io6g8pynbfA1ihlKasfwYDgMgt8TMA
QO/wum2ozq6NJF0PuJtakVn1izWagaHcGB9RABEBAAG0L1Jldm9rZWQgU3Via2V5
IChQVyBpcyAnYWJjZCcpIDxyZXZva2VkQHN1Yi5rZXk+iQE3BBMBCgAhBQJWuUCs
AhsDBQsJCAcDBRUKCQgLBRYCAwEAAh4BAheAAAoJECCariPD5X1jXNoIAIQTRem2
NSTDgt7Qi4R9Yo4PCS26uCVVv7XEmPjxQvEqSTeG7R0pNtGTOLIEO3/Jp5FMfDmC
9o/UHpRxEoS2ZB7F3yVlRhbX20k9O8SFf+G1JyRFKfD4dG/5S6zv+16eDO8sZEMj
JvZoSf1W+0MsAGYf3x03l3Iy5EbhU/r/ICG725AB4aFElSS3+DdfpV/FgUMf3HPU
HbX7DYGwfvukgZU4u853ded0pFcslxm8GusIEwbHtbADsF7Cq91NMh1x8SEXbz6V
7x7Fs/RORdTs3jVLWmcL2kWvSSP88j+nxJTL1YGpDua2uMH6Z7dZXbjdzQzlV/EY
WBZ5jTDHvPxhXtC5AQ0EVrlArAEIALGgYGt1g/xRrZQzosZzaG5hsx288p/6XKnJ
4tvLYau3iqrO3r9qRkrQkalpcj6XRZ1aNbGdhwCRolZsEr8lZc4gicQxYPpN9j8j
YuMpD6UEaJhBraCpytiktmV7urSgQw9MAD3BHTC4z4k4mvyRZh7TyxI7sHaEsxQx
Z7aDEO5IU3IR4YH/WDxaIwf2khjVzAsqtz32NTjWRh3n2M5T70nyAyB0RaWn754F
cu3iBzcqlb1NFM+y0+rRWOkb0bHnGyllk/rJvolG1TUZBsWffE+c8kSsCV2h8K4H
GqRnWEpPztMJ0LxZJZ944sOFpzFlyq/zXoFvHNYQvAnkJ9sOeX8AEQEAAYkBHwQY
AQoACQUCVrlArAIbDAAKCRAgmq4jw+V9Y9ppB/9euMEcY0Bs8wWlSzoa+mMtwP4o
RAcXWUVl7qk7YF0t5PBNzu9t+qSRt6jInImaOCboKyMCmaRFb2LpgKt4L8dvufBe
c7QGJe0hWbZJ0Ku2GW0uylw9jl0K7jvJQjMXax/iUX3wR/mdTyytYv/SNvYO40/Z
rtM+ae224OdxWc2ryRPC8L5J8pXtCvcYYy5V7GXTpTKdV5O1f19AYKqtwBSjS4//
f+DtXBX2VcWCz+Q77u3Z/hZlmWKb14y4B247sFFaT1c16Vrx0e+Xn2ZaMBwwj/Jw
1/4py7jIBQVyPuzFwMP/wW6IJAvd/enYT4MPLcdSEZ4tTx6PNuGMLRev9Tn6uQEN
BFa5QngBCAC2DeQArEENKYOYsCs0kqZbnGiBfsa0v9pvOswQ5Ki5VeiI7fSz6gr9
dDxCJ3Iho58O0DG2QBDo8bn7nA85Wj2yBNJXQCauc3MPctiGBJqxcL2Fs41SxsNU
fzRQDabcodh1Iq69u+PwjShfHR78MWJTmCQaySSxau0iEhYD+dnEP6FbN8nuBxAX
vNfnhM+uA8Y2R+M14U6i4pd0ZRle+Xu1Q1whF7v4OhKnOYezTFbUC3kXGNdUnCep
u5AM0hw+kV8wqtShMc4uw9KJ9Phu1Vmb4X/A+pd1J1S30ZbrWcfdqzjYF9XjOqda
gmG1B6uRbi6pn473S/G1Q/44S7XBdEvrABEBAAGJASYEKAEKABAFAla5QpoJHQJu
byBkaWNlAAoJECCariPD5X1jABMH/R7f+2chVR/8uYITexjHANUtszf41vo/nYo7
ekyEaB4mzq4meB7h+pEhdkzYnXp7rvk6hpkflGk2eEFTUH8Tqw0BFtpdS0N2youW
6n/TeTfuSjzXyecn5c4rgSCw0DP1qFrWoneN5HDcDoJk93QlUqujsE6Ru5QXLgI7
MfojF6heh0CdIyXBrUN6oyWKYGFwWFMUQIPkYQmLsJ1QhLAvmMDovzlSjGDPOK/6
Ly7CVmdaawyCpAQ2A97aN2OS3c3YxefbVQrIeD195xPFE6R0aybjb9xzRXh9hmMe
nKVAqXBIqhWZl9XfrlJJqdty3YSyn0olBFPM+3TXFSJq5leRQuSJAj4EGAEKAAkF
Ala5QngCGwIBKQkQIJquI8PlfWPAXSAEGQEKAAYFAla5QngACgkQWiVrsAiVPozJ
hwf/edwVPbyyI2EV7twEC83AF1cEQ1Hpwsor079WWfoythLaX6hzInBOGT8UC5Wd
MXpKbiFjBi/0DqFCan0xoJ1aysTvfAB8Hyq9y8FKc3gfFvibFzBvvLW0fCo1IkQl
lNQCu8hFv7e1tUvdQO/N/2pcEncgLXzPAt3Iu/lbTyDH5B15wMQMH/6t+Z82qEh2
q6x5j2EiBix2adeRaVF1iDEpB0nW9GfSBeb6TPOap8l6FJGPYLqdDdd/S9q7O5hs
nXvsr9BFT4rzqV8HzHQS2SVOT60uIw8Vnk4iyYH5mVZ4i6iNferFSxfa2Ju32U/q
3J5CHJhETt1lStDRsm8qQXGApvASB/9vw/R13U1IFQKZi0SZ0LJBRbuXf+LEGe+1
5o00RoghB1FLzyZ3SHiKOlnPdFtB4FpUHhE/qp7ehWLw27/5FF28PXJogIUdA5id
3pa298bRCuvwUtJvjahSaPIry53/Th2ZELWeXJ9nJYtzwtptvnCrr9rX4Bly+iop
NfPdj9BVTOR3miC33bKE8E0mKK5OrKtwp82viZKkmOeZmYZw2mOV5NmrtY5I3HQr
sYRVoR9/9XUt7nCrRB93e9rjHlB7837a0sCc60p4/+9y4lnqaHTV/IcmWgfvyb69
F5Frpj3NfmZSY1HuBMDr2qXGiMxMPqPwdaqiNTRwEeoWVZ1IBItUuQENBFa5QqIB
CADiZy6KgIfcdNSluaYOh/w5HchCL6r+5FMKeX/BtttLl9l+0ysDZUZVMx5WMPjR
LpBkRLFK9hDydfXkCBwAvgtn4PNxRfETi4uIV2R7TBGh4Ld0Lw71oX1kZajB2EaK
lQob+wmZ9vKypVebWurgulIRtLbWeBMqAol91Oa439lK4MrY/5L6Ia+uFDbpqkyl
hToIUxos0gVIUSW4nxVi+AyhD8tVxrV0IghZmRucrXSFdCN4PhPWMV30eBiBirtj
eCBsjE/x8U8gpa23JN/fYKbEcKxtNOMgZmo5HyCiCunXov4xmt/j6cvkwAPo3lyl
UsBz3jm9BEk7lbe3Qliv7HTLABEBAAGJAj4EGAEKAAkFAla5QqICGwIBKQkQIJqu
I8PlfWPAXSAEGQEKAAYFAla5QqIACgkQ4kNZbVhl1g+OnQf+JB+wD3xXhGXOhQ1t
gLtlOWts1yfOMnrQ3C6008EEMgFD6gGcEkvf6bRaJPaHqjH5APQpO39r2wmf6ZJb
Ht0cNKVCO+59pY7zMATrYyoTou89vxQ4pJ8RXNaEd5iRBSrxyaDpjszZ+avU6sSV
a+0odQvgACs9yvQX1rFt/hIUaiH8QLHQNqr2AjROJ0eTeYStMAZISLEDceqx6bTh
iuqdChG0IY8bZju2AM6tbgD9lYF9ENt/lnIQwcfMidTJnVsLQIDa8ygZnhxNeaOd
BUB+GncSR79k9/FPPYMPVXZ6BJ2Ac+Fml3xGzrDEE6tN9Nz++ApL6PHKM1naf5bZ
6EdMpLVwB/9roBNdSCh2EZFrEhvc2hVLACn9e42usrIG1zenlVf7ML///xEQ1fSp
5jAXs256kN+ecKH0/k0n7+jkMVofP9D7aA1UTEalFvtJo0na7bar1r73NLQzI4ff
PEFSUPZ0XGlSFJ5JAuiXVqtWdfCwGEImux5wx7+Zgy/NvapDx2RpysuGRWJ31IXB
JjZE17lYkH+WoRB7HGVqb9cNSVIEmQtH+NfOHJtw22fa7n2s54kybGIKSBdIo3WA
eWyxOkyZmC5cJwkR8RWY8trq35SpTSUVXXDFFHer7ddMilnMwPzCLxcYkdWUQaa5
tmIuHu1WeYgLy8ZUju/jcJcb9XYI6rBP
=YFA2
-----END PGP PUBLIC KEY BLOCK-----
"""
count_subkeys = (km) ->
n = 0
km = km.pgp
n++ for i in km.subkeys when not km.key(i).is_revoked()
n
exports.test_subkey_without_cross_sig = (T,cb) ->
await KeyManager.import_from_armored_pgp { raw : key_without_cross_sig, opts : { strict : true } }, defer err, km, warnings
T.no_error err
T.assert count_subkeys(km) is 1
T.assert warnings.warnings().length is 1
T.equal warnings.warnings()[0], "Subkey 1 was invalid; discarding"
k = km.find_verifying_pgp_key()
wanted = new Buffer ("36A9 F360 387A 32F8 4D78 C18D 15D6 C614 51B2 0E13".split(/\s+/).join('')), 'hex'
T.assert bufeq_secure wanted, k.get_fingerprint()
cb()
exports.test_subkey_with_cross_sig = (T,cb) ->
await KeyManager.import_from_armored_pgp { raw : key_with_cross_sig, opts : { strict : true } }, defer err, km, warnings
T.no_error err
T.assert count_subkeys(km) is 2
T.assert warnings.warnings().length is 0
k = km.find_verifying_pgp_key()
wanted = new Buffer ("FCFF 7A50 95B7 29EF F05D 846C E243 596D 5865 D60F".split(/\s+/).join('')), 'hex'
T.assert bufeq_secure wanted, k.get_fingerprint()
cb()
| 217310 | {KeyManager} = require '../..'
{bufeq_secure} = require '../../lib/util'
#============================================================================
key_without_cross_sig = """-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: Keybase Go 1.0.10 (darwin)
Comment: https://keybase.io/download
<KEY>
jfq<KEY>
-----END PGP PUBLIC KEY BLOCK-----"""
key_with_cross_sig = """-----BEGIN PGP PUBLIC KEY BLOCK-----
Comment: GPGTools - https://gpgtools.org
mQENBFa5QKwBCADHqlsggv3b4EWV7WtH<KEY>
-----END PGP PUBLIC KEY BLOCK-----
"""
count_subkeys = (km) ->
n = 0
km = km.pgp
n++ for i in km.subkeys when not km.key(i).is_revoked()
n
exports.test_subkey_without_cross_sig = (T,cb) ->
await KeyManager.import_from_armored_pgp { raw : key_without_cross_sig, opts : { strict : true } }, defer err, km, warnings
T.no_error err
T.assert count_subkeys(km) is 1
T.assert warnings.warnings().length is 1
T.equal warnings.warnings()[0], "Subkey 1 was invalid; discarding"
k = km.find_verifying_pgp_key()
wanted = new Buffer ("36A9 F360 387A 32F8 4D78 C18D 15D6 C614 51B2 0E13".split(/\s+/).join('')), 'hex'
T.assert bufeq_secure wanted, k.get_fingerprint()
cb()
exports.test_subkey_with_cross_sig = (T,cb) ->
await KeyManager.import_from_armored_pgp { raw : key_with_cross_sig, opts : { strict : true } }, defer err, km, warnings
T.no_error err
T.assert count_subkeys(km) is 2
T.assert warnings.warnings().length is 0
k = km.find_verifying_pgp_key()
wanted = new Buffer ("FCFF 7A50 95B7 29EF F05D 846C E243 596D 5865 D60F".split(/\s+/).join('')), 'hex'
T.assert bufeq_secure wanted, k.get_fingerprint()
cb()
| true | {KeyManager} = require '../..'
{bufeq_secure} = require '../../lib/util'
#============================================================================
key_without_cross_sig = """-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: Keybase Go 1.0.10 (darwin)
Comment: https://keybase.io/download
PI:KEY:<KEY>END_PI
jfqPI:KEY:<KEY>END_PI
-----END PGP PUBLIC KEY BLOCK-----"""
key_with_cross_sig = """-----BEGIN PGP PUBLIC KEY BLOCK-----
Comment: GPGTools - https://gpgtools.org
mQENBFa5QKwBCADHqlsggv3b4EWV7WtHPI:KEY:<KEY>END_PI
-----END PGP PUBLIC KEY BLOCK-----
"""
count_subkeys = (km) ->
n = 0
km = km.pgp
n++ for i in km.subkeys when not km.key(i).is_revoked()
n
exports.test_subkey_without_cross_sig = (T,cb) ->
await KeyManager.import_from_armored_pgp { raw : key_without_cross_sig, opts : { strict : true } }, defer err, km, warnings
T.no_error err
T.assert count_subkeys(km) is 1
T.assert warnings.warnings().length is 1
T.equal warnings.warnings()[0], "Subkey 1 was invalid; discarding"
k = km.find_verifying_pgp_key()
wanted = new Buffer ("36A9 F360 387A 32F8 4D78 C18D 15D6 C614 51B2 0E13".split(/\s+/).join('')), 'hex'
T.assert bufeq_secure wanted, k.get_fingerprint()
cb()
exports.test_subkey_with_cross_sig = (T,cb) ->
await KeyManager.import_from_armored_pgp { raw : key_with_cross_sig, opts : { strict : true } }, defer err, km, warnings
T.no_error err
T.assert count_subkeys(km) is 2
T.assert warnings.warnings().length is 0
k = km.find_verifying_pgp_key()
wanted = new Buffer ("FCFF 7A50 95B7 29EF F05D 846C E243 596D 5865 D60F".split(/\s+/).join('')), 'hex'
T.assert bufeq_secure wanted, k.get_fingerprint()
cb()
|
[
{
"context": "\t\tuserData =\n\t\t\temail: formData.email\n\t\t\tpassword: formData.pass\n\n\t\tuserId = Accounts.createUser userData\n\n\t\tRocke",
"end": 108,
"score": 0.9988147616386414,
"start": 95,
"tag": "PASSWORD",
"value": "formData.pass"
}
] | server/methods/registerUser.coffee | 41studio/41chat | 1 | Meteor.methods
registerUser: (formData) ->
userData =
email: formData.email
password: formData.pass
userId = Accounts.createUser userData
RocketChat.models.Users.setName userId, formData.name
if userData.email
Accounts.sendVerificationEmail(userId, userData.email);
| 150578 | Meteor.methods
registerUser: (formData) ->
userData =
email: formData.email
password: <PASSWORD>
userId = Accounts.createUser userData
RocketChat.models.Users.setName userId, formData.name
if userData.email
Accounts.sendVerificationEmail(userId, userData.email);
| true | Meteor.methods
registerUser: (formData) ->
userData =
email: formData.email
password: PI:PASSWORD:<PASSWORD>END_PI
userId = Accounts.createUser userData
RocketChat.models.Users.setName userId, formData.name
if userData.email
Accounts.sendVerificationEmail(userId, userData.email);
|
[
{
"context": "###\n * Copyright 2013-2017 Thibaut Courouble and other contributors\n *\n * This source code is ",
"end": 44,
"score": 0.9998654723167419,
"start": 27,
"tag": "NAME",
"value": "Thibaut Courouble"
}
] | public/javascripts/lib/license.coffee | w3cub/docshub-node | 3 | ###
* Copyright 2013-2017 Thibaut Courouble and other contributors
*
* This source code is licensed under the terms of the Mozilla
* Public License, v. 2.0, a copy of which may be obtained at:
* http://mozilla.org/MPL/2.0/
###
| 152494 | ###
* Copyright 2013-2017 <NAME> and other contributors
*
* This source code is licensed under the terms of the Mozilla
* Public License, v. 2.0, a copy of which may be obtained at:
* http://mozilla.org/MPL/2.0/
###
| true | ###
* Copyright 2013-2017 PI:NAME:<NAME>END_PI and other contributors
*
* This source code is licensed under the terms of the Mozilla
* Public License, v. 2.0, a copy of which may be obtained at:
* http://mozilla.org/MPL/2.0/
###
|
[
{
"context": "sh the password', (done)->\n user.username = 'hey'\n user.password = 'testing'\n user.saveQ",
"end": 853,
"score": 0.999467670917511,
"start": 850,
"tag": "USERNAME",
"value": "hey"
},
{
"context": " user.username = 'hey'\n user.password = 'testi... | test/unit/user.coffee | ethanmick/fastchat-server | 7 | 'use strict'
#
# FastChat
# 2015
#
require('../../lib/helpers/helpers')()
mongoose = require 'mongoose'
Q = require 'q'
sinon = require 'sinon'
ObjectId = mongoose.Types.ObjectId
should = require('chai').should()
User = require '../../lib/model/user'
Device = require '../../lib/model/device'
Group = require '../../lib/model/group'
AvatarTests = process.env.AWS_KEY? and process.env.AWS_SECRET?
describe 'User', ->
before (done)->
mongoose.connect 'mongodb://localhost/test'
db = mongoose.connection
db.once 'open', ->
User.removeQ({}).then -> done()
user = null
beforeEach ->
user = new User()
describe 'Model', ->
it 'should be a user', ->
user = new User()
(user instanceof User).should.be.ok
describe 'Authentication', ->
it 'should hash the password', (done)->
user.username = 'hey'
user.password = 'testing'
user.saveQ().then ->
user.password.should.not.equal 'testing'
done()
it 'should make a random token', ->
user = new User()
result = user.generateRandomToken()
should.exist result
it 'should compare correct passwords', (done)->
user.username = 'hey0'
user.password = 'testing'
user.saveQ().then ->
user.comparePassword('testing')
.then (matched)->
should.exist matched
matched.should.be.true
done()
it 'should compare incorrect passwords', (done)->
user.username = 'heyo'
user.password = 'testing'
user.saveQ().then ->
user.comparePassword('mypassword')
.catch (err)->
err.message.should.equal 'Incorrect username or password'
done()
describe 'Push', ->
it 'should push to all the users devices', (done)->
d1 = new Device()
spy1 = sinon.spy(d1, 'send')
d2 = new Device()
spy2 = sinon.spy(d2, 'send')
sinon.stub(Device, 'findQ').returns( Q([d1, d2]) )
user.push().then ->
spy1.calledOnce.should.be.true
spy2.calledOnce.should.be.true
Device.findQ.restore()
done()
describe 'Groups', ->
it 'should throw when not found', ->
(-> user.leave(new Group())).should.throw /Not Found/
it 'should leave a group', ->
user.groups.should.have.length 0
group = new Group()
user.groups.push group
user.groups.should.have.length 1
user.leave group
user.groups.should.have.length 0
user.leftGroups.should.have.length 1
it 'should add a group', ->
user.groups.should.have.length 0
group = new Group()
user.add group
user.groups.should.have.length 1
it 'should not add a group twice', ->
user.groups.should.have.length 0
group = new Group()
user.add group
(-> user.add(group)).should.throw /cannot be readded/
it 'should not allow a user to be added to a group they left', ->
user.groups.should.have.length 0
group = new Group()
user.add group
user.leave group
(-> user.add(group)).should.throw /cannot be readded/
it 'should returns no if nothing is passed in', ->
user.hasGroup().should.be.no
it 'should return no if it is not an object id', ->
user.hasGroup('dkfjdsf').should.be.no
it 'should return no if the user does not have the group', ->
user.hasGroup(new ObjectId()).should.be.no
it 'should return yes when they have the group', ->
group = new Group()
id = group._id
user.groups.push group
user.hasGroup(id).should.be.yes
describe 'Logout', ->
it 'should remove the one token', (done)->
user.username = 'test123'
user.password = 'testing'
user.accessToken = [
'111'
'222'
'333'
'444'
'555'
]
sinon.stub(Device, 'findQ').returns( Q([]) )
user.logout('111').then ->
user.accessToken.should.have.length 4
User.findOneQ(username: 'test123').then (u)->
should.exist u
u.accessToken.should.have.length 4
Device.findQ.restore()
done()
it 'should remove all the tokens', (done)->
user.username = 'test1234'
user.password = 'testing'
user.accessToken = [
'111'
'222'
'333'
'444'
'555'
]
sinon.stub(Device, 'findQ').returns( Q([new Device()]) )
user.logout('111', yes).then ->
user.accessToken.should.have.length 0
User.findOneQ(username: 'test1234').then (u)->
should.exist u
u.accessToken.should.have.length 0
Device.findQ.restore()
done()
describe 'Avatars', ->
upload =
path: './test/integration/test_image.png'
headers:
'content-type': 'image/png'
bytes: 7762
it 'should throw an error with no files', ->
(-> user.uploadAvatar()).should.throw /No files were found/
avatarId = null
it 'should upload the avatar', (done)->
return done() unless AvatarTests
user.username = 'uploader'
user.password = 'testing'
should.not.exist user.avatar
user.uploadAvatar(upload).then ->
should.exist user.avatar
avatarId = user.avatar
done()
.done()
it 'should throw without an avatar', ->
(-> user.getAvatar()).should.throw /Not Found/
it 'should pull down the avatar', (done)->
return done() unless AvatarTests
User.findOneQ(username: 'uploader').then (found)->
found.getAvatar()
.spread (type, data)->
should.exist type
should.exist data
type.should.equal 'image/jpeg'
done()
.done()
describe 'Registering', ->
it 'should throw without a username', ->
(-> User.register()).should.throw /Username is required/
it 'should throw without a password', ->
(-> User.register('username')).should.throw /Password is required/
it 'should throw with a bad username', ->
(-> User.register('GG no re', 'testing')).should.throw /Invalid username/
it 'should register the user', ->
User.register('hello', 'testing').then (found)->
found.username.should.equal 'hello'
should.exist found.password
it 'should throw when finding a nonexistent user', (done)->
User.findByLowercaseUsername('boby').catch (err)->
err.message.should.equal 'Unauthorized'
done()
.done()
it 'should find the user by lowercase', (done)->
return done() unless AvatarTests
User.findByLowercaseUsername('uploader').then (found)->
should.exist found
found.username.should.equal 'uploader'
done()
after ->
mongoose.disconnect()
| 13012 | 'use strict'
#
# FastChat
# 2015
#
require('../../lib/helpers/helpers')()
mongoose = require 'mongoose'
Q = require 'q'
sinon = require 'sinon'
ObjectId = mongoose.Types.ObjectId
should = require('chai').should()
User = require '../../lib/model/user'
Device = require '../../lib/model/device'
Group = require '../../lib/model/group'
AvatarTests = process.env.AWS_KEY? and process.env.AWS_SECRET?
describe 'User', ->
before (done)->
mongoose.connect 'mongodb://localhost/test'
db = mongoose.connection
db.once 'open', ->
User.removeQ({}).then -> done()
user = null
beforeEach ->
user = new User()
describe 'Model', ->
it 'should be a user', ->
user = new User()
(user instanceof User).should.be.ok
describe 'Authentication', ->
it 'should hash the password', (done)->
user.username = 'hey'
user.password = '<PASSWORD>'
user.saveQ().then ->
user.password.should.not.equal '<PASSWORD>'
done()
it 'should make a random token', ->
user = new User()
result = user.generateRandomToken()
should.exist result
it 'should compare correct passwords', (done)->
user.username = 'hey0'
user.password = '<PASSWORD>'
user.saveQ().then ->
user.comparePassword('testing')
.then (matched)->
should.exist matched
matched.should.be.true
done()
it 'should compare incorrect passwords', (done)->
user.username = 'heyo'
user.password = '<PASSWORD>'
user.saveQ().then ->
user.comparePassword('<PASSWORD>')
.catch (err)->
err.message.should.equal 'Incorrect username or password'
done()
describe 'Push', ->
it 'should push to all the users devices', (done)->
d1 = new Device()
spy1 = sinon.spy(d1, 'send')
d2 = new Device()
spy2 = sinon.spy(d2, 'send')
sinon.stub(Device, 'findQ').returns( Q([d1, d2]) )
user.push().then ->
spy1.calledOnce.should.be.true
spy2.calledOnce.should.be.true
Device.findQ.restore()
done()
describe 'Groups', ->
it 'should throw when not found', ->
(-> user.leave(new Group())).should.throw /Not Found/
it 'should leave a group', ->
user.groups.should.have.length 0
group = new Group()
user.groups.push group
user.groups.should.have.length 1
user.leave group
user.groups.should.have.length 0
user.leftGroups.should.have.length 1
it 'should add a group', ->
user.groups.should.have.length 0
group = new Group()
user.add group
user.groups.should.have.length 1
it 'should not add a group twice', ->
user.groups.should.have.length 0
group = new Group()
user.add group
(-> user.add(group)).should.throw /cannot be readded/
it 'should not allow a user to be added to a group they left', ->
user.groups.should.have.length 0
group = new Group()
user.add group
user.leave group
(-> user.add(group)).should.throw /cannot be readded/
it 'should returns no if nothing is passed in', ->
user.hasGroup().should.be.no
it 'should return no if it is not an object id', ->
user.hasGroup('dkfjdsf').should.be.no
it 'should return no if the user does not have the group', ->
user.hasGroup(new ObjectId()).should.be.no
it 'should return yes when they have the group', ->
group = new Group()
id = group._id
user.groups.push group
user.hasGroup(id).should.be.yes
describe 'Logout', ->
it 'should remove the one token', (done)->
user.username = 'test123'
user.password = '<PASSWORD>'
user.accessToken = [
'1<PASSWORD>'
'222'
'333'
'444'
'555'
]
sinon.stub(Device, 'findQ').returns( Q([]) )
user.logout('111').then ->
user.accessToken.should.have.length 4
User.findOneQ(username: 'test123').then (u)->
should.exist u
u.accessToken.should.have.length 4
Device.findQ.restore()
done()
it 'should remove all the tokens', (done)->
user.username = 'test1234'
user.password = '<PASSWORD>'
user.accessToken = [
'111'
'222'
'333'
'444'
'555'
]
sinon.stub(Device, 'findQ').returns( Q([new Device()]) )
user.logout('111', yes).then ->
user.accessToken.should.have.length 0
User.findOneQ(username: 'test1234').then (u)->
should.exist u
u.accessToken.should.have.length 0
Device.findQ.restore()
done()
describe 'Avatars', ->
upload =
path: './test/integration/test_image.png'
headers:
'content-type': 'image/png'
bytes: 7762
it 'should throw an error with no files', ->
(-> user.uploadAvatar()).should.throw /No files were found/
avatarId = null
it 'should upload the avatar', (done)->
return done() unless AvatarTests
user.username = 'uploader'
user.password = '<PASSWORD>'
should.not.exist user.avatar
user.uploadAvatar(upload).then ->
should.exist user.avatar
avatarId = user.avatar
done()
.done()
it 'should throw without an avatar', ->
(-> user.getAvatar()).should.throw /Not Found/
it 'should pull down the avatar', (done)->
return done() unless AvatarTests
User.findOneQ(username: 'uploader').then (found)->
found.getAvatar()
.spread (type, data)->
should.exist type
should.exist data
type.should.equal 'image/jpeg'
done()
.done()
describe 'Registering', ->
it 'should throw without a username', ->
(-> User.register()).should.throw /Username is required/
it 'should throw without a password', ->
(-> User.register('username')).should.throw /Password is required/
it 'should throw with a bad username', ->
(-> User.register('GG no re', 'testing')).should.throw /Invalid username/
it 'should register the user', ->
User.register('hello', 'testing').then (found)->
found.username.should.equal 'hello'
should.exist found.password
it 'should throw when finding a nonexistent user', (done)->
User.findByLowercaseUsername('boby').catch (err)->
err.message.should.equal 'Unauthorized'
done()
.done()
it 'should find the user by lowercase', (done)->
return done() unless AvatarTests
User.findByLowercaseUsername('uploader').then (found)->
should.exist found
found.username.should.equal 'uploader'
done()
after ->
mongoose.disconnect()
| true | 'use strict'
#
# FastChat
# 2015
#
require('../../lib/helpers/helpers')()
mongoose = require 'mongoose'
Q = require 'q'
sinon = require 'sinon'
ObjectId = mongoose.Types.ObjectId
should = require('chai').should()
User = require '../../lib/model/user'
Device = require '../../lib/model/device'
Group = require '../../lib/model/group'
AvatarTests = process.env.AWS_KEY? and process.env.AWS_SECRET?
describe 'User', ->
before (done)->
mongoose.connect 'mongodb://localhost/test'
db = mongoose.connection
db.once 'open', ->
User.removeQ({}).then -> done()
user = null
beforeEach ->
user = new User()
describe 'Model', ->
it 'should be a user', ->
user = new User()
(user instanceof User).should.be.ok
describe 'Authentication', ->
it 'should hash the password', (done)->
user.username = 'hey'
user.password = 'PI:PASSWORD:<PASSWORD>END_PI'
user.saveQ().then ->
user.password.should.not.equal 'PI:PASSWORD:<PASSWORD>END_PI'
done()
it 'should make a random token', ->
user = new User()
result = user.generateRandomToken()
should.exist result
it 'should compare correct passwords', (done)->
user.username = 'hey0'
user.password = 'PI:PASSWORD:<PASSWORD>END_PI'
user.saveQ().then ->
user.comparePassword('testing')
.then (matched)->
should.exist matched
matched.should.be.true
done()
it 'should compare incorrect passwords', (done)->
user.username = 'heyo'
user.password = 'PI:PASSWORD:<PASSWORD>END_PI'
user.saveQ().then ->
user.comparePassword('PI:PASSWORD:<PASSWORD>END_PI')
.catch (err)->
err.message.should.equal 'Incorrect username or password'
done()
describe 'Push', ->
it 'should push to all the users devices', (done)->
d1 = new Device()
spy1 = sinon.spy(d1, 'send')
d2 = new Device()
spy2 = sinon.spy(d2, 'send')
sinon.stub(Device, 'findQ').returns( Q([d1, d2]) )
user.push().then ->
spy1.calledOnce.should.be.true
spy2.calledOnce.should.be.true
Device.findQ.restore()
done()
describe 'Groups', ->
it 'should throw when not found', ->
(-> user.leave(new Group())).should.throw /Not Found/
it 'should leave a group', ->
user.groups.should.have.length 0
group = new Group()
user.groups.push group
user.groups.should.have.length 1
user.leave group
user.groups.should.have.length 0
user.leftGroups.should.have.length 1
it 'should add a group', ->
user.groups.should.have.length 0
group = new Group()
user.add group
user.groups.should.have.length 1
it 'should not add a group twice', ->
user.groups.should.have.length 0
group = new Group()
user.add group
(-> user.add(group)).should.throw /cannot be readded/
it 'should not allow a user to be added to a group they left', ->
user.groups.should.have.length 0
group = new Group()
user.add group
user.leave group
(-> user.add(group)).should.throw /cannot be readded/
it 'should returns no if nothing is passed in', ->
user.hasGroup().should.be.no
it 'should return no if it is not an object id', ->
user.hasGroup('dkfjdsf').should.be.no
it 'should return no if the user does not have the group', ->
user.hasGroup(new ObjectId()).should.be.no
it 'should return yes when they have the group', ->
group = new Group()
id = group._id
user.groups.push group
user.hasGroup(id).should.be.yes
describe 'Logout', ->
it 'should remove the one token', (done)->
user.username = 'test123'
user.password = 'PI:PASSWORD:<PASSWORD>END_PI'
user.accessToken = [
'1PI:PASSWORD:<PASSWORD>END_PI'
'222'
'333'
'444'
'555'
]
sinon.stub(Device, 'findQ').returns( Q([]) )
user.logout('111').then ->
user.accessToken.should.have.length 4
User.findOneQ(username: 'test123').then (u)->
should.exist u
u.accessToken.should.have.length 4
Device.findQ.restore()
done()
it 'should remove all the tokens', (done)->
user.username = 'test1234'
user.password = 'PI:PASSWORD:<PASSWORD>END_PI'
user.accessToken = [
'111'
'222'
'333'
'444'
'555'
]
sinon.stub(Device, 'findQ').returns( Q([new Device()]) )
user.logout('111', yes).then ->
user.accessToken.should.have.length 0
User.findOneQ(username: 'test1234').then (u)->
should.exist u
u.accessToken.should.have.length 0
Device.findQ.restore()
done()
describe 'Avatars', ->
upload =
path: './test/integration/test_image.png'
headers:
'content-type': 'image/png'
bytes: 7762
it 'should throw an error with no files', ->
(-> user.uploadAvatar()).should.throw /No files were found/
avatarId = null
it 'should upload the avatar', (done)->
return done() unless AvatarTests
user.username = 'uploader'
user.password = 'PI:PASSWORD:<PASSWORD>END_PI'
should.not.exist user.avatar
user.uploadAvatar(upload).then ->
should.exist user.avatar
avatarId = user.avatar
done()
.done()
it 'should throw without an avatar', ->
(-> user.getAvatar()).should.throw /Not Found/
it 'should pull down the avatar', (done)->
return done() unless AvatarTests
User.findOneQ(username: 'uploader').then (found)->
found.getAvatar()
.spread (type, data)->
should.exist type
should.exist data
type.should.equal 'image/jpeg'
done()
.done()
describe 'Registering', ->
it 'should throw without a username', ->
(-> User.register()).should.throw /Username is required/
it 'should throw without a password', ->
(-> User.register('username')).should.throw /Password is required/
it 'should throw with a bad username', ->
(-> User.register('GG no re', 'testing')).should.throw /Invalid username/
it 'should register the user', ->
User.register('hello', 'testing').then (found)->
found.username.should.equal 'hello'
should.exist found.password
it 'should throw when finding a nonexistent user', (done)->
User.findByLowercaseUsername('boby').catch (err)->
err.message.should.equal 'Unauthorized'
done()
.done()
it 'should find the user by lowercase', (done)->
return done() unless AvatarTests
User.findByLowercaseUsername('uploader').then (found)->
should.exist found
found.username.should.equal 'uploader'
done()
after ->
mongoose.disconnect()
|
[
{
"context": " 'mock-region'\r\n credentials:\r\n accessKeyId: 'akid'\r\n secretAccessKey: 'secret'\r\n\r\n# Disable setT",
"end": 433,
"score": 0.9911525249481201,
"start": 429,
"tag": "KEY",
"value": "akid"
},
{
"context": ":\r\n accessKeyId: 'akid'\r\n secretAccessKey... | node_modules/sqlite3/node_modules/node-pre-gyp/node_modules/aws-sdk/test/helpers.coffee | xhhjin/heroku-ghost | 0 | AWS = null
ignoreRequire = require
if typeof window == 'undefined'
AWS = ignoreRequire('../lib/aws')
else
AWS = window.AWS
EventEmitter = require('events').EventEmitter
Buffer = AWS.util.Buffer
semver = require('semver')
require('util').print = (data) ->
process.stdout.write(data)
# Mock credentials
AWS.config.update
paramValidation: false
region: 'mock-region'
credentials:
accessKeyId: 'akid'
secretAccessKey: 'secret'
# Disable setTimeout for tests
# Warning: this might cause unpredictable results
# TODO: refactor this out.
`setTimeout = function(fn, delay) { fn(); }`
flattenXML = (xml) ->
if (!xml)
return xml
xml.split("\n").join(''). # remove newlines
replace(/>\s+</g, '><'). # prunes whitespace between elements
replace(/^\s+|\s+$/g, '') # trims whitespace from ends
matchXML = (xml1, xml2) ->
expect(flattenXML(xml1)).toEqual(flattenXML(xml2))
MockService = AWS.Service.defineService 'mockService',
serviceIdentifier: 'mock'
initialize: (config) ->
AWS.Service.prototype.initialize.call(this, config)
@config.credentials = accessKeyId: 'akid', secretAccessKey: 'secret'
@config.region = 'mock-region'
setupRequestListeners: (request) ->
request.on 'extractData', (resp) ->
resp.data = resp.httpResponse.body.toString()
request.on 'extractError', (resp) ->
resp.error =
code: resp.httpResponse.body.toString() || resp.httpResponse.statusCode
message: null
api:
endpointPrefix: 'mockservice'
signatureVersion: 'v4'
mockHttpSuccessfulResponse = (status, headers, data, cb) ->
if !Array.isArray(data)
data = [data]
httpResp = new EventEmitter()
httpResp.statusCode = status
httpResp.headers = headers
httpResp.read = ->
if data.length > 0
chunk = data.shift()
if chunk is null
null
else
new Buffer(chunk)
else
null
cb(httpResp)
httpResp.emit('headers', status, headers)
AWS.util.arrayEach data.slice(), (str) ->
if AWS.util.isNode() && (httpResp._events.readable || semver.gt(process.version, 'v0.11.3'))
httpResp.emit('readable')
else
httpResp.emit('data', new Buffer(str))
if httpResp._events['readable'] || httpResp._events['data']
httpResp.emit('end')
else
httpResp.emit('aborted')
mockHttpResponse = (status, headers, data) ->
stream = new EventEmitter()
stream.setMaxListeners(0)
spyOn(AWS.HttpClient, 'getInstance')
AWS.HttpClient.getInstance.andReturn handleRequest: (req, opts, cb, errCb) ->
if typeof status == 'number'
mockHttpSuccessfulResponse status, headers, data, cb
else
errCb(status)
stream
return stream
mockIntermittentFailureResponse = (numFailures, status, headers, data) ->
retryCount = 0
spyOn(AWS.HttpClient, 'getInstance')
AWS.HttpClient.getInstance.andReturn handleRequest: (req, opts, cb, errCb) ->
if retryCount < numFailures
retryCount += 1
errCb code: 'NetworkingError', message: 'FAIL!'
else
statusCode = retryCount < numFailures ? 500 : status
mockHttpSuccessfulResponse statusCode, headers, data, cb
new EventEmitter()
module.exports =
AWS: AWS
matchXML: matchXML
mockHttpResponse: mockHttpResponse
mockIntermittentFailureResponse: mockIntermittentFailureResponse
mockHttpSuccessfulResponse: mockHttpSuccessfulResponse
MockService: MockService
| 202599 | AWS = null
ignoreRequire = require
if typeof window == 'undefined'
AWS = ignoreRequire('../lib/aws')
else
AWS = window.AWS
EventEmitter = require('events').EventEmitter
Buffer = AWS.util.Buffer
semver = require('semver')
require('util').print = (data) ->
process.stdout.write(data)
# Mock credentials
AWS.config.update
paramValidation: false
region: 'mock-region'
credentials:
accessKeyId: '<KEY>'
secretAccessKey: '<KEY>'
# Disable setTimeout for tests
# Warning: this might cause unpredictable results
# TODO: refactor this out.
`setTimeout = function(fn, delay) { fn(); }`
flattenXML = (xml) ->
if (!xml)
return xml
xml.split("\n").join(''). # remove newlines
replace(/>\s+</g, '><'). # prunes whitespace between elements
replace(/^\s+|\s+$/g, '') # trims whitespace from ends
matchXML = (xml1, xml2) ->
expect(flattenXML(xml1)).toEqual(flattenXML(xml2))
MockService = AWS.Service.defineService 'mockService',
serviceIdentifier: 'mock'
initialize: (config) ->
AWS.Service.prototype.initialize.call(this, config)
@config.credentials = accessKeyId: '<KEY>', secretAccessKey: '<KEY>'
@config.region = 'mock-region'
setupRequestListeners: (request) ->
request.on 'extractData', (resp) ->
resp.data = resp.httpResponse.body.toString()
request.on 'extractError', (resp) ->
resp.error =
code: resp.httpResponse.body.toString() || resp.httpResponse.statusCode
message: null
api:
endpointPrefix: 'mockservice'
signatureVersion: 'v4'
mockHttpSuccessfulResponse = (status, headers, data, cb) ->
if !Array.isArray(data)
data = [data]
httpResp = new EventEmitter()
httpResp.statusCode = status
httpResp.headers = headers
httpResp.read = ->
if data.length > 0
chunk = data.shift()
if chunk is null
null
else
new Buffer(chunk)
else
null
cb(httpResp)
httpResp.emit('headers', status, headers)
AWS.util.arrayEach data.slice(), (str) ->
if AWS.util.isNode() && (httpResp._events.readable || semver.gt(process.version, 'v0.11.3'))
httpResp.emit('readable')
else
httpResp.emit('data', new Buffer(str))
if httpResp._events['readable'] || httpResp._events['data']
httpResp.emit('end')
else
httpResp.emit('aborted')
mockHttpResponse = (status, headers, data) ->
stream = new EventEmitter()
stream.setMaxListeners(0)
spyOn(AWS.HttpClient, 'getInstance')
AWS.HttpClient.getInstance.andReturn handleRequest: (req, opts, cb, errCb) ->
if typeof status == 'number'
mockHttpSuccessfulResponse status, headers, data, cb
else
errCb(status)
stream
return stream
mockIntermittentFailureResponse = (numFailures, status, headers, data) ->
retryCount = 0
spyOn(AWS.HttpClient, 'getInstance')
AWS.HttpClient.getInstance.andReturn handleRequest: (req, opts, cb, errCb) ->
if retryCount < numFailures
retryCount += 1
errCb code: 'NetworkingError', message: 'FAIL!'
else
statusCode = retryCount < numFailures ? 500 : status
mockHttpSuccessfulResponse statusCode, headers, data, cb
new EventEmitter()
module.exports =
AWS: AWS
matchXML: matchXML
mockHttpResponse: mockHttpResponse
mockIntermittentFailureResponse: mockIntermittentFailureResponse
mockHttpSuccessfulResponse: mockHttpSuccessfulResponse
MockService: MockService
| true | AWS = null
ignoreRequire = require
if typeof window == 'undefined'
AWS = ignoreRequire('../lib/aws')
else
AWS = window.AWS
EventEmitter = require('events').EventEmitter
Buffer = AWS.util.Buffer
semver = require('semver')
require('util').print = (data) ->
process.stdout.write(data)
# Mock credentials
AWS.config.update
paramValidation: false
region: 'mock-region'
credentials:
accessKeyId: 'PI:KEY:<KEY>END_PI'
secretAccessKey: 'PI:KEY:<KEY>END_PI'
# Disable setTimeout for tests
# Warning: this might cause unpredictable results
# TODO: refactor this out.
`setTimeout = function(fn, delay) { fn(); }`
flattenXML = (xml) ->
if (!xml)
return xml
xml.split("\n").join(''). # remove newlines
replace(/>\s+</g, '><'). # prunes whitespace between elements
replace(/^\s+|\s+$/g, '') # trims whitespace from ends
matchXML = (xml1, xml2) ->
expect(flattenXML(xml1)).toEqual(flattenXML(xml2))
MockService = AWS.Service.defineService 'mockService',
serviceIdentifier: 'mock'
initialize: (config) ->
AWS.Service.prototype.initialize.call(this, config)
@config.credentials = accessKeyId: 'PI:KEY:<KEY>END_PI', secretAccessKey: 'PI:KEY:<KEY>END_PI'
@config.region = 'mock-region'
setupRequestListeners: (request) ->
request.on 'extractData', (resp) ->
resp.data = resp.httpResponse.body.toString()
request.on 'extractError', (resp) ->
resp.error =
code: resp.httpResponse.body.toString() || resp.httpResponse.statusCode
message: null
api:
endpointPrefix: 'mockservice'
signatureVersion: 'v4'
mockHttpSuccessfulResponse = (status, headers, data, cb) ->
if !Array.isArray(data)
data = [data]
httpResp = new EventEmitter()
httpResp.statusCode = status
httpResp.headers = headers
httpResp.read = ->
if data.length > 0
chunk = data.shift()
if chunk is null
null
else
new Buffer(chunk)
else
null
cb(httpResp)
httpResp.emit('headers', status, headers)
AWS.util.arrayEach data.slice(), (str) ->
if AWS.util.isNode() && (httpResp._events.readable || semver.gt(process.version, 'v0.11.3'))
httpResp.emit('readable')
else
httpResp.emit('data', new Buffer(str))
if httpResp._events['readable'] || httpResp._events['data']
httpResp.emit('end')
else
httpResp.emit('aborted')
mockHttpResponse = (status, headers, data) ->
stream = new EventEmitter()
stream.setMaxListeners(0)
spyOn(AWS.HttpClient, 'getInstance')
AWS.HttpClient.getInstance.andReturn handleRequest: (req, opts, cb, errCb) ->
if typeof status == 'number'
mockHttpSuccessfulResponse status, headers, data, cb
else
errCb(status)
stream
return stream
mockIntermittentFailureResponse = (numFailures, status, headers, data) ->
retryCount = 0
spyOn(AWS.HttpClient, 'getInstance')
AWS.HttpClient.getInstance.andReturn handleRequest: (req, opts, cb, errCb) ->
if retryCount < numFailures
retryCount += 1
errCb code: 'NetworkingError', message: 'FAIL!'
else
statusCode = retryCount < numFailures ? 500 : status
mockHttpSuccessfulResponse statusCode, headers, data, cb
new EventEmitter()
module.exports =
AWS: AWS
matchXML: matchXML
mockHttpResponse: mockHttpResponse
mockIntermittentFailureResponse: mockIntermittentFailureResponse
mockHttpSuccessfulResponse: mockHttpSuccessfulResponse
MockService: MockService
|
[
{
"context": "\n Nick Schrock\n </d",
"end": 17184,
"score": 0.9984708428382874,
"start": 17172,
"tag": "NAME",
"value": "Nick Schrock"
},
{
"context": "\n ... | src/pagedraw/landingdesktop.cjsx | hanhaihome/pagedraw | 3 | # Generated by https://pagedraw.io/pages/5249
React = require 'react'
createReactClass = require 'create-react-class'
Landingtopbar = require './landingtopbar'
Demobutton = require './demobutton'
Button = require './button'
Demopills = require './demopills'
Comparisontable = require './comparisontable'
Landingfooter = require './landingfooter'
module.exports = Landingdesktop = createReactClass {
displayName: 'Landingdesktop'
render: ->
<div style={{"display": "flex", "flexDirection": "column", "flexGrow": "1", "background": "rgb(255, 255, 255)", "minHeight": "100vh"}}>
<style dangerouslySetInnerHTML={__html: """
@import url('https://fonts.googleapis.com/css?family=Lato:|Lato:300');
* {
box-sizing: border-box;
}
body {
margin: 0;
}
button:hover {
cursor: pointer;
}
a {
text-decoration: none;
color: inherit;
}
.pd-onhover-parent >.pd-onhover {
display: none;
}
.pd-onhover-parent:hover > * {
display: none;
}
.pd-onhover-parent:hover > .pd-onhover {
display: flex;
}
.pd-onactive-parent > .pd-onactive {
display: none;
}
.pd-onactive-parent:active > * {
display: none;
}
.pd-onactive-parent:active > .pd-onactive {
display: flex;
}
.pd-onactive-parent.pd-onhover-parent:active > .pd-onhover {
display: none;
}
"""} />
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"display": "flex", "flexDirection": "column", "flexGrow": "1", "flexBasis": 0, "minHeight": "fit-content", "paddingTop": 36, "background": "rgb(42, 42, 89)"}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"height": 0, "flexGrow": "0.5011389521640092", "flexBasis": 0}} />
<div style={{"display": "flex", "flexDirection": "column"}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"flexShrink": "0", "display": "flex", "flexDirection": "column", "minWidth": 1001}}>
<Landingtopbar white={true} />
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 84}}>
<div style={{"width": 1001, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgb(255, 255, 255)", "fontSize": 50, "lineHeight": "50px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
The best UI builder for the web. Open source
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 35, "paddingLeft": 53, "paddingRight": 53}}>
<div style={{"width": 895, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgba(255, 255, 255, 0.7)", "fontSize": 19, "lineHeight": "22px", "letterSpacing": 0, "fontWeight": "300", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
{"Draw your React components, but use them like components coded manually. Already have mockups drawn? Just import them from Sketch or Figma."}
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 49, "paddingLeft": 84, "paddingRight": 48}}>
<div style={{"flexShrink": "0", "display": "flex", "flexDirection": "column", "minWidth": 354}}>
<Demobutton selected={true} content={"Pagedraw for a component named \"MainScreen\""} />
</div>
<div style={{"flexShrink": "0", "marginLeft": 204, "display": "flex", "flexDirection": "column", "minWidth": 311}}>
<Demobutton selected={true} content={"React code using that component"} />
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 21}}>
<div style={{"display": "flex", "flexDirection": "column", "paddingBottom": 3}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<img src="https://ucarecdn.com/cfba35fa-6c23-4bad-8554-df007a1e4f14/" style={{"width": 522, "height": 359, "flexShrink": "0", "borderWidth": 0}} />
</div>
</div>
<div style={{"display": "flex", "flexDirection": "column", "marginLeft": 72, "paddingTop": 2}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"width": 407, "height": 360, "flexShrink": "0", "display": "flex", "flexDirection": "column"}}>
{this.props.importPagedrawn}
</div>
</div>
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 66, "paddingLeft": 329, "paddingRight": 329}}>
<a href="/tutorials/basics" style={{"flexShrink": "0", "display": "flex"}}>
<div style={{"display": "flex", "flexDirection": "column", "minWidth": 343, "flexGrow": "1"}}>
<Button content={"Continue to demo →"} state={"Secondary"} />
</div>
</a>
</div>
</div>
<div style={{"height": 0, "flexGrow": "0.4988610478359909", "flexBasis": 0}} />
</div>
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"flexGrow": "1", "flexBasis": 0}}>
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1440 132" style={{"display": "block"}}>
<polygon points="0 132 1440 0 0 0" style={{"fill": "rgb(42, 42, 89)"}} />
</svg>
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"height": 0, "flexGrow": "0.375", "flexBasis": 0}} />
<div style={{"flexGrow": "0.25069444444444444", "flexBasis": 0, "fontFamily": "\"Lato\", sans-serif", "color": "rgb(0, 0, 31)", "fontSize": 40, "lineHeight": "50px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
Built for developers
</div>
<div style={{"height": 0, "flexGrow": "0.37430555555555556", "flexBasis": 0}} />
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 25}}>
<div style={{"height": 0, "flexGrow": "0.3034722222222222", "flexBasis": 0}} />
<div style={{"flexGrow": "0.3923611111111111", "flexBasis": 0, "fontFamily": "\"Lato\", sans-serif", "color": "rgba(0, 0, 31, 0.8)", "fontSize": 17, "lineHeight": "25.5px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
<div>{"Who need to deliver high-quality code faster than ever. Who don't want to have to think about CSS. Who need to use semantic, authentic HTML that integrates into their existing React codebase. "}</div>
<br/>
<div>{"We don't use a JS based layout engine, or ever make you ship extra dependencies. We'll never make your site slower, or fatter."}</div>
</div>
<div style={{"height": 0, "flexGrow": "0.30416666666666664", "flexBasis": 0}} />
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 52}}>
<div style={{"height": 0, "flexGrow": "0.5021459227467812", "flexBasis": 0}} />
<div style={{"display": "flex", "flexDirection": "column"}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"display": "flex", "flexDirection": "column"}}>
<div style={{"display": "flex", "flexShrink": "0", "paddingLeft": 144, "paddingRight": 160}}>
<div style={{"width": 142, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgba(6, 18, 44, 0.5)", "fontSize": 24, "lineHeight": "12px", "letterSpacing": 0.4000000059604645, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
works with
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 24, "paddingLeft": 79, "paddingRight": 80}}>
<div style={{"display": "flex", "flexDirection": "column", "paddingTop": 6}}>
<div style={{"display": "flex", "flexShrink": "0", "paddingLeft": 7, "paddingRight": 5}}>
<div style={{"display": "flex", "flexDirection": "column", "paddingTop": 10, "paddingBottom": 5}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<a href="https://reactjs.org/" target="_blank" style={{"flexShrink": "0", "display": "flex"}}>
<img src="https://pagedraw-images.s3.amazonaws.com/1786119702726483-1511943211646-D4982605-43E9-48EC-9604-858B5CF597D3.png" style={{"width": 66, "height": 55, "borderWidth": 0, "flexGrow": "1"}} />
</a>
</div>
</div>
<a href="https://www.figma.com/" target="_blank" style={{"flexShrink": "0", "marginLeft": 33, "display": "flex"}}>
<img src="https://ucarecdn.com/cdec4e4d-0f1b-4a53-99e4-20b2848ad39b/" style={{"width": 70, "height": 70, "borderWidth": 0, "flexGrow": "1"}} />
</a>
<div style={{"display": "flex", "flexDirection": "column", "marginLeft": 36, "paddingTop": 5, "paddingBottom": 5}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<a href="https://www.sketchapp.com/" target="_blank" style={{"flexShrink": "0", "display": "flex"}}>
<img src="https://ucarecdn.com/32701dc9-f7cf-4828-9f0a-b166cb8e38c8/" style={{"width": 70, "height": 60, "borderWidth": 0, "flexGrow": "1"}} />
</a>
</div>
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 8}}>
<div style={{"display": "flex", "flexDirection": "column", "paddingTop": 2}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"width": 80, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgb(0, 216, 255)", "fontSize": 16, "lineHeight": "18px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
React
</div>
</div>
</div>
<div style={{"display": "flex", "flexDirection": "column", "marginLeft": 22, "paddingBottom": 2}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"width": 78, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgba(0, 0, 32, 0.8)", "fontSize": 16, "lineHeight": "18px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
Figma
</div>
</div>
</div>
<div style={{"display": "flex", "flexDirection": "column", "marginLeft": 27, "paddingTop": 2}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"width": 80, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgba(0, 0, 32, 0.8)", "fontSize": 16, "lineHeight": "18px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
Sketch
</div>
</div>
</div>
</div>
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 36}}>
<div style={{"display": "flex", "flexDirection": "column", "paddingTop": 46, "paddingBottom": 22, "borderRadius": 10, "boxShadow": "0px 5px 15px 0px rgba(0,0,0,0.07), 0px 15px 35px 0px rgba(50,50,93,0.10)", "background": "rgb(255, 255, 255)"}}>
<div style={{"display": "flex", "flexShrink": "0", "paddingLeft": 20, "paddingRight": 33}}>
<div style={{"width": 393, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgba(0, 0, 32, 0.8)", "fontSize": 17, "lineHeight": "25.5px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
{"\“This is the one that actually works.\” "}
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 38, "paddingLeft": 64, "paddingRight": 82}}>
<div style={{"display": "flex", "flexDirection": "column", "paddingTop": 1, "paddingBottom": 3}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<a href="http://graphql.org/" target="_blank" style={{"flexShrink": "0", "display": "flex"}}>
<img src="https://ucarecdn.com/0a12e233-3a96-4b5b-8566-816c0448d035/" style={{"width": 101, "height": 35, "borderWidth": 0, "flexGrow": "1"}} />
</a>
</div>
</div>
<div style={{"display": "flex", "flexDirection": "column", "marginLeft": 19}}>
<div style={{"display": "flex", "flexShrink": "0", "paddingRight": 53}}>
<div style={{"width": 127, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgb(0, 0, 32)", "fontSize": 15, "lineHeight": "18.75px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "left", "wordWrap": "break-word"}}>
Nick Schrock
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 3}}>
<div style={{"width": 180, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgba(0, 0, 32, 0.5)", "fontSize": 15, "lineHeight": "18.75px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "left", "wordWrap": "break-word"}}>
Co-creator of GraphQL
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div style={{"display": "flex", "flexDirection": "column", "marginLeft": 56}}>
<div style={{"display": "flex", "flexShrink": "0", "paddingLeft": 164, "paddingRight": 148}}>
<div style={{"width": 160, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgba(6, 18, 44, 0.5)", "fontSize": 24, "lineHeight": "12px", "letterSpacing": 0.4000000059604645, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
coming soon
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 30, "paddingLeft": 102, "paddingRight": 88}}>
<div style={{"display": "flex", "flexDirection": "column", "paddingTop": 5}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<img src="https://pagedraw-images.s3.amazonaws.com/1786119702726483-1511943211646-D4982605-43E9-48EC-9604-858B5CF597D3.png" style={{"width": 66, "height": 55, "flexShrink": "0", "borderWidth": 0}} />
</div>
</div>
<a href="https://vuejs.org/" target="_blank" style={{"flexShrink": "0", "marginLeft": 48, "display": "flex"}}>
<img src="https://ucarecdn.com/5a8da673-8daf-478f-9a30-7cf507808db9/" style={{"width": 60, "height": 60, "borderWidth": 0, "flexGrow": "1"}} />
</a>
<a href="https://angular.io/" target="_blank" style={{"flexShrink": "0", "marginLeft": 48, "display": "flex"}}>
<img src="https://ucarecdn.com/55e6c57d-d7f1-4834-8e1c-160bf9b5dc05/" style={{"width": 60, "height": 60, "borderWidth": 0, "flexGrow": "1"}} />
</a>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 17, "paddingLeft": 78, "paddingRight": 78}}>
<div style={{"display": "flex", "flexDirection": "column", "paddingBottom": 2}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"width": 115, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgb(0, 216, 255)", "fontSize": 16, "lineHeight": "18px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
React Native
</div>
</div>
</div>
<div style={{"display": "flex", "flexDirection": "column", "marginLeft": 13, "paddingBottom": 2}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"width": 80, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgba(0, 0, 32, 0.8)", "fontSize": 16, "lineHeight": "18px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
Vue
</div>
</div>
</div>
<div style={{"display": "flex", "flexDirection": "column", "marginLeft": 28, "paddingTop": 2}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"width": 80, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgba(0, 0, 32, 0.8)", "fontSize": 16, "lineHeight": "18px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
Angular
</div>
</div>
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 37, "paddingLeft": 26}}>
<div style={{"display": "flex", "flexDirection": "column", "paddingTop": 20, "paddingBottom": 14, "borderRadius": 10, "boxShadow": "0px 5px 15px 0px rgba(0,0,0,0.07), 0px 15px 35px 0px rgba(50,50,93,0.10)", "background": "rgb(255, 255, 255)"}}>
<div style={{"display": "flex", "flexShrink": "0", "paddingLeft": 20, "paddingRight": 25}}>
<div style={{"width": 401, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgba(0, 0, 32, 0.8)", "fontSize": 17, "lineHeight": "25.5px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
{"\“We've built over 3 different dashboards in very little time using Pagedraw. What used to take a sprint now takes only a couple of days.\” "}
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 23, "paddingLeft": 84, "paddingRight": 61}}>
<div style={{"display": "flex", "flexDirection": "column", "paddingTop": 1, "paddingBottom": 4}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<a href="https://getrileynow.com" target="_blank" style={{"flexShrink": "0", "display": "flex"}}>
<img src="https://ucarecdn.com/1e305a79-4529-46dc-ba03-3e67b74fb3f4/" style={{"width": 97, "height": 33, "borderWidth": 0, "flexGrow": "1"}} />
</a>
</div>
</div>
<div style={{"display": "flex", "flexDirection": "column", "marginLeft": 19}}>
<div style={{"display": "flex", "flexShrink": "0", "paddingRight": 50}}>
<div style={{"width": 135, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgb(0, 0, 32)", "fontSize": 15, "lineHeight": "18.75px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "left", "wordWrap": "break-word"}}>
Helson Taveras
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 2}}>
<div style={{"width": 185, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgba(0, 0, 32, 0.5)", "fontSize": 15, "lineHeight": "18.75px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "left", "wordWrap": "break-word"}}>
{"Cofounder & CTO of Riley"}
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 45}}>
<div style={{"display": "flex", "flexDirection": "column", "paddingTop": 29, "paddingBottom": 22, "borderRadius": 10, "boxShadow": "0px 5px 15px 0px rgba(0,0,0,0.07), 0px 15px 35px 0px rgba(50,50,93,0.10)", "background": "rgb(255, 255, 255)"}}>
<div style={{"display": "flex", "flexShrink": "0", "paddingLeft": 20, "paddingRight": 33}}>
<div style={{"width": 393, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgba(0, 0, 32, 0.8)", "fontSize": 17, "lineHeight": "25.5px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
{"\"Pagedraw is perhaps the most ambitious WYSIWYG editor for React apps.\" "}
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 30, "paddingLeft": 122, "paddingRight": 60}}>
<div style={{"display": "flex", "flexDirection": "column", "paddingTop": 3}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<img src="https://pagedraw-images.s3.amazonaws.com/1786119702726483-1511943211646-D4982605-43E9-48EC-9604-858B5CF597D3.png" style={{"width": 40, "height": 36, "flexShrink": "0", "borderWidth": 0}} />
</div>
</div>
<div style={{"display": "flex", "flexDirection": "column", "marginLeft": 22}}>
<div style={{"display": "flex", "flexShrink": "0", "paddingRight": 75}}>
<div style={{"width": 127, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgb(0, 0, 32)", "fontSize": 15, "lineHeight": "18.75px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "left", "wordWrap": "break-word"}}>
Pete Hunt
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 3}}>
<div style={{"width": 202, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgba(0, 0, 32, 0.5)", "fontSize": 15, "lineHeight": "18.75px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "left", "wordWrap": "break-word"}}>
Co-creator of React.js
</div>
</div>
</div>
</div>
</div>
<div style={{"display": "flex", "flexDirection": "column", "marginLeft": 82, "paddingTop": 33, "paddingBottom": 22, "borderRadius": 10, "boxShadow": "0px 5px 15px 0px rgba(0,0,0,0.07), 0px 15px 35px 0px rgba(50,50,93,0.10)", "background": "rgb(255, 255, 255)"}}>
<div style={{"display": "flex", "flexShrink": "0", "paddingLeft": 20, "paddingRight": 33}}>
<div style={{"width": 393, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgba(0, 0, 32, 0.8)", "fontSize": 17, "lineHeight": "25.5px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
{"\“Really impressed with Pagedraw. Can’t wait for it to work with React Native as well.\”"}
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 26, "paddingLeft": 68, "paddingRight": 33}}>
<div style={{"display": "flex", "flexDirection": "column", "paddingTop": 6, "paddingBottom": 3}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<a href="https://expo.io/" style={{"flexShrink": "0", "display": "flex"}}>
<img src="https://ucarecdn.com/0e28dfd2-9ea1-4a04-bf11-2cd82be3d36c/" style={{"width": 105, "height": 30, "borderWidth": 0, "flexGrow": "1"}} />
</a>
</div>
</div>
<div style={{"display": "flex", "flexDirection": "column", "marginLeft": 11}}>
<div style={{"display": "flex", "flexShrink": "0", "paddingRight": 102}}>
<div style={{"width": 127, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgb(0, 0, 32)", "fontSize": 15, "lineHeight": "18.75px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "left", "wordWrap": "break-word"}}>
Charlie Cheever
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 3}}>
<div style={{"width": 229, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgba(0, 0, 32, 0.5)", "fontSize": 15, "lineHeight": "18.75px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "left", "wordWrap": "break-word"}}>
Cofounder of Quora and Expo.io
</div>
</div>
</div>
</div>
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 72, "paddingLeft": 255, "paddingRight": 254}}>
<a href="/tutorials/basics" style={{"flexShrink": "0", "display": "flex"}}>
<div style={{"display": "flex", "flexDirection": "column", "minWidth": 465, "flexGrow": "1"}}>
<Button content={"Try it out in browser →"} state={"Primary"} />
</div>
</a>
</div>
</div>
<div style={{"height": 0, "flexGrow": "0.4978540772532189", "flexBasis": 0}} />
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 87}}>
<div style={{"display": "flex", "flexDirection": "column", "flexGrow": "1", "flexBasis": 0, "minHeight": "fit-content", "paddingTop": 1, "background": "rgb(38, 38, 38)"}}>
<div style={{"display": "flex", "flexShrink": "0", "paddingLeft": 8}}>
<div style={{"height": 702, "flexGrow": "0.3058659217877095", "flexBasis": 0, "backgroundImage": "url('https://ucarecdn.com/900b6875-8bfb-4d24-9562-c0050bb955eb/')", "backgroundSize": "cover", "backgroundPosition": "center"}} />
<div style={{"height": 0, "flexGrow": "0.052374301675977654", "flexBasis": 0}} />
<div style={{"display": "flex", "flexDirection": "column", "flexGrow": "0.5349162011173184", "flexBasis": 0, "minHeight": "fit-content", "paddingTop": 101, "paddingBottom": 102}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"display": "flex", "flexDirection": "column", "flexGrow": "1", "flexBasis": 0, "minHeight": "fit-content"}}>
<div style={{"display": "flex", "flexShrink": "0", "paddingLeft": 28, "paddingRight": 27}}>
<div style={{"flexGrow": "1", "flexBasis": 0, "fontFamily": "\"Lato\", sans-serif", "color": "rgb(76, 253, 26)", "fontSize": 40, "lineHeight": "46px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "left", "wordWrap": "break-word"}}>
Redesign the green files in Pagedraw.
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 16, "paddingLeft": 28, "paddingRight": 27}}>
<div style={{"flexGrow": "1", "flexBasis": 0, "fontFamily": "Helvetica, Arial, sans-serif", "color": "rgb(222, 221, 221)", "fontSize": 17, "lineHeight": "25.5px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "left", "wordWrap": "break-word"}}>
<div>You edit them via Pagedraw editor, not by modifying the code. </div>
<br/>
<div>The Pagedraw CLI syncs Pagedraw docs with your codebase, so your localhost shows your latest designs, live, as you make them.</div>
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 57, "paddingLeft": 26, "paddingRight": 29}}>
<div style={{"flexGrow": "1", "flexBasis": 0, "fontFamily": "\"Lato\", sans-serif", "color": "rgb(179, 178, 178)", "fontSize": 40, "lineHeight": "46px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "left", "wordWrap": "break-word"}}>
Code the other files in your text editor.
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 24, "paddingLeft": 26}}>
<div style={{"flexGrow": "1", "flexBasis": 0, "fontFamily": "Helvetica, Arial, sans-serif", "color": "rgb(222, 221, 221)", "fontSize": 16, "lineHeight": "25.5px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "left", "wordWrap": "break-word"}}>
<div>{"These you edit with Sublime, Vim, your preference. Pagedraw doesn’t even know about them. They import the presentational components made in Pagedraw. "}</div>
<br/>
<div>These are your Redux containers, your React state management, and so on. If you have a design system or any components already done in code, Pagedraw docs can import them, too.</div>
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 35, "paddingLeft": 26, "paddingRight": 370}}>
<a href="/fiddle/DinV9PIR2Prt" style={{"flexShrink": "0", "display": "flex"}}>
<div style={{"display": "flex", "flexDirection": "column", "minWidth": 370, "flexGrow": "1"}}>
<Button content={"See integration example →"} state={"Primary"} />
</div>
</a>
</div>
</div>
</div>
</div>
<div style={{"height": 0, "flexGrow": "0.10684357541899442", "flexBasis": 0}} />
</div>
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 81, "justifyContent": "center"}}>
<div style={{"display": "flex", "flexDirection": "column", "paddingBottom": 1}}>
<div style={{"display": "flex", "flexShrink": "0", "paddingLeft": 148, "paddingRight": 149}}>
<div style={{"width": 705, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgb(0, 0, 31)", "fontSize": 40, "lineHeight": "50px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
Try without leaving your browser.
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 25, "paddingLeft": 218, "paddingRight": 219}}>
<div style={{"width": 565, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgba(0, 0, 31, 0.8)", "fontSize": 17, "lineHeight": "25.5px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
In this demo below you can change the design of the component on the left and modify the React code on the right side and see what happens live!
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 53, "paddingLeft": 1, "paddingRight": 1}}>
<div style={{"display": "flex", "flexDirection": "column"}}>
{this.props.pdPlayground}
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 50, "paddingLeft": 218, "paddingRight": 219}}>
<div style={{"width": 565, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgba(0, 0, 31, 0.8)", "fontSize": 17, "lineHeight": "25.5px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
Pagedraw generates code guaranteed to work correctly and in all browsers, which means less code in your codebase over which you have to worry about correctness and safety. It writes code just like we would by hand.
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 27, "paddingLeft": 268, "paddingRight": 269}}>
<a href="/tutorials/basics" style={{"flexShrink": "0", "display": "flex"}}>
<div style={{"display": "flex", "flexDirection": "column", "minWidth": 465, "flexGrow": "1"}}>
<Button content={"Tutorial →"} state={"Primary"} />
</div>
</a>
</div>
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 54}}>
<div style={{"flexGrow": "1", "flexBasis": 0}}>
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1440 132" style={{"display": "block"}}>
<polygon points="0 132 1440 0 1440 132" style={{"fill": "rgb(42, 42, 89)"}} />
</svg>
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"display": "flex", "flexDirection": "column", "flexGrow": "1", "flexBasis": 0, "minHeight": "fit-content", "paddingTop": 14, "paddingBottom": 22, "background": "rgb(42, 42, 89)"}}>
<div style={{"display": "flex", "flexShrink": "0", "justifyContent": "center"}}>
<div style={{"width": 560, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgb(255, 255, 255)", "fontSize": 40, "lineHeight": "50px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
Stress-test your designs.
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 36, "justifyContent": "center"}}>
<div style={{"width": 500, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgb(255, 255, 255)", "fontSize": 17, "lineHeight": "25.5px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
Test your designs with real data and different screen sizes. Once responsive resizing and data reflowing looks correct, bringing your design to production is as easy as calling your Pagedrawn component with a single line of code.
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 30, "justifyContent": "center"}}>
<div style={{"display": "flex", "flexDirection": "column", "paddingTop": 32}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"flexShrink": "0", "display": "flex", "flexDirection": "column"}}>
<Demopills step={1} list={[{"title": "Mark responsive constraints", "body": "Define how components resize and reflow. Test it out instantly with Pagedraw's Stress Tester"}, {"title": "Connect design to data", "body": ""}, {"title": "Define reusable components", "body": ""}, {"title": "Call Pagedraw generated components as if they were regular React components in your codebase", "body": ""}]} />
</div>
<div style={{"display": "flex", "flexDirection": "column", "marginLeft": 23, "paddingTop": 40, "paddingBottom": 25}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<img src="https://ucarecdn.com/97fe0dae-3938-4035-b1a3-a97d6baeff37/" style={{"width": 473.00000000000006, "height": 287, "flexShrink": "0", "borderWidth": 0}} />
</div>
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 54, "paddingLeft": 363, "paddingRight": 363}}>
<a href="https://medium.com/pagedraw/designer-developer-handoff-with-pagedraw-1ae2add4450d" style={{"flexShrink": "0", "display": "flex"}}>
<div style={{"display": "flex", "flexDirection": "column", "minWidth": 258, "flexGrow": "1"}}>
<Button content={"Learn more"} state={"Primary"} />
</div>
</a>
</div>
</div>
</div>
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"flexGrow": "1", "flexBasis": 0}}>
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1440 132" style={{"display": "block"}}>
<polygon points="0 132 1440 0 0 0" style={{"fill": "rgb(42, 42, 89)"}} />
</svg>
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 49, "justifyContent": "center"}}>
<div style={{"display": "flex", "flexDirection": "column"}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"display": "flex", "flexDirection": "column", "paddingTop": 27, "paddingBottom": 30, "borderRadius": 10, "boxShadow": "0px 5px 15px 0px rgba(0,0,0,0.07), 0px 15px 35px 0px rgba(50,50,93,0.10)", "background": "rgb(255, 255, 255)"}}>
<div style={{"display": "flex", "flexShrink": "0", "paddingLeft": 30, "paddingRight": 34}}>
<div style={{"display": "flex", "flexDirection": "column", "paddingTop": 3, "paddingBottom": 3}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"display": "flex", "flexDirection": "column", "paddingTop": 7, "paddingBottom": 9, "borderRadius": 2, "background": "rgb(202, 193, 255)"}}>
<div style={{"display": "flex", "flexShrink": "0", "paddingLeft": 19, "paddingRight": 15}}>
<div style={{"width": 14, "height": 12, "flexShrink": "0", "borderRadius": 2, "background": "rgb(75, 75, 149)"}} />
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 1, "paddingLeft": 6, "paddingRight": 7}}>
<div style={{"display": "flex", "flexDirection": "column", "paddingTop": 4}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"width": 18, "height": 15, "flexShrink": "0", "borderRadius": 2, "background": "rgb(75, 75, 149)"}} />
</div>
</div>
<div style={{"display": "flex", "flexDirection": "column", "marginLeft": 9, "paddingBottom": 11}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"width": 8, "height": 8, "flexShrink": "0", "borderRadius": 2, "background": "rgb(75, 75, 149)"}} />
</div>
</div>
</div>
</div>
</div>
</div>
<div style={{"width": 212, "flexShrink": "0", "marginLeft": 16, "fontFamily": "\"Lato\", sans-serif", "color": "rgb(0, 0, 32)", "fontSize": 15, "lineHeight": "18.75px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "left", "wordWrap": "break-word"}}>
Use Pagedraw components in your existing React or Angular app.
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 37, "paddingLeft": 30, "paddingRight": 4}}>
<div style={{"display": "flex", "flexDirection": "column", "paddingTop": 3, "paddingBottom": 3}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"display": "flex", "flexDirection": "column", "paddingTop": 10, "paddingBottom": 9, "borderRadius": 2, "background": "rgb(75, 75, 149)"}}>
<div style={{"display": "flex", "flexShrink": "0", "paddingLeft": 6, "paddingRight": 12}}>
<div style={{"width": 14, "height": 12, "flexShrink": "0", "borderRadius": 2, "background": "rgb(202, 193, 255)"}} />
<div style={{"display": "flex", "flexDirection": "column", "marginLeft": 8, "paddingBottom": 4}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"width": 8, "height": 8, "flexShrink": "0", "borderRadius": 2, "background": "rgb(202, 193, 255)"}} />
</div>
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 2, "paddingLeft": 23, "paddingRight": 7}}>
<div style={{"width": 18, "height": 15, "flexShrink": "0", "borderRadius": 2, "background": "rgb(202, 193, 255)"}} />
</div>
</div>
</div>
</div>
<div style={{"width": 242, "flexShrink": "0", "marginLeft": 16, "fontFamily": "\"Lato\", sans-serif", "color": "rgb(0, 0, 32)", "fontSize": 15, "lineHeight": "18.75px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "left", "wordWrap": "break-word"}}>
Use handwritten React or Angular components in any Pagedraw project.
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 39, "paddingLeft": 30, "paddingRight": 34}}>
<div style={{"display": "flex", "flexDirection": "column", "paddingTop": 13, "paddingBottom": 13, "borderRadius": 100, "background": "rgb(202, 193, 255)"}}>
<div style={{"display": "flex", "flexShrink": "0", "paddingLeft": 15, "paddingRight": 14}}>
<img src="https://pagedraw-images.s3-us-west-1.amazonaws.com/1546411725700145-1511943211994-035A820E-4995-45F4-8CEB-2FA9385CD192.png" style={{"width": 19, "height": 15, "flexShrink": "0", "borderWidth": 0}} />
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 5, "paddingLeft": 14, "paddingRight": 14}}>
<div style={{"width": 20, "height": 2, "flexShrink": "0", "background": "rgb(75, 75, 149)"}} />
</div>
</div>
<div style={{"display": "flex", "flexDirection": "column", "marginLeft": 16, "paddingTop": 7, "paddingBottom": 5}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"width": 212, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgb(0, 0, 32)", "fontSize": 15, "lineHeight": "18.75px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "left", "wordWrap": "break-word"}}>
No libraries required. Just one line of code.
</div>
</div>
</div>
</div>
</div>
<div style={{"display": "flex", "flexDirection": "column", "marginLeft": 98, "paddingTop": 12, "paddingBottom": 58}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"width": 488, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgb(0, 0, 32)", "fontSize": 40, "lineHeight": "50px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "left", "wordWrap": "break-word"}}>
{"Import the generated code, don't edit it."}
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 19}}>
<div style={{"width": 488, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgba(0, 0, 32, 0.8)", "fontSize": 17, "lineHeight": "25.5px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "left", "wordWrap": "break-word"}}>
Changes to a Pagedraw component should be done visually, not in code. Of course we are hackers too, so we provide you with escape hatches whenever you feel like code is a better tool to solve a problem.
</div>
</div>
</div>
</div>
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 93, "justifyContent": "center"}}>
<div style={{"display": "flex", "flexDirection": "column", "paddingBottom": 19}}>
<div style={{"display": "flex", "flexShrink": "0", "paddingLeft": 61, "paddingRight": 61}}>
<div style={{"width": 534, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgb(0, 0, 31)", "fontSize": 40, "lineHeight": "50px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
{"Another WYSIWYG editor?"}
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 40}}>
<div style={{"flexShrink": "0", "display": "flex", "flexDirection": "column", "minWidth": 656}}>
<Comparisontable rows={[{"col1": "Translates visual design to code", "col2": true, "col3": true}, {"col1": "Responsive layouts", "col2": true, "col3": true}, {"col1": "Reflows correctly w/ dynamic data", "col2": false, "col3": true}, {"col1": "Works w/ tools designers already love", "col2": false, "col3": true}, {"col1": "CLI that syncs with Git", "col2": false, "col3": true}, {"col1": "Generates semantic flexbox code", "col2": false, "col3": true}, {"col1": "Code w/ position: absolute all over", "col2": true, "col3": false}]} header1={""} header2={"Traditional WYSIWYGs"} header3={"Pagedraw"} show={false} />
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 36, "paddingLeft": 24}}>
<div style={{"width": 632, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgba(0, 0, 0, 0.8)", "fontSize": 17, "lineHeight": "25.5px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "left", "wordWrap": "break-word"}}>
<div>Instead of a naive WYSIWYG approach, we built Pagedraw with a compiler mindset.</div>
<br/>
<div> Drawing more from GCC than Dreamweaver, we compile the designer mental model into JSX/TS and CSS, striving to make the generated code just like what we would write by hand as developers.</div>
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 39, "paddingLeft": 195, "paddingRight": 196}}>
<a href="https://documentation.pagedraw.io/wysiwyg" style={{"flexShrink": "0", "display": "flex"}}>
<div style={{"width": 265, "fontFamily": "\"Lato\", sans-serif", "color": "rgb(0, 0, 31)", "fontSize": 17, "lineHeight": "25.5px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word", "flexGrow": "1"}}>
{"Learn more →"}
</div>
</a>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 89, "paddingLeft": 158, "paddingRight": 158}}>
<div style={{"width": 340, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgb(0, 0, 31)", "fontSize": 40, "lineHeight": "50px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
<div>Pagedraw is free.</div>
<div>Try it today.</div>
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 34, "paddingLeft": 158, "paddingRight": 158}}>
<a href="/fiddle/0ziyVbuEDB_s" target="_blank" style={{"display": "flex"}}>
<div style={{"display": "flex", "flexDirection": "column", "borderRadius": 6, "boxShadow": "0px 5px 15px 0px rgba(0,0,0,0.07), 0px 15px 35px 0px rgba(50,50,93,0.10)", "background": "rgb(255, 255, 255)", "flexGrow": "1"}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"width": 47, "height": 48, "flexShrink": "0", "backgroundImage": "url('https://pagedraw-images.s3-us-west-1.amazonaws.com/1686591547037643-1511943211989-9867A4DF-AEE1-4B45-97BE-59491087D79B.png')", "backgroundSize": "cover", "backgroundPosition": "center"}} />
<div style={{"display": "flex", "flexDirection": "column", "marginLeft": 30, "paddingTop": 13, "paddingBottom": 14}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"width": 263, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgb(0, 0, 31)", "fontSize": 17, "lineHeight": "normal", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "left", "wordWrap": "break-word"}}>
{"Hacker News built in Pagedraw →"}
</div>
</div>
</div>
</div>
</div>
</a>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 13, "paddingLeft": 158, "paddingRight": 158}}>
<a href="/fiddle/fb-newsfeed" target="_blank" style={{"display": "flex"}}>
<div style={{"display": "flex", "flexDirection": "column", "borderRadius": 6, "boxShadow": "0px 5px 15px 0px rgba(0,0,0,0.07), 0px 15px 35px 0px rgba(50,50,93,0.10)", "background": "rgb(255, 255, 255)", "flexGrow": "1"}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<img src="https://ucarecdn.com/ed20d640-50fb-4c1e-9404-ecd1d8d71fa2/" style={{"width": 47, "height": 48, "flexShrink": "0", "borderWidth": 0}} />
<div style={{"display": "flex", "flexDirection": "column", "marginLeft": 30, "paddingTop": 13, "paddingBottom": 14}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"width": 263, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgb(0, 0, 31)", "fontSize": 17, "lineHeight": "normal", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "left", "wordWrap": "break-word"}}>
{"Facebook built in Pagedraw →"}
</div>
</div>
</div>
</div>
</div>
</a>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 13, "paddingLeft": 158, "paddingRight": 158}}>
<a href="/tutorials/basics" target="_blank" style={{"display": "flex"}}>
<div style={{"display": "flex", "flexDirection": "column", "borderRadius": 6, "boxShadow": "0px 5px 15px 0px rgba(0,0,0,0.07), 0px 15px 35px 0px rgba(50,50,93,0.10)", "background": "rgb(255, 255, 255)", "flexGrow": "1"}}>
<div style={{"display": "flex", "flexShrink": "0", "paddingLeft": 5}}>
<div style={{"display": "flex", "flexDirection": "column", "paddingTop": 9, "paddingBottom": 9}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<img src="https://ucarecdn.com/f8b3ff29-bde2-4e98-b67e-bfa1f4cfbe04/" style={{"width": 36, "height": 30, "flexShrink": "0", "borderWidth": 0}} />
</div>
</div>
<div style={{"width": 1, "height": 48, "flexShrink": "0", "marginLeft": 6, "background": "rgb(229, 229, 229)"}} />
<div style={{"display": "flex", "flexDirection": "column", "marginLeft": 29, "paddingTop": 13, "paddingBottom": 14}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"width": 263, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgb(0, 0, 31)", "fontSize": 17, "lineHeight": "normal", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "left", "wordWrap": "break-word"}}>
{"Quick demo →"}
</div>
</div>
</div>
</div>
</div>
</a>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 13, "paddingLeft": 158, "paddingRight": 158}}>
<a href="/apps" style={{"display": "flex"}}>
<div style={{"display": "flex", "flexDirection": "column", "borderRadius": 6, "boxShadow": "0px 5px 15px 0px rgba(0,0,0,0.07), 0px 15px 35px 0px rgba(50,50,93,0.10)", "background": "rgb(255, 255, 255)", "flexGrow": "1"}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"display": "flex", "flexDirection": "column", "paddingTop": 4, "paddingBottom": 4, "background": "rgba(243, 243, 245, 0)", "border": "1px solid #F4F4F4"}}>
<div style={{"display": "flex", "flexShrink": "0", "paddingLeft": 4, "paddingRight": 3}}>
<img src="https://pagedraw-images.s3-us-west-1.amazonaws.com/1623852088319076-1511943211991-ACDA0F8B-4E2C-4705-A47E-3E686EF2177D.png" style={{"width": 38, "height": 38, "flexShrink": "0", "borderWidth": 0}} />
</div>
</div>
<div style={{"display": "flex", "flexDirection": "column", "marginLeft": 30, "paddingTop": 13, "paddingBottom": 14}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"width": 263, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgb(0, 0, 31)", "fontSize": 17, "lineHeight": "normal", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "left", "wordWrap": "break-word"}}>
{"Start from your own Sketch file →"}
</div>
</div>
</div>
</div>
</div>
</a>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 33, "paddingLeft": 245, "paddingRight": 246}}>
<a href="mailto:team@pagedraw.io" style={{"flexShrink": "0", "display": "flex"}}>
<div style={{"width": 165, "fontFamily": "\"Lato\", sans-serif", "color": "rgb(0, 0, 31)", "fontSize": 17, "lineHeight": "40px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word", "flexGrow": "1"}}>
{"Contact us →"}
</div>
</a>
</div>
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 94}}>
<div style={{"flexGrow": "1", "flexBasis": 0, "display": "flex", "flexDirection": "column"}}>
<Landingfooter />
</div>
</div>
<div style={{"width": 0, "flexShrink": "0", "flexGrow": "1", "flexBasis": 0}} />
</div>
}
| 223025 | # Generated by https://pagedraw.io/pages/5249
React = require 'react'
createReactClass = require 'create-react-class'
Landingtopbar = require './landingtopbar'
Demobutton = require './demobutton'
Button = require './button'
Demopills = require './demopills'
Comparisontable = require './comparisontable'
Landingfooter = require './landingfooter'
module.exports = Landingdesktop = createReactClass {
displayName: 'Landingdesktop'
render: ->
<div style={{"display": "flex", "flexDirection": "column", "flexGrow": "1", "background": "rgb(255, 255, 255)", "minHeight": "100vh"}}>
<style dangerouslySetInnerHTML={__html: """
@import url('https://fonts.googleapis.com/css?family=Lato:|Lato:300');
* {
box-sizing: border-box;
}
body {
margin: 0;
}
button:hover {
cursor: pointer;
}
a {
text-decoration: none;
color: inherit;
}
.pd-onhover-parent >.pd-onhover {
display: none;
}
.pd-onhover-parent:hover > * {
display: none;
}
.pd-onhover-parent:hover > .pd-onhover {
display: flex;
}
.pd-onactive-parent > .pd-onactive {
display: none;
}
.pd-onactive-parent:active > * {
display: none;
}
.pd-onactive-parent:active > .pd-onactive {
display: flex;
}
.pd-onactive-parent.pd-onhover-parent:active > .pd-onhover {
display: none;
}
"""} />
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"display": "flex", "flexDirection": "column", "flexGrow": "1", "flexBasis": 0, "minHeight": "fit-content", "paddingTop": 36, "background": "rgb(42, 42, 89)"}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"height": 0, "flexGrow": "0.5011389521640092", "flexBasis": 0}} />
<div style={{"display": "flex", "flexDirection": "column"}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"flexShrink": "0", "display": "flex", "flexDirection": "column", "minWidth": 1001}}>
<Landingtopbar white={true} />
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 84}}>
<div style={{"width": 1001, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgb(255, 255, 255)", "fontSize": 50, "lineHeight": "50px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
The best UI builder for the web. Open source
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 35, "paddingLeft": 53, "paddingRight": 53}}>
<div style={{"width": 895, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgba(255, 255, 255, 0.7)", "fontSize": 19, "lineHeight": "22px", "letterSpacing": 0, "fontWeight": "300", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
{"Draw your React components, but use them like components coded manually. Already have mockups drawn? Just import them from Sketch or Figma."}
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 49, "paddingLeft": 84, "paddingRight": 48}}>
<div style={{"flexShrink": "0", "display": "flex", "flexDirection": "column", "minWidth": 354}}>
<Demobutton selected={true} content={"Pagedraw for a component named \"MainScreen\""} />
</div>
<div style={{"flexShrink": "0", "marginLeft": 204, "display": "flex", "flexDirection": "column", "minWidth": 311}}>
<Demobutton selected={true} content={"React code using that component"} />
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 21}}>
<div style={{"display": "flex", "flexDirection": "column", "paddingBottom": 3}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<img src="https://ucarecdn.com/cfba35fa-6c23-4bad-8554-df007a1e4f14/" style={{"width": 522, "height": 359, "flexShrink": "0", "borderWidth": 0}} />
</div>
</div>
<div style={{"display": "flex", "flexDirection": "column", "marginLeft": 72, "paddingTop": 2}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"width": 407, "height": 360, "flexShrink": "0", "display": "flex", "flexDirection": "column"}}>
{this.props.importPagedrawn}
</div>
</div>
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 66, "paddingLeft": 329, "paddingRight": 329}}>
<a href="/tutorials/basics" style={{"flexShrink": "0", "display": "flex"}}>
<div style={{"display": "flex", "flexDirection": "column", "minWidth": 343, "flexGrow": "1"}}>
<Button content={"Continue to demo →"} state={"Secondary"} />
</div>
</a>
</div>
</div>
<div style={{"height": 0, "flexGrow": "0.4988610478359909", "flexBasis": 0}} />
</div>
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"flexGrow": "1", "flexBasis": 0}}>
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1440 132" style={{"display": "block"}}>
<polygon points="0 132 1440 0 0 0" style={{"fill": "rgb(42, 42, 89)"}} />
</svg>
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"height": 0, "flexGrow": "0.375", "flexBasis": 0}} />
<div style={{"flexGrow": "0.25069444444444444", "flexBasis": 0, "fontFamily": "\"Lato\", sans-serif", "color": "rgb(0, 0, 31)", "fontSize": 40, "lineHeight": "50px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
Built for developers
</div>
<div style={{"height": 0, "flexGrow": "0.37430555555555556", "flexBasis": 0}} />
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 25}}>
<div style={{"height": 0, "flexGrow": "0.3034722222222222", "flexBasis": 0}} />
<div style={{"flexGrow": "0.3923611111111111", "flexBasis": 0, "fontFamily": "\"Lato\", sans-serif", "color": "rgba(0, 0, 31, 0.8)", "fontSize": 17, "lineHeight": "25.5px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
<div>{"Who need to deliver high-quality code faster than ever. Who don't want to have to think about CSS. Who need to use semantic, authentic HTML that integrates into their existing React codebase. "}</div>
<br/>
<div>{"We don't use a JS based layout engine, or ever make you ship extra dependencies. We'll never make your site slower, or fatter."}</div>
</div>
<div style={{"height": 0, "flexGrow": "0.30416666666666664", "flexBasis": 0}} />
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 52}}>
<div style={{"height": 0, "flexGrow": "0.5021459227467812", "flexBasis": 0}} />
<div style={{"display": "flex", "flexDirection": "column"}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"display": "flex", "flexDirection": "column"}}>
<div style={{"display": "flex", "flexShrink": "0", "paddingLeft": 144, "paddingRight": 160}}>
<div style={{"width": 142, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgba(6, 18, 44, 0.5)", "fontSize": 24, "lineHeight": "12px", "letterSpacing": 0.4000000059604645, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
works with
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 24, "paddingLeft": 79, "paddingRight": 80}}>
<div style={{"display": "flex", "flexDirection": "column", "paddingTop": 6}}>
<div style={{"display": "flex", "flexShrink": "0", "paddingLeft": 7, "paddingRight": 5}}>
<div style={{"display": "flex", "flexDirection": "column", "paddingTop": 10, "paddingBottom": 5}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<a href="https://reactjs.org/" target="_blank" style={{"flexShrink": "0", "display": "flex"}}>
<img src="https://pagedraw-images.s3.amazonaws.com/1786119702726483-1511943211646-D4982605-43E9-48EC-9604-858B5CF597D3.png" style={{"width": 66, "height": 55, "borderWidth": 0, "flexGrow": "1"}} />
</a>
</div>
</div>
<a href="https://www.figma.com/" target="_blank" style={{"flexShrink": "0", "marginLeft": 33, "display": "flex"}}>
<img src="https://ucarecdn.com/cdec4e4d-0f1b-4a53-99e4-20b2848ad39b/" style={{"width": 70, "height": 70, "borderWidth": 0, "flexGrow": "1"}} />
</a>
<div style={{"display": "flex", "flexDirection": "column", "marginLeft": 36, "paddingTop": 5, "paddingBottom": 5}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<a href="https://www.sketchapp.com/" target="_blank" style={{"flexShrink": "0", "display": "flex"}}>
<img src="https://ucarecdn.com/32701dc9-f7cf-4828-9f0a-b166cb8e38c8/" style={{"width": 70, "height": 60, "borderWidth": 0, "flexGrow": "1"}} />
</a>
</div>
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 8}}>
<div style={{"display": "flex", "flexDirection": "column", "paddingTop": 2}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"width": 80, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgb(0, 216, 255)", "fontSize": 16, "lineHeight": "18px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
React
</div>
</div>
</div>
<div style={{"display": "flex", "flexDirection": "column", "marginLeft": 22, "paddingBottom": 2}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"width": 78, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgba(0, 0, 32, 0.8)", "fontSize": 16, "lineHeight": "18px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
Figma
</div>
</div>
</div>
<div style={{"display": "flex", "flexDirection": "column", "marginLeft": 27, "paddingTop": 2}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"width": 80, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgba(0, 0, 32, 0.8)", "fontSize": 16, "lineHeight": "18px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
Sketch
</div>
</div>
</div>
</div>
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 36}}>
<div style={{"display": "flex", "flexDirection": "column", "paddingTop": 46, "paddingBottom": 22, "borderRadius": 10, "boxShadow": "0px 5px 15px 0px rgba(0,0,0,0.07), 0px 15px 35px 0px rgba(50,50,93,0.10)", "background": "rgb(255, 255, 255)"}}>
<div style={{"display": "flex", "flexShrink": "0", "paddingLeft": 20, "paddingRight": 33}}>
<div style={{"width": 393, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgba(0, 0, 32, 0.8)", "fontSize": 17, "lineHeight": "25.5px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
{"\“This is the one that actually works.\” "}
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 38, "paddingLeft": 64, "paddingRight": 82}}>
<div style={{"display": "flex", "flexDirection": "column", "paddingTop": 1, "paddingBottom": 3}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<a href="http://graphql.org/" target="_blank" style={{"flexShrink": "0", "display": "flex"}}>
<img src="https://ucarecdn.com/0a12e233-3a96-4b5b-8566-816c0448d035/" style={{"width": 101, "height": 35, "borderWidth": 0, "flexGrow": "1"}} />
</a>
</div>
</div>
<div style={{"display": "flex", "flexDirection": "column", "marginLeft": 19}}>
<div style={{"display": "flex", "flexShrink": "0", "paddingRight": 53}}>
<div style={{"width": 127, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgb(0, 0, 32)", "fontSize": 15, "lineHeight": "18.75px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "left", "wordWrap": "break-word"}}>
<NAME>
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 3}}>
<div style={{"width": 180, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgba(0, 0, 32, 0.5)", "fontSize": 15, "lineHeight": "18.75px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "left", "wordWrap": "break-word"}}>
Co-creator of GraphQL
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div style={{"display": "flex", "flexDirection": "column", "marginLeft": 56}}>
<div style={{"display": "flex", "flexShrink": "0", "paddingLeft": 164, "paddingRight": 148}}>
<div style={{"width": 160, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgba(6, 18, 44, 0.5)", "fontSize": 24, "lineHeight": "12px", "letterSpacing": 0.4000000059604645, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
coming soon
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 30, "paddingLeft": 102, "paddingRight": 88}}>
<div style={{"display": "flex", "flexDirection": "column", "paddingTop": 5}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<img src="https://pagedraw-images.s3.amazonaws.com/1786119702726483-1511943211646-D4982605-43E9-48EC-9604-858B5CF597D3.png" style={{"width": 66, "height": 55, "flexShrink": "0", "borderWidth": 0}} />
</div>
</div>
<a href="https://vuejs.org/" target="_blank" style={{"flexShrink": "0", "marginLeft": 48, "display": "flex"}}>
<img src="https://ucarecdn.com/5a8da673-8daf-478f-9a30-7cf507808db9/" style={{"width": 60, "height": 60, "borderWidth": 0, "flexGrow": "1"}} />
</a>
<a href="https://angular.io/" target="_blank" style={{"flexShrink": "0", "marginLeft": 48, "display": "flex"}}>
<img src="https://ucarecdn.com/55e6c57d-d7f1-4834-8e1c-160bf9b5dc05/" style={{"width": 60, "height": 60, "borderWidth": 0, "flexGrow": "1"}} />
</a>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 17, "paddingLeft": 78, "paddingRight": 78}}>
<div style={{"display": "flex", "flexDirection": "column", "paddingBottom": 2}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"width": 115, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgb(0, 216, 255)", "fontSize": 16, "lineHeight": "18px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
React Native
</div>
</div>
</div>
<div style={{"display": "flex", "flexDirection": "column", "marginLeft": 13, "paddingBottom": 2}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"width": 80, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgba(0, 0, 32, 0.8)", "fontSize": 16, "lineHeight": "18px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
Vue
</div>
</div>
</div>
<div style={{"display": "flex", "flexDirection": "column", "marginLeft": 28, "paddingTop": 2}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"width": 80, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgba(0, 0, 32, 0.8)", "fontSize": 16, "lineHeight": "18px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
Angular
</div>
</div>
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 37, "paddingLeft": 26}}>
<div style={{"display": "flex", "flexDirection": "column", "paddingTop": 20, "paddingBottom": 14, "borderRadius": 10, "boxShadow": "0px 5px 15px 0px rgba(0,0,0,0.07), 0px 15px 35px 0px rgba(50,50,93,0.10)", "background": "rgb(255, 255, 255)"}}>
<div style={{"display": "flex", "flexShrink": "0", "paddingLeft": 20, "paddingRight": 25}}>
<div style={{"width": 401, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgba(0, 0, 32, 0.8)", "fontSize": 17, "lineHeight": "25.5px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
{"\“We've built over 3 different dashboards in very little time using Pagedraw. What used to take a sprint now takes only a couple of days.\” "}
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 23, "paddingLeft": 84, "paddingRight": 61}}>
<div style={{"display": "flex", "flexDirection": "column", "paddingTop": 1, "paddingBottom": 4}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<a href="https://getrileynow.com" target="_blank" style={{"flexShrink": "0", "display": "flex"}}>
<img src="https://ucarecdn.com/1e305a79-4529-46dc-ba03-3e67b74fb3f4/" style={{"width": 97, "height": 33, "borderWidth": 0, "flexGrow": "1"}} />
</a>
</div>
</div>
<div style={{"display": "flex", "flexDirection": "column", "marginLeft": 19}}>
<div style={{"display": "flex", "flexShrink": "0", "paddingRight": 50}}>
<div style={{"width": 135, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgb(0, 0, 32)", "fontSize": 15, "lineHeight": "18.75px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "left", "wordWrap": "break-word"}}>
<NAME>
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 2}}>
<div style={{"width": 185, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgba(0, 0, 32, 0.5)", "fontSize": 15, "lineHeight": "18.75px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "left", "wordWrap": "break-word"}}>
{"Cofounder & CTO of Riley"}
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 45}}>
<div style={{"display": "flex", "flexDirection": "column", "paddingTop": 29, "paddingBottom": 22, "borderRadius": 10, "boxShadow": "0px 5px 15px 0px rgba(0,0,0,0.07), 0px 15px 35px 0px rgba(50,50,93,0.10)", "background": "rgb(255, 255, 255)"}}>
<div style={{"display": "flex", "flexShrink": "0", "paddingLeft": 20, "paddingRight": 33}}>
<div style={{"width": 393, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgba(0, 0, 32, 0.8)", "fontSize": 17, "lineHeight": "25.5px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
{"\"Pagedraw is perhaps the most ambitious WYSIWYG editor for React apps.\" "}
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 30, "paddingLeft": 122, "paddingRight": 60}}>
<div style={{"display": "flex", "flexDirection": "column", "paddingTop": 3}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<img src="https://pagedraw-images.s3.amazonaws.com/1786119702726483-1511943211646-D4982605-43E9-48EC-9604-858B5CF597D3.png" style={{"width": 40, "height": 36, "flexShrink": "0", "borderWidth": 0}} />
</div>
</div>
<div style={{"display": "flex", "flexDirection": "column", "marginLeft": 22}}>
<div style={{"display": "flex", "flexShrink": "0", "paddingRight": 75}}>
<div style={{"width": 127, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgb(0, 0, 32)", "fontSize": 15, "lineHeight": "18.75px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "left", "wordWrap": "break-word"}}>
<NAME>
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 3}}>
<div style={{"width": 202, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgba(0, 0, 32, 0.5)", "fontSize": 15, "lineHeight": "18.75px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "left", "wordWrap": "break-word"}}>
Co-creator of React.js
</div>
</div>
</div>
</div>
</div>
<div style={{"display": "flex", "flexDirection": "column", "marginLeft": 82, "paddingTop": 33, "paddingBottom": 22, "borderRadius": 10, "boxShadow": "0px 5px 15px 0px rgba(0,0,0,0.07), 0px 15px 35px 0px rgba(50,50,93,0.10)", "background": "rgb(255, 255, 255)"}}>
<div style={{"display": "flex", "flexShrink": "0", "paddingLeft": 20, "paddingRight": 33}}>
<div style={{"width": 393, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgba(0, 0, 32, 0.8)", "fontSize": 17, "lineHeight": "25.5px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
{"\“Really impressed with Pagedraw. Can’t wait for it to work with React Native as well.\”"}
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 26, "paddingLeft": 68, "paddingRight": 33}}>
<div style={{"display": "flex", "flexDirection": "column", "paddingTop": 6, "paddingBottom": 3}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<a href="https://expo.io/" style={{"flexShrink": "0", "display": "flex"}}>
<img src="https://ucarecdn.com/0e28dfd2-9ea1-4a04-bf11-2cd82be3d36c/" style={{"width": 105, "height": 30, "borderWidth": 0, "flexGrow": "1"}} />
</a>
</div>
</div>
<div style={{"display": "flex", "flexDirection": "column", "marginLeft": 11}}>
<div style={{"display": "flex", "flexShrink": "0", "paddingRight": 102}}>
<div style={{"width": 127, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgb(0, 0, 32)", "fontSize": 15, "lineHeight": "18.75px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "left", "wordWrap": "break-word"}}>
<NAME>
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 3}}>
<div style={{"width": 229, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgba(0, 0, 32, 0.5)", "fontSize": 15, "lineHeight": "18.75px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "left", "wordWrap": "break-word"}}>
Cofounder of Quora and Expo.io
</div>
</div>
</div>
</div>
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 72, "paddingLeft": 255, "paddingRight": 254}}>
<a href="/tutorials/basics" style={{"flexShrink": "0", "display": "flex"}}>
<div style={{"display": "flex", "flexDirection": "column", "minWidth": 465, "flexGrow": "1"}}>
<Button content={"Try it out in browser →"} state={"Primary"} />
</div>
</a>
</div>
</div>
<div style={{"height": 0, "flexGrow": "0.4978540772532189", "flexBasis": 0}} />
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 87}}>
<div style={{"display": "flex", "flexDirection": "column", "flexGrow": "1", "flexBasis": 0, "minHeight": "fit-content", "paddingTop": 1, "background": "rgb(38, 38, 38)"}}>
<div style={{"display": "flex", "flexShrink": "0", "paddingLeft": 8}}>
<div style={{"height": 702, "flexGrow": "0.3058659217877095", "flexBasis": 0, "backgroundImage": "url('https://ucarecdn.com/900b6875-8bfb-4d24-9562-c0050bb955eb/')", "backgroundSize": "cover", "backgroundPosition": "center"}} />
<div style={{"height": 0, "flexGrow": "0.052374301675977654", "flexBasis": 0}} />
<div style={{"display": "flex", "flexDirection": "column", "flexGrow": "0.5349162011173184", "flexBasis": 0, "minHeight": "fit-content", "paddingTop": 101, "paddingBottom": 102}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"display": "flex", "flexDirection": "column", "flexGrow": "1", "flexBasis": 0, "minHeight": "fit-content"}}>
<div style={{"display": "flex", "flexShrink": "0", "paddingLeft": 28, "paddingRight": 27}}>
<div style={{"flexGrow": "1", "flexBasis": 0, "fontFamily": "\"Lato\", sans-serif", "color": "rgb(76, 253, 26)", "fontSize": 40, "lineHeight": "46px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "left", "wordWrap": "break-word"}}>
Redesign the green files in Pagedraw.
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 16, "paddingLeft": 28, "paddingRight": 27}}>
<div style={{"flexGrow": "1", "flexBasis": 0, "fontFamily": "Helvetica, Arial, sans-serif", "color": "rgb(222, 221, 221)", "fontSize": 17, "lineHeight": "25.5px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "left", "wordWrap": "break-word"}}>
<div>You edit them via Pagedraw editor, not by modifying the code. </div>
<br/>
<div>The Pagedraw CLI syncs Pagedraw docs with your codebase, so your localhost shows your latest designs, live, as you make them.</div>
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 57, "paddingLeft": 26, "paddingRight": 29}}>
<div style={{"flexGrow": "1", "flexBasis": 0, "fontFamily": "\"Lato\", sans-serif", "color": "rgb(179, 178, 178)", "fontSize": 40, "lineHeight": "46px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "left", "wordWrap": "break-word"}}>
Code the other files in your text editor.
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 24, "paddingLeft": 26}}>
<div style={{"flexGrow": "1", "flexBasis": 0, "fontFamily": "Helvetica, Arial, sans-serif", "color": "rgb(222, 221, 221)", "fontSize": 16, "lineHeight": "25.5px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "left", "wordWrap": "break-word"}}>
<div>{"These you edit with Sublime, Vim, your preference. Pagedraw doesn’t even know about them. They import the presentational components made in Pagedraw. "}</div>
<br/>
<div>These are your Redux containers, your React state management, and so on. If you have a design system or any components already done in code, Pagedraw docs can import them, too.</div>
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 35, "paddingLeft": 26, "paddingRight": 370}}>
<a href="/fiddle/DinV9PIR2Prt" style={{"flexShrink": "0", "display": "flex"}}>
<div style={{"display": "flex", "flexDirection": "column", "minWidth": 370, "flexGrow": "1"}}>
<Button content={"See integration example →"} state={"Primary"} />
</div>
</a>
</div>
</div>
</div>
</div>
<div style={{"height": 0, "flexGrow": "0.10684357541899442", "flexBasis": 0}} />
</div>
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 81, "justifyContent": "center"}}>
<div style={{"display": "flex", "flexDirection": "column", "paddingBottom": 1}}>
<div style={{"display": "flex", "flexShrink": "0", "paddingLeft": 148, "paddingRight": 149}}>
<div style={{"width": 705, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgb(0, 0, 31)", "fontSize": 40, "lineHeight": "50px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
Try without leaving your browser.
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 25, "paddingLeft": 218, "paddingRight": 219}}>
<div style={{"width": 565, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgba(0, 0, 31, 0.8)", "fontSize": 17, "lineHeight": "25.5px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
In this demo below you can change the design of the component on the left and modify the React code on the right side and see what happens live!
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 53, "paddingLeft": 1, "paddingRight": 1}}>
<div style={{"display": "flex", "flexDirection": "column"}}>
{this.props.pdPlayground}
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 50, "paddingLeft": 218, "paddingRight": 219}}>
<div style={{"width": 565, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgba(0, 0, 31, 0.8)", "fontSize": 17, "lineHeight": "25.5px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
Pagedraw generates code guaranteed to work correctly and in all browsers, which means less code in your codebase over which you have to worry about correctness and safety. It writes code just like we would by hand.
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 27, "paddingLeft": 268, "paddingRight": 269}}>
<a href="/tutorials/basics" style={{"flexShrink": "0", "display": "flex"}}>
<div style={{"display": "flex", "flexDirection": "column", "minWidth": 465, "flexGrow": "1"}}>
<Button content={"Tutorial →"} state={"Primary"} />
</div>
</a>
</div>
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 54}}>
<div style={{"flexGrow": "1", "flexBasis": 0}}>
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1440 132" style={{"display": "block"}}>
<polygon points="0 132 1440 0 1440 132" style={{"fill": "rgb(42, 42, 89)"}} />
</svg>
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"display": "flex", "flexDirection": "column", "flexGrow": "1", "flexBasis": 0, "minHeight": "fit-content", "paddingTop": 14, "paddingBottom": 22, "background": "rgb(42, 42, 89)"}}>
<div style={{"display": "flex", "flexShrink": "0", "justifyContent": "center"}}>
<div style={{"width": 560, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgb(255, 255, 255)", "fontSize": 40, "lineHeight": "50px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
Stress-test your designs.
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 36, "justifyContent": "center"}}>
<div style={{"width": 500, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgb(255, 255, 255)", "fontSize": 17, "lineHeight": "25.5px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
Test your designs with real data and different screen sizes. Once responsive resizing and data reflowing looks correct, bringing your design to production is as easy as calling your Pagedrawn component with a single line of code.
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 30, "justifyContent": "center"}}>
<div style={{"display": "flex", "flexDirection": "column", "paddingTop": 32}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"flexShrink": "0", "display": "flex", "flexDirection": "column"}}>
<Demopills step={1} list={[{"title": "Mark responsive constraints", "body": "Define how components resize and reflow. Test it out instantly with Pagedraw's Stress Tester"}, {"title": "Connect design to data", "body": ""}, {"title": "Define reusable components", "body": ""}, {"title": "Call Pagedraw generated components as if they were regular React components in your codebase", "body": ""}]} />
</div>
<div style={{"display": "flex", "flexDirection": "column", "marginLeft": 23, "paddingTop": 40, "paddingBottom": 25}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<img src="https://ucarecdn.com/97fe0dae-3938-4035-b1a3-a97d6baeff37/" style={{"width": 473.00000000000006, "height": 287, "flexShrink": "0", "borderWidth": 0}} />
</div>
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 54, "paddingLeft": 363, "paddingRight": 363}}>
<a href="https://medium.com/pagedraw/designer-developer-handoff-with-pagedraw-1ae2add4450d" style={{"flexShrink": "0", "display": "flex"}}>
<div style={{"display": "flex", "flexDirection": "column", "minWidth": 258, "flexGrow": "1"}}>
<Button content={"Learn more"} state={"Primary"} />
</div>
</a>
</div>
</div>
</div>
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"flexGrow": "1", "flexBasis": 0}}>
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1440 132" style={{"display": "block"}}>
<polygon points="0 132 1440 0 0 0" style={{"fill": "rgb(42, 42, 89)"}} />
</svg>
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 49, "justifyContent": "center"}}>
<div style={{"display": "flex", "flexDirection": "column"}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"display": "flex", "flexDirection": "column", "paddingTop": 27, "paddingBottom": 30, "borderRadius": 10, "boxShadow": "0px 5px 15px 0px rgba(0,0,0,0.07), 0px 15px 35px 0px rgba(50,50,93,0.10)", "background": "rgb(255, 255, 255)"}}>
<div style={{"display": "flex", "flexShrink": "0", "paddingLeft": 30, "paddingRight": 34}}>
<div style={{"display": "flex", "flexDirection": "column", "paddingTop": 3, "paddingBottom": 3}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"display": "flex", "flexDirection": "column", "paddingTop": 7, "paddingBottom": 9, "borderRadius": 2, "background": "rgb(202, 193, 255)"}}>
<div style={{"display": "flex", "flexShrink": "0", "paddingLeft": 19, "paddingRight": 15}}>
<div style={{"width": 14, "height": 12, "flexShrink": "0", "borderRadius": 2, "background": "rgb(75, 75, 149)"}} />
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 1, "paddingLeft": 6, "paddingRight": 7}}>
<div style={{"display": "flex", "flexDirection": "column", "paddingTop": 4}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"width": 18, "height": 15, "flexShrink": "0", "borderRadius": 2, "background": "rgb(75, 75, 149)"}} />
</div>
</div>
<div style={{"display": "flex", "flexDirection": "column", "marginLeft": 9, "paddingBottom": 11}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"width": 8, "height": 8, "flexShrink": "0", "borderRadius": 2, "background": "rgb(75, 75, 149)"}} />
</div>
</div>
</div>
</div>
</div>
</div>
<div style={{"width": 212, "flexShrink": "0", "marginLeft": 16, "fontFamily": "\"Lato\", sans-serif", "color": "rgb(0, 0, 32)", "fontSize": 15, "lineHeight": "18.75px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "left", "wordWrap": "break-word"}}>
Use Pagedraw components in your existing React or Angular app.
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 37, "paddingLeft": 30, "paddingRight": 4}}>
<div style={{"display": "flex", "flexDirection": "column", "paddingTop": 3, "paddingBottom": 3}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"display": "flex", "flexDirection": "column", "paddingTop": 10, "paddingBottom": 9, "borderRadius": 2, "background": "rgb(75, 75, 149)"}}>
<div style={{"display": "flex", "flexShrink": "0", "paddingLeft": 6, "paddingRight": 12}}>
<div style={{"width": 14, "height": 12, "flexShrink": "0", "borderRadius": 2, "background": "rgb(202, 193, 255)"}} />
<div style={{"display": "flex", "flexDirection": "column", "marginLeft": 8, "paddingBottom": 4}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"width": 8, "height": 8, "flexShrink": "0", "borderRadius": 2, "background": "rgb(202, 193, 255)"}} />
</div>
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 2, "paddingLeft": 23, "paddingRight": 7}}>
<div style={{"width": 18, "height": 15, "flexShrink": "0", "borderRadius": 2, "background": "rgb(202, 193, 255)"}} />
</div>
</div>
</div>
</div>
<div style={{"width": 242, "flexShrink": "0", "marginLeft": 16, "fontFamily": "\"Lato\", sans-serif", "color": "rgb(0, 0, 32)", "fontSize": 15, "lineHeight": "18.75px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "left", "wordWrap": "break-word"}}>
Use handwritten React or Angular components in any Pagedraw project.
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 39, "paddingLeft": 30, "paddingRight": 34}}>
<div style={{"display": "flex", "flexDirection": "column", "paddingTop": 13, "paddingBottom": 13, "borderRadius": 100, "background": "rgb(202, 193, 255)"}}>
<div style={{"display": "flex", "flexShrink": "0", "paddingLeft": 15, "paddingRight": 14}}>
<img src="https://pagedraw-images.s3-us-west-1.amazonaws.com/1546411725700145-1511943211994-035A820E-4995-45F4-8CEB-2FA9385CD192.png" style={{"width": 19, "height": 15, "flexShrink": "0", "borderWidth": 0}} />
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 5, "paddingLeft": 14, "paddingRight": 14}}>
<div style={{"width": 20, "height": 2, "flexShrink": "0", "background": "rgb(75, 75, 149)"}} />
</div>
</div>
<div style={{"display": "flex", "flexDirection": "column", "marginLeft": 16, "paddingTop": 7, "paddingBottom": 5}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"width": 212, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgb(0, 0, 32)", "fontSize": 15, "lineHeight": "18.75px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "left", "wordWrap": "break-word"}}>
No libraries required. Just one line of code.
</div>
</div>
</div>
</div>
</div>
<div style={{"display": "flex", "flexDirection": "column", "marginLeft": 98, "paddingTop": 12, "paddingBottom": 58}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"width": 488, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgb(0, 0, 32)", "fontSize": 40, "lineHeight": "50px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "left", "wordWrap": "break-word"}}>
{"Import the generated code, don't edit it."}
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 19}}>
<div style={{"width": 488, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgba(0, 0, 32, 0.8)", "fontSize": 17, "lineHeight": "25.5px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "left", "wordWrap": "break-word"}}>
Changes to a Pagedraw component should be done visually, not in code. Of course we are hackers too, so we provide you with escape hatches whenever you feel like code is a better tool to solve a problem.
</div>
</div>
</div>
</div>
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 93, "justifyContent": "center"}}>
<div style={{"display": "flex", "flexDirection": "column", "paddingBottom": 19}}>
<div style={{"display": "flex", "flexShrink": "0", "paddingLeft": 61, "paddingRight": 61}}>
<div style={{"width": 534, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgb(0, 0, 31)", "fontSize": 40, "lineHeight": "50px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
{"Another WYSIWYG editor?"}
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 40}}>
<div style={{"flexShrink": "0", "display": "flex", "flexDirection": "column", "minWidth": 656}}>
<Comparisontable rows={[{"col1": "Translates visual design to code", "col2": true, "col3": true}, {"col1": "Responsive layouts", "col2": true, "col3": true}, {"col1": "Reflows correctly w/ dynamic data", "col2": false, "col3": true}, {"col1": "Works w/ tools designers already love", "col2": false, "col3": true}, {"col1": "CLI that syncs with Git", "col2": false, "col3": true}, {"col1": "Generates semantic flexbox code", "col2": false, "col3": true}, {"col1": "Code w/ position: absolute all over", "col2": true, "col3": false}]} header1={""} header2={"Traditional WYSIWYGs"} header3={"Pagedraw"} show={false} />
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 36, "paddingLeft": 24}}>
<div style={{"width": 632, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgba(0, 0, 0, 0.8)", "fontSize": 17, "lineHeight": "25.5px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "left", "wordWrap": "break-word"}}>
<div>Instead of a naive WYSIWYG approach, we built Pagedraw with a compiler mindset.</div>
<br/>
<div> Drawing more from GCC than Dreamweaver, we compile the designer mental model into JSX/TS and CSS, striving to make the generated code just like what we would write by hand as developers.</div>
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 39, "paddingLeft": 195, "paddingRight": 196}}>
<a href="https://documentation.pagedraw.io/wysiwyg" style={{"flexShrink": "0", "display": "flex"}}>
<div style={{"width": 265, "fontFamily": "\"Lato\", sans-serif", "color": "rgb(0, 0, 31)", "fontSize": 17, "lineHeight": "25.5px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word", "flexGrow": "1"}}>
{"Learn more →"}
</div>
</a>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 89, "paddingLeft": 158, "paddingRight": 158}}>
<div style={{"width": 340, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgb(0, 0, 31)", "fontSize": 40, "lineHeight": "50px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
<div>Pagedraw is free.</div>
<div>Try it today.</div>
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 34, "paddingLeft": 158, "paddingRight": 158}}>
<a href="/fiddle/0ziyVbuEDB_s" target="_blank" style={{"display": "flex"}}>
<div style={{"display": "flex", "flexDirection": "column", "borderRadius": 6, "boxShadow": "0px 5px 15px 0px rgba(0,0,0,0.07), 0px 15px 35px 0px rgba(50,50,93,0.10)", "background": "rgb(255, 255, 255)", "flexGrow": "1"}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"width": 47, "height": 48, "flexShrink": "0", "backgroundImage": "url('https://pagedraw-images.s3-us-west-1.amazonaws.com/1686591547037643-1511943211989-9867A4DF-AEE1-4B45-97BE-59491087D79B.png')", "backgroundSize": "cover", "backgroundPosition": "center"}} />
<div style={{"display": "flex", "flexDirection": "column", "marginLeft": 30, "paddingTop": 13, "paddingBottom": 14}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"width": 263, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgb(0, 0, 31)", "fontSize": 17, "lineHeight": "normal", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "left", "wordWrap": "break-word"}}>
{"Hacker News built in Pagedraw →"}
</div>
</div>
</div>
</div>
</div>
</a>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 13, "paddingLeft": 158, "paddingRight": 158}}>
<a href="/fiddle/fb-newsfeed" target="_blank" style={{"display": "flex"}}>
<div style={{"display": "flex", "flexDirection": "column", "borderRadius": 6, "boxShadow": "0px 5px 15px 0px rgba(0,0,0,0.07), 0px 15px 35px 0px rgba(50,50,93,0.10)", "background": "rgb(255, 255, 255)", "flexGrow": "1"}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<img src="https://ucarecdn.com/ed20d640-50fb-4c1e-9404-ecd1d8d71fa2/" style={{"width": 47, "height": 48, "flexShrink": "0", "borderWidth": 0}} />
<div style={{"display": "flex", "flexDirection": "column", "marginLeft": 30, "paddingTop": 13, "paddingBottom": 14}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"width": 263, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgb(0, 0, 31)", "fontSize": 17, "lineHeight": "normal", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "left", "wordWrap": "break-word"}}>
{"Facebook built in Pagedraw →"}
</div>
</div>
</div>
</div>
</div>
</a>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 13, "paddingLeft": 158, "paddingRight": 158}}>
<a href="/tutorials/basics" target="_blank" style={{"display": "flex"}}>
<div style={{"display": "flex", "flexDirection": "column", "borderRadius": 6, "boxShadow": "0px 5px 15px 0px rgba(0,0,0,0.07), 0px 15px 35px 0px rgba(50,50,93,0.10)", "background": "rgb(255, 255, 255)", "flexGrow": "1"}}>
<div style={{"display": "flex", "flexShrink": "0", "paddingLeft": 5}}>
<div style={{"display": "flex", "flexDirection": "column", "paddingTop": 9, "paddingBottom": 9}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<img src="https://ucarecdn.com/f8b3ff29-bde2-4e98-b67e-bfa1f4cfbe04/" style={{"width": 36, "height": 30, "flexShrink": "0", "borderWidth": 0}} />
</div>
</div>
<div style={{"width": 1, "height": 48, "flexShrink": "0", "marginLeft": 6, "background": "rgb(229, 229, 229)"}} />
<div style={{"display": "flex", "flexDirection": "column", "marginLeft": 29, "paddingTop": 13, "paddingBottom": 14}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"width": 263, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgb(0, 0, 31)", "fontSize": 17, "lineHeight": "normal", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "left", "wordWrap": "break-word"}}>
{"Quick demo →"}
</div>
</div>
</div>
</div>
</div>
</a>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 13, "paddingLeft": 158, "paddingRight": 158}}>
<a href="/apps" style={{"display": "flex"}}>
<div style={{"display": "flex", "flexDirection": "column", "borderRadius": 6, "boxShadow": "0px 5px 15px 0px rgba(0,0,0,0.07), 0px 15px 35px 0px rgba(50,50,93,0.10)", "background": "rgb(255, 255, 255)", "flexGrow": "1"}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"display": "flex", "flexDirection": "column", "paddingTop": 4, "paddingBottom": 4, "background": "rgba(243, 243, 245, 0)", "border": "1px solid #F4F4F4"}}>
<div style={{"display": "flex", "flexShrink": "0", "paddingLeft": 4, "paddingRight": 3}}>
<img src="https://pagedraw-images.s3-us-west-1.amazonaws.com/1623852088319076-1511943211991-ACDA0F8B-4E2C-4705-A47E-3E686EF2177D.png" style={{"width": 38, "height": 38, "flexShrink": "0", "borderWidth": 0}} />
</div>
</div>
<div style={{"display": "flex", "flexDirection": "column", "marginLeft": 30, "paddingTop": 13, "paddingBottom": 14}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"width": 263, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgb(0, 0, 31)", "fontSize": 17, "lineHeight": "normal", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "left", "wordWrap": "break-word"}}>
{"Start from your own Sketch file →"}
</div>
</div>
</div>
</div>
</div>
</a>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 33, "paddingLeft": 245, "paddingRight": 246}}>
<a href="mailto:<EMAIL>" style={{"flexShrink": "0", "display": "flex"}}>
<div style={{"width": 165, "fontFamily": "\"Lato\", sans-serif", "color": "rgb(0, 0, 31)", "fontSize": 17, "lineHeight": "40px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word", "flexGrow": "1"}}>
{"Contact us →"}
</div>
</a>
</div>
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 94}}>
<div style={{"flexGrow": "1", "flexBasis": 0, "display": "flex", "flexDirection": "column"}}>
<Landingfooter />
</div>
</div>
<div style={{"width": 0, "flexShrink": "0", "flexGrow": "1", "flexBasis": 0}} />
</div>
}
| true | # Generated by https://pagedraw.io/pages/5249
React = require 'react'
createReactClass = require 'create-react-class'
Landingtopbar = require './landingtopbar'
Demobutton = require './demobutton'
Button = require './button'
Demopills = require './demopills'
Comparisontable = require './comparisontable'
Landingfooter = require './landingfooter'
module.exports = Landingdesktop = createReactClass {
displayName: 'Landingdesktop'
render: ->
<div style={{"display": "flex", "flexDirection": "column", "flexGrow": "1", "background": "rgb(255, 255, 255)", "minHeight": "100vh"}}>
<style dangerouslySetInnerHTML={__html: """
@import url('https://fonts.googleapis.com/css?family=Lato:|Lato:300');
* {
box-sizing: border-box;
}
body {
margin: 0;
}
button:hover {
cursor: pointer;
}
a {
text-decoration: none;
color: inherit;
}
.pd-onhover-parent >.pd-onhover {
display: none;
}
.pd-onhover-parent:hover > * {
display: none;
}
.pd-onhover-parent:hover > .pd-onhover {
display: flex;
}
.pd-onactive-parent > .pd-onactive {
display: none;
}
.pd-onactive-parent:active > * {
display: none;
}
.pd-onactive-parent:active > .pd-onactive {
display: flex;
}
.pd-onactive-parent.pd-onhover-parent:active > .pd-onhover {
display: none;
}
"""} />
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"display": "flex", "flexDirection": "column", "flexGrow": "1", "flexBasis": 0, "minHeight": "fit-content", "paddingTop": 36, "background": "rgb(42, 42, 89)"}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"height": 0, "flexGrow": "0.5011389521640092", "flexBasis": 0}} />
<div style={{"display": "flex", "flexDirection": "column"}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"flexShrink": "0", "display": "flex", "flexDirection": "column", "minWidth": 1001}}>
<Landingtopbar white={true} />
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 84}}>
<div style={{"width": 1001, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgb(255, 255, 255)", "fontSize": 50, "lineHeight": "50px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
The best UI builder for the web. Open source
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 35, "paddingLeft": 53, "paddingRight": 53}}>
<div style={{"width": 895, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgba(255, 255, 255, 0.7)", "fontSize": 19, "lineHeight": "22px", "letterSpacing": 0, "fontWeight": "300", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
{"Draw your React components, but use them like components coded manually. Already have mockups drawn? Just import them from Sketch or Figma."}
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 49, "paddingLeft": 84, "paddingRight": 48}}>
<div style={{"flexShrink": "0", "display": "flex", "flexDirection": "column", "minWidth": 354}}>
<Demobutton selected={true} content={"Pagedraw for a component named \"MainScreen\""} />
</div>
<div style={{"flexShrink": "0", "marginLeft": 204, "display": "flex", "flexDirection": "column", "minWidth": 311}}>
<Demobutton selected={true} content={"React code using that component"} />
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 21}}>
<div style={{"display": "flex", "flexDirection": "column", "paddingBottom": 3}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<img src="https://ucarecdn.com/cfba35fa-6c23-4bad-8554-df007a1e4f14/" style={{"width": 522, "height": 359, "flexShrink": "0", "borderWidth": 0}} />
</div>
</div>
<div style={{"display": "flex", "flexDirection": "column", "marginLeft": 72, "paddingTop": 2}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"width": 407, "height": 360, "flexShrink": "0", "display": "flex", "flexDirection": "column"}}>
{this.props.importPagedrawn}
</div>
</div>
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 66, "paddingLeft": 329, "paddingRight": 329}}>
<a href="/tutorials/basics" style={{"flexShrink": "0", "display": "flex"}}>
<div style={{"display": "flex", "flexDirection": "column", "minWidth": 343, "flexGrow": "1"}}>
<Button content={"Continue to demo →"} state={"Secondary"} />
</div>
</a>
</div>
</div>
<div style={{"height": 0, "flexGrow": "0.4988610478359909", "flexBasis": 0}} />
</div>
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"flexGrow": "1", "flexBasis": 0}}>
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1440 132" style={{"display": "block"}}>
<polygon points="0 132 1440 0 0 0" style={{"fill": "rgb(42, 42, 89)"}} />
</svg>
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"height": 0, "flexGrow": "0.375", "flexBasis": 0}} />
<div style={{"flexGrow": "0.25069444444444444", "flexBasis": 0, "fontFamily": "\"Lato\", sans-serif", "color": "rgb(0, 0, 31)", "fontSize": 40, "lineHeight": "50px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
Built for developers
</div>
<div style={{"height": 0, "flexGrow": "0.37430555555555556", "flexBasis": 0}} />
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 25}}>
<div style={{"height": 0, "flexGrow": "0.3034722222222222", "flexBasis": 0}} />
<div style={{"flexGrow": "0.3923611111111111", "flexBasis": 0, "fontFamily": "\"Lato\", sans-serif", "color": "rgba(0, 0, 31, 0.8)", "fontSize": 17, "lineHeight": "25.5px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
<div>{"Who need to deliver high-quality code faster than ever. Who don't want to have to think about CSS. Who need to use semantic, authentic HTML that integrates into their existing React codebase. "}</div>
<br/>
<div>{"We don't use a JS based layout engine, or ever make you ship extra dependencies. We'll never make your site slower, or fatter."}</div>
</div>
<div style={{"height": 0, "flexGrow": "0.30416666666666664", "flexBasis": 0}} />
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 52}}>
<div style={{"height": 0, "flexGrow": "0.5021459227467812", "flexBasis": 0}} />
<div style={{"display": "flex", "flexDirection": "column"}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"display": "flex", "flexDirection": "column"}}>
<div style={{"display": "flex", "flexShrink": "0", "paddingLeft": 144, "paddingRight": 160}}>
<div style={{"width": 142, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgba(6, 18, 44, 0.5)", "fontSize": 24, "lineHeight": "12px", "letterSpacing": 0.4000000059604645, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
works with
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 24, "paddingLeft": 79, "paddingRight": 80}}>
<div style={{"display": "flex", "flexDirection": "column", "paddingTop": 6}}>
<div style={{"display": "flex", "flexShrink": "0", "paddingLeft": 7, "paddingRight": 5}}>
<div style={{"display": "flex", "flexDirection": "column", "paddingTop": 10, "paddingBottom": 5}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<a href="https://reactjs.org/" target="_blank" style={{"flexShrink": "0", "display": "flex"}}>
<img src="https://pagedraw-images.s3.amazonaws.com/1786119702726483-1511943211646-D4982605-43E9-48EC-9604-858B5CF597D3.png" style={{"width": 66, "height": 55, "borderWidth": 0, "flexGrow": "1"}} />
</a>
</div>
</div>
<a href="https://www.figma.com/" target="_blank" style={{"flexShrink": "0", "marginLeft": 33, "display": "flex"}}>
<img src="https://ucarecdn.com/cdec4e4d-0f1b-4a53-99e4-20b2848ad39b/" style={{"width": 70, "height": 70, "borderWidth": 0, "flexGrow": "1"}} />
</a>
<div style={{"display": "flex", "flexDirection": "column", "marginLeft": 36, "paddingTop": 5, "paddingBottom": 5}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<a href="https://www.sketchapp.com/" target="_blank" style={{"flexShrink": "0", "display": "flex"}}>
<img src="https://ucarecdn.com/32701dc9-f7cf-4828-9f0a-b166cb8e38c8/" style={{"width": 70, "height": 60, "borderWidth": 0, "flexGrow": "1"}} />
</a>
</div>
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 8}}>
<div style={{"display": "flex", "flexDirection": "column", "paddingTop": 2}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"width": 80, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgb(0, 216, 255)", "fontSize": 16, "lineHeight": "18px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
React
</div>
</div>
</div>
<div style={{"display": "flex", "flexDirection": "column", "marginLeft": 22, "paddingBottom": 2}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"width": 78, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgba(0, 0, 32, 0.8)", "fontSize": 16, "lineHeight": "18px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
Figma
</div>
</div>
</div>
<div style={{"display": "flex", "flexDirection": "column", "marginLeft": 27, "paddingTop": 2}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"width": 80, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgba(0, 0, 32, 0.8)", "fontSize": 16, "lineHeight": "18px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
Sketch
</div>
</div>
</div>
</div>
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 36}}>
<div style={{"display": "flex", "flexDirection": "column", "paddingTop": 46, "paddingBottom": 22, "borderRadius": 10, "boxShadow": "0px 5px 15px 0px rgba(0,0,0,0.07), 0px 15px 35px 0px rgba(50,50,93,0.10)", "background": "rgb(255, 255, 255)"}}>
<div style={{"display": "flex", "flexShrink": "0", "paddingLeft": 20, "paddingRight": 33}}>
<div style={{"width": 393, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgba(0, 0, 32, 0.8)", "fontSize": 17, "lineHeight": "25.5px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
{"\“This is the one that actually works.\” "}
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 38, "paddingLeft": 64, "paddingRight": 82}}>
<div style={{"display": "flex", "flexDirection": "column", "paddingTop": 1, "paddingBottom": 3}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<a href="http://graphql.org/" target="_blank" style={{"flexShrink": "0", "display": "flex"}}>
<img src="https://ucarecdn.com/0a12e233-3a96-4b5b-8566-816c0448d035/" style={{"width": 101, "height": 35, "borderWidth": 0, "flexGrow": "1"}} />
</a>
</div>
</div>
<div style={{"display": "flex", "flexDirection": "column", "marginLeft": 19}}>
<div style={{"display": "flex", "flexShrink": "0", "paddingRight": 53}}>
<div style={{"width": 127, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgb(0, 0, 32)", "fontSize": 15, "lineHeight": "18.75px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "left", "wordWrap": "break-word"}}>
PI:NAME:<NAME>END_PI
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 3}}>
<div style={{"width": 180, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgba(0, 0, 32, 0.5)", "fontSize": 15, "lineHeight": "18.75px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "left", "wordWrap": "break-word"}}>
Co-creator of GraphQL
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div style={{"display": "flex", "flexDirection": "column", "marginLeft": 56}}>
<div style={{"display": "flex", "flexShrink": "0", "paddingLeft": 164, "paddingRight": 148}}>
<div style={{"width": 160, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgba(6, 18, 44, 0.5)", "fontSize": 24, "lineHeight": "12px", "letterSpacing": 0.4000000059604645, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
coming soon
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 30, "paddingLeft": 102, "paddingRight": 88}}>
<div style={{"display": "flex", "flexDirection": "column", "paddingTop": 5}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<img src="https://pagedraw-images.s3.amazonaws.com/1786119702726483-1511943211646-D4982605-43E9-48EC-9604-858B5CF597D3.png" style={{"width": 66, "height": 55, "flexShrink": "0", "borderWidth": 0}} />
</div>
</div>
<a href="https://vuejs.org/" target="_blank" style={{"flexShrink": "0", "marginLeft": 48, "display": "flex"}}>
<img src="https://ucarecdn.com/5a8da673-8daf-478f-9a30-7cf507808db9/" style={{"width": 60, "height": 60, "borderWidth": 0, "flexGrow": "1"}} />
</a>
<a href="https://angular.io/" target="_blank" style={{"flexShrink": "0", "marginLeft": 48, "display": "flex"}}>
<img src="https://ucarecdn.com/55e6c57d-d7f1-4834-8e1c-160bf9b5dc05/" style={{"width": 60, "height": 60, "borderWidth": 0, "flexGrow": "1"}} />
</a>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 17, "paddingLeft": 78, "paddingRight": 78}}>
<div style={{"display": "flex", "flexDirection": "column", "paddingBottom": 2}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"width": 115, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgb(0, 216, 255)", "fontSize": 16, "lineHeight": "18px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
React Native
</div>
</div>
</div>
<div style={{"display": "flex", "flexDirection": "column", "marginLeft": 13, "paddingBottom": 2}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"width": 80, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgba(0, 0, 32, 0.8)", "fontSize": 16, "lineHeight": "18px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
Vue
</div>
</div>
</div>
<div style={{"display": "flex", "flexDirection": "column", "marginLeft": 28, "paddingTop": 2}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"width": 80, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgba(0, 0, 32, 0.8)", "fontSize": 16, "lineHeight": "18px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
Angular
</div>
</div>
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 37, "paddingLeft": 26}}>
<div style={{"display": "flex", "flexDirection": "column", "paddingTop": 20, "paddingBottom": 14, "borderRadius": 10, "boxShadow": "0px 5px 15px 0px rgba(0,0,0,0.07), 0px 15px 35px 0px rgba(50,50,93,0.10)", "background": "rgb(255, 255, 255)"}}>
<div style={{"display": "flex", "flexShrink": "0", "paddingLeft": 20, "paddingRight": 25}}>
<div style={{"width": 401, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgba(0, 0, 32, 0.8)", "fontSize": 17, "lineHeight": "25.5px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
{"\“We've built over 3 different dashboards in very little time using Pagedraw. What used to take a sprint now takes only a couple of days.\” "}
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 23, "paddingLeft": 84, "paddingRight": 61}}>
<div style={{"display": "flex", "flexDirection": "column", "paddingTop": 1, "paddingBottom": 4}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<a href="https://getrileynow.com" target="_blank" style={{"flexShrink": "0", "display": "flex"}}>
<img src="https://ucarecdn.com/1e305a79-4529-46dc-ba03-3e67b74fb3f4/" style={{"width": 97, "height": 33, "borderWidth": 0, "flexGrow": "1"}} />
</a>
</div>
</div>
<div style={{"display": "flex", "flexDirection": "column", "marginLeft": 19}}>
<div style={{"display": "flex", "flexShrink": "0", "paddingRight": 50}}>
<div style={{"width": 135, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgb(0, 0, 32)", "fontSize": 15, "lineHeight": "18.75px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "left", "wordWrap": "break-word"}}>
PI:NAME:<NAME>END_PI
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 2}}>
<div style={{"width": 185, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgba(0, 0, 32, 0.5)", "fontSize": 15, "lineHeight": "18.75px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "left", "wordWrap": "break-word"}}>
{"Cofounder & CTO of Riley"}
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 45}}>
<div style={{"display": "flex", "flexDirection": "column", "paddingTop": 29, "paddingBottom": 22, "borderRadius": 10, "boxShadow": "0px 5px 15px 0px rgba(0,0,0,0.07), 0px 15px 35px 0px rgba(50,50,93,0.10)", "background": "rgb(255, 255, 255)"}}>
<div style={{"display": "flex", "flexShrink": "0", "paddingLeft": 20, "paddingRight": 33}}>
<div style={{"width": 393, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgba(0, 0, 32, 0.8)", "fontSize": 17, "lineHeight": "25.5px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
{"\"Pagedraw is perhaps the most ambitious WYSIWYG editor for React apps.\" "}
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 30, "paddingLeft": 122, "paddingRight": 60}}>
<div style={{"display": "flex", "flexDirection": "column", "paddingTop": 3}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<img src="https://pagedraw-images.s3.amazonaws.com/1786119702726483-1511943211646-D4982605-43E9-48EC-9604-858B5CF597D3.png" style={{"width": 40, "height": 36, "flexShrink": "0", "borderWidth": 0}} />
</div>
</div>
<div style={{"display": "flex", "flexDirection": "column", "marginLeft": 22}}>
<div style={{"display": "flex", "flexShrink": "0", "paddingRight": 75}}>
<div style={{"width": 127, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgb(0, 0, 32)", "fontSize": 15, "lineHeight": "18.75px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "left", "wordWrap": "break-word"}}>
PI:NAME:<NAME>END_PI
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 3}}>
<div style={{"width": 202, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgba(0, 0, 32, 0.5)", "fontSize": 15, "lineHeight": "18.75px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "left", "wordWrap": "break-word"}}>
Co-creator of React.js
</div>
</div>
</div>
</div>
</div>
<div style={{"display": "flex", "flexDirection": "column", "marginLeft": 82, "paddingTop": 33, "paddingBottom": 22, "borderRadius": 10, "boxShadow": "0px 5px 15px 0px rgba(0,0,0,0.07), 0px 15px 35px 0px rgba(50,50,93,0.10)", "background": "rgb(255, 255, 255)"}}>
<div style={{"display": "flex", "flexShrink": "0", "paddingLeft": 20, "paddingRight": 33}}>
<div style={{"width": 393, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgba(0, 0, 32, 0.8)", "fontSize": 17, "lineHeight": "25.5px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
{"\“Really impressed with Pagedraw. Can’t wait for it to work with React Native as well.\”"}
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 26, "paddingLeft": 68, "paddingRight": 33}}>
<div style={{"display": "flex", "flexDirection": "column", "paddingTop": 6, "paddingBottom": 3}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<a href="https://expo.io/" style={{"flexShrink": "0", "display": "flex"}}>
<img src="https://ucarecdn.com/0e28dfd2-9ea1-4a04-bf11-2cd82be3d36c/" style={{"width": 105, "height": 30, "borderWidth": 0, "flexGrow": "1"}} />
</a>
</div>
</div>
<div style={{"display": "flex", "flexDirection": "column", "marginLeft": 11}}>
<div style={{"display": "flex", "flexShrink": "0", "paddingRight": 102}}>
<div style={{"width": 127, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgb(0, 0, 32)", "fontSize": 15, "lineHeight": "18.75px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "left", "wordWrap": "break-word"}}>
PI:NAME:<NAME>END_PI
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 3}}>
<div style={{"width": 229, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgba(0, 0, 32, 0.5)", "fontSize": 15, "lineHeight": "18.75px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "left", "wordWrap": "break-word"}}>
Cofounder of Quora and Expo.io
</div>
</div>
</div>
</div>
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 72, "paddingLeft": 255, "paddingRight": 254}}>
<a href="/tutorials/basics" style={{"flexShrink": "0", "display": "flex"}}>
<div style={{"display": "flex", "flexDirection": "column", "minWidth": 465, "flexGrow": "1"}}>
<Button content={"Try it out in browser →"} state={"Primary"} />
</div>
</a>
</div>
</div>
<div style={{"height": 0, "flexGrow": "0.4978540772532189", "flexBasis": 0}} />
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 87}}>
<div style={{"display": "flex", "flexDirection": "column", "flexGrow": "1", "flexBasis": 0, "minHeight": "fit-content", "paddingTop": 1, "background": "rgb(38, 38, 38)"}}>
<div style={{"display": "flex", "flexShrink": "0", "paddingLeft": 8}}>
<div style={{"height": 702, "flexGrow": "0.3058659217877095", "flexBasis": 0, "backgroundImage": "url('https://ucarecdn.com/900b6875-8bfb-4d24-9562-c0050bb955eb/')", "backgroundSize": "cover", "backgroundPosition": "center"}} />
<div style={{"height": 0, "flexGrow": "0.052374301675977654", "flexBasis": 0}} />
<div style={{"display": "flex", "flexDirection": "column", "flexGrow": "0.5349162011173184", "flexBasis": 0, "minHeight": "fit-content", "paddingTop": 101, "paddingBottom": 102}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"display": "flex", "flexDirection": "column", "flexGrow": "1", "flexBasis": 0, "minHeight": "fit-content"}}>
<div style={{"display": "flex", "flexShrink": "0", "paddingLeft": 28, "paddingRight": 27}}>
<div style={{"flexGrow": "1", "flexBasis": 0, "fontFamily": "\"Lato\", sans-serif", "color": "rgb(76, 253, 26)", "fontSize": 40, "lineHeight": "46px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "left", "wordWrap": "break-word"}}>
Redesign the green files in Pagedraw.
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 16, "paddingLeft": 28, "paddingRight": 27}}>
<div style={{"flexGrow": "1", "flexBasis": 0, "fontFamily": "Helvetica, Arial, sans-serif", "color": "rgb(222, 221, 221)", "fontSize": 17, "lineHeight": "25.5px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "left", "wordWrap": "break-word"}}>
<div>You edit them via Pagedraw editor, not by modifying the code. </div>
<br/>
<div>The Pagedraw CLI syncs Pagedraw docs with your codebase, so your localhost shows your latest designs, live, as you make them.</div>
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 57, "paddingLeft": 26, "paddingRight": 29}}>
<div style={{"flexGrow": "1", "flexBasis": 0, "fontFamily": "\"Lato\", sans-serif", "color": "rgb(179, 178, 178)", "fontSize": 40, "lineHeight": "46px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "left", "wordWrap": "break-word"}}>
Code the other files in your text editor.
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 24, "paddingLeft": 26}}>
<div style={{"flexGrow": "1", "flexBasis": 0, "fontFamily": "Helvetica, Arial, sans-serif", "color": "rgb(222, 221, 221)", "fontSize": 16, "lineHeight": "25.5px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "left", "wordWrap": "break-word"}}>
<div>{"These you edit with Sublime, Vim, your preference. Pagedraw doesn’t even know about them. They import the presentational components made in Pagedraw. "}</div>
<br/>
<div>These are your Redux containers, your React state management, and so on. If you have a design system or any components already done in code, Pagedraw docs can import them, too.</div>
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 35, "paddingLeft": 26, "paddingRight": 370}}>
<a href="/fiddle/DinV9PIR2Prt" style={{"flexShrink": "0", "display": "flex"}}>
<div style={{"display": "flex", "flexDirection": "column", "minWidth": 370, "flexGrow": "1"}}>
<Button content={"See integration example →"} state={"Primary"} />
</div>
</a>
</div>
</div>
</div>
</div>
<div style={{"height": 0, "flexGrow": "0.10684357541899442", "flexBasis": 0}} />
</div>
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 81, "justifyContent": "center"}}>
<div style={{"display": "flex", "flexDirection": "column", "paddingBottom": 1}}>
<div style={{"display": "flex", "flexShrink": "0", "paddingLeft": 148, "paddingRight": 149}}>
<div style={{"width": 705, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgb(0, 0, 31)", "fontSize": 40, "lineHeight": "50px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
Try without leaving your browser.
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 25, "paddingLeft": 218, "paddingRight": 219}}>
<div style={{"width": 565, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgba(0, 0, 31, 0.8)", "fontSize": 17, "lineHeight": "25.5px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
In this demo below you can change the design of the component on the left and modify the React code on the right side and see what happens live!
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 53, "paddingLeft": 1, "paddingRight": 1}}>
<div style={{"display": "flex", "flexDirection": "column"}}>
{this.props.pdPlayground}
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 50, "paddingLeft": 218, "paddingRight": 219}}>
<div style={{"width": 565, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgba(0, 0, 31, 0.8)", "fontSize": 17, "lineHeight": "25.5px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
Pagedraw generates code guaranteed to work correctly and in all browsers, which means less code in your codebase over which you have to worry about correctness and safety. It writes code just like we would by hand.
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 27, "paddingLeft": 268, "paddingRight": 269}}>
<a href="/tutorials/basics" style={{"flexShrink": "0", "display": "flex"}}>
<div style={{"display": "flex", "flexDirection": "column", "minWidth": 465, "flexGrow": "1"}}>
<Button content={"Tutorial →"} state={"Primary"} />
</div>
</a>
</div>
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 54}}>
<div style={{"flexGrow": "1", "flexBasis": 0}}>
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1440 132" style={{"display": "block"}}>
<polygon points="0 132 1440 0 1440 132" style={{"fill": "rgb(42, 42, 89)"}} />
</svg>
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"display": "flex", "flexDirection": "column", "flexGrow": "1", "flexBasis": 0, "minHeight": "fit-content", "paddingTop": 14, "paddingBottom": 22, "background": "rgb(42, 42, 89)"}}>
<div style={{"display": "flex", "flexShrink": "0", "justifyContent": "center"}}>
<div style={{"width": 560, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgb(255, 255, 255)", "fontSize": 40, "lineHeight": "50px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
Stress-test your designs.
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 36, "justifyContent": "center"}}>
<div style={{"width": 500, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgb(255, 255, 255)", "fontSize": 17, "lineHeight": "25.5px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
Test your designs with real data and different screen sizes. Once responsive resizing and data reflowing looks correct, bringing your design to production is as easy as calling your Pagedrawn component with a single line of code.
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 30, "justifyContent": "center"}}>
<div style={{"display": "flex", "flexDirection": "column", "paddingTop": 32}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"flexShrink": "0", "display": "flex", "flexDirection": "column"}}>
<Demopills step={1} list={[{"title": "Mark responsive constraints", "body": "Define how components resize and reflow. Test it out instantly with Pagedraw's Stress Tester"}, {"title": "Connect design to data", "body": ""}, {"title": "Define reusable components", "body": ""}, {"title": "Call Pagedraw generated components as if they were regular React components in your codebase", "body": ""}]} />
</div>
<div style={{"display": "flex", "flexDirection": "column", "marginLeft": 23, "paddingTop": 40, "paddingBottom": 25}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<img src="https://ucarecdn.com/97fe0dae-3938-4035-b1a3-a97d6baeff37/" style={{"width": 473.00000000000006, "height": 287, "flexShrink": "0", "borderWidth": 0}} />
</div>
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 54, "paddingLeft": 363, "paddingRight": 363}}>
<a href="https://medium.com/pagedraw/designer-developer-handoff-with-pagedraw-1ae2add4450d" style={{"flexShrink": "0", "display": "flex"}}>
<div style={{"display": "flex", "flexDirection": "column", "minWidth": 258, "flexGrow": "1"}}>
<Button content={"Learn more"} state={"Primary"} />
</div>
</a>
</div>
</div>
</div>
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"flexGrow": "1", "flexBasis": 0}}>
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1440 132" style={{"display": "block"}}>
<polygon points="0 132 1440 0 0 0" style={{"fill": "rgb(42, 42, 89)"}} />
</svg>
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 49, "justifyContent": "center"}}>
<div style={{"display": "flex", "flexDirection": "column"}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"display": "flex", "flexDirection": "column", "paddingTop": 27, "paddingBottom": 30, "borderRadius": 10, "boxShadow": "0px 5px 15px 0px rgba(0,0,0,0.07), 0px 15px 35px 0px rgba(50,50,93,0.10)", "background": "rgb(255, 255, 255)"}}>
<div style={{"display": "flex", "flexShrink": "0", "paddingLeft": 30, "paddingRight": 34}}>
<div style={{"display": "flex", "flexDirection": "column", "paddingTop": 3, "paddingBottom": 3}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"display": "flex", "flexDirection": "column", "paddingTop": 7, "paddingBottom": 9, "borderRadius": 2, "background": "rgb(202, 193, 255)"}}>
<div style={{"display": "flex", "flexShrink": "0", "paddingLeft": 19, "paddingRight": 15}}>
<div style={{"width": 14, "height": 12, "flexShrink": "0", "borderRadius": 2, "background": "rgb(75, 75, 149)"}} />
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 1, "paddingLeft": 6, "paddingRight": 7}}>
<div style={{"display": "flex", "flexDirection": "column", "paddingTop": 4}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"width": 18, "height": 15, "flexShrink": "0", "borderRadius": 2, "background": "rgb(75, 75, 149)"}} />
</div>
</div>
<div style={{"display": "flex", "flexDirection": "column", "marginLeft": 9, "paddingBottom": 11}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"width": 8, "height": 8, "flexShrink": "0", "borderRadius": 2, "background": "rgb(75, 75, 149)"}} />
</div>
</div>
</div>
</div>
</div>
</div>
<div style={{"width": 212, "flexShrink": "0", "marginLeft": 16, "fontFamily": "\"Lato\", sans-serif", "color": "rgb(0, 0, 32)", "fontSize": 15, "lineHeight": "18.75px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "left", "wordWrap": "break-word"}}>
Use Pagedraw components in your existing React or Angular app.
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 37, "paddingLeft": 30, "paddingRight": 4}}>
<div style={{"display": "flex", "flexDirection": "column", "paddingTop": 3, "paddingBottom": 3}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"display": "flex", "flexDirection": "column", "paddingTop": 10, "paddingBottom": 9, "borderRadius": 2, "background": "rgb(75, 75, 149)"}}>
<div style={{"display": "flex", "flexShrink": "0", "paddingLeft": 6, "paddingRight": 12}}>
<div style={{"width": 14, "height": 12, "flexShrink": "0", "borderRadius": 2, "background": "rgb(202, 193, 255)"}} />
<div style={{"display": "flex", "flexDirection": "column", "marginLeft": 8, "paddingBottom": 4}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"width": 8, "height": 8, "flexShrink": "0", "borderRadius": 2, "background": "rgb(202, 193, 255)"}} />
</div>
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 2, "paddingLeft": 23, "paddingRight": 7}}>
<div style={{"width": 18, "height": 15, "flexShrink": "0", "borderRadius": 2, "background": "rgb(202, 193, 255)"}} />
</div>
</div>
</div>
</div>
<div style={{"width": 242, "flexShrink": "0", "marginLeft": 16, "fontFamily": "\"Lato\", sans-serif", "color": "rgb(0, 0, 32)", "fontSize": 15, "lineHeight": "18.75px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "left", "wordWrap": "break-word"}}>
Use handwritten React or Angular components in any Pagedraw project.
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 39, "paddingLeft": 30, "paddingRight": 34}}>
<div style={{"display": "flex", "flexDirection": "column", "paddingTop": 13, "paddingBottom": 13, "borderRadius": 100, "background": "rgb(202, 193, 255)"}}>
<div style={{"display": "flex", "flexShrink": "0", "paddingLeft": 15, "paddingRight": 14}}>
<img src="https://pagedraw-images.s3-us-west-1.amazonaws.com/1546411725700145-1511943211994-035A820E-4995-45F4-8CEB-2FA9385CD192.png" style={{"width": 19, "height": 15, "flexShrink": "0", "borderWidth": 0}} />
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 5, "paddingLeft": 14, "paddingRight": 14}}>
<div style={{"width": 20, "height": 2, "flexShrink": "0", "background": "rgb(75, 75, 149)"}} />
</div>
</div>
<div style={{"display": "flex", "flexDirection": "column", "marginLeft": 16, "paddingTop": 7, "paddingBottom": 5}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"width": 212, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgb(0, 0, 32)", "fontSize": 15, "lineHeight": "18.75px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "left", "wordWrap": "break-word"}}>
No libraries required. Just one line of code.
</div>
</div>
</div>
</div>
</div>
<div style={{"display": "flex", "flexDirection": "column", "marginLeft": 98, "paddingTop": 12, "paddingBottom": 58}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"width": 488, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgb(0, 0, 32)", "fontSize": 40, "lineHeight": "50px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "left", "wordWrap": "break-word"}}>
{"Import the generated code, don't edit it."}
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 19}}>
<div style={{"width": 488, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgba(0, 0, 32, 0.8)", "fontSize": 17, "lineHeight": "25.5px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "left", "wordWrap": "break-word"}}>
Changes to a Pagedraw component should be done visually, not in code. Of course we are hackers too, so we provide you with escape hatches whenever you feel like code is a better tool to solve a problem.
</div>
</div>
</div>
</div>
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 93, "justifyContent": "center"}}>
<div style={{"display": "flex", "flexDirection": "column", "paddingBottom": 19}}>
<div style={{"display": "flex", "flexShrink": "0", "paddingLeft": 61, "paddingRight": 61}}>
<div style={{"width": 534, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgb(0, 0, 31)", "fontSize": 40, "lineHeight": "50px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
{"Another WYSIWYG editor?"}
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 40}}>
<div style={{"flexShrink": "0", "display": "flex", "flexDirection": "column", "minWidth": 656}}>
<Comparisontable rows={[{"col1": "Translates visual design to code", "col2": true, "col3": true}, {"col1": "Responsive layouts", "col2": true, "col3": true}, {"col1": "Reflows correctly w/ dynamic data", "col2": false, "col3": true}, {"col1": "Works w/ tools designers already love", "col2": false, "col3": true}, {"col1": "CLI that syncs with Git", "col2": false, "col3": true}, {"col1": "Generates semantic flexbox code", "col2": false, "col3": true}, {"col1": "Code w/ position: absolute all over", "col2": true, "col3": false}]} header1={""} header2={"Traditional WYSIWYGs"} header3={"Pagedraw"} show={false} />
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 36, "paddingLeft": 24}}>
<div style={{"width": 632, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgba(0, 0, 0, 0.8)", "fontSize": 17, "lineHeight": "25.5px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "left", "wordWrap": "break-word"}}>
<div>Instead of a naive WYSIWYG approach, we built Pagedraw with a compiler mindset.</div>
<br/>
<div> Drawing more from GCC than Dreamweaver, we compile the designer mental model into JSX/TS and CSS, striving to make the generated code just like what we would write by hand as developers.</div>
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 39, "paddingLeft": 195, "paddingRight": 196}}>
<a href="https://documentation.pagedraw.io/wysiwyg" style={{"flexShrink": "0", "display": "flex"}}>
<div style={{"width": 265, "fontFamily": "\"Lato\", sans-serif", "color": "rgb(0, 0, 31)", "fontSize": 17, "lineHeight": "25.5px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word", "flexGrow": "1"}}>
{"Learn more →"}
</div>
</a>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 89, "paddingLeft": 158, "paddingRight": 158}}>
<div style={{"width": 340, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgb(0, 0, 31)", "fontSize": 40, "lineHeight": "50px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
<div>Pagedraw is free.</div>
<div>Try it today.</div>
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 34, "paddingLeft": 158, "paddingRight": 158}}>
<a href="/fiddle/0ziyVbuEDB_s" target="_blank" style={{"display": "flex"}}>
<div style={{"display": "flex", "flexDirection": "column", "borderRadius": 6, "boxShadow": "0px 5px 15px 0px rgba(0,0,0,0.07), 0px 15px 35px 0px rgba(50,50,93,0.10)", "background": "rgb(255, 255, 255)", "flexGrow": "1"}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"width": 47, "height": 48, "flexShrink": "0", "backgroundImage": "url('https://pagedraw-images.s3-us-west-1.amazonaws.com/1686591547037643-1511943211989-9867A4DF-AEE1-4B45-97BE-59491087D79B.png')", "backgroundSize": "cover", "backgroundPosition": "center"}} />
<div style={{"display": "flex", "flexDirection": "column", "marginLeft": 30, "paddingTop": 13, "paddingBottom": 14}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"width": 263, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgb(0, 0, 31)", "fontSize": 17, "lineHeight": "normal", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "left", "wordWrap": "break-word"}}>
{"Hacker News built in Pagedraw →"}
</div>
</div>
</div>
</div>
</div>
</a>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 13, "paddingLeft": 158, "paddingRight": 158}}>
<a href="/fiddle/fb-newsfeed" target="_blank" style={{"display": "flex"}}>
<div style={{"display": "flex", "flexDirection": "column", "borderRadius": 6, "boxShadow": "0px 5px 15px 0px rgba(0,0,0,0.07), 0px 15px 35px 0px rgba(50,50,93,0.10)", "background": "rgb(255, 255, 255)", "flexGrow": "1"}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<img src="https://ucarecdn.com/ed20d640-50fb-4c1e-9404-ecd1d8d71fa2/" style={{"width": 47, "height": 48, "flexShrink": "0", "borderWidth": 0}} />
<div style={{"display": "flex", "flexDirection": "column", "marginLeft": 30, "paddingTop": 13, "paddingBottom": 14}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"width": 263, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgb(0, 0, 31)", "fontSize": 17, "lineHeight": "normal", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "left", "wordWrap": "break-word"}}>
{"Facebook built in Pagedraw →"}
</div>
</div>
</div>
</div>
</div>
</a>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 13, "paddingLeft": 158, "paddingRight": 158}}>
<a href="/tutorials/basics" target="_blank" style={{"display": "flex"}}>
<div style={{"display": "flex", "flexDirection": "column", "borderRadius": 6, "boxShadow": "0px 5px 15px 0px rgba(0,0,0,0.07), 0px 15px 35px 0px rgba(50,50,93,0.10)", "background": "rgb(255, 255, 255)", "flexGrow": "1"}}>
<div style={{"display": "flex", "flexShrink": "0", "paddingLeft": 5}}>
<div style={{"display": "flex", "flexDirection": "column", "paddingTop": 9, "paddingBottom": 9}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<img src="https://ucarecdn.com/f8b3ff29-bde2-4e98-b67e-bfa1f4cfbe04/" style={{"width": 36, "height": 30, "flexShrink": "0", "borderWidth": 0}} />
</div>
</div>
<div style={{"width": 1, "height": 48, "flexShrink": "0", "marginLeft": 6, "background": "rgb(229, 229, 229)"}} />
<div style={{"display": "flex", "flexDirection": "column", "marginLeft": 29, "paddingTop": 13, "paddingBottom": 14}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"width": 263, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgb(0, 0, 31)", "fontSize": 17, "lineHeight": "normal", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "left", "wordWrap": "break-word"}}>
{"Quick demo →"}
</div>
</div>
</div>
</div>
</div>
</a>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 13, "paddingLeft": 158, "paddingRight": 158}}>
<a href="/apps" style={{"display": "flex"}}>
<div style={{"display": "flex", "flexDirection": "column", "borderRadius": 6, "boxShadow": "0px 5px 15px 0px rgba(0,0,0,0.07), 0px 15px 35px 0px rgba(50,50,93,0.10)", "background": "rgb(255, 255, 255)", "flexGrow": "1"}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"display": "flex", "flexDirection": "column", "paddingTop": 4, "paddingBottom": 4, "background": "rgba(243, 243, 245, 0)", "border": "1px solid #F4F4F4"}}>
<div style={{"display": "flex", "flexShrink": "0", "paddingLeft": 4, "paddingRight": 3}}>
<img src="https://pagedraw-images.s3-us-west-1.amazonaws.com/1623852088319076-1511943211991-ACDA0F8B-4E2C-4705-A47E-3E686EF2177D.png" style={{"width": 38, "height": 38, "flexShrink": "0", "borderWidth": 0}} />
</div>
</div>
<div style={{"display": "flex", "flexDirection": "column", "marginLeft": 30, "paddingTop": 13, "paddingBottom": 14}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"width": 263, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgb(0, 0, 31)", "fontSize": 17, "lineHeight": "normal", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "left", "wordWrap": "break-word"}}>
{"Start from your own Sketch file →"}
</div>
</div>
</div>
</div>
</div>
</a>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 33, "paddingLeft": 245, "paddingRight": 246}}>
<a href="mailto:PI:EMAIL:<EMAIL>END_PI" style={{"flexShrink": "0", "display": "flex"}}>
<div style={{"width": 165, "fontFamily": "\"Lato\", sans-serif", "color": "rgb(0, 0, 31)", "fontSize": 17, "lineHeight": "40px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word", "flexGrow": "1"}}>
{"Contact us →"}
</div>
</a>
</div>
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 94}}>
<div style={{"flexGrow": "1", "flexBasis": 0, "display": "flex", "flexDirection": "column"}}>
<Landingfooter />
</div>
</div>
<div style={{"width": 0, "flexShrink": "0", "flexGrow": "1", "flexBasis": 0}} />
</div>
}
|
[
{
"context": "odifying variables of class declarations\n# @author Toru Nagashima\n###\n\n'use strict'\n\nastUtils = require '../eslint-",
"end": 106,
"score": 0.9998648762702942,
"start": 92,
"tag": "NAME",
"value": "Toru Nagashima"
}
] | src/rules/no-class-assign.coffee | danielbayley/eslint-plugin-coffee | 21 | ###*
# @fileoverview A rule to disallow modifying variables of class declarations
# @author Toru Nagashima
###
'use strict'
astUtils = require '../eslint-ast-utils'
#------------------------------------------------------------------------------
# Rule Definition
#------------------------------------------------------------------------------
module.exports =
meta:
docs:
description: 'disallow reassigning class members'
category: 'ECMAScript 6'
recommended: yes
url: 'https://eslint.org/docs/rules/no-class-assign'
schema: []
messages:
class: "'{{name}}' is a class."
create: (context) ->
report = (node) ->
context.report {
node
messageId: 'class'
data: name: node.name ? node.id?.name
}
###*
# Finds and reports references that are non initializer and writable.
# @param {Variable} variable - A variable to check.
# @returns {void}
###
checkVariable = (variable) ->
astUtils
.getModifyingReferences variable.references
.forEach (reference) ->
report reference.identifier
###*
# Finds and reports references that are non initializer and writable.
# @param {ASTNode} node - A ClassDeclaration/ClassExpression node to check.
# @returns {void}
###
checkForClass = (node) ->
context.getDeclaredVariables(node).forEach checkVariable
if (
node.id?.type is 'Identifier' and
not node.id?.declaration and
not (
node.parent.type is 'AssignmentExpression' and
node.parent.left.type is 'Identifier' and
node.parent.left.name is node.id.name
)
)
clashingDefinition =
context.getScope().upper.set.get(node.id.name)?.defs?[0]?.node
report clashingDefinition if clashingDefinition?
ClassDeclaration: checkForClass
ClassExpression: checkForClass
| 208423 | ###*
# @fileoverview A rule to disallow modifying variables of class declarations
# @author <NAME>
###
'use strict'
astUtils = require '../eslint-ast-utils'
#------------------------------------------------------------------------------
# Rule Definition
#------------------------------------------------------------------------------
module.exports =
meta:
docs:
description: 'disallow reassigning class members'
category: 'ECMAScript 6'
recommended: yes
url: 'https://eslint.org/docs/rules/no-class-assign'
schema: []
messages:
class: "'{{name}}' is a class."
create: (context) ->
report = (node) ->
context.report {
node
messageId: 'class'
data: name: node.name ? node.id?.name
}
###*
# Finds and reports references that are non initializer and writable.
# @param {Variable} variable - A variable to check.
# @returns {void}
###
checkVariable = (variable) ->
astUtils
.getModifyingReferences variable.references
.forEach (reference) ->
report reference.identifier
###*
# Finds and reports references that are non initializer and writable.
# @param {ASTNode} node - A ClassDeclaration/ClassExpression node to check.
# @returns {void}
###
checkForClass = (node) ->
context.getDeclaredVariables(node).forEach checkVariable
if (
node.id?.type is 'Identifier' and
not node.id?.declaration and
not (
node.parent.type is 'AssignmentExpression' and
node.parent.left.type is 'Identifier' and
node.parent.left.name is node.id.name
)
)
clashingDefinition =
context.getScope().upper.set.get(node.id.name)?.defs?[0]?.node
report clashingDefinition if clashingDefinition?
ClassDeclaration: checkForClass
ClassExpression: checkForClass
| true | ###*
# @fileoverview A rule to disallow modifying variables of class declarations
# @author PI:NAME:<NAME>END_PI
###
'use strict'
astUtils = require '../eslint-ast-utils'
#------------------------------------------------------------------------------
# Rule Definition
#------------------------------------------------------------------------------
module.exports =
meta:
docs:
description: 'disallow reassigning class members'
category: 'ECMAScript 6'
recommended: yes
url: 'https://eslint.org/docs/rules/no-class-assign'
schema: []
messages:
class: "'{{name}}' is a class."
create: (context) ->
report = (node) ->
context.report {
node
messageId: 'class'
data: name: node.name ? node.id?.name
}
###*
# Finds and reports references that are non initializer and writable.
# @param {Variable} variable - A variable to check.
# @returns {void}
###
checkVariable = (variable) ->
astUtils
.getModifyingReferences variable.references
.forEach (reference) ->
report reference.identifier
###*
# Finds and reports references that are non initializer and writable.
# @param {ASTNode} node - A ClassDeclaration/ClassExpression node to check.
# @returns {void}
###
checkForClass = (node) ->
context.getDeclaredVariables(node).forEach checkVariable
if (
node.id?.type is 'Identifier' and
not node.id?.declaration and
not (
node.parent.type is 'AssignmentExpression' and
node.parent.left.type is 'Identifier' and
node.parent.left.name is node.id.name
)
)
clashingDefinition =
context.getScope().upper.set.get(node.id.name)?.defs?[0]?.node
report clashingDefinition if clashingDefinition?
ClassDeclaration: checkForClass
ClassExpression: checkForClass
|
[
{
"context": "5, 1, .5, 2, 1, 2, 1, 1, 1, 1, .5, 1 ], # Roc\n [ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2,",
"end": 1929,
"score": 0.8688939213752747,
"start": 1928,
"tag": "NAME",
"value": "R"
},
{
"context": "1, 1, 1, 1, 2, 1, 1, 2, 1, .5, .5, 1 ], # Gho\n [ 1... | server/bw/util.coffee | sarenji/pokebattle-sim | 5 | @roundHalfDown = (number) ->
Math.ceil(number - .5)
@typeEffectiveness = (userType, againstTypes, options = {}) ->
userType = Type[userType]
effectiveness = 1
for subtype in againstTypes
targetType = Type[subtype]
multiplier = typeChart[userType][targetType]
multiplier = 1 if multiplier == 0 && options.ignoreImmunities
multiplier = 2 if options.superEffectiveAgainst == subtype
effectiveness *= multiplier
effectiveness
@Type = Type =
Normal : 0
Fire : 1
Water : 2
Electric : 3
Grass : 4
Ice : 5
Fighting : 6
Poison : 7
Ground : 8
Flying : 9
Psychic : 10
Bug : 11
Rock : 12
Ghost : 13
Dragon : 14
Dark : 15
Steel : 16
"???" : 17
typeChart = [
# Nor Fir Wat Ele Gra Ice Fig Poi Gro Fly Psy Bug Roc Gho Dra Dar Ste ???
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, .5, 0, 1, 1, .5, 1 ], # Nor
[ 1, .5, .5, 1, 2, 2, 1, 1, 1, 1, 1, 2, .5, 1, .5, 1, 2, 1 ], # Fir
[ 1, 2, .5, 1, .5, 1, 1, 1, 2, 1, 1, 1, 2, 1, .5, 1, 1, 1 ], # Wat
[ 1, 1, 2, .5, .5, 1, 1, 1, 0, 2, 1, 1, 1, 1, .5, 1, 1, 1 ], # Ele
[ 1, .5, 2, 1, .5, 1, 1, .5, 2, .5, 1, .5, 2, 1, .5, 1, .5, 1 ], # Gra
[ 1, .5, .5, 1, 2, .5, 1, 1, 2, 2, 1, 1, 1, 1, 2, 1, .5, 1 ], # Ice
[ 2, 1, 1, 1, 1, 2, 1, .5, 1, .5, .5, .5, 2, 0, 1, 2, 2, 1 ], # Fig
[ 1, 1, 1, 1, 2, 1, 1, .5, .5, 1, 1, 1, .5, .5, 1, 1, 0, 1 ], # Poi
[ 1, 2, 1, 2, .5, 1, 1, 2, 1, 0, 1, .5, 2, 1, 1, 1, 2, 1 ], # Gro
[ 1, 1, 1, .5, 2, 1, 2, 1, 1, 1, 1, 2, .5, 1, 1, 1, .5, 1 ], # Fly
[ 1, 1, 1, 1, 1, 1, 2, 2, 1, 1, .5, 1, 1, 1, 1, 0, .5, 1 ], # Psy
[ 1, .5, 1, 1, 2, 1, .5, .5, 1, .5, 2, 1, 1, .5, 1, 2, .5, 1 ], # Bug
[ 1, 2, 1, 1, 1, 2, .5, 1, .5, 2, 1, 2, 1, 1, 1, 1, .5, 1 ], # Roc
[ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 2, 1, .5, .5, 1 ], # Gho
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, .5, 1 ], # Dra
[ 1, 1, 1, 1, 1, 1, .5, 1, 1, 1, 2, 1, 1, 2, 1, .5, .5, 1 ], # Dar
[ 1, .5, .5, .5, 1, 2, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, .5, 1 ], # Ste
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ] # ???
]
| 190446 | @roundHalfDown = (number) ->
Math.ceil(number - .5)
@typeEffectiveness = (userType, againstTypes, options = {}) ->
userType = Type[userType]
effectiveness = 1
for subtype in againstTypes
targetType = Type[subtype]
multiplier = typeChart[userType][targetType]
multiplier = 1 if multiplier == 0 && options.ignoreImmunities
multiplier = 2 if options.superEffectiveAgainst == subtype
effectiveness *= multiplier
effectiveness
@Type = Type =
Normal : 0
Fire : 1
Water : 2
Electric : 3
Grass : 4
Ice : 5
Fighting : 6
Poison : 7
Ground : 8
Flying : 9
Psychic : 10
Bug : 11
Rock : 12
Ghost : 13
Dragon : 14
Dark : 15
Steel : 16
"???" : 17
typeChart = [
# Nor Fir Wat Ele Gra Ice Fig Poi Gro Fly Psy Bug Roc Gho Dra Dar Ste ???
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, .5, 0, 1, 1, .5, 1 ], # Nor
[ 1, .5, .5, 1, 2, 2, 1, 1, 1, 1, 1, 2, .5, 1, .5, 1, 2, 1 ], # Fir
[ 1, 2, .5, 1, .5, 1, 1, 1, 2, 1, 1, 1, 2, 1, .5, 1, 1, 1 ], # Wat
[ 1, 1, 2, .5, .5, 1, 1, 1, 0, 2, 1, 1, 1, 1, .5, 1, 1, 1 ], # Ele
[ 1, .5, 2, 1, .5, 1, 1, .5, 2, .5, 1, .5, 2, 1, .5, 1, .5, 1 ], # Gra
[ 1, .5, .5, 1, 2, .5, 1, 1, 2, 2, 1, 1, 1, 1, 2, 1, .5, 1 ], # Ice
[ 2, 1, 1, 1, 1, 2, 1, .5, 1, .5, .5, .5, 2, 0, 1, 2, 2, 1 ], # Fig
[ 1, 1, 1, 1, 2, 1, 1, .5, .5, 1, 1, 1, .5, .5, 1, 1, 0, 1 ], # Poi
[ 1, 2, 1, 2, .5, 1, 1, 2, 1, 0, 1, .5, 2, 1, 1, 1, 2, 1 ], # Gro
[ 1, 1, 1, .5, 2, 1, 2, 1, 1, 1, 1, 2, .5, 1, 1, 1, .5, 1 ], # Fly
[ 1, 1, 1, 1, 1, 1, 2, 2, 1, 1, .5, 1, 1, 1, 1, 0, .5, 1 ], # Psy
[ 1, .5, 1, 1, 2, 1, .5, .5, 1, .5, 2, 1, 1, .5, 1, 2, .5, 1 ], # Bug
[ 1, 2, 1, 1, 1, 2, .5, 1, .5, 2, 1, 2, 1, 1, 1, 1, .5, 1 ], # <NAME>oc
[ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 2, 1, .5, .5, 1 ], # <NAME>ho
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, .5, 1 ], # <NAME>ra
[ 1, 1, 1, 1, 1, 1, .5, 1, 1, 1, 2, 1, 1, 2, 1, .5, .5, 1 ], # <NAME>
[ 1, .5, .5, .5, 1, 2, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, .5, 1 ], # <NAME>
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ] # ???
]
| true | @roundHalfDown = (number) ->
Math.ceil(number - .5)
@typeEffectiveness = (userType, againstTypes, options = {}) ->
userType = Type[userType]
effectiveness = 1
for subtype in againstTypes
targetType = Type[subtype]
multiplier = typeChart[userType][targetType]
multiplier = 1 if multiplier == 0 && options.ignoreImmunities
multiplier = 2 if options.superEffectiveAgainst == subtype
effectiveness *= multiplier
effectiveness
@Type = Type =
Normal : 0
Fire : 1
Water : 2
Electric : 3
Grass : 4
Ice : 5
Fighting : 6
Poison : 7
Ground : 8
Flying : 9
Psychic : 10
Bug : 11
Rock : 12
Ghost : 13
Dragon : 14
Dark : 15
Steel : 16
"???" : 17
typeChart = [
# Nor Fir Wat Ele Gra Ice Fig Poi Gro Fly Psy Bug Roc Gho Dra Dar Ste ???
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, .5, 0, 1, 1, .5, 1 ], # Nor
[ 1, .5, .5, 1, 2, 2, 1, 1, 1, 1, 1, 2, .5, 1, .5, 1, 2, 1 ], # Fir
[ 1, 2, .5, 1, .5, 1, 1, 1, 2, 1, 1, 1, 2, 1, .5, 1, 1, 1 ], # Wat
[ 1, 1, 2, .5, .5, 1, 1, 1, 0, 2, 1, 1, 1, 1, .5, 1, 1, 1 ], # Ele
[ 1, .5, 2, 1, .5, 1, 1, .5, 2, .5, 1, .5, 2, 1, .5, 1, .5, 1 ], # Gra
[ 1, .5, .5, 1, 2, .5, 1, 1, 2, 2, 1, 1, 1, 1, 2, 1, .5, 1 ], # Ice
[ 2, 1, 1, 1, 1, 2, 1, .5, 1, .5, .5, .5, 2, 0, 1, 2, 2, 1 ], # Fig
[ 1, 1, 1, 1, 2, 1, 1, .5, .5, 1, 1, 1, .5, .5, 1, 1, 0, 1 ], # Poi
[ 1, 2, 1, 2, .5, 1, 1, 2, 1, 0, 1, .5, 2, 1, 1, 1, 2, 1 ], # Gro
[ 1, 1, 1, .5, 2, 1, 2, 1, 1, 1, 1, 2, .5, 1, 1, 1, .5, 1 ], # Fly
[ 1, 1, 1, 1, 1, 1, 2, 2, 1, 1, .5, 1, 1, 1, 1, 0, .5, 1 ], # Psy
[ 1, .5, 1, 1, 2, 1, .5, .5, 1, .5, 2, 1, 1, .5, 1, 2, .5, 1 ], # Bug
[ 1, 2, 1, 1, 1, 2, .5, 1, .5, 2, 1, 2, 1, 1, 1, 1, .5, 1 ], # PI:NAME:<NAME>END_PIoc
[ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 2, 1, .5, .5, 1 ], # PI:NAME:<NAME>END_PIho
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, .5, 1 ], # PI:NAME:<NAME>END_PIra
[ 1, 1, 1, 1, 1, 1, .5, 1, 1, 1, 2, 1, 1, 2, 1, .5, .5, 1 ], # PI:NAME:<NAME>END_PI
[ 1, .5, .5, .5, 1, 2, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, .5, 1 ], # PI:NAME:<NAME>END_PI
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ] # ???
]
|
[
{
"context": "itor (of confines, of-course)\n [ [ 1, 5, \"JU\"]\n , [ 3, 6, \"ME\"]\n , [ 3, 20, \"MA",
"end": 1719,
"score": 0.9996891617774963,
"start": 1717,
"tag": "NAME",
"value": "JU"
},
{
"context": "rse)\n [ [ 1, 5, \"JU\"]\n , [ 3, 6, \... | test/lib/cosmos.spec.coffee | astrolet/archai | 1 | cosmos = new (require "../../index").Cosmos
_ = require "underscore"
inspect = (require "eyes").inspector()
assert = (require "chai").assert
should = (require "chai").should
describe "Cosmos:", ->
describe "built with defaults -", ->
it "has an 'element' attribute among many", ->
assert cosmos.zodiac.id(12).get('element') is "W"
describe "dispositor defaults -", ->
it "has at least one 'domicile' dispositor", ->
theFishes = cosmos.zodiac.id 12
assert theFishes.get('domicile') is "JU"
assert theFishes.domicile().get('id') is "JU"
it "has at least one 'exaltation' dispositor", ->
theCrab = cosmos.zodiac.id 4
assert theCrab.get('exaltation') is "JU"
assert theCrab.exaltation().get('id') is "JU"
it "the Crab has all the three Trigon Lords set", ->
theCrab = cosmos.zodiac.id 4
theCrab.trigons.pluck('lord').should.eql ['MO', 'VE', 'MA']
assert theCrab.trigons.day().get('id') is 'VE'
assert theCrab.trigons.night().get('id') is 'MA'
assert theCrab.trigons.cooperating().get('id') is 'MO'
it "there are dispositors that aren't planets, i.e. the exalted nodes", ->
assert cosmos.zodiac.id(3).exaltation().get('id') is "NN"
assert cosmos.zodiac.id(9).exaltation().get('id') is "SN"
it "can handle the no exaltation dispositors, getting the *none* item", ->
cosmos.zodiac.id(8).exaltation().should.eql cosmos.ensemble.getNone()
it "can get the Confines Lords, given certain Representation portions", ->
# These aren't boundary-testing portions, but rather Orlin's verification.
rpd = # representation, portion, dispositor (of confines, of-course)
[ [ 1, 5, "JU"]
, [ 3, 6, "ME"]
, [ 3, 20, "MA"]
, [ 4, 9, "VE"]
, [ 4, 25, "JU"]
, [ 5, 14, "SA"]
, [ 5, 24, "ME"]
, [ 6, 19, "JU"]
, [ 7, 5, "SA"]
, [ 7, 24, "VE"]
, [ 7, 29, "MA"]
, [ 8, 15, "ME"]
, [ 8, 29, "SA"]
, [ 9, 8, "JU"]
, [ 9, 14, "VE"]
, [ 9, 20, "ME"]
, [10, 3, "ME"]
, [10, 13, "JU"]
, [10, 17, "VE"]
, [12, 18, "ME"]
]
for c in rpd
# Explicitly check for Egyptian Confines.
assert cosmos.zodiac.id(c[0]).confines.followed([c[0], c[1]], 'EC').get('id') is c[2]
# inspect cosmos.zodiac.confines rpd
| 107616 | cosmos = new (require "../../index").Cosmos
_ = require "underscore"
inspect = (require "eyes").inspector()
assert = (require "chai").assert
should = (require "chai").should
describe "Cosmos:", ->
describe "built with defaults -", ->
it "has an 'element' attribute among many", ->
assert cosmos.zodiac.id(12).get('element') is "W"
describe "dispositor defaults -", ->
it "has at least one 'domicile' dispositor", ->
theFishes = cosmos.zodiac.id 12
assert theFishes.get('domicile') is "JU"
assert theFishes.domicile().get('id') is "JU"
it "has at least one 'exaltation' dispositor", ->
theCrab = cosmos.zodiac.id 4
assert theCrab.get('exaltation') is "JU"
assert theCrab.exaltation().get('id') is "JU"
it "the Crab has all the three Trigon Lords set", ->
theCrab = cosmos.zodiac.id 4
theCrab.trigons.pluck('lord').should.eql ['MO', 'VE', 'MA']
assert theCrab.trigons.day().get('id') is 'VE'
assert theCrab.trigons.night().get('id') is 'MA'
assert theCrab.trigons.cooperating().get('id') is 'MO'
it "there are dispositors that aren't planets, i.e. the exalted nodes", ->
assert cosmos.zodiac.id(3).exaltation().get('id') is "NN"
assert cosmos.zodiac.id(9).exaltation().get('id') is "SN"
it "can handle the no exaltation dispositors, getting the *none* item", ->
cosmos.zodiac.id(8).exaltation().should.eql cosmos.ensemble.getNone()
it "can get the Confines Lords, given certain Representation portions", ->
# These aren't boundary-testing portions, but rather Orlin's verification.
rpd = # representation, portion, dispositor (of confines, of-course)
[ [ 1, 5, "<NAME>"]
, [ 3, 6, "<NAME>"]
, [ 3, 20, "<NAME>"]
, [ 4, 9, "<NAME>"]
, [ 4, 25, "<NAME>"]
, [ 5, 14, "<NAME>"]
, [ 5, 24, "<NAME>"]
, [ 6, 19, "<NAME>"]
, [ 7, 5, "<NAME>"]
, [ 7, 24, "<NAME>"]
, [ 7, 29, "<NAME>"]
, [ 8, 15, "<NAME>"]
, [ 8, 29, "<NAME>"]
, [ 9, 8, "<NAME>"]
, [ 9, 14, "<NAME>"]
, [ 9, 20, "<NAME>"]
, [10, 3, "<NAME>"]
, [10, 13, "<NAME>"]
, [10, 17, "<NAME>"]
, [12, 18, "<NAME>"]
]
for c in rpd
# Explicitly check for Egyptian Confines.
assert cosmos.zodiac.id(c[0]).confines.followed([c[0], c[1]], 'EC').get('id') is c[2]
# inspect cosmos.zodiac.confines rpd
| true | cosmos = new (require "../../index").Cosmos
_ = require "underscore"
inspect = (require "eyes").inspector()
assert = (require "chai").assert
should = (require "chai").should
describe "Cosmos:", ->
describe "built with defaults -", ->
it "has an 'element' attribute among many", ->
assert cosmos.zodiac.id(12).get('element') is "W"
describe "dispositor defaults -", ->
it "has at least one 'domicile' dispositor", ->
theFishes = cosmos.zodiac.id 12
assert theFishes.get('domicile') is "JU"
assert theFishes.domicile().get('id') is "JU"
it "has at least one 'exaltation' dispositor", ->
theCrab = cosmos.zodiac.id 4
assert theCrab.get('exaltation') is "JU"
assert theCrab.exaltation().get('id') is "JU"
it "the Crab has all the three Trigon Lords set", ->
theCrab = cosmos.zodiac.id 4
theCrab.trigons.pluck('lord').should.eql ['MO', 'VE', 'MA']
assert theCrab.trigons.day().get('id') is 'VE'
assert theCrab.trigons.night().get('id') is 'MA'
assert theCrab.trigons.cooperating().get('id') is 'MO'
it "there are dispositors that aren't planets, i.e. the exalted nodes", ->
assert cosmos.zodiac.id(3).exaltation().get('id') is "NN"
assert cosmos.zodiac.id(9).exaltation().get('id') is "SN"
it "can handle the no exaltation dispositors, getting the *none* item", ->
cosmos.zodiac.id(8).exaltation().should.eql cosmos.ensemble.getNone()
it "can get the Confines Lords, given certain Representation portions", ->
# These aren't boundary-testing portions, but rather Orlin's verification.
rpd = # representation, portion, dispositor (of confines, of-course)
[ [ 1, 5, "PI:NAME:<NAME>END_PI"]
, [ 3, 6, "PI:NAME:<NAME>END_PI"]
, [ 3, 20, "PI:NAME:<NAME>END_PI"]
, [ 4, 9, "PI:NAME:<NAME>END_PI"]
, [ 4, 25, "PI:NAME:<NAME>END_PI"]
, [ 5, 14, "PI:NAME:<NAME>END_PI"]
, [ 5, 24, "PI:NAME:<NAME>END_PI"]
, [ 6, 19, "PI:NAME:<NAME>END_PI"]
, [ 7, 5, "PI:NAME:<NAME>END_PI"]
, [ 7, 24, "PI:NAME:<NAME>END_PI"]
, [ 7, 29, "PI:NAME:<NAME>END_PI"]
, [ 8, 15, "PI:NAME:<NAME>END_PI"]
, [ 8, 29, "PI:NAME:<NAME>END_PI"]
, [ 9, 8, "PI:NAME:<NAME>END_PI"]
, [ 9, 14, "PI:NAME:<NAME>END_PI"]
, [ 9, 20, "PI:NAME:<NAME>END_PI"]
, [10, 3, "PI:NAME:<NAME>END_PI"]
, [10, 13, "PI:NAME:<NAME>END_PI"]
, [10, 17, "PI:NAME:<NAME>END_PI"]
, [12, 18, "PI:NAME:<NAME>END_PI"]
]
for c in rpd
# Explicitly check for Egyptian Confines.
assert cosmos.zodiac.id(c[0]).confines.followed([c[0], c[1]], 'EC').get('id') is c[2]
# inspect cosmos.zodiac.confines rpd
|
[
{
"context": "'Heroes' may get a second lease\"\n author: \"Nathan Ingraham\"\n origin:\n title: \"The V",
"end": 3454,
"score": 0.9998666048049927,
"start": 3448,
"tag": "NAME",
"value": "Nathan"
}
] | my-feed-title/node_modules/feedly/test/feedly.test.coffee | uraway/Learnings | 0 | fs = require 'fs'
request = require 'request'
q = require 'q'
Feedly = require '../lib/feedly'
FEEDLY_SECRET = process.env.FEEDLY_SECRET
if !FEEDLY_SECRET?
throw new Error """
Specify the client secret in the FEEDLY_SECRET environment variable
Find it here: https://groups.google.com/forum/#!forum/feedly-cloud
"""
FEED_URL = 'http://blog.foodnetwork.com/fn-dish/feed/'
FEED = "feed/#{FEED_URL}"
CONFIG = "#{__dirname}/test_config.json"
module.exports =
feeds: (test)->
f = new Feedly
client_id: 'sandbox'
client_secret: FEEDLY_SECRET
base: 'http://sandbox.feedly.com'
port: 8080
config_file: CONFIG
test.ok f
test.equals f.options.base, 'http://sandbox.feedly.com'
f.profile()
.then (prof) ->
test.ok prof
f.updateProfile
gender: 'male'
.then ->
f.preferences()
.then (prefs) ->
test.ok prefs
f.updatePreferences
"category/reviews/entryOverviewSize": 0
.then ->
f.updatePreferences
"category/reviews/entryOverviewSize": "==DELETE=="
.then ->
f.refresh()
.then ->
f.subscribe FEED
.then ->
f.subscriptions()
.then (subs) ->
test.ok subs
sub = subs.find (s) ->
return s.id == FEED
test.ok sub
.then ->
test.ok true
f.unsubscribe FEED
.then ->
test.ok true
f.subscribe FEED_URL, ['testing_foo', 'testing_bar']
.then ->
test.ok true
f.feed FEED
.then (fee) ->
test.equals fee.id, FEED
f.categories()
.then (cats) ->
test.ok Array.isArray(cats)
test.ok cats.length >= 2
foo = cats.find (c) ->
c.label == 'testing_foo'
test.ok foo?
f.setCategoryLabel foo.id, 'testing_foo2'
.then ->
f.deleteCategory foo.id
.then ->
f.counts()
.then (counts)->
test.ok Array.isArray(counts.unreadcounts)
test.ok counts.unreadcounts.length >= 2
f.stream FEED
.then (page) ->
ent = page.ids[0]
f.entry ent
.then (entries) ->
test.ok entries?
test.ok entries.length > 0
id = entries[0].id
f.markEntryRead id
.then ->
f.markEntryUnread id
.then ->
f.tagEntry id, 'test_tag_foo'
.then ->
f.tags()
.then (tags) ->
test.ok tags
f.untagEntries id, 'test_tag_foo'
.then ->
f.setTagLabel 'test_tag_foo', 'test_tag_foo2'
.then ->
f.untagEntries id, 'test_tag_foo'
.then ->
f.deleteTags 'test_tag_foo'
.then ->
f.shorten id
.then (short) ->
test.ok short
test.ok typeof(short.shortUrl) == 'string'
.then ->
f.contents FEED
.then (contents) ->
test.ok contents
test.ok Array.isArray(contents.items)
test.ok contents.continuation
f.contents FEED, contents.continuation
.then (contents) ->
test.ok contents
f.markFeedRead FEED
.then ->
f.markCategoryRead 'testing_bar'
.then ->
f.reads()
.then (reads) ->
test.ok reads
test.ok Array.isArray(reads.entries)
.then ->
f.searchFeeds 'arduino'
.then (results) ->
test.ok results
test.ok Array.isArray(results.results)
f.unsubscribe FEED
.then ->
userid = f.state.id
f.createEntry
title: "NBC's reviled sci-fi drama 'Heroes' may get a second lease"
author: "Nathan Ingraham"
origin:
title: "The Verge - All Posts"
htmlUrl: "http://www.theverge.com/"
content:
direction: "ltr"
content: "...html content the user wants to associate with this entry.."
alternate: [
type: "text/html"
href: "http://www.theverge.com/2013/4/17/4236096/nbc-heroes-may-get-a-second-lease-on-life-on-xbox-live"
]
tags: [
{
id: "user/#{userid}/tag/global.saved"
}
{
id: "user/#{userid}/tag/inspiration"
label: "inspiration"
}
]
keywords: [
"NBC"
"sci-fi"
]
.then ->
f.logout()
.then ->
q.nfcall fs.unlink, CONFIG
.then ->
test.done()
, (er) ->
console.log 'ERROR', er, er.stack
test.ifError er
| 125082 | fs = require 'fs'
request = require 'request'
q = require 'q'
Feedly = require '../lib/feedly'
FEEDLY_SECRET = process.env.FEEDLY_SECRET
if !FEEDLY_SECRET?
throw new Error """
Specify the client secret in the FEEDLY_SECRET environment variable
Find it here: https://groups.google.com/forum/#!forum/feedly-cloud
"""
FEED_URL = 'http://blog.foodnetwork.com/fn-dish/feed/'
FEED = "feed/#{FEED_URL}"
CONFIG = "#{__dirname}/test_config.json"
module.exports =
feeds: (test)->
f = new Feedly
client_id: 'sandbox'
client_secret: FEEDLY_SECRET
base: 'http://sandbox.feedly.com'
port: 8080
config_file: CONFIG
test.ok f
test.equals f.options.base, 'http://sandbox.feedly.com'
f.profile()
.then (prof) ->
test.ok prof
f.updateProfile
gender: 'male'
.then ->
f.preferences()
.then (prefs) ->
test.ok prefs
f.updatePreferences
"category/reviews/entryOverviewSize": 0
.then ->
f.updatePreferences
"category/reviews/entryOverviewSize": "==DELETE=="
.then ->
f.refresh()
.then ->
f.subscribe FEED
.then ->
f.subscriptions()
.then (subs) ->
test.ok subs
sub = subs.find (s) ->
return s.id == FEED
test.ok sub
.then ->
test.ok true
f.unsubscribe FEED
.then ->
test.ok true
f.subscribe FEED_URL, ['testing_foo', 'testing_bar']
.then ->
test.ok true
f.feed FEED
.then (fee) ->
test.equals fee.id, FEED
f.categories()
.then (cats) ->
test.ok Array.isArray(cats)
test.ok cats.length >= 2
foo = cats.find (c) ->
c.label == 'testing_foo'
test.ok foo?
f.setCategoryLabel foo.id, 'testing_foo2'
.then ->
f.deleteCategory foo.id
.then ->
f.counts()
.then (counts)->
test.ok Array.isArray(counts.unreadcounts)
test.ok counts.unreadcounts.length >= 2
f.stream FEED
.then (page) ->
ent = page.ids[0]
f.entry ent
.then (entries) ->
test.ok entries?
test.ok entries.length > 0
id = entries[0].id
f.markEntryRead id
.then ->
f.markEntryUnread id
.then ->
f.tagEntry id, 'test_tag_foo'
.then ->
f.tags()
.then (tags) ->
test.ok tags
f.untagEntries id, 'test_tag_foo'
.then ->
f.setTagLabel 'test_tag_foo', 'test_tag_foo2'
.then ->
f.untagEntries id, 'test_tag_foo'
.then ->
f.deleteTags 'test_tag_foo'
.then ->
f.shorten id
.then (short) ->
test.ok short
test.ok typeof(short.shortUrl) == 'string'
.then ->
f.contents FEED
.then (contents) ->
test.ok contents
test.ok Array.isArray(contents.items)
test.ok contents.continuation
f.contents FEED, contents.continuation
.then (contents) ->
test.ok contents
f.markFeedRead FEED
.then ->
f.markCategoryRead 'testing_bar'
.then ->
f.reads()
.then (reads) ->
test.ok reads
test.ok Array.isArray(reads.entries)
.then ->
f.searchFeeds 'arduino'
.then (results) ->
test.ok results
test.ok Array.isArray(results.results)
f.unsubscribe FEED
.then ->
userid = f.state.id
f.createEntry
title: "NBC's reviled sci-fi drama 'Heroes' may get a second lease"
author: "<NAME> Ingraham"
origin:
title: "The Verge - All Posts"
htmlUrl: "http://www.theverge.com/"
content:
direction: "ltr"
content: "...html content the user wants to associate with this entry.."
alternate: [
type: "text/html"
href: "http://www.theverge.com/2013/4/17/4236096/nbc-heroes-may-get-a-second-lease-on-life-on-xbox-live"
]
tags: [
{
id: "user/#{userid}/tag/global.saved"
}
{
id: "user/#{userid}/tag/inspiration"
label: "inspiration"
}
]
keywords: [
"NBC"
"sci-fi"
]
.then ->
f.logout()
.then ->
q.nfcall fs.unlink, CONFIG
.then ->
test.done()
, (er) ->
console.log 'ERROR', er, er.stack
test.ifError er
| true | fs = require 'fs'
request = require 'request'
q = require 'q'
Feedly = require '../lib/feedly'
FEEDLY_SECRET = process.env.FEEDLY_SECRET
if !FEEDLY_SECRET?
throw new Error """
Specify the client secret in the FEEDLY_SECRET environment variable
Find it here: https://groups.google.com/forum/#!forum/feedly-cloud
"""
FEED_URL = 'http://blog.foodnetwork.com/fn-dish/feed/'
FEED = "feed/#{FEED_URL}"
CONFIG = "#{__dirname}/test_config.json"
module.exports =
feeds: (test)->
f = new Feedly
client_id: 'sandbox'
client_secret: FEEDLY_SECRET
base: 'http://sandbox.feedly.com'
port: 8080
config_file: CONFIG
test.ok f
test.equals f.options.base, 'http://sandbox.feedly.com'
f.profile()
.then (prof) ->
test.ok prof
f.updateProfile
gender: 'male'
.then ->
f.preferences()
.then (prefs) ->
test.ok prefs
f.updatePreferences
"category/reviews/entryOverviewSize": 0
.then ->
f.updatePreferences
"category/reviews/entryOverviewSize": "==DELETE=="
.then ->
f.refresh()
.then ->
f.subscribe FEED
.then ->
f.subscriptions()
.then (subs) ->
test.ok subs
sub = subs.find (s) ->
return s.id == FEED
test.ok sub
.then ->
test.ok true
f.unsubscribe FEED
.then ->
test.ok true
f.subscribe FEED_URL, ['testing_foo', 'testing_bar']
.then ->
test.ok true
f.feed FEED
.then (fee) ->
test.equals fee.id, FEED
f.categories()
.then (cats) ->
test.ok Array.isArray(cats)
test.ok cats.length >= 2
foo = cats.find (c) ->
c.label == 'testing_foo'
test.ok foo?
f.setCategoryLabel foo.id, 'testing_foo2'
.then ->
f.deleteCategory foo.id
.then ->
f.counts()
.then (counts)->
test.ok Array.isArray(counts.unreadcounts)
test.ok counts.unreadcounts.length >= 2
f.stream FEED
.then (page) ->
ent = page.ids[0]
f.entry ent
.then (entries) ->
test.ok entries?
test.ok entries.length > 0
id = entries[0].id
f.markEntryRead id
.then ->
f.markEntryUnread id
.then ->
f.tagEntry id, 'test_tag_foo'
.then ->
f.tags()
.then (tags) ->
test.ok tags
f.untagEntries id, 'test_tag_foo'
.then ->
f.setTagLabel 'test_tag_foo', 'test_tag_foo2'
.then ->
f.untagEntries id, 'test_tag_foo'
.then ->
f.deleteTags 'test_tag_foo'
.then ->
f.shorten id
.then (short) ->
test.ok short
test.ok typeof(short.shortUrl) == 'string'
.then ->
f.contents FEED
.then (contents) ->
test.ok contents
test.ok Array.isArray(contents.items)
test.ok contents.continuation
f.contents FEED, contents.continuation
.then (contents) ->
test.ok contents
f.markFeedRead FEED
.then ->
f.markCategoryRead 'testing_bar'
.then ->
f.reads()
.then (reads) ->
test.ok reads
test.ok Array.isArray(reads.entries)
.then ->
f.searchFeeds 'arduino'
.then (results) ->
test.ok results
test.ok Array.isArray(results.results)
f.unsubscribe FEED
.then ->
userid = f.state.id
f.createEntry
title: "NBC's reviled sci-fi drama 'Heroes' may get a second lease"
author: "PI:NAME:<NAME>END_PI Ingraham"
origin:
title: "The Verge - All Posts"
htmlUrl: "http://www.theverge.com/"
content:
direction: "ltr"
content: "...html content the user wants to associate with this entry.."
alternate: [
type: "text/html"
href: "http://www.theverge.com/2013/4/17/4236096/nbc-heroes-may-get-a-second-lease-on-life-on-xbox-live"
]
tags: [
{
id: "user/#{userid}/tag/global.saved"
}
{
id: "user/#{userid}/tag/inspiration"
label: "inspiration"
}
]
keywords: [
"NBC"
"sci-fi"
]
.then ->
f.logout()
.then ->
q.nfcall fs.unlink, CONFIG
.then ->
test.done()
, (er) ->
console.log 'ERROR', er, er.stack
test.ifError er
|
[
{
"context": "# Copyright © 2014–6 Brad Ackerman.\n#\n# Licensed under the Apache License, Version 2",
"end": 34,
"score": 0.9998512268066406,
"start": 21,
"tag": "NAME",
"value": "Brad Ackerman"
}
] | assets/coffee/promise-buttons.coffee | backerman/eveindy | 2 | # Copyright © 2014–6 Brad Ackerman.
#
# 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.
angular.module 'eveindy'
.config ['angularPromiseButtonsProvider', (angularPromiseButtonsProvider) ->
angularPromiseButtonsProvider.extendConfig
spinnerTpl: '<span class="btn-spinner spinner-sm spinner-inline"></span>'
disableBtn: true
btnLoadingClass: 'is-loading'
addClassToCurrentBtnOnly: false
disableCurrentBtnOnly: false
]
| 173981 | # Copyright © 2014–6 <NAME>.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
angular.module 'eveindy'
.config ['angularPromiseButtonsProvider', (angularPromiseButtonsProvider) ->
angularPromiseButtonsProvider.extendConfig
spinnerTpl: '<span class="btn-spinner spinner-sm spinner-inline"></span>'
disableBtn: true
btnLoadingClass: 'is-loading'
addClassToCurrentBtnOnly: false
disableCurrentBtnOnly: false
]
| true | # Copyright © 2014–6 PI:NAME:<NAME>END_PI.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
angular.module 'eveindy'
.config ['angularPromiseButtonsProvider', (angularPromiseButtonsProvider) ->
angularPromiseButtonsProvider.extendConfig
spinnerTpl: '<span class="btn-spinner spinner-sm spinner-inline"></span>'
disableBtn: true
btnLoadingClass: 'is-loading'
addClassToCurrentBtnOnly: false
disableCurrentBtnOnly: false
]
|
[
{
"context": "username': config.mongoUser\n 'mongo-password': config.mongoPass\n \"http-port\": config.port\n\n server = cube.se",
"end": 1069,
"score": 0.9861753582954407,
"start": 1053,
"tag": "PASSWORD",
"value": "config.mongoPass"
}
] | app.coffee | cveksitron/cube-evaluator | 0 | require('coffee-script')
config = require("./config")
cors = require('cors')
cube = require("cube")
express = require('express')
http = require('http')
logger = require('logfmt')
pkg = require('./package.json')
requestid = require('connect-requestid')
app = express()
app.set 'port', config.port
app.set 'version', pkg.version
app.use logger.requestLogger()
app.use express.json()
app.use express.methodOverride()
app.use express.responseTime()
app.use requestid
# CORS
corsOptions = { origin: true, credentials: true }
app.use cors(corsOptions)
app.options('*', cors(corsOptions))
# Basic auth
if config.is(config.basicAuthUsername) && config.is(config.basicAuthPassword)
logger.log(msg: "Enabling BASIC authentication.", username: config.basicAuthUsername)
app.use express.basicAuth(config.basicAuthUsername, config.basicAuthPassword)
# Connect to database and configure server.
start = (callback) ->
options =
'mongo-url': config.mongoUrl
'mongo-username': config.mongoUser
'mongo-password': config.mongoPass
"http-port": config.port
server = cube.server(options)
server.register = (db, endpoints) ->
app.set('db', db)
cube.evaluator.register(db, endpoints)
server.start()
module.exports = {server: app, start: start}
| 81512 | require('coffee-script')
config = require("./config")
cors = require('cors')
cube = require("cube")
express = require('express')
http = require('http')
logger = require('logfmt')
pkg = require('./package.json')
requestid = require('connect-requestid')
app = express()
app.set 'port', config.port
app.set 'version', pkg.version
app.use logger.requestLogger()
app.use express.json()
app.use express.methodOverride()
app.use express.responseTime()
app.use requestid
# CORS
corsOptions = { origin: true, credentials: true }
app.use cors(corsOptions)
app.options('*', cors(corsOptions))
# Basic auth
if config.is(config.basicAuthUsername) && config.is(config.basicAuthPassword)
logger.log(msg: "Enabling BASIC authentication.", username: config.basicAuthUsername)
app.use express.basicAuth(config.basicAuthUsername, config.basicAuthPassword)
# Connect to database and configure server.
start = (callback) ->
options =
'mongo-url': config.mongoUrl
'mongo-username': config.mongoUser
'mongo-password': <PASSWORD>
"http-port": config.port
server = cube.server(options)
server.register = (db, endpoints) ->
app.set('db', db)
cube.evaluator.register(db, endpoints)
server.start()
module.exports = {server: app, start: start}
| true | require('coffee-script')
config = require("./config")
cors = require('cors')
cube = require("cube")
express = require('express')
http = require('http')
logger = require('logfmt')
pkg = require('./package.json')
requestid = require('connect-requestid')
app = express()
app.set 'port', config.port
app.set 'version', pkg.version
app.use logger.requestLogger()
app.use express.json()
app.use express.methodOverride()
app.use express.responseTime()
app.use requestid
# CORS
corsOptions = { origin: true, credentials: true }
app.use cors(corsOptions)
app.options('*', cors(corsOptions))
# Basic auth
if config.is(config.basicAuthUsername) && config.is(config.basicAuthPassword)
logger.log(msg: "Enabling BASIC authentication.", username: config.basicAuthUsername)
app.use express.basicAuth(config.basicAuthUsername, config.basicAuthPassword)
# Connect to database and configure server.
start = (callback) ->
options =
'mongo-url': config.mongoUrl
'mongo-username': config.mongoUser
'mongo-password': PI:PASSWORD:<PASSWORD>END_PI
"http-port": config.port
server = cube.server(options)
server.register = (db, endpoints) ->
app.set('db', db)
cube.evaluator.register(db, endpoints)
server.start()
module.exports = {server: app, start: start}
|
[
{
"context": "firstName + ' ' + @lastName\n\nperson = new Person 'Jeremy', 'Ruten'\nname = person.name()\n\n# Trace:\n# 1: b",
"end": 128,
"score": 0.9998825192451477,
"start": 122,
"tag": "NAME",
"value": "Jeremy"
},
{
"context": "+ ' ' + @lastName\n\nperson = new Person 'Jeremy',... | test/traces/coffee/class.coffee | paigeruten/pencil-tracer | 1 | class Person
constructor: (@firstName, @lastName) ->
name: ->
@firstName + ' ' + @lastName
person = new Person 'Jeremy', 'Ruten'
name = person.name()
# Trace:
# 1: before Person=<function>
# 1: after Person=<function>
# 2: before
# 2: after
# 4: before
# 4: after
# 7: before person=/
# 2: enter @firstName='Jeremy' @lastName='Ruten'
# 2: leave return=/
# 7: after person=<object> Person()=<object>
# 8: before person=<object> name=/
# 4: enter
# 5: before @firstName='Jeremy' @lastName='Ruten'
# 5: after @firstName='Jeremy' @lastName='Ruten'
# 4: leave return='Jeremy Ruten'
# 8: after person=<object> name='Jeremy Ruten' name()='Jeremy Ruten'
| 133749 | class Person
constructor: (@firstName, @lastName) ->
name: ->
@firstName + ' ' + @lastName
person = new Person '<NAME>', '<NAME>'
name = person.name()
# Trace:
# 1: before Person=<function>
# 1: after Person=<function>
# 2: before
# 2: after
# 4: before
# 4: after
# 7: before person=/
# 2: enter @firstName='<NAME>' @lastName='<NAME>'
# 2: leave return=/
# 7: after person=<object> Person()=<object>
# 8: before person=<object> name=/
# 4: enter
# 5: before @firstName='<NAME>' @lastName='<NAME>'
# 5: after @firstName='<NAME>' @lastName='<NAME>'
# 4: leave return='<NAME>'
# 8: after person=<object> name='<NAME>' name()='<NAME>'
| true | class Person
constructor: (@firstName, @lastName) ->
name: ->
@firstName + ' ' + @lastName
person = new Person 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI'
name = person.name()
# Trace:
# 1: before Person=<function>
# 1: after Person=<function>
# 2: before
# 2: after
# 4: before
# 4: after
# 7: before person=/
# 2: enter @firstName='PI:NAME:<NAME>END_PI' @lastName='PI:NAME:<NAME>END_PI'
# 2: leave return=/
# 7: after person=<object> Person()=<object>
# 8: before person=<object> name=/
# 4: enter
# 5: before @firstName='PI:NAME:<NAME>END_PI' @lastName='PI:NAME:<NAME>END_PI'
# 5: after @firstName='PI:NAME:<NAME>END_PI' @lastName='PI:NAME:<NAME>END_PI'
# 4: leave return='PI:NAME:<NAME>END_PI'
# 8: after person=<object> name='PI:NAME:<NAME>END_PI' name()='PI:NAME:<NAME>END_PI'
|
[
{
"context": "miter\n path = delimiter + path\n\n key = \"#{id}#{path}\"\n\n getRemote(bucket, key)\n .then n",
"end": 4238,
"score": 0.9981131553649902,
"start": 4230,
"tag": "KEY",
"value": "\"#{id}#{"
},
{
"context": " path = delimiter + path\n\n key = \... | lib/s3-fs.coffee | STRd6/zine | 12 | Bindable = require "bindable"
Model = require "model"
delimiter = "/"
status = (response) ->
if response.status >= 200 && response.status < 300
return response
else
throw response
json = (response) ->
response.json()
blob = (response) ->
response.blob()
module.exports = (id, bucket, refreshCredentials) ->
{pinvoke, startsWith, endsWith} = require "../util"
refreshCredentials ?= -> Promise.reject new Error "No method given to refresh credentials automatically"
refreshCredentialsPromise = Promise.resolve()
do (oldPromiseInvoke=pinvoke) ->
pinvoke = (args...) ->
# Guard for expired credentials
refreshCredentialsPromise.then ->
oldPromiseInvoke.apply(null, args)
.catch (e) ->
if e.code is "CredentialsError"
console.info "Refreshing credentials after CredentialsError", e
refreshCredentialsPromise = refreshCredentials()
refreshCredentialsPromise.then ->
# Retry calls after refreshing expired credentials
oldPromiseInvoke.apply(null, args)
else
throw e
localCache = {}
metaCache = {}
uploadToS3 = (bucket, key, file, options={}) ->
{cacheControl} = options
cacheControl ?= 0
# Optimistically Cache
localCache[key] = file
metaCache[key] =
ContentType: file.type
UpdatedAt: new Date
pinvoke bucket, "putObject",
Key: key
ContentType: file.type
Body: file
CacheControl: "max-age=#{cacheControl}"
getRemote = (bucket, key) ->
cachedItem = localCache[key]
if cachedItem
if cachedItem instanceof Blob
return Promise.resolve(cachedItem)
else
return Promise.reject(cachedItem)
pinvoke bucket, "getObject",
Key: key
.then (data) ->
{Body, ContentType} = data
new Blob [Body],
type: ContentType
.then (data) ->
localCache[key] = data
.catch (e) ->
# Cache Not Founds too, since that's often what is slow
localCache[key] = e
throw e
deleteFromS3 = (bucket, key) ->
localCache[key] = new Error "Not Found"
delete metaCache[key]
pinvoke bucket, "deleteObject",
Key: key
list = (bucket, id, dir) ->
unless startsWith dir, delimiter
dir = "#{delimiter}#{dir}"
unless endsWith dir, delimiter
dir = "#{dir}#{delimiter}"
prefix = "#{id}#{dir}"
pinvoke bucket, "listObjects",
Prefix: prefix
Delimiter: delimiter
.then (result) ->
results = result.CommonPrefixes.map (p) ->
FolderEntry p.Prefix, id, prefix
.concat result.Contents.map (o) ->
FileEntry o, id, prefix, bucket
.map (entry) ->
fetchMeta(entry, bucket)
Promise.all results
fetchFileMeta = (key, bucket) ->
cachedItem = metaCache[key]
if cachedItem
return Promise.resolve(cachedItem)
pinvoke bucket, "headObject",
Key: key
.then (result) ->
metaCache[key] = result
return result
fetchMeta = (entry, bucket) ->
Promise.resolve()
.then ->
return entry if entry.folder
fetchFileMeta(entry.remotePath, bucket)
.then (meta) ->
entry.type = meta.ContentType
entry.updatedAt = new Date(meta.LastModified)
return entry
notify = (eventType, path) ->
(result) ->
self.trigger eventType, path
return result
FolderEntry = (path, id, prefix) ->
folder: true
path: path.replace(id, "")
relativePath: path.replace(prefix, "")
remotePath: path
FileEntry = (object, id, prefix, bucket) ->
path = object.Key
entry =
path: path.replace(id, "")
relativePath: path.replace(prefix, "")
remotePath: path
size: object.Size
entry.blob = BlobSham(entry, bucket)
return entry
BlobSham = (entry, bucket) ->
remotePath = entry.remotePath
getURL: ->
getRemote(bucket, remotePath)
.then URL.createObjectURL
readAsText: ->
getRemote(bucket, remotePath)
.then (blob) ->
blob.readAsText()
self = Model()
.include Bindable
.extend
read: (path) ->
unless startsWith path, delimiter
path = delimiter + path
key = "#{id}#{path}"
getRemote(bucket, key)
.then notify "read", path
write: (path, blob) ->
unless startsWith path, delimiter
path = delimiter + path
key = "#{id}#{path}"
uploadToS3 bucket, key, blob
.then notify "write", path
delete: (path) ->
unless startsWith path, delimiter
path = delimiter + path
key = "#{id}#{path}"
deleteFromS3 bucket, key
.then notify "delete", path
list: (folderPath="/") ->
list bucket, id, folderPath
.then notify "list", folderPath
| 69588 | Bindable = require "bindable"
Model = require "model"
delimiter = "/"
status = (response) ->
if response.status >= 200 && response.status < 300
return response
else
throw response
json = (response) ->
response.json()
blob = (response) ->
response.blob()
module.exports = (id, bucket, refreshCredentials) ->
{pinvoke, startsWith, endsWith} = require "../util"
refreshCredentials ?= -> Promise.reject new Error "No method given to refresh credentials automatically"
refreshCredentialsPromise = Promise.resolve()
do (oldPromiseInvoke=pinvoke) ->
pinvoke = (args...) ->
# Guard for expired credentials
refreshCredentialsPromise.then ->
oldPromiseInvoke.apply(null, args)
.catch (e) ->
if e.code is "CredentialsError"
console.info "Refreshing credentials after CredentialsError", e
refreshCredentialsPromise = refreshCredentials()
refreshCredentialsPromise.then ->
# Retry calls after refreshing expired credentials
oldPromiseInvoke.apply(null, args)
else
throw e
localCache = {}
metaCache = {}
uploadToS3 = (bucket, key, file, options={}) ->
{cacheControl} = options
cacheControl ?= 0
# Optimistically Cache
localCache[key] = file
metaCache[key] =
ContentType: file.type
UpdatedAt: new Date
pinvoke bucket, "putObject",
Key: key
ContentType: file.type
Body: file
CacheControl: "max-age=#{cacheControl}"
getRemote = (bucket, key) ->
cachedItem = localCache[key]
if cachedItem
if cachedItem instanceof Blob
return Promise.resolve(cachedItem)
else
return Promise.reject(cachedItem)
pinvoke bucket, "getObject",
Key: key
.then (data) ->
{Body, ContentType} = data
new Blob [Body],
type: ContentType
.then (data) ->
localCache[key] = data
.catch (e) ->
# Cache Not Founds too, since that's often what is slow
localCache[key] = e
throw e
deleteFromS3 = (bucket, key) ->
localCache[key] = new Error "Not Found"
delete metaCache[key]
pinvoke bucket, "deleteObject",
Key: key
list = (bucket, id, dir) ->
unless startsWith dir, delimiter
dir = "#{delimiter}#{dir}"
unless endsWith dir, delimiter
dir = "#{dir}#{delimiter}"
prefix = "#{id}#{dir}"
pinvoke bucket, "listObjects",
Prefix: prefix
Delimiter: delimiter
.then (result) ->
results = result.CommonPrefixes.map (p) ->
FolderEntry p.Prefix, id, prefix
.concat result.Contents.map (o) ->
FileEntry o, id, prefix, bucket
.map (entry) ->
fetchMeta(entry, bucket)
Promise.all results
fetchFileMeta = (key, bucket) ->
cachedItem = metaCache[key]
if cachedItem
return Promise.resolve(cachedItem)
pinvoke bucket, "headObject",
Key: key
.then (result) ->
metaCache[key] = result
return result
fetchMeta = (entry, bucket) ->
Promise.resolve()
.then ->
return entry if entry.folder
fetchFileMeta(entry.remotePath, bucket)
.then (meta) ->
entry.type = meta.ContentType
entry.updatedAt = new Date(meta.LastModified)
return entry
notify = (eventType, path) ->
(result) ->
self.trigger eventType, path
return result
FolderEntry = (path, id, prefix) ->
folder: true
path: path.replace(id, "")
relativePath: path.replace(prefix, "")
remotePath: path
FileEntry = (object, id, prefix, bucket) ->
path = object.Key
entry =
path: path.replace(id, "")
relativePath: path.replace(prefix, "")
remotePath: path
size: object.Size
entry.blob = BlobSham(entry, bucket)
return entry
BlobSham = (entry, bucket) ->
remotePath = entry.remotePath
getURL: ->
getRemote(bucket, remotePath)
.then URL.createObjectURL
readAsText: ->
getRemote(bucket, remotePath)
.then (blob) ->
blob.readAsText()
self = Model()
.include Bindable
.extend
read: (path) ->
unless startsWith path, delimiter
path = delimiter + path
key = <KEY>path<KEY>}"
getRemote(bucket, key)
.then notify "read", path
write: (path, blob) ->
unless startsWith path, delimiter
path = delimiter + path
key = <KEY>
uploadToS3 bucket, key, blob
.then notify "write", path
delete: (path) ->
unless startsWith path, delimiter
path = delimiter + path
key = <KEY>
deleteFromS3 bucket, key
.then notify "delete", path
list: (folderPath="/") ->
list bucket, id, folderPath
.then notify "list", folderPath
| true | Bindable = require "bindable"
Model = require "model"
delimiter = "/"
status = (response) ->
if response.status >= 200 && response.status < 300
return response
else
throw response
json = (response) ->
response.json()
blob = (response) ->
response.blob()
module.exports = (id, bucket, refreshCredentials) ->
{pinvoke, startsWith, endsWith} = require "../util"
refreshCredentials ?= -> Promise.reject new Error "No method given to refresh credentials automatically"
refreshCredentialsPromise = Promise.resolve()
do (oldPromiseInvoke=pinvoke) ->
pinvoke = (args...) ->
# Guard for expired credentials
refreshCredentialsPromise.then ->
oldPromiseInvoke.apply(null, args)
.catch (e) ->
if e.code is "CredentialsError"
console.info "Refreshing credentials after CredentialsError", e
refreshCredentialsPromise = refreshCredentials()
refreshCredentialsPromise.then ->
# Retry calls after refreshing expired credentials
oldPromiseInvoke.apply(null, args)
else
throw e
localCache = {}
metaCache = {}
uploadToS3 = (bucket, key, file, options={}) ->
{cacheControl} = options
cacheControl ?= 0
# Optimistically Cache
localCache[key] = file
metaCache[key] =
ContentType: file.type
UpdatedAt: new Date
pinvoke bucket, "putObject",
Key: key
ContentType: file.type
Body: file
CacheControl: "max-age=#{cacheControl}"
getRemote = (bucket, key) ->
cachedItem = localCache[key]
if cachedItem
if cachedItem instanceof Blob
return Promise.resolve(cachedItem)
else
return Promise.reject(cachedItem)
pinvoke bucket, "getObject",
Key: key
.then (data) ->
{Body, ContentType} = data
new Blob [Body],
type: ContentType
.then (data) ->
localCache[key] = data
.catch (e) ->
# Cache Not Founds too, since that's often what is slow
localCache[key] = e
throw e
deleteFromS3 = (bucket, key) ->
localCache[key] = new Error "Not Found"
delete metaCache[key]
pinvoke bucket, "deleteObject",
Key: key
list = (bucket, id, dir) ->
unless startsWith dir, delimiter
dir = "#{delimiter}#{dir}"
unless endsWith dir, delimiter
dir = "#{dir}#{delimiter}"
prefix = "#{id}#{dir}"
pinvoke bucket, "listObjects",
Prefix: prefix
Delimiter: delimiter
.then (result) ->
results = result.CommonPrefixes.map (p) ->
FolderEntry p.Prefix, id, prefix
.concat result.Contents.map (o) ->
FileEntry o, id, prefix, bucket
.map (entry) ->
fetchMeta(entry, bucket)
Promise.all results
fetchFileMeta = (key, bucket) ->
cachedItem = metaCache[key]
if cachedItem
return Promise.resolve(cachedItem)
pinvoke bucket, "headObject",
Key: key
.then (result) ->
metaCache[key] = result
return result
fetchMeta = (entry, bucket) ->
Promise.resolve()
.then ->
return entry if entry.folder
fetchFileMeta(entry.remotePath, bucket)
.then (meta) ->
entry.type = meta.ContentType
entry.updatedAt = new Date(meta.LastModified)
return entry
notify = (eventType, path) ->
(result) ->
self.trigger eventType, path
return result
FolderEntry = (path, id, prefix) ->
folder: true
path: path.replace(id, "")
relativePath: path.replace(prefix, "")
remotePath: path
FileEntry = (object, id, prefix, bucket) ->
path = object.Key
entry =
path: path.replace(id, "")
relativePath: path.replace(prefix, "")
remotePath: path
size: object.Size
entry.blob = BlobSham(entry, bucket)
return entry
BlobSham = (entry, bucket) ->
remotePath = entry.remotePath
getURL: ->
getRemote(bucket, remotePath)
.then URL.createObjectURL
readAsText: ->
getRemote(bucket, remotePath)
.then (blob) ->
blob.readAsText()
self = Model()
.include Bindable
.extend
read: (path) ->
unless startsWith path, delimiter
path = delimiter + path
key = PI:KEY:<KEY>END_PIpathPI:KEY:<KEY>END_PI}"
getRemote(bucket, key)
.then notify "read", path
write: (path, blob) ->
unless startsWith path, delimiter
path = delimiter + path
key = PI:KEY:<KEY>END_PI
uploadToS3 bucket, key, blob
.then notify "write", path
delete: (path) ->
unless startsWith path, delimiter
path = delimiter + path
key = PI:KEY:<KEY>END_PI
deleteFromS3 bucket, key
.then notify "delete", path
list: (folderPath="/") ->
list bucket, id, folderPath
.then notify "list", folderPath
|
[
{
"context": "pe, model) ->\n model.meta ?= {}\n keyPrefix = \"uih-#{ type }:#{ model.uid() }:\"\n\n # Read/write to lo",
"end": 1817,
"score": 0.7442280054092407,
"start": 1815,
"tag": "KEY",
"value": "h-"
}
] | client/internal/bdd.coffee | praneybehl/meteor-ui-harness | 1 | ###
Declares a "spec" as a boolean property that can be toggled.
@param name: The name of the property
@param func: The test function.
###
it.boolean = (name, func) ->
spec = it(name, func)
meta = spec.meta
meta.type = 'boolean'
meta.propName = name
spec
###
Decalres a "spec" with multiple dropdown options.
@param name: The name of the property
@param options: The options:
- array
- object (key:value)
@param func: The test function.
###
it.select = (name, options, func) ->
{ name, options, func } = fixOptionParams(name, options, func)
spec = it(name, func)
meta = spec.meta
meta.type = 'select'
meta.propName = name
meta.options = options
spec
###
Decalres a "spec" with multiple radio-button options.
@param name: The name of the property
@param options: The options:
- array
- object (key:value)
@param func: The test function.
###
it.radio = (name, options, func) ->
{ name, options, func } = fixOptionParams(name, options, func)
spec = it(name, func)
meta = spec.meta
meta.type = 'radio'
meta.propName = name
meta.options = options
spec
fixOptionParams = (name, options, func) ->
if Object.isFunction(options) and not func?
func = options
options = null
result =
name: name
options: options
func: func
# ----------------------------------------------------------------------
###
Initialize common meta data and function extensions
on each [Spec] model at creation.
###
BDD.specCreated (spec) -> extendModel 'spec', spec
###
Initialize common meta data and function extensions
on each [Suite] model at creation.
###
BDD.suiteCreated (suite) -> extendModel 'suite', suite
extendModel = (type, model) ->
model.meta ?= {}
keyPrefix = "uih-#{ type }:#{ model.uid() }:"
# Read/write to local storage for the model.
model.localStorage = (key, value, options) ->
LocalStorage.prop((keyPrefix + key), value, options)
# Clears all local-storage values for the model.
model.localStorage.clear = ->
for key, value of localStorage
if key.startsWith(keyPrefix)
localStorage.removeItem(key)
# ----------------------------------------------------------------------
###
Update the [this] context that is passed to the
"describe" function
###
BDD.beforeDescribe (context) ->
context.title = (value) -> setHeaderText.call(context, 'title', value)
context.subtitle = (value) -> setHeaderText.call(context, 'subtitle', value)
context.ctrl = -> UIHarness.ctrl()
context.hash = UIHarness.hash
context.log = INTERNAL.log
context.prop = (key, value, options) -> UIHarness.prop(key, value, options)
context.delay = (msecs, func) -> UIHarness.delay(msecs, func)
###
Sets the "display" title/subtitle on the host header.
@param prop: The name of the property attribute.
@param value: The title to display:
- String
- Function
###
setHeaderText = (prop, value) ->
meta = @suite.meta
meta[prop] = value
| 99626 | ###
Declares a "spec" as a boolean property that can be toggled.
@param name: The name of the property
@param func: The test function.
###
it.boolean = (name, func) ->
spec = it(name, func)
meta = spec.meta
meta.type = 'boolean'
meta.propName = name
spec
###
Decalres a "spec" with multiple dropdown options.
@param name: The name of the property
@param options: The options:
- array
- object (key:value)
@param func: The test function.
###
it.select = (name, options, func) ->
{ name, options, func } = fixOptionParams(name, options, func)
spec = it(name, func)
meta = spec.meta
meta.type = 'select'
meta.propName = name
meta.options = options
spec
###
Decalres a "spec" with multiple radio-button options.
@param name: The name of the property
@param options: The options:
- array
- object (key:value)
@param func: The test function.
###
it.radio = (name, options, func) ->
{ name, options, func } = fixOptionParams(name, options, func)
spec = it(name, func)
meta = spec.meta
meta.type = 'radio'
meta.propName = name
meta.options = options
spec
fixOptionParams = (name, options, func) ->
if Object.isFunction(options) and not func?
func = options
options = null
result =
name: name
options: options
func: func
# ----------------------------------------------------------------------
###
Initialize common meta data and function extensions
on each [Spec] model at creation.
###
BDD.specCreated (spec) -> extendModel 'spec', spec
###
Initialize common meta data and function extensions
on each [Suite] model at creation.
###
BDD.suiteCreated (suite) -> extendModel 'suite', suite
extendModel = (type, model) ->
model.meta ?= {}
keyPrefix = "ui<KEY>#{ type }:#{ model.uid() }:"
# Read/write to local storage for the model.
model.localStorage = (key, value, options) ->
LocalStorage.prop((keyPrefix + key), value, options)
# Clears all local-storage values for the model.
model.localStorage.clear = ->
for key, value of localStorage
if key.startsWith(keyPrefix)
localStorage.removeItem(key)
# ----------------------------------------------------------------------
###
Update the [this] context that is passed to the
"describe" function
###
BDD.beforeDescribe (context) ->
context.title = (value) -> setHeaderText.call(context, 'title', value)
context.subtitle = (value) -> setHeaderText.call(context, 'subtitle', value)
context.ctrl = -> UIHarness.ctrl()
context.hash = UIHarness.hash
context.log = INTERNAL.log
context.prop = (key, value, options) -> UIHarness.prop(key, value, options)
context.delay = (msecs, func) -> UIHarness.delay(msecs, func)
###
Sets the "display" title/subtitle on the host header.
@param prop: The name of the property attribute.
@param value: The title to display:
- String
- Function
###
setHeaderText = (prop, value) ->
meta = @suite.meta
meta[prop] = value
| true | ###
Declares a "spec" as a boolean property that can be toggled.
@param name: The name of the property
@param func: The test function.
###
it.boolean = (name, func) ->
spec = it(name, func)
meta = spec.meta
meta.type = 'boolean'
meta.propName = name
spec
###
Decalres a "spec" with multiple dropdown options.
@param name: The name of the property
@param options: The options:
- array
- object (key:value)
@param func: The test function.
###
it.select = (name, options, func) ->
{ name, options, func } = fixOptionParams(name, options, func)
spec = it(name, func)
meta = spec.meta
meta.type = 'select'
meta.propName = name
meta.options = options
spec
###
Decalres a "spec" with multiple radio-button options.
@param name: The name of the property
@param options: The options:
- array
- object (key:value)
@param func: The test function.
###
it.radio = (name, options, func) ->
{ name, options, func } = fixOptionParams(name, options, func)
spec = it(name, func)
meta = spec.meta
meta.type = 'radio'
meta.propName = name
meta.options = options
spec
fixOptionParams = (name, options, func) ->
if Object.isFunction(options) and not func?
func = options
options = null
result =
name: name
options: options
func: func
# ----------------------------------------------------------------------
###
Initialize common meta data and function extensions
on each [Spec] model at creation.
###
BDD.specCreated (spec) -> extendModel 'spec', spec
###
Initialize common meta data and function extensions
on each [Suite] model at creation.
###
BDD.suiteCreated (suite) -> extendModel 'suite', suite
extendModel = (type, model) ->
model.meta ?= {}
keyPrefix = "uiPI:KEY:<KEY>END_PI#{ type }:#{ model.uid() }:"
# Read/write to local storage for the model.
model.localStorage = (key, value, options) ->
LocalStorage.prop((keyPrefix + key), value, options)
# Clears all local-storage values for the model.
model.localStorage.clear = ->
for key, value of localStorage
if key.startsWith(keyPrefix)
localStorage.removeItem(key)
# ----------------------------------------------------------------------
###
Update the [this] context that is passed to the
"describe" function
###
BDD.beforeDescribe (context) ->
context.title = (value) -> setHeaderText.call(context, 'title', value)
context.subtitle = (value) -> setHeaderText.call(context, 'subtitle', value)
context.ctrl = -> UIHarness.ctrl()
context.hash = UIHarness.hash
context.log = INTERNAL.log
context.prop = (key, value, options) -> UIHarness.prop(key, value, options)
context.delay = (msecs, func) -> UIHarness.delay(msecs, func)
###
Sets the "display" title/subtitle on the host header.
@param prop: The name of the property attribute.
@param value: The title to display:
- String
- Function
###
setHeaderText = (prop, value) ->
meta = @suite.meta
meta[prop] = value
|
[
{
"context": " Meteor.users.insert { _id: testingUid, username: testingUid }\n\ninsertUserWithKey = ->\n insertUser()\n testin",
"end": 480,
"score": 0.9981849789619446,
"start": 470,
"tag": "USERNAME",
"value": "testingUid"
},
{
"context": "er} = NogAuthTest\n\n masterKeys = [\n... | packages/nog-auth/nog-auth-server-tests.coffee | nogproject/nog | 0 | import { expect } from 'chai'
crypto = Npm.require 'crypto'
urlparse = Npm.require('url').parse
# Encode without ':' and strip milliseconds, since they are irrelevant.
toISOStringUrlsafe = (date) ->
date.toISOString().replace(/:|\.[^Z]*/g, '')
testingKey = null
testingUid = '__testing_nog-auth-user'
testingScopes = [{action: 'fakeAction', opts: {'foo': 'bar'}}]
insertUser = ->
Meteor.users.remove testingUid
Meteor.users.insert { _id: testingUid, username: testingUid }
insertUserWithKey = ->
insertUser()
testingKey = NogAuth.createKeySudo {keyOwnerId: testingUid}
insertUserWithScopedKey = ->
insertUser()
testingKey = NogAuth.createKeySudo {
keyOwnerId: testingUid
scopes: testingScopes
}
createSignedReq = (opts) ->
opts ?= {}
authalgorithm = 'nog-v1'
authkeyid = testingKey.keyid
now = new Date()
authdate = toISOStringUrlsafe(opts.authdate ? now)
authexpires = opts.authexpires ? 600
authnonce = opts.authnonce ? crypto.randomBytes(10).toString('hex')
authsignature = null
method = 'GET'
url = '/api' + '?'
if opts.query?
url += opts.query + '&'
url += "authalgorithm=#{authalgorithm}"
url += '&' + "authkeyid=#{authkeyid}"
url += '&' + "authdate=#{authdate}"
if authexpires
url += '&' + "authexpires=#{authexpires}"
if authnonce
url += '&' + "authnonce=#{authnonce}"
hmac = crypto.createHmac 'sha256', testingKey.secretkey
hmac.update method + "\n" + url + "\n"
authsignature = hmac.digest 'hex'
url += '&' + "authsignature=#{authsignature}"
{method, url}
describe 'nog-auth', -> describe 'Crypter', ->
{Crypter} = NogAuthTest
masterKeys = [
{ keyid: 'master2', secretkey: 'bbbb' }
{ keyid: 'master1', secretkey: 'aaaa' }
]
key = { keyid: 'user', secretkey: 'xxxx' }
it 'encrypts with first master key.', ->
crypter = new Crypter masterKeys
ckey = crypter.encrypt key
check ckey, {keyid: String, crypt: String, masterkeyid: String}
expect(ckey.keyid).to.equal key.keyid
expect(ckey.masterkeyid).to.equal masterKeys[0].keyid
it 'decrypts with any master key.', ->
crypter1 = new Crypter masterKeys[1..]
ckey1 = crypter1.encrypt key
expect(ckey1.masterkeyid).to.equal masterKeys[1].keyid
crypter = new Crypter masterKeys
ckey = crypter.encrypt key
expect(ckey1.masterkeyid).to.not.equal ckey.masterkeyid
expect(crypter.decrypt(ckey1)).to.deep.equal key
expect(crypter.decrypt(ckey)).to.deep.equal key
it 'throws if master key is unknown.', ->
crypter = new Crypter masterKeys
ckey = crypter.encrypt key
ckey.masterkeyid = 'invalid'
fn = -> crypter.decrypt ckey
expect(fn).to.throw 'ERR_UNKNOWN_MASTER_KEY'
expect(fn).to.throw 'master key id'
expect(fn).to.throw 'invalid'
describe 'nog-auth', -> describe 'KeyKeeper', ->
{KeyKeeper} = NogAuthTest
fakeUsers = null
before ->
fakeUsers = new Mongo.Collection null
for uid in ['user1', 'user2']
fakeUsers.insert { _id: uid, username: uid }
masterKeys = [
{ keyid: 'master2', secretkey: 'bbbb' }
{ keyid: 'master1', secretkey: 'aaaa' }
]
masterKeys1 = masterKeys[1..1]
it "createKey() throws if user is unknown.", ->
keeper = new KeyKeeper fakeUsers, masterKeys1
fn = -> keeper.createKey {keyOwnerId: 'invalidUser'}
expect(fn).to.throw 'ERR_UNKNOWN_USERID'
expect(fn).to.throw 'user id'
expect(fn).to.throw 'invalidUser'
it "createKey() inserts crypted key into 'users' and returns plain key.", ->
uid = 'user1'
keeper = new KeyKeeper fakeUsers, masterKeys1
key = keeper.createKey {keyOwnerId: uid}
check key, {keyid: String, secretkey: String}
user = fakeUsers.findOne {'services.nogauth.keys.keyid': key.keyid}
expect(user._id).to.equal uid
ckey = user.services.nogauth.keys[0]
check ckey, {
keyid: String,
crypt: String,
masterkeyid: String,
createDate: Date
comment: String,
scopes: [{action: String, opts: Object}]
}
expect(ckey.keyid).to.equal key.keyid
expect(ckey.masterkeyid).to.equal masterKeys1[0].keyid
it "createKey() inserts key with comment.", ->
uid = 'user1'
keeper = new KeyKeeper fakeUsers, masterKeys1
fakeComment = 'fake comment'
key = keeper.createKey {
keyOwnerId: uid
comment: fakeComment
}
user = fakeUsers.findOne {'services.nogauth.keys.keyid': key.keyid}
ukey = user.services.nogauth.keys.pop()
expect(ukey.comment).to.equal fakeComment
it "createKey() inserts key with scopes.", ->
uid = 'user1'
keeper = new KeyKeeper fakeUsers, masterKeys1
fakeScopes = [
{action: 'fakeAction', opts: {}}
{action: 'fakeAction2', opts: {ownerName: 'userFoo'}}
]
key = keeper.createKey {
keyOwnerId: uid
scopes: fakeScopes
}
user = fakeUsers.findOne {'services.nogauth.keys.keyid': key.keyid}
ukey = user.services.nogauth.keys.pop()
expect(ukey.scopes).to.deep.equal fakeScopes
it "findKey() throws if keyid is unknown.", ->
uid = 'user2'
keeper = new KeyKeeper fakeUsers, masterKeys1
fn = -> keeper.findKey 'unknownKeyId'
expect(fn).to.throw 'ERR_UNKNOWN_KEYID'
expect(fn).to.throw 'key id'
expect(fn).to.throw 'unknownKeyId'
it "
findKey() returns a decrypted key, the corresponding user, and scopes.
", ->
uid = 'user2'
keeper = new KeyKeeper fakeUsers, masterKeys1
# Create multiple keys and search for middle one to test that search works.
keeper.createKey {keyOwnerId: uid}
key = keeper.createKey {keyOwnerId: uid}
keeper.createKey {keyOwnerId: uid}
match = keeper.findKey key.keyid
check match, {
user: Object,
key: {keyid: String, secretkey: String}
scopes: [Object]
}
it "upgradeKeys() re-encrypts keys with the primary master key " +
"and returns the number of re-encrypted keys.", ->
selOld = { 'services.nogauth.keys.masterkeyid': masterKeys1[0].keyid }
selNew = { 'services.nogauth.keys.masterkeyid': masterKeys[0].keyid }
nOld = fakeUsers.find(selOld).count()
expect(nOld).to.be.above 0
expect(fakeUsers.find(selNew).count()).to.equal 0
keeper = new KeyKeeper fakeUsers, masterKeys
nUpdates = keeper.upgradeKeys()
# At least one key must have changed for every user that selOld matched.
expect(nUpdates).to.be.at.least nOld
expect(fakeUsers.find(selOld).count()).to.equal 0
expect(fakeUsers.find(selNew).count()).to.be.above 0
describe 'nog-auth', -> describe 'NogAuth.createKeySudo()', ->
before insertUser
it 'creates a key in Meteor.users.', ->
key = NogAuth.createKeySudo {keyOwnerId: testingUid}
check key, {keyid: String, secretkey: String}
user = Meteor.users.findOne {'services.nogauth.keys.keyid': key.keyid}
expect(user._id).to.equal testingUid
describe 'nog-auth', -> describe 'NogAuth.checkRequestAuth()', ->
before insertUserWithKey
{checkRequestAuth} = NogAuth
describe 'with valid signature', ->
it "returns true", ->
req = createSignedReq()
expect(checkRequestAuth(req)).to.equal true
it "adds req.auth.user.", ->
req = createSignedReq()
checkRequestAuth(req)
expect(req.auth.user._id).to.equal testingUid
it "removes auth fields from query.", ->
req = createSignedReq {query: 'foo=bar'}
checkRequestAuth(req)
expect(req.query).to.exist
expect(req.query).to.deep.equal {foo: 'bar'}
describe 'with valid signature, without expires', ->
it "returns true", ->
req = createSignedReq {authexpires: false}
expect(checkRequestAuth(req)).to.equal true
describe 'with valid signature, without nonce', ->
it "returns true", ->
req = createSignedReq {authnonce: false}
expect(checkRequestAuth(req)).to.equal true
describe 'with malformed request', ->
it "throws match error (missing method)", ->
wellformed = createSignedReq()
fn = -> checkRequestAuth _.omit(wellformed, 'method')
expect(fn).to.throw 'Match error'
it "throws match error (missing url)", ->
wellformed = createSignedReq()
fn = -> checkRequestAuth _.omit(wellformed, 'url')
expect(fn).to.throw 'Match error'
for f in ['authkeyid', 'authsignature', 'authdate']
do (f) ->
it "throws 401 (missing #{f})", ->
req = createSignedReq()
req.url = req.url.replace(new RegExp('&' + f + '=[^&]*'), '')
fn = -> checkRequestAuth req
expect(fn).to.throw 'ERR_AUTH_FIELD_MISSING'
expect(fn).to.throw "missing #{f}"
describe 'with invalid date string', ->
it "throws 'invalid authdate'", ->
req = createSignedReq()
req.url = req.url.replace /authdate=[^&]*/, 'authdate=20010101T010101'
fn = -> checkRequestAuth req
expect(fn).to.throw 'ERR_AUTH_DATE_INVALID'
expect(fn).to.throw 'Invalid authdate'
describe 'with unknown key', ->
it "throws 'unknown key'", ->
req = createSignedReq()
req.url = req.url.replace /authkeyid=[^&]*/, 'authkeyid=unknownkey'
fn = -> checkRequestAuth req
expect(fn).to.throw 'ERR_AUTH_KEY_UNKNOWN'
expect(fn).to.throw 'Unknown key'
expect(fn).to.throw 'Cause'
describe 'with invalid signature', ->
it "throws 'invalid'", ->
req = createSignedReq()
req.url = req.url.replace /authsignature=[^&]*/,
('authsignature=' + Array(64).join '0')
fn = -> checkRequestAuth req
expect(fn).to.throw 'ERR_AUTH_SIG_INVALID'
expect(fn).to.throw 'Invalid signature'
describe 'with expired signature', ->
it "throws 'expired'", ->
req = createSignedReq { authdate: new Date('2001-01-01') }
fn = -> checkRequestAuth req
expect(fn).to.throw 'ERR_AUTH_SIG_EXPIRED'
expect(fn).to.throw 'Expired signature'
describe 'with duplicate nonce', ->
it "throws 'invalid'", ->
req = createSignedReq()
expect(checkRequestAuth(req)).to.equal true
fn = -> checkRequestAuth req
expect(fn).to.throw 'ERR_AUTH_NONCE_INVALID'
expect(fn).to.throw 'Invalid nonce'
describe 'with nonce and long expires', ->
it "throws 'invalid'", ->
req = createSignedReq {authexpires: 2 * 24 * 3600}
fn = -> checkRequestAuth req
expect(fn).to.throw 'ERR_AUTH_EXPIRES_INVALID'
expect(fn).to.throw 'Invalid expires'
describe 'nog-auth', -> describe 'NogAuth.checkRequestAuth()', ->
before insertUserWithScopedKey
{checkRequestAuth} = NogAuth
describe 'with scoped key', ->
it "adds req.auth.user.scopes.", ->
req = createSignedReq()
checkRequestAuth(req)
expect(req.auth.user._id).to.equal testingUid
expect(req.auth.user.scopes).to.deep.equal testingScopes
describe 'nog-auth', -> describe 'NogAuth.signRequest()', ->
{signRequest, checkRequestAuth} = NogAuth
before insertUserWithKey
it "signs a request.", ->
req = signRequest testingKey, { method: 'GET', url: '/path' }
expect(checkRequestAuth(req)).to.equal true
req = signRequest testingKey, { method: 'POST', url: '/path' }
expect(checkRequestAuth(req)).to.equal true
it "handles an existing query part.", ->
req = signRequest testingKey, { method: 'GET', url: '/path?x=1' }
expect(urlparse(req.url, true).query.x).to.equal '1'
expect(checkRequestAuth(req)).to.equal true
# Add a test that marks completion to detect side-effect that cause missing
# result lists.
describe 'nog-auth', ->
it 'server tests completed.', ->
| 123764 | import { expect } from 'chai'
crypto = Npm.require 'crypto'
urlparse = Npm.require('url').parse
# Encode without ':' and strip milliseconds, since they are irrelevant.
toISOStringUrlsafe = (date) ->
date.toISOString().replace(/:|\.[^Z]*/g, '')
testingKey = null
testingUid = '__testing_nog-auth-user'
testingScopes = [{action: 'fakeAction', opts: {'foo': 'bar'}}]
insertUser = ->
Meteor.users.remove testingUid
Meteor.users.insert { _id: testingUid, username: testingUid }
insertUserWithKey = ->
insertUser()
testingKey = NogAuth.createKeySudo {keyOwnerId: testingUid}
insertUserWithScopedKey = ->
insertUser()
testingKey = NogAuth.createKeySudo {
keyOwnerId: testingUid
scopes: testingScopes
}
createSignedReq = (opts) ->
opts ?= {}
authalgorithm = 'nog-v1'
authkeyid = testingKey.keyid
now = new Date()
authdate = toISOStringUrlsafe(opts.authdate ? now)
authexpires = opts.authexpires ? 600
authnonce = opts.authnonce ? crypto.randomBytes(10).toString('hex')
authsignature = null
method = 'GET'
url = '/api' + '?'
if opts.query?
url += opts.query + '&'
url += "authalgorithm=#{authalgorithm}"
url += '&' + "authkeyid=#{authkeyid}"
url += '&' + "authdate=#{authdate}"
if authexpires
url += '&' + "authexpires=#{authexpires}"
if authnonce
url += '&' + "authnonce=#{authnonce}"
hmac = crypto.createHmac 'sha256', testingKey.secretkey
hmac.update method + "\n" + url + "\n"
authsignature = hmac.digest 'hex'
url += '&' + "authsignature=#{authsignature}"
{method, url}
describe 'nog-auth', -> describe 'Crypter', ->
{Crypter} = NogAuthTest
masterKeys = [
{ keyid: '<KEY>', secretkey: '<KEY>' }
{ keyid: '<KEY>', secretkey: '<KEY>' }
]
key = { keyid: '<KEY>', secretkey: '<KEY>' }
it 'encrypts with first master key.', ->
crypter = new Crypter masterKeys
ckey = crypter.encrypt key
check ckey, {keyid: String, crypt: String, masterkeyid: String}
expect(ckey.keyid).to.equal key.keyid
expect(ckey.masterkeyid).to.equal masterKeys[0].keyid
it 'decrypts with any master key.', ->
crypter1 = new Crypter masterKeys[1..]
ckey1 = crypter1.encrypt key
expect(ckey1.masterkeyid).to.equal masterKeys[1].keyid
crypter = new Crypter masterKeys
ckey = crypter.encrypt key
expect(ckey1.masterkeyid).to.not.equal ckey.masterkeyid
expect(crypter.decrypt(ckey1)).to.deep.equal key
expect(crypter.decrypt(ckey)).to.deep.equal key
it 'throws if master key is unknown.', ->
crypter = new Crypter masterKeys
ckey = crypter.encrypt key
ckey.masterkeyid = 'invalid'
fn = -> crypter.decrypt ckey
expect(fn).to.throw 'ERR_UNKNOWN_MASTER_KEY'
expect(fn).to.throw 'master key id'
expect(fn).to.throw 'invalid'
describe 'nog-auth', -> describe 'KeyKeeper', ->
{KeyKeeper} = NogAuthTest
fakeUsers = null
before ->
fakeUsers = new Mongo.Collection null
for uid in ['user1', 'user2']
fakeUsers.insert { _id: uid, username: uid }
masterKeys = [
{ keyid: '<KEY>', secretkey: '<KEY>' }
{ keyid: '<KEY>', secretkey: '<KEY>' }
]
masterKeys1 = masterKeys[1..1]
it "createKey() throws if user is unknown.", ->
keeper = new KeyKeeper fakeUsers, masterKeys1
fn = -> keeper.createKey {keyOwnerId: 'invalidUser'}
expect(fn).to.throw 'ERR_UNKNOWN_USERID'
expect(fn).to.throw 'user id'
expect(fn).to.throw 'invalidUser'
it "createKey() inserts crypted key into 'users' and returns plain key.", ->
uid = 'user1'
keeper = new KeyKeeper fakeUsers, masterKeys1
key = keeper.createKey {keyOwnerId: uid}
check key, {keyid: String, secretkey: String}
user = fakeUsers.findOne {'services.nogauth.keys.keyid': key.keyid}
expect(user._id).to.equal uid
ckey = user.services.nogauth.keys[0]
check ckey, {
keyid: String,
crypt: String,
masterkeyid: String,
createDate: Date
comment: String,
scopes: [{action: String, opts: Object}]
}
expect(ckey.keyid).to.equal key.keyid
expect(ckey.masterkeyid).to.equal masterKeys1[0].keyid
it "createKey() inserts key with comment.", ->
uid = 'user1'
keeper = new KeyKeeper fakeUsers, masterKeys1
fakeComment = 'fake comment'
key = keeper.createKey {
keyOwnerId: uid
comment: fakeComment
}
user = fakeUsers.findOne {'services.nogauth.keys.keyid': key.keyid}
ukey = user.services.nogauth.keys.pop()
expect(ukey.comment).to.equal fakeComment
it "createKey() inserts key with scopes.", ->
uid = 'user1'
keeper = new KeyKeeper fakeUsers, masterKeys1
fakeScopes = [
{action: 'fakeAction', opts: {}}
{action: 'fakeAction2', opts: {ownerName: 'userFoo'}}
]
key = keeper.createKey {
keyOwnerId: uid
scopes: fakeScopes
}
user = fakeUsers.findOne {'services.nogauth.keys.keyid': key.keyid}
ukey = user.services.nogauth.keys.pop()
expect(ukey.scopes).to.deep.equal fakeScopes
it "findKey() throws if keyid is unknown.", ->
uid = 'user2'
keeper = new KeyKeeper fakeUsers, masterKeys1
fn = -> keeper.findKey 'unknownKeyId'
expect(fn).to.throw 'ERR_UNKNOWN_KEYID'
expect(fn).to.throw 'key id'
expect(fn).to.throw 'unknownKeyId'
it "
findKey() returns a decrypted key, the corresponding user, and scopes.
", ->
uid = 'user2'
keeper = new KeyKeeper fakeUsers, masterKeys1
# Create multiple keys and search for middle one to test that search works.
keeper.createKey {keyOwnerId: uid}
key = keeper.createKey {keyOwnerId: uid}
keeper.createKey {keyOwnerId: uid}
match = keeper.findKey key.keyid
check match, {
user: Object,
key: {keyid: String, secretkey: String}
scopes: [Object]
}
it "upgradeKeys() re-encrypts keys with the primary master key " +
"and returns the number of re-encrypted keys.", ->
selOld = { 'services.nogauth.keys.masterkeyid': masterKeys1[0].keyid }
selNew = { 'services.nogauth.keys.masterkeyid': masterKeys[0].keyid }
nOld = fakeUsers.find(selOld).count()
expect(nOld).to.be.above 0
expect(fakeUsers.find(selNew).count()).to.equal 0
keeper = new KeyKeeper fakeUsers, masterKeys
nUpdates = keeper.upgradeKeys()
# At least one key must have changed for every user that selOld matched.
expect(nUpdates).to.be.at.least nOld
expect(fakeUsers.find(selOld).count()).to.equal 0
expect(fakeUsers.find(selNew).count()).to.be.above 0
describe 'nog-auth', -> describe 'NogAuth.createKeySudo()', ->
before insertUser
it 'creates a key in Meteor.users.', ->
key = NogAuth.createKeySudo {keyOwnerId: testingUid}
check key, {keyid: String, secretkey: String}
user = Meteor.users.findOne {'services.nogauth.keys.keyid': key.keyid}
expect(user._id).to.equal testingUid
describe 'nog-auth', -> describe 'NogAuth.checkRequestAuth()', ->
before insertUserWithKey
{checkRequestAuth} = NogAuth
describe 'with valid signature', ->
it "returns true", ->
req = createSignedReq()
expect(checkRequestAuth(req)).to.equal true
it "adds req.auth.user.", ->
req = createSignedReq()
checkRequestAuth(req)
expect(req.auth.user._id).to.equal testingUid
it "removes auth fields from query.", ->
req = createSignedReq {query: 'foo=bar'}
checkRequestAuth(req)
expect(req.query).to.exist
expect(req.query).to.deep.equal {foo: 'bar'}
describe 'with valid signature, without expires', ->
it "returns true", ->
req = createSignedReq {authexpires: false}
expect(checkRequestAuth(req)).to.equal true
describe 'with valid signature, without nonce', ->
it "returns true", ->
req = createSignedReq {authnonce: false}
expect(checkRequestAuth(req)).to.equal true
describe 'with malformed request', ->
it "throws match error (missing method)", ->
wellformed = createSignedReq()
fn = -> checkRequestAuth _.omit(wellformed, 'method')
expect(fn).to.throw 'Match error'
it "throws match error (missing url)", ->
wellformed = createSignedReq()
fn = -> checkRequestAuth _.omit(wellformed, 'url')
expect(fn).to.throw 'Match error'
for f in ['authkeyid', 'authsignature', 'authdate']
do (f) ->
it "throws 401 (missing #{f})", ->
req = createSignedReq()
req.url = req.url.replace(new RegExp('&' + f + '=[^&]*'), '')
fn = -> checkRequestAuth req
expect(fn).to.throw 'ERR_AUTH_FIELD_MISSING'
expect(fn).to.throw "missing #{f}"
describe 'with invalid date string', ->
it "throws 'invalid authdate'", ->
req = createSignedReq()
req.url = req.url.replace /authdate=[^&]*/, 'authdate=20010101T010101'
fn = -> checkRequestAuth req
expect(fn).to.throw 'ERR_AUTH_DATE_INVALID'
expect(fn).to.throw 'Invalid authdate'
describe 'with unknown key', ->
it "throws 'unknown key'", ->
req = createSignedReq()
req.url = req.url.replace /authkeyid=[^&]*/, 'authkeyid=unknownkey'
fn = -> checkRequestAuth req
expect(fn).to.throw 'ERR_AUTH_KEY_UNKNOWN'
expect(fn).to.throw 'Unknown key'
expect(fn).to.throw 'Cause'
describe 'with invalid signature', ->
it "throws 'invalid'", ->
req = createSignedReq()
req.url = req.url.replace /authsignature=[^&]*/,
('authsignature=' + Array(64).join '0')
fn = -> checkRequestAuth req
expect(fn).to.throw 'ERR_AUTH_SIG_INVALID'
expect(fn).to.throw 'Invalid signature'
describe 'with expired signature', ->
it "throws 'expired'", ->
req = createSignedReq { authdate: new Date('2001-01-01') }
fn = -> checkRequestAuth req
expect(fn).to.throw 'ERR_AUTH_SIG_EXPIRED'
expect(fn).to.throw 'Expired signature'
describe 'with duplicate nonce', ->
it "throws 'invalid'", ->
req = createSignedReq()
expect(checkRequestAuth(req)).to.equal true
fn = -> checkRequestAuth req
expect(fn).to.throw 'ERR_AUTH_NONCE_INVALID'
expect(fn).to.throw 'Invalid nonce'
describe 'with nonce and long expires', ->
it "throws 'invalid'", ->
req = createSignedReq {authexpires: 2 * 24 * 3600}
fn = -> checkRequestAuth req
expect(fn).to.throw 'ERR_AUTH_EXPIRES_INVALID'
expect(fn).to.throw 'Invalid expires'
describe 'nog-auth', -> describe 'NogAuth.checkRequestAuth()', ->
before insertUserWithScopedKey
{checkRequestAuth} = NogAuth
describe 'with scoped key', ->
it "adds req.auth.user.scopes.", ->
req = createSignedReq()
checkRequestAuth(req)
expect(req.auth.user._id).to.equal testingUid
expect(req.auth.user.scopes).to.deep.equal testingScopes
describe 'nog-auth', -> describe 'NogAuth.signRequest()', ->
{signRequest, checkRequestAuth} = NogAuth
before insertUserWithKey
it "signs a request.", ->
req = signRequest testingKey, { method: 'GET', url: '/path' }
expect(checkRequestAuth(req)).to.equal true
req = signRequest testingKey, { method: 'POST', url: '/path' }
expect(checkRequestAuth(req)).to.equal true
it "handles an existing query part.", ->
req = signRequest testingKey, { method: 'GET', url: '/path?x=1' }
expect(urlparse(req.url, true).query.x).to.equal '1'
expect(checkRequestAuth(req)).to.equal true
# Add a test that marks completion to detect side-effect that cause missing
# result lists.
describe 'nog-auth', ->
it 'server tests completed.', ->
| true | import { expect } from 'chai'
crypto = Npm.require 'crypto'
urlparse = Npm.require('url').parse
# Encode without ':' and strip milliseconds, since they are irrelevant.
toISOStringUrlsafe = (date) ->
date.toISOString().replace(/:|\.[^Z]*/g, '')
testingKey = null
testingUid = '__testing_nog-auth-user'
testingScopes = [{action: 'fakeAction', opts: {'foo': 'bar'}}]
insertUser = ->
Meteor.users.remove testingUid
Meteor.users.insert { _id: testingUid, username: testingUid }
insertUserWithKey = ->
insertUser()
testingKey = NogAuth.createKeySudo {keyOwnerId: testingUid}
insertUserWithScopedKey = ->
insertUser()
testingKey = NogAuth.createKeySudo {
keyOwnerId: testingUid
scopes: testingScopes
}
createSignedReq = (opts) ->
opts ?= {}
authalgorithm = 'nog-v1'
authkeyid = testingKey.keyid
now = new Date()
authdate = toISOStringUrlsafe(opts.authdate ? now)
authexpires = opts.authexpires ? 600
authnonce = opts.authnonce ? crypto.randomBytes(10).toString('hex')
authsignature = null
method = 'GET'
url = '/api' + '?'
if opts.query?
url += opts.query + '&'
url += "authalgorithm=#{authalgorithm}"
url += '&' + "authkeyid=#{authkeyid}"
url += '&' + "authdate=#{authdate}"
if authexpires
url += '&' + "authexpires=#{authexpires}"
if authnonce
url += '&' + "authnonce=#{authnonce}"
hmac = crypto.createHmac 'sha256', testingKey.secretkey
hmac.update method + "\n" + url + "\n"
authsignature = hmac.digest 'hex'
url += '&' + "authsignature=#{authsignature}"
{method, url}
describe 'nog-auth', -> describe 'Crypter', ->
{Crypter} = NogAuthTest
masterKeys = [
{ keyid: 'PI:KEY:<KEY>END_PI', secretkey: 'PI:KEY:<KEY>END_PI' }
{ keyid: 'PI:KEY:<KEY>END_PI', secretkey: 'PI:KEY:<KEY>END_PI' }
]
key = { keyid: 'PI:KEY:<KEY>END_PI', secretkey: 'PI:KEY:<KEY>END_PI' }
it 'encrypts with first master key.', ->
crypter = new Crypter masterKeys
ckey = crypter.encrypt key
check ckey, {keyid: String, crypt: String, masterkeyid: String}
expect(ckey.keyid).to.equal key.keyid
expect(ckey.masterkeyid).to.equal masterKeys[0].keyid
it 'decrypts with any master key.', ->
crypter1 = new Crypter masterKeys[1..]
ckey1 = crypter1.encrypt key
expect(ckey1.masterkeyid).to.equal masterKeys[1].keyid
crypter = new Crypter masterKeys
ckey = crypter.encrypt key
expect(ckey1.masterkeyid).to.not.equal ckey.masterkeyid
expect(crypter.decrypt(ckey1)).to.deep.equal key
expect(crypter.decrypt(ckey)).to.deep.equal key
it 'throws if master key is unknown.', ->
crypter = new Crypter masterKeys
ckey = crypter.encrypt key
ckey.masterkeyid = 'invalid'
fn = -> crypter.decrypt ckey
expect(fn).to.throw 'ERR_UNKNOWN_MASTER_KEY'
expect(fn).to.throw 'master key id'
expect(fn).to.throw 'invalid'
describe 'nog-auth', -> describe 'KeyKeeper', ->
{KeyKeeper} = NogAuthTest
fakeUsers = null
before ->
fakeUsers = new Mongo.Collection null
for uid in ['user1', 'user2']
fakeUsers.insert { _id: uid, username: uid }
masterKeys = [
{ keyid: 'PI:KEY:<KEY>END_PI', secretkey: 'PI:KEY:<KEY>END_PI' }
{ keyid: 'PI:KEY:<KEY>END_PI', secretkey: 'PI:KEY:<KEY>END_PI' }
]
masterKeys1 = masterKeys[1..1]
it "createKey() throws if user is unknown.", ->
keeper = new KeyKeeper fakeUsers, masterKeys1
fn = -> keeper.createKey {keyOwnerId: 'invalidUser'}
expect(fn).to.throw 'ERR_UNKNOWN_USERID'
expect(fn).to.throw 'user id'
expect(fn).to.throw 'invalidUser'
it "createKey() inserts crypted key into 'users' and returns plain key.", ->
uid = 'user1'
keeper = new KeyKeeper fakeUsers, masterKeys1
key = keeper.createKey {keyOwnerId: uid}
check key, {keyid: String, secretkey: String}
user = fakeUsers.findOne {'services.nogauth.keys.keyid': key.keyid}
expect(user._id).to.equal uid
ckey = user.services.nogauth.keys[0]
check ckey, {
keyid: String,
crypt: String,
masterkeyid: String,
createDate: Date
comment: String,
scopes: [{action: String, opts: Object}]
}
expect(ckey.keyid).to.equal key.keyid
expect(ckey.masterkeyid).to.equal masterKeys1[0].keyid
it "createKey() inserts key with comment.", ->
uid = 'user1'
keeper = new KeyKeeper fakeUsers, masterKeys1
fakeComment = 'fake comment'
key = keeper.createKey {
keyOwnerId: uid
comment: fakeComment
}
user = fakeUsers.findOne {'services.nogauth.keys.keyid': key.keyid}
ukey = user.services.nogauth.keys.pop()
expect(ukey.comment).to.equal fakeComment
it "createKey() inserts key with scopes.", ->
uid = 'user1'
keeper = new KeyKeeper fakeUsers, masterKeys1
fakeScopes = [
{action: 'fakeAction', opts: {}}
{action: 'fakeAction2', opts: {ownerName: 'userFoo'}}
]
key = keeper.createKey {
keyOwnerId: uid
scopes: fakeScopes
}
user = fakeUsers.findOne {'services.nogauth.keys.keyid': key.keyid}
ukey = user.services.nogauth.keys.pop()
expect(ukey.scopes).to.deep.equal fakeScopes
it "findKey() throws if keyid is unknown.", ->
uid = 'user2'
keeper = new KeyKeeper fakeUsers, masterKeys1
fn = -> keeper.findKey 'unknownKeyId'
expect(fn).to.throw 'ERR_UNKNOWN_KEYID'
expect(fn).to.throw 'key id'
expect(fn).to.throw 'unknownKeyId'
it "
findKey() returns a decrypted key, the corresponding user, and scopes.
", ->
uid = 'user2'
keeper = new KeyKeeper fakeUsers, masterKeys1
# Create multiple keys and search for middle one to test that search works.
keeper.createKey {keyOwnerId: uid}
key = keeper.createKey {keyOwnerId: uid}
keeper.createKey {keyOwnerId: uid}
match = keeper.findKey key.keyid
check match, {
user: Object,
key: {keyid: String, secretkey: String}
scopes: [Object]
}
it "upgradeKeys() re-encrypts keys with the primary master key " +
"and returns the number of re-encrypted keys.", ->
selOld = { 'services.nogauth.keys.masterkeyid': masterKeys1[0].keyid }
selNew = { 'services.nogauth.keys.masterkeyid': masterKeys[0].keyid }
nOld = fakeUsers.find(selOld).count()
expect(nOld).to.be.above 0
expect(fakeUsers.find(selNew).count()).to.equal 0
keeper = new KeyKeeper fakeUsers, masterKeys
nUpdates = keeper.upgradeKeys()
# At least one key must have changed for every user that selOld matched.
expect(nUpdates).to.be.at.least nOld
expect(fakeUsers.find(selOld).count()).to.equal 0
expect(fakeUsers.find(selNew).count()).to.be.above 0
describe 'nog-auth', -> describe 'NogAuth.createKeySudo()', ->
before insertUser
it 'creates a key in Meteor.users.', ->
key = NogAuth.createKeySudo {keyOwnerId: testingUid}
check key, {keyid: String, secretkey: String}
user = Meteor.users.findOne {'services.nogauth.keys.keyid': key.keyid}
expect(user._id).to.equal testingUid
describe 'nog-auth', -> describe 'NogAuth.checkRequestAuth()', ->
before insertUserWithKey
{checkRequestAuth} = NogAuth
describe 'with valid signature', ->
it "returns true", ->
req = createSignedReq()
expect(checkRequestAuth(req)).to.equal true
it "adds req.auth.user.", ->
req = createSignedReq()
checkRequestAuth(req)
expect(req.auth.user._id).to.equal testingUid
it "removes auth fields from query.", ->
req = createSignedReq {query: 'foo=bar'}
checkRequestAuth(req)
expect(req.query).to.exist
expect(req.query).to.deep.equal {foo: 'bar'}
describe 'with valid signature, without expires', ->
it "returns true", ->
req = createSignedReq {authexpires: false}
expect(checkRequestAuth(req)).to.equal true
describe 'with valid signature, without nonce', ->
it "returns true", ->
req = createSignedReq {authnonce: false}
expect(checkRequestAuth(req)).to.equal true
describe 'with malformed request', ->
it "throws match error (missing method)", ->
wellformed = createSignedReq()
fn = -> checkRequestAuth _.omit(wellformed, 'method')
expect(fn).to.throw 'Match error'
it "throws match error (missing url)", ->
wellformed = createSignedReq()
fn = -> checkRequestAuth _.omit(wellformed, 'url')
expect(fn).to.throw 'Match error'
for f in ['authkeyid', 'authsignature', 'authdate']
do (f) ->
it "throws 401 (missing #{f})", ->
req = createSignedReq()
req.url = req.url.replace(new RegExp('&' + f + '=[^&]*'), '')
fn = -> checkRequestAuth req
expect(fn).to.throw 'ERR_AUTH_FIELD_MISSING'
expect(fn).to.throw "missing #{f}"
describe 'with invalid date string', ->
it "throws 'invalid authdate'", ->
req = createSignedReq()
req.url = req.url.replace /authdate=[^&]*/, 'authdate=20010101T010101'
fn = -> checkRequestAuth req
expect(fn).to.throw 'ERR_AUTH_DATE_INVALID'
expect(fn).to.throw 'Invalid authdate'
describe 'with unknown key', ->
it "throws 'unknown key'", ->
req = createSignedReq()
req.url = req.url.replace /authkeyid=[^&]*/, 'authkeyid=unknownkey'
fn = -> checkRequestAuth req
expect(fn).to.throw 'ERR_AUTH_KEY_UNKNOWN'
expect(fn).to.throw 'Unknown key'
expect(fn).to.throw 'Cause'
describe 'with invalid signature', ->
it "throws 'invalid'", ->
req = createSignedReq()
req.url = req.url.replace /authsignature=[^&]*/,
('authsignature=' + Array(64).join '0')
fn = -> checkRequestAuth req
expect(fn).to.throw 'ERR_AUTH_SIG_INVALID'
expect(fn).to.throw 'Invalid signature'
describe 'with expired signature', ->
it "throws 'expired'", ->
req = createSignedReq { authdate: new Date('2001-01-01') }
fn = -> checkRequestAuth req
expect(fn).to.throw 'ERR_AUTH_SIG_EXPIRED'
expect(fn).to.throw 'Expired signature'
describe 'with duplicate nonce', ->
it "throws 'invalid'", ->
req = createSignedReq()
expect(checkRequestAuth(req)).to.equal true
fn = -> checkRequestAuth req
expect(fn).to.throw 'ERR_AUTH_NONCE_INVALID'
expect(fn).to.throw 'Invalid nonce'
describe 'with nonce and long expires', ->
it "throws 'invalid'", ->
req = createSignedReq {authexpires: 2 * 24 * 3600}
fn = -> checkRequestAuth req
expect(fn).to.throw 'ERR_AUTH_EXPIRES_INVALID'
expect(fn).to.throw 'Invalid expires'
describe 'nog-auth', -> describe 'NogAuth.checkRequestAuth()', ->
before insertUserWithScopedKey
{checkRequestAuth} = NogAuth
describe 'with scoped key', ->
it "adds req.auth.user.scopes.", ->
req = createSignedReq()
checkRequestAuth(req)
expect(req.auth.user._id).to.equal testingUid
expect(req.auth.user.scopes).to.deep.equal testingScopes
describe 'nog-auth', -> describe 'NogAuth.signRequest()', ->
{signRequest, checkRequestAuth} = NogAuth
before insertUserWithKey
it "signs a request.", ->
req = signRequest testingKey, { method: 'GET', url: '/path' }
expect(checkRequestAuth(req)).to.equal true
req = signRequest testingKey, { method: 'POST', url: '/path' }
expect(checkRequestAuth(req)).to.equal true
it "handles an existing query part.", ->
req = signRequest testingKey, { method: 'GET', url: '/path?x=1' }
expect(urlparse(req.url, true).query.x).to.equal '1'
expect(checkRequestAuth(req)).to.equal true
# Add a test that marks completion to detect side-effect that cause missing
# result lists.
describe 'nog-auth', ->
it 'server tests completed.', ->
|
[
{
"context": "a.json': ->\n record =\n id: 123\n name: @params.name\n email: \"#{@params.name}@example.",
"end": 796,
"score": 0.9142112135887146,
"start": 796,
"tag": "NAME",
"value": ""
},
{
"context": " id: 123\n name: @params.name\n email: \"#{@par... | examples/readme.coffee | zappajs/zappajs | 50 | # This is the example from README.md
require('./zappajs') ->
## Server-side ##
teacup = @teacup
@get '/': ->
@render 'index',
title: 'Zappa!'
scripts: '/index.js /more.js /client.js'
stylesheet: '/index.css'
@view index: ->
{doctype,html,head,title,script,link,body,h1,div} = teacup
doctype 5
html =>
head =>
title @title if @title
for s in @scripts.split ' '
script src: s
link rel:'stylesheet', href:@stylesheet
body ->
h1 'Welcome to Zappa!'
div id:'content'
div id:'content2'
pixels = 12
@css '/index.css':
body:
font: '12px Helvetica'
h1:
color: 'pink'
height: "#{pixels}px"
@get '/:name/data.json': ->
record =
id: 123
name: @params.name
email: "#{@params.name}@example.com"
@json record
## Client-side ##
@coffee '/index.js': ->
alert 'hi'
## Client-side with Browserify ##
@with 'client' # requires `zappajs-plugin-client`
@browser '/more.js': ->
domready = require 'domready'
$ = require 'component-dom'
domready ->
$('#content').html 'Ready to roll!'
## Client-side with ExpressJS/Socket.IO session sharing ##
@use session:
store: new @session.MemoryStore()
secret: 'foo'
resave: true, saveUninitialized: true
@on 'ready': ->
console.log "Client #{@id} is ready and says #{@data}."
@emit 'ok', null
@client '/client.js': ->
@emit 'ready', 'hello'
console.log 'A'
$ = require 'component-dom'
console.log 'B'
@on 'ok', ->
$('#content2').html 'Ready to roll too!'
| 21616 | # This is the example from README.md
require('./zappajs') ->
## Server-side ##
teacup = @teacup
@get '/': ->
@render 'index',
title: 'Zappa!'
scripts: '/index.js /more.js /client.js'
stylesheet: '/index.css'
@view index: ->
{doctype,html,head,title,script,link,body,h1,div} = teacup
doctype 5
html =>
head =>
title @title if @title
for s in @scripts.split ' '
script src: s
link rel:'stylesheet', href:@stylesheet
body ->
h1 'Welcome to Zappa!'
div id:'content'
div id:'content2'
pixels = 12
@css '/index.css':
body:
font: '12px Helvetica'
h1:
color: 'pink'
height: "#{pixels}px"
@get '/:name/data.json': ->
record =
id: 123
name:<NAME> @params.name
email: <EMAIL>"
@json record
## Client-side ##
@coffee '/index.js': ->
alert 'hi'
## Client-side with Browserify ##
@with 'client' # requires `zappajs-plugin-client`
@browser '/more.js': ->
domready = require 'domready'
$ = require 'component-dom'
domready ->
$('#content').html 'Ready to roll!'
## Client-side with ExpressJS/Socket.IO session sharing ##
@use session:
store: new @session.MemoryStore()
secret: 'foo'
resave: true, saveUninitialized: true
@on 'ready': ->
console.log "Client #{@id} is ready and says #{@data}."
@emit 'ok', null
@client '/client.js': ->
@emit 'ready', 'hello'
console.log 'A'
$ = require 'component-dom'
console.log 'B'
@on 'ok', ->
$('#content2').html 'Ready to roll too!'
| true | # This is the example from README.md
require('./zappajs') ->
## Server-side ##
teacup = @teacup
@get '/': ->
@render 'index',
title: 'Zappa!'
scripts: '/index.js /more.js /client.js'
stylesheet: '/index.css'
@view index: ->
{doctype,html,head,title,script,link,body,h1,div} = teacup
doctype 5
html =>
head =>
title @title if @title
for s in @scripts.split ' '
script src: s
link rel:'stylesheet', href:@stylesheet
body ->
h1 'Welcome to Zappa!'
div id:'content'
div id:'content2'
pixels = 12
@css '/index.css':
body:
font: '12px Helvetica'
h1:
color: 'pink'
height: "#{pixels}px"
@get '/:name/data.json': ->
record =
id: 123
name:PI:NAME:<NAME>END_PI @params.name
email: PI:EMAIL:<EMAIL>END_PI"
@json record
## Client-side ##
@coffee '/index.js': ->
alert 'hi'
## Client-side with Browserify ##
@with 'client' # requires `zappajs-plugin-client`
@browser '/more.js': ->
domready = require 'domready'
$ = require 'component-dom'
domready ->
$('#content').html 'Ready to roll!'
## Client-side with ExpressJS/Socket.IO session sharing ##
@use session:
store: new @session.MemoryStore()
secret: 'foo'
resave: true, saveUninitialized: true
@on 'ready': ->
console.log "Client #{@id} is ready and says #{@data}."
@emit 'ok', null
@client '/client.js': ->
@emit 'ready', 'hello'
console.log 'A'
$ = require 'component-dom'
console.log 'B'
@on 'ok', ->
$('#content2').html 'Ready to roll too!'
|
[
{
"context": "= (require '../')\n url: 'test'\n token: 'test'\n\n projects = gitlab.projects\n members = pr",
"end": 280,
"score": 0.7870383262634277,
"start": 276,
"tag": "PASSWORD",
"value": "test"
}
] | tests/ProjectMembers.test.coffee | lengyuedaidai/node-gitlab | 143 | chai = require 'chai'
expect = chai.expect
sinon = require 'sinon'
sinonChai = require 'sinon-chai'
chai.use sinonChai
describe "ProjectMembers", ->
gitlab = null
projects = null
members = null
before ->
gitlab = (require '../')
url: 'test'
token: 'test'
projects = gitlab.projects
members = projects.members
beforeEach ->
describe "list()", ->
it "should use GET verb", ->
getStub = sinon.stub members, "get"
members.list 1
getStub.restore()
expect(getStub).to.have.been.called
it "should pass Numeric projectIDs to Utils.parseProjectId", ->
getStub = sinon.stub members, "get"
members.list 1
getStub.restore()
expect(getStub).to.have.been.calledWith "projects/1/members"
it "should pass Namespaced projectIDs to Utils.parseProjectId", ->
getStub = sinon.stub members, "get"
members.list "abc/def"
getStub.restore()
expect(getStub).to.have.been.calledWith "projects/abc%2Fdef/members"
describe "show()", ->
it "should use GET verb", ->
getStub = sinon.stub members, "get"
members.show 1, 2
getStub.restore()
expect(getStub).to.have.been.called
it "should pass Numeric projectIDs to Utils.parseProjectId", ->
getStub = sinon.stub members, "get"
members.show 1, 2
getStub.restore()
expect(getStub).to.have.been.calledWith "projects/1/members/2"
it "should pass Namespaced projectIDs to Utils.parseProjectId", ->
getStub = sinon.stub members, "get"
members.show "abc/def", 2
getStub.restore()
expect(getStub).to.have.been.calledWith "projects/abc%2Fdef/members/2"
describe "add()", ->
it "should use POST verb", ->
postStub = sinon.stub members, "post"
members.add 1, 1, 30
postStub.restore()
expect(postStub).to.have.been.called
| 33970 | chai = require 'chai'
expect = chai.expect
sinon = require 'sinon'
sinonChai = require 'sinon-chai'
chai.use sinonChai
describe "ProjectMembers", ->
gitlab = null
projects = null
members = null
before ->
gitlab = (require '../')
url: 'test'
token: '<PASSWORD>'
projects = gitlab.projects
members = projects.members
beforeEach ->
describe "list()", ->
it "should use GET verb", ->
getStub = sinon.stub members, "get"
members.list 1
getStub.restore()
expect(getStub).to.have.been.called
it "should pass Numeric projectIDs to Utils.parseProjectId", ->
getStub = sinon.stub members, "get"
members.list 1
getStub.restore()
expect(getStub).to.have.been.calledWith "projects/1/members"
it "should pass Namespaced projectIDs to Utils.parseProjectId", ->
getStub = sinon.stub members, "get"
members.list "abc/def"
getStub.restore()
expect(getStub).to.have.been.calledWith "projects/abc%2Fdef/members"
describe "show()", ->
it "should use GET verb", ->
getStub = sinon.stub members, "get"
members.show 1, 2
getStub.restore()
expect(getStub).to.have.been.called
it "should pass Numeric projectIDs to Utils.parseProjectId", ->
getStub = sinon.stub members, "get"
members.show 1, 2
getStub.restore()
expect(getStub).to.have.been.calledWith "projects/1/members/2"
it "should pass Namespaced projectIDs to Utils.parseProjectId", ->
getStub = sinon.stub members, "get"
members.show "abc/def", 2
getStub.restore()
expect(getStub).to.have.been.calledWith "projects/abc%2Fdef/members/2"
describe "add()", ->
it "should use POST verb", ->
postStub = sinon.stub members, "post"
members.add 1, 1, 30
postStub.restore()
expect(postStub).to.have.been.called
| true | chai = require 'chai'
expect = chai.expect
sinon = require 'sinon'
sinonChai = require 'sinon-chai'
chai.use sinonChai
describe "ProjectMembers", ->
gitlab = null
projects = null
members = null
before ->
gitlab = (require '../')
url: 'test'
token: 'PI:PASSWORD:<PASSWORD>END_PI'
projects = gitlab.projects
members = projects.members
beforeEach ->
describe "list()", ->
it "should use GET verb", ->
getStub = sinon.stub members, "get"
members.list 1
getStub.restore()
expect(getStub).to.have.been.called
it "should pass Numeric projectIDs to Utils.parseProjectId", ->
getStub = sinon.stub members, "get"
members.list 1
getStub.restore()
expect(getStub).to.have.been.calledWith "projects/1/members"
it "should pass Namespaced projectIDs to Utils.parseProjectId", ->
getStub = sinon.stub members, "get"
members.list "abc/def"
getStub.restore()
expect(getStub).to.have.been.calledWith "projects/abc%2Fdef/members"
describe "show()", ->
it "should use GET verb", ->
getStub = sinon.stub members, "get"
members.show 1, 2
getStub.restore()
expect(getStub).to.have.been.called
it "should pass Numeric projectIDs to Utils.parseProjectId", ->
getStub = sinon.stub members, "get"
members.show 1, 2
getStub.restore()
expect(getStub).to.have.been.calledWith "projects/1/members/2"
it "should pass Namespaced projectIDs to Utils.parseProjectId", ->
getStub = sinon.stub members, "get"
members.show "abc/def", 2
getStub.restore()
expect(getStub).to.have.been.calledWith "projects/abc%2Fdef/members/2"
describe "add()", ->
it "should use POST verb", ->
postStub = sinon.stub members, "post"
members.add 1, 1, 30
postStub.restore()
expect(postStub).to.have.been.called
|
[
{
"context": "egistry' ]\n idx = registry.length\n key = \"#{kind}#{idx}\"\n registry.push { key, markup, raw, parsed, }\n r",
"end": 3201,
"score": 0.9974177479743958,
"start": 3186,
"tag": "KEY",
"value": "\"#{kind}#{idx}\""
}
] | src/macro-escaper.coffee | loveencounterflow/mingkwai-typesetter | 1 |
############################################################################################################
njs_path = require 'path'
njs_fs = require 'fs'
#...........................................................................................................
CND = require 'cnd'
rpr = CND.rpr
badge = 'MK/TS/MACRO-ESCAPER'
log = CND.get_logger 'plain', badge
info = CND.get_logger 'info', badge
whisper = CND.get_logger 'whisper', badge
alert = CND.get_logger 'alert', badge
debug = CND.get_logger 'debug', badge
warn = CND.get_logger 'warn', badge
help = CND.get_logger 'help', badge
urge = CND.get_logger 'urge', badge
echo = CND.echo.bind CND
#-----------------------------------------------------------------------------------------------------------
D = require 'pipedreams'
$ = D.remit.bind D
# $async = D.remit_async.bind D
#...........................................................................................................
# Markdown_parser = require 'markdown-it'
# # Html_parser = ( require 'htmlparser2' ).Parser
# new_md_inline_plugin = require 'markdown-it-regexp'
#...........................................................................................................
# HELPERS = require './HELPERS'
#...........................................................................................................
# misfit = Symbol 'misfit'
MKTS = require './main'
@cloak = ( require './cloak' ).new()
# hide = MKTS.hide.bind MKTS
# copy = MKTS.MD_READER.copy.bind MKTS
# stamp = MKTS.stamp.bind MKTS
# select = MKTS.MD_READER.select.bind MKTS
# is_hidden = MKTS.is_hidden.bind MKTS
# is_stamped = MKTS.is_stamped.bind MKTS
XREGEXP = require 'xregexp'
@_raw_tags = []
#===========================================================================================================
# HELPERS
#-----------------------------------------------------------------------------------------------------------
@initialize_state = ( state ) =>
state[ 'MACRO_ESCAPER' ] =
registry: []
return state
#-----------------------------------------------------------------------------------------------------------
@_match_first = ( patterns, text ) =>
for pattern in patterns
return R if ( R = text.match pattern )?
return null
#-----------------------------------------------------------------------------------------------------------
@_register_content = ( S, kind, markup, raw, parsed = null ) =>
registry = S[ 'MACRO_ESCAPER' ][ 'registry' ]
idx = registry.length
key = "#{kind}#{idx}"
registry.push { key, markup, raw, parsed, }
return key
#-----------------------------------------------------------------------------------------------------------
@_retrieve_entry = ( S, id ) =>
throw new Error "unknown ID #{rpr id}" unless ( R = S[ 'MACRO_ESCAPER' ][ 'registry' ][ id ] )?
return R
#===========================================================================================================
# PATTERNS
#-----------------------------------------------------------------------------------------------------------
@PATTERNS = {}
#-----------------------------------------------------------------------------------------------------------
@html_comment_patterns = [
/// # HTML comments...
<!-- # start with less-than, exclamation mark, double hyphen;
( [ \s\S ]*? ) # then: anything, not-greedy, until we hit upon
--> # a double-slash, then greater-than.
///g # (NB: end-of-comment cannot be escaped, because HTML).
]
#-----------------------------------------------------------------------------------------------------------
@action_patterns = [
/// # A silent or vocal action macro...
#
# Start Tag
# =========
<<\( # starts with two left pointy brackets, then: left round bracket,
( [ . : ] ) # then: a dot or a colon;
(
(?: # then:
[^ > ] | # or: anything but a RPB
> (?! > ) # or: a RPB not followed by yet another RPB
)* # repeated any number of times
)
>> # then: two RPBs...
#
# Content
# =========
# Empty content.
#
# Stop Tag
# =========
() << # (then: an empty group; see below), then: two left pointy brackets,
( (?: \1 \2 )? ) # then: optionally, whatever appeared in the start tag,
\)>> # then: right round bracket, then: two RPBs.
///g
, #...........................................................................
/// # Alternatively (non-empty content):
#
# Start Tag
# =========
<<\( # starts with two left pointy brackets, then: left round bracket,
( [ . : ] ) # then: a dot or a colon;
(
(?: # then:
[^ > ] | # or: anything but a RPB
> (?! > ) # or: a RPB not followed by yet another RPB
)* # repeated any number of times
)
>> # then: two RPBs...
#
# Content
# =========
(
(?: # ...followed by content, which is:
[^ < ] | # or: anything but a LPB
< (?! < ) # or: a LPB not followed by yet another LPB
)* # repeated any number of times
)
#
# Stop Tag
# =========
<< # then: two left pointy brackets,
( (?: \1 \2 )? ) # then: optionally, whatever appeared in the start tag,
\)>> # then: right round bracket, then: two RPBs.
///g
]
#-----------------------------------------------------------------------------------------------------------
@region_patterns = [
/// # A region macro tag...
#
# Start Tag
# =========
<< # starts with two left pointy brackets
( \( ) # then: left round bracket,
( #
(?: # then:
[^ > ] | # or: anything but a RPB
> (?! > ) # or: a RPB not followed by yet another RPB
)* # repeated any number of times
)
() # then: empty group for no markup here
>> # then: two RPBs.
///g
,
/// # Stop Tag
# ========
#
<< # starts with two left pointy brackets
() # then: empty group for no markup here
( | #
[^ . : ]
(?: # then:
[^ > ] | # or: anything but a RPB
> (?! > ) # or: a RPB not followed by yet another RPB
)* # repeated any number of times
)
( \) ) # a right round bracket;
>> # then: two RPBs.
///g
]
# debug '234652', @action_patterns
# debug "abc<<(:js>>4 + 3<<:js)>>def".match @action_patterns[ 0 ]
# process.exit()
#-----------------------------------------------------------------------------------------------------------
@bracketed_raw_patterns = [
/// # A bracketed raw macro
<<(<) # starts with three left pointy brackets,
(
(?: # then:
[^ > ] | # or: anything but a RPB
>{1,2} (?! > ) # or: one or two RPBs not followed by yet another RPB
)* # repeated any number of times
)
>>> # then: three RPBs.
///g
]
#-----------------------------------------------------------------------------------------------------------
@comma_patterns = [
/// # Comma macro to separate arguments within macro regions
<<,>>
///g
]
# #-----------------------------------------------------------------------------------------------------------
# @raw_heredoc_pattern = ///
# ( ^ | [^\\] ) <<! raw: ( [^\s>]* )>> ( .*? ) \2
# ///g
#-----------------------------------------------------------------------------------------------------------
@command_and_value_patterns = [
/// # A command macro
<< # starts with two left pointy brackets,
( [ ! @ ] ) # then: an exclamation mark or a commerical-at sign,
(
(?: # then:
[^ > ] | # or: anything but a RPB
> (?! > ) # or: a RPB not followed by yet another RPB
)* # repeated any number of times
)
>> # then: two RPBs.
///g
]
#-----------------------------------------------------------------------------------------------------------
@insert_command_patterns = [
/// # An insert command macro
<< # starts with two left pointy brackets,
( ! ) # then: an exclamation mark
insert (?= [\s>] ) # then: an 'insert' literal (followed by WS or RPB)
(
(?: # then:
[^ > ] | # or: anything but a RPB
> (?! > ) # or: a RPB not followed by yet another RPB
)* # repeated any number of times
)
>> # then: two RPBs.
///g
]
#-----------------------------------------------------------------------------------------------------------
### NB The end command macro looks like any other command except we can detect it with a much simpler
RegEx; we want to do that so we can, as a first processing step, remove it and any material that appears
after it, thereby inhibiting any processing of those portions. ###
@end_command_patterns = [
/// # Then end command macro
( ^ | # starts either at the first chr
^ [ \s\S ]*? [^ \\ ] ) # or a minimal number of chrs whose last one is not a backslash
<<!end>> # then: the `<<!end>>` literal.
/// # NB that this pattern is not global.
]
#-----------------------------------------------------------------------------------------------------------
@illegal_patterns = [
/// # After applying all other macro patterns, treat as error
( << | >> ) # any occurrances of two left or two right pointy brackets.
///g
]
#===========================================================================================================
# ESCAPING
#-----------------------------------------------------------------------------------------------------------
@escape = ( S, text ) =>
# debug '©II6XI', rpr text
[ R, discard_count, ] = @escape.truncate_text_at_end_command_macro S, text
whisper "detected <<!end>> macro; discarding approx. #{discard_count} characters" if discard_count > 0
R = @escape.insert_macros S, R
R = @escape.escape_chrs S, R
R = @escape.html_comments S, R
# R = @escape.sensitive_ws S, R
R = @escape.bracketed_raw_macros S, R
R = @escape.taggish_raw_macros S, R
R = @escape.action_macros S, R
R = @escape.region_macros S, R
R = @escape.comma_macros S, R
R = @escape.command_and_value_macros S, R
#.........................................................................................................
return R
#-----------------------------------------------------------------------------------------------------------
@escape.truncate_text_at_end_command_macro = ( S, text ) =>
return [ text, 0, ] unless ( match = @_match_first @end_command_patterns, text )?
R = match[ 1 ]
# urge '©ΣΩΗΔΨ', rpr R
return [ R, text.length - R.length, ]
#-----------------------------------------------------------------------------------------------------------
@escape.escape_chrs = ( S, text ) => @cloak.backslashed.hide @cloak.hide text
@escape.unescape_escape_chrs = ( S, text ) => @cloak.reveal @cloak.backslashed.reveal text
@escape.remove_escaping_backslashes = ( S, text ) => @cloak.backslashed.remove text
#-----------------------------------------------------------------------------------------------------------
@escape.sensitive_ws = ( S, text ) =>
### Fixes an annoying parsing problem with Markdown-it where the leading whitespace in
```
<<(keep-lines>>
|𠦝韦 韩
```
is kept but deleted when the first line is blank, as in
```
<<(keep-lines>>
|𠦝韦 韩
```
###
# pattern = /// (>>) (\s*) ///g
pattern = /// (<<\(keep-lines>>) (\s*) ///g
R = text
#.........................................................................................................
# for pattern in @region_patterns
R = R.replace pattern, ( _, anchor, sws ) =>
id = @_register_content S, 'sws', sws, sws
return "#{anchor}\x15#{id}\x13"
#.........................................................................................................
return R
#-----------------------------------------------------------------------------------------------------------
@escape.html_comments = ( S, text ) =>
R = text
#.........................................................................................................
for pattern in @html_comment_patterns
R = R.replace pattern, ( _, content ) =>
key = @_register_content S, 'comment', null, content, content.trim()
return "\x15#{key}\x13"
#.........................................................................................................
return R
#-----------------------------------------------------------------------------------------------------------
@escape.bracketed_raw_macros = ( S, text ) =>
R = text
#.........................................................................................................
for pattern in @bracketed_raw_patterns
R = R.replace pattern, ( _, markup, content ) =>
id = @_register_content S, 'raw', markup, [ 'raw', content, ]
return "\x15#{id}\x13"
#.........................................................................................................
return R
#-----------------------------------------------------------------------------------------------------------
@register_raw_tag = ( tag_name ) =>
### TAINT extend to match tag with attributes ###
start_pattern = ///<#{tag_name}>|<#{tag_name}\s+(?<attributes>[^>]*)(?<!\/)>///g
stop_pattern = ///<\/#{tag_name}>///g
@_raw_tags.push [ tag_name, start_pattern, stop_pattern, ]
#...........................................................................................................
@register_raw_tag 'raw'
#-----------------------------------------------------------------------------------------------------------
@escape.taggish_raw_macros = ( S, text ) =>
parts = []
markup = null
#.........................................................................................................
settings = { valueNames: [ 'between', 'left', 'match', 'right', ], }
for [ tag_name, start_pattern, stop_pattern, ] in @_raw_tags
try
matches = XREGEXP.matchRecursive text, start_pattern.source, stop_pattern.source, 'g', settings
catch error
warn "when trying to parse text:"
urge rpr text
warn "using start pattern: #{rpr start_pattern}"
warn "using stop pattern: #{rpr stop_pattern}"
warn "for tag: #{rpr tag_name}"
warn "an error occurred: #{error.message}"
throw new Error "µ49022 #{error.message}"
#.......................................................................................................
if matches?
for match in matches
switch match.name
when 'between'
parts.push match.value
when 'left'
markup = match.value
when 'match'
id = @_register_content S, 'raw', markup, [ tag_name, match.value, ]
parts.push "\x15#{id}\x13"
when 'right'
null
text = parts.join ''
parts.length = 0
#.........................................................................................................
return text
#-----------------------------------------------------------------------------------------------------------
@escape.action_macros = ( S, text ) =>
R = text
#.........................................................................................................
for pattern in @action_patterns
R = R.replace pattern, ( _, markup, identifier, content, stopper ) =>
mode = if markup is '.' then 'silent' else 'vocal'
language = identifier
language = 'coffee' if language is ''
### TAINT not using arguments peoperly ###
id = @_register_content S, 'action', [ mode, language, ], content
return "\x15#{id}\x13"
#.........................................................................................................
return R
#-----------------------------------------------------------------------------------------------------------
@escape.insert_macros = ( S, text ) =>
R = text
#.........................................................................................................
for pattern in @insert_command_patterns
R = R.replace pattern, ( _, markup, parameter_txt ) =>
[ error_message, result, ] = MKTS.MACRO_INTERPRETER._parameters_from_text S, 0, parameter_txt
### TAINT need current context to resolve file route ###
### TAINT how to return proper error message? ###
### TAINT what kind of error handling is this? ###
if result?
[ route, ] = result
locator = njs_path.resolve S.layout_info[ 'source-home' ], route
if route?
whisper "resolved route: #{route} -> #{locator}"
try
content = njs_fs.readFileSync locator, encoding: 'utf-8'
catch error
error_message = ( error_message ? '' ) + "\n" + error[ 'message' ]
else
error_message = ( error_message ? '' ) + "\nneed file route for insert macro"
if error_message?
### TAINT provide proper location ###
# return [ '.', 'warning', error_message, {}, ]
return " ███ #{error_message} ███ "
return content
#.........................................................................................................
return R
#-----------------------------------------------------------------------------------------------------------
@escape.region_macros = ( S, text ) =>
R = text
#.........................................................................................................
for pattern in @region_patterns
R = R.replace pattern, ( _, start_markup, identifier, stop_markup ) =>
markup = if start_markup.length is 0 then stop_markup else start_markup
id = @_register_content S, 'region', markup, identifier
# if identifier is 'keep-lines'
# if start_markup is '('
# return """
# \x15#{id}\x13
# ```keep-lines"""
# else
# return """
# ```
# \x15#{id}\x13"""
return "\x15#{id}\x13"
#.........................................................................................................
return R
#-----------------------------------------------------------------------------------------------------------
@escape.comma_macros = ( S, text ) =>
R = text
#.........................................................................................................
for pattern in @comma_patterns
R = R.replace pattern, ( _ ) =>
# debug '©ΛΨ regions', ( rpr text ), [ previous_chr, markup, identifier, content, stopper, ]
id = @_register_content S, 'comma', null, null
return "\x15#{id}\x13"
#.........................................................................................................
return R
#-----------------------------------------------------------------------------------------------------------
@escape.command_and_value_macros = ( S, text ) =>
R = text
#.........................................................................................................
for pattern in @command_and_value_patterns
R = R.replace pattern, ( _, markup, content ) =>
kind = if markup is '!' then 'command' else 'value'
key = @_register_content S, kind, markup, content, null
return "\x15#{key}\x13"
#.........................................................................................................
return R
#===========================================================================================================
# EXPANDING
#-----------------------------------------------------------------------------------------------------------
@raw_id_pattern = ///
\x15 raw ( [ 0-9 ]+ ) \x13
///g
#-----------------------------------------------------------------------------------------------------------
@html_comment_id_pattern = ///
\x15 comment ( [ 0-9 ]+ ) \x13
///g
#-----------------------------------------------------------------------------------------------------------
@action_id_pattern = ///
\x15 action ( [ 0-9 ]+ ) \x13
///g
#-----------------------------------------------------------------------------------------------------------
@region_id_pattern = ///
\x15 region ( [ 0-9 ]+ ) \x13
///g
#-----------------------------------------------------------------------------------------------------------
@comma_id_pattern = ///
\x15 comma ( [ 0-9 ]+ ) \x13
///g
#-----------------------------------------------------------------------------------------------------------
@sws_id_pattern = ///
\x15 sws ( [ 0-9 ]+ ) \x13
///g
#-----------------------------------------------------------------------------------------------------------
@command_and_value_id_pattern = ///
\x15 (?: command | value ) ( [ 0-9 ]+ ) \x13
///g
#===========================================================================================================
# EXPANDERS
#-----------------------------------------------------------------------------------------------------------
@$expand = ( S ) ->
pipeline = [
@$expand.$command_and_value_macros S
@$expand.$comma_macros S
@$expand.$region_macros S
@$expand.$action_macros S
@$expand.$raw_macros S
@$expand.$sensitive_ws S
@$expand.$html_comments S
@$expand.$escape_chrs S
# @$expand.$escape_illegals S
]
#.......................................................................................................
settings =
# inputs:
# mktscript: mktscript_in
# outputs:
# mktscript: mktscript_out
S: S
#.......................................................................................................
return D.TEE.from_pipeline pipeline, settings
#-----------------------------------------------------------------------------------------------------------
@$expand.$html_comments = ( S ) =>
return @_get_expander S, @html_comment_id_pattern, ( meta, entry ) =>
[ tag_name, content, ] = entry[ 'raw' ]
return [ '.', 'comment', content, ( MKTS.MD_READER.copy meta ), ]
#-----------------------------------------------------------------------------------------------------------
@$expand.$raw_macros = ( S ) =>
return @_get_expander S, @raw_id_pattern, ( meta, entry ) =>
[ _, _, attributes, ] = MKTS.MD_READER._parse_html_open_or_lone_tag entry.markup
[ tag_name, text, ] = entry[ 'raw' ]
Q = { attributes, text, }
return [ '.', tag_name, Q, ( MKTS.MD_READER.copy meta ), ]
#-----------------------------------------------------------------------------------------------------------
@$expand.$action_macros = ( S ) =>
return @_get_expander S, @action_id_pattern, ( meta, entry ) =>
[ mode, language ] = entry[ 'markup' ]
[ tag_name, content, ] = entry[ 'raw' ]
# debug '©19694', rpr content
return [ '.', 'action', content, ( MKTS.MD_READER.copy meta, { mode, language, } ), ]
#-----------------------------------------------------------------------------------------------------------
@$expand.$comma_macros = ( S ) =>
return @_get_expander S, @comma_id_pattern, ( meta, entry ) =>
return [ '.', 'comma', null, ( MKTS.MD_READER.copy meta, ), ]
#-----------------------------------------------------------------------------------------------------------
@$expand.$sensitive_ws = ( S ) =>
return @_get_expander S, @sws_id_pattern, ( meta, entry ) =>
[ tag_name, content, ] = entry[ 'raw' ]
return [ '.', 'text', content, ( MKTS.MD_READER.copy meta, ), ]
#-----------------------------------------------------------------------------------------------------------
@$expand.$region_macros = ( S ) =>
return @_get_expander S, @region_id_pattern, ( meta, entry ) =>
{ raw
markup } = entry
return [ markup, raw, null, ( MKTS.MD_READER.copy meta ), ]
#-----------------------------------------------------------------------------------------------------------
@$expand.$command_and_value_macros = ( S ) =>
return @_get_expander S, @command_and_value_id_pattern, ( meta, entry ) =>
{ raw
markup } = entry
# macro_type = if markup is '!' then 'command' else 'value'
return [ markup, raw, null, ( MKTS.MD_READER.copy meta ), ]
#-----------------------------------------------------------------------------------------------------------
@$expand.$escape_chrs = ( S ) =>
return $ ( event, send ) =>
#.......................................................................................................
if MKTS.MD_READER.select event, '.', 'text'
[ type, name, text, meta, ] = event
# debug '9573485', rpr text
# debug '9573485', rpr @escape.unescape_escape_chrs S, text
send [ type, name, ( @escape.unescape_escape_chrs S, text ), meta, ]
#.......................................................................................................
else
send event
#-----------------------------------------------------------------------------------------------------------
@$expand.$remove_backslashes = ( S ) =>
return $ ( event, send ) =>
#.......................................................................................................
if MKTS.MD_READER.select event, '.', 'text'
[ type, name, text, meta, ] = event
# debug '83457', rpr text
# debug '83457', rpr @escape.remove_escaping_backslashes S, text
send [ type, name, ( @escape.remove_escaping_backslashes S, text ), meta, ]
#.......................................................................................................
else
send event
#-----------------------------------------------------------------------------------------------------------
@$expand.$escape_illegals = ( S ) =>
return $ ( event, send ) =>
#.......................................................................................................
if MKTS.MD_READER.select event, '.', 'text'
[ type, name, text, meta, ] = event
# debug '©38889', rpr text
#.....................................................................................................
for pattern in @illegal_patterns
stretches = []
#...................................................................................................
for raw_stretch, idx in text.split pattern
if ( idx % 3 ) is 1 then stretches[ stretches.length - 1 ] += raw_stretch
else stretches.push raw_stretch
#...................................................................................................
is_plain = yes
for stretch in stretches
is_plain = not is_plain
debug '©10012', ( if is_plain then CND.green else CND.red ) rpr stretch
unless is_plain
{ line_nr } = meta
error_message = "illegal macro pattern on line #{line_nr}: #{rpr stretch}"
send [ '.', 'warning', error_message, ( MKTS.MD_READER.copy meta ), ]
else
send [ type, name, stretch, ( MKTS.MD_READER.copy meta ), ] unless stretch.length is 0
#.......................................................................................................
else
send event
#===========================================================================================================
# GENERIC EXPANDER
#-----------------------------------------------------------------------------------------------------------
@_get_expander = ( S, pattern, method ) =>
return $ ( event, send ) =>
#.......................................................................................................
if MKTS.MD_READER.select event, '.', 'text'
is_plain = no
[ type, name, text, meta, ] = event
for stretch in text.split pattern
is_plain = not is_plain
unless is_plain
id = parseInt stretch, 10
entry = @_retrieve_entry S, id
send method meta, entry
else
send [ type, name, stretch, ( MKTS.MD_READER.copy meta ), ] unless stretch.length is 0
#.......................................................................................................
else
send event
| 135303 |
############################################################################################################
njs_path = require 'path'
njs_fs = require 'fs'
#...........................................................................................................
CND = require 'cnd'
rpr = CND.rpr
badge = 'MK/TS/MACRO-ESCAPER'
log = CND.get_logger 'plain', badge
info = CND.get_logger 'info', badge
whisper = CND.get_logger 'whisper', badge
alert = CND.get_logger 'alert', badge
debug = CND.get_logger 'debug', badge
warn = CND.get_logger 'warn', badge
help = CND.get_logger 'help', badge
urge = CND.get_logger 'urge', badge
echo = CND.echo.bind CND
#-----------------------------------------------------------------------------------------------------------
D = require 'pipedreams'
$ = D.remit.bind D
# $async = D.remit_async.bind D
#...........................................................................................................
# Markdown_parser = require 'markdown-it'
# # Html_parser = ( require 'htmlparser2' ).Parser
# new_md_inline_plugin = require 'markdown-it-regexp'
#...........................................................................................................
# HELPERS = require './HELPERS'
#...........................................................................................................
# misfit = Symbol 'misfit'
MKTS = require './main'
@cloak = ( require './cloak' ).new()
# hide = MKTS.hide.bind MKTS
# copy = MKTS.MD_READER.copy.bind MKTS
# stamp = MKTS.stamp.bind MKTS
# select = MKTS.MD_READER.select.bind MKTS
# is_hidden = MKTS.is_hidden.bind MKTS
# is_stamped = MKTS.is_stamped.bind MKTS
XREGEXP = require 'xregexp'
@_raw_tags = []
#===========================================================================================================
# HELPERS
#-----------------------------------------------------------------------------------------------------------
@initialize_state = ( state ) =>
state[ 'MACRO_ESCAPER' ] =
registry: []
return state
#-----------------------------------------------------------------------------------------------------------
@_match_first = ( patterns, text ) =>
for pattern in patterns
return R if ( R = text.match pattern )?
return null
#-----------------------------------------------------------------------------------------------------------
@_register_content = ( S, kind, markup, raw, parsed = null ) =>
registry = S[ 'MACRO_ESCAPER' ][ 'registry' ]
idx = registry.length
key = <KEY>
registry.push { key, markup, raw, parsed, }
return key
#-----------------------------------------------------------------------------------------------------------
@_retrieve_entry = ( S, id ) =>
throw new Error "unknown ID #{rpr id}" unless ( R = S[ 'MACRO_ESCAPER' ][ 'registry' ][ id ] )?
return R
#===========================================================================================================
# PATTERNS
#-----------------------------------------------------------------------------------------------------------
@PATTERNS = {}
#-----------------------------------------------------------------------------------------------------------
@html_comment_patterns = [
/// # HTML comments...
<!-- # start with less-than, exclamation mark, double hyphen;
( [ \s\S ]*? ) # then: anything, not-greedy, until we hit upon
--> # a double-slash, then greater-than.
///g # (NB: end-of-comment cannot be escaped, because HTML).
]
#-----------------------------------------------------------------------------------------------------------
@action_patterns = [
/// # A silent or vocal action macro...
#
# Start Tag
# =========
<<\( # starts with two left pointy brackets, then: left round bracket,
( [ . : ] ) # then: a dot or a colon;
(
(?: # then:
[^ > ] | # or: anything but a RPB
> (?! > ) # or: a RPB not followed by yet another RPB
)* # repeated any number of times
)
>> # then: two RPBs...
#
# Content
# =========
# Empty content.
#
# Stop Tag
# =========
() << # (then: an empty group; see below), then: two left pointy brackets,
( (?: \1 \2 )? ) # then: optionally, whatever appeared in the start tag,
\)>> # then: right round bracket, then: two RPBs.
///g
, #...........................................................................
/// # Alternatively (non-empty content):
#
# Start Tag
# =========
<<\( # starts with two left pointy brackets, then: left round bracket,
( [ . : ] ) # then: a dot or a colon;
(
(?: # then:
[^ > ] | # or: anything but a RPB
> (?! > ) # or: a RPB not followed by yet another RPB
)* # repeated any number of times
)
>> # then: two RPBs...
#
# Content
# =========
(
(?: # ...followed by content, which is:
[^ < ] | # or: anything but a LPB
< (?! < ) # or: a LPB not followed by yet another LPB
)* # repeated any number of times
)
#
# Stop Tag
# =========
<< # then: two left pointy brackets,
( (?: \1 \2 )? ) # then: optionally, whatever appeared in the start tag,
\)>> # then: right round bracket, then: two RPBs.
///g
]
#-----------------------------------------------------------------------------------------------------------
@region_patterns = [
/// # A region macro tag...
#
# Start Tag
# =========
<< # starts with two left pointy brackets
( \( ) # then: left round bracket,
( #
(?: # then:
[^ > ] | # or: anything but a RPB
> (?! > ) # or: a RPB not followed by yet another RPB
)* # repeated any number of times
)
() # then: empty group for no markup here
>> # then: two RPBs.
///g
,
/// # Stop Tag
# ========
#
<< # starts with two left pointy brackets
() # then: empty group for no markup here
( | #
[^ . : ]
(?: # then:
[^ > ] | # or: anything but a RPB
> (?! > ) # or: a RPB not followed by yet another RPB
)* # repeated any number of times
)
( \) ) # a right round bracket;
>> # then: two RPBs.
///g
]
# debug '234652', @action_patterns
# debug "abc<<(:js>>4 + 3<<:js)>>def".match @action_patterns[ 0 ]
# process.exit()
#-----------------------------------------------------------------------------------------------------------
@bracketed_raw_patterns = [
/// # A bracketed raw macro
<<(<) # starts with three left pointy brackets,
(
(?: # then:
[^ > ] | # or: anything but a RPB
>{1,2} (?! > ) # or: one or two RPBs not followed by yet another RPB
)* # repeated any number of times
)
>>> # then: three RPBs.
///g
]
#-----------------------------------------------------------------------------------------------------------
@comma_patterns = [
/// # Comma macro to separate arguments within macro regions
<<,>>
///g
]
# #-----------------------------------------------------------------------------------------------------------
# @raw_heredoc_pattern = ///
# ( ^ | [^\\] ) <<! raw: ( [^\s>]* )>> ( .*? ) \2
# ///g
#-----------------------------------------------------------------------------------------------------------
@command_and_value_patterns = [
/// # A command macro
<< # starts with two left pointy brackets,
( [ ! @ ] ) # then: an exclamation mark or a commerical-at sign,
(
(?: # then:
[^ > ] | # or: anything but a RPB
> (?! > ) # or: a RPB not followed by yet another RPB
)* # repeated any number of times
)
>> # then: two RPBs.
///g
]
#-----------------------------------------------------------------------------------------------------------
@insert_command_patterns = [
/// # An insert command macro
<< # starts with two left pointy brackets,
( ! ) # then: an exclamation mark
insert (?= [\s>] ) # then: an 'insert' literal (followed by WS or RPB)
(
(?: # then:
[^ > ] | # or: anything but a RPB
> (?! > ) # or: a RPB not followed by yet another RPB
)* # repeated any number of times
)
>> # then: two RPBs.
///g
]
#-----------------------------------------------------------------------------------------------------------
### NB The end command macro looks like any other command except we can detect it with a much simpler
RegEx; we want to do that so we can, as a first processing step, remove it and any material that appears
after it, thereby inhibiting any processing of those portions. ###
@end_command_patterns = [
/// # Then end command macro
( ^ | # starts either at the first chr
^ [ \s\S ]*? [^ \\ ] ) # or a minimal number of chrs whose last one is not a backslash
<<!end>> # then: the `<<!end>>` literal.
/// # NB that this pattern is not global.
]
#-----------------------------------------------------------------------------------------------------------
@illegal_patterns = [
/// # After applying all other macro patterns, treat as error
( << | >> ) # any occurrances of two left or two right pointy brackets.
///g
]
#===========================================================================================================
# ESCAPING
#-----------------------------------------------------------------------------------------------------------
@escape = ( S, text ) =>
# debug '©II6XI', rpr text
[ R, discard_count, ] = @escape.truncate_text_at_end_command_macro S, text
whisper "detected <<!end>> macro; discarding approx. #{discard_count} characters" if discard_count > 0
R = @escape.insert_macros S, R
R = @escape.escape_chrs S, R
R = @escape.html_comments S, R
# R = @escape.sensitive_ws S, R
R = @escape.bracketed_raw_macros S, R
R = @escape.taggish_raw_macros S, R
R = @escape.action_macros S, R
R = @escape.region_macros S, R
R = @escape.comma_macros S, R
R = @escape.command_and_value_macros S, R
#.........................................................................................................
return R
#-----------------------------------------------------------------------------------------------------------
@escape.truncate_text_at_end_command_macro = ( S, text ) =>
return [ text, 0, ] unless ( match = @_match_first @end_command_patterns, text )?
R = match[ 1 ]
# urge '©ΣΩΗΔΨ', rpr R
return [ R, text.length - R.length, ]
#-----------------------------------------------------------------------------------------------------------
@escape.escape_chrs = ( S, text ) => @cloak.backslashed.hide @cloak.hide text
@escape.unescape_escape_chrs = ( S, text ) => @cloak.reveal @cloak.backslashed.reveal text
@escape.remove_escaping_backslashes = ( S, text ) => @cloak.backslashed.remove text
#-----------------------------------------------------------------------------------------------------------
@escape.sensitive_ws = ( S, text ) =>
### Fixes an annoying parsing problem with Markdown-it where the leading whitespace in
```
<<(keep-lines>>
|𠦝韦 韩
```
is kept but deleted when the first line is blank, as in
```
<<(keep-lines>>
|𠦝韦 韩
```
###
# pattern = /// (>>) (\s*) ///g
pattern = /// (<<\(keep-lines>>) (\s*) ///g
R = text
#.........................................................................................................
# for pattern in @region_patterns
R = R.replace pattern, ( _, anchor, sws ) =>
id = @_register_content S, 'sws', sws, sws
return "#{anchor}\x15#{id}\x13"
#.........................................................................................................
return R
#-----------------------------------------------------------------------------------------------------------
@escape.html_comments = ( S, text ) =>
R = text
#.........................................................................................................
for pattern in @html_comment_patterns
R = R.replace pattern, ( _, content ) =>
key = @_register_content S, 'comment', null, content, content.trim()
return "\x15#{key}\x13"
#.........................................................................................................
return R
#-----------------------------------------------------------------------------------------------------------
@escape.bracketed_raw_macros = ( S, text ) =>
R = text
#.........................................................................................................
for pattern in @bracketed_raw_patterns
R = R.replace pattern, ( _, markup, content ) =>
id = @_register_content S, 'raw', markup, [ 'raw', content, ]
return "\x15#{id}\x13"
#.........................................................................................................
return R
#-----------------------------------------------------------------------------------------------------------
@register_raw_tag = ( tag_name ) =>
### TAINT extend to match tag with attributes ###
start_pattern = ///<#{tag_name}>|<#{tag_name}\s+(?<attributes>[^>]*)(?<!\/)>///g
stop_pattern = ///<\/#{tag_name}>///g
@_raw_tags.push [ tag_name, start_pattern, stop_pattern, ]
#...........................................................................................................
@register_raw_tag 'raw'
#-----------------------------------------------------------------------------------------------------------
@escape.taggish_raw_macros = ( S, text ) =>
parts = []
markup = null
#.........................................................................................................
settings = { valueNames: [ 'between', 'left', 'match', 'right', ], }
for [ tag_name, start_pattern, stop_pattern, ] in @_raw_tags
try
matches = XREGEXP.matchRecursive text, start_pattern.source, stop_pattern.source, 'g', settings
catch error
warn "when trying to parse text:"
urge rpr text
warn "using start pattern: #{rpr start_pattern}"
warn "using stop pattern: #{rpr stop_pattern}"
warn "for tag: #{rpr tag_name}"
warn "an error occurred: #{error.message}"
throw new Error "µ49022 #{error.message}"
#.......................................................................................................
if matches?
for match in matches
switch match.name
when 'between'
parts.push match.value
when 'left'
markup = match.value
when 'match'
id = @_register_content S, 'raw', markup, [ tag_name, match.value, ]
parts.push "\x15#{id}\x13"
when 'right'
null
text = parts.join ''
parts.length = 0
#.........................................................................................................
return text
#-----------------------------------------------------------------------------------------------------------
@escape.action_macros = ( S, text ) =>
R = text
#.........................................................................................................
for pattern in @action_patterns
R = R.replace pattern, ( _, markup, identifier, content, stopper ) =>
mode = if markup is '.' then 'silent' else 'vocal'
language = identifier
language = 'coffee' if language is ''
### TAINT not using arguments peoperly ###
id = @_register_content S, 'action', [ mode, language, ], content
return "\x15#{id}\x13"
#.........................................................................................................
return R
#-----------------------------------------------------------------------------------------------------------
@escape.insert_macros = ( S, text ) =>
R = text
#.........................................................................................................
for pattern in @insert_command_patterns
R = R.replace pattern, ( _, markup, parameter_txt ) =>
[ error_message, result, ] = MKTS.MACRO_INTERPRETER._parameters_from_text S, 0, parameter_txt
### TAINT need current context to resolve file route ###
### TAINT how to return proper error message? ###
### TAINT what kind of error handling is this? ###
if result?
[ route, ] = result
locator = njs_path.resolve S.layout_info[ 'source-home' ], route
if route?
whisper "resolved route: #{route} -> #{locator}"
try
content = njs_fs.readFileSync locator, encoding: 'utf-8'
catch error
error_message = ( error_message ? '' ) + "\n" + error[ 'message' ]
else
error_message = ( error_message ? '' ) + "\nneed file route for insert macro"
if error_message?
### TAINT provide proper location ###
# return [ '.', 'warning', error_message, {}, ]
return " ███ #{error_message} ███ "
return content
#.........................................................................................................
return R
#-----------------------------------------------------------------------------------------------------------
@escape.region_macros = ( S, text ) =>
R = text
#.........................................................................................................
for pattern in @region_patterns
R = R.replace pattern, ( _, start_markup, identifier, stop_markup ) =>
markup = if start_markup.length is 0 then stop_markup else start_markup
id = @_register_content S, 'region', markup, identifier
# if identifier is 'keep-lines'
# if start_markup is '('
# return """
# \x15#{id}\x13
# ```keep-lines"""
# else
# return """
# ```
# \x15#{id}\x13"""
return "\x15#{id}\x13"
#.........................................................................................................
return R
#-----------------------------------------------------------------------------------------------------------
@escape.comma_macros = ( S, text ) =>
R = text
#.........................................................................................................
for pattern in @comma_patterns
R = R.replace pattern, ( _ ) =>
# debug '©ΛΨ regions', ( rpr text ), [ previous_chr, markup, identifier, content, stopper, ]
id = @_register_content S, 'comma', null, null
return "\x15#{id}\x13"
#.........................................................................................................
return R
#-----------------------------------------------------------------------------------------------------------
@escape.command_and_value_macros = ( S, text ) =>
R = text
#.........................................................................................................
for pattern in @command_and_value_patterns
R = R.replace pattern, ( _, markup, content ) =>
kind = if markup is '!' then 'command' else 'value'
key = @_register_content S, kind, markup, content, null
return "\x15#{key}\x13"
#.........................................................................................................
return R
#===========================================================================================================
# EXPANDING
#-----------------------------------------------------------------------------------------------------------
@raw_id_pattern = ///
\x15 raw ( [ 0-9 ]+ ) \x13
///g
#-----------------------------------------------------------------------------------------------------------
@html_comment_id_pattern = ///
\x15 comment ( [ 0-9 ]+ ) \x13
///g
#-----------------------------------------------------------------------------------------------------------
@action_id_pattern = ///
\x15 action ( [ 0-9 ]+ ) \x13
///g
#-----------------------------------------------------------------------------------------------------------
@region_id_pattern = ///
\x15 region ( [ 0-9 ]+ ) \x13
///g
#-----------------------------------------------------------------------------------------------------------
@comma_id_pattern = ///
\x15 comma ( [ 0-9 ]+ ) \x13
///g
#-----------------------------------------------------------------------------------------------------------
@sws_id_pattern = ///
\x15 sws ( [ 0-9 ]+ ) \x13
///g
#-----------------------------------------------------------------------------------------------------------
@command_and_value_id_pattern = ///
\x15 (?: command | value ) ( [ 0-9 ]+ ) \x13
///g
#===========================================================================================================
# EXPANDERS
#-----------------------------------------------------------------------------------------------------------
@$expand = ( S ) ->
pipeline = [
@$expand.$command_and_value_macros S
@$expand.$comma_macros S
@$expand.$region_macros S
@$expand.$action_macros S
@$expand.$raw_macros S
@$expand.$sensitive_ws S
@$expand.$html_comments S
@$expand.$escape_chrs S
# @$expand.$escape_illegals S
]
#.......................................................................................................
settings =
# inputs:
# mktscript: mktscript_in
# outputs:
# mktscript: mktscript_out
S: S
#.......................................................................................................
return D.TEE.from_pipeline pipeline, settings
#-----------------------------------------------------------------------------------------------------------
@$expand.$html_comments = ( S ) =>
return @_get_expander S, @html_comment_id_pattern, ( meta, entry ) =>
[ tag_name, content, ] = entry[ 'raw' ]
return [ '.', 'comment', content, ( MKTS.MD_READER.copy meta ), ]
#-----------------------------------------------------------------------------------------------------------
@$expand.$raw_macros = ( S ) =>
return @_get_expander S, @raw_id_pattern, ( meta, entry ) =>
[ _, _, attributes, ] = MKTS.MD_READER._parse_html_open_or_lone_tag entry.markup
[ tag_name, text, ] = entry[ 'raw' ]
Q = { attributes, text, }
return [ '.', tag_name, Q, ( MKTS.MD_READER.copy meta ), ]
#-----------------------------------------------------------------------------------------------------------
@$expand.$action_macros = ( S ) =>
return @_get_expander S, @action_id_pattern, ( meta, entry ) =>
[ mode, language ] = entry[ 'markup' ]
[ tag_name, content, ] = entry[ 'raw' ]
# debug '©19694', rpr content
return [ '.', 'action', content, ( MKTS.MD_READER.copy meta, { mode, language, } ), ]
#-----------------------------------------------------------------------------------------------------------
@$expand.$comma_macros = ( S ) =>
return @_get_expander S, @comma_id_pattern, ( meta, entry ) =>
return [ '.', 'comma', null, ( MKTS.MD_READER.copy meta, ), ]
#-----------------------------------------------------------------------------------------------------------
@$expand.$sensitive_ws = ( S ) =>
return @_get_expander S, @sws_id_pattern, ( meta, entry ) =>
[ tag_name, content, ] = entry[ 'raw' ]
return [ '.', 'text', content, ( MKTS.MD_READER.copy meta, ), ]
#-----------------------------------------------------------------------------------------------------------
@$expand.$region_macros = ( S ) =>
return @_get_expander S, @region_id_pattern, ( meta, entry ) =>
{ raw
markup } = entry
return [ markup, raw, null, ( MKTS.MD_READER.copy meta ), ]
#-----------------------------------------------------------------------------------------------------------
@$expand.$command_and_value_macros = ( S ) =>
return @_get_expander S, @command_and_value_id_pattern, ( meta, entry ) =>
{ raw
markup } = entry
# macro_type = if markup is '!' then 'command' else 'value'
return [ markup, raw, null, ( MKTS.MD_READER.copy meta ), ]
#-----------------------------------------------------------------------------------------------------------
@$expand.$escape_chrs = ( S ) =>
return $ ( event, send ) =>
#.......................................................................................................
if MKTS.MD_READER.select event, '.', 'text'
[ type, name, text, meta, ] = event
# debug '9573485', rpr text
# debug '9573485', rpr @escape.unescape_escape_chrs S, text
send [ type, name, ( @escape.unescape_escape_chrs S, text ), meta, ]
#.......................................................................................................
else
send event
#-----------------------------------------------------------------------------------------------------------
@$expand.$remove_backslashes = ( S ) =>
return $ ( event, send ) =>
#.......................................................................................................
if MKTS.MD_READER.select event, '.', 'text'
[ type, name, text, meta, ] = event
# debug '83457', rpr text
# debug '83457', rpr @escape.remove_escaping_backslashes S, text
send [ type, name, ( @escape.remove_escaping_backslashes S, text ), meta, ]
#.......................................................................................................
else
send event
#-----------------------------------------------------------------------------------------------------------
@$expand.$escape_illegals = ( S ) =>
return $ ( event, send ) =>
#.......................................................................................................
if MKTS.MD_READER.select event, '.', 'text'
[ type, name, text, meta, ] = event
# debug '©38889', rpr text
#.....................................................................................................
for pattern in @illegal_patterns
stretches = []
#...................................................................................................
for raw_stretch, idx in text.split pattern
if ( idx % 3 ) is 1 then stretches[ stretches.length - 1 ] += raw_stretch
else stretches.push raw_stretch
#...................................................................................................
is_plain = yes
for stretch in stretches
is_plain = not is_plain
debug '©10012', ( if is_plain then CND.green else CND.red ) rpr stretch
unless is_plain
{ line_nr } = meta
error_message = "illegal macro pattern on line #{line_nr}: #{rpr stretch}"
send [ '.', 'warning', error_message, ( MKTS.MD_READER.copy meta ), ]
else
send [ type, name, stretch, ( MKTS.MD_READER.copy meta ), ] unless stretch.length is 0
#.......................................................................................................
else
send event
#===========================================================================================================
# GENERIC EXPANDER
#-----------------------------------------------------------------------------------------------------------
@_get_expander = ( S, pattern, method ) =>
return $ ( event, send ) =>
#.......................................................................................................
if MKTS.MD_READER.select event, '.', 'text'
is_plain = no
[ type, name, text, meta, ] = event
for stretch in text.split pattern
is_plain = not is_plain
unless is_plain
id = parseInt stretch, 10
entry = @_retrieve_entry S, id
send method meta, entry
else
send [ type, name, stretch, ( MKTS.MD_READER.copy meta ), ] unless stretch.length is 0
#.......................................................................................................
else
send event
| true |
############################################################################################################
njs_path = require 'path'
njs_fs = require 'fs'
#...........................................................................................................
CND = require 'cnd'
rpr = CND.rpr
badge = 'MK/TS/MACRO-ESCAPER'
log = CND.get_logger 'plain', badge
info = CND.get_logger 'info', badge
whisper = CND.get_logger 'whisper', badge
alert = CND.get_logger 'alert', badge
debug = CND.get_logger 'debug', badge
warn = CND.get_logger 'warn', badge
help = CND.get_logger 'help', badge
urge = CND.get_logger 'urge', badge
echo = CND.echo.bind CND
#-----------------------------------------------------------------------------------------------------------
D = require 'pipedreams'
$ = D.remit.bind D
# $async = D.remit_async.bind D
#...........................................................................................................
# Markdown_parser = require 'markdown-it'
# # Html_parser = ( require 'htmlparser2' ).Parser
# new_md_inline_plugin = require 'markdown-it-regexp'
#...........................................................................................................
# HELPERS = require './HELPERS'
#...........................................................................................................
# misfit = Symbol 'misfit'
MKTS = require './main'
@cloak = ( require './cloak' ).new()
# hide = MKTS.hide.bind MKTS
# copy = MKTS.MD_READER.copy.bind MKTS
# stamp = MKTS.stamp.bind MKTS
# select = MKTS.MD_READER.select.bind MKTS
# is_hidden = MKTS.is_hidden.bind MKTS
# is_stamped = MKTS.is_stamped.bind MKTS
XREGEXP = require 'xregexp'
@_raw_tags = []
#===========================================================================================================
# HELPERS
#-----------------------------------------------------------------------------------------------------------
@initialize_state = ( state ) =>
state[ 'MACRO_ESCAPER' ] =
registry: []
return state
#-----------------------------------------------------------------------------------------------------------
@_match_first = ( patterns, text ) =>
for pattern in patterns
return R if ( R = text.match pattern )?
return null
#-----------------------------------------------------------------------------------------------------------
@_register_content = ( S, kind, markup, raw, parsed = null ) =>
registry = S[ 'MACRO_ESCAPER' ][ 'registry' ]
idx = registry.length
key = PI:KEY:<KEY>END_PI
registry.push { key, markup, raw, parsed, }
return key
#-----------------------------------------------------------------------------------------------------------
@_retrieve_entry = ( S, id ) =>
throw new Error "unknown ID #{rpr id}" unless ( R = S[ 'MACRO_ESCAPER' ][ 'registry' ][ id ] )?
return R
#===========================================================================================================
# PATTERNS
#-----------------------------------------------------------------------------------------------------------
@PATTERNS = {}
#-----------------------------------------------------------------------------------------------------------
@html_comment_patterns = [
/// # HTML comments...
<!-- # start with less-than, exclamation mark, double hyphen;
( [ \s\S ]*? ) # then: anything, not-greedy, until we hit upon
--> # a double-slash, then greater-than.
///g # (NB: end-of-comment cannot be escaped, because HTML).
]
#-----------------------------------------------------------------------------------------------------------
@action_patterns = [
/// # A silent or vocal action macro...
#
# Start Tag
# =========
<<\( # starts with two left pointy brackets, then: left round bracket,
( [ . : ] ) # then: a dot or a colon;
(
(?: # then:
[^ > ] | # or: anything but a RPB
> (?! > ) # or: a RPB not followed by yet another RPB
)* # repeated any number of times
)
>> # then: two RPBs...
#
# Content
# =========
# Empty content.
#
# Stop Tag
# =========
() << # (then: an empty group; see below), then: two left pointy brackets,
( (?: \1 \2 )? ) # then: optionally, whatever appeared in the start tag,
\)>> # then: right round bracket, then: two RPBs.
///g
, #...........................................................................
/// # Alternatively (non-empty content):
#
# Start Tag
# =========
<<\( # starts with two left pointy brackets, then: left round bracket,
( [ . : ] ) # then: a dot or a colon;
(
(?: # then:
[^ > ] | # or: anything but a RPB
> (?! > ) # or: a RPB not followed by yet another RPB
)* # repeated any number of times
)
>> # then: two RPBs...
#
# Content
# =========
(
(?: # ...followed by content, which is:
[^ < ] | # or: anything but a LPB
< (?! < ) # or: a LPB not followed by yet another LPB
)* # repeated any number of times
)
#
# Stop Tag
# =========
<< # then: two left pointy brackets,
( (?: \1 \2 )? ) # then: optionally, whatever appeared in the start tag,
\)>> # then: right round bracket, then: two RPBs.
///g
]
#-----------------------------------------------------------------------------------------------------------
@region_patterns = [
/// # A region macro tag...
#
# Start Tag
# =========
<< # starts with two left pointy brackets
( \( ) # then: left round bracket,
( #
(?: # then:
[^ > ] | # or: anything but a RPB
> (?! > ) # or: a RPB not followed by yet another RPB
)* # repeated any number of times
)
() # then: empty group for no markup here
>> # then: two RPBs.
///g
,
/// # Stop Tag
# ========
#
<< # starts with two left pointy brackets
() # then: empty group for no markup here
( | #
[^ . : ]
(?: # then:
[^ > ] | # or: anything but a RPB
> (?! > ) # or: a RPB not followed by yet another RPB
)* # repeated any number of times
)
( \) ) # a right round bracket;
>> # then: two RPBs.
///g
]
# debug '234652', @action_patterns
# debug "abc<<(:js>>4 + 3<<:js)>>def".match @action_patterns[ 0 ]
# process.exit()
#-----------------------------------------------------------------------------------------------------------
@bracketed_raw_patterns = [
/// # A bracketed raw macro
<<(<) # starts with three left pointy brackets,
(
(?: # then:
[^ > ] | # or: anything but a RPB
>{1,2} (?! > ) # or: one or two RPBs not followed by yet another RPB
)* # repeated any number of times
)
>>> # then: three RPBs.
///g
]
#-----------------------------------------------------------------------------------------------------------
@comma_patterns = [
/// # Comma macro to separate arguments within macro regions
<<,>>
///g
]
# #-----------------------------------------------------------------------------------------------------------
# @raw_heredoc_pattern = ///
# ( ^ | [^\\] ) <<! raw: ( [^\s>]* )>> ( .*? ) \2
# ///g
#-----------------------------------------------------------------------------------------------------------
@command_and_value_patterns = [
/// # A command macro
<< # starts with two left pointy brackets,
( [ ! @ ] ) # then: an exclamation mark or a commerical-at sign,
(
(?: # then:
[^ > ] | # or: anything but a RPB
> (?! > ) # or: a RPB not followed by yet another RPB
)* # repeated any number of times
)
>> # then: two RPBs.
///g
]
#-----------------------------------------------------------------------------------------------------------
@insert_command_patterns = [
/// # An insert command macro
<< # starts with two left pointy brackets,
( ! ) # then: an exclamation mark
insert (?= [\s>] ) # then: an 'insert' literal (followed by WS or RPB)
(
(?: # then:
[^ > ] | # or: anything but a RPB
> (?! > ) # or: a RPB not followed by yet another RPB
)* # repeated any number of times
)
>> # then: two RPBs.
///g
]
#-----------------------------------------------------------------------------------------------------------
### NB The end command macro looks like any other command except we can detect it with a much simpler
RegEx; we want to do that so we can, as a first processing step, remove it and any material that appears
after it, thereby inhibiting any processing of those portions. ###
@end_command_patterns = [
/// # Then end command macro
( ^ | # starts either at the first chr
^ [ \s\S ]*? [^ \\ ] ) # or a minimal number of chrs whose last one is not a backslash
<<!end>> # then: the `<<!end>>` literal.
/// # NB that this pattern is not global.
]
#-----------------------------------------------------------------------------------------------------------
@illegal_patterns = [
/// # After applying all other macro patterns, treat as error
( << | >> ) # any occurrances of two left or two right pointy brackets.
///g
]
#===========================================================================================================
# ESCAPING
#-----------------------------------------------------------------------------------------------------------
@escape = ( S, text ) =>
# debug '©II6XI', rpr text
[ R, discard_count, ] = @escape.truncate_text_at_end_command_macro S, text
whisper "detected <<!end>> macro; discarding approx. #{discard_count} characters" if discard_count > 0
R = @escape.insert_macros S, R
R = @escape.escape_chrs S, R
R = @escape.html_comments S, R
# R = @escape.sensitive_ws S, R
R = @escape.bracketed_raw_macros S, R
R = @escape.taggish_raw_macros S, R
R = @escape.action_macros S, R
R = @escape.region_macros S, R
R = @escape.comma_macros S, R
R = @escape.command_and_value_macros S, R
#.........................................................................................................
return R
#-----------------------------------------------------------------------------------------------------------
@escape.truncate_text_at_end_command_macro = ( S, text ) =>
return [ text, 0, ] unless ( match = @_match_first @end_command_patterns, text )?
R = match[ 1 ]
# urge '©ΣΩΗΔΨ', rpr R
return [ R, text.length - R.length, ]
#-----------------------------------------------------------------------------------------------------------
@escape.escape_chrs = ( S, text ) => @cloak.backslashed.hide @cloak.hide text
@escape.unescape_escape_chrs = ( S, text ) => @cloak.reveal @cloak.backslashed.reveal text
@escape.remove_escaping_backslashes = ( S, text ) => @cloak.backslashed.remove text
#-----------------------------------------------------------------------------------------------------------
@escape.sensitive_ws = ( S, text ) =>
### Fixes an annoying parsing problem with Markdown-it where the leading whitespace in
```
<<(keep-lines>>
|𠦝韦 韩
```
is kept but deleted when the first line is blank, as in
```
<<(keep-lines>>
|𠦝韦 韩
```
###
# pattern = /// (>>) (\s*) ///g
pattern = /// (<<\(keep-lines>>) (\s*) ///g
R = text
#.........................................................................................................
# for pattern in @region_patterns
R = R.replace pattern, ( _, anchor, sws ) =>
id = @_register_content S, 'sws', sws, sws
return "#{anchor}\x15#{id}\x13"
#.........................................................................................................
return R
#-----------------------------------------------------------------------------------------------------------
@escape.html_comments = ( S, text ) =>
R = text
#.........................................................................................................
for pattern in @html_comment_patterns
R = R.replace pattern, ( _, content ) =>
key = @_register_content S, 'comment', null, content, content.trim()
return "\x15#{key}\x13"
#.........................................................................................................
return R
#-----------------------------------------------------------------------------------------------------------
@escape.bracketed_raw_macros = ( S, text ) =>
R = text
#.........................................................................................................
for pattern in @bracketed_raw_patterns
R = R.replace pattern, ( _, markup, content ) =>
id = @_register_content S, 'raw', markup, [ 'raw', content, ]
return "\x15#{id}\x13"
#.........................................................................................................
return R
#-----------------------------------------------------------------------------------------------------------
@register_raw_tag = ( tag_name ) =>
### TAINT extend to match tag with attributes ###
start_pattern = ///<#{tag_name}>|<#{tag_name}\s+(?<attributes>[^>]*)(?<!\/)>///g
stop_pattern = ///<\/#{tag_name}>///g
@_raw_tags.push [ tag_name, start_pattern, stop_pattern, ]
#...........................................................................................................
@register_raw_tag 'raw'
#-----------------------------------------------------------------------------------------------------------
@escape.taggish_raw_macros = ( S, text ) =>
parts = []
markup = null
#.........................................................................................................
settings = { valueNames: [ 'between', 'left', 'match', 'right', ], }
for [ tag_name, start_pattern, stop_pattern, ] in @_raw_tags
try
matches = XREGEXP.matchRecursive text, start_pattern.source, stop_pattern.source, 'g', settings
catch error
warn "when trying to parse text:"
urge rpr text
warn "using start pattern: #{rpr start_pattern}"
warn "using stop pattern: #{rpr stop_pattern}"
warn "for tag: #{rpr tag_name}"
warn "an error occurred: #{error.message}"
throw new Error "µ49022 #{error.message}"
#.......................................................................................................
if matches?
for match in matches
switch match.name
when 'between'
parts.push match.value
when 'left'
markup = match.value
when 'match'
id = @_register_content S, 'raw', markup, [ tag_name, match.value, ]
parts.push "\x15#{id}\x13"
when 'right'
null
text = parts.join ''
parts.length = 0
#.........................................................................................................
return text
#-----------------------------------------------------------------------------------------------------------
@escape.action_macros = ( S, text ) =>
R = text
#.........................................................................................................
for pattern in @action_patterns
R = R.replace pattern, ( _, markup, identifier, content, stopper ) =>
mode = if markup is '.' then 'silent' else 'vocal'
language = identifier
language = 'coffee' if language is ''
### TAINT not using arguments peoperly ###
id = @_register_content S, 'action', [ mode, language, ], content
return "\x15#{id}\x13"
#.........................................................................................................
return R
#-----------------------------------------------------------------------------------------------------------
@escape.insert_macros = ( S, text ) =>
R = text
#.........................................................................................................
for pattern in @insert_command_patterns
R = R.replace pattern, ( _, markup, parameter_txt ) =>
[ error_message, result, ] = MKTS.MACRO_INTERPRETER._parameters_from_text S, 0, parameter_txt
### TAINT need current context to resolve file route ###
### TAINT how to return proper error message? ###
### TAINT what kind of error handling is this? ###
if result?
[ route, ] = result
locator = njs_path.resolve S.layout_info[ 'source-home' ], route
if route?
whisper "resolved route: #{route} -> #{locator}"
try
content = njs_fs.readFileSync locator, encoding: 'utf-8'
catch error
error_message = ( error_message ? '' ) + "\n" + error[ 'message' ]
else
error_message = ( error_message ? '' ) + "\nneed file route for insert macro"
if error_message?
### TAINT provide proper location ###
# return [ '.', 'warning', error_message, {}, ]
return " ███ #{error_message} ███ "
return content
#.........................................................................................................
return R
#-----------------------------------------------------------------------------------------------------------
@escape.region_macros = ( S, text ) =>
R = text
#.........................................................................................................
for pattern in @region_patterns
R = R.replace pattern, ( _, start_markup, identifier, stop_markup ) =>
markup = if start_markup.length is 0 then stop_markup else start_markup
id = @_register_content S, 'region', markup, identifier
# if identifier is 'keep-lines'
# if start_markup is '('
# return """
# \x15#{id}\x13
# ```keep-lines"""
# else
# return """
# ```
# \x15#{id}\x13"""
return "\x15#{id}\x13"
#.........................................................................................................
return R
#-----------------------------------------------------------------------------------------------------------
@escape.comma_macros = ( S, text ) =>
R = text
#.........................................................................................................
for pattern in @comma_patterns
R = R.replace pattern, ( _ ) =>
# debug '©ΛΨ regions', ( rpr text ), [ previous_chr, markup, identifier, content, stopper, ]
id = @_register_content S, 'comma', null, null
return "\x15#{id}\x13"
#.........................................................................................................
return R
#-----------------------------------------------------------------------------------------------------------
@escape.command_and_value_macros = ( S, text ) =>
R = text
#.........................................................................................................
for pattern in @command_and_value_patterns
R = R.replace pattern, ( _, markup, content ) =>
kind = if markup is '!' then 'command' else 'value'
key = @_register_content S, kind, markup, content, null
return "\x15#{key}\x13"
#.........................................................................................................
return R
#===========================================================================================================
# EXPANDING
#-----------------------------------------------------------------------------------------------------------
@raw_id_pattern = ///
\x15 raw ( [ 0-9 ]+ ) \x13
///g
#-----------------------------------------------------------------------------------------------------------
@html_comment_id_pattern = ///
\x15 comment ( [ 0-9 ]+ ) \x13
///g
#-----------------------------------------------------------------------------------------------------------
@action_id_pattern = ///
\x15 action ( [ 0-9 ]+ ) \x13
///g
#-----------------------------------------------------------------------------------------------------------
@region_id_pattern = ///
\x15 region ( [ 0-9 ]+ ) \x13
///g
#-----------------------------------------------------------------------------------------------------------
@comma_id_pattern = ///
\x15 comma ( [ 0-9 ]+ ) \x13
///g
#-----------------------------------------------------------------------------------------------------------
@sws_id_pattern = ///
\x15 sws ( [ 0-9 ]+ ) \x13
///g
#-----------------------------------------------------------------------------------------------------------
@command_and_value_id_pattern = ///
\x15 (?: command | value ) ( [ 0-9 ]+ ) \x13
///g
#===========================================================================================================
# EXPANDERS
#-----------------------------------------------------------------------------------------------------------
@$expand = ( S ) ->
pipeline = [
@$expand.$command_and_value_macros S
@$expand.$comma_macros S
@$expand.$region_macros S
@$expand.$action_macros S
@$expand.$raw_macros S
@$expand.$sensitive_ws S
@$expand.$html_comments S
@$expand.$escape_chrs S
# @$expand.$escape_illegals S
]
#.......................................................................................................
settings =
# inputs:
# mktscript: mktscript_in
# outputs:
# mktscript: mktscript_out
S: S
#.......................................................................................................
return D.TEE.from_pipeline pipeline, settings
#-----------------------------------------------------------------------------------------------------------
@$expand.$html_comments = ( S ) =>
return @_get_expander S, @html_comment_id_pattern, ( meta, entry ) =>
[ tag_name, content, ] = entry[ 'raw' ]
return [ '.', 'comment', content, ( MKTS.MD_READER.copy meta ), ]
#-----------------------------------------------------------------------------------------------------------
@$expand.$raw_macros = ( S ) =>
return @_get_expander S, @raw_id_pattern, ( meta, entry ) =>
[ _, _, attributes, ] = MKTS.MD_READER._parse_html_open_or_lone_tag entry.markup
[ tag_name, text, ] = entry[ 'raw' ]
Q = { attributes, text, }
return [ '.', tag_name, Q, ( MKTS.MD_READER.copy meta ), ]
#-----------------------------------------------------------------------------------------------------------
@$expand.$action_macros = ( S ) =>
return @_get_expander S, @action_id_pattern, ( meta, entry ) =>
[ mode, language ] = entry[ 'markup' ]
[ tag_name, content, ] = entry[ 'raw' ]
# debug '©19694', rpr content
return [ '.', 'action', content, ( MKTS.MD_READER.copy meta, { mode, language, } ), ]
#-----------------------------------------------------------------------------------------------------------
@$expand.$comma_macros = ( S ) =>
return @_get_expander S, @comma_id_pattern, ( meta, entry ) =>
return [ '.', 'comma', null, ( MKTS.MD_READER.copy meta, ), ]
#-----------------------------------------------------------------------------------------------------------
@$expand.$sensitive_ws = ( S ) =>
return @_get_expander S, @sws_id_pattern, ( meta, entry ) =>
[ tag_name, content, ] = entry[ 'raw' ]
return [ '.', 'text', content, ( MKTS.MD_READER.copy meta, ), ]
#-----------------------------------------------------------------------------------------------------------
@$expand.$region_macros = ( S ) =>
return @_get_expander S, @region_id_pattern, ( meta, entry ) =>
{ raw
markup } = entry
return [ markup, raw, null, ( MKTS.MD_READER.copy meta ), ]
#-----------------------------------------------------------------------------------------------------------
@$expand.$command_and_value_macros = ( S ) =>
return @_get_expander S, @command_and_value_id_pattern, ( meta, entry ) =>
{ raw
markup } = entry
# macro_type = if markup is '!' then 'command' else 'value'
return [ markup, raw, null, ( MKTS.MD_READER.copy meta ), ]
#-----------------------------------------------------------------------------------------------------------
@$expand.$escape_chrs = ( S ) =>
return $ ( event, send ) =>
#.......................................................................................................
if MKTS.MD_READER.select event, '.', 'text'
[ type, name, text, meta, ] = event
# debug '9573485', rpr text
# debug '9573485', rpr @escape.unescape_escape_chrs S, text
send [ type, name, ( @escape.unescape_escape_chrs S, text ), meta, ]
#.......................................................................................................
else
send event
#-----------------------------------------------------------------------------------------------------------
@$expand.$remove_backslashes = ( S ) =>
return $ ( event, send ) =>
#.......................................................................................................
if MKTS.MD_READER.select event, '.', 'text'
[ type, name, text, meta, ] = event
# debug '83457', rpr text
# debug '83457', rpr @escape.remove_escaping_backslashes S, text
send [ type, name, ( @escape.remove_escaping_backslashes S, text ), meta, ]
#.......................................................................................................
else
send event
#-----------------------------------------------------------------------------------------------------------
@$expand.$escape_illegals = ( S ) =>
return $ ( event, send ) =>
#.......................................................................................................
if MKTS.MD_READER.select event, '.', 'text'
[ type, name, text, meta, ] = event
# debug '©38889', rpr text
#.....................................................................................................
for pattern in @illegal_patterns
stretches = []
#...................................................................................................
for raw_stretch, idx in text.split pattern
if ( idx % 3 ) is 1 then stretches[ stretches.length - 1 ] += raw_stretch
else stretches.push raw_stretch
#...................................................................................................
is_plain = yes
for stretch in stretches
is_plain = not is_plain
debug '©10012', ( if is_plain then CND.green else CND.red ) rpr stretch
unless is_plain
{ line_nr } = meta
error_message = "illegal macro pattern on line #{line_nr}: #{rpr stretch}"
send [ '.', 'warning', error_message, ( MKTS.MD_READER.copy meta ), ]
else
send [ type, name, stretch, ( MKTS.MD_READER.copy meta ), ] unless stretch.length is 0
#.......................................................................................................
else
send event
#===========================================================================================================
# GENERIC EXPANDER
#-----------------------------------------------------------------------------------------------------------
@_get_expander = ( S, pattern, method ) =>
return $ ( event, send ) =>
#.......................................................................................................
if MKTS.MD_READER.select event, '.', 'text'
is_plain = no
[ type, name, text, meta, ] = event
for stretch in text.split pattern
is_plain = not is_plain
unless is_plain
id = parseInt stretch, 10
entry = @_retrieve_entry S, id
send method meta, entry
else
send [ type, name, stretch, ( MKTS.MD_READER.copy meta ), ] unless stretch.length is 0
#.......................................................................................................
else
send event
|
[
{
"context": "uire '@moqada/hubot-schedule-helper'\n\nstoreKey = 'hubot-schedule-helper-example:schedule'\n\n\nclass ExampleJob extends Job\n exec: (robot) -",
"end": 435,
"score": 0.9945791363716125,
"start": 397,
"tag": "KEY",
"value": "hubot-schedule-helper-example:schedule"
}
] | example/scripts/example.coffee | JervisTetch/hubot-schedule-helper | 0 | # Description:
# Example scripts for @moqada/hubot-schedule-helper
#
# Commands:
# hubot schedule add "<cron pattern>" <message> - Add Schedule
# hubot schedule cancel <id> - Cancel Schedule
# hubot schedule update <id> <message> - Update Schedule
# hubot schedule list - List Schedule
{Scheduler, Job, JobNotFound, InvalidPattern} = require '@moqada/hubot-schedule-helper'
storeKey = 'hubot-schedule-helper-example:schedule'
class ExampleJob extends Job
exec: (robot) ->
robot.send @getEnvelope(), @meta.message
module.exports = (robot) ->
scheduler = new Scheduler({robot, storeKey, job: ExampleJob})
robot.respond /schedule add "(.+)" (.+)$/i, (res) ->
[pattern, message] = res.match.slice(1)
{user} = res.message
try
job = scheduler.createJob({pattern, user, meta: {message}})
res.send "Created: #{job.id}"
catch err
if err.name is InvalidPattern.name
return res.send 'invalid pattern!!!'
res.send err.message
robot.respond /schedule cancel (\d+)$/i, (res) ->
[id] = res.match.slice(1)
try
scheduler.cancelJob id
res.send "Canceled: #{id}"
catch err
if err.name is JobNotFound.name
return res.send "Job not found: #{id}"
res.send err
robot.respond /schedule list$/i, (res) ->
jobs = []
for id, job of scheduler.jobs
jobs.push "#{id}: \"#{job.pattern}\" ##{job.getRoom()} #{job.meta.message}"
if jobs.length > 0
return res.send jobs.join '\n'
res.send 'No jobs'
robot.respond /schedule update (\d+) (.+)$/i, (res) ->
[id, message] = res.match.slice(1)
try
scheduler.updateJob id, {message}
res.send "#{id}: Updated"
catch err
if err.name is JobNotFound.name
return res.send "Job not found: #{id}"
res.send err
| 85728 | # Description:
# Example scripts for @moqada/hubot-schedule-helper
#
# Commands:
# hubot schedule add "<cron pattern>" <message> - Add Schedule
# hubot schedule cancel <id> - Cancel Schedule
# hubot schedule update <id> <message> - Update Schedule
# hubot schedule list - List Schedule
{Scheduler, Job, JobNotFound, InvalidPattern} = require '@moqada/hubot-schedule-helper'
storeKey = '<KEY>'
class ExampleJob extends Job
exec: (robot) ->
robot.send @getEnvelope(), @meta.message
module.exports = (robot) ->
scheduler = new Scheduler({robot, storeKey, job: ExampleJob})
robot.respond /schedule add "(.+)" (.+)$/i, (res) ->
[pattern, message] = res.match.slice(1)
{user} = res.message
try
job = scheduler.createJob({pattern, user, meta: {message}})
res.send "Created: #{job.id}"
catch err
if err.name is InvalidPattern.name
return res.send 'invalid pattern!!!'
res.send err.message
robot.respond /schedule cancel (\d+)$/i, (res) ->
[id] = res.match.slice(1)
try
scheduler.cancelJob id
res.send "Canceled: #{id}"
catch err
if err.name is JobNotFound.name
return res.send "Job not found: #{id}"
res.send err
robot.respond /schedule list$/i, (res) ->
jobs = []
for id, job of scheduler.jobs
jobs.push "#{id}: \"#{job.pattern}\" ##{job.getRoom()} #{job.meta.message}"
if jobs.length > 0
return res.send jobs.join '\n'
res.send 'No jobs'
robot.respond /schedule update (\d+) (.+)$/i, (res) ->
[id, message] = res.match.slice(1)
try
scheduler.updateJob id, {message}
res.send "#{id}: Updated"
catch err
if err.name is JobNotFound.name
return res.send "Job not found: #{id}"
res.send err
| true | # Description:
# Example scripts for @moqada/hubot-schedule-helper
#
# Commands:
# hubot schedule add "<cron pattern>" <message> - Add Schedule
# hubot schedule cancel <id> - Cancel Schedule
# hubot schedule update <id> <message> - Update Schedule
# hubot schedule list - List Schedule
{Scheduler, Job, JobNotFound, InvalidPattern} = require '@moqada/hubot-schedule-helper'
storeKey = 'PI:KEY:<KEY>END_PI'
class ExampleJob extends Job
exec: (robot) ->
robot.send @getEnvelope(), @meta.message
module.exports = (robot) ->
scheduler = new Scheduler({robot, storeKey, job: ExampleJob})
robot.respond /schedule add "(.+)" (.+)$/i, (res) ->
[pattern, message] = res.match.slice(1)
{user} = res.message
try
job = scheduler.createJob({pattern, user, meta: {message}})
res.send "Created: #{job.id}"
catch err
if err.name is InvalidPattern.name
return res.send 'invalid pattern!!!'
res.send err.message
robot.respond /schedule cancel (\d+)$/i, (res) ->
[id] = res.match.slice(1)
try
scheduler.cancelJob id
res.send "Canceled: #{id}"
catch err
if err.name is JobNotFound.name
return res.send "Job not found: #{id}"
res.send err
robot.respond /schedule list$/i, (res) ->
jobs = []
for id, job of scheduler.jobs
jobs.push "#{id}: \"#{job.pattern}\" ##{job.getRoom()} #{job.meta.message}"
if jobs.length > 0
return res.send jobs.join '\n'
res.send 'No jobs'
robot.respond /schedule update (\d+) (.+)$/i, (res) ->
[id, message] = res.match.slice(1)
try
scheduler.updateJob id, {message}
res.send "#{id}: Updated"
catch err
if err.name is JobNotFound.name
return res.send "Job not found: #{id}"
res.send err
|
[
{
"context": "#\njQuery Credit Card Validator 1.2\n\nCopyright 2012 Pawel Decowski\n\nPermission is hereby granted, free of charge, to",
"end": 67,
"score": 0.9998152852058411,
"start": 53,
"tag": "NAME",
"value": "Pawel Decowski"
},
{
"context": "th: [ 16 ]\n }\n {\n ... | jquery.creditCardValidator.coffee | devasia2112/jQuery-CreditCardValidator | 540 | ###
jQuery Credit Card Validator 1.2
Copyright 2012 Pawel Decowski
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.
###
$ = jQuery
$.fn.validateCreditCard = (callback, options) ->
card_types = [
{
name: 'amex'
range: '34,37'
valid_length: [ 15 ]
}
{
name: 'diners_club_carte_blanche'
range: '300-305'
valid_length: [ 16..19 ]
}
{
name: 'diners_club_international'
range: '3095, 36, 38-39'
valid_length: [ 14..19 ]
}
{
name: 'jcb'
range: '3088-3094, 3096-3102, 3112-3120, 3158-3159, 3337-3349, 3528-3589'
valid_length: [ 16 ]
}
{
name: 'laser'
range: '6304, 6706, 6709, 6771'
valid_length: [ 16..19 ]
}
{
name: 'visa_electron'
range: '4026, 417500, 4508, 4844, 4913, 4917'
valid_length: [ 16 ]
}
{
name: 'visa'
range: '4'
valid_length: [ 13..19 ]
}
{
name: 'mastercard'
range: '51-55,2221-2720'
valid_length: [ 16 ]
}
{
name: 'discover'
range: '6011, 622126-622925, 644-649, 65'
valid_length: [ 16..19 ]
}
{
name: 'dankort'
range: '5019'
valid_length: [ 16 ]
}
{
name: 'maestro'
range: '50, 56-69'
valid_length: [ 12..19 ]
}
{
name: 'uatp'
range: '1'
valid_length: [ 15 ]
}
{
name: 'mir'
range: '2200-2204'
valid_length: [ 16 ]
}
]
bind = false
if callback
if typeof callback == 'object'
# callback has been skipped and only options parameter has been passed
options = callback
bind = false
callback = null
else if typeof callback == 'function'
bind = true
options ?= {}
options.accept ?= (card.name for card in card_types)
for card_type in options.accept
if card_type not in (card.name for card in card_types)
throw Error "Credit card type '#{ card_type }' is not supported"
get_card_type = (number) ->
for card_type in (card for card in card_types when card.name in options.accept)
r = Range.rangeWithString(card_type.range)
if r.match(number)
return card_type
null
is_valid_luhn = (number) ->
sum = 0
for digit, n in number.split('').reverse()
digit = +digit # the + casts the string to int
if n % 2
digit *= 2
if digit < 10 then sum += digit else sum += digit - 9
else
sum += digit
sum % 10 == 0
is_valid_length = (number, card_type) ->
number.length in card_type.valid_length
validate_number = (number) ->
card_type = get_card_type number
luhn_valid = is_valid_luhn number
length_valid = false
if card_type?
length_valid = is_valid_length number, card_type
card_type: card_type
valid: luhn_valid and length_valid
luhn_valid: luhn_valid
length_valid: length_valid
validate = =>
number = normalize $(this).val()
validate_number number
normalize = (number) ->
number.replace /[ -]/g, ''
if not bind
return validate()
this.on('input.jccv', =>
$(this).off('keyup.jccv') # if input event is fired (so is supported) then unbind keyup
callback.call this, validate()
)
# bind keyup in case input event isn't supported
this.on('keyup.jccv', =>
callback.call this, validate()
)
# run validation straight away in case the card number is prefilled
callback.call this, validate()
this
| 86893 | ###
jQuery Credit Card Validator 1.2
Copyright 2012 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
###
$ = jQuery
$.fn.validateCreditCard = (callback, options) ->
card_types = [
{
name: 'amex'
range: '34,37'
valid_length: [ 15 ]
}
{
name: 'diners_club_carte_blanche'
range: '300-305'
valid_length: [ 16..19 ]
}
{
name: 'diners_club_international'
range: '3095, 36, 38-39'
valid_length: [ 14..19 ]
}
{
name: 'jcb'
range: '3088-3094, 3096-3102, 3112-3120, 3158-3159, 3337-3349, 3528-3589'
valid_length: [ 16 ]
}
{
name: 'laser'
range: '6304, 6706, 6709, 6771'
valid_length: [ 16..19 ]
}
{
name: 'visa_electron'
range: '4026, 417500, 4508, 4844, 4913, 4917'
valid_length: [ 16 ]
}
{
name: '<NAME>'
range: '4'
valid_length: [ 13..19 ]
}
{
name: '<NAME>'
range: '51-55,2221-2720'
valid_length: [ 16 ]
}
{
name: '<NAME>'
range: '6011, 622126-622925, 644-649, 65'
valid_length: [ 16..19 ]
}
{
name: '<NAME>'
range: '5019'
valid_length: [ 16 ]
}
{
name: '<NAME>'
range: '50, 56-69'
valid_length: [ 12..19 ]
}
{
name: '<NAME>'
range: '1'
valid_length: [ 15 ]
}
{
name: '<NAME>'
range: '2200-2204'
valid_length: [ 16 ]
}
]
bind = false
if callback
if typeof callback == 'object'
# callback has been skipped and only options parameter has been passed
options = callback
bind = false
callback = null
else if typeof callback == 'function'
bind = true
options ?= {}
options.accept ?= (card.name for card in card_types)
for card_type in options.accept
if card_type not in (card.name for card in card_types)
throw Error "Credit card type '#{ card_type }' is not supported"
get_card_type = (number) ->
for card_type in (card for card in card_types when card.name in options.accept)
r = Range.rangeWithString(card_type.range)
if r.match(number)
return card_type
null
is_valid_luhn = (number) ->
sum = 0
for digit, n in number.split('').reverse()
digit = +digit # the + casts the string to int
if n % 2
digit *= 2
if digit < 10 then sum += digit else sum += digit - 9
else
sum += digit
sum % 10 == 0
is_valid_length = (number, card_type) ->
number.length in card_type.valid_length
validate_number = (number) ->
card_type = get_card_type number
luhn_valid = is_valid_luhn number
length_valid = false
if card_type?
length_valid = is_valid_length number, card_type
card_type: card_type
valid: luhn_valid and length_valid
luhn_valid: luhn_valid
length_valid: length_valid
validate = =>
number = normalize $(this).val()
validate_number number
normalize = (number) ->
number.replace /[ -]/g, ''
if not bind
return validate()
this.on('input.jccv', =>
$(this).off('keyup.jccv') # if input event is fired (so is supported) then unbind keyup
callback.call this, validate()
)
# bind keyup in case input event isn't supported
this.on('keyup.jccv', =>
callback.call this, validate()
)
# run validation straight away in case the card number is prefilled
callback.call this, validate()
this
| true | ###
jQuery Credit Card Validator 1.2
Copyright 2012 PI:NAME:<NAME>END_PI
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
###
$ = jQuery
$.fn.validateCreditCard = (callback, options) ->
card_types = [
{
name: 'amex'
range: '34,37'
valid_length: [ 15 ]
}
{
name: 'diners_club_carte_blanche'
range: '300-305'
valid_length: [ 16..19 ]
}
{
name: 'diners_club_international'
range: '3095, 36, 38-39'
valid_length: [ 14..19 ]
}
{
name: 'jcb'
range: '3088-3094, 3096-3102, 3112-3120, 3158-3159, 3337-3349, 3528-3589'
valid_length: [ 16 ]
}
{
name: 'laser'
range: '6304, 6706, 6709, 6771'
valid_length: [ 16..19 ]
}
{
name: 'visa_electron'
range: '4026, 417500, 4508, 4844, 4913, 4917'
valid_length: [ 16 ]
}
{
name: 'PI:NAME:<NAME>END_PI'
range: '4'
valid_length: [ 13..19 ]
}
{
name: 'PI:NAME:<NAME>END_PI'
range: '51-55,2221-2720'
valid_length: [ 16 ]
}
{
name: 'PI:NAME:<NAME>END_PI'
range: '6011, 622126-622925, 644-649, 65'
valid_length: [ 16..19 ]
}
{
name: 'PI:NAME:<NAME>END_PI'
range: '5019'
valid_length: [ 16 ]
}
{
name: 'PI:NAME:<NAME>END_PI'
range: '50, 56-69'
valid_length: [ 12..19 ]
}
{
name: 'PI:NAME:<NAME>END_PI'
range: '1'
valid_length: [ 15 ]
}
{
name: 'PI:NAME:<NAME>END_PI'
range: '2200-2204'
valid_length: [ 16 ]
}
]
bind = false
if callback
if typeof callback == 'object'
# callback has been skipped and only options parameter has been passed
options = callback
bind = false
callback = null
else if typeof callback == 'function'
bind = true
options ?= {}
options.accept ?= (card.name for card in card_types)
for card_type in options.accept
if card_type not in (card.name for card in card_types)
throw Error "Credit card type '#{ card_type }' is not supported"
get_card_type = (number) ->
for card_type in (card for card in card_types when card.name in options.accept)
r = Range.rangeWithString(card_type.range)
if r.match(number)
return card_type
null
is_valid_luhn = (number) ->
sum = 0
for digit, n in number.split('').reverse()
digit = +digit # the + casts the string to int
if n % 2
digit *= 2
if digit < 10 then sum += digit else sum += digit - 9
else
sum += digit
sum % 10 == 0
is_valid_length = (number, card_type) ->
number.length in card_type.valid_length
validate_number = (number) ->
card_type = get_card_type number
luhn_valid = is_valid_luhn number
length_valid = false
if card_type?
length_valid = is_valid_length number, card_type
card_type: card_type
valid: luhn_valid and length_valid
luhn_valid: luhn_valid
length_valid: length_valid
validate = =>
number = normalize $(this).val()
validate_number number
normalize = (number) ->
number.replace /[ -]/g, ''
if not bind
return validate()
this.on('input.jccv', =>
$(this).off('keyup.jccv') # if input event is fired (so is supported) then unbind keyup
callback.call this, validate()
)
# bind keyup in case input event isn't supported
this.on('keyup.jccv', =>
callback.call this, validate()
)
# run validation straight away in case the card number is prefilled
callback.call this, validate()
this
|
[
{
"context": "f square bracket notation when possible.\n# @author Josh Perez\n###\n'use strict'\n\n#------------------------------",
"end": 129,
"score": 0.9998550415039062,
"start": 119,
"tag": "NAME",
"value": "Josh Perez"
}
] | src/rules/dot-notation.coffee | danielbayley/eslint-plugin-coffee | 21 | ###*
# @fileoverview Rule to warn about using dot notation instead of square bracket notation when possible.
# @author Josh Perez
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
astUtils = require '../eslint-ast-utils'
#------------------------------------------------------------------------------
# Rule Definition
#------------------------------------------------------------------------------
validIdentifier = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/
keywords = require '../eslint-keywords'
module.exports =
meta:
docs:
description: 'enforce dot notation whenever possible'
category: 'Best Practices'
recommended: no
url: 'https://eslint.org/docs/rules/dot-notation'
schema: [
type: 'object'
properties:
allowKeywords:
type: 'boolean'
allowPattern:
type: 'string'
additionalProperties: no
]
fixable: 'code'
messages:
useDot: '[{{key}}] is better written in dot notation.'
useBrackets: '.{{key}} is a syntax error.'
create: (context) ->
options = context.options[0] or {}
allowKeywords =
options.allowKeywords is undefined or !!options.allowKeywords
sourceCode = context.getSourceCode()
allowPattern = new RegExp options.allowPattern if options.allowPattern
###*
# Check if the property is valid dot notation
# @param {ASTNode} node The dot notation node
# @param {string} value Value which is to be checked
# @returns {void}
###
checkComputedProperty = (node, value) ->
if (
validIdentifier.test(value) and
(allowKeywords or keywords.indexOf(String value) is -1) and
not allowPattern?.test value
)
formattedValue =
if node.property.type is 'Literal'
JSON.stringify value
else
"\"#{value}\""
context.report
node: node.property
messageId: 'useDot'
data:
key: formattedValue
fix: (fixer) ->
leftBracket = sourceCode.getTokenAfter(
node.object
astUtils.isOpeningBracketToken
)
rightBracket = sourceCode.getLastToken node
# Don't perform any fixes if there are comments inside the brackets.
return null if sourceCode.getFirstTokenBetween(
leftBracket
rightBracket
includeComments: yes, filter: astUtils.isCommentToken
)
tokenAfterProperty = sourceCode.getTokenAfter rightBracket
needsSpaceAfterProperty =
tokenAfterProperty and
rightBracket.range[1] is tokenAfterProperty.range[0] and
not astUtils.canTokensBeAdjacent String(value), tokenAfterProperty
textBeforeDot =
if astUtils.isDecimalInteger node.object
' '
else
''
textAfterProperty = if needsSpaceAfterProperty then ' ' else ''
fixer.replaceTextRange(
[leftBracket.range[0], rightBracket.range[1]]
"#{textBeforeDot}.#{value}#{textAfterProperty}"
)
MemberExpression: (node) ->
if node.computed and node.property.type is 'Literal'
checkComputedProperty node, node.property.value
if (
node.computed and
node.property.type is 'TemplateLiteral' and
node.property.expressions.length is 0
)
# TODO: use cooked once exposed on AST?
# checkComputedProperty node, node.property.quasis[0].value.cooked
checkComputedProperty node, node.property.quasis[0].value.raw
if (
not allowKeywords and
not node.computed and
keywords.indexOf(String node.property.name) isnt -1
)
context.report
node: node.property
messageId: 'useBrackets'
data:
key: node.property.name
fix: (fixer) ->
dot = sourceCode.getTokenBefore node.property
textAfterDot = sourceCode.text.slice(
dot.range[1]
node.property.range[0]
)
# Don't perform any fixes if there are comments between the dot and the property name.
return null if textAfterDot.trim()
# ###
# # A statement that starts with `let[` is parsed as a destructuring variable declaration, not
# # a MemberExpression.
# ###
# return null if (
# node.object.type is 'Identifier' and node.object.name is 'let'
# )
fixer.replaceTextRange(
[dot.range[0], node.property.range[1]]
"[#{textAfterDot}\"#{node.property.name}\"]"
)
| 101760 | ###*
# @fileoverview Rule to warn about using dot notation instead of square bracket notation when possible.
# @author <NAME>
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
astUtils = require '../eslint-ast-utils'
#------------------------------------------------------------------------------
# Rule Definition
#------------------------------------------------------------------------------
validIdentifier = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/
keywords = require '../eslint-keywords'
module.exports =
meta:
docs:
description: 'enforce dot notation whenever possible'
category: 'Best Practices'
recommended: no
url: 'https://eslint.org/docs/rules/dot-notation'
schema: [
type: 'object'
properties:
allowKeywords:
type: 'boolean'
allowPattern:
type: 'string'
additionalProperties: no
]
fixable: 'code'
messages:
useDot: '[{{key}}] is better written in dot notation.'
useBrackets: '.{{key}} is a syntax error.'
create: (context) ->
options = context.options[0] or {}
allowKeywords =
options.allowKeywords is undefined or !!options.allowKeywords
sourceCode = context.getSourceCode()
allowPattern = new RegExp options.allowPattern if options.allowPattern
###*
# Check if the property is valid dot notation
# @param {ASTNode} node The dot notation node
# @param {string} value Value which is to be checked
# @returns {void}
###
checkComputedProperty = (node, value) ->
if (
validIdentifier.test(value) and
(allowKeywords or keywords.indexOf(String value) is -1) and
not allowPattern?.test value
)
formattedValue =
if node.property.type is 'Literal'
JSON.stringify value
else
"\"#{value}\""
context.report
node: node.property
messageId: 'useDot'
data:
key: formattedValue
fix: (fixer) ->
leftBracket = sourceCode.getTokenAfter(
node.object
astUtils.isOpeningBracketToken
)
rightBracket = sourceCode.getLastToken node
# Don't perform any fixes if there are comments inside the brackets.
return null if sourceCode.getFirstTokenBetween(
leftBracket
rightBracket
includeComments: yes, filter: astUtils.isCommentToken
)
tokenAfterProperty = sourceCode.getTokenAfter rightBracket
needsSpaceAfterProperty =
tokenAfterProperty and
rightBracket.range[1] is tokenAfterProperty.range[0] and
not astUtils.canTokensBeAdjacent String(value), tokenAfterProperty
textBeforeDot =
if astUtils.isDecimalInteger node.object
' '
else
''
textAfterProperty = if needsSpaceAfterProperty then ' ' else ''
fixer.replaceTextRange(
[leftBracket.range[0], rightBracket.range[1]]
"#{textBeforeDot}.#{value}#{textAfterProperty}"
)
MemberExpression: (node) ->
if node.computed and node.property.type is 'Literal'
checkComputedProperty node, node.property.value
if (
node.computed and
node.property.type is 'TemplateLiteral' and
node.property.expressions.length is 0
)
# TODO: use cooked once exposed on AST?
# checkComputedProperty node, node.property.quasis[0].value.cooked
checkComputedProperty node, node.property.quasis[0].value.raw
if (
not allowKeywords and
not node.computed and
keywords.indexOf(String node.property.name) isnt -1
)
context.report
node: node.property
messageId: 'useBrackets'
data:
key: node.property.name
fix: (fixer) ->
dot = sourceCode.getTokenBefore node.property
textAfterDot = sourceCode.text.slice(
dot.range[1]
node.property.range[0]
)
# Don't perform any fixes if there are comments between the dot and the property name.
return null if textAfterDot.trim()
# ###
# # A statement that starts with `let[` is parsed as a destructuring variable declaration, not
# # a MemberExpression.
# ###
# return null if (
# node.object.type is 'Identifier' and node.object.name is 'let'
# )
fixer.replaceTextRange(
[dot.range[0], node.property.range[1]]
"[#{textAfterDot}\"#{node.property.name}\"]"
)
| true | ###*
# @fileoverview Rule to warn about using dot notation instead of square bracket notation when possible.
# @author PI:NAME:<NAME>END_PI
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
astUtils = require '../eslint-ast-utils'
#------------------------------------------------------------------------------
# Rule Definition
#------------------------------------------------------------------------------
validIdentifier = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/
keywords = require '../eslint-keywords'
module.exports =
meta:
docs:
description: 'enforce dot notation whenever possible'
category: 'Best Practices'
recommended: no
url: 'https://eslint.org/docs/rules/dot-notation'
schema: [
type: 'object'
properties:
allowKeywords:
type: 'boolean'
allowPattern:
type: 'string'
additionalProperties: no
]
fixable: 'code'
messages:
useDot: '[{{key}}] is better written in dot notation.'
useBrackets: '.{{key}} is a syntax error.'
create: (context) ->
options = context.options[0] or {}
allowKeywords =
options.allowKeywords is undefined or !!options.allowKeywords
sourceCode = context.getSourceCode()
allowPattern = new RegExp options.allowPattern if options.allowPattern
###*
# Check if the property is valid dot notation
# @param {ASTNode} node The dot notation node
# @param {string} value Value which is to be checked
# @returns {void}
###
checkComputedProperty = (node, value) ->
if (
validIdentifier.test(value) and
(allowKeywords or keywords.indexOf(String value) is -1) and
not allowPattern?.test value
)
formattedValue =
if node.property.type is 'Literal'
JSON.stringify value
else
"\"#{value}\""
context.report
node: node.property
messageId: 'useDot'
data:
key: formattedValue
fix: (fixer) ->
leftBracket = sourceCode.getTokenAfter(
node.object
astUtils.isOpeningBracketToken
)
rightBracket = sourceCode.getLastToken node
# Don't perform any fixes if there are comments inside the brackets.
return null if sourceCode.getFirstTokenBetween(
leftBracket
rightBracket
includeComments: yes, filter: astUtils.isCommentToken
)
tokenAfterProperty = sourceCode.getTokenAfter rightBracket
needsSpaceAfterProperty =
tokenAfterProperty and
rightBracket.range[1] is tokenAfterProperty.range[0] and
not astUtils.canTokensBeAdjacent String(value), tokenAfterProperty
textBeforeDot =
if astUtils.isDecimalInteger node.object
' '
else
''
textAfterProperty = if needsSpaceAfterProperty then ' ' else ''
fixer.replaceTextRange(
[leftBracket.range[0], rightBracket.range[1]]
"#{textBeforeDot}.#{value}#{textAfterProperty}"
)
MemberExpression: (node) ->
if node.computed and node.property.type is 'Literal'
checkComputedProperty node, node.property.value
if (
node.computed and
node.property.type is 'TemplateLiteral' and
node.property.expressions.length is 0
)
# TODO: use cooked once exposed on AST?
# checkComputedProperty node, node.property.quasis[0].value.cooked
checkComputedProperty node, node.property.quasis[0].value.raw
if (
not allowKeywords and
not node.computed and
keywords.indexOf(String node.property.name) isnt -1
)
context.report
node: node.property
messageId: 'useBrackets'
data:
key: node.property.name
fix: (fixer) ->
dot = sourceCode.getTokenBefore node.property
textAfterDot = sourceCode.text.slice(
dot.range[1]
node.property.range[0]
)
# Don't perform any fixes if there are comments between the dot and the property name.
return null if textAfterDot.trim()
# ###
# # A statement that starts with `let[` is parsed as a destructuring variable declaration, not
# # a MemberExpression.
# ###
# return null if (
# node.object.type is 'Identifier' and node.object.name is 'let'
# )
fixer.replaceTextRange(
[dot.range[0], node.property.range[1]]
"[#{textAfterDot}\"#{node.property.name}\"]"
)
|
[
{
"context": "###\n# @author Argi Karunia <https://github.com/hkyo89>\n# @link https://gi",
"end": 27,
"score": 0.9998682141304016,
"start": 15,
"tag": "NAME",
"value": "Argi Karunia"
},
{
"context": "###\n# @author Argi Karunia <https://github.com/hkyo89>\n# @link https://gi... | src/file.coffee | tokopedia/nodame | 2 | ###
# @author Argi Karunia <https://github.com/hkyo89>
# @link https://github.com/tokopedia/nodame
# @license http://opensource.org/licenses/MIT
#
# @version 1.0.0
###
sha512 = require('js-sha512').sha512;
fs = require('fs')
path = require('./path')
YAMLParser = require('js-yaml')
class File
readJSON: (filepath) ->
return unless fs.statSync filepath
JSON.parse fs.readFileSync(filepath)
readGRUNT: (filepath) ->
json = @readYAML filepath
confDir = path.dirname filepath
config = @readYAML "#{confDir}/main.yaml"
assetsDir = path.safe "#{path.app}/assets"
if config.assets.dir?
assetsDir =
if config.assets.dir.substr(0, 1) is '/' then config.assets.dir
else path.safe "#{path.app}/#{config.assets.dir}"
grunt = {}
typeDir =
css: 'css'
js: 'scripts'
for groups of json
for group of json[groups]
for type of json[groups][group]
grunt[type] = [] unless grunt[type]?
baseName = "#{groups}.#{group}"
hash = @_hash "#{baseName}#{type}", 8
dest = "#{baseName}.min.#{hash}.#{type}"
destSrc = {}
destSrc[dest] = []
baseDir = ''
if json[groups][group][type].length > 0
for j of json[groups][group][type]
filename = json[groups][group][type][j]
if filename?
_filepath = "#{baseDir}#{json[groups][group][type][j]}"
destSrc[dest].push _filepath
grunt[type].push destSrc
grunt
_hash: (str, len) ->
hash = sha512 "#{str}#{new Date()}"
if len? and len < hash.length
lenMed = Math.floor hash.length / 2
start = if len < lenMed then lenMed - (Math.floor len / 2) else 0
hash = hash.substr start, len
hash
readYAML: (filepath) ->
return unless fs.statSync filepath
YAMLParser.safeLoad(fs.readFileSync(filepath))
module.exports = new File()
| 7298 | ###
# @author <NAME> <https://github.com/hkyo89>
# @link https://github.com/tokopedia/nodame
# @license http://opensource.org/licenses/MIT
#
# @version 1.0.0
###
sha512 = require('js-sha512').sha512;
fs = require('fs')
path = require('./path')
YAMLParser = require('js-yaml')
class File
readJSON: (filepath) ->
return unless fs.statSync filepath
JSON.parse fs.readFileSync(filepath)
readGRUNT: (filepath) ->
json = @readYAML filepath
confDir = path.dirname filepath
config = @readYAML "#{confDir}/main.yaml"
assetsDir = path.safe "#{path.app}/assets"
if config.assets.dir?
assetsDir =
if config.assets.dir.substr(0, 1) is '/' then config.assets.dir
else path.safe "#{path.app}/#{config.assets.dir}"
grunt = {}
typeDir =
css: 'css'
js: 'scripts'
for groups of json
for group of json[groups]
for type of json[groups][group]
grunt[type] = [] unless grunt[type]?
baseName = "#{groups}.#{group}"
hash = @_hash "#{baseName}#{type}", 8
dest = "#{baseName}.min.#{hash}.#{type}"
destSrc = {}
destSrc[dest] = []
baseDir = ''
if json[groups][group][type].length > 0
for j of json[groups][group][type]
filename = json[groups][group][type][j]
if filename?
_filepath = "#{baseDir}#{json[groups][group][type][j]}"
destSrc[dest].push _filepath
grunt[type].push destSrc
grunt
_hash: (str, len) ->
hash = sha512 "#{str}#{new Date()}"
if len? and len < hash.length
lenMed = Math.floor hash.length / 2
start = if len < lenMed then lenMed - (Math.floor len / 2) else 0
hash = hash.substr start, len
hash
readYAML: (filepath) ->
return unless fs.statSync filepath
YAMLParser.safeLoad(fs.readFileSync(filepath))
module.exports = new File()
| true | ###
# @author PI:NAME:<NAME>END_PI <https://github.com/hkyo89>
# @link https://github.com/tokopedia/nodame
# @license http://opensource.org/licenses/MIT
#
# @version 1.0.0
###
sha512 = require('js-sha512').sha512;
fs = require('fs')
path = require('./path')
YAMLParser = require('js-yaml')
class File
readJSON: (filepath) ->
return unless fs.statSync filepath
JSON.parse fs.readFileSync(filepath)
readGRUNT: (filepath) ->
json = @readYAML filepath
confDir = path.dirname filepath
config = @readYAML "#{confDir}/main.yaml"
assetsDir = path.safe "#{path.app}/assets"
if config.assets.dir?
assetsDir =
if config.assets.dir.substr(0, 1) is '/' then config.assets.dir
else path.safe "#{path.app}/#{config.assets.dir}"
grunt = {}
typeDir =
css: 'css'
js: 'scripts'
for groups of json
for group of json[groups]
for type of json[groups][group]
grunt[type] = [] unless grunt[type]?
baseName = "#{groups}.#{group}"
hash = @_hash "#{baseName}#{type}", 8
dest = "#{baseName}.min.#{hash}.#{type}"
destSrc = {}
destSrc[dest] = []
baseDir = ''
if json[groups][group][type].length > 0
for j of json[groups][group][type]
filename = json[groups][group][type][j]
if filename?
_filepath = "#{baseDir}#{json[groups][group][type][j]}"
destSrc[dest].push _filepath
grunt[type].push destSrc
grunt
_hash: (str, len) ->
hash = sha512 "#{str}#{new Date()}"
if len? and len < hash.length
lenMed = Math.floor hash.length / 2
start = if len < lenMed then lenMed - (Math.floor len / 2) else 0
hash = hash.substr start, len
hash
readYAML: (filepath) ->
return unless fs.statSync filepath
YAMLParser.safeLoad(fs.readFileSync(filepath))
module.exports = new File()
|
[
{
"context": ")\n no\n\n\n# /user/u@catz.net/posts → [\"/user/u@catz.net/\", \"u@catz.net\"]\nNODEID_TO_USER_REGEX = ",
"end": 698,
"score": 0.7696087956428528,
"start": 697,
"tag": "EMAIL",
"value": "u"
},
{
"context": " no\n\n\n# /user/u@catz.net/posts → [\"/user/u@ca... | src/util.coffee | surevine/buddycloud-webclient | 1 |
exports.transEndEventNames = transEndEventNames =
'WebkitTransition' : 'webkitTransitionEnd'
'MozTransition' : 'transitionend'
'OTransition' : 'oTransitionEnd'
'msTransition' : 'MSTransitionEnd'
'transition' : 'transitionend'
exports.transitionendEvent = transEndEventNames[Modernizr.prefixed('transition')]
exports.gravatar = (mail) ->
opts = s:50, d:'retro'
hash = MD5.hexdigest mail?.toLowerCase?() or ""
"https://secure.gravatar.com/avatar/#{hash}?" + $.param(opts)
exports.EventHandler = (handler) ->
return (ev) ->
ev?.preventDefault?()
handler.apply(this, arguments)
no
# /user/u@catz.net/posts → ["/user/u@catz.net/", "u@catz.net"]
NODEID_TO_USER_REGEX = /\/user\/([^\/]+@[^\/]+)\//
exports.nodeid_to_user = (nodeid) ->
nodeid?.match?(NODEID_TO_USER_REGEX)?[1] # jid
# "/user/:jid/posts/stuff" → ["/user/:jid/posts", ":jid", "channel"]
NODEID_TO_TYPE_REGEX = /\/user\/([^\/]+)\/([^\/]+)/
exports.nodeid_to_type = (nodeid) ->
nodeid?.match?(NODEID_TO_TYPE_REGEX)?[2] # type
exports.compare_by_id = (model1, model2) ->
id1 = model1.get 'id'
id2 = model2.get 'id'
if id1 < id2
-1
else if id1 > id2
1
else
0
URLS_REGEX = ///^
(.*?) # Beginning of text
(?:
# Crazy regexp for matching URLs.
# Based on http://daringfireball.net/2010/07/improved_regex_for_matching_urls
# plus changed some '(' to '(?:'.
\b((?:[a-z][\w-]+:(?:/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\((?:[^\s()<>]+|(?:\([^\s()<>]+\)))*\))+(?:\((?:[^\s()<>]+|(?:\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))
#' <-- fix syntax highlighting...
|
# JID (or e-mail address not starting with mailto:)
\b(\S+@[a-zA-Z0-9_\-\.]+)\b
)
(.*) # End of text
$///
exports.parse_post = (content = "") ->
# Trim leading & trailing whitespace:
if content.trim?
content = content.trim()
parts = []
for line in content.split(/\n/)
while line.length > 0
if (m = line.match(URLS_REGEX, "i"))
if m[1]
parts.push
type: 'text'
value: m[1]
if m[2]
parts.push
type: 'link'
value: m[2]
if m[3]
parts.push
type: 'user'
value: m[3]
line = m[4] or ""
else
parts.push
type: 'text'
value: line
line = ""
# Restore line break
parts.push
type: 'text'
value: "\n"
return parts
##
# Delay a callback by `interval' ms, while avoiding calling it
# multiple times successively.
exports.throttle_callback = (interval, callback) ->
timeout = null
# We return a proxy callback:
() ->
that = this
args = arguments
# None yet scheduled?
unless timeout
timeout = setTimeout ->
timeout = null
callback?.apply that, args
, interval
| 195015 |
exports.transEndEventNames = transEndEventNames =
'WebkitTransition' : 'webkitTransitionEnd'
'MozTransition' : 'transitionend'
'OTransition' : 'oTransitionEnd'
'msTransition' : 'MSTransitionEnd'
'transition' : 'transitionend'
exports.transitionendEvent = transEndEventNames[Modernizr.prefixed('transition')]
exports.gravatar = (mail) ->
opts = s:50, d:'retro'
hash = MD5.hexdigest mail?.toLowerCase?() or ""
"https://secure.gravatar.com/avatar/#{hash}?" + $.param(opts)
exports.EventHandler = (handler) ->
return (ev) ->
ev?.preventDefault?()
handler.apply(this, arguments)
no
# /user/u@catz.net/posts → ["/user/<EMAIL>@<EMAIL>/", "<EMAIL>"]
NODEID_TO_USER_REGEX = /\/user\/([^\/]+@[^\/]+)\//
exports.nodeid_to_user = (nodeid) ->
nodeid?.match?(NODEID_TO_USER_REGEX)?[1] # jid
# "/user/:jid/posts/stuff" → ["/user/:jid/posts", ":jid", "channel"]
NODEID_TO_TYPE_REGEX = /\/user\/([^\/]+)\/([^\/]+)/
exports.nodeid_to_type = (nodeid) ->
nodeid?.match?(NODEID_TO_TYPE_REGEX)?[2] # type
exports.compare_by_id = (model1, model2) ->
id1 = model1.get 'id'
id2 = model2.get 'id'
if id1 < id2
-1
else if id1 > id2
1
else
0
URLS_REGEX = ///^
(.*?) # Beginning of text
(?:
# Crazy regexp for matching URLs.
# Based on http://daringfireball.net/2010/07/improved_regex_for_matching_urls
# plus changed some '(' to '(?:'.
\b((?:[a-z][\w-]+:(?:/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\((?:[^\s()<>]+|(?:\([^\s()<>]+\)))*\))+(?:\((?:[^\s()<>]+|(?:\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))
#' <-- fix syntax highlighting...
|
# JID (or e-mail address not starting with mailto:)
\b(\S+@[a-zA-Z0-9_\-\.]+)\b
)
(.*) # End of text
$///
exports.parse_post = (content = "") ->
# Trim leading & trailing whitespace:
if content.trim?
content = content.trim()
parts = []
for line in content.split(/\n/)
while line.length > 0
if (m = line.match(URLS_REGEX, "i"))
if m[1]
parts.push
type: 'text'
value: m[1]
if m[2]
parts.push
type: 'link'
value: m[2]
if m[3]
parts.push
type: 'user'
value: m[3]
line = m[4] or ""
else
parts.push
type: 'text'
value: line
line = ""
# Restore line break
parts.push
type: 'text'
value: "\n"
return parts
##
# Delay a callback by `interval' ms, while avoiding calling it
# multiple times successively.
exports.throttle_callback = (interval, callback) ->
timeout = null
# We return a proxy callback:
() ->
that = this
args = arguments
# None yet scheduled?
unless timeout
timeout = setTimeout ->
timeout = null
callback?.apply that, args
, interval
| true |
exports.transEndEventNames = transEndEventNames =
'WebkitTransition' : 'webkitTransitionEnd'
'MozTransition' : 'transitionend'
'OTransition' : 'oTransitionEnd'
'msTransition' : 'MSTransitionEnd'
'transition' : 'transitionend'
exports.transitionendEvent = transEndEventNames[Modernizr.prefixed('transition')]
exports.gravatar = (mail) ->
opts = s:50, d:'retro'
hash = MD5.hexdigest mail?.toLowerCase?() or ""
"https://secure.gravatar.com/avatar/#{hash}?" + $.param(opts)
exports.EventHandler = (handler) ->
return (ev) ->
ev?.preventDefault?()
handler.apply(this, arguments)
no
# /user/u@catz.net/posts → ["/user/PI:EMAIL:<EMAIL>END_PI@PI:EMAIL:<EMAIL>END_PI/", "PI:EMAIL:<EMAIL>END_PI"]
NODEID_TO_USER_REGEX = /\/user\/([^\/]+@[^\/]+)\//
exports.nodeid_to_user = (nodeid) ->
nodeid?.match?(NODEID_TO_USER_REGEX)?[1] # jid
# "/user/:jid/posts/stuff" → ["/user/:jid/posts", ":jid", "channel"]
NODEID_TO_TYPE_REGEX = /\/user\/([^\/]+)\/([^\/]+)/
exports.nodeid_to_type = (nodeid) ->
nodeid?.match?(NODEID_TO_TYPE_REGEX)?[2] # type
exports.compare_by_id = (model1, model2) ->
id1 = model1.get 'id'
id2 = model2.get 'id'
if id1 < id2
-1
else if id1 > id2
1
else
0
URLS_REGEX = ///^
(.*?) # Beginning of text
(?:
# Crazy regexp for matching URLs.
# Based on http://daringfireball.net/2010/07/improved_regex_for_matching_urls
# plus changed some '(' to '(?:'.
\b((?:[a-z][\w-]+:(?:/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\((?:[^\s()<>]+|(?:\([^\s()<>]+\)))*\))+(?:\((?:[^\s()<>]+|(?:\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))
#' <-- fix syntax highlighting...
|
# JID (or e-mail address not starting with mailto:)
\b(\S+@[a-zA-Z0-9_\-\.]+)\b
)
(.*) # End of text
$///
exports.parse_post = (content = "") ->
# Trim leading & trailing whitespace:
if content.trim?
content = content.trim()
parts = []
for line in content.split(/\n/)
while line.length > 0
if (m = line.match(URLS_REGEX, "i"))
if m[1]
parts.push
type: 'text'
value: m[1]
if m[2]
parts.push
type: 'link'
value: m[2]
if m[3]
parts.push
type: 'user'
value: m[3]
line = m[4] or ""
else
parts.push
type: 'text'
value: line
line = ""
# Restore line break
parts.push
type: 'text'
value: "\n"
return parts
##
# Delay a callback by `interval' ms, while avoiding calling it
# multiple times successively.
exports.throttle_callback = (interval, callback) ->
timeout = null
# We return a proxy callback:
() ->
that = this
args = arguments
# None yet scheduled?
unless timeout
timeout = setTimeout ->
timeout = null
callback?.apply that, args
, interval
|
[
{
"context": " updateWidgets('comstat', null, { author: author })\n updateWidgets('jsondump', null",
"end": 4505,
"score": 0.9955365061759949,
"start": 4499,
"tag": "NAME",
"value": "author"
},
{
"context": " updateWidgets('jsondump', null, { author: a... | ui/js/coffee/explorer.coffee | thadguidry/kibble | 0 | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF 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.
explorer = (json, state) ->
org = json.organisation
h = document.createElement('h2')
if json.tag
org.name += " (Filter: " + json.tag + ")"
h.appendChild(document.createTextNode("Exploring " + org.name + ":"))
state.widget.inject(h, true)
list = document.createElement('select')
state.widget.inject(list)
opt = document.createElement('option')
opt.value = ""
slen = 0
for item in json.sources
if item.type in ['git', 'svn', 'gerrit', 'github'] and item.noclone != true
slen++
opt.text = "All " + slen + " repositories"
list.appendChild(opt)
json.sources.sort((a,b) ->
return if (a.sourceURL == b.sourceURL) then 0 else (if a.sourceURL > b.sourceURL then 1 else -1)
)
for item in json.sources
if item.type in ['git', 'svn', 'gerrit', 'github'] and item.noclone != true
opt = document.createElement('option')
opt.value = item.sourceID
ezURL = null
m = item.sourceURL.match(/^([a-z]+:\/\/.+?)[\/?]([^\/?]+)$/i)
if m and m.length == 3
ezURL = "#{m[2]} - (#{m[1]})"
opt.text = if ezURL then ezURL else item.sourceURL
if globArgs.source and globArgs.source == item.sourceID
opt.selected = 'selected'
list.appendChild(opt)
ID = Math.floor(Math.random() * 987654321).toString(16)
list.setAttribute('id', ID)
$("#"+ID).chosen().change(() ->
source = this.value
if source == ""
source = null
globArgs.source = source
updateWidgets('donut', null, { source: source })
updateWidgets('gauge', null, { source: source })
updateWidgets('line', null, { source: source })
updateWidgets('phonebook', null, { source: source })
updateWidgets('top5', null, { source: source })
updateWidgets('factors', null, { source: source })
updateWidgets('trends', null, { source: source })
updateWidgets('mvp', null, { source: source })
updateWidgets('comstat', null, { source: source })
updateWidgets('jsondump', null, { source: source })
)
# Unique commits label
id = Math.floor(Math.random() * 987654321).toString(16)
chk = document.createElement('input')
chk.setAttribute("type", "checkbox")
chk.setAttribute("id", id)
chk.style.marginLeft = '10px'
if globArgs.author and globArgs.author == 'true'
chk.checked = true
chk.addEventListener("change", () ->
unique = null
if this.checked
author = 'true'
globArgs['author'] = 'true'
updateWidgets('donut', null, { author: author })
updateWidgets('gauge', null, { author: author })
updateWidgets('line', null, { author: author })
updateWidgets('phonebook', null, { author: author })
updateWidgets('top5', null, { author: author })
updateWidgets('factors', null, { author: author })
updateWidgets('trends', null, { author: author })
updateWidgets('relationship', null, {author: author})
updateWidgets('mvp', null, {author: author})
updateWidgets('comstat', null, { author: author })
updateWidgets('jsondump', null, { author: author })
)
state.widget.inject(chk)
label = document.createElement('label')
label.setAttribute("for", id)
label.setAttribute("title", "Check this box to authorships instead of committerships")
chk.setAttribute("title", "Check this box to authorships instead of committerships")
label.style.paddingLeft = '5px'
label.appendChild(document.createTextNode('Show authors'))
state.widget.inject(label)
br = new HTML('br')
p = new HTML('input', {id:'pathfilter', size: 32, type: 'text', value: globArgs.pathfilter, onChange: 'pathFilterGlob = this.value;',placeholder: 'optional path-filter'})
state.widget.inject(br)
state.widget.inject(p)
b = new HTML('input', {style: { marginLeft: '10px'}, class: 'btn btn-small btn-success', type: 'button', onClick: 'pathFilter();', value: "filter paths"})
rb = new HTML('input', {style: { marginLeft: '10px'}, class: 'btn btn-small btn-danger', type: 'button', onClick: 'get("pathfilter").value = ""; pathFilterGlob = ""; pathFilter();', value: "reset"})
state.widget.inject(b)
state.widget.inject(rb)
sourceexplorer = (json, state) ->
org = json.organisation
h = document.createElement('h4')
if json.tag
org.name += " (Filter: " + json.tag + ")"
h.appendChild(document.createTextNode("Exploring " + org.name + ":"))
state.widget.inject(h, true)
div = new HTML('div', {class: "form-group"})
list = new HTML('select', { class: "form-control"})
div.inject(list)
state.widget.inject(div)
opt = document.createElement('option')
opt.value = ""
slen = 0
for item in json.sources
slen++
opt.text = "All " + slen + " sources"
list.appendChild(opt)
json.sources.sort((a,b) ->
return if (a.sourceURL == b.sourceURL) then 0 else (if a.sourceURL > b.sourceURL then 1 else -1)
)
for item in json.sources
if true
opt = document.createElement('option')
opt.value = item.sourceID
ezURL = null
m = item.sourceURL.match(/^([a-z]+:\/\/.+?)[\/?]([^\/?]+)$/i)
if m and m.length == 3
ezURL = "#{m[2]} - (#{m[1]})"
opt.text = if ezURL then ezURL else item.sourceURL
if globArgs.source and globArgs.source == item.sourceID
opt.selected = 'selected'
list.appendChild(opt)
ID = Math.floor(Math.random() * 987654321).toString(16)
list.setAttribute('id', ID)
$("#"+ID).chosen().change(() ->
source = this.value
if source == ""
source = null
globArgs.source = source
updateWidgets('donut', null, { source: source })
updateWidgets('gauge', null, { source: source })
updateWidgets('line', null, { source: source })
updateWidgets('phonebook', null, { source: source })
updateWidgets('top5', null, { source: source })
updateWidgets('factors', null, { source: source })
updateWidgets('trends', null, { source: source })
updateWidgets('mvp', null, { source: source })
updateWidgets('comstat', null, { source: source })
updateWidgets('jsondump', null, { source: source })
)
mailexplorer = (json, state) ->
org = json.organisation
h = document.createElement('h4')
if json.tag
org.name += " (Filter: " + json.tag + ")"
h.appendChild(document.createTextNode("Exploring " + org.name + ":"))
state.widget.inject(h, true)
list = document.createElement('select')
state.widget.inject(list)
opt = document.createElement('option')
opt.value = ""
slen = 0
for item in json.sources
if item.type in ['mail', 'ponymail', 'pipermail', 'hyperkitty']
slen++
opt.text = "All " + slen + " mailing lists"
list.appendChild(opt)
json.sources.sort((a,b) ->
return if (a.sourceURL == b.sourceURL) then 0 else (if a.sourceURL > b.sourceURL then 1 else -1)
)
for item in json.sources
if item.type in ['mail', 'ponymail', 'pipermail', 'hyperkitty']
opt = document.createElement('option')
opt.value = item.sourceID
ezURL = null
m = item.sourceURL.match(/^([a-z]+:\/\/.+?)[\/?]([^\/?]+)$/i)
if m and m.length == 3
ezURL = "#{m[2]} - (#{m[1]})"
opt.text = if ezURL then ezURL else item.sourceURL
if globArgs.source and globArgs.source == item.sourceID
opt.selected = 'selected'
list.appendChild(opt)
ID = Math.floor(Math.random() * 987654321).toString(16)
list.setAttribute('id', ID)
$("#"+ID).chosen().change(() ->
source = this.value
if source == ""
source = null
globArgs.source = source
updateWidgets('donut', null, { source: source })
updateWidgets('gauge', null, { source: source })
updateWidgets('line', null, { source: source })
updateWidgets('phonebook', null, { source: source })
updateWidgets('top5', null, { source: source })
updateWidgets('factors', null, { source: source })
updateWidgets('trends', null, { source: source })
updateWidgets('relationship', null, { source: source })
)
logexplorer = (json, state) ->
org = json.organisation
h = document.createElement('h4')
if json.tag
org.name += " (Filter: " + json.tag + ")"
h.appendChild(document.createTextNode("Exploring " + org.name + ":"))
state.widget.inject(h, true)
list = document.createElement('select')
state.widget.inject(list)
opt = document.createElement('option')
opt.value = ""
slen = 0
for item in json.sources
if item.type == 'stats'
slen++
opt.text = "All " + slen + " log files"
list.appendChild(opt)
json.sources.sort((a,b) ->
return if (a.sourceURL == b.sourceURL) then 0 else (if a.sourceURL > b.sourceURL then 1 else -1)
)
for item in json.sources
if item.type == 'stats'
opt = document.createElement('option')
opt.value = item.sourceID
ezURL = null
m = item.sourceURL.match(/^([a-z]+:\/\/.+?)[\/?]([^\/?]+)$/i)
if m and m.length == 3
ezURL = "#{m[2]} - (#{m[1]})"
opt.text = if ezURL then ezURL else item.sourceURL
if globArgs.source and globArgs.source == item.sourceID
opt.selected = 'selected'
list.appendChild(opt)
ID = Math.floor(Math.random() * 987654321).toString(16)
list.setAttribute('id', ID)
$("#"+ID).chosen().change(() ->
source = this.value
if source == ""
source = null
globArgs.source = source
updateWidgets('donut', null, { source: source })
updateWidgets('gauge', null, { source: source })
updateWidgets('line', null, { source: source })
updateWidgets('worldmap', null, { source: source })
updateWidgets('top5', null, { source: source })
updateWidgets('factors', null, { source: source })
updateWidgets('trends', null, { source: source })
)
issueexplorer = (json, state) ->
org = json.organisation
if json.tag
org.name += " (Filter: " + json.tag + ")"
h = document.createElement('h4')
h.appendChild(document.createTextNode("Exploring " + org.name + ":"))
state.widget.inject(h, true)
list = document.createElement('select')
state.widget.inject(list)
opt = document.createElement('option')
opt.value = ""
slen = 0
for item in json.sources
if item.type in ['jira', 'gerrit', 'github', 'bugzilla']
slen++
opt.text = "All " + slen + " issue tracker(s)"
list.appendChild(opt)
json.sources.sort((a,b) ->
return if (a.sourceURL == b.sourceURL) then 0 else (if a.sourceURL > b.sourceURL then 1 else -1)
)
for item in json.sources
if item.type in ['jira', 'gerrit', 'github', 'bugzilla']
opt = document.createElement('option')
opt.value = item.sourceID
ezURL = null
n = item.sourceURL.match(/^([a-z]+:\/\/.+?)\/([-.A-Z0-9]+)$/i)
m = item.sourceURL.match(/^([a-z]+:\/\/.+?)\s(.+)$/i)
if n and n.length == 3
ezURL = "#{n[2]} - (#{n[1]})"
else if m and m.length == 3
ezURL = "#{m[2]} - (#{m[1]})"
opt.text = if ezURL then ezURL else item.sourceURL
if globArgs.source and globArgs.source == item.sourceID
opt.selected = 'selected'
list.appendChild(opt)
ID = Math.floor(Math.random() * 987654321).toString(16)
list.setAttribute('id', ID)
$("#"+ID).chosen().change(() ->
source = this.value
if source == ""
source = null
globArgs.source = source
updateWidgets('donut', null, { source: source })
updateWidgets('gauge', null, { source: source })
updateWidgets('line', null, { source: source })
updateWidgets('phonebook', null, { source: source })
updateWidgets('top5', null, { source: source })
updateWidgets('factors', null, { source: source })
updateWidgets('trends', null, { source: source })
)
forumexplorer = (json, state) ->
org = json.organisation
if json.tag
org.name += " (Filter: " + json.tag + ")"
h = document.createElement('h4')
h.appendChild(document.createTextNode("Exploring " + org.name + ":"))
state.widget.inject(h, true)
list = document.createElement('select')
state.widget.inject(list)
opt = document.createElement('option')
opt.value = ""
slen = 0
for item in json.sources
if item.type in ['forum', 'discourse', 'askbot']
slen++
opt.text = "All " + slen + " forum(s)"
list.appendChild(opt)
json.sources.sort((a,b) ->
return if (a.sourceURL == b.sourceURL) then 0 else (if a.sourceURL > b.sourceURL then 1 else -1)
)
for item in json.sources
if item.type in ['forum', 'discourse', 'askbot']
opt = document.createElement('option')
opt.value = item.sourceID
ezURL = null
n = item.sourceURL.match(/^([a-z]+:\/\/.+?)\/([-.A-Z0-9]+)$/i)
m = item.sourceURL.match(/^([a-z]+:\/\/.+?)\s(.+)$/i)
if n and n.length == 3
ezURL = "#{n[2]} - (#{n[1]})"
else if m and m.length == 3
ezURL = "#{m[2]} - (#{m[1]})"
opt.text = if ezURL then ezURL else item.sourceURL
if globArgs.source and globArgs.source == item.sourceID
opt.selected = 'selected'
list.appendChild(opt)
ID = Math.floor(Math.random() * 987654321).toString(16)
list.setAttribute('id', ID)
$("#"+ID).chosen().change(() ->
source = this.value
if source == ""
source = null
globArgs.source = source
updateWidgets('donut', null, { source: source })
updateWidgets('gauge', null, { source: source })
updateWidgets('line', null, { source: source })
updateWidgets('phonebook', null, { source: source })
updateWidgets('top5', null, { source: source })
updateWidgets('factors', null, { source: source })
updateWidgets('trends', null, { source: source })
)
imexplorer = (json, state) ->
org = json.organisation
if json.tag
org.name += " (Filter: " + json.tag + ")"
h = document.createElement('h4')
h.appendChild(document.createTextNode("Exploring " + org.name + ":"))
state.widget.inject(h, true)
list = document.createElement('select')
state.widget.inject(list)
opt = document.createElement('option')
opt.value = ""
slen = 0
for item in json.sources
if item.type in ['irc','gitter']
slen++
opt.text = "All " + slen + " messaging sources"
list.appendChild(opt)
json.sources.sort((a,b) ->
return if (a.sourceURL == b.sourceURL) then 0 else (if a.sourceURL > b.sourceURL then 1 else -1)
)
for item in json.sources
if item.type in ['irc', 'gitter']
opt = document.createElement('option')
opt.value = item.sourceID
ezURL = null
n = item.sourceURL.match(/^([a-z]+:\/\/.+?)\/([#\S+]+)$/i)
m = item.sourceURL.match(/^([a-z]+:\/\/.+?)\s(.+)$/i)
if n and n.length == 3
ezURL = "#{n[2]} - (#{n[1]})"
else if m and m.length == 3
ezURL = "#{m[2]} - (#{m[1]})"
opt.text = if ezURL then ezURL else item.sourceURL
if globArgs.source and globArgs.source == item.sourceID
opt.selected = 'selected'
list.appendChild(opt)
ID = Math.floor(Math.random() * 987654321).toString(16)
list.setAttribute('id', ID)
$("#"+ID).chosen().change(() ->
source = this.value
if source == ""
source = null
globArgs.source = source
updateWidgets('donut', null, { source: source })
updateWidgets('gauge', null, { source: source })
updateWidgets('line', null, { source: source })
updateWidgets('phonebook', null, { source: source })
updateWidgets('top5', null, { source: source })
updateWidgets('factors', null, { source: source })
updateWidgets('trends', null, { source: source })
, false)
$('select').chosen();
ciexplorer = (json, state) ->
org = json.organisation
if json.tag
org.name += " (Filter: " + json.tag + ")"
h = document.createElement('h4')
h.appendChild(document.createTextNode("Exploring " + org.name + ":"))
state.widget.inject(h, true)
list = document.createElement('select')
state.widget.inject(list)
opt = document.createElement('option')
opt.value = ""
slen = 0
for item in json.sources
if item.type in ['jenkins','travis','buildbot']
slen++
opt.text = "All " + slen + " CI Services"
list.appendChild(opt)
json.sources.sort((a,b) ->
return if (a.sourceURL == b.sourceURL) then 0 else (if a.sourceURL > b.sourceURL then 1 else -1)
)
for item in json.sources
if item.type in ['jenkins','travis','buildbot']
opt = document.createElement('option')
opt.value = item.sourceID
ezURL = null
n = item.sourceURL.match(/^([a-z]+:\/\/.+?)\/([#\S+]+)$/i)
m = item.sourceURL.match(/^([a-z]+:\/\/.+?)\s(.+)$/i)
if n and n.length == 3
ezURL = "#{n[2]} - (#{n[1]})"
else if m and m.length == 3
ezURL = "#{m[2]} - (#{m[1]})"
opt.text = if ezURL then ezURL else item.sourceURL
if globArgs.source and globArgs.source == item.sourceID
opt.selected = 'selected'
list.appendChild(opt)
ID = Math.floor(Math.random() * 987654321).toString(16)
list.setAttribute('id', ID)
$("#"+ID).chosen().change(() ->
source = this.value
if source == ""
source = null
globArgs.source = source
updateWidgets('donut', null, { source: source })
updateWidgets('gauge', null, { source: source })
updateWidgets('line', null, { source: source })
updateWidgets('phonebook', null, { source: source })
updateWidgets('top5', null, { source: source })
updateWidgets('factors', null, { source: source })
updateWidgets('trends', null, { source: source })
updateWidgets('relationship', null, { source: source })
)
multiviewexplorer = (json, state) ->
org = json.organisation
h = document.createElement('h4')
h.appendChild(document.createTextNode("Select views to compare:"))
state.widget.inject(h, true)
for k in [1..3]
tName = 'tag'+k
list = document.createElement('select')
list.setAttribute("data", tName)
state.widget.inject(list)
opt = document.createElement('option')
opt.value = ""
opt.text = "(None)"
list.appendChild(opt)
opt = document.createElement('option')
opt.value = "---"
opt.text = "Entire organisation"
if globArgs[tName] and globArgs[tName] == '---'
opt.selected = 'selected'
list.appendChild(opt)
if isArray(json.views)
json.views.sort((a,b) ->
return if (a.name == b.name) then 0 else (if a.name > b.name then 1 else -1)
)
for item in json.views
opt = document.createElement('option')
opt.value = item.id
opt.text = item.name
if globArgs[tName] and globArgs[tName] == item.id
opt.selected = 'selected'
list.appendChild(opt)
ID = Math.floor(Math.random() * 987654321).toString(16)
list.setAttribute('id', ID)
$("#"+ID).chosen().change(() ->
source = this.value
if source == ""
source = null
tName = this.getAttribute("data")
globArgs[tName] = source
x = {}
x[tName] = source
updateWidgets('donut', null, x)
updateWidgets('gauge', null, x)
updateWidgets('line', null, x)
updateWidgets('phonebook', null, x)
updateWidgets('top5', null, x)
updateWidgets('factors', null, x)
updateWidgets('trends', null, x)
updateWidgets('radar', null, x)
)
subFilterGlob = null
subFilter = () ->
source = subFilterGlob
if source == ""
source = null
tName = 'subfilter'
globArgs[tName] = source
x = {}
x[tName] = source
updateWidgets('sourcepicker', null, x)
updateWidgets('repopicker', null, x)
updateWidgets('issuepicker', null, x)
updateWidgets('forumpicker', null, x)
updateWidgets('mailpicker', null, x)
updateWidgets('logpicker', null, x)
updateWidgets('donut', null, x)
updateWidgets('gauge', null, x)
updateWidgets('line', null, x)
updateWidgets('phonebook', null, x)
updateWidgets('top5', null, x)
updateWidgets('factors', null, x)
updateWidgets('trends', null, x)
updateWidgets('radar', null, x)
updateWidgets('widget', null, x)
updateWidgets('relationship', null, x)
updateWidgets('treemap', null, x)
updateWidgets('report', null, x)
updateWidgets('mvp', null, x)
updateWidgets('comstat', null, x)
updateWidgets('worldmap', null, x)
updateWidgets('jsondump', null, x)
$( "a" ).each( () ->
url = $(this).attr('href')
if url
m = url.match(/^(.+\?page=[-a-z]+.*?)(?:&subfilter=[^&]+)?(.*)$/)
if m
if source
$(this).attr('href', "#{m[1]}&subfilter=#{source}#{m[2]}")
else
$(this).attr('href', "#{m[1]}#{m[2]}")
)
pathFilterGlob = null
pathFilter = () ->
source = pathFilterGlob
if source == ""
source = null
tName = 'pathfilter'
globArgs[tName] = source
x = {}
x[tName] = source
updateWidgets('donut', null, x)
updateWidgets('gauge', null, x)
updateWidgets('line', null, x)
updateWidgets('phonebook', null, x)
updateWidgets('top5', null, x)
updateWidgets('factors', null, x)
updateWidgets('trends', null, x)
updateWidgets('radar', null, x)
updateWidgets('widget', null, x)
updateWidgets('relationship', null, x)
updateWidgets('treemap', null, x)
updateWidgets('report', null, x)
updateWidgets('mvp', null, x)
updateWidgets('comstat', null, x)
updateWidgets('worldmap', null, x)
updateWidgets('jsondump', null, x)
$( "a" ).each( () ->
url = $(this).attr('href')
if url
m = url.match(/^(.+\?page=[-a-z]+.*?)(?:&pathfilter=[^&]+)?(.*)$/)
if m
if source
$(this).attr('href', "#{m[1]}&pathfilter=#{source}#{m[2]}")
else
$(this).attr('href', "#{m[1]}#{m[2]}")
)
viewexplorer = (json, state) ->
org = json.organisation
h = document.createElement('h4')
h.appendChild(document.createTextNode("Select a view to use:"))
state.widget.inject(h, true)
tName = 'view'
list = document.createElement('select')
list.setAttribute("data", tName)
state.widget.inject(list)
opt = document.createElement('option')
opt.value = ""
opt.text = "(None)"
list.appendChild(opt)
opt = document.createElement('option')
opt.value = "---"
opt.text = "Entire organisation"
if globArgs[tName] and globArgs[tName] == '---'
opt.selected = 'selected'
list.appendChild(opt)
if isArray(json.views)
json.views.sort((a,b) ->
return if (a.name == b.name) then 0 else (if a.name > b.name then 1 else -1)
)
for item in json.views
opt = document.createElement('option')
opt.value = item.id
opt.text = item.name
if globArgs[tName] and globArgs[tName] == item.id
opt.selected = 'selected'
list.appendChild(opt)
ID = Math.floor(Math.random() * 987654321).toString(16)
list.setAttribute('id', ID)
$("#"+ID).chosen().change(() ->
source = this.value
if source == ""
source = null
tName = this.getAttribute("data")
globArgs[tName] = source
x = {}
x[tName] = source
updateWidgets('sourcepicker', null, x)
updateWidgets('repopicker', null, x)
updateWidgets('issuepicker', null, x)
updateWidgets('mailpicker', null, x)
updateWidgets('logpicker', null, x)
updateWidgets('donut', null, x)
updateWidgets('gauge', null, x)
updateWidgets('line', null, x)
updateWidgets('phonebook', null, x)
updateWidgets('top5', null, x)
updateWidgets('factors', null, x)
updateWidgets('trends', null, x)
updateWidgets('radar', null, x)
updateWidgets('widget', null, x)
updateWidgets('relationship', null, x)
updateWidgets('treemap', null, x)
updateWidgets('report', null, x)
updateWidgets('mvp', null, x)
updateWidgets('comstat', null, x)
updateWidgets('worldmap', null, x)
updateWidgets('jsondump', null, x)
$( "a" ).each( () ->
url = $(this).attr('href')
if url
m = url.match(/^(.+\?page=[-a-z]+)(?:&view=[a-f0-9]+)?(.*)$/)
if m
if source
$(this).attr('href', "#{m[1]}&view=#{source}#{m[2]}")
else
$(this).attr('href', "#{m[1]}#{m[2]}")
)
)
# Quick filter
state.widget.inject(new HTML('br'))
i = new HTML('input', {id:'subfilter', size: 16, type: 'text', value: globArgs.subfilter, onChange: 'subFilterGlob = this.value;', placeholder: 'sub-filter'})
b = new HTML('input', {style: { marginLeft: '10px'}, class: 'btn btn-small btn-success', type: 'button', onClick: 'subFilter();', value: "sub-filter"})
rb = new HTML('input', {style: { marginLeft: '10px'}, class: 'btn btn-small btn-danger', type: 'button', onClick: 'get("subfilter").value=""; subFilterGlob=""; subFilter();', value: "reset"})
state.widget.inject(i)
state.widget.inject(b)
state.widget.inject(rb)
if globArgs.subfilter and globArgs.subfilter.length > 0
source = globArgs.subfilter
$( "a" ).each( () ->
url = $(this).attr('href')
if url
m = url.match(/^(.+\?page=[-a-z]+.*?)(?:&subfilter=[a-f0-9]+)?(.*)$/)
if m
if source
$(this).attr('href', "#{m[1]}&subfilter=#{source}#{m[2]}")
else
$(this).attr('href', "#{m[1]}#{m[2]}")
)
if globArgs.email
div = new HTML('div', {}, "Currently filtering results based on " + globArgs.email + ". - ")
div.inject(new HTML('a', { href: 'javascript:void(filterPerson(null));'}, "Reset filter"))
state.widget.inject(div)
widgetexplorer = (json, state) ->
pwidgets = {
'languages': 'Code: Language breakdown',
'commit-history-year': "Code: Commit history (past year)"
'commit-history-all': "Code: Commit history (all time)"
'commit-top5-year': "Code: top 5 committers (past year)"
'commit-top5-all': "Code: top 5 committers (all time)"
'committer-count-year': "Code: Committers/Authors per month (past year)"
'committer-count-all': "Code: Committers/Authors per month (all time)"
'commit-lines-year': "Code: Lines changed (past year)"
'commit-lines-all': "Code: Lines changed (all time)"
'sloc-map': "Code: Language Treemap"
'repo-size-year': "Repos: top 15 by lines of code"
'repo-commits-year': "Repos: top 15 by number of commits (past year)"
'repo-commits-all': "Repos: top 15 by number of commits (all time)"
'evolution': "Code: Code evolution (all time)"
'evolution-extended': "Code: Code evolution (individual languages, all time)"
'issue-count-year': "Issues: Tickets opened/closed (past year)"
'issue-count-all': "Issues: Tickets opened/closed (all time)"
'issue-operators-year': "Issues: Ticket creators/closers (past year)"
'issue-operators-all': "Issues: Ticket creators/closers (all time)"
'issue-queue-all': "Issue queue size by ticket age"
'email-count-year': "Mail: Emails/threads/authors (past year)"
'email-count-all': "Mail: Emails/threads/authors (all time)"
'im-stats-year': "Online messaging activity (past year)",
'im-stats-all': "Online messaging activity (all time)",
'compare-commits-year': "Commits by Affiliation (past year)",
'compare-commits-all': "Commits by Affiliation (all time)"
'repo-relationship-year': "Repository relationships (past year)"
'repo-relationship-2year': "Repository relationships (past two years)"
'issue-relationship-year': "Issue tracker relationships (past year)"
'issue-relationship-2year': "Issue tracker relationships (past two years)"
'log-stats-year': "Downloads/Visits (past year)"
'log-stats-all': "Downloads/Visits (all time)"
'log-map-month': "Downloads/Visits per country (past month)"
'log-map-year': "Downloads/Visits per country (past year)"
'log-map-all': "Downloads/Visits per country (all time)"
}
org = json.organisation
h = document.createElement('h4')
h.appendChild(document.createTextNode("Select a widget to use:"))
state.widget.inject(h, true)
tName = 'widget'
list = document.createElement('select')
list.setAttribute("data", tName)
state.widget.inject(list)
opt = document.createElement('option')
opt.value = ""
opt.text = "Select a widget type:"
list.appendChild(opt)
for key, value of pwidgets
opt = document.createElement('option')
opt.value = key
opt.text = value
if globArgs[tName] and globArgs[tName] == key
opt.selected = 'selected'
list.appendChild(opt)
list.addEventListener("change", () ->
source = this.value
if source == ""
source = null
tName = this.getAttribute("data")
globArgs[tName] = source
x = {}
x[tName] = source
updateWidgets('widget', null, x)
updateWidgets('donut', null, x)
updateWidgets('gauge', null, x)
updateWidgets('line', null, x)
updateWidgets('phonebook', null, x)
updateWidgets('top5', null, x)
updateWidgets('factors', null, x)
updateWidgets('trends', null, x)
updateWidgets('radar', null, x)
, false)
| 180031 | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF 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.
explorer = (json, state) ->
org = json.organisation
h = document.createElement('h2')
if json.tag
org.name += " (Filter: " + json.tag + ")"
h.appendChild(document.createTextNode("Exploring " + org.name + ":"))
state.widget.inject(h, true)
list = document.createElement('select')
state.widget.inject(list)
opt = document.createElement('option')
opt.value = ""
slen = 0
for item in json.sources
if item.type in ['git', 'svn', 'gerrit', 'github'] and item.noclone != true
slen++
opt.text = "All " + slen + " repositories"
list.appendChild(opt)
json.sources.sort((a,b) ->
return if (a.sourceURL == b.sourceURL) then 0 else (if a.sourceURL > b.sourceURL then 1 else -1)
)
for item in json.sources
if item.type in ['git', 'svn', 'gerrit', 'github'] and item.noclone != true
opt = document.createElement('option')
opt.value = item.sourceID
ezURL = null
m = item.sourceURL.match(/^([a-z]+:\/\/.+?)[\/?]([^\/?]+)$/i)
if m and m.length == 3
ezURL = "#{m[2]} - (#{m[1]})"
opt.text = if ezURL then ezURL else item.sourceURL
if globArgs.source and globArgs.source == item.sourceID
opt.selected = 'selected'
list.appendChild(opt)
ID = Math.floor(Math.random() * 987654321).toString(16)
list.setAttribute('id', ID)
$("#"+ID).chosen().change(() ->
source = this.value
if source == ""
source = null
globArgs.source = source
updateWidgets('donut', null, { source: source })
updateWidgets('gauge', null, { source: source })
updateWidgets('line', null, { source: source })
updateWidgets('phonebook', null, { source: source })
updateWidgets('top5', null, { source: source })
updateWidgets('factors', null, { source: source })
updateWidgets('trends', null, { source: source })
updateWidgets('mvp', null, { source: source })
updateWidgets('comstat', null, { source: source })
updateWidgets('jsondump', null, { source: source })
)
# Unique commits label
id = Math.floor(Math.random() * 987654321).toString(16)
chk = document.createElement('input')
chk.setAttribute("type", "checkbox")
chk.setAttribute("id", id)
chk.style.marginLeft = '10px'
if globArgs.author and globArgs.author == 'true'
chk.checked = true
chk.addEventListener("change", () ->
unique = null
if this.checked
author = 'true'
globArgs['author'] = 'true'
updateWidgets('donut', null, { author: author })
updateWidgets('gauge', null, { author: author })
updateWidgets('line', null, { author: author })
updateWidgets('phonebook', null, { author: author })
updateWidgets('top5', null, { author: author })
updateWidgets('factors', null, { author: author })
updateWidgets('trends', null, { author: author })
updateWidgets('relationship', null, {author: author})
updateWidgets('mvp', null, {author: author})
updateWidgets('comstat', null, { author: <NAME> })
updateWidgets('jsondump', null, { author: <NAME> })
)
state.widget.inject(chk)
label = document.createElement('label')
label.setAttribute("for", id)
label.setAttribute("title", "Check this box to authorships instead of committerships")
chk.setAttribute("title", "Check this box to authorships instead of committerships")
label.style.paddingLeft = '5px'
label.appendChild(document.createTextNode('Show authors'))
state.widget.inject(label)
br = new HTML('br')
p = new HTML('input', {id:'pathfilter', size: 32, type: 'text', value: globArgs.pathfilter, onChange: 'pathFilterGlob = this.value;',placeholder: 'optional path-filter'})
state.widget.inject(br)
state.widget.inject(p)
b = new HTML('input', {style: { marginLeft: '10px'}, class: 'btn btn-small btn-success', type: 'button', onClick: 'pathFilter();', value: "filter paths"})
rb = new HTML('input', {style: { marginLeft: '10px'}, class: 'btn btn-small btn-danger', type: 'button', onClick: 'get("pathfilter").value = ""; pathFilterGlob = ""; pathFilter();', value: "reset"})
state.widget.inject(b)
state.widget.inject(rb)
sourceexplorer = (json, state) ->
org = json.organisation
h = document.createElement('h4')
if json.tag
org.name += " (Filter: " + json.tag + ")"
h.appendChild(document.createTextNode("Exploring " + org.name + ":"))
state.widget.inject(h, true)
div = new HTML('div', {class: "form-group"})
list = new HTML('select', { class: "form-control"})
div.inject(list)
state.widget.inject(div)
opt = document.createElement('option')
opt.value = ""
slen = 0
for item in json.sources
slen++
opt.text = "All " + slen + " sources"
list.appendChild(opt)
json.sources.sort((a,b) ->
return if (a.sourceURL == b.sourceURL) then 0 else (if a.sourceURL > b.sourceURL then 1 else -1)
)
for item in json.sources
if true
opt = document.createElement('option')
opt.value = item.sourceID
ezURL = null
m = item.sourceURL.match(/^([a-z]+:\/\/.+?)[\/?]([^\/?]+)$/i)
if m and m.length == 3
ezURL = "#{m[2]} - (#{m[1]})"
opt.text = if ezURL then ezURL else item.sourceURL
if globArgs.source and globArgs.source == item.sourceID
opt.selected = 'selected'
list.appendChild(opt)
ID = Math.floor(Math.random() * 987654321).toString(16)
list.setAttribute('id', ID)
$("#"+ID).chosen().change(() ->
source = this.value
if source == ""
source = null
globArgs.source = source
updateWidgets('donut', null, { source: source })
updateWidgets('gauge', null, { source: source })
updateWidgets('line', null, { source: source })
updateWidgets('phonebook', null, { source: source })
updateWidgets('top5', null, { source: source })
updateWidgets('factors', null, { source: source })
updateWidgets('trends', null, { source: source })
updateWidgets('mvp', null, { source: source })
updateWidgets('comstat', null, { source: source })
updateWidgets('jsondump', null, { source: source })
)
mailexplorer = (json, state) ->
org = json.organisation
h = document.createElement('h4')
if json.tag
org.name += " (Filter: " + json.tag + ")"
h.appendChild(document.createTextNode("Exploring " + org.name + ":"))
state.widget.inject(h, true)
list = document.createElement('select')
state.widget.inject(list)
opt = document.createElement('option')
opt.value = ""
slen = 0
for item in json.sources
if item.type in ['mail', 'ponymail', 'pipermail', 'hyperkitty']
slen++
opt.text = "All " + slen + " mailing lists"
list.appendChild(opt)
json.sources.sort((a,b) ->
return if (a.sourceURL == b.sourceURL) then 0 else (if a.sourceURL > b.sourceURL then 1 else -1)
)
for item in json.sources
if item.type in ['mail', 'ponymail', 'pipermail', 'hyperkitty']
opt = document.createElement('option')
opt.value = item.sourceID
ezURL = null
m = item.sourceURL.match(/^([a-z]+:\/\/.+?)[\/?]([^\/?]+)$/i)
if m and m.length == 3
ezURL = "#{m[2]} - (#{m[1]})"
opt.text = if ezURL then ezURL else item.sourceURL
if globArgs.source and globArgs.source == item.sourceID
opt.selected = 'selected'
list.appendChild(opt)
ID = Math.floor(Math.random() * 987654321).toString(16)
list.setAttribute('id', ID)
$("#"+ID).chosen().change(() ->
source = this.value
if source == ""
source = null
globArgs.source = source
updateWidgets('donut', null, { source: source })
updateWidgets('gauge', null, { source: source })
updateWidgets('line', null, { source: source })
updateWidgets('phonebook', null, { source: source })
updateWidgets('top5', null, { source: source })
updateWidgets('factors', null, { source: source })
updateWidgets('trends', null, { source: source })
updateWidgets('relationship', null, { source: source })
)
logexplorer = (json, state) ->
org = json.organisation
h = document.createElement('h4')
if json.tag
org.name += " (Filter: " + json.tag + ")"
h.appendChild(document.createTextNode("Exploring " + org.name + ":"))
state.widget.inject(h, true)
list = document.createElement('select')
state.widget.inject(list)
opt = document.createElement('option')
opt.value = ""
slen = 0
for item in json.sources
if item.type == 'stats'
slen++
opt.text = "All " + slen + " log files"
list.appendChild(opt)
json.sources.sort((a,b) ->
return if (a.sourceURL == b.sourceURL) then 0 else (if a.sourceURL > b.sourceURL then 1 else -1)
)
for item in json.sources
if item.type == 'stats'
opt = document.createElement('option')
opt.value = item.sourceID
ezURL = null
m = item.sourceURL.match(/^([a-z]+:\/\/.+?)[\/?]([^\/?]+)$/i)
if m and m.length == 3
ezURL = "#{m[2]} - (#{m[1]})"
opt.text = if ezURL then ezURL else item.sourceURL
if globArgs.source and globArgs.source == item.sourceID
opt.selected = 'selected'
list.appendChild(opt)
ID = Math.floor(Math.random() * 987654321).toString(16)
list.setAttribute('id', ID)
$("#"+ID).chosen().change(() ->
source = this.value
if source == ""
source = null
globArgs.source = source
updateWidgets('donut', null, { source: source })
updateWidgets('gauge', null, { source: source })
updateWidgets('line', null, { source: source })
updateWidgets('worldmap', null, { source: source })
updateWidgets('top5', null, { source: source })
updateWidgets('factors', null, { source: source })
updateWidgets('trends', null, { source: source })
)
issueexplorer = (json, state) ->
org = json.organisation
if json.tag
org.name += " (Filter: " + json.tag + ")"
h = document.createElement('h4')
h.appendChild(document.createTextNode("Exploring " + org.name + ":"))
state.widget.inject(h, true)
list = document.createElement('select')
state.widget.inject(list)
opt = document.createElement('option')
opt.value = ""
slen = 0
for item in json.sources
if item.type in ['jira', 'gerrit', 'github', 'bugzilla']
slen++
opt.text = "All " + slen + " issue tracker(s)"
list.appendChild(opt)
json.sources.sort((a,b) ->
return if (a.sourceURL == b.sourceURL) then 0 else (if a.sourceURL > b.sourceURL then 1 else -1)
)
for item in json.sources
if item.type in ['jira', 'gerrit', 'github', 'bugzilla']
opt = document.createElement('option')
opt.value = item.sourceID
ezURL = null
n = item.sourceURL.match(/^([a-z]+:\/\/.+?)\/([-.A-Z0-9]+)$/i)
m = item.sourceURL.match(/^([a-z]+:\/\/.+?)\s(.+)$/i)
if n and n.length == 3
ezURL = "#{n[2]} - (#{n[1]})"
else if m and m.length == 3
ezURL = "#{m[2]} - (#{m[1]})"
opt.text = if ezURL then ezURL else item.sourceURL
if globArgs.source and globArgs.source == item.sourceID
opt.selected = 'selected'
list.appendChild(opt)
ID = Math.floor(Math.random() * 987654321).toString(16)
list.setAttribute('id', ID)
$("#"+ID).chosen().change(() ->
source = this.value
if source == ""
source = null
globArgs.source = source
updateWidgets('donut', null, { source: source })
updateWidgets('gauge', null, { source: source })
updateWidgets('line', null, { source: source })
updateWidgets('phonebook', null, { source: source })
updateWidgets('top5', null, { source: source })
updateWidgets('factors', null, { source: source })
updateWidgets('trends', null, { source: source })
)
forumexplorer = (json, state) ->
org = json.organisation
if json.tag
org.name += " (Filter: " + json.tag + ")"
h = document.createElement('h4')
h.appendChild(document.createTextNode("Exploring " + org.name + ":"))
state.widget.inject(h, true)
list = document.createElement('select')
state.widget.inject(list)
opt = document.createElement('option')
opt.value = ""
slen = 0
for item in json.sources
if item.type in ['forum', 'discourse', 'askbot']
slen++
opt.text = "All " + slen + " forum(s)"
list.appendChild(opt)
json.sources.sort((a,b) ->
return if (a.sourceURL == b.sourceURL) then 0 else (if a.sourceURL > b.sourceURL then 1 else -1)
)
for item in json.sources
if item.type in ['forum', 'discourse', 'askbot']
opt = document.createElement('option')
opt.value = item.sourceID
ezURL = null
n = item.sourceURL.match(/^([a-z]+:\/\/.+?)\/([-.A-Z0-9]+)$/i)
m = item.sourceURL.match(/^([a-z]+:\/\/.+?)\s(.+)$/i)
if n and n.length == 3
ezURL = "#{n[2]} - (#{n[1]})"
else if m and m.length == 3
ezURL = "#{m[2]} - (#{m[1]})"
opt.text = if ezURL then ezURL else item.sourceURL
if globArgs.source and globArgs.source == item.sourceID
opt.selected = 'selected'
list.appendChild(opt)
ID = Math.floor(Math.random() * 987654321).toString(16)
list.setAttribute('id', ID)
$("#"+ID).chosen().change(() ->
source = this.value
if source == ""
source = null
globArgs.source = source
updateWidgets('donut', null, { source: source })
updateWidgets('gauge', null, { source: source })
updateWidgets('line', null, { source: source })
updateWidgets('phonebook', null, { source: source })
updateWidgets('top5', null, { source: source })
updateWidgets('factors', null, { source: source })
updateWidgets('trends', null, { source: source })
)
imexplorer = (json, state) ->
org = json.organisation
if json.tag
org.name += " (Filter: " + json.tag + ")"
h = document.createElement('h4')
h.appendChild(document.createTextNode("Exploring " + org.name + ":"))
state.widget.inject(h, true)
list = document.createElement('select')
state.widget.inject(list)
opt = document.createElement('option')
opt.value = ""
slen = 0
for item in json.sources
if item.type in ['irc','gitter']
slen++
opt.text = "All " + slen + " messaging sources"
list.appendChild(opt)
json.sources.sort((a,b) ->
return if (a.sourceURL == b.sourceURL) then 0 else (if a.sourceURL > b.sourceURL then 1 else -1)
)
for item in json.sources
if item.type in ['irc', 'gitter']
opt = document.createElement('option')
opt.value = item.sourceID
ezURL = null
n = item.sourceURL.match(/^([a-z]+:\/\/.+?)\/([#\S+]+)$/i)
m = item.sourceURL.match(/^([a-z]+:\/\/.+?)\s(.+)$/i)
if n and n.length == 3
ezURL = "#{n[2]} - (#{n[1]})"
else if m and m.length == 3
ezURL = "#{m[2]} - (#{m[1]})"
opt.text = if ezURL then ezURL else item.sourceURL
if globArgs.source and globArgs.source == item.sourceID
opt.selected = 'selected'
list.appendChild(opt)
ID = Math.floor(Math.random() * 987654321).toString(16)
list.setAttribute('id', ID)
$("#"+ID).chosen().change(() ->
source = this.value
if source == ""
source = null
globArgs.source = source
updateWidgets('donut', null, { source: source })
updateWidgets('gauge', null, { source: source })
updateWidgets('line', null, { source: source })
updateWidgets('phonebook', null, { source: source })
updateWidgets('top5', null, { source: source })
updateWidgets('factors', null, { source: source })
updateWidgets('trends', null, { source: source })
, false)
$('select').chosen();
ciexplorer = (json, state) ->
org = json.organisation
if json.tag
org.name += " (Filter: " + json.tag + ")"
h = document.createElement('h4')
h.appendChild(document.createTextNode("Exploring " + org.name + ":"))
state.widget.inject(h, true)
list = document.createElement('select')
state.widget.inject(list)
opt = document.createElement('option')
opt.value = ""
slen = 0
for item in json.sources
if item.type in ['jenkins','travis','buildbot']
slen++
opt.text = "All " + slen + " CI Services"
list.appendChild(opt)
json.sources.sort((a,b) ->
return if (a.sourceURL == b.sourceURL) then 0 else (if a.sourceURL > b.sourceURL then 1 else -1)
)
for item in json.sources
if item.type in ['jenkins','travis','buildbot']
opt = document.createElement('option')
opt.value = item.sourceID
ezURL = null
n = item.sourceURL.match(/^([a-z]+:\/\/.+?)\/([#\S+]+)$/i)
m = item.sourceURL.match(/^([a-z]+:\/\/.+?)\s(.+)$/i)
if n and n.length == 3
ezURL = "#{n[2]} - (#{n[1]})"
else if m and m.length == 3
ezURL = "#{m[2]} - (#{m[1]})"
opt.text = if ezURL then ezURL else item.sourceURL
if globArgs.source and globArgs.source == item.sourceID
opt.selected = 'selected'
list.appendChild(opt)
ID = Math.floor(Math.random() * 987654321).toString(16)
list.setAttribute('id', ID)
$("#"+ID).chosen().change(() ->
source = this.value
if source == ""
source = null
globArgs.source = source
updateWidgets('donut', null, { source: source })
updateWidgets('gauge', null, { source: source })
updateWidgets('line', null, { source: source })
updateWidgets('phonebook', null, { source: source })
updateWidgets('top5', null, { source: source })
updateWidgets('factors', null, { source: source })
updateWidgets('trends', null, { source: source })
updateWidgets('relationship', null, { source: source })
)
multiviewexplorer = (json, state) ->
org = json.organisation
h = document.createElement('h4')
h.appendChild(document.createTextNode("Select views to compare:"))
state.widget.inject(h, true)
for k in [1..3]
tName = 'tag'+k
list = document.createElement('select')
list.setAttribute("data", tName)
state.widget.inject(list)
opt = document.createElement('option')
opt.value = ""
opt.text = "(None)"
list.appendChild(opt)
opt = document.createElement('option')
opt.value = "---"
opt.text = "Entire organisation"
if globArgs[tName] and globArgs[tName] == '---'
opt.selected = 'selected'
list.appendChild(opt)
if isArray(json.views)
json.views.sort((a,b) ->
return if (a.name == b.name) then 0 else (if a.name > b.name then 1 else -1)
)
for item in json.views
opt = document.createElement('option')
opt.value = item.id
opt.text = item.name
if globArgs[tName] and globArgs[tName] == item.id
opt.selected = 'selected'
list.appendChild(opt)
ID = Math.floor(Math.random() * 987654321).toString(16)
list.setAttribute('id', ID)
$("#"+ID).chosen().change(() ->
source = this.value
if source == ""
source = null
tName = this.getAttribute("data")
globArgs[tName] = source
x = {}
x[tName] = source
updateWidgets('donut', null, x)
updateWidgets('gauge', null, x)
updateWidgets('line', null, x)
updateWidgets('phonebook', null, x)
updateWidgets('top5', null, x)
updateWidgets('factors', null, x)
updateWidgets('trends', null, x)
updateWidgets('radar', null, x)
)
subFilterGlob = null
subFilter = () ->
source = subFilterGlob
if source == ""
source = null
tName = 'subfilter'
globArgs[tName] = source
x = {}
x[tName] = source
updateWidgets('sourcepicker', null, x)
updateWidgets('repopicker', null, x)
updateWidgets('issuepicker', null, x)
updateWidgets('forumpicker', null, x)
updateWidgets('mailpicker', null, x)
updateWidgets('logpicker', null, x)
updateWidgets('donut', null, x)
updateWidgets('gauge', null, x)
updateWidgets('line', null, x)
updateWidgets('phonebook', null, x)
updateWidgets('top5', null, x)
updateWidgets('factors', null, x)
updateWidgets('trends', null, x)
updateWidgets('radar', null, x)
updateWidgets('widget', null, x)
updateWidgets('relationship', null, x)
updateWidgets('treemap', null, x)
updateWidgets('report', null, x)
updateWidgets('mvp', null, x)
updateWidgets('comstat', null, x)
updateWidgets('worldmap', null, x)
updateWidgets('jsondump', null, x)
$( "a" ).each( () ->
url = $(this).attr('href')
if url
m = url.match(/^(.+\?page=[-a-z]+.*?)(?:&subfilter=[^&]+)?(.*)$/)
if m
if source
$(this).attr('href', "#{m[1]}&subfilter=#{source}#{m[2]}")
else
$(this).attr('href', "#{m[1]}#{m[2]}")
)
pathFilterGlob = null
pathFilter = () ->
source = pathFilterGlob
if source == ""
source = null
tName = 'pathfilter'
globArgs[tName] = source
x = {}
x[tName] = source
updateWidgets('donut', null, x)
updateWidgets('gauge', null, x)
updateWidgets('line', null, x)
updateWidgets('phonebook', null, x)
updateWidgets('top5', null, x)
updateWidgets('factors', null, x)
updateWidgets('trends', null, x)
updateWidgets('radar', null, x)
updateWidgets('widget', null, x)
updateWidgets('relationship', null, x)
updateWidgets('treemap', null, x)
updateWidgets('report', null, x)
updateWidgets('mvp', null, x)
updateWidgets('comstat', null, x)
updateWidgets('worldmap', null, x)
updateWidgets('jsondump', null, x)
$( "a" ).each( () ->
url = $(this).attr('href')
if url
m = url.match(/^(.+\?page=[-a-z]+.*?)(?:&pathfilter=[^&]+)?(.*)$/)
if m
if source
$(this).attr('href', "#{m[1]}&pathfilter=#{source}#{m[2]}")
else
$(this).attr('href', "#{m[1]}#{m[2]}")
)
viewexplorer = (json, state) ->
org = json.organisation
h = document.createElement('h4')
h.appendChild(document.createTextNode("Select a view to use:"))
state.widget.inject(h, true)
tName = 'view'
list = document.createElement('select')
list.setAttribute("data", tName)
state.widget.inject(list)
opt = document.createElement('option')
opt.value = ""
opt.text = "(None)"
list.appendChild(opt)
opt = document.createElement('option')
opt.value = "---"
opt.text = "Entire organisation"
if globArgs[tName] and globArgs[tName] == '---'
opt.selected = 'selected'
list.appendChild(opt)
if isArray(json.views)
json.views.sort((a,b) ->
return if (a.name == b.name) then 0 else (if a.name > b.name then 1 else -1)
)
for item in json.views
opt = document.createElement('option')
opt.value = item.id
opt.text = item.name
if globArgs[tName] and globArgs[tName] == item.id
opt.selected = 'selected'
list.appendChild(opt)
ID = Math.floor(Math.random() * 987654321).toString(16)
list.setAttribute('id', ID)
$("#"+ID).chosen().change(() ->
source = this.value
if source == ""
source = null
tName = this.getAttribute("data")
globArgs[tName] = source
x = {}
x[tName] = source
updateWidgets('sourcepicker', null, x)
updateWidgets('repopicker', null, x)
updateWidgets('issuepicker', null, x)
updateWidgets('mailpicker', null, x)
updateWidgets('logpicker', null, x)
updateWidgets('donut', null, x)
updateWidgets('gauge', null, x)
updateWidgets('line', null, x)
updateWidgets('phonebook', null, x)
updateWidgets('top5', null, x)
updateWidgets('factors', null, x)
updateWidgets('trends', null, x)
updateWidgets('radar', null, x)
updateWidgets('widget', null, x)
updateWidgets('relationship', null, x)
updateWidgets('treemap', null, x)
updateWidgets('report', null, x)
updateWidgets('mvp', null, x)
updateWidgets('comstat', null, x)
updateWidgets('worldmap', null, x)
updateWidgets('jsondump', null, x)
$( "a" ).each( () ->
url = $(this).attr('href')
if url
m = url.match(/^(.+\?page=[-a-z]+)(?:&view=[a-f0-9]+)?(.*)$/)
if m
if source
$(this).attr('href', "#{m[1]}&view=#{source}#{m[2]}")
else
$(this).attr('href', "#{m[1]}#{m[2]}")
)
)
# Quick filter
state.widget.inject(new HTML('br'))
i = new HTML('input', {id:'subfilter', size: 16, type: 'text', value: globArgs.subfilter, onChange: 'subFilterGlob = this.value;', placeholder: 'sub-filter'})
b = new HTML('input', {style: { marginLeft: '10px'}, class: 'btn btn-small btn-success', type: 'button', onClick: 'subFilter();', value: "sub-filter"})
rb = new HTML('input', {style: { marginLeft: '10px'}, class: 'btn btn-small btn-danger', type: 'button', onClick: 'get("subfilter").value=""; subFilterGlob=""; subFilter();', value: "reset"})
state.widget.inject(i)
state.widget.inject(b)
state.widget.inject(rb)
if globArgs.subfilter and globArgs.subfilter.length > 0
source = globArgs.subfilter
$( "a" ).each( () ->
url = $(this).attr('href')
if url
m = url.match(/^(.+\?page=[-a-z]+.*?)(?:&subfilter=[a-f0-9]+)?(.*)$/)
if m
if source
$(this).attr('href', "#{m[1]}&subfilter=#{source}#{m[2]}")
else
$(this).attr('href', "#{m[1]}#{m[2]}")
)
if globArgs.email
div = new HTML('div', {}, "Currently filtering results based on " + globArgs.email + ". - ")
div.inject(new HTML('a', { href: 'javascript:void(filterPerson(null));'}, "Reset filter"))
state.widget.inject(div)
widgetexplorer = (json, state) ->
pwidgets = {
'languages': 'Code: Language breakdown',
'commit-history-year': "Code: Commit history (past year)"
'commit-history-all': "Code: Commit history (all time)"
'commit-top5-year': "Code: top 5 committers (past year)"
'commit-top5-all': "Code: top 5 committers (all time)"
'committer-count-year': "Code: Committers/Authors per month (past year)"
'committer-count-all': "Code: Committers/Authors per month (all time)"
'commit-lines-year': "Code: Lines changed (past year)"
'commit-lines-all': "Code: Lines changed (all time)"
'sloc-map': "Code: Language Treemap"
'repo-size-year': "Repos: top 15 by lines of code"
'repo-commits-year': "Repos: top 15 by number of commits (past year)"
'repo-commits-all': "Repos: top 15 by number of commits (all time)"
'evolution': "Code: Code evolution (all time)"
'evolution-extended': "Code: Code evolution (individual languages, all time)"
'issue-count-year': "Issues: Tickets opened/closed (past year)"
'issue-count-all': "Issues: Tickets opened/closed (all time)"
'issue-operators-year': "Issues: Ticket creators/closers (past year)"
'issue-operators-all': "Issues: Ticket creators/closers (all time)"
'issue-queue-all': "Issue queue size by ticket age"
'email-count-year': "Mail: Emails/threads/authors (past year)"
'email-count-all': "Mail: Emails/threads/authors (all time)"
'im-stats-year': "Online messaging activity (past year)",
'im-stats-all': "Online messaging activity (all time)",
'compare-commits-year': "Commits by Affiliation (past year)",
'compare-commits-all': "Commits by Affiliation (all time)"
'repo-relationship-year': "Repository relationships (past year)"
'repo-relationship-2year': "Repository relationships (past two years)"
'issue-relationship-year': "Issue tracker relationships (past year)"
'issue-relationship-2year': "Issue tracker relationships (past two years)"
'log-stats-year': "Downloads/Visits (past year)"
'log-stats-all': "Downloads/Visits (all time)"
'log-map-month': "Downloads/Visits per country (past month)"
'log-map-year': "Downloads/Visits per country (past year)"
'log-map-all': "Downloads/Visits per country (all time)"
}
org = json.organisation
h = document.createElement('h4')
h.appendChild(document.createTextNode("Select a widget to use:"))
state.widget.inject(h, true)
tName = 'widget'
list = document.createElement('select')
list.setAttribute("data", tName)
state.widget.inject(list)
opt = document.createElement('option')
opt.value = ""
opt.text = "Select a widget type:"
list.appendChild(opt)
for key, value of pwidgets
opt = document.createElement('option')
opt.value = key
opt.text = value
if globArgs[tName] and globArgs[tName] == key
opt.selected = 'selected'
list.appendChild(opt)
list.addEventListener("change", () ->
source = this.value
if source == ""
source = null
tName = this.getAttribute("data")
globArgs[tName] = source
x = {}
x[tName] = source
updateWidgets('widget', null, x)
updateWidgets('donut', null, x)
updateWidgets('gauge', null, x)
updateWidgets('line', null, x)
updateWidgets('phonebook', null, x)
updateWidgets('top5', null, x)
updateWidgets('factors', null, x)
updateWidgets('trends', null, x)
updateWidgets('radar', null, x)
, false)
| true | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF 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.
explorer = (json, state) ->
org = json.organisation
h = document.createElement('h2')
if json.tag
org.name += " (Filter: " + json.tag + ")"
h.appendChild(document.createTextNode("Exploring " + org.name + ":"))
state.widget.inject(h, true)
list = document.createElement('select')
state.widget.inject(list)
opt = document.createElement('option')
opt.value = ""
slen = 0
for item in json.sources
if item.type in ['git', 'svn', 'gerrit', 'github'] and item.noclone != true
slen++
opt.text = "All " + slen + " repositories"
list.appendChild(opt)
json.sources.sort((a,b) ->
return if (a.sourceURL == b.sourceURL) then 0 else (if a.sourceURL > b.sourceURL then 1 else -1)
)
for item in json.sources
if item.type in ['git', 'svn', 'gerrit', 'github'] and item.noclone != true
opt = document.createElement('option')
opt.value = item.sourceID
ezURL = null
m = item.sourceURL.match(/^([a-z]+:\/\/.+?)[\/?]([^\/?]+)$/i)
if m and m.length == 3
ezURL = "#{m[2]} - (#{m[1]})"
opt.text = if ezURL then ezURL else item.sourceURL
if globArgs.source and globArgs.source == item.sourceID
opt.selected = 'selected'
list.appendChild(opt)
ID = Math.floor(Math.random() * 987654321).toString(16)
list.setAttribute('id', ID)
$("#"+ID).chosen().change(() ->
source = this.value
if source == ""
source = null
globArgs.source = source
updateWidgets('donut', null, { source: source })
updateWidgets('gauge', null, { source: source })
updateWidgets('line', null, { source: source })
updateWidgets('phonebook', null, { source: source })
updateWidgets('top5', null, { source: source })
updateWidgets('factors', null, { source: source })
updateWidgets('trends', null, { source: source })
updateWidgets('mvp', null, { source: source })
updateWidgets('comstat', null, { source: source })
updateWidgets('jsondump', null, { source: source })
)
# Unique commits label
id = Math.floor(Math.random() * 987654321).toString(16)
chk = document.createElement('input')
chk.setAttribute("type", "checkbox")
chk.setAttribute("id", id)
chk.style.marginLeft = '10px'
if globArgs.author and globArgs.author == 'true'
chk.checked = true
chk.addEventListener("change", () ->
unique = null
if this.checked
author = 'true'
globArgs['author'] = 'true'
updateWidgets('donut', null, { author: author })
updateWidgets('gauge', null, { author: author })
updateWidgets('line', null, { author: author })
updateWidgets('phonebook', null, { author: author })
updateWidgets('top5', null, { author: author })
updateWidgets('factors', null, { author: author })
updateWidgets('trends', null, { author: author })
updateWidgets('relationship', null, {author: author})
updateWidgets('mvp', null, {author: author})
updateWidgets('comstat', null, { author: PI:NAME:<NAME>END_PI })
updateWidgets('jsondump', null, { author: PI:NAME:<NAME>END_PI })
)
state.widget.inject(chk)
label = document.createElement('label')
label.setAttribute("for", id)
label.setAttribute("title", "Check this box to authorships instead of committerships")
chk.setAttribute("title", "Check this box to authorships instead of committerships")
label.style.paddingLeft = '5px'
label.appendChild(document.createTextNode('Show authors'))
state.widget.inject(label)
br = new HTML('br')
p = new HTML('input', {id:'pathfilter', size: 32, type: 'text', value: globArgs.pathfilter, onChange: 'pathFilterGlob = this.value;',placeholder: 'optional path-filter'})
state.widget.inject(br)
state.widget.inject(p)
b = new HTML('input', {style: { marginLeft: '10px'}, class: 'btn btn-small btn-success', type: 'button', onClick: 'pathFilter();', value: "filter paths"})
rb = new HTML('input', {style: { marginLeft: '10px'}, class: 'btn btn-small btn-danger', type: 'button', onClick: 'get("pathfilter").value = ""; pathFilterGlob = ""; pathFilter();', value: "reset"})
state.widget.inject(b)
state.widget.inject(rb)
sourceexplorer = (json, state) ->
org = json.organisation
h = document.createElement('h4')
if json.tag
org.name += " (Filter: " + json.tag + ")"
h.appendChild(document.createTextNode("Exploring " + org.name + ":"))
state.widget.inject(h, true)
div = new HTML('div', {class: "form-group"})
list = new HTML('select', { class: "form-control"})
div.inject(list)
state.widget.inject(div)
opt = document.createElement('option')
opt.value = ""
slen = 0
for item in json.sources
slen++
opt.text = "All " + slen + " sources"
list.appendChild(opt)
json.sources.sort((a,b) ->
return if (a.sourceURL == b.sourceURL) then 0 else (if a.sourceURL > b.sourceURL then 1 else -1)
)
for item in json.sources
if true
opt = document.createElement('option')
opt.value = item.sourceID
ezURL = null
m = item.sourceURL.match(/^([a-z]+:\/\/.+?)[\/?]([^\/?]+)$/i)
if m and m.length == 3
ezURL = "#{m[2]} - (#{m[1]})"
opt.text = if ezURL then ezURL else item.sourceURL
if globArgs.source and globArgs.source == item.sourceID
opt.selected = 'selected'
list.appendChild(opt)
ID = Math.floor(Math.random() * 987654321).toString(16)
list.setAttribute('id', ID)
$("#"+ID).chosen().change(() ->
source = this.value
if source == ""
source = null
globArgs.source = source
updateWidgets('donut', null, { source: source })
updateWidgets('gauge', null, { source: source })
updateWidgets('line', null, { source: source })
updateWidgets('phonebook', null, { source: source })
updateWidgets('top5', null, { source: source })
updateWidgets('factors', null, { source: source })
updateWidgets('trends', null, { source: source })
updateWidgets('mvp', null, { source: source })
updateWidgets('comstat', null, { source: source })
updateWidgets('jsondump', null, { source: source })
)
mailexplorer = (json, state) ->
org = json.organisation
h = document.createElement('h4')
if json.tag
org.name += " (Filter: " + json.tag + ")"
h.appendChild(document.createTextNode("Exploring " + org.name + ":"))
state.widget.inject(h, true)
list = document.createElement('select')
state.widget.inject(list)
opt = document.createElement('option')
opt.value = ""
slen = 0
for item in json.sources
if item.type in ['mail', 'ponymail', 'pipermail', 'hyperkitty']
slen++
opt.text = "All " + slen + " mailing lists"
list.appendChild(opt)
json.sources.sort((a,b) ->
return if (a.sourceURL == b.sourceURL) then 0 else (if a.sourceURL > b.sourceURL then 1 else -1)
)
for item in json.sources
if item.type in ['mail', 'ponymail', 'pipermail', 'hyperkitty']
opt = document.createElement('option')
opt.value = item.sourceID
ezURL = null
m = item.sourceURL.match(/^([a-z]+:\/\/.+?)[\/?]([^\/?]+)$/i)
if m and m.length == 3
ezURL = "#{m[2]} - (#{m[1]})"
opt.text = if ezURL then ezURL else item.sourceURL
if globArgs.source and globArgs.source == item.sourceID
opt.selected = 'selected'
list.appendChild(opt)
ID = Math.floor(Math.random() * 987654321).toString(16)
list.setAttribute('id', ID)
$("#"+ID).chosen().change(() ->
source = this.value
if source == ""
source = null
globArgs.source = source
updateWidgets('donut', null, { source: source })
updateWidgets('gauge', null, { source: source })
updateWidgets('line', null, { source: source })
updateWidgets('phonebook', null, { source: source })
updateWidgets('top5', null, { source: source })
updateWidgets('factors', null, { source: source })
updateWidgets('trends', null, { source: source })
updateWidgets('relationship', null, { source: source })
)
logexplorer = (json, state) ->
org = json.organisation
h = document.createElement('h4')
if json.tag
org.name += " (Filter: " + json.tag + ")"
h.appendChild(document.createTextNode("Exploring " + org.name + ":"))
state.widget.inject(h, true)
list = document.createElement('select')
state.widget.inject(list)
opt = document.createElement('option')
opt.value = ""
slen = 0
for item in json.sources
if item.type == 'stats'
slen++
opt.text = "All " + slen + " log files"
list.appendChild(opt)
json.sources.sort((a,b) ->
return if (a.sourceURL == b.sourceURL) then 0 else (if a.sourceURL > b.sourceURL then 1 else -1)
)
for item in json.sources
if item.type == 'stats'
opt = document.createElement('option')
opt.value = item.sourceID
ezURL = null
m = item.sourceURL.match(/^([a-z]+:\/\/.+?)[\/?]([^\/?]+)$/i)
if m and m.length == 3
ezURL = "#{m[2]} - (#{m[1]})"
opt.text = if ezURL then ezURL else item.sourceURL
if globArgs.source and globArgs.source == item.sourceID
opt.selected = 'selected'
list.appendChild(opt)
ID = Math.floor(Math.random() * 987654321).toString(16)
list.setAttribute('id', ID)
$("#"+ID).chosen().change(() ->
source = this.value
if source == ""
source = null
globArgs.source = source
updateWidgets('donut', null, { source: source })
updateWidgets('gauge', null, { source: source })
updateWidgets('line', null, { source: source })
updateWidgets('worldmap', null, { source: source })
updateWidgets('top5', null, { source: source })
updateWidgets('factors', null, { source: source })
updateWidgets('trends', null, { source: source })
)
issueexplorer = (json, state) ->
org = json.organisation
if json.tag
org.name += " (Filter: " + json.tag + ")"
h = document.createElement('h4')
h.appendChild(document.createTextNode("Exploring " + org.name + ":"))
state.widget.inject(h, true)
list = document.createElement('select')
state.widget.inject(list)
opt = document.createElement('option')
opt.value = ""
slen = 0
for item in json.sources
if item.type in ['jira', 'gerrit', 'github', 'bugzilla']
slen++
opt.text = "All " + slen + " issue tracker(s)"
list.appendChild(opt)
json.sources.sort((a,b) ->
return if (a.sourceURL == b.sourceURL) then 0 else (if a.sourceURL > b.sourceURL then 1 else -1)
)
for item in json.sources
if item.type in ['jira', 'gerrit', 'github', 'bugzilla']
opt = document.createElement('option')
opt.value = item.sourceID
ezURL = null
n = item.sourceURL.match(/^([a-z]+:\/\/.+?)\/([-.A-Z0-9]+)$/i)
m = item.sourceURL.match(/^([a-z]+:\/\/.+?)\s(.+)$/i)
if n and n.length == 3
ezURL = "#{n[2]} - (#{n[1]})"
else if m and m.length == 3
ezURL = "#{m[2]} - (#{m[1]})"
opt.text = if ezURL then ezURL else item.sourceURL
if globArgs.source and globArgs.source == item.sourceID
opt.selected = 'selected'
list.appendChild(opt)
ID = Math.floor(Math.random() * 987654321).toString(16)
list.setAttribute('id', ID)
$("#"+ID).chosen().change(() ->
source = this.value
if source == ""
source = null
globArgs.source = source
updateWidgets('donut', null, { source: source })
updateWidgets('gauge', null, { source: source })
updateWidgets('line', null, { source: source })
updateWidgets('phonebook', null, { source: source })
updateWidgets('top5', null, { source: source })
updateWidgets('factors', null, { source: source })
updateWidgets('trends', null, { source: source })
)
forumexplorer = (json, state) ->
org = json.organisation
if json.tag
org.name += " (Filter: " + json.tag + ")"
h = document.createElement('h4')
h.appendChild(document.createTextNode("Exploring " + org.name + ":"))
state.widget.inject(h, true)
list = document.createElement('select')
state.widget.inject(list)
opt = document.createElement('option')
opt.value = ""
slen = 0
for item in json.sources
if item.type in ['forum', 'discourse', 'askbot']
slen++
opt.text = "All " + slen + " forum(s)"
list.appendChild(opt)
json.sources.sort((a,b) ->
return if (a.sourceURL == b.sourceURL) then 0 else (if a.sourceURL > b.sourceURL then 1 else -1)
)
for item in json.sources
if item.type in ['forum', 'discourse', 'askbot']
opt = document.createElement('option')
opt.value = item.sourceID
ezURL = null
n = item.sourceURL.match(/^([a-z]+:\/\/.+?)\/([-.A-Z0-9]+)$/i)
m = item.sourceURL.match(/^([a-z]+:\/\/.+?)\s(.+)$/i)
if n and n.length == 3
ezURL = "#{n[2]} - (#{n[1]})"
else if m and m.length == 3
ezURL = "#{m[2]} - (#{m[1]})"
opt.text = if ezURL then ezURL else item.sourceURL
if globArgs.source and globArgs.source == item.sourceID
opt.selected = 'selected'
list.appendChild(opt)
ID = Math.floor(Math.random() * 987654321).toString(16)
list.setAttribute('id', ID)
$("#"+ID).chosen().change(() ->
source = this.value
if source == ""
source = null
globArgs.source = source
updateWidgets('donut', null, { source: source })
updateWidgets('gauge', null, { source: source })
updateWidgets('line', null, { source: source })
updateWidgets('phonebook', null, { source: source })
updateWidgets('top5', null, { source: source })
updateWidgets('factors', null, { source: source })
updateWidgets('trends', null, { source: source })
)
imexplorer = (json, state) ->
org = json.organisation
if json.tag
org.name += " (Filter: " + json.tag + ")"
h = document.createElement('h4')
h.appendChild(document.createTextNode("Exploring " + org.name + ":"))
state.widget.inject(h, true)
list = document.createElement('select')
state.widget.inject(list)
opt = document.createElement('option')
opt.value = ""
slen = 0
for item in json.sources
if item.type in ['irc','gitter']
slen++
opt.text = "All " + slen + " messaging sources"
list.appendChild(opt)
json.sources.sort((a,b) ->
return if (a.sourceURL == b.sourceURL) then 0 else (if a.sourceURL > b.sourceURL then 1 else -1)
)
for item in json.sources
if item.type in ['irc', 'gitter']
opt = document.createElement('option')
opt.value = item.sourceID
ezURL = null
n = item.sourceURL.match(/^([a-z]+:\/\/.+?)\/([#\S+]+)$/i)
m = item.sourceURL.match(/^([a-z]+:\/\/.+?)\s(.+)$/i)
if n and n.length == 3
ezURL = "#{n[2]} - (#{n[1]})"
else if m and m.length == 3
ezURL = "#{m[2]} - (#{m[1]})"
opt.text = if ezURL then ezURL else item.sourceURL
if globArgs.source and globArgs.source == item.sourceID
opt.selected = 'selected'
list.appendChild(opt)
ID = Math.floor(Math.random() * 987654321).toString(16)
list.setAttribute('id', ID)
$("#"+ID).chosen().change(() ->
source = this.value
if source == ""
source = null
globArgs.source = source
updateWidgets('donut', null, { source: source })
updateWidgets('gauge', null, { source: source })
updateWidgets('line', null, { source: source })
updateWidgets('phonebook', null, { source: source })
updateWidgets('top5', null, { source: source })
updateWidgets('factors', null, { source: source })
updateWidgets('trends', null, { source: source })
, false)
$('select').chosen();
ciexplorer = (json, state) ->
org = json.organisation
if json.tag
org.name += " (Filter: " + json.tag + ")"
h = document.createElement('h4')
h.appendChild(document.createTextNode("Exploring " + org.name + ":"))
state.widget.inject(h, true)
list = document.createElement('select')
state.widget.inject(list)
opt = document.createElement('option')
opt.value = ""
slen = 0
for item in json.sources
if item.type in ['jenkins','travis','buildbot']
slen++
opt.text = "All " + slen + " CI Services"
list.appendChild(opt)
json.sources.sort((a,b) ->
return if (a.sourceURL == b.sourceURL) then 0 else (if a.sourceURL > b.sourceURL then 1 else -1)
)
for item in json.sources
if item.type in ['jenkins','travis','buildbot']
opt = document.createElement('option')
opt.value = item.sourceID
ezURL = null
n = item.sourceURL.match(/^([a-z]+:\/\/.+?)\/([#\S+]+)$/i)
m = item.sourceURL.match(/^([a-z]+:\/\/.+?)\s(.+)$/i)
if n and n.length == 3
ezURL = "#{n[2]} - (#{n[1]})"
else if m and m.length == 3
ezURL = "#{m[2]} - (#{m[1]})"
opt.text = if ezURL then ezURL else item.sourceURL
if globArgs.source and globArgs.source == item.sourceID
opt.selected = 'selected'
list.appendChild(opt)
ID = Math.floor(Math.random() * 987654321).toString(16)
list.setAttribute('id', ID)
$("#"+ID).chosen().change(() ->
source = this.value
if source == ""
source = null
globArgs.source = source
updateWidgets('donut', null, { source: source })
updateWidgets('gauge', null, { source: source })
updateWidgets('line', null, { source: source })
updateWidgets('phonebook', null, { source: source })
updateWidgets('top5', null, { source: source })
updateWidgets('factors', null, { source: source })
updateWidgets('trends', null, { source: source })
updateWidgets('relationship', null, { source: source })
)
multiviewexplorer = (json, state) ->
org = json.organisation
h = document.createElement('h4')
h.appendChild(document.createTextNode("Select views to compare:"))
state.widget.inject(h, true)
for k in [1..3]
tName = 'tag'+k
list = document.createElement('select')
list.setAttribute("data", tName)
state.widget.inject(list)
opt = document.createElement('option')
opt.value = ""
opt.text = "(None)"
list.appendChild(opt)
opt = document.createElement('option')
opt.value = "---"
opt.text = "Entire organisation"
if globArgs[tName] and globArgs[tName] == '---'
opt.selected = 'selected'
list.appendChild(opt)
if isArray(json.views)
json.views.sort((a,b) ->
return if (a.name == b.name) then 0 else (if a.name > b.name then 1 else -1)
)
for item in json.views
opt = document.createElement('option')
opt.value = item.id
opt.text = item.name
if globArgs[tName] and globArgs[tName] == item.id
opt.selected = 'selected'
list.appendChild(opt)
ID = Math.floor(Math.random() * 987654321).toString(16)
list.setAttribute('id', ID)
$("#"+ID).chosen().change(() ->
source = this.value
if source == ""
source = null
tName = this.getAttribute("data")
globArgs[tName] = source
x = {}
x[tName] = source
updateWidgets('donut', null, x)
updateWidgets('gauge', null, x)
updateWidgets('line', null, x)
updateWidgets('phonebook', null, x)
updateWidgets('top5', null, x)
updateWidgets('factors', null, x)
updateWidgets('trends', null, x)
updateWidgets('radar', null, x)
)
subFilterGlob = null
subFilter = () ->
source = subFilterGlob
if source == ""
source = null
tName = 'subfilter'
globArgs[tName] = source
x = {}
x[tName] = source
updateWidgets('sourcepicker', null, x)
updateWidgets('repopicker', null, x)
updateWidgets('issuepicker', null, x)
updateWidgets('forumpicker', null, x)
updateWidgets('mailpicker', null, x)
updateWidgets('logpicker', null, x)
updateWidgets('donut', null, x)
updateWidgets('gauge', null, x)
updateWidgets('line', null, x)
updateWidgets('phonebook', null, x)
updateWidgets('top5', null, x)
updateWidgets('factors', null, x)
updateWidgets('trends', null, x)
updateWidgets('radar', null, x)
updateWidgets('widget', null, x)
updateWidgets('relationship', null, x)
updateWidgets('treemap', null, x)
updateWidgets('report', null, x)
updateWidgets('mvp', null, x)
updateWidgets('comstat', null, x)
updateWidgets('worldmap', null, x)
updateWidgets('jsondump', null, x)
$( "a" ).each( () ->
url = $(this).attr('href')
if url
m = url.match(/^(.+\?page=[-a-z]+.*?)(?:&subfilter=[^&]+)?(.*)$/)
if m
if source
$(this).attr('href', "#{m[1]}&subfilter=#{source}#{m[2]}")
else
$(this).attr('href', "#{m[1]}#{m[2]}")
)
pathFilterGlob = null
pathFilter = () ->
source = pathFilterGlob
if source == ""
source = null
tName = 'pathfilter'
globArgs[tName] = source
x = {}
x[tName] = source
updateWidgets('donut', null, x)
updateWidgets('gauge', null, x)
updateWidgets('line', null, x)
updateWidgets('phonebook', null, x)
updateWidgets('top5', null, x)
updateWidgets('factors', null, x)
updateWidgets('trends', null, x)
updateWidgets('radar', null, x)
updateWidgets('widget', null, x)
updateWidgets('relationship', null, x)
updateWidgets('treemap', null, x)
updateWidgets('report', null, x)
updateWidgets('mvp', null, x)
updateWidgets('comstat', null, x)
updateWidgets('worldmap', null, x)
updateWidgets('jsondump', null, x)
$( "a" ).each( () ->
url = $(this).attr('href')
if url
m = url.match(/^(.+\?page=[-a-z]+.*?)(?:&pathfilter=[^&]+)?(.*)$/)
if m
if source
$(this).attr('href', "#{m[1]}&pathfilter=#{source}#{m[2]}")
else
$(this).attr('href', "#{m[1]}#{m[2]}")
)
viewexplorer = (json, state) ->
org = json.organisation
h = document.createElement('h4')
h.appendChild(document.createTextNode("Select a view to use:"))
state.widget.inject(h, true)
tName = 'view'
list = document.createElement('select')
list.setAttribute("data", tName)
state.widget.inject(list)
opt = document.createElement('option')
opt.value = ""
opt.text = "(None)"
list.appendChild(opt)
opt = document.createElement('option')
opt.value = "---"
opt.text = "Entire organisation"
if globArgs[tName] and globArgs[tName] == '---'
opt.selected = 'selected'
list.appendChild(opt)
if isArray(json.views)
json.views.sort((a,b) ->
return if (a.name == b.name) then 0 else (if a.name > b.name then 1 else -1)
)
for item in json.views
opt = document.createElement('option')
opt.value = item.id
opt.text = item.name
if globArgs[tName] and globArgs[tName] == item.id
opt.selected = 'selected'
list.appendChild(opt)
ID = Math.floor(Math.random() * 987654321).toString(16)
list.setAttribute('id', ID)
$("#"+ID).chosen().change(() ->
source = this.value
if source == ""
source = null
tName = this.getAttribute("data")
globArgs[tName] = source
x = {}
x[tName] = source
updateWidgets('sourcepicker', null, x)
updateWidgets('repopicker', null, x)
updateWidgets('issuepicker', null, x)
updateWidgets('mailpicker', null, x)
updateWidgets('logpicker', null, x)
updateWidgets('donut', null, x)
updateWidgets('gauge', null, x)
updateWidgets('line', null, x)
updateWidgets('phonebook', null, x)
updateWidgets('top5', null, x)
updateWidgets('factors', null, x)
updateWidgets('trends', null, x)
updateWidgets('radar', null, x)
updateWidgets('widget', null, x)
updateWidgets('relationship', null, x)
updateWidgets('treemap', null, x)
updateWidgets('report', null, x)
updateWidgets('mvp', null, x)
updateWidgets('comstat', null, x)
updateWidgets('worldmap', null, x)
updateWidgets('jsondump', null, x)
$( "a" ).each( () ->
url = $(this).attr('href')
if url
m = url.match(/^(.+\?page=[-a-z]+)(?:&view=[a-f0-9]+)?(.*)$/)
if m
if source
$(this).attr('href', "#{m[1]}&view=#{source}#{m[2]}")
else
$(this).attr('href', "#{m[1]}#{m[2]}")
)
)
# Quick filter
state.widget.inject(new HTML('br'))
i = new HTML('input', {id:'subfilter', size: 16, type: 'text', value: globArgs.subfilter, onChange: 'subFilterGlob = this.value;', placeholder: 'sub-filter'})
b = new HTML('input', {style: { marginLeft: '10px'}, class: 'btn btn-small btn-success', type: 'button', onClick: 'subFilter();', value: "sub-filter"})
rb = new HTML('input', {style: { marginLeft: '10px'}, class: 'btn btn-small btn-danger', type: 'button', onClick: 'get("subfilter").value=""; subFilterGlob=""; subFilter();', value: "reset"})
state.widget.inject(i)
state.widget.inject(b)
state.widget.inject(rb)
if globArgs.subfilter and globArgs.subfilter.length > 0
source = globArgs.subfilter
$( "a" ).each( () ->
url = $(this).attr('href')
if url
m = url.match(/^(.+\?page=[-a-z]+.*?)(?:&subfilter=[a-f0-9]+)?(.*)$/)
if m
if source
$(this).attr('href', "#{m[1]}&subfilter=#{source}#{m[2]}")
else
$(this).attr('href', "#{m[1]}#{m[2]}")
)
if globArgs.email
div = new HTML('div', {}, "Currently filtering results based on " + globArgs.email + ". - ")
div.inject(new HTML('a', { href: 'javascript:void(filterPerson(null));'}, "Reset filter"))
state.widget.inject(div)
widgetexplorer = (json, state) ->
pwidgets = {
'languages': 'Code: Language breakdown',
'commit-history-year': "Code: Commit history (past year)"
'commit-history-all': "Code: Commit history (all time)"
'commit-top5-year': "Code: top 5 committers (past year)"
'commit-top5-all': "Code: top 5 committers (all time)"
'committer-count-year': "Code: Committers/Authors per month (past year)"
'committer-count-all': "Code: Committers/Authors per month (all time)"
'commit-lines-year': "Code: Lines changed (past year)"
'commit-lines-all': "Code: Lines changed (all time)"
'sloc-map': "Code: Language Treemap"
'repo-size-year': "Repos: top 15 by lines of code"
'repo-commits-year': "Repos: top 15 by number of commits (past year)"
'repo-commits-all': "Repos: top 15 by number of commits (all time)"
'evolution': "Code: Code evolution (all time)"
'evolution-extended': "Code: Code evolution (individual languages, all time)"
'issue-count-year': "Issues: Tickets opened/closed (past year)"
'issue-count-all': "Issues: Tickets opened/closed (all time)"
'issue-operators-year': "Issues: Ticket creators/closers (past year)"
'issue-operators-all': "Issues: Ticket creators/closers (all time)"
'issue-queue-all': "Issue queue size by ticket age"
'email-count-year': "Mail: Emails/threads/authors (past year)"
'email-count-all': "Mail: Emails/threads/authors (all time)"
'im-stats-year': "Online messaging activity (past year)",
'im-stats-all': "Online messaging activity (all time)",
'compare-commits-year': "Commits by Affiliation (past year)",
'compare-commits-all': "Commits by Affiliation (all time)"
'repo-relationship-year': "Repository relationships (past year)"
'repo-relationship-2year': "Repository relationships (past two years)"
'issue-relationship-year': "Issue tracker relationships (past year)"
'issue-relationship-2year': "Issue tracker relationships (past two years)"
'log-stats-year': "Downloads/Visits (past year)"
'log-stats-all': "Downloads/Visits (all time)"
'log-map-month': "Downloads/Visits per country (past month)"
'log-map-year': "Downloads/Visits per country (past year)"
'log-map-all': "Downloads/Visits per country (all time)"
}
org = json.organisation
h = document.createElement('h4')
h.appendChild(document.createTextNode("Select a widget to use:"))
state.widget.inject(h, true)
tName = 'widget'
list = document.createElement('select')
list.setAttribute("data", tName)
state.widget.inject(list)
opt = document.createElement('option')
opt.value = ""
opt.text = "Select a widget type:"
list.appendChild(opt)
for key, value of pwidgets
opt = document.createElement('option')
opt.value = key
opt.text = value
if globArgs[tName] and globArgs[tName] == key
opt.selected = 'selected'
list.appendChild(opt)
list.addEventListener("change", () ->
source = this.value
if source == ""
source = null
tName = this.getAttribute("data")
globArgs[tName] = source
x = {}
x[tName] = source
updateWidgets('widget', null, x)
updateWidgets('donut', null, x)
updateWidgets('gauge', null, x)
updateWidgets('line', null, x)
updateWidgets('phonebook', null, x)
updateWidgets('top5', null, x)
updateWidgets('factors', null, x)
updateWidgets('trends', null, x)
updateWidgets('radar', null, x)
, false)
|
[
{
"context": "s globalConfig.project\n\n author =\n name: 'changeme'\n email: 'changeme'\n description = 'chang",
"end": 237,
"score": 0.9995826482772827,
"start": 229,
"tag": "USERNAME",
"value": "changeme"
},
{
"context": " author =\n name: 'changeme'\n ... | lib/packages/bundler/write_gemfile.coffee | gampleman/praxis-client-generator | 1 | _ = require 'lodash-fp'
module.exports = (dependencies, globalConfig, execLater) ->
$runAfter: ['renderCode']
$runBefore: ['writeCode']
$process: (docs) ->
return unless globalConfig.project
author =
name: 'changeme'
email: 'changeme'
description = 'changeme'
summary = description
homepage = 'https://github.com/gampleman/praxis-client-generator'
deps = []
for {identifier, version} in dependencies.dependencies('gem-ruby')
deps.push("gem.add_dependency '#{identifier}'")
for {identifier, version} in dependencies.dependencies('gem-ruby-dev')
deps.push("gem.add_development_dependency '#{identifier}'")
docs.push {
type: 'ruby'
outputPath: 'Gemfile'
rendered: """
source 'https://rubygems.org'
gemspec
"""
}
path = _.snakeCase(globalConfig.moduleName)
docs.push {
type: 'ruby'
outputPath: globalConfig.moduleName + '.gemspec'
rendered: """
# -*- encoding: utf-8 -*-
require File.expand_path('../lib/#{path}/version', __FILE__)
Gem::Specification.new do |gem|
gem.authors = ["#{author.name}"]
gem.email = ["#{author.email}"]
gem.description = %q{#{description}}
gem.summary = %q{#{summary}}
gem.homepage = "#{homepage}" # changeme
gem.files = `git ls-files`.split($\\)
gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) }
gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
gem.name = "#{path}"
gem.require_paths = ["lib"]
gem.version = #{globalConfig.moduleName}::VERSION
gem.license = 'MIT'
#{deps.join('\n')}
end
"""
}
execLater 'bundle install'
docs
| 201248 | _ = require 'lodash-fp'
module.exports = (dependencies, globalConfig, execLater) ->
$runAfter: ['renderCode']
$runBefore: ['writeCode']
$process: (docs) ->
return unless globalConfig.project
author =
name: 'changeme'
email: '<PASSWORD>'
description = 'changeme'
summary = description
homepage = 'https://github.com/gampleman/praxis-client-generator'
deps = []
for {identifier, version} in dependencies.dependencies('gem-ruby')
deps.push("gem.add_dependency '#{identifier}'")
for {identifier, version} in dependencies.dependencies('gem-ruby-dev')
deps.push("gem.add_development_dependency '#{identifier}'")
docs.push {
type: 'ruby'
outputPath: 'Gemfile'
rendered: """
source 'https://rubygems.org'
gemspec
"""
}
path = _.snakeCase(globalConfig.moduleName)
docs.push {
type: 'ruby'
outputPath: globalConfig.moduleName + '.gemspec'
rendered: """
# -*- encoding: utf-8 -*-
require File.expand_path('../lib/#{path}/version', __FILE__)
Gem::Specification.new do |gem|
gem.authors = ["#{author.name}"]
gem.email = ["#{author.email}"]
gem.description = %q{#{description}}
gem.summary = %q{#{summary}}
gem.homepage = "#{homepage}" # changeme
gem.files = `git ls-files`.split($\\)
gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) }
gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
gem.name = "#{path}"
gem.require_paths = ["lib"]
gem.version = #{globalConfig.moduleName}::VERSION
gem.license = 'MIT'
#{deps.join('\n')}
end
"""
}
execLater 'bundle install'
docs
| true | _ = require 'lodash-fp'
module.exports = (dependencies, globalConfig, execLater) ->
$runAfter: ['renderCode']
$runBefore: ['writeCode']
$process: (docs) ->
return unless globalConfig.project
author =
name: 'changeme'
email: 'PI:PASSWORD:<PASSWORD>END_PI'
description = 'changeme'
summary = description
homepage = 'https://github.com/gampleman/praxis-client-generator'
deps = []
for {identifier, version} in dependencies.dependencies('gem-ruby')
deps.push("gem.add_dependency '#{identifier}'")
for {identifier, version} in dependencies.dependencies('gem-ruby-dev')
deps.push("gem.add_development_dependency '#{identifier}'")
docs.push {
type: 'ruby'
outputPath: 'Gemfile'
rendered: """
source 'https://rubygems.org'
gemspec
"""
}
path = _.snakeCase(globalConfig.moduleName)
docs.push {
type: 'ruby'
outputPath: globalConfig.moduleName + '.gemspec'
rendered: """
# -*- encoding: utf-8 -*-
require File.expand_path('../lib/#{path}/version', __FILE__)
Gem::Specification.new do |gem|
gem.authors = ["#{author.name}"]
gem.email = ["#{author.email}"]
gem.description = %q{#{description}}
gem.summary = %q{#{summary}}
gem.homepage = "#{homepage}" # changeme
gem.files = `git ls-files`.split($\\)
gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) }
gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
gem.name = "#{path}"
gem.require_paths = ["lib"]
gem.version = #{globalConfig.moduleName}::VERSION
gem.license = 'MIT'
#{deps.join('\n')}
end
"""
}
execLater 'bundle install'
docs
|
[
{
"context": " 'count'\n if prefix == ''\n key = 'count'\n else\n key = '_count'\n else",
"end": 6258,
"score": 0.6865840554237366,
"start": 6253,
"tag": "KEY",
"value": "count"
},
{
"context": " key = 'count'\n else\n key =... | sprocs/cube.coffee | lmaccherone/documentdb-lumenize | 71 | module.exports = (memo) ->
# utils
utils = {}
utils.assert = (exp, message) ->
if (!exp)
throw new Error(message)
# Uses the properties of obj1, so will still match if obj2 has extra properties.
utils.match = (obj1, obj2) ->
for key, value of obj1
if (value != obj2[key])
return false
return true
utils.exactMatch = (a, b) ->
return true if a is b
atype = typeof(a);
btype = typeof(b)
return false if atype isnt btype
return false if (!a and b) or (a and !b)
return false if atype isnt 'object'
return false if a.length and (a.length isnt b.length)
return false for key, val of a when !(key of b) or not exactMatch(val, b[key])
return true
# At the top level, it will match even if obj1 is missing some elements that are in obj2, but at the lower levels, it must be an exact match.
utils.filterMatch = (obj1, obj2) ->
unless type(obj1) is 'object' and type(obj2) is 'object'
throw new Error('obj1 and obj2 must both be objects when calling filterMatch')
for key, value of obj1
if not exactMatch(value, obj2[key])
return false
return true
utils.trim = (val) ->
return if String::trim? then val.trim() else val.replace(/^\s+|\s+$/g, "")
utils.startsWith = (bigString, potentialStartString) ->
return bigString.substring(0, potentialStartString.length) == potentialStartString
utils.isArray = (a) ->
return Object.prototype.toString.apply(a) == '[object Array]'
utils.type = do -> # from http://arcturo.github.com/library/coffeescript/07_the_bad_parts.html
classToType = {}
for name in "Boolean Number String Function Array Date RegExp Undefined Null".split(" ")
classToType["[object " + name + "]"] = name.toLowerCase()
(obj) ->
strType = Object::toString.call(obj)
classToType[strType] or "object"
utils.clone = (obj) ->
if not obj? or typeof obj isnt 'object'
return obj
if obj instanceof Date
return new Date(obj.getTime())
if obj instanceof RegExp
flags = ''
flags += 'g' if obj.global?
flags += 'i' if obj.ignoreCase?
flags += 'm' if obj.multiline?
flags += 'y' if obj.sticky?
return new RegExp(obj.source, flags)
newInstance = new obj.constructor()
for key of obj
newInstance[key] = utils.clone(obj[key])
return newInstance
utils.keys = Object.keys or (obj) ->
return (key for key, val of obj)
utils.values = (obj) ->
return (val for key, val of obj)
utils.compare = (a, b) -> # Used for sorting any type
if a is null
return 1
if b is null
return -1
switch type(a)
when 'number', 'boolean', 'date'
return b - a
when 'array'
for value, index in a
if b.length - 1 >= index and value < b[index]
return 1
if b.length - 1 >= index and value > b[index]
return -1
if a.length < b.length
return 1
else if a.length > b.length
return -1
else
return 0
when 'object', 'string'
aString = JSON.stringify(a)
bString = JSON.stringify(b)
if aString < bString
return 1
else if aString > bString
return -1
else
return 0
else
throw new Error("Do not know how to sort objects of type #{utils.type(a)}.")
# dataTransform
csvStyleArray_To_ArrayOfMaps = (csvStyleArray, rowKeys) ->
###
@method csvStyleArray_To_ArrayOfMaps
@param {Array[]} csvStyleArray The first row is usually the list of column headers but if not, you can
provide your own such list in the second parameter
@param {String[]} [rowKeys] specify the column headers like `['column1', 'column2']`. If not provided, it will use
the first row of the csvStyleArray
@return {Object[]}
`csvStyleArry_To_ArryOfMaps` is a convenience function that will convert a csvStyleArray like:
{csvStyleArray_To_ArrayOfMaps} = require('../')
csvStyleArray = [
['column1', 'column2'],
[1 , 2 ],
[3 , 4 ],
[5 , 6 ]
]
to an Array of Maps like this:
console.log(csvStyleArray_To_ArrayOfMaps(csvStyleArray))
# [ { column1: 1, column2: 2 },
# { column1: 3, column2: 4 },
# { column1: 5, column2: 6 } ]
`
###
arrayOfMaps = []
if rowKeys?
i = 0
else
rowKeys = csvStyleArray[0]
i = 1
tableLength = csvStyleArray.length
while i < tableLength
inputRow = csvStyleArray[i]
outputRow = {}
for key, index in rowKeys
outputRow[key] = inputRow[index]
arrayOfMaps.push(outputRow)
i++
return arrayOfMaps
arrayOfMaps_To_CSVStyleArray = (arrayOfMaps, keys) ->
###
@method arrayOfMaps_To_CSVStyleArray
@param {Object[]} arrayOfMaps
@param {Object} [keys] If not provided, it will use the first row and get all fields
@return {Array[]} The first row will be the column headers
`arrayOfMaps_To_CSVStyleArray` is a convenience function that will convert an array of maps like:
{arrayOfMaps_To_CSVStyleArray} = require('../')
arrayOfMaps = [
{column1: 10000, column2: 20000},
{column1: 30000, column2: 40000},
{column1: 50000, column2: 60000}
]
to a CSV-style array like this:
console.log(arrayOfMaps_To_CSVStyleArray(arrayOfMaps))
# [ [ 'column1', 'column2' ],
# [ 10000, 20000 ],
# [ 30000, 40000 ],
# [ 50000, 60000 ] ]
`
###
if arrayOfMaps.length == 0
return []
csvStyleArray = []
outRow = []
unless keys?
keys = []
for key, value of arrayOfMaps[0]
keys.push(key)
csvStyleArray.push(keys)
for inRow in arrayOfMaps
outRow = []
for key in keys
outRow.push(inRow[key])
csvStyleArray.push(outRow)
return csvStyleArray
# functions
_populateDependentValues = (values, dependencies, dependentValues = {}, prefix = '') ->
out = {}
for d in dependencies
if d == 'count'
if prefix == ''
key = 'count'
else
key = '_count'
else
key = prefix + d
unless dependentValues[key]?
dependentValues[key] = functions[d](values, undefined, undefined, dependentValues, prefix)
out[d] = dependentValues[key]
return out
###
@method sum
@static
@param {Number[]} [values] Must either provide values or oldResult and newValues
@param {Number} [oldResult] for incremental calculation
@param {Number[]} [newValues] for incremental calculation
@return {Number} The sum of the values
###
###
@class functions
Rules about dependencies:
* If a function can be calculated incrementally from an oldResult and newValues, then you do not need to specify dependencies
* If a funciton can be calculated from other incrementally calculable results, then you need only specify those dependencies
* If a function needs the full list of values to be calculated (like percentile coverage), then you must specify 'values'
* To support the direct passing in of OLAP cube cells, you can provide a prefix (field name) so the key in dependentValues
can be generated
* 'count' is special and does not use a prefix because it is not dependent up a particular field
* You should calculate the dependencies before you calculate the thing that is depedent. The OLAP cube does some
checking to confirm you've done this.
###
functions = {}
functions.sum = (values, oldResult, newValues) ->
if oldResult?
temp = oldResult
tempValues = newValues
else
temp = 0
tempValues = values
for v in tempValues
temp += v
return temp
###
@method product
@static
@param {Number[]} [values] Must either provide values or oldResult and newValues
@param {Number} [oldResult] for incremental calculation
@param {Number[]} [newValues] for incremental calculation
@return {Number} The product of the values
###
functions.product = (values, oldResult, newValues) ->
if oldResult?
temp = oldResult
tempValues = newValues
else
temp = 1
tempValues = values
for v in tempValues
temp = temp * v
return temp
###
@method sumSquares
@static
@param {Number[]} [values] Must either provide values or oldResult and newValues
@param {Number} [oldResult] for incremental calculation
@param {Number[]} [newValues] for incremental calculation
@return {Number} The sum of the squares of the values
###
functions.sumSquares = (values, oldResult, newValues) ->
if oldResult?
temp = oldResult
tempValues = newValues
else
temp = 0
tempValues = values
for v in tempValues
temp += v * v
return temp
###
@method sumCubes
@static
@param {Number[]} [values] Must either provide values or oldResult and newValues
@param {Number} [oldResult] for incremental calculation
@param {Number[]} [newValues] for incremental calculation
@return {Number} The sum of the cubes of the values
###
functions.sumCubes = (values, oldResult, newValues) ->
if oldResult?
temp = oldResult
tempValues = newValues
else
temp = 0
tempValues = values
for v in tempValues
temp += v * v * v
return temp
###
@method lastValue
@static
@param {Number[]} [values] Must either provide values or newValues
@param {Number} [oldResult] Not used. It is included to make the interface consistent.
@param {Number[]} [newValues] for incremental calculation
@return {Number} The last value
###
functions.lastValue = (values, oldResult, newValues) ->
if newValues?
return newValues[newValues.length - 1]
return values[values.length - 1]
###
@method firstValue
@static
@param {Number[]} [values] Must either provide values or oldResult
@param {Number} [oldResult] for incremental calculation
@param {Number[]} [newValues] Not used. It is included to make the interface consistent.
@return {Number} The first value
###
functions.firstValue = (values, oldResult, newValues) ->
if oldResult?
return oldResult
return values[0]
###
@method count
@static
@param {Number[]} [values] Must either provide values or oldResult and newValues
@param {Number} [oldResult] for incremental calculation
@param {Number[]} [newValues] for incremental calculation
@return {Number} The length of the values Array
###
functions.count = (values, oldResult, newValues) ->
if oldResult?
return oldResult + newValues.length
return values.length
###
@method min
@static
@param {Number[]} [values] Must either provide values or oldResult and newValues
@param {Number} [oldResult] for incremental calculation
@param {Number[]} [newValues] for incremental calculation
@return {Number} The minimum value or null if no values
###
functions.min = (values, oldResult, newValues) ->
if oldResult?
return functions.min(newValues.concat([oldResult]))
if values.length == 0
return null
temp = values[0]
for v in values
if v < temp
temp = v
return temp
###
@method max
@static
@param {Number[]} [values] Must either provide values or oldResult and newValues
@param {Number} [oldResult] for incremental calculation
@param {Number[]} [newValues] for incremental calculation
@return {Number} The maximum value or null if no values
###
functions.max = (values, oldResult, newValues) ->
if oldResult?
return functions.max(newValues.concat([oldResult]))
if values.length == 0
return null
temp = values[0]
for v in values
if v > temp
temp = v
return temp
###
@method values
@static
@param {Object[]} [values] Must either provide values or oldResult and newValues
@param {Number} [oldResult] for incremental calculation
@param {Number[]} [newValues] for incremental calculation
@return {Array} All values (allows duplicates). Can be used for drill down.
###
functions.values = (values, oldResult, newValues) ->
if oldResult?
return oldResult.concat(newValues)
return values
# temp = []
# for v in values
# temp.push(v)
# return temp
###
@method uniqueValues
@static
@param {Object[]} [values] Must either provide values or oldResult and newValues
@param {Number} [oldResult] for incremental calculation
@param {Number[]} [newValues] for incremental calculation
@return {Array} Unique values. This is good for generating an OLAP dimension or drill down.
###
functions.uniqueValues = (values, oldResult, newValues) ->
temp = {}
if oldResult?
for r in oldResult
temp[r] = null
tempValues = newValues
else
tempValues = values
temp2 = []
for v in tempValues
temp[v] = null
for key, value of temp
temp2.push(key)
return temp2
###
@method average
@static
@param {Number[]} [values] Must either provide values or oldResult and newValues
@param {Number} [oldResult] not used by this function but included so all functions have a consistent signature
@param {Number[]} [newValues] not used by this function but included so all functions have a consistent signature
@param {Object} [dependentValues] If the function can be calculated from the results of other functions, this allows
you to provide those pre-calculated values.
@return {Number} The arithmetic mean
###
functions.average = (values, oldResult, newValues, dependentValues, prefix) ->
{count, sum} = _populateDependentValues(values, functions.average.dependencies, dependentValues, prefix)
if count is 0
return null
else
return sum / count
functions.average.dependencies = ['count', 'sum']
###
@method errorSquared
@static
@param {Number[]} [values] Must either provide values or oldResult and newValues
@param {Number} [oldResult] not used by this function but included so all functions have a consistent signature
@param {Number[]} [newValues] not used by this function but included so all functions have a consistent signature
@param {Object} [dependentValues] If the function can be calculated from the results of other functions, this allows
you to provide those pre-calculated values.
@return {Number} The error squared
###
functions.errorSquared = (values, oldResult, newValues, dependentValues, prefix) ->
{count, sum} = _populateDependentValues(values, functions.errorSquared.dependencies, dependentValues, prefix)
mean = sum / count
errorSquared = 0
for v in values
difference = v - mean
errorSquared += difference * difference
return errorSquared
functions.errorSquared.dependencies = ['count', 'sum']
###
@method variance
@static
@param {Number[]} [values] Must either provide values or oldResult and newValues
@param {Number} [oldResult] not used by this function but included so all functions have a consistent signature
@param {Number[]} [newValues] not used by this function but included so all functions have a consistent signature
@param {Object} [dependentValues] If the function can be calculated from the results of other functions, this allows
you to provide those pre-calculated values.
@return {Number} The variance
###
functions.variance = (values, oldResult, newValues, dependentValues, prefix) ->
{count, sum, sumSquares} = _populateDependentValues(values, functions.variance.dependencies, dependentValues, prefix)
if count is 0
return null
else if count is 1
return 0
else
return (count * sumSquares - sum * sum) / (count * (count - 1))
functions.variance.dependencies = ['count', 'sum', 'sumSquares']
###
@method standardDeviation
@static
@param {Number[]} [values] Must either provide values or oldResult and newValues
@param {Number} [oldResult] not used by this function but included so all functions have a consistent signature
@param {Number[]} [newValues] not used by this function but included so all functions have a consistent signature
@param {Object} [dependentValues] If the function can be calculated from the results of other functions, this allows
you to provide those pre-calculated values.
@return {Number} The standard deviation
###
functions.standardDeviation = (values, oldResult, newValues, dependentValues, prefix) ->
return Math.sqrt(functions.variance(values, oldResult, newValues, dependentValues, prefix))
functions.standardDeviation.dependencies = functions.variance.dependencies
###
@method percentileCreator
@static
@param {Number} p The percentile for the resulting function (50 = median, 75, 99, etc.)
@return {Function} A function to calculate the percentile
When the user passes in `p<n>` as an aggregation function, this `percentileCreator` is called to return the appropriate
percentile function. The returned function will find the `<n>`th percentile where `<n>` is some number in the form of
`##[.##]`. (e.g. `p40`, `p99`, `p99.9`).
There is no official definition of percentile. The most popular choices differ in the interpolation algorithm that they
use. The function returned by this `percentileCreator` uses the Excel interpolation algorithm which differs from the NIST
primary method. However, NIST lists something very similar to the Excel approach as an acceptible alternative. The only
difference seems to be for the edge case for when you have only two data points in your data set. Agreement with Excel,
NIST's acceptance of it as an alternative (almost), and the fact that it makes the most sense to me is why this approach
was chosen.
http://en.wikipedia.org/wiki/Percentile#Alternative_methods
Note: `median` is an alias for p50. The approach chosen for calculating p50 gives you the
exact same result as the definition for median even for edge cases like sets with only one or two data points.
###
functions.percentileCreator = (p) ->
f = (values, oldResult, newValues, dependentValues, prefix) ->
unless values?
{values} = _populateDependentValues(values, ['values'], dependentValues, prefix)
if values.length is 0
return null
sortfunc = (a, b) ->
return a - b
vLength = values.length
values.sort(sortfunc)
n = (p * (vLength - 1) / 100) + 1
k = Math.floor(n)
d = n - k
if n == 1
return values[1 - 1]
if n == vLength
return values[vLength - 1]
return values[k - 1] + d * (values[k] - values[k - 1])
f.dependencies = ['values']
return f
###
@method median
@static
@param {Number[]} [values] Must either provide values or oldResult and newValues
@param {Number} [oldResult] not used by this function but included so all functions have a consistent signature
@param {Number[]} [newValues] not used by this function but included so all functions have a consistent signature
@param {Object} [dependentValues] If the function can be calculated from the results of other functions, this allows
you to provide those pre-calculated values.
@return {Number} The median
###
functions.median = functions.percentileCreator(50)
functions.expandFandAs = (a) ->
###
@method expandFandAs
@static
@param {Object} a Will look like this `{as: 'mySum', f: 'sum', field: 'Points'}`
@return {Object} returns the expanded specification
Takes specifications for functions and expands them to include the actual function and 'as'. If you do not provide
an 'as' property, it will build it from the field name and function with an underscore between. Also, if the
'f' provided is a string, it is copied over to the 'metric' property before the 'f' property is replaced with the
actual function. `{field: 'a', f: 'sum'}` would expand to `{as: 'a_sum', field: 'a', metric: 'sum', f: [Function]}`.
###
utils.assert(a.f?, "'f' missing from specification: \n#{JSON.stringify(a, undefined, 4)}")
if utils.type(a.f) == 'function'
throw new Error('User defined metric functions not supported in a stored procedure')
utils.assert(a.as?, 'Must provide "as" field with your aggregation when providing a user defined function')
a.metric = a.f.toString()
else if functions[a.f]?
a.metric = a.f
a.f = functions[a.f]
else if a.f.substr(0, 1) == 'p'
a.metric = a.f
p = /\p(\d+(.\d+)?)/.exec(a.f)[1]
a.f = functions.percentileCreator(Number(p))
else
throw new Error("#{a.f} is not a recognized built-in function")
unless a.as?
if a.metric == 'count'
a.field = ''
a.metric = 'count'
a.as = "#{a.field}_#{a.metric}"
utils.assert(a.field? or a.f == 'count', "'field' missing from specification: \n#{JSON.stringify(a, undefined, 4)}")
return a
functions.expandMetrics = (metrics = [], addCountIfMissing = false, addValuesForCustomFunctions = false) ->
###
@method expandMetrics
@static
@private
This is called internally by several Lumenize Calculators. You should probably not call it.
###
confirmMetricAbove = (m, fieldName, aboveThisIndex) ->
if m is 'count'
lookingFor = '_' + m
else
lookingFor = fieldName + '_' + m
i = 0
while i < aboveThisIndex
currentRow = metrics[i]
if currentRow.as == lookingFor
return true
i++
# OK, it's not above, let's now see if it's below. Then throw error.
i = aboveThisIndex + 1
metricsLength = metrics.length
while i < metricsLength
currentRow = metrics[i]
if currentRow.as == lookingFor
throw new Error("Depdencies must appear before the metric they are dependant upon. #{m} appears after.")
i++
return false
assureDependenciesAbove = (dependencies, fieldName, aboveThisIndex) ->
for d in dependencies
unless confirmMetricAbove(d, fieldName, aboveThisIndex)
if d == 'count'
newRow = {f: 'count'}
else
newRow = {f: d, field: fieldName}
functions.expandFandAs(newRow)
metrics.unshift(newRow)
return false
return true
# add values for custom functions
if addValuesForCustomFunctions
for m, index in metrics
if utils.type(m.f) is 'function'
unless m.f.dependencies?
m.f.dependencies = []
unless m.f.dependencies[0] is 'values'
m.f.dependencies.push('values')
unless confirmMetricAbove('values', m.field, index)
valuesRow = {f: 'values', field: m.field}
functions.expandFandAs(valuesRow)
metrics.unshift(valuesRow)
hasCount = false
for m in metrics
functions.expandFandAs(m)
if m.metric is 'count'
hasCount = true
if addCountIfMissing and not hasCount
countRow = {f: 'count'}
functions.expandFandAs(countRow)
metrics.unshift(countRow)
index = 0
while index < metrics.length # intentionally not caching length because the loop can add rows
metricsRow = metrics[index]
if utils.type(metricsRow.f) is 'function'
dependencies = ['values']
if metricsRow.f.dependencies?
unless assureDependenciesAbove(metricsRow.f.dependencies, metricsRow.field, index)
index = -1
index++
return metrics
# OLAPCube
# !TODO: Add summary metrics
# !TODO: Be smart enough to move dependent metrics to the deriveFieldsOnOutput
class OLAPCube
###
@class OLAPCube
__An efficient, in-memory, incrementally-updateable, hierarchy-capable OLAP Cube implementation.__
[OLAP Cubes](http://en.wikipedia.org/wiki/OLAP_cube) are a powerful abstraction that makes it easier to do everything
from simple group-by operations to more complex multi-dimensional and hierarchical analysis. This implementation has
the same conceptual ancestry as implementations found in business intelligence and OLAP database solutions. However,
it is meant as a light weight alternative primarily targeting the goal of making it easier for developers to implement
desired analysis. It also supports serialization and incremental updating so it's ideally
suited for visualizations and analysis that are updated on a periodic or even continuous basis.
## Features ##
* In-memory
* Incrementally-updateable
* Serialize (`getStateForSaving()`) and deserialize (`newFromSavedState()`) to preserve aggregations between sessions
* Accepts simple JavaScript Objects as facts
* Storage and output as simple JavaScript Arrays of Objects
* Hierarchy (trees) derived from fact data assuming [materialized path](http://en.wikipedia.org/wiki/Materialized_path)
array model commonly used with NoSQL databases
## 2D Example ##
Let's walk through a simple 2D example from facts to output. Let's say you have this set of facts:
facts = [
{ProjectHierarchy: [1, 2, 3], Priority: 1, Points: 10},
{ProjectHierarchy: [1, 2, 4], Priority: 2, Points: 5 },
{ProjectHierarchy: [5] , Priority: 1, Points: 17},
{ProjectHierarchy: [1, 2] , Priority: 1, Points: 3 },
]
The ProjectHierarchy field models its hierarchy (tree) as an array containing a
[materialized path](http://en.wikipedia.org/wiki/Materialized_path). The first fact is "in" Project 3 whose parent is
Project 2, whose parent is Project 1. The second fact is "in" Project 4 whose parent is Project 2 which still has
Project 1 as its parent. Project 5 is another root Project like Project 1; and the fourth fact is "in" Project 2.
So the first fact will roll-up the tree and be aggregated against [1], and [1, 2] as well as [1, 2, 3]. Root Project 1
will get the data from all but the third fact which will get aggregated against root Project 5.
We specify the ProjectHierarchy field as a dimension of type 'hierarchy' and the Priorty field as a simple value dimension.
dimensions = [
{field: "ProjectHierarchy", type: 'hierarchy'},
{field: "Priority"}
]
This will create a 2D "cube" where each unique value for ProjectHierarchy and Priority defines a different cell.
Note, this happens to be a 2D "cube" (more commonly referred to as a [pivot table](http://en.wikipedia.org/wiki/Pivot_Table)),
but you can also have a 1D cube (a simple group-by), a 3D cube, or even an n-dimensional hypercube where n is greater than 3.
You can specify any number of metrics to be calculated for each cell in the cube.
metrics = [
{field: "Points", f: "sum", as: "Scope"}
]
You can use any of the aggregation functions found in Lumenize.functions except `count`. The count metric is
automatically tracked for each cell. The `as` specification is optional unless you provide a custom function. If missing,
it will build the name of the resulting metric from the field name and the function. So without the `as: "Scope"` the
second metric in the example above would have been named "Points_sum".
You can also use custom functions in the form of `f(values) -> return <some function of values>`.
Next, we build the config parameter from our dimension and metrics specifications.
config = {dimensions, metrics}
Hierarchy dimensions automatically roll up but you can also tell it to keep all totals by setting config.keepTotals to
true. The totals are then kept in the cells where one or more of the dimension values are set to `null`. Note, you
can also set keepTotals for individual dimension and should probably use that if you have more than a few dimensions
but we're going to set it globally here:
config.keepTotals = true
Now, let's create the cube.
{OLAPCube} = require('../')
cube = new OLAPCube(config, facts)
`getCell()` allows you to extract a single cell. The "total" cell for all facts where Priority = 1 can be found as follows:
console.log(cube.getCell({Priority: 1}))
# { ProjectHierarchy: null, Priority: 1, _count: 3, Scope: 30 }
Notice how the ProjectHierarchy field value is `null`. This is because it is a total cell for Priority dimension
for all ProjectHierarchy values. Think of `null` values in this context as wildcards.
Similarly, we can get the total for all descendants of ProjectHierarchy = [1] regarless of Priority as follows:
console.log(cube.getCell({ProjectHierarchy: [1]}))
# { ProjectHierarchy: [ 1 ], Priority: null, _count: 3, Scope: 18 }
`getCell()` uses the cellIndex so it's very efficient. Using `getCell()` and `getDimensionValues()`, you can iterate
over a slice of the OLAPCube. It is usually preferable to access the cells in place like this rather than the
traditional OLAP approach of extracting a slice for processing. However, there is a `slice()` method for extracting
a 2D slice.
rowValues = cube.getDimensionValues('ProjectHierarchy')
columnValues = cube.getDimensionValues('Priority')
s = OLAPCube._padToWidth('', 7) + ' | '
s += ((OLAPCube._padToWidth(JSON.stringify(c), 7) for c in columnValues).join(' | '))
s += ' | '
console.log(s)
for r in rowValues
s = OLAPCube._padToWidth(JSON.stringify(r), 7) + ' | '
for c in columnValues
cell = cube.getCell({ProjectHierarchy: r, Priority: c})
if cell?
cellString = JSON.stringify(cell._count)
else
cellString = ''
s += OLAPCube._padToWidth(cellString, 7) + ' | '
console.log(s)
# | null | 1 | 2 |
# null | 4 | 3 | 1 |
# [1] | 3 | 2 | 1 |
# [1,2] | 3 | 2 | 1 |
# [1,2,3] | 1 | 1 | |
# [1,2,4] | 1 | | 1 |
# [5] | 1 | 1 | |
Or you can just call `toString()` method which extracts a 2D slice for tabular display. Both approachs will work on
cubes of any number of dimensions two or greater. The manual example above extracted the `count` metric. We'll tell
the example below to extract the `Scope` metric.
console.log(cube.toString('ProjectHierarchy', 'Priority', 'Scope'))
# | || Total | 1 2|
# |==============================|
# |Total || 35 | 30 5|
# |------------------------------|
# |[1] || 18 | 13 5|
# |[1,2] || 18 | 13 5|
# |[1,2,3] || 10 | 10 |
# |[1,2,4] || 5 | 5|
# |[5] || 17 | 17 |
## Dimension types ##
The following dimension types are supported:
1. Single value
* Number
* String
* Does not work:
* Boolean - known to fail
* Object - may sorta work but sort-order at least is not obvious
* Date - not tested but may actually work
2. Arrays as materialized path for hierarchical (tree) data
3. Non-hierarchical Arrays ("tags")
There is no need to tell the OLAPCube what type to use with the exception of #2. In that case, add `type: 'hierarchy'`
to the dimensions row like this:
dimensions = [
{field: 'hierarchicalDimensionField', type: 'hierarchy'} #, ...
]
## Hierarchical (tree) data ##
This OLAP Cube implementation assumes your hierarchies (trees) are modeled as a
[materialized path](http://en.wikipedia.org/wiki/Materialized_path) array. This approach is commonly used with NoSQL databases like
[CouchDB](http://probablyprogramming.com/2008/07/04/storing-hierarchical-data-in-couchdb) and
[MongoDB (combining materialized path and array of ancestors)](http://docs.mongodb.org/manual/tutorial/model-tree-structures/)
and even SQL databases supporting array types like [Postgres](http://justcramer.com/2012/04/08/using-arrays-as-materialized-paths-in-postgres/).
This approach differs from the traditional OLAP/MDX fixed/named level hierarchy approach. In that approach, you assume
that the number of levels in the hierarchy are fixed. Also, each level in the hierarchy is either represented by a different
column (clothing example --> level 0: SEX column - mens vs womens; level 1: TYPE column - pants vs shorts vs shirts; etc.) or
predetermined ranges of values in a single field (date example --> level 0: year; level 1: quarter; level 2: month; etc.)
However, the approach used by this OLAPCube implementaion is the more general case, because it can easily simulate
fixed/named level hierachies whereas the reverse is not true. In the clothing example above, you would simply key
your dimension off of a derived field that was a combination of the SEX and TYPE columns (e.g. ['mens', 'pants'])
## Date/Time hierarchies ##
Lumenize is designed to work well with the tzTime library. Here is an example of taking a bunch of ISOString data
and doing timezone precise hierarchical roll up based upon the date segments (year, month).
data = [
{date: '2011-12-31T12:34:56.789Z', value: 10},
{date: '2012-01-05T12:34:56.789Z', value: 20},
{date: '2012-01-15T12:34:56.789Z', value: 30},
{date: '2012-02-01T00:00:01.000Z', value: 40},
{date: '2012-02-15T12:34:56.789Z', value: 50},
]
{Time} = require('../')
config =
deriveFieldsOnInput: [{
field: 'dateSegments',
f: (row) ->
return new Time(row.date, Time.MONTH, 'America/New_York').getSegmentsAsArray()
}]
metrics: [{field: 'value', f: 'sum'}]
dimensions: [{field: 'dateSegments', type: 'hierarchy'}]
cube = new OLAPCube(config, data)
console.log(cube.toString(undefined, undefined, 'value_sum'))
# | dateSegments | value_sum |
# |==========================|
# | [2011] | 10 |
# | [2011,12] | 10 |
# | [2012] | 140 |
# | [2012,1] | 90 |
# | [2012,2] | 50 |
Notice how '2012-02-01T00:00:01.000Z' got bucketed in January because the calculation was done in timezone
'America/New_York'.
## Non-hierarchical Array fields ##
If you don't specify type: 'hierarchy' and the OLAPCube sees a field whose value is an Array in a dimension field, the
data in that fact would get aggregated against each element in the Array. So a non-hierarchical Array field like
['x', 'y', 'z'] would get aggregated against 'x', 'y', and 'z' rather than ['x'], ['x', 'y'], and ['x','y','z]. This
functionality is useful for accomplishing analytics on tags, but it can be used in other powerful ways. For instance
let's say you have a list of events:
events = [
{name: 'Renaissance Festival', activeMonths: ['September', 'October']},
{name: 'Concert Series', activeMonths: ['July', 'August', 'September']},
{name: 'Fall Festival', activeMonths: ['September']}
]
You could figure out the number of events active in each month by specifying "activeMonths" as a dimension.
Lumenize.TimeInStateCalculator (and other calculators in Lumenize) use this technique.
###
constructor: (@userConfig, facts) ->
###
@constructor
@param {Object} config See Config options for details. DO NOT change the config settings after the OLAP class is instantiated.
@param {Object[]} [facts] Optional parameter allowing the population of the OLAPCube with an intitial set of facts
upon instantiation. Use addFacts() to add facts after instantiation.
@cfg {Object[]} [dimensions] Array which specifies the fields to use as dimension fields. If the field contains a
hierarchy array, say so in the row, (e.g. `{field: 'SomeFieldName', type: 'hierarchy'}`). Any array values that it
finds in the supplied facts will be assumed to be tags rather than a hierarchy specification unless `type: 'hierarchy'`
is specified.
For example, let's say you have a set of facts that look like this:
fact = {
dimensionField: 'a',
hierarchicalDimensionField: ['1','2','3'],
tagDimensionField: ['x', 'y', 'z'],
valueField: 10
}
Then a set of dimensions like this makes sense.
config.dimensions = [
{field: 'dimensionField'},
{field: 'hierarchicalDimensionField', type: 'hierarchy'},
{field: 'tagDimensionField', keepTotals: true}
]
Notice how a keepTotals can be set for an individual dimension. This is preferable to setting it for the entire
cube in cases where you don't want totals in all dimensions.
If no dimension config is provided, then you must use syntactic sugar like groupBy.
@cfg {String} [groupBy] Syntactic sugar for single-dimension/single-metric usage.
@cfg {String} [f] Syntactic sugar for single-dimension/single-metric usage. If provided, you must also provide
a `groupBy` config. If you provided a `groupBy` but no `f` or `field`, then the default `count` metric will be used.
@cfg {String} [field] Syntactic sugar for single-dimension/single-metric usage. If provided, you must also provide
a `groupBy` config. If you provided a `groupBy` but no `f` or `field`, then the default `count` metric will be used.
@cfg {Object[]} [metrics=[]] Array which specifies the metrics to calculate for each cell in the cube.
Example:
config = {}
config.metrics = [
{field: 'field3'}, # defaults to metrics: ['sum']
{field: 'field4', metrics: [
{f: 'sum'}, # will add a metric named field4_sum
{as: 'median4', f: 'p50'}, # renamed p50 to median4 from default of field4_p50
{as: 'myCount', f: (values) -> return values.length} # user-supplied function
]}
]
If you specify a field without any metrics, it will assume you want the sum but it will not automatically
add the sum metric to fields with a metrics specification. User-supplied aggregation functions are also supported as
shown in the 'myCount' metric above.
Note, if the metric has dependencies (e.g. average depends upon count and sum) it will automatically add those to
your metric definition. If you've already added a dependency but put it under a different "as", it's not smart
enough to sense that and it will add it again. Either live with the slight inefficiency and duplication or leave
dependency metrics named their default by not providing an "as" field.
@cfg {Boolean} [keepTotals=false] Setting this will add an additional total row (indicated with field: null) along
all dimensions. This setting can have an impact on the memory usage and performance of the OLAPCube so
if things are tight, only use it if you really need it. If you don't need it for all dimension, you can specify
keepTotals for individual dimensions.
@cfg {Boolean} [keepFacts=false] Setting this will cause the OLAPCube to keep track of the facts that contributed to
the metrics for each cell by adding an automatic 'facts' metric. Note, facts are restored after deserialization
as you would expect, but they are no longer tied to the original facts. This feature, especially after a restore
can eat up memory.
@cfg {Object[]} [deriveFieldsOnInput] An Array of Maps in the form `{field:'myField', f:(fact)->...}`
@cfg {Object[]} [deriveFieldsOnOutput] same format as deriveFieldsOnInput, except the callback is in the form `f(row)`
This is only called for dirty rows that were effected by the latest round of addFacts. It's more efficient to calculate things
like standard deviation and percentile coverage here than in config.metrics. You just have to remember to include the dependencies
in config.metrics. Standard deviation depends upon `sum` and `sumSquares`. Percentile coverage depends upon `values`.
In fact, if you are going to capture values anyway, all of the functions are most efficiently calculated here.
Maybe some day, I'll write the code to analyze your metrics and move them out to here if it improves efficiency.
###
@config = utils.clone(@userConfig)
@cells = []
@cellIndex = {}
@currentValues = {}
# Syntactic sugar for groupBy
if @config.groupBy?
@config.dimensions = [{field: @config.groupBy}]
if @config.f? and @config.field?
@config.metrics = [{field: @config.field, f: @config.f}]
utils.assert(@config.dimensions?, 'Must provide config.dimensions.')
unless @config.metrics?
@config.metrics = []
@_dimensionValues = {} # key: fieldName, value: {} where key: uniqueValue, value: the real key (not stringified)
for d in @config.dimensions
@_dimensionValues[d.field] = {}
unless @config.keepTotals
@config.keepTotals = false
unless @config.keepFacts
@config.keepFacts = false
for d in @config.dimensions
if @config.keepTotals or d.keepTotals
d.keepTotals = true
else
d.keepTotals = false
functions.expandMetrics(@config.metrics, true, true)
# Set required fields
requiredFieldsObject = {}
for m in @config.metrics
if m.field?.length > 0 # Should only be false if function is count
requiredFieldsObject[m.field] = null
@requiredMetricsFields = (key for key, value of requiredFieldsObject)
requiredFieldsObject = {}
for d in @config.dimensions
requiredFieldsObject[d.field] = null
@requiredDimensionFields = (key for key, value of requiredFieldsObject)
@summaryMetrics = {}
@addFacts(facts)
@_possibilities: (key, type, keepTotals) ->
switch utils.type(key)
when 'array'
if keepTotals
a = [null]
else
a = []
if type == 'hierarchy'
len = key.length
while len > 0
a.push(key.slice(0, len))
len--
else # assume it's a tag array
if keepTotals
a = [null].concat(key)
else
a = key
return a
when 'string', 'number'
if keepTotals
return [null, key]
else
return [key]
@_decrement: (a, rollover) ->
i = a.length - 1
a[i]--
while a[i] < 0
a[i] = rollover[i]
i--
if i < 0
return false
else
a[i]--
return true
_expandFact: (fact) ->
possibilitiesArray = []
countdownArray = []
rolloverArray = []
for d in @config.dimensions
p = OLAPCube._possibilities(fact[d.field], d.type, d.keepTotals)
possibilitiesArray.push(p)
countdownArray.push(p.length - 1)
rolloverArray.push(p.length - 1) # !TODO: If I need some speed, we could calculate the rolloverArray once and make a copy to the countdownArray for each run
for m in @config.metrics
@currentValues[m.field] = [fact[m.field]] # !TODO: Add default values here. I think this is the only place it is needed. write tests with incremental update to confirm.
out = []
more = true
while more
outRow = {}
for d, index in @config.dimensions
outRow[d.field] = possibilitiesArray[index][countdownArray[index]]
outRow._count = 1
if @config.keepFacts
outRow._facts = [fact]
for m in @config.metrics
outRow[m.as] = m.f([fact[m.field]], undefined, undefined, outRow, m.field + '_')
out.push(outRow)
more = OLAPCube._decrement(countdownArray, rolloverArray)
return out
@_extractFilter: (row, dimensions) ->
out = {}
for d in dimensions
out[d.field] = row[d.field]
return out
_mergeExpandedFactArray: (expandedFactArray) ->
for er in expandedFactArray
# set _dimensionValues
for d in @config.dimensions
fieldValue = er[d.field]
@_dimensionValues[d.field][JSON.stringify(fieldValue)] = fieldValue
# start merge
filterString = JSON.stringify(OLAPCube._extractFilter(er, @config.dimensions))
olapRow = @cellIndex[filterString]
if olapRow?
for m in @config.metrics
olapRow[m.as] = m.f(olapRow[m.field + '_values'], olapRow[m.as], @currentValues[m.field], olapRow, m.field + '_')
else
olapRow = er
@cellIndex[filterString] = olapRow
@cells.push(olapRow)
@dirtyRows[filterString] = olapRow
addFacts: (facts) ->
###
@method addFacts
Adds facts to the OLAPCube.
@chainable
@param {Object[]} facts An Array of facts to be aggregated into OLAPCube. Each fact is a Map where the keys are the field names
and the values are the field values (e.g. `{field1: 'a', field2: 5}`).
###
@dirtyRows = {}
if utils.type(facts) == 'array'
if facts.length <= 0
return
else
if facts?
facts = [facts]
else
return
if @config.deriveFieldsOnInput
for fact in facts
for d in @config.deriveFieldsOnInput
if d.as?
fieldName = d.as
else
fieldName = d.field
fact[fieldName] = d.f(fact)
for fact in facts
@addMissingFields(fact)
@currentValues = {}
expandedFactArray = @_expandFact(fact)
@_mergeExpandedFactArray(expandedFactArray)
# deriveFieldsOnOutput for @dirtyRows
if @config.deriveFieldsOnOutput?
for filterString, dirtyRow of @dirtyRows
for d in @config.deriveFieldsOnOutput
if d.as?
fieldName = d.as
else
fieldName = d.field
dirtyRow[fieldName] = d.f(dirtyRow)
@dirtyRows = {}
return this
addMissingFields: (fact) ->
for field in @requiredMetricsFields
if fact[field] is undefined
fact[field] = null
for field in @requiredDimensionFields
unless fact[field]?
fact[field] = '<missing>'
return fact
getCells: (filterObject) ->
###
@method getCells
Returns a subset of the cells that match the supplied filter. You can perform slice and dice operations using
this. If you have criteria for all of the dimensions, you are better off using `getCell()`. Most times, it's
better to iterate over the unique values for the dimensions of interest using `getCell()` in place of slice or
dice operations. However, there is a `slice()` method for extracting a 2D slice
@param {Object} [filterObject] Specifies the constraints that the returned cells must match in the form of
`{field1: value1, field2: value2}`. If this parameter is missing, the internal cells array is returned.
@return {Object[]} Returns the cells that match the supplied filter
###
unless filterObject?
return @cells
output = []
for c in @cells
if utils.filterMatch(filterObject, c)
output.push(c)
return output
getCell: (filter, defaultValue) ->
###
@method getCell
Returns the single cell matching the supplied filter. Iterating over the unique values for the dimensions of
interest, you can incrementally retrieve a slice or dice using this method. Since `getCell()` always uses an index,
in most cases, this is better than using `getCells()` to prefetch a slice or dice.
@param {Object} [filter={}] Specifies the constraints for the returned cell in the form of `{field1: value1, field2: value2}.
Any fields that are specified in config.dimensions that are missing from the filter are automatically filled in
with null. Calling `getCell()` with no parameter or `{}` will return the total of all dimensions (if @config.keepTotals=true).
@return {Object[]} Returns the cell that match the supplied filter
###
unless filter?
filter = {}
for key, value of filter
foundIt = false
for d in @config.dimensions
if d.field == key
foundIt = true
unless foundIt
throw new Error("#{key} is not a dimension for this cube.")
normalizedFilter = {}
for d in @config.dimensions
if filter.hasOwnProperty(d.field)
normalizedFilter[d.field] = filter[d.field]
else
if d.keepTotals
normalizedFilter[d.field] = null
else
throw new Error('Must set keepTotals to use getCell with a partial filter.')
cell = @cellIndex[JSON.stringify(normalizedFilter)]
if cell?
return cell
else
return defaultValue
getDimensionValues: (field, descending = false) ->
###
@method getDimensionValues
Returns the unique values for the specified dimension in sort order.
@param {String} field The field whose values you want
@param {Boolean} [descending=false] Set to true if you want them in reverse order
###
values = utils.values(@_dimensionValues[field])
values.sort(utils.compare)
unless descending
values.reverse()
return values
@roundToSignificance: (value, significance) ->
unless significance?
return value
multiple = 1 / significance
return Math.floor(value * multiple) / multiple
slice: (rows, columns, metric, significance) ->
###
@method slice
Extracts a 2D slice of the data. It outputs an array of arrays (JavaScript two-dimensional array) organized as the
C3 charting library would expect if submitting row-oriented data. Note, the output of this function is very similar
to the 2D toString() function output except the data is organized as a two-dimensional array instead of newline-separated
lines and the cells are filled with actual values instead of padded string representations of those values.
@return {[[]]} An array of arrays with the one row for the header and each row label
@param {String} [rows=<first dimension>]
@param {String} [columns=<second dimension>]
@param {String} [metric='count']
@param {Number} [significance] The multiple to which you want to round the bucket edges. 1 means whole numbers.
0.1 means to round to tenths. 0.01 to hundreds. Etc.
###
unless rows?
rows = @config.dimensions[0].field
unless columns?
columns = @config.dimensions[1].field
rowValues = @getDimensionValues(rows)
columnValues = @getDimensionValues(columns)
values = []
topRow = []
topRow.push('x')
for c, indexColumn in columnValues
if c is null
topRow.push('Total')
else
topRow.push(c)
values.push(topRow)
for r, indexRow in rowValues
valuesRow = []
if r is null
valuesRow.push('Total')
else
valuesRow.push(r)
for c, indexColumn in columnValues
filter = {}
filter[rows] = r
filter[columns] = c
cell = @getCell(filter)
if cell?
cellValue = OLAPCube.roundToSignificance(cell[metric], significance)
else
cellValue = null
valuesRow.push(cellValue)
values.push(valuesRow)
return values
@_padToWidth: (s, width, padCharacter = ' ', rightPad = false) ->
if s.length > width
return s.substr(0, width)
padding = new Array(width - s.length + 1).join(padCharacter)
if rightPad
return s + padding
else
return padding + s
getStateForSaving: (meta) ->
###
@method getStateForSaving
Enables saving the state of an OLAPCube.
@param {Object} [meta] An optional parameter that will be added to the serialized output and added to the meta field
within the deserialized OLAPCube
@return {Object} Returns an Ojbect representing the state of the OLAPCube. This Object is suitable for saving to
to an object store. Use the static method `newFromSavedState()` with this Object as the parameter to reconstitute the OLAPCube.
facts = [
{ProjectHierarchy: [1, 2, 3], Priority: 1},
{ProjectHierarchy: [1, 2, 4], Priority: 2},
{ProjectHierarchy: [5] , Priority: 1},
{ProjectHierarchy: [1, 2] , Priority: 1},
]
dimensions = [
{field: "ProjectHierarchy", type: 'hierarchy'},
{field: "Priority"}
]
config = {dimensions, metrics: []}
config.keepTotals = true
originalCube = new OLAPCube(config, facts)
dateString = '2012-12-27T12:34:56.789Z'
savedState = originalCube.getStateForSaving({upToDate: dateString})
restoredCube = OLAPCube.newFromSavedState(savedState)
newFacts = [
{ProjectHierarchy: [5], Priority: 3},
{ProjectHierarchy: [1, 2, 4], Priority: 1}
]
originalCube.addFacts(newFacts)
restoredCube.addFacts(newFacts)
console.log(restoredCube.toString() == originalCube.toString())
# true
console.log(restoredCube.meta.upToDate)
# 2012-12-27T12:34:56.789Z
###
out =
config: @userConfig
cellsAsCSVStyleArray: arrayOfMaps_To_CSVStyleArray(@cells) # !TODO: This makes the package smaller, but it's less well tested than using the Maps like the line below.
# cells: @cells
summaryMetrics: @summaryMetrics
if meta?
out.meta = meta
return out
@newFromSavedState: (p) ->
###
@method newFromSavedState
Deserializes a previously stringified OLAPCube and returns a new OLAPCube.
See `getStateForSaving()` documentation for a detailed example.
Note, if you have specified config.keepFacts = true, the values for the facts will be restored, however, they
will no longer be references to the original facts. For this reason, it's usually better to include a `values` or
`uniqueValues` metric on some ID field if you want fact drill-down support to survive a save and restore.
@static
@param {String/Object} p A String or Object from a previously saved OLAPCube state
@return {OLAPCube}
###
if utils.type(p) is 'string'
p = JSON.parse(p)
cube = new OLAPCube(p.config)
cube.summaryMetrics = p.summaryMetrics
if p.meta?
cube.meta = p.meta
if p.cellsAsCSVStyleArray?
cube.cells = csvStyleArray_To_ArrayOfMaps(p.cellsAsCSVStyleArray)
else
cube.cells = p.cells
cube.cellIndex = {}
cube._dimensionValues = {}
for d in cube.config.dimensions
cube._dimensionValues[d.field] = {}
for c in cube.cells
filterString = JSON.stringify(OLAPCube._extractFilter(c, cube.config.dimensions))
# rebuild cellIndex
cube.cellIndex[filterString] = c
# rebuild _dimensionValues
for d in cube.config.dimensions
fieldValue = c[d.field]
cube._dimensionValues[d.field][JSON.stringify(fieldValue)] = fieldValue
return cube
# cube
context = getContext()
collection = context.getCollection()
unless memo.continuation?
memo.continuation = null
if memo.savedCube?
theCube = OLAPCube.newFromSavedState(memo.savedCube)
else if memo.cubeConfig?
theCube = new OLAPCube(memo.cubeConfig)
else
throw new Error('cubeConfig or savedCube required')
memo.stillQueueing = true
query = () ->
setBody()
if memo.stillQueueing
responseOptions =
continuation: memo.continuation
pageSize: 1000
if memo.filterQuery?
memo.stillQueueing = collection.queryDocuments(collection.getSelfLink(), memo.filterQuery, responseOptions, onReadDocuments)
else
memo.stillQueueing = collection.readDocuments(collection.getSelfLink(), responseOptions, onReadDocuments)
onReadDocuments = (err, resources, options) ->
if err?
throw new Error(JSON.stringify(err))
theCube.addFacts(resources)
memo.savedCube = theCube.getStateForSaving()
memo.example = resources[0]
if options.continuation?
memo.continuation = options.continuation
query()
else
memo.continuation = null
setBody()
setBody = () ->
getContext().getResponse().setBody(memo)
query()
return memo
| 188134 | module.exports = (memo) ->
# utils
utils = {}
utils.assert = (exp, message) ->
if (!exp)
throw new Error(message)
# Uses the properties of obj1, so will still match if obj2 has extra properties.
utils.match = (obj1, obj2) ->
for key, value of obj1
if (value != obj2[key])
return false
return true
utils.exactMatch = (a, b) ->
return true if a is b
atype = typeof(a);
btype = typeof(b)
return false if atype isnt btype
return false if (!a and b) or (a and !b)
return false if atype isnt 'object'
return false if a.length and (a.length isnt b.length)
return false for key, val of a when !(key of b) or not exactMatch(val, b[key])
return true
# At the top level, it will match even if obj1 is missing some elements that are in obj2, but at the lower levels, it must be an exact match.
utils.filterMatch = (obj1, obj2) ->
unless type(obj1) is 'object' and type(obj2) is 'object'
throw new Error('obj1 and obj2 must both be objects when calling filterMatch')
for key, value of obj1
if not exactMatch(value, obj2[key])
return false
return true
utils.trim = (val) ->
return if String::trim? then val.trim() else val.replace(/^\s+|\s+$/g, "")
utils.startsWith = (bigString, potentialStartString) ->
return bigString.substring(0, potentialStartString.length) == potentialStartString
utils.isArray = (a) ->
return Object.prototype.toString.apply(a) == '[object Array]'
utils.type = do -> # from http://arcturo.github.com/library/coffeescript/07_the_bad_parts.html
classToType = {}
for name in "Boolean Number String Function Array Date RegExp Undefined Null".split(" ")
classToType["[object " + name + "]"] = name.toLowerCase()
(obj) ->
strType = Object::toString.call(obj)
classToType[strType] or "object"
utils.clone = (obj) ->
if not obj? or typeof obj isnt 'object'
return obj
if obj instanceof Date
return new Date(obj.getTime())
if obj instanceof RegExp
flags = ''
flags += 'g' if obj.global?
flags += 'i' if obj.ignoreCase?
flags += 'm' if obj.multiline?
flags += 'y' if obj.sticky?
return new RegExp(obj.source, flags)
newInstance = new obj.constructor()
for key of obj
newInstance[key] = utils.clone(obj[key])
return newInstance
utils.keys = Object.keys or (obj) ->
return (key for key, val of obj)
utils.values = (obj) ->
return (val for key, val of obj)
utils.compare = (a, b) -> # Used for sorting any type
if a is null
return 1
if b is null
return -1
switch type(a)
when 'number', 'boolean', 'date'
return b - a
when 'array'
for value, index in a
if b.length - 1 >= index and value < b[index]
return 1
if b.length - 1 >= index and value > b[index]
return -1
if a.length < b.length
return 1
else if a.length > b.length
return -1
else
return 0
when 'object', 'string'
aString = JSON.stringify(a)
bString = JSON.stringify(b)
if aString < bString
return 1
else if aString > bString
return -1
else
return 0
else
throw new Error("Do not know how to sort objects of type #{utils.type(a)}.")
# dataTransform
csvStyleArray_To_ArrayOfMaps = (csvStyleArray, rowKeys) ->
###
@method csvStyleArray_To_ArrayOfMaps
@param {Array[]} csvStyleArray The first row is usually the list of column headers but if not, you can
provide your own such list in the second parameter
@param {String[]} [rowKeys] specify the column headers like `['column1', 'column2']`. If not provided, it will use
the first row of the csvStyleArray
@return {Object[]}
`csvStyleArry_To_ArryOfMaps` is a convenience function that will convert a csvStyleArray like:
{csvStyleArray_To_ArrayOfMaps} = require('../')
csvStyleArray = [
['column1', 'column2'],
[1 , 2 ],
[3 , 4 ],
[5 , 6 ]
]
to an Array of Maps like this:
console.log(csvStyleArray_To_ArrayOfMaps(csvStyleArray))
# [ { column1: 1, column2: 2 },
# { column1: 3, column2: 4 },
# { column1: 5, column2: 6 } ]
`
###
arrayOfMaps = []
if rowKeys?
i = 0
else
rowKeys = csvStyleArray[0]
i = 1
tableLength = csvStyleArray.length
while i < tableLength
inputRow = csvStyleArray[i]
outputRow = {}
for key, index in rowKeys
outputRow[key] = inputRow[index]
arrayOfMaps.push(outputRow)
i++
return arrayOfMaps
arrayOfMaps_To_CSVStyleArray = (arrayOfMaps, keys) ->
###
@method arrayOfMaps_To_CSVStyleArray
@param {Object[]} arrayOfMaps
@param {Object} [keys] If not provided, it will use the first row and get all fields
@return {Array[]} The first row will be the column headers
`arrayOfMaps_To_CSVStyleArray` is a convenience function that will convert an array of maps like:
{arrayOfMaps_To_CSVStyleArray} = require('../')
arrayOfMaps = [
{column1: 10000, column2: 20000},
{column1: 30000, column2: 40000},
{column1: 50000, column2: 60000}
]
to a CSV-style array like this:
console.log(arrayOfMaps_To_CSVStyleArray(arrayOfMaps))
# [ [ 'column1', 'column2' ],
# [ 10000, 20000 ],
# [ 30000, 40000 ],
# [ 50000, 60000 ] ]
`
###
if arrayOfMaps.length == 0
return []
csvStyleArray = []
outRow = []
unless keys?
keys = []
for key, value of arrayOfMaps[0]
keys.push(key)
csvStyleArray.push(keys)
for inRow in arrayOfMaps
outRow = []
for key in keys
outRow.push(inRow[key])
csvStyleArray.push(outRow)
return csvStyleArray
# functions
_populateDependentValues = (values, dependencies, dependentValues = {}, prefix = '') ->
out = {}
for d in dependencies
if d == 'count'
if prefix == ''
key = '<KEY>'
else
key = <KEY>'
else
key = prefix + d
unless dependentValues[key]?
dependentValues[key] = functions[d](values, undefined, undefined, dependentValues, prefix)
out[d] = dependentValues[key]
return out
###
@method sum
@static
@param {Number[]} [values] Must either provide values or oldResult and newValues
@param {Number} [oldResult] for incremental calculation
@param {Number[]} [newValues] for incremental calculation
@return {Number} The sum of the values
###
###
@class functions
Rules about dependencies:
* If a function can be calculated incrementally from an oldResult and newValues, then you do not need to specify dependencies
* If a funciton can be calculated from other incrementally calculable results, then you need only specify those dependencies
* If a function needs the full list of values to be calculated (like percentile coverage), then you must specify 'values'
* To support the direct passing in of OLAP cube cells, you can provide a prefix (field name) so the key in dependentValues
can be generated
* 'count' is special and does not use a prefix because it is not dependent up a particular field
* You should calculate the dependencies before you calculate the thing that is depedent. The OLAP cube does some
checking to confirm you've done this.
###
functions = {}
functions.sum = (values, oldResult, newValues) ->
if oldResult?
temp = oldResult
tempValues = newValues
else
temp = 0
tempValues = values
for v in tempValues
temp += v
return temp
###
@method product
@static
@param {Number[]} [values] Must either provide values or oldResult and newValues
@param {Number} [oldResult] for incremental calculation
@param {Number[]} [newValues] for incremental calculation
@return {Number} The product of the values
###
functions.product = (values, oldResult, newValues) ->
if oldResult?
temp = oldResult
tempValues = newValues
else
temp = 1
tempValues = values
for v in tempValues
temp = temp * v
return temp
###
@method sumSquares
@static
@param {Number[]} [values] Must either provide values or oldResult and newValues
@param {Number} [oldResult] for incremental calculation
@param {Number[]} [newValues] for incremental calculation
@return {Number} The sum of the squares of the values
###
functions.sumSquares = (values, oldResult, newValues) ->
if oldResult?
temp = oldResult
tempValues = newValues
else
temp = 0
tempValues = values
for v in tempValues
temp += v * v
return temp
###
@method sumCubes
@static
@param {Number[]} [values] Must either provide values or oldResult and newValues
@param {Number} [oldResult] for incremental calculation
@param {Number[]} [newValues] for incremental calculation
@return {Number} The sum of the cubes of the values
###
functions.sumCubes = (values, oldResult, newValues) ->
if oldResult?
temp = oldResult
tempValues = newValues
else
temp = 0
tempValues = values
for v in tempValues
temp += v * v * v
return temp
###
@method lastValue
@static
@param {Number[]} [values] Must either provide values or newValues
@param {Number} [oldResult] Not used. It is included to make the interface consistent.
@param {Number[]} [newValues] for incremental calculation
@return {Number} The last value
###
functions.lastValue = (values, oldResult, newValues) ->
if newValues?
return newValues[newValues.length - 1]
return values[values.length - 1]
###
@method firstValue
@static
@param {Number[]} [values] Must either provide values or oldResult
@param {Number} [oldResult] for incremental calculation
@param {Number[]} [newValues] Not used. It is included to make the interface consistent.
@return {Number} The first value
###
functions.firstValue = (values, oldResult, newValues) ->
if oldResult?
return oldResult
return values[0]
###
@method count
@static
@param {Number[]} [values] Must either provide values or oldResult and newValues
@param {Number} [oldResult] for incremental calculation
@param {Number[]} [newValues] for incremental calculation
@return {Number} The length of the values Array
###
functions.count = (values, oldResult, newValues) ->
if oldResult?
return oldResult + newValues.length
return values.length
###
@method min
@static
@param {Number[]} [values] Must either provide values or oldResult and newValues
@param {Number} [oldResult] for incremental calculation
@param {Number[]} [newValues] for incremental calculation
@return {Number} The minimum value or null if no values
###
functions.min = (values, oldResult, newValues) ->
if oldResult?
return functions.min(newValues.concat([oldResult]))
if values.length == 0
return null
temp = values[0]
for v in values
if v < temp
temp = v
return temp
###
@method max
@static
@param {Number[]} [values] Must either provide values or oldResult and newValues
@param {Number} [oldResult] for incremental calculation
@param {Number[]} [newValues] for incremental calculation
@return {Number} The maximum value or null if no values
###
functions.max = (values, oldResult, newValues) ->
if oldResult?
return functions.max(newValues.concat([oldResult]))
if values.length == 0
return null
temp = values[0]
for v in values
if v > temp
temp = v
return temp
###
@method values
@static
@param {Object[]} [values] Must either provide values or oldResult and newValues
@param {Number} [oldResult] for incremental calculation
@param {Number[]} [newValues] for incremental calculation
@return {Array} All values (allows duplicates). Can be used for drill down.
###
functions.values = (values, oldResult, newValues) ->
if oldResult?
return oldResult.concat(newValues)
return values
# temp = []
# for v in values
# temp.push(v)
# return temp
###
@method uniqueValues
@static
@param {Object[]} [values] Must either provide values or oldResult and newValues
@param {Number} [oldResult] for incremental calculation
@param {Number[]} [newValues] for incremental calculation
@return {Array} Unique values. This is good for generating an OLAP dimension or drill down.
###
functions.uniqueValues = (values, oldResult, newValues) ->
temp = {}
if oldResult?
for r in oldResult
temp[r] = null
tempValues = newValues
else
tempValues = values
temp2 = []
for v in tempValues
temp[v] = null
for key, value of temp
temp2.push(key)
return temp2
###
@method average
@static
@param {Number[]} [values] Must either provide values or oldResult and newValues
@param {Number} [oldResult] not used by this function but included so all functions have a consistent signature
@param {Number[]} [newValues] not used by this function but included so all functions have a consistent signature
@param {Object} [dependentValues] If the function can be calculated from the results of other functions, this allows
you to provide those pre-calculated values.
@return {Number} The arithmetic mean
###
functions.average = (values, oldResult, newValues, dependentValues, prefix) ->
{count, sum} = _populateDependentValues(values, functions.average.dependencies, dependentValues, prefix)
if count is 0
return null
else
return sum / count
functions.average.dependencies = ['count', 'sum']
###
@method errorSquared
@static
@param {Number[]} [values] Must either provide values or oldResult and newValues
@param {Number} [oldResult] not used by this function but included so all functions have a consistent signature
@param {Number[]} [newValues] not used by this function but included so all functions have a consistent signature
@param {Object} [dependentValues] If the function can be calculated from the results of other functions, this allows
you to provide those pre-calculated values.
@return {Number} The error squared
###
functions.errorSquared = (values, oldResult, newValues, dependentValues, prefix) ->
{count, sum} = _populateDependentValues(values, functions.errorSquared.dependencies, dependentValues, prefix)
mean = sum / count
errorSquared = 0
for v in values
difference = v - mean
errorSquared += difference * difference
return errorSquared
functions.errorSquared.dependencies = ['count', 'sum']
###
@method variance
@static
@param {Number[]} [values] Must either provide values or oldResult and newValues
@param {Number} [oldResult] not used by this function but included so all functions have a consistent signature
@param {Number[]} [newValues] not used by this function but included so all functions have a consistent signature
@param {Object} [dependentValues] If the function can be calculated from the results of other functions, this allows
you to provide those pre-calculated values.
@return {Number} The variance
###
functions.variance = (values, oldResult, newValues, dependentValues, prefix) ->
{count, sum, sumSquares} = _populateDependentValues(values, functions.variance.dependencies, dependentValues, prefix)
if count is 0
return null
else if count is 1
return 0
else
return (count * sumSquares - sum * sum) / (count * (count - 1))
functions.variance.dependencies = ['count', 'sum', 'sumSquares']
###
@method standardDeviation
@static
@param {Number[]} [values] Must either provide values or oldResult and newValues
@param {Number} [oldResult] not used by this function but included so all functions have a consistent signature
@param {Number[]} [newValues] not used by this function but included so all functions have a consistent signature
@param {Object} [dependentValues] If the function can be calculated from the results of other functions, this allows
you to provide those pre-calculated values.
@return {Number} The standard deviation
###
functions.standardDeviation = (values, oldResult, newValues, dependentValues, prefix) ->
return Math.sqrt(functions.variance(values, oldResult, newValues, dependentValues, prefix))
functions.standardDeviation.dependencies = functions.variance.dependencies
###
@method percentileCreator
@static
@param {Number} p The percentile for the resulting function (50 = median, 75, 99, etc.)
@return {Function} A function to calculate the percentile
When the user passes in `p<n>` as an aggregation function, this `percentileCreator` is called to return the appropriate
percentile function. The returned function will find the `<n>`th percentile where `<n>` is some number in the form of
`##[.##]`. (e.g. `p40`, `p99`, `p99.9`).
There is no official definition of percentile. The most popular choices differ in the interpolation algorithm that they
use. The function returned by this `percentileCreator` uses the Excel interpolation algorithm which differs from the NIST
primary method. However, NIST lists something very similar to the Excel approach as an acceptible alternative. The only
difference seems to be for the edge case for when you have only two data points in your data set. Agreement with Excel,
NIST's acceptance of it as an alternative (almost), and the fact that it makes the most sense to me is why this approach
was chosen.
http://en.wikipedia.org/wiki/Percentile#Alternative_methods
Note: `median` is an alias for p50. The approach chosen for calculating p50 gives you the
exact same result as the definition for median even for edge cases like sets with only one or two data points.
###
functions.percentileCreator = (p) ->
f = (values, oldResult, newValues, dependentValues, prefix) ->
unless values?
{values} = _populateDependentValues(values, ['values'], dependentValues, prefix)
if values.length is 0
return null
sortfunc = (a, b) ->
return a - b
vLength = values.length
values.sort(sortfunc)
n = (p * (vLength - 1) / 100) + 1
k = Math.floor(n)
d = n - k
if n == 1
return values[1 - 1]
if n == vLength
return values[vLength - 1]
return values[k - 1] + d * (values[k] - values[k - 1])
f.dependencies = ['values']
return f
###
@method median
@static
@param {Number[]} [values] Must either provide values or oldResult and newValues
@param {Number} [oldResult] not used by this function but included so all functions have a consistent signature
@param {Number[]} [newValues] not used by this function but included so all functions have a consistent signature
@param {Object} [dependentValues] If the function can be calculated from the results of other functions, this allows
you to provide those pre-calculated values.
@return {Number} The median
###
functions.median = functions.percentileCreator(50)
functions.expandFandAs = (a) ->
###
@method expandFandAs
@static
@param {Object} a Will look like this `{as: 'mySum', f: 'sum', field: 'Points'}`
@return {Object} returns the expanded specification
Takes specifications for functions and expands them to include the actual function and 'as'. If you do not provide
an 'as' property, it will build it from the field name and function with an underscore between. Also, if the
'f' provided is a string, it is copied over to the 'metric' property before the 'f' property is replaced with the
actual function. `{field: 'a', f: 'sum'}` would expand to `{as: 'a_sum', field: 'a', metric: 'sum', f: [Function]}`.
###
utils.assert(a.f?, "'f' missing from specification: \n#{JSON.stringify(a, undefined, 4)}")
if utils.type(a.f) == 'function'
throw new Error('User defined metric functions not supported in a stored procedure')
utils.assert(a.as?, 'Must provide "as" field with your aggregation when providing a user defined function')
a.metric = a.f.toString()
else if functions[a.f]?
a.metric = a.f
a.f = functions[a.f]
else if a.f.substr(0, 1) == 'p'
a.metric = a.f
p = /\p(\d+(.\d+)?)/.exec(a.f)[1]
a.f = functions.percentileCreator(Number(p))
else
throw new Error("#{a.f} is not a recognized built-in function")
unless a.as?
if a.metric == 'count'
a.field = ''
a.metric = 'count'
a.as = "#{a.field}_#{a.metric}"
utils.assert(a.field? or a.f == 'count', "'field' missing from specification: \n#{JSON.stringify(a, undefined, 4)}")
return a
functions.expandMetrics = (metrics = [], addCountIfMissing = false, addValuesForCustomFunctions = false) ->
###
@method expandMetrics
@static
@private
This is called internally by several Lumenize Calculators. You should probably not call it.
###
confirmMetricAbove = (m, fieldName, aboveThisIndex) ->
if m is 'count'
lookingFor = '_' + m
else
lookingFor = fieldName + '_' + m
i = 0
while i < aboveThisIndex
currentRow = metrics[i]
if currentRow.as == lookingFor
return true
i++
# OK, it's not above, let's now see if it's below. Then throw error.
i = aboveThisIndex + 1
metricsLength = metrics.length
while i < metricsLength
currentRow = metrics[i]
if currentRow.as == lookingFor
throw new Error("Depdencies must appear before the metric they are dependant upon. #{m} appears after.")
i++
return false
assureDependenciesAbove = (dependencies, fieldName, aboveThisIndex) ->
for d in dependencies
unless confirmMetricAbove(d, fieldName, aboveThisIndex)
if d == 'count'
newRow = {f: 'count'}
else
newRow = {f: d, field: fieldName}
functions.expandFandAs(newRow)
metrics.unshift(newRow)
return false
return true
# add values for custom functions
if addValuesForCustomFunctions
for m, index in metrics
if utils.type(m.f) is 'function'
unless m.f.dependencies?
m.f.dependencies = []
unless m.f.dependencies[0] is 'values'
m.f.dependencies.push('values')
unless confirmMetricAbove('values', m.field, index)
valuesRow = {f: 'values', field: m.field}
functions.expandFandAs(valuesRow)
metrics.unshift(valuesRow)
hasCount = false
for m in metrics
functions.expandFandAs(m)
if m.metric is 'count'
hasCount = true
if addCountIfMissing and not hasCount
countRow = {f: 'count'}
functions.expandFandAs(countRow)
metrics.unshift(countRow)
index = 0
while index < metrics.length # intentionally not caching length because the loop can add rows
metricsRow = metrics[index]
if utils.type(metricsRow.f) is 'function'
dependencies = ['values']
if metricsRow.f.dependencies?
unless assureDependenciesAbove(metricsRow.f.dependencies, metricsRow.field, index)
index = -1
index++
return metrics
# OLAPCube
# !TODO: Add summary metrics
# !TODO: Be smart enough to move dependent metrics to the deriveFieldsOnOutput
class OLAPCube
###
@class OLAPCube
__An efficient, in-memory, incrementally-updateable, hierarchy-capable OLAP Cube implementation.__
[OLAP Cubes](http://en.wikipedia.org/wiki/OLAP_cube) are a powerful abstraction that makes it easier to do everything
from simple group-by operations to more complex multi-dimensional and hierarchical analysis. This implementation has
the same conceptual ancestry as implementations found in business intelligence and OLAP database solutions. However,
it is meant as a light weight alternative primarily targeting the goal of making it easier for developers to implement
desired analysis. It also supports serialization and incremental updating so it's ideally
suited for visualizations and analysis that are updated on a periodic or even continuous basis.
## Features ##
* In-memory
* Incrementally-updateable
* Serialize (`getStateForSaving()`) and deserialize (`newFromSavedState()`) to preserve aggregations between sessions
* Accepts simple JavaScript Objects as facts
* Storage and output as simple JavaScript Arrays of Objects
* Hierarchy (trees) derived from fact data assuming [materialized path](http://en.wikipedia.org/wiki/Materialized_path)
array model commonly used with NoSQL databases
## 2D Example ##
Let's walk through a simple 2D example from facts to output. Let's say you have this set of facts:
facts = [
{ProjectHierarchy: [1, 2, 3], Priority: 1, Points: 10},
{ProjectHierarchy: [1, 2, 4], Priority: 2, Points: 5 },
{ProjectHierarchy: [5] , Priority: 1, Points: 17},
{ProjectHierarchy: [1, 2] , Priority: 1, Points: 3 },
]
The ProjectHierarchy field models its hierarchy (tree) as an array containing a
[materialized path](http://en.wikipedia.org/wiki/Materialized_path). The first fact is "in" Project 3 whose parent is
Project 2, whose parent is Project 1. The second fact is "in" Project 4 whose parent is Project 2 which still has
Project 1 as its parent. Project 5 is another root Project like Project 1; and the fourth fact is "in" Project 2.
So the first fact will roll-up the tree and be aggregated against [1], and [1, 2] as well as [1, 2, 3]. Root Project 1
will get the data from all but the third fact which will get aggregated against root Project 5.
We specify the ProjectHierarchy field as a dimension of type 'hierarchy' and the Priorty field as a simple value dimension.
dimensions = [
{field: "ProjectHierarchy", type: 'hierarchy'},
{field: "Priority"}
]
This will create a 2D "cube" where each unique value for ProjectHierarchy and Priority defines a different cell.
Note, this happens to be a 2D "cube" (more commonly referred to as a [pivot table](http://en.wikipedia.org/wiki/Pivot_Table)),
but you can also have a 1D cube (a simple group-by), a 3D cube, or even an n-dimensional hypercube where n is greater than 3.
You can specify any number of metrics to be calculated for each cell in the cube.
metrics = [
{field: "Points", f: "sum", as: "Scope"}
]
You can use any of the aggregation functions found in Lumenize.functions except `count`. The count metric is
automatically tracked for each cell. The `as` specification is optional unless you provide a custom function. If missing,
it will build the name of the resulting metric from the field name and the function. So without the `as: "Scope"` the
second metric in the example above would have been named "Points_sum".
You can also use custom functions in the form of `f(values) -> return <some function of values>`.
Next, we build the config parameter from our dimension and metrics specifications.
config = {dimensions, metrics}
Hierarchy dimensions automatically roll up but you can also tell it to keep all totals by setting config.keepTotals to
true. The totals are then kept in the cells where one or more of the dimension values are set to `null`. Note, you
can also set keepTotals for individual dimension and should probably use that if you have more than a few dimensions
but we're going to set it globally here:
config.keepTotals = true
Now, let's create the cube.
{OLAPCube} = require('../')
cube = new OLAPCube(config, facts)
`getCell()` allows you to extract a single cell. The "total" cell for all facts where Priority = 1 can be found as follows:
console.log(cube.getCell({Priority: 1}))
# { ProjectHierarchy: null, Priority: 1, _count: 3, Scope: 30 }
Notice how the ProjectHierarchy field value is `null`. This is because it is a total cell for Priority dimension
for all ProjectHierarchy values. Think of `null` values in this context as wildcards.
Similarly, we can get the total for all descendants of ProjectHierarchy = [1] regarless of Priority as follows:
console.log(cube.getCell({ProjectHierarchy: [1]}))
# { ProjectHierarchy: [ 1 ], Priority: null, _count: 3, Scope: 18 }
`getCell()` uses the cellIndex so it's very efficient. Using `getCell()` and `getDimensionValues()`, you can iterate
over a slice of the OLAPCube. It is usually preferable to access the cells in place like this rather than the
traditional OLAP approach of extracting a slice for processing. However, there is a `slice()` method for extracting
a 2D slice.
rowValues = cube.getDimensionValues('ProjectHierarchy')
columnValues = cube.getDimensionValues('Priority')
s = OLAPCube._padToWidth('', 7) + ' | '
s += ((OLAPCube._padToWidth(JSON.stringify(c), 7) for c in columnValues).join(' | '))
s += ' | '
console.log(s)
for r in rowValues
s = OLAPCube._padToWidth(JSON.stringify(r), 7) + ' | '
for c in columnValues
cell = cube.getCell({ProjectHierarchy: r, Priority: c})
if cell?
cellString = JSON.stringify(cell._count)
else
cellString = ''
s += OLAPCube._padToWidth(cellString, 7) + ' | '
console.log(s)
# | null | 1 | 2 |
# null | 4 | 3 | 1 |
# [1] | 3 | 2 | 1 |
# [1,2] | 3 | 2 | 1 |
# [1,2,3] | 1 | 1 | |
# [1,2,4] | 1 | | 1 |
# [5] | 1 | 1 | |
Or you can just call `toString()` method which extracts a 2D slice for tabular display. Both approachs will work on
cubes of any number of dimensions two or greater. The manual example above extracted the `count` metric. We'll tell
the example below to extract the `Scope` metric.
console.log(cube.toString('ProjectHierarchy', 'Priority', 'Scope'))
# | || Total | 1 2|
# |==============================|
# |Total || 35 | 30 5|
# |------------------------------|
# |[1] || 18 | 13 5|
# |[1,2] || 18 | 13 5|
# |[1,2,3] || 10 | 10 |
# |[1,2,4] || 5 | 5|
# |[5] || 17 | 17 |
## Dimension types ##
The following dimension types are supported:
1. Single value
* Number
* String
* Does not work:
* Boolean - known to fail
* Object - may sorta work but sort-order at least is not obvious
* Date - not tested but may actually work
2. Arrays as materialized path for hierarchical (tree) data
3. Non-hierarchical Arrays ("tags")
There is no need to tell the OLAPCube what type to use with the exception of #2. In that case, add `type: 'hierarchy'`
to the dimensions row like this:
dimensions = [
{field: 'hierarchicalDimensionField', type: 'hierarchy'} #, ...
]
## Hierarchical (tree) data ##
This OLAP Cube implementation assumes your hierarchies (trees) are modeled as a
[materialized path](http://en.wikipedia.org/wiki/Materialized_path) array. This approach is commonly used with NoSQL databases like
[CouchDB](http://probablyprogramming.com/2008/07/04/storing-hierarchical-data-in-couchdb) and
[MongoDB (combining materialized path and array of ancestors)](http://docs.mongodb.org/manual/tutorial/model-tree-structures/)
and even SQL databases supporting array types like [Postgres](http://justcramer.com/2012/04/08/using-arrays-as-materialized-paths-in-postgres/).
This approach differs from the traditional OLAP/MDX fixed/named level hierarchy approach. In that approach, you assume
that the number of levels in the hierarchy are fixed. Also, each level in the hierarchy is either represented by a different
column (clothing example --> level 0: SEX column - mens vs womens; level 1: TYPE column - pants vs shorts vs shirts; etc.) or
predetermined ranges of values in a single field (date example --> level 0: year; level 1: quarter; level 2: month; etc.)
However, the approach used by this OLAPCube implementaion is the more general case, because it can easily simulate
fixed/named level hierachies whereas the reverse is not true. In the clothing example above, you would simply key
your dimension off of a derived field that was a combination of the SEX and TYPE columns (e.g. ['mens', 'pants'])
## Date/Time hierarchies ##
Lumenize is designed to work well with the tzTime library. Here is an example of taking a bunch of ISOString data
and doing timezone precise hierarchical roll up based upon the date segments (year, month).
data = [
{date: '2011-12-31T12:34:56.789Z', value: 10},
{date: '2012-01-05T12:34:56.789Z', value: 20},
{date: '2012-01-15T12:34:56.789Z', value: 30},
{date: '2012-02-01T00:00:01.000Z', value: 40},
{date: '2012-02-15T12:34:56.789Z', value: 50},
]
{Time} = require('../')
config =
deriveFieldsOnInput: [{
field: 'dateSegments',
f: (row) ->
return new Time(row.date, Time.MONTH, 'America/New_York').getSegmentsAsArray()
}]
metrics: [{field: 'value', f: 'sum'}]
dimensions: [{field: 'dateSegments', type: 'hierarchy'}]
cube = new OLAPCube(config, data)
console.log(cube.toString(undefined, undefined, 'value_sum'))
# | dateSegments | value_sum |
# |==========================|
# | [2011] | 10 |
# | [2011,12] | 10 |
# | [2012] | 140 |
# | [2012,1] | 90 |
# | [2012,2] | 50 |
Notice how '2012-02-01T00:00:01.000Z' got bucketed in January because the calculation was done in timezone
'America/New_York'.
## Non-hierarchical Array fields ##
If you don't specify type: 'hierarchy' and the OLAPCube sees a field whose value is an Array in a dimension field, the
data in that fact would get aggregated against each element in the Array. So a non-hierarchical Array field like
['x', 'y', 'z'] would get aggregated against 'x', 'y', and 'z' rather than ['x'], ['x', 'y'], and ['x','y','z]. This
functionality is useful for accomplishing analytics on tags, but it can be used in other powerful ways. For instance
let's say you have a list of events:
events = [
{name: 'Renaissance Festival', activeMonths: ['September', 'October']},
{name: 'Concert Series', activeMonths: ['July', 'August', 'September']},
{name: 'Fall Festival', activeMonths: ['September']}
]
You could figure out the number of events active in each month by specifying "activeMonths" as a dimension.
Lumenize.TimeInStateCalculator (and other calculators in Lumenize) use this technique.
###
constructor: (@userConfig, facts) ->
###
@constructor
@param {Object} config See Config options for details. DO NOT change the config settings after the OLAP class is instantiated.
@param {Object[]} [facts] Optional parameter allowing the population of the OLAPCube with an intitial set of facts
upon instantiation. Use addFacts() to add facts after instantiation.
@cfg {Object[]} [dimensions] Array which specifies the fields to use as dimension fields. If the field contains a
hierarchy array, say so in the row, (e.g. `{field: 'SomeFieldName', type: 'hierarchy'}`). Any array values that it
finds in the supplied facts will be assumed to be tags rather than a hierarchy specification unless `type: 'hierarchy'`
is specified.
For example, let's say you have a set of facts that look like this:
fact = {
dimensionField: 'a',
hierarchicalDimensionField: ['1','2','3'],
tagDimensionField: ['x', 'y', 'z'],
valueField: 10
}
Then a set of dimensions like this makes sense.
config.dimensions = [
{field: 'dimensionField'},
{field: 'hierarchicalDimensionField', type: 'hierarchy'},
{field: 'tagDimensionField', keepTotals: true}
]
Notice how a keepTotals can be set for an individual dimension. This is preferable to setting it for the entire
cube in cases where you don't want totals in all dimensions.
If no dimension config is provided, then you must use syntactic sugar like groupBy.
@cfg {String} [groupBy] Syntactic sugar for single-dimension/single-metric usage.
@cfg {String} [f] Syntactic sugar for single-dimension/single-metric usage. If provided, you must also provide
a `groupBy` config. If you provided a `groupBy` but no `f` or `field`, then the default `count` metric will be used.
@cfg {String} [field] Syntactic sugar for single-dimension/single-metric usage. If provided, you must also provide
a `groupBy` config. If you provided a `groupBy` but no `f` or `field`, then the default `count` metric will be used.
@cfg {Object[]} [metrics=[]] Array which specifies the metrics to calculate for each cell in the cube.
Example:
config = {}
config.metrics = [
{field: 'field3'}, # defaults to metrics: ['sum']
{field: 'field4', metrics: [
{f: 'sum'}, # will add a metric named field4_sum
{as: 'median4', f: 'p50'}, # renamed p50 to median4 from default of field4_p50
{as: 'myCount', f: (values) -> return values.length} # user-supplied function
]}
]
If you specify a field without any metrics, it will assume you want the sum but it will not automatically
add the sum metric to fields with a metrics specification. User-supplied aggregation functions are also supported as
shown in the 'myCount' metric above.
Note, if the metric has dependencies (e.g. average depends upon count and sum) it will automatically add those to
your metric definition. If you've already added a dependency but put it under a different "as", it's not smart
enough to sense that and it will add it again. Either live with the slight inefficiency and duplication or leave
dependency metrics named their default by not providing an "as" field.
@cfg {Boolean} [keepTotals=false] Setting this will add an additional total row (indicated with field: null) along
all dimensions. This setting can have an impact on the memory usage and performance of the OLAPCube so
if things are tight, only use it if you really need it. If you don't need it for all dimension, you can specify
keepTotals for individual dimensions.
@cfg {Boolean} [keepFacts=false] Setting this will cause the OLAPCube to keep track of the facts that contributed to
the metrics for each cell by adding an automatic 'facts' metric. Note, facts are restored after deserialization
as you would expect, but they are no longer tied to the original facts. This feature, especially after a restore
can eat up memory.
@cfg {Object[]} [deriveFieldsOnInput] An Array of Maps in the form `{field:'myField', f:(fact)->...}`
@cfg {Object[]} [deriveFieldsOnOutput] same format as deriveFieldsOnInput, except the callback is in the form `f(row)`
This is only called for dirty rows that were effected by the latest round of addFacts. It's more efficient to calculate things
like standard deviation and percentile coverage here than in config.metrics. You just have to remember to include the dependencies
in config.metrics. Standard deviation depends upon `sum` and `sumSquares`. Percentile coverage depends upon `values`.
In fact, if you are going to capture values anyway, all of the functions are most efficiently calculated here.
Maybe some day, I'll write the code to analyze your metrics and move them out to here if it improves efficiency.
###
@config = utils.clone(@userConfig)
@cells = []
@cellIndex = {}
@currentValues = {}
# Syntactic sugar for groupBy
if @config.groupBy?
@config.dimensions = [{field: @config.groupBy}]
if @config.f? and @config.field?
@config.metrics = [{field: @config.field, f: @config.f}]
utils.assert(@config.dimensions?, 'Must provide config.dimensions.')
unless @config.metrics?
@config.metrics = []
@_dimensionValues = {} # key: fieldName, value: {} where key: uniqueValue, value: the real key (not stringified)
for d in @config.dimensions
@_dimensionValues[d.field] = {}
unless @config.keepTotals
@config.keepTotals = false
unless @config.keepFacts
@config.keepFacts = false
for d in @config.dimensions
if @config.keepTotals or d.keepTotals
d.keepTotals = true
else
d.keepTotals = false
functions.expandMetrics(@config.metrics, true, true)
# Set required fields
requiredFieldsObject = {}
for m in @config.metrics
if m.field?.length > 0 # Should only be false if function is count
requiredFieldsObject[m.field] = null
@requiredMetricsFields = (key for key, value of requiredFieldsObject)
requiredFieldsObject = {}
for d in @config.dimensions
requiredFieldsObject[d.field] = null
@requiredDimensionFields = (key for key, value of requiredFieldsObject)
@summaryMetrics = {}
@addFacts(facts)
@_possibilities: (key, type, keepTotals) ->
switch utils.type(key)
when 'array'
if keepTotals
a = [null]
else
a = []
if type == 'hierarchy'
len = key.length
while len > 0
a.push(key.slice(0, len))
len--
else # assume it's a tag array
if keepTotals
a = [null].concat(key)
else
a = key
return a
when 'string', 'number'
if keepTotals
return [null, key]
else
return [key]
@_decrement: (a, rollover) ->
i = a.length - 1
a[i]--
while a[i] < 0
a[i] = rollover[i]
i--
if i < 0
return false
else
a[i]--
return true
_expandFact: (fact) ->
possibilitiesArray = []
countdownArray = []
rolloverArray = []
for d in @config.dimensions
p = OLAPCube._possibilities(fact[d.field], d.type, d.keepTotals)
possibilitiesArray.push(p)
countdownArray.push(p.length - 1)
rolloverArray.push(p.length - 1) # !TODO: If I need some speed, we could calculate the rolloverArray once and make a copy to the countdownArray for each run
for m in @config.metrics
@currentValues[m.field] = [fact[m.field]] # !TODO: Add default values here. I think this is the only place it is needed. write tests with incremental update to confirm.
out = []
more = true
while more
outRow = {}
for d, index in @config.dimensions
outRow[d.field] = possibilitiesArray[index][countdownArray[index]]
outRow._count = 1
if @config.keepFacts
outRow._facts = [fact]
for m in @config.metrics
outRow[m.as] = m.f([fact[m.field]], undefined, undefined, outRow, m.field + '_')
out.push(outRow)
more = OLAPCube._decrement(countdownArray, rolloverArray)
return out
@_extractFilter: (row, dimensions) ->
out = {}
for d in dimensions
out[d.field] = row[d.field]
return out
_mergeExpandedFactArray: (expandedFactArray) ->
for er in expandedFactArray
# set _dimensionValues
for d in @config.dimensions
fieldValue = er[d.field]
@_dimensionValues[d.field][JSON.stringify(fieldValue)] = fieldValue
# start merge
filterString = JSON.stringify(OLAPCube._extractFilter(er, @config.dimensions))
olapRow = @cellIndex[filterString]
if olapRow?
for m in @config.metrics
olapRow[m.as] = m.f(olapRow[m.field + '_values'], olapRow[m.as], @currentValues[m.field], olapRow, m.field + '_')
else
olapRow = er
@cellIndex[filterString] = olapRow
@cells.push(olapRow)
@dirtyRows[filterString] = olapRow
addFacts: (facts) ->
###
@method addFacts
Adds facts to the OLAPCube.
@chainable
@param {Object[]} facts An Array of facts to be aggregated into OLAPCube. Each fact is a Map where the keys are the field names
and the values are the field values (e.g. `{field1: 'a', field2: 5}`).
###
@dirtyRows = {}
if utils.type(facts) == 'array'
if facts.length <= 0
return
else
if facts?
facts = [facts]
else
return
if @config.deriveFieldsOnInput
for fact in facts
for d in @config.deriveFieldsOnInput
if d.as?
fieldName = d.as
else
fieldName = d.field
fact[fieldName] = d.f(fact)
for fact in facts
@addMissingFields(fact)
@currentValues = {}
expandedFactArray = @_expandFact(fact)
@_mergeExpandedFactArray(expandedFactArray)
# deriveFieldsOnOutput for @dirtyRows
if @config.deriveFieldsOnOutput?
for filterString, dirtyRow of @dirtyRows
for d in @config.deriveFieldsOnOutput
if d.as?
fieldName = d.as
else
fieldName = d.field
dirtyRow[fieldName] = d.f(dirtyRow)
@dirtyRows = {}
return this
addMissingFields: (fact) ->
for field in @requiredMetricsFields
if fact[field] is undefined
fact[field] = null
for field in @requiredDimensionFields
unless fact[field]?
fact[field] = '<missing>'
return fact
getCells: (filterObject) ->
###
@method getCells
Returns a subset of the cells that match the supplied filter. You can perform slice and dice operations using
this. If you have criteria for all of the dimensions, you are better off using `getCell()`. Most times, it's
better to iterate over the unique values for the dimensions of interest using `getCell()` in place of slice or
dice operations. However, there is a `slice()` method for extracting a 2D slice
@param {Object} [filterObject] Specifies the constraints that the returned cells must match in the form of
`{field1: value1, field2: value2}`. If this parameter is missing, the internal cells array is returned.
@return {Object[]} Returns the cells that match the supplied filter
###
unless filterObject?
return @cells
output = []
for c in @cells
if utils.filterMatch(filterObject, c)
output.push(c)
return output
getCell: (filter, defaultValue) ->
###
@method getCell
Returns the single cell matching the supplied filter. Iterating over the unique values for the dimensions of
interest, you can incrementally retrieve a slice or dice using this method. Since `getCell()` always uses an index,
in most cases, this is better than using `getCells()` to prefetch a slice or dice.
@param {Object} [filter={}] Specifies the constraints for the returned cell in the form of `{field1: value1, field2: value2}.
Any fields that are specified in config.dimensions that are missing from the filter are automatically filled in
with null. Calling `getCell()` with no parameter or `{}` will return the total of all dimensions (if @config.keepTotals=true).
@return {Object[]} Returns the cell that match the supplied filter
###
unless filter?
filter = {}
for key, value of filter
foundIt = false
for d in @config.dimensions
if d.field == key
foundIt = true
unless foundIt
throw new Error("#{key} is not a dimension for this cube.")
normalizedFilter = {}
for d in @config.dimensions
if filter.hasOwnProperty(d.field)
normalizedFilter[d.field] = filter[d.field]
else
if d.keepTotals
normalizedFilter[d.field] = null
else
throw new Error('Must set keepTotals to use getCell with a partial filter.')
cell = @cellIndex[JSON.stringify(normalizedFilter)]
if cell?
return cell
else
return defaultValue
getDimensionValues: (field, descending = false) ->
###
@method getDimensionValues
Returns the unique values for the specified dimension in sort order.
@param {String} field The field whose values you want
@param {Boolean} [descending=false] Set to true if you want them in reverse order
###
values = utils.values(@_dimensionValues[field])
values.sort(utils.compare)
unless descending
values.reverse()
return values
@roundToSignificance: (value, significance) ->
unless significance?
return value
multiple = 1 / significance
return Math.floor(value * multiple) / multiple
slice: (rows, columns, metric, significance) ->
###
@method slice
Extracts a 2D slice of the data. It outputs an array of arrays (JavaScript two-dimensional array) organized as the
C3 charting library would expect if submitting row-oriented data. Note, the output of this function is very similar
to the 2D toString() function output except the data is organized as a two-dimensional array instead of newline-separated
lines and the cells are filled with actual values instead of padded string representations of those values.
@return {[[]]} An array of arrays with the one row for the header and each row label
@param {String} [rows=<first dimension>]
@param {String} [columns=<second dimension>]
@param {String} [metric='count']
@param {Number} [significance] The multiple to which you want to round the bucket edges. 1 means whole numbers.
0.1 means to round to tenths. 0.01 to hundreds. Etc.
###
unless rows?
rows = @config.dimensions[0].field
unless columns?
columns = @config.dimensions[1].field
rowValues = @getDimensionValues(rows)
columnValues = @getDimensionValues(columns)
values = []
topRow = []
topRow.push('x')
for c, indexColumn in columnValues
if c is null
topRow.push('Total')
else
topRow.push(c)
values.push(topRow)
for r, indexRow in rowValues
valuesRow = []
if r is null
valuesRow.push('Total')
else
valuesRow.push(r)
for c, indexColumn in columnValues
filter = {}
filter[rows] = r
filter[columns] = c
cell = @getCell(filter)
if cell?
cellValue = OLAPCube.roundToSignificance(cell[metric], significance)
else
cellValue = null
valuesRow.push(cellValue)
values.push(valuesRow)
return values
@_padToWidth: (s, width, padCharacter = ' ', rightPad = false) ->
if s.length > width
return s.substr(0, width)
padding = new Array(width - s.length + 1).join(padCharacter)
if rightPad
return s + padding
else
return padding + s
getStateForSaving: (meta) ->
###
@method getStateForSaving
Enables saving the state of an OLAPCube.
@param {Object} [meta] An optional parameter that will be added to the serialized output and added to the meta field
within the deserialized OLAPCube
@return {Object} Returns an Ojbect representing the state of the OLAPCube. This Object is suitable for saving to
to an object store. Use the static method `newFromSavedState()` with this Object as the parameter to reconstitute the OLAPCube.
facts = [
{ProjectHierarchy: [1, 2, 3], Priority: 1},
{ProjectHierarchy: [1, 2, 4], Priority: 2},
{ProjectHierarchy: [5] , Priority: 1},
{ProjectHierarchy: [1, 2] , Priority: 1},
]
dimensions = [
{field: "ProjectHierarchy", type: 'hierarchy'},
{field: "Priority"}
]
config = {dimensions, metrics: []}
config.keepTotals = true
originalCube = new OLAPCube(config, facts)
dateString = '2012-12-27T12:34:56.789Z'
savedState = originalCube.getStateForSaving({upToDate: dateString})
restoredCube = OLAPCube.newFromSavedState(savedState)
newFacts = [
{ProjectHierarchy: [5], Priority: 3},
{ProjectHierarchy: [1, 2, 4], Priority: 1}
]
originalCube.addFacts(newFacts)
restoredCube.addFacts(newFacts)
console.log(restoredCube.toString() == originalCube.toString())
# true
console.log(restoredCube.meta.upToDate)
# 2012-12-27T12:34:56.789Z
###
out =
config: @userConfig
cellsAsCSVStyleArray: arrayOfMaps_To_CSVStyleArray(@cells) # !TODO: This makes the package smaller, but it's less well tested than using the Maps like the line below.
# cells: @cells
summaryMetrics: @summaryMetrics
if meta?
out.meta = meta
return out
@newFromSavedState: (p) ->
###
@method newFromSavedState
Deserializes a previously stringified OLAPCube and returns a new OLAPCube.
See `getStateForSaving()` documentation for a detailed example.
Note, if you have specified config.keepFacts = true, the values for the facts will be restored, however, they
will no longer be references to the original facts. For this reason, it's usually better to include a `values` or
`uniqueValues` metric on some ID field if you want fact drill-down support to survive a save and restore.
@static
@param {String/Object} p A String or Object from a previously saved OLAPCube state
@return {OLAPCube}
###
if utils.type(p) is 'string'
p = JSON.parse(p)
cube = new OLAPCube(p.config)
cube.summaryMetrics = p.summaryMetrics
if p.meta?
cube.meta = p.meta
if p.cellsAsCSVStyleArray?
cube.cells = csvStyleArray_To_ArrayOfMaps(p.cellsAsCSVStyleArray)
else
cube.cells = p.cells
cube.cellIndex = {}
cube._dimensionValues = {}
for d in cube.config.dimensions
cube._dimensionValues[d.field] = {}
for c in cube.cells
filterString = JSON.stringify(OLAPCube._extractFilter(c, cube.config.dimensions))
# rebuild cellIndex
cube.cellIndex[filterString] = c
# rebuild _dimensionValues
for d in cube.config.dimensions
fieldValue = c[d.field]
cube._dimensionValues[d.field][JSON.stringify(fieldValue)] = fieldValue
return cube
# cube
context = getContext()
collection = context.getCollection()
unless memo.continuation?
memo.continuation = null
if memo.savedCube?
theCube = OLAPCube.newFromSavedState(memo.savedCube)
else if memo.cubeConfig?
theCube = new OLAPCube(memo.cubeConfig)
else
throw new Error('cubeConfig or savedCube required')
memo.stillQueueing = true
query = () ->
setBody()
if memo.stillQueueing
responseOptions =
continuation: memo.continuation
pageSize: 1000
if memo.filterQuery?
memo.stillQueueing = collection.queryDocuments(collection.getSelfLink(), memo.filterQuery, responseOptions, onReadDocuments)
else
memo.stillQueueing = collection.readDocuments(collection.getSelfLink(), responseOptions, onReadDocuments)
onReadDocuments = (err, resources, options) ->
if err?
throw new Error(JSON.stringify(err))
theCube.addFacts(resources)
memo.savedCube = theCube.getStateForSaving()
memo.example = resources[0]
if options.continuation?
memo.continuation = options.continuation
query()
else
memo.continuation = null
setBody()
setBody = () ->
getContext().getResponse().setBody(memo)
query()
return memo
| true | module.exports = (memo) ->
# utils
utils = {}
utils.assert = (exp, message) ->
if (!exp)
throw new Error(message)
# Uses the properties of obj1, so will still match if obj2 has extra properties.
utils.match = (obj1, obj2) ->
for key, value of obj1
if (value != obj2[key])
return false
return true
utils.exactMatch = (a, b) ->
return true if a is b
atype = typeof(a);
btype = typeof(b)
return false if atype isnt btype
return false if (!a and b) or (a and !b)
return false if atype isnt 'object'
return false if a.length and (a.length isnt b.length)
return false for key, val of a when !(key of b) or not exactMatch(val, b[key])
return true
# At the top level, it will match even if obj1 is missing some elements that are in obj2, but at the lower levels, it must be an exact match.
utils.filterMatch = (obj1, obj2) ->
unless type(obj1) is 'object' and type(obj2) is 'object'
throw new Error('obj1 and obj2 must both be objects when calling filterMatch')
for key, value of obj1
if not exactMatch(value, obj2[key])
return false
return true
utils.trim = (val) ->
return if String::trim? then val.trim() else val.replace(/^\s+|\s+$/g, "")
utils.startsWith = (bigString, potentialStartString) ->
return bigString.substring(0, potentialStartString.length) == potentialStartString
utils.isArray = (a) ->
return Object.prototype.toString.apply(a) == '[object Array]'
utils.type = do -> # from http://arcturo.github.com/library/coffeescript/07_the_bad_parts.html
classToType = {}
for name in "Boolean Number String Function Array Date RegExp Undefined Null".split(" ")
classToType["[object " + name + "]"] = name.toLowerCase()
(obj) ->
strType = Object::toString.call(obj)
classToType[strType] or "object"
utils.clone = (obj) ->
if not obj? or typeof obj isnt 'object'
return obj
if obj instanceof Date
return new Date(obj.getTime())
if obj instanceof RegExp
flags = ''
flags += 'g' if obj.global?
flags += 'i' if obj.ignoreCase?
flags += 'm' if obj.multiline?
flags += 'y' if obj.sticky?
return new RegExp(obj.source, flags)
newInstance = new obj.constructor()
for key of obj
newInstance[key] = utils.clone(obj[key])
return newInstance
utils.keys = Object.keys or (obj) ->
return (key for key, val of obj)
utils.values = (obj) ->
return (val for key, val of obj)
utils.compare = (a, b) -> # Used for sorting any type
if a is null
return 1
if b is null
return -1
switch type(a)
when 'number', 'boolean', 'date'
return b - a
when 'array'
for value, index in a
if b.length - 1 >= index and value < b[index]
return 1
if b.length - 1 >= index and value > b[index]
return -1
if a.length < b.length
return 1
else if a.length > b.length
return -1
else
return 0
when 'object', 'string'
aString = JSON.stringify(a)
bString = JSON.stringify(b)
if aString < bString
return 1
else if aString > bString
return -1
else
return 0
else
throw new Error("Do not know how to sort objects of type #{utils.type(a)}.")
# dataTransform
csvStyleArray_To_ArrayOfMaps = (csvStyleArray, rowKeys) ->
###
@method csvStyleArray_To_ArrayOfMaps
@param {Array[]} csvStyleArray The first row is usually the list of column headers but if not, you can
provide your own such list in the second parameter
@param {String[]} [rowKeys] specify the column headers like `['column1', 'column2']`. If not provided, it will use
the first row of the csvStyleArray
@return {Object[]}
`csvStyleArry_To_ArryOfMaps` is a convenience function that will convert a csvStyleArray like:
{csvStyleArray_To_ArrayOfMaps} = require('../')
csvStyleArray = [
['column1', 'column2'],
[1 , 2 ],
[3 , 4 ],
[5 , 6 ]
]
to an Array of Maps like this:
console.log(csvStyleArray_To_ArrayOfMaps(csvStyleArray))
# [ { column1: 1, column2: 2 },
# { column1: 3, column2: 4 },
# { column1: 5, column2: 6 } ]
`
###
arrayOfMaps = []
if rowKeys?
i = 0
else
rowKeys = csvStyleArray[0]
i = 1
tableLength = csvStyleArray.length
while i < tableLength
inputRow = csvStyleArray[i]
outputRow = {}
for key, index in rowKeys
outputRow[key] = inputRow[index]
arrayOfMaps.push(outputRow)
i++
return arrayOfMaps
arrayOfMaps_To_CSVStyleArray = (arrayOfMaps, keys) ->
###
@method arrayOfMaps_To_CSVStyleArray
@param {Object[]} arrayOfMaps
@param {Object} [keys] If not provided, it will use the first row and get all fields
@return {Array[]} The first row will be the column headers
`arrayOfMaps_To_CSVStyleArray` is a convenience function that will convert an array of maps like:
{arrayOfMaps_To_CSVStyleArray} = require('../')
arrayOfMaps = [
{column1: 10000, column2: 20000},
{column1: 30000, column2: 40000},
{column1: 50000, column2: 60000}
]
to a CSV-style array like this:
console.log(arrayOfMaps_To_CSVStyleArray(arrayOfMaps))
# [ [ 'column1', 'column2' ],
# [ 10000, 20000 ],
# [ 30000, 40000 ],
# [ 50000, 60000 ] ]
`
###
if arrayOfMaps.length == 0
return []
csvStyleArray = []
outRow = []
unless keys?
keys = []
for key, value of arrayOfMaps[0]
keys.push(key)
csvStyleArray.push(keys)
for inRow in arrayOfMaps
outRow = []
for key in keys
outRow.push(inRow[key])
csvStyleArray.push(outRow)
return csvStyleArray
# functions
_populateDependentValues = (values, dependencies, dependentValues = {}, prefix = '') ->
out = {}
for d in dependencies
if d == 'count'
if prefix == ''
key = 'PI:KEY:<KEY>END_PI'
else
key = PI:KEY:<KEY>END_PI'
else
key = prefix + d
unless dependentValues[key]?
dependentValues[key] = functions[d](values, undefined, undefined, dependentValues, prefix)
out[d] = dependentValues[key]
return out
###
@method sum
@static
@param {Number[]} [values] Must either provide values or oldResult and newValues
@param {Number} [oldResult] for incremental calculation
@param {Number[]} [newValues] for incremental calculation
@return {Number} The sum of the values
###
###
@class functions
Rules about dependencies:
* If a function can be calculated incrementally from an oldResult and newValues, then you do not need to specify dependencies
* If a funciton can be calculated from other incrementally calculable results, then you need only specify those dependencies
* If a function needs the full list of values to be calculated (like percentile coverage), then you must specify 'values'
* To support the direct passing in of OLAP cube cells, you can provide a prefix (field name) so the key in dependentValues
can be generated
* 'count' is special and does not use a prefix because it is not dependent up a particular field
* You should calculate the dependencies before you calculate the thing that is depedent. The OLAP cube does some
checking to confirm you've done this.
###
functions = {}
functions.sum = (values, oldResult, newValues) ->
if oldResult?
temp = oldResult
tempValues = newValues
else
temp = 0
tempValues = values
for v in tempValues
temp += v
return temp
###
@method product
@static
@param {Number[]} [values] Must either provide values or oldResult and newValues
@param {Number} [oldResult] for incremental calculation
@param {Number[]} [newValues] for incremental calculation
@return {Number} The product of the values
###
functions.product = (values, oldResult, newValues) ->
if oldResult?
temp = oldResult
tempValues = newValues
else
temp = 1
tempValues = values
for v in tempValues
temp = temp * v
return temp
###
@method sumSquares
@static
@param {Number[]} [values] Must either provide values or oldResult and newValues
@param {Number} [oldResult] for incremental calculation
@param {Number[]} [newValues] for incremental calculation
@return {Number} The sum of the squares of the values
###
functions.sumSquares = (values, oldResult, newValues) ->
if oldResult?
temp = oldResult
tempValues = newValues
else
temp = 0
tempValues = values
for v in tempValues
temp += v * v
return temp
###
@method sumCubes
@static
@param {Number[]} [values] Must either provide values or oldResult and newValues
@param {Number} [oldResult] for incremental calculation
@param {Number[]} [newValues] for incremental calculation
@return {Number} The sum of the cubes of the values
###
functions.sumCubes = (values, oldResult, newValues) ->
if oldResult?
temp = oldResult
tempValues = newValues
else
temp = 0
tempValues = values
for v in tempValues
temp += v * v * v
return temp
###
@method lastValue
@static
@param {Number[]} [values] Must either provide values or newValues
@param {Number} [oldResult] Not used. It is included to make the interface consistent.
@param {Number[]} [newValues] for incremental calculation
@return {Number} The last value
###
functions.lastValue = (values, oldResult, newValues) ->
if newValues?
return newValues[newValues.length - 1]
return values[values.length - 1]
###
@method firstValue
@static
@param {Number[]} [values] Must either provide values or oldResult
@param {Number} [oldResult] for incremental calculation
@param {Number[]} [newValues] Not used. It is included to make the interface consistent.
@return {Number} The first value
###
functions.firstValue = (values, oldResult, newValues) ->
if oldResult?
return oldResult
return values[0]
###
@method count
@static
@param {Number[]} [values] Must either provide values or oldResult and newValues
@param {Number} [oldResult] for incremental calculation
@param {Number[]} [newValues] for incremental calculation
@return {Number} The length of the values Array
###
functions.count = (values, oldResult, newValues) ->
if oldResult?
return oldResult + newValues.length
return values.length
###
@method min
@static
@param {Number[]} [values] Must either provide values or oldResult and newValues
@param {Number} [oldResult] for incremental calculation
@param {Number[]} [newValues] for incremental calculation
@return {Number} The minimum value or null if no values
###
functions.min = (values, oldResult, newValues) ->
if oldResult?
return functions.min(newValues.concat([oldResult]))
if values.length == 0
return null
temp = values[0]
for v in values
if v < temp
temp = v
return temp
###
@method max
@static
@param {Number[]} [values] Must either provide values or oldResult and newValues
@param {Number} [oldResult] for incremental calculation
@param {Number[]} [newValues] for incremental calculation
@return {Number} The maximum value or null if no values
###
functions.max = (values, oldResult, newValues) ->
if oldResult?
return functions.max(newValues.concat([oldResult]))
if values.length == 0
return null
temp = values[0]
for v in values
if v > temp
temp = v
return temp
###
@method values
@static
@param {Object[]} [values] Must either provide values or oldResult and newValues
@param {Number} [oldResult] for incremental calculation
@param {Number[]} [newValues] for incremental calculation
@return {Array} All values (allows duplicates). Can be used for drill down.
###
functions.values = (values, oldResult, newValues) ->
if oldResult?
return oldResult.concat(newValues)
return values
# temp = []
# for v in values
# temp.push(v)
# return temp
###
@method uniqueValues
@static
@param {Object[]} [values] Must either provide values or oldResult and newValues
@param {Number} [oldResult] for incremental calculation
@param {Number[]} [newValues] for incremental calculation
@return {Array} Unique values. This is good for generating an OLAP dimension or drill down.
###
functions.uniqueValues = (values, oldResult, newValues) ->
temp = {}
if oldResult?
for r in oldResult
temp[r] = null
tempValues = newValues
else
tempValues = values
temp2 = []
for v in tempValues
temp[v] = null
for key, value of temp
temp2.push(key)
return temp2
###
@method average
@static
@param {Number[]} [values] Must either provide values or oldResult and newValues
@param {Number} [oldResult] not used by this function but included so all functions have a consistent signature
@param {Number[]} [newValues] not used by this function but included so all functions have a consistent signature
@param {Object} [dependentValues] If the function can be calculated from the results of other functions, this allows
you to provide those pre-calculated values.
@return {Number} The arithmetic mean
###
functions.average = (values, oldResult, newValues, dependentValues, prefix) ->
{count, sum} = _populateDependentValues(values, functions.average.dependencies, dependentValues, prefix)
if count is 0
return null
else
return sum / count
functions.average.dependencies = ['count', 'sum']
###
@method errorSquared
@static
@param {Number[]} [values] Must either provide values or oldResult and newValues
@param {Number} [oldResult] not used by this function but included so all functions have a consistent signature
@param {Number[]} [newValues] not used by this function but included so all functions have a consistent signature
@param {Object} [dependentValues] If the function can be calculated from the results of other functions, this allows
you to provide those pre-calculated values.
@return {Number} The error squared
###
functions.errorSquared = (values, oldResult, newValues, dependentValues, prefix) ->
{count, sum} = _populateDependentValues(values, functions.errorSquared.dependencies, dependentValues, prefix)
mean = sum / count
errorSquared = 0
for v in values
difference = v - mean
errorSquared += difference * difference
return errorSquared
functions.errorSquared.dependencies = ['count', 'sum']
###
@method variance
@static
@param {Number[]} [values] Must either provide values or oldResult and newValues
@param {Number} [oldResult] not used by this function but included so all functions have a consistent signature
@param {Number[]} [newValues] not used by this function but included so all functions have a consistent signature
@param {Object} [dependentValues] If the function can be calculated from the results of other functions, this allows
you to provide those pre-calculated values.
@return {Number} The variance
###
functions.variance = (values, oldResult, newValues, dependentValues, prefix) ->
{count, sum, sumSquares} = _populateDependentValues(values, functions.variance.dependencies, dependentValues, prefix)
if count is 0
return null
else if count is 1
return 0
else
return (count * sumSquares - sum * sum) / (count * (count - 1))
functions.variance.dependencies = ['count', 'sum', 'sumSquares']
###
@method standardDeviation
@static
@param {Number[]} [values] Must either provide values or oldResult and newValues
@param {Number} [oldResult] not used by this function but included so all functions have a consistent signature
@param {Number[]} [newValues] not used by this function but included so all functions have a consistent signature
@param {Object} [dependentValues] If the function can be calculated from the results of other functions, this allows
you to provide those pre-calculated values.
@return {Number} The standard deviation
###
functions.standardDeviation = (values, oldResult, newValues, dependentValues, prefix) ->
return Math.sqrt(functions.variance(values, oldResult, newValues, dependentValues, prefix))
functions.standardDeviation.dependencies = functions.variance.dependencies
###
@method percentileCreator
@static
@param {Number} p The percentile for the resulting function (50 = median, 75, 99, etc.)
@return {Function} A function to calculate the percentile
When the user passes in `p<n>` as an aggregation function, this `percentileCreator` is called to return the appropriate
percentile function. The returned function will find the `<n>`th percentile where `<n>` is some number in the form of
`##[.##]`. (e.g. `p40`, `p99`, `p99.9`).
There is no official definition of percentile. The most popular choices differ in the interpolation algorithm that they
use. The function returned by this `percentileCreator` uses the Excel interpolation algorithm which differs from the NIST
primary method. However, NIST lists something very similar to the Excel approach as an acceptible alternative. The only
difference seems to be for the edge case for when you have only two data points in your data set. Agreement with Excel,
NIST's acceptance of it as an alternative (almost), and the fact that it makes the most sense to me is why this approach
was chosen.
http://en.wikipedia.org/wiki/Percentile#Alternative_methods
Note: `median` is an alias for p50. The approach chosen for calculating p50 gives you the
exact same result as the definition for median even for edge cases like sets with only one or two data points.
###
functions.percentileCreator = (p) ->
f = (values, oldResult, newValues, dependentValues, prefix) ->
unless values?
{values} = _populateDependentValues(values, ['values'], dependentValues, prefix)
if values.length is 0
return null
sortfunc = (a, b) ->
return a - b
vLength = values.length
values.sort(sortfunc)
n = (p * (vLength - 1) / 100) + 1
k = Math.floor(n)
d = n - k
if n == 1
return values[1 - 1]
if n == vLength
return values[vLength - 1]
return values[k - 1] + d * (values[k] - values[k - 1])
f.dependencies = ['values']
return f
###
@method median
@static
@param {Number[]} [values] Must either provide values or oldResult and newValues
@param {Number} [oldResult] not used by this function but included so all functions have a consistent signature
@param {Number[]} [newValues] not used by this function but included so all functions have a consistent signature
@param {Object} [dependentValues] If the function can be calculated from the results of other functions, this allows
you to provide those pre-calculated values.
@return {Number} The median
###
functions.median = functions.percentileCreator(50)
functions.expandFandAs = (a) ->
###
@method expandFandAs
@static
@param {Object} a Will look like this `{as: 'mySum', f: 'sum', field: 'Points'}`
@return {Object} returns the expanded specification
Takes specifications for functions and expands them to include the actual function and 'as'. If you do not provide
an 'as' property, it will build it from the field name and function with an underscore between. Also, if the
'f' provided is a string, it is copied over to the 'metric' property before the 'f' property is replaced with the
actual function. `{field: 'a', f: 'sum'}` would expand to `{as: 'a_sum', field: 'a', metric: 'sum', f: [Function]}`.
###
utils.assert(a.f?, "'f' missing from specification: \n#{JSON.stringify(a, undefined, 4)}")
if utils.type(a.f) == 'function'
throw new Error('User defined metric functions not supported in a stored procedure')
utils.assert(a.as?, 'Must provide "as" field with your aggregation when providing a user defined function')
a.metric = a.f.toString()
else if functions[a.f]?
a.metric = a.f
a.f = functions[a.f]
else if a.f.substr(0, 1) == 'p'
a.metric = a.f
p = /\p(\d+(.\d+)?)/.exec(a.f)[1]
a.f = functions.percentileCreator(Number(p))
else
throw new Error("#{a.f} is not a recognized built-in function")
unless a.as?
if a.metric == 'count'
a.field = ''
a.metric = 'count'
a.as = "#{a.field}_#{a.metric}"
utils.assert(a.field? or a.f == 'count', "'field' missing from specification: \n#{JSON.stringify(a, undefined, 4)}")
return a
functions.expandMetrics = (metrics = [], addCountIfMissing = false, addValuesForCustomFunctions = false) ->
###
@method expandMetrics
@static
@private
This is called internally by several Lumenize Calculators. You should probably not call it.
###
confirmMetricAbove = (m, fieldName, aboveThisIndex) ->
if m is 'count'
lookingFor = '_' + m
else
lookingFor = fieldName + '_' + m
i = 0
while i < aboveThisIndex
currentRow = metrics[i]
if currentRow.as == lookingFor
return true
i++
# OK, it's not above, let's now see if it's below. Then throw error.
i = aboveThisIndex + 1
metricsLength = metrics.length
while i < metricsLength
currentRow = metrics[i]
if currentRow.as == lookingFor
throw new Error("Depdencies must appear before the metric they are dependant upon. #{m} appears after.")
i++
return false
assureDependenciesAbove = (dependencies, fieldName, aboveThisIndex) ->
for d in dependencies
unless confirmMetricAbove(d, fieldName, aboveThisIndex)
if d == 'count'
newRow = {f: 'count'}
else
newRow = {f: d, field: fieldName}
functions.expandFandAs(newRow)
metrics.unshift(newRow)
return false
return true
# add values for custom functions
if addValuesForCustomFunctions
for m, index in metrics
if utils.type(m.f) is 'function'
unless m.f.dependencies?
m.f.dependencies = []
unless m.f.dependencies[0] is 'values'
m.f.dependencies.push('values')
unless confirmMetricAbove('values', m.field, index)
valuesRow = {f: 'values', field: m.field}
functions.expandFandAs(valuesRow)
metrics.unshift(valuesRow)
hasCount = false
for m in metrics
functions.expandFandAs(m)
if m.metric is 'count'
hasCount = true
if addCountIfMissing and not hasCount
countRow = {f: 'count'}
functions.expandFandAs(countRow)
metrics.unshift(countRow)
index = 0
while index < metrics.length # intentionally not caching length because the loop can add rows
metricsRow = metrics[index]
if utils.type(metricsRow.f) is 'function'
dependencies = ['values']
if metricsRow.f.dependencies?
unless assureDependenciesAbove(metricsRow.f.dependencies, metricsRow.field, index)
index = -1
index++
return metrics
# OLAPCube
# !TODO: Add summary metrics
# !TODO: Be smart enough to move dependent metrics to the deriveFieldsOnOutput
class OLAPCube
###
@class OLAPCube
__An efficient, in-memory, incrementally-updateable, hierarchy-capable OLAP Cube implementation.__
[OLAP Cubes](http://en.wikipedia.org/wiki/OLAP_cube) are a powerful abstraction that makes it easier to do everything
from simple group-by operations to more complex multi-dimensional and hierarchical analysis. This implementation has
the same conceptual ancestry as implementations found in business intelligence and OLAP database solutions. However,
it is meant as a light weight alternative primarily targeting the goal of making it easier for developers to implement
desired analysis. It also supports serialization and incremental updating so it's ideally
suited for visualizations and analysis that are updated on a periodic or even continuous basis.
## Features ##
* In-memory
* Incrementally-updateable
* Serialize (`getStateForSaving()`) and deserialize (`newFromSavedState()`) to preserve aggregations between sessions
* Accepts simple JavaScript Objects as facts
* Storage and output as simple JavaScript Arrays of Objects
* Hierarchy (trees) derived from fact data assuming [materialized path](http://en.wikipedia.org/wiki/Materialized_path)
array model commonly used with NoSQL databases
## 2D Example ##
Let's walk through a simple 2D example from facts to output. Let's say you have this set of facts:
facts = [
{ProjectHierarchy: [1, 2, 3], Priority: 1, Points: 10},
{ProjectHierarchy: [1, 2, 4], Priority: 2, Points: 5 },
{ProjectHierarchy: [5] , Priority: 1, Points: 17},
{ProjectHierarchy: [1, 2] , Priority: 1, Points: 3 },
]
The ProjectHierarchy field models its hierarchy (tree) as an array containing a
[materialized path](http://en.wikipedia.org/wiki/Materialized_path). The first fact is "in" Project 3 whose parent is
Project 2, whose parent is Project 1. The second fact is "in" Project 4 whose parent is Project 2 which still has
Project 1 as its parent. Project 5 is another root Project like Project 1; and the fourth fact is "in" Project 2.
So the first fact will roll-up the tree and be aggregated against [1], and [1, 2] as well as [1, 2, 3]. Root Project 1
will get the data from all but the third fact which will get aggregated against root Project 5.
We specify the ProjectHierarchy field as a dimension of type 'hierarchy' and the Priorty field as a simple value dimension.
dimensions = [
{field: "ProjectHierarchy", type: 'hierarchy'},
{field: "Priority"}
]
This will create a 2D "cube" where each unique value for ProjectHierarchy and Priority defines a different cell.
Note, this happens to be a 2D "cube" (more commonly referred to as a [pivot table](http://en.wikipedia.org/wiki/Pivot_Table)),
but you can also have a 1D cube (a simple group-by), a 3D cube, or even an n-dimensional hypercube where n is greater than 3.
You can specify any number of metrics to be calculated for each cell in the cube.
metrics = [
{field: "Points", f: "sum", as: "Scope"}
]
You can use any of the aggregation functions found in Lumenize.functions except `count`. The count metric is
automatically tracked for each cell. The `as` specification is optional unless you provide a custom function. If missing,
it will build the name of the resulting metric from the field name and the function. So without the `as: "Scope"` the
second metric in the example above would have been named "Points_sum".
You can also use custom functions in the form of `f(values) -> return <some function of values>`.
Next, we build the config parameter from our dimension and metrics specifications.
config = {dimensions, metrics}
Hierarchy dimensions automatically roll up but you can also tell it to keep all totals by setting config.keepTotals to
true. The totals are then kept in the cells where one or more of the dimension values are set to `null`. Note, you
can also set keepTotals for individual dimension and should probably use that if you have more than a few dimensions
but we're going to set it globally here:
config.keepTotals = true
Now, let's create the cube.
{OLAPCube} = require('../')
cube = new OLAPCube(config, facts)
`getCell()` allows you to extract a single cell. The "total" cell for all facts where Priority = 1 can be found as follows:
console.log(cube.getCell({Priority: 1}))
# { ProjectHierarchy: null, Priority: 1, _count: 3, Scope: 30 }
Notice how the ProjectHierarchy field value is `null`. This is because it is a total cell for Priority dimension
for all ProjectHierarchy values. Think of `null` values in this context as wildcards.
Similarly, we can get the total for all descendants of ProjectHierarchy = [1] regarless of Priority as follows:
console.log(cube.getCell({ProjectHierarchy: [1]}))
# { ProjectHierarchy: [ 1 ], Priority: null, _count: 3, Scope: 18 }
`getCell()` uses the cellIndex so it's very efficient. Using `getCell()` and `getDimensionValues()`, you can iterate
over a slice of the OLAPCube. It is usually preferable to access the cells in place like this rather than the
traditional OLAP approach of extracting a slice for processing. However, there is a `slice()` method for extracting
a 2D slice.
rowValues = cube.getDimensionValues('ProjectHierarchy')
columnValues = cube.getDimensionValues('Priority')
s = OLAPCube._padToWidth('', 7) + ' | '
s += ((OLAPCube._padToWidth(JSON.stringify(c), 7) for c in columnValues).join(' | '))
s += ' | '
console.log(s)
for r in rowValues
s = OLAPCube._padToWidth(JSON.stringify(r), 7) + ' | '
for c in columnValues
cell = cube.getCell({ProjectHierarchy: r, Priority: c})
if cell?
cellString = JSON.stringify(cell._count)
else
cellString = ''
s += OLAPCube._padToWidth(cellString, 7) + ' | '
console.log(s)
# | null | 1 | 2 |
# null | 4 | 3 | 1 |
# [1] | 3 | 2 | 1 |
# [1,2] | 3 | 2 | 1 |
# [1,2,3] | 1 | 1 | |
# [1,2,4] | 1 | | 1 |
# [5] | 1 | 1 | |
Or you can just call `toString()` method which extracts a 2D slice for tabular display. Both approachs will work on
cubes of any number of dimensions two or greater. The manual example above extracted the `count` metric. We'll tell
the example below to extract the `Scope` metric.
console.log(cube.toString('ProjectHierarchy', 'Priority', 'Scope'))
# | || Total | 1 2|
# |==============================|
# |Total || 35 | 30 5|
# |------------------------------|
# |[1] || 18 | 13 5|
# |[1,2] || 18 | 13 5|
# |[1,2,3] || 10 | 10 |
# |[1,2,4] || 5 | 5|
# |[5] || 17 | 17 |
## Dimension types ##
The following dimension types are supported:
1. Single value
* Number
* String
* Does not work:
* Boolean - known to fail
* Object - may sorta work but sort-order at least is not obvious
* Date - not tested but may actually work
2. Arrays as materialized path for hierarchical (tree) data
3. Non-hierarchical Arrays ("tags")
There is no need to tell the OLAPCube what type to use with the exception of #2. In that case, add `type: 'hierarchy'`
to the dimensions row like this:
dimensions = [
{field: 'hierarchicalDimensionField', type: 'hierarchy'} #, ...
]
## Hierarchical (tree) data ##
This OLAP Cube implementation assumes your hierarchies (trees) are modeled as a
[materialized path](http://en.wikipedia.org/wiki/Materialized_path) array. This approach is commonly used with NoSQL databases like
[CouchDB](http://probablyprogramming.com/2008/07/04/storing-hierarchical-data-in-couchdb) and
[MongoDB (combining materialized path and array of ancestors)](http://docs.mongodb.org/manual/tutorial/model-tree-structures/)
and even SQL databases supporting array types like [Postgres](http://justcramer.com/2012/04/08/using-arrays-as-materialized-paths-in-postgres/).
This approach differs from the traditional OLAP/MDX fixed/named level hierarchy approach. In that approach, you assume
that the number of levels in the hierarchy are fixed. Also, each level in the hierarchy is either represented by a different
column (clothing example --> level 0: SEX column - mens vs womens; level 1: TYPE column - pants vs shorts vs shirts; etc.) or
predetermined ranges of values in a single field (date example --> level 0: year; level 1: quarter; level 2: month; etc.)
However, the approach used by this OLAPCube implementaion is the more general case, because it can easily simulate
fixed/named level hierachies whereas the reverse is not true. In the clothing example above, you would simply key
your dimension off of a derived field that was a combination of the SEX and TYPE columns (e.g. ['mens', 'pants'])
## Date/Time hierarchies ##
Lumenize is designed to work well with the tzTime library. Here is an example of taking a bunch of ISOString data
and doing timezone precise hierarchical roll up based upon the date segments (year, month).
data = [
{date: '2011-12-31T12:34:56.789Z', value: 10},
{date: '2012-01-05T12:34:56.789Z', value: 20},
{date: '2012-01-15T12:34:56.789Z', value: 30},
{date: '2012-02-01T00:00:01.000Z', value: 40},
{date: '2012-02-15T12:34:56.789Z', value: 50},
]
{Time} = require('../')
config =
deriveFieldsOnInput: [{
field: 'dateSegments',
f: (row) ->
return new Time(row.date, Time.MONTH, 'America/New_York').getSegmentsAsArray()
}]
metrics: [{field: 'value', f: 'sum'}]
dimensions: [{field: 'dateSegments', type: 'hierarchy'}]
cube = new OLAPCube(config, data)
console.log(cube.toString(undefined, undefined, 'value_sum'))
# | dateSegments | value_sum |
# |==========================|
# | [2011] | 10 |
# | [2011,12] | 10 |
# | [2012] | 140 |
# | [2012,1] | 90 |
# | [2012,2] | 50 |
Notice how '2012-02-01T00:00:01.000Z' got bucketed in January because the calculation was done in timezone
'America/New_York'.
## Non-hierarchical Array fields ##
If you don't specify type: 'hierarchy' and the OLAPCube sees a field whose value is an Array in a dimension field, the
data in that fact would get aggregated against each element in the Array. So a non-hierarchical Array field like
['x', 'y', 'z'] would get aggregated against 'x', 'y', and 'z' rather than ['x'], ['x', 'y'], and ['x','y','z]. This
functionality is useful for accomplishing analytics on tags, but it can be used in other powerful ways. For instance
let's say you have a list of events:
events = [
{name: 'Renaissance Festival', activeMonths: ['September', 'October']},
{name: 'Concert Series', activeMonths: ['July', 'August', 'September']},
{name: 'Fall Festival', activeMonths: ['September']}
]
You could figure out the number of events active in each month by specifying "activeMonths" as a dimension.
Lumenize.TimeInStateCalculator (and other calculators in Lumenize) use this technique.
###
constructor: (@userConfig, facts) ->
###
@constructor
@param {Object} config See Config options for details. DO NOT change the config settings after the OLAP class is instantiated.
@param {Object[]} [facts] Optional parameter allowing the population of the OLAPCube with an intitial set of facts
upon instantiation. Use addFacts() to add facts after instantiation.
@cfg {Object[]} [dimensions] Array which specifies the fields to use as dimension fields. If the field contains a
hierarchy array, say so in the row, (e.g. `{field: 'SomeFieldName', type: 'hierarchy'}`). Any array values that it
finds in the supplied facts will be assumed to be tags rather than a hierarchy specification unless `type: 'hierarchy'`
is specified.
For example, let's say you have a set of facts that look like this:
fact = {
dimensionField: 'a',
hierarchicalDimensionField: ['1','2','3'],
tagDimensionField: ['x', 'y', 'z'],
valueField: 10
}
Then a set of dimensions like this makes sense.
config.dimensions = [
{field: 'dimensionField'},
{field: 'hierarchicalDimensionField', type: 'hierarchy'},
{field: 'tagDimensionField', keepTotals: true}
]
Notice how a keepTotals can be set for an individual dimension. This is preferable to setting it for the entire
cube in cases where you don't want totals in all dimensions.
If no dimension config is provided, then you must use syntactic sugar like groupBy.
@cfg {String} [groupBy] Syntactic sugar for single-dimension/single-metric usage.
@cfg {String} [f] Syntactic sugar for single-dimension/single-metric usage. If provided, you must also provide
a `groupBy` config. If you provided a `groupBy` but no `f` or `field`, then the default `count` metric will be used.
@cfg {String} [field] Syntactic sugar for single-dimension/single-metric usage. If provided, you must also provide
a `groupBy` config. If you provided a `groupBy` but no `f` or `field`, then the default `count` metric will be used.
@cfg {Object[]} [metrics=[]] Array which specifies the metrics to calculate for each cell in the cube.
Example:
config = {}
config.metrics = [
{field: 'field3'}, # defaults to metrics: ['sum']
{field: 'field4', metrics: [
{f: 'sum'}, # will add a metric named field4_sum
{as: 'median4', f: 'p50'}, # renamed p50 to median4 from default of field4_p50
{as: 'myCount', f: (values) -> return values.length} # user-supplied function
]}
]
If you specify a field without any metrics, it will assume you want the sum but it will not automatically
add the sum metric to fields with a metrics specification. User-supplied aggregation functions are also supported as
shown in the 'myCount' metric above.
Note, if the metric has dependencies (e.g. average depends upon count and sum) it will automatically add those to
your metric definition. If you've already added a dependency but put it under a different "as", it's not smart
enough to sense that and it will add it again. Either live with the slight inefficiency and duplication or leave
dependency metrics named their default by not providing an "as" field.
@cfg {Boolean} [keepTotals=false] Setting this will add an additional total row (indicated with field: null) along
all dimensions. This setting can have an impact on the memory usage and performance of the OLAPCube so
if things are tight, only use it if you really need it. If you don't need it for all dimension, you can specify
keepTotals for individual dimensions.
@cfg {Boolean} [keepFacts=false] Setting this will cause the OLAPCube to keep track of the facts that contributed to
the metrics for each cell by adding an automatic 'facts' metric. Note, facts are restored after deserialization
as you would expect, but they are no longer tied to the original facts. This feature, especially after a restore
can eat up memory.
@cfg {Object[]} [deriveFieldsOnInput] An Array of Maps in the form `{field:'myField', f:(fact)->...}`
@cfg {Object[]} [deriveFieldsOnOutput] same format as deriveFieldsOnInput, except the callback is in the form `f(row)`
This is only called for dirty rows that were effected by the latest round of addFacts. It's more efficient to calculate things
like standard deviation and percentile coverage here than in config.metrics. You just have to remember to include the dependencies
in config.metrics. Standard deviation depends upon `sum` and `sumSquares`. Percentile coverage depends upon `values`.
In fact, if you are going to capture values anyway, all of the functions are most efficiently calculated here.
Maybe some day, I'll write the code to analyze your metrics and move them out to here if it improves efficiency.
###
@config = utils.clone(@userConfig)
@cells = []
@cellIndex = {}
@currentValues = {}
# Syntactic sugar for groupBy
if @config.groupBy?
@config.dimensions = [{field: @config.groupBy}]
if @config.f? and @config.field?
@config.metrics = [{field: @config.field, f: @config.f}]
utils.assert(@config.dimensions?, 'Must provide config.dimensions.')
unless @config.metrics?
@config.metrics = []
@_dimensionValues = {} # key: fieldName, value: {} where key: uniqueValue, value: the real key (not stringified)
for d in @config.dimensions
@_dimensionValues[d.field] = {}
unless @config.keepTotals
@config.keepTotals = false
unless @config.keepFacts
@config.keepFacts = false
for d in @config.dimensions
if @config.keepTotals or d.keepTotals
d.keepTotals = true
else
d.keepTotals = false
functions.expandMetrics(@config.metrics, true, true)
# Set required fields
requiredFieldsObject = {}
for m in @config.metrics
if m.field?.length > 0 # Should only be false if function is count
requiredFieldsObject[m.field] = null
@requiredMetricsFields = (key for key, value of requiredFieldsObject)
requiredFieldsObject = {}
for d in @config.dimensions
requiredFieldsObject[d.field] = null
@requiredDimensionFields = (key for key, value of requiredFieldsObject)
@summaryMetrics = {}
@addFacts(facts)
@_possibilities: (key, type, keepTotals) ->
switch utils.type(key)
when 'array'
if keepTotals
a = [null]
else
a = []
if type == 'hierarchy'
len = key.length
while len > 0
a.push(key.slice(0, len))
len--
else # assume it's a tag array
if keepTotals
a = [null].concat(key)
else
a = key
return a
when 'string', 'number'
if keepTotals
return [null, key]
else
return [key]
@_decrement: (a, rollover) ->
i = a.length - 1
a[i]--
while a[i] < 0
a[i] = rollover[i]
i--
if i < 0
return false
else
a[i]--
return true
_expandFact: (fact) ->
possibilitiesArray = []
countdownArray = []
rolloverArray = []
for d in @config.dimensions
p = OLAPCube._possibilities(fact[d.field], d.type, d.keepTotals)
possibilitiesArray.push(p)
countdownArray.push(p.length - 1)
rolloverArray.push(p.length - 1) # !TODO: If I need some speed, we could calculate the rolloverArray once and make a copy to the countdownArray for each run
for m in @config.metrics
@currentValues[m.field] = [fact[m.field]] # !TODO: Add default values here. I think this is the only place it is needed. write tests with incremental update to confirm.
out = []
more = true
while more
outRow = {}
for d, index in @config.dimensions
outRow[d.field] = possibilitiesArray[index][countdownArray[index]]
outRow._count = 1
if @config.keepFacts
outRow._facts = [fact]
for m in @config.metrics
outRow[m.as] = m.f([fact[m.field]], undefined, undefined, outRow, m.field + '_')
out.push(outRow)
more = OLAPCube._decrement(countdownArray, rolloverArray)
return out
@_extractFilter: (row, dimensions) ->
out = {}
for d in dimensions
out[d.field] = row[d.field]
return out
_mergeExpandedFactArray: (expandedFactArray) ->
for er in expandedFactArray
# set _dimensionValues
for d in @config.dimensions
fieldValue = er[d.field]
@_dimensionValues[d.field][JSON.stringify(fieldValue)] = fieldValue
# start merge
filterString = JSON.stringify(OLAPCube._extractFilter(er, @config.dimensions))
olapRow = @cellIndex[filterString]
if olapRow?
for m in @config.metrics
olapRow[m.as] = m.f(olapRow[m.field + '_values'], olapRow[m.as], @currentValues[m.field], olapRow, m.field + '_')
else
olapRow = er
@cellIndex[filterString] = olapRow
@cells.push(olapRow)
@dirtyRows[filterString] = olapRow
addFacts: (facts) ->
###
@method addFacts
Adds facts to the OLAPCube.
@chainable
@param {Object[]} facts An Array of facts to be aggregated into OLAPCube. Each fact is a Map where the keys are the field names
and the values are the field values (e.g. `{field1: 'a', field2: 5}`).
###
@dirtyRows = {}
if utils.type(facts) == 'array'
if facts.length <= 0
return
else
if facts?
facts = [facts]
else
return
if @config.deriveFieldsOnInput
for fact in facts
for d in @config.deriveFieldsOnInput
if d.as?
fieldName = d.as
else
fieldName = d.field
fact[fieldName] = d.f(fact)
for fact in facts
@addMissingFields(fact)
@currentValues = {}
expandedFactArray = @_expandFact(fact)
@_mergeExpandedFactArray(expandedFactArray)
# deriveFieldsOnOutput for @dirtyRows
if @config.deriveFieldsOnOutput?
for filterString, dirtyRow of @dirtyRows
for d in @config.deriveFieldsOnOutput
if d.as?
fieldName = d.as
else
fieldName = d.field
dirtyRow[fieldName] = d.f(dirtyRow)
@dirtyRows = {}
return this
addMissingFields: (fact) ->
for field in @requiredMetricsFields
if fact[field] is undefined
fact[field] = null
for field in @requiredDimensionFields
unless fact[field]?
fact[field] = '<missing>'
return fact
getCells: (filterObject) ->
###
@method getCells
Returns a subset of the cells that match the supplied filter. You can perform slice and dice operations using
this. If you have criteria for all of the dimensions, you are better off using `getCell()`. Most times, it's
better to iterate over the unique values for the dimensions of interest using `getCell()` in place of slice or
dice operations. However, there is a `slice()` method for extracting a 2D slice
@param {Object} [filterObject] Specifies the constraints that the returned cells must match in the form of
`{field1: value1, field2: value2}`. If this parameter is missing, the internal cells array is returned.
@return {Object[]} Returns the cells that match the supplied filter
###
unless filterObject?
return @cells
output = []
for c in @cells
if utils.filterMatch(filterObject, c)
output.push(c)
return output
getCell: (filter, defaultValue) ->
###
@method getCell
Returns the single cell matching the supplied filter. Iterating over the unique values for the dimensions of
interest, you can incrementally retrieve a slice or dice using this method. Since `getCell()` always uses an index,
in most cases, this is better than using `getCells()` to prefetch a slice or dice.
@param {Object} [filter={}] Specifies the constraints for the returned cell in the form of `{field1: value1, field2: value2}.
Any fields that are specified in config.dimensions that are missing from the filter are automatically filled in
with null. Calling `getCell()` with no parameter or `{}` will return the total of all dimensions (if @config.keepTotals=true).
@return {Object[]} Returns the cell that match the supplied filter
###
unless filter?
filter = {}
for key, value of filter
foundIt = false
for d in @config.dimensions
if d.field == key
foundIt = true
unless foundIt
throw new Error("#{key} is not a dimension for this cube.")
normalizedFilter = {}
for d in @config.dimensions
if filter.hasOwnProperty(d.field)
normalizedFilter[d.field] = filter[d.field]
else
if d.keepTotals
normalizedFilter[d.field] = null
else
throw new Error('Must set keepTotals to use getCell with a partial filter.')
cell = @cellIndex[JSON.stringify(normalizedFilter)]
if cell?
return cell
else
return defaultValue
getDimensionValues: (field, descending = false) ->
###
@method getDimensionValues
Returns the unique values for the specified dimension in sort order.
@param {String} field The field whose values you want
@param {Boolean} [descending=false] Set to true if you want them in reverse order
###
values = utils.values(@_dimensionValues[field])
values.sort(utils.compare)
unless descending
values.reverse()
return values
@roundToSignificance: (value, significance) ->
unless significance?
return value
multiple = 1 / significance
return Math.floor(value * multiple) / multiple
slice: (rows, columns, metric, significance) ->
###
@method slice
Extracts a 2D slice of the data. It outputs an array of arrays (JavaScript two-dimensional array) organized as the
C3 charting library would expect if submitting row-oriented data. Note, the output of this function is very similar
to the 2D toString() function output except the data is organized as a two-dimensional array instead of newline-separated
lines and the cells are filled with actual values instead of padded string representations of those values.
@return {[[]]} An array of arrays with the one row for the header and each row label
@param {String} [rows=<first dimension>]
@param {String} [columns=<second dimension>]
@param {String} [metric='count']
@param {Number} [significance] The multiple to which you want to round the bucket edges. 1 means whole numbers.
0.1 means to round to tenths. 0.01 to hundreds. Etc.
###
unless rows?
rows = @config.dimensions[0].field
unless columns?
columns = @config.dimensions[1].field
rowValues = @getDimensionValues(rows)
columnValues = @getDimensionValues(columns)
values = []
topRow = []
topRow.push('x')
for c, indexColumn in columnValues
if c is null
topRow.push('Total')
else
topRow.push(c)
values.push(topRow)
for r, indexRow in rowValues
valuesRow = []
if r is null
valuesRow.push('Total')
else
valuesRow.push(r)
for c, indexColumn in columnValues
filter = {}
filter[rows] = r
filter[columns] = c
cell = @getCell(filter)
if cell?
cellValue = OLAPCube.roundToSignificance(cell[metric], significance)
else
cellValue = null
valuesRow.push(cellValue)
values.push(valuesRow)
return values
@_padToWidth: (s, width, padCharacter = ' ', rightPad = false) ->
if s.length > width
return s.substr(0, width)
padding = new Array(width - s.length + 1).join(padCharacter)
if rightPad
return s + padding
else
return padding + s
getStateForSaving: (meta) ->
###
@method getStateForSaving
Enables saving the state of an OLAPCube.
@param {Object} [meta] An optional parameter that will be added to the serialized output and added to the meta field
within the deserialized OLAPCube
@return {Object} Returns an Ojbect representing the state of the OLAPCube. This Object is suitable for saving to
to an object store. Use the static method `newFromSavedState()` with this Object as the parameter to reconstitute the OLAPCube.
facts = [
{ProjectHierarchy: [1, 2, 3], Priority: 1},
{ProjectHierarchy: [1, 2, 4], Priority: 2},
{ProjectHierarchy: [5] , Priority: 1},
{ProjectHierarchy: [1, 2] , Priority: 1},
]
dimensions = [
{field: "ProjectHierarchy", type: 'hierarchy'},
{field: "Priority"}
]
config = {dimensions, metrics: []}
config.keepTotals = true
originalCube = new OLAPCube(config, facts)
dateString = '2012-12-27T12:34:56.789Z'
savedState = originalCube.getStateForSaving({upToDate: dateString})
restoredCube = OLAPCube.newFromSavedState(savedState)
newFacts = [
{ProjectHierarchy: [5], Priority: 3},
{ProjectHierarchy: [1, 2, 4], Priority: 1}
]
originalCube.addFacts(newFacts)
restoredCube.addFacts(newFacts)
console.log(restoredCube.toString() == originalCube.toString())
# true
console.log(restoredCube.meta.upToDate)
# 2012-12-27T12:34:56.789Z
###
out =
config: @userConfig
cellsAsCSVStyleArray: arrayOfMaps_To_CSVStyleArray(@cells) # !TODO: This makes the package smaller, but it's less well tested than using the Maps like the line below.
# cells: @cells
summaryMetrics: @summaryMetrics
if meta?
out.meta = meta
return out
@newFromSavedState: (p) ->
###
@method newFromSavedState
Deserializes a previously stringified OLAPCube and returns a new OLAPCube.
See `getStateForSaving()` documentation for a detailed example.
Note, if you have specified config.keepFacts = true, the values for the facts will be restored, however, they
will no longer be references to the original facts. For this reason, it's usually better to include a `values` or
`uniqueValues` metric on some ID field if you want fact drill-down support to survive a save and restore.
@static
@param {String/Object} p A String or Object from a previously saved OLAPCube state
@return {OLAPCube}
###
if utils.type(p) is 'string'
p = JSON.parse(p)
cube = new OLAPCube(p.config)
cube.summaryMetrics = p.summaryMetrics
if p.meta?
cube.meta = p.meta
if p.cellsAsCSVStyleArray?
cube.cells = csvStyleArray_To_ArrayOfMaps(p.cellsAsCSVStyleArray)
else
cube.cells = p.cells
cube.cellIndex = {}
cube._dimensionValues = {}
for d in cube.config.dimensions
cube._dimensionValues[d.field] = {}
for c in cube.cells
filterString = JSON.stringify(OLAPCube._extractFilter(c, cube.config.dimensions))
# rebuild cellIndex
cube.cellIndex[filterString] = c
# rebuild _dimensionValues
for d in cube.config.dimensions
fieldValue = c[d.field]
cube._dimensionValues[d.field][JSON.stringify(fieldValue)] = fieldValue
return cube
# cube
context = getContext()
collection = context.getCollection()
unless memo.continuation?
memo.continuation = null
if memo.savedCube?
theCube = OLAPCube.newFromSavedState(memo.savedCube)
else if memo.cubeConfig?
theCube = new OLAPCube(memo.cubeConfig)
else
throw new Error('cubeConfig or savedCube required')
memo.stillQueueing = true
query = () ->
setBody()
if memo.stillQueueing
responseOptions =
continuation: memo.continuation
pageSize: 1000
if memo.filterQuery?
memo.stillQueueing = collection.queryDocuments(collection.getSelfLink(), memo.filterQuery, responseOptions, onReadDocuments)
else
memo.stillQueueing = collection.readDocuments(collection.getSelfLink(), responseOptions, onReadDocuments)
onReadDocuments = (err, resources, options) ->
if err?
throw new Error(JSON.stringify(err))
theCube.addFacts(resources)
memo.savedCube = theCube.getStateForSaving()
memo.example = resources[0]
if options.continuation?
memo.continuation = options.continuation
query()
else
memo.continuation = null
setBody()
setBody = () ->
getContext().getResponse().setBody(memo)
query()
return memo
|
[
{
"context": "# project = { _id: uuid, name: 'cayman', description: 'cayman is a project', authorId: n",
"end": 38,
"score": 0.9978004693984985,
"start": 32,
"tag": "NAME",
"value": "cayman"
},
{
"context": "ject = { _id: uuid, name: 'cayman', description: 'cayman is a project', auth... | client/projects.coffee | tyrchen/teamspark | 21 | # project = { _id: uuid, name: 'cayman', description: 'cayman is a project', authorId: null, parentId: null, teamId: teamId, createdAt: Date() }
_.extend Template.projects,
events:
'click #filter-team': (e) ->
ts.State.filterType.set 'team'
'click #filter-member': (e) ->
ts.State.filterType.set 'user'
'click .filter-project': (e) ->
$node = $(e.currentTarget)
id = $node.data('id')
name = $node.data('name')
if id == ''
ts.State.filterSelected.set {id: 'all', name: 'all'}
else
ts.State.filterSelected.set {id: id, name: name}
Router.setProject id
'click #add-project': (e) ->
$('#add-project-dialog').modal()
'click #add-project-submit': (e) ->
$form = $('#add-project-dialog form')
$name = $('input[name="name"]', $form)
name = $name.val()
description = $('textarea[name="description"]', $form).val()
parentId = $('select[name="parent"]', $form).val()
if parentId is 'null'
parentId = null
#console.log "name: #{name}, desc: #{description}, parent: #{parentId}"
count = Projects.find({name: name, teamId: Meteor.user().teamId}).count()
if not name or count > 0
$name.parent().addClass 'error'
return null
Actions.createProject name, description, parentId
$('.control-group', $form).removeClass 'error'
$form[0].reset()
$('#add-project-dialog').modal 'hide'
'click #add-project-cancel': (e) ->
$('#add-project-dialog form .control-group').removeClass 'error'
$('#add-project-dialog').modal 'hide'
isActiveMember: ->
if ts.filteringUser()
return 'active'
return ''
isActiveTeam: ->
if ts.filteringTeam()
return 'active'
return ''
isFilterSelected: (id='all') ->
if ts.State.filterSelected.get() is id
return 'active'
return ''
totalUnfinished: (id=null) ->
ts.sparks.totalUnfinished id, null
hasProject: -> Projects.find().count()
projects: -> Projects.find()
parentProjects: -> Projects.find parent: null
childProjects: (id)-> Projects.find parent: id | 79535 | # project = { _id: uuid, name: '<NAME>', description: '<NAME> is a project', authorId: null, parentId: null, teamId: teamId, createdAt: Date() }
_.extend Template.projects,
events:
'click #filter-team': (e) ->
ts.State.filterType.set 'team'
'click #filter-member': (e) ->
ts.State.filterType.set 'user'
'click .filter-project': (e) ->
$node = $(e.currentTarget)
id = $node.data('id')
name = $node.data('name')
if id == ''
ts.State.filterSelected.set {id: 'all', name: 'all'}
else
ts.State.filterSelected.set {id: id, name: name}
Router.setProject id
'click #add-project': (e) ->
$('#add-project-dialog').modal()
'click #add-project-submit': (e) ->
$form = $('#add-project-dialog form')
$name = $('input[name="name"]', $form)
name = $name.val()
description = $('textarea[name="description"]', $form).val()
parentId = $('select[name="parent"]', $form).val()
if parentId is 'null'
parentId = null
#console.log "name: #{name}, desc: #{description}, parent: #{parentId}"
count = Projects.find({name: name, teamId: Meteor.user().teamId}).count()
if not name or count > 0
$name.parent().addClass 'error'
return null
Actions.createProject name, description, parentId
$('.control-group', $form).removeClass 'error'
$form[0].reset()
$('#add-project-dialog').modal 'hide'
'click #add-project-cancel': (e) ->
$('#add-project-dialog form .control-group').removeClass 'error'
$('#add-project-dialog').modal 'hide'
isActiveMember: ->
if ts.filteringUser()
return 'active'
return ''
isActiveTeam: ->
if ts.filteringTeam()
return 'active'
return ''
isFilterSelected: (id='all') ->
if ts.State.filterSelected.get() is id
return 'active'
return ''
totalUnfinished: (id=null) ->
ts.sparks.totalUnfinished id, null
hasProject: -> Projects.find().count()
projects: -> Projects.find()
parentProjects: -> Projects.find parent: null
childProjects: (id)-> Projects.find parent: id | true | # project = { _id: uuid, name: 'PI:NAME:<NAME>END_PI', description: 'PI:NAME:<NAME>END_PI is a project', authorId: null, parentId: null, teamId: teamId, createdAt: Date() }
_.extend Template.projects,
events:
'click #filter-team': (e) ->
ts.State.filterType.set 'team'
'click #filter-member': (e) ->
ts.State.filterType.set 'user'
'click .filter-project': (e) ->
$node = $(e.currentTarget)
id = $node.data('id')
name = $node.data('name')
if id == ''
ts.State.filterSelected.set {id: 'all', name: 'all'}
else
ts.State.filterSelected.set {id: id, name: name}
Router.setProject id
'click #add-project': (e) ->
$('#add-project-dialog').modal()
'click #add-project-submit': (e) ->
$form = $('#add-project-dialog form')
$name = $('input[name="name"]', $form)
name = $name.val()
description = $('textarea[name="description"]', $form).val()
parentId = $('select[name="parent"]', $form).val()
if parentId is 'null'
parentId = null
#console.log "name: #{name}, desc: #{description}, parent: #{parentId}"
count = Projects.find({name: name, teamId: Meteor.user().teamId}).count()
if not name or count > 0
$name.parent().addClass 'error'
return null
Actions.createProject name, description, parentId
$('.control-group', $form).removeClass 'error'
$form[0].reset()
$('#add-project-dialog').modal 'hide'
'click #add-project-cancel': (e) ->
$('#add-project-dialog form .control-group').removeClass 'error'
$('#add-project-dialog').modal 'hide'
isActiveMember: ->
if ts.filteringUser()
return 'active'
return ''
isActiveTeam: ->
if ts.filteringTeam()
return 'active'
return ''
isFilterSelected: (id='all') ->
if ts.State.filterSelected.get() is id
return 'active'
return ''
totalUnfinished: (id=null) ->
ts.sparks.totalUnfinished id, null
hasProject: -> Projects.find().count()
projects: -> Projects.find()
parentProjects: -> Projects.find parent: null
childProjects: (id)-> Projects.find parent: id |
[
{
"context": "#\n# The Ajax main unit\n#\n# Copyright (C) 2011 Nikolay Nemshilov\n#\nclass Ajax\n include: [core.Options, core.Event",
"end": 63,
"score": 0.9998812675476074,
"start": 46,
"tag": "NAME",
"value": "Nikolay Nemshilov"
}
] | stl/ajax/src/ajax.coffee | lovely-io/lovely.io-stl | 2 | #
# The Ajax main unit
#
# Copyright (C) 2011 Nikolay Nemshilov
#
class Ajax
include: [core.Options, core.Events]
extend:
#
# default options
#
Options:
method: 'post' # default request method
encoding: 'utf-8' # default request encoding
evalResponse: false # forced response eval
evalJS: true # auto-eval text/javascript responses
evalJSON: true # auto-convert text/json data
urlEncoded: true # url-encode params and data
spinner: null # spinner reference a css-rule or an element object
params: null # params to send. string or a hash
jsonp: false # perform a JSONP request
headers: { # default headers
'X-Requested-With': 'XMLHttpRequest'
'Accept': 'text/javascript,text/html,application/xml,text/xml,*/*'
}
#
# A shortcut to make a quick GET request
#
# @param {String} url-address
# @param {Object} options
# @return {Ajax} request
#
get: (url, options)->
options or= {}
options.method = 'get' unless 'method' of options
new Ajax(url, options).send()
# public params
_: null # raw XMLHttpRequest object
url: null # the url address
status: null # HTTP response status code
responseText: null
responseXML: null
responseJSON: null
headerJSON: null # JSON data from the X-JSON header
#
# Basic Ajax constructor
#
# @param {String} url address
# @param {Object} options
# @return {Ajax} this
#
constructor: (url, options) ->
@url = url
@options = ext({}, Ajax.Options)
@options = ext(@options, options)
# attaching the standard listeners
@on 'complete', 'evalScripts'
@on
create: 'showSpinner'
complete: 'hideSpinner'
cancel: 'hideSpinner'
# catching the event listeners that are specified in the options
for key, method of @options
if key in ['success', 'failure', 'complete', 'create', 'request', 'progress', 'cancel']
@on key, method
return @
#
# Sets a request header key-value, or reads a response header
#
# @param {String} header name
# @param {String} header value
# @return {String|Ajax} header value or this request
#
header: (name, value)->
if arguments.length is 1
try # in case there is no request yet, or the name is bogus
return @_.getResponseHeader(name)
catch e
return undefined
else
@options.headers[name] = value
return @
#
# Checks if the status of the request is successful
#
# @return {Boolean} check result
#
successful: ->
@status >= 200 && @status < 400
#
# Sends the request to the server
#
# @return {Ajax} this
#
send: ->
options = @options
headers = @options.headers
params = Ajax_merge(Ajax.Options.params, options.params)
method = @options.method.toLowerCase()
url = @url
if method in ['put', 'delete']
params._method = method
method = 'post'
if method is 'post' and options.urlEncoded and !headers['Content-type']
headers['Content-type'] = 'application/x-www-form-urlencoded;charset='+ options.encoding
params = Hash.toQueryString(params)
if method is 'get'
if params
url = url + (if url.indexOf('?') is -1 then '?' else '&')
url += params
params = null
xhr = @_ = if @options.jsonp then new JSONP(@) else new XMLHttpRequest()
@emit 'create'
xhr.open(method, url, true) # <- it's always an async request!
xhr.onreadystatechange = Ajax_state(@)
if 'upload' of xhr # HTML5 upload progress
xhr.upload.onprogress =
xhr.upload.onload = bind((e)->
if e.lengthComputable
@emit 'progress',
loaded: e.loaded,
total: e.total
, @)
# sending the headers
for name of headers
xhr.setRequestHeader(name, headers[name])
# sending the data
xhr.send(Ajax_prepare(params, options))
@emit 'request'
xhr.onreadystatechange() if xhr instanceof JSONP
return @
#
# Cancels the request
#
# @return {Ajax} this
#
cancel: ->
return @ if @__canceled
if @_
@_.abort()
@_.onreadystatechange = ->
@_.canceled = true
return @emit('cancel')
#
# Overloading the original method so that
# it sent this ajax request and the raw XHR
# objects to the listner as the default arguments
# It also fires `ajax:eventname` dom-events on the
# `document` object so that they could be catched up
# in there, in case you need to have some global
# ajax events listener
#
# @param {String} event name
# @param {Object} event options
# @return {Ajax} this
#
emit: (name, options)->
options = ext(ajax: @, options)
super(name, options)
doc.emit("ajax:#{name}",options)
return @
# protected
#
# Tries to auto-handle JavaScript and JSON responses
#
# @return void
#
evalScripts: ->
content_type = @header('Content-type') || ''
options = @options
if options.evalResponse or (options.evalJS && /(ecma|java)script/i.test(content_type))
$.eval(@responseText)
else if options.evalJSON and /json/i.test(content_type)
@responseJSON = JSON.parse(@responseText)
if options = @header('X-JSON')
this.headerJSON = JSON.parse(options)
return;
#
# Tries to show the current spinner
#
# @return void
#
showSpinner: ->
Ajax_spinner(@, 'show')
#
# Tries to hide the current spinner
#
# @return void
#
hideSpinner: ->
Ajax_spinner(@, 'hide')
# private
# global spinner handling
Ajax_counter = 0
Ajax_spinner = (ajax, operation)->
spinner = ajax.options.spinner
spinner = spinner && $(spinner)[0]
shared = Ajax.Options.spinner
shared = shared && $(shared)[0]
if spinner
if spinner is shared
# counting the number of requests to handle the global spinner correctly
Ajax_counter += if operation is 'show' then 1 else -1
if operation is 'show' or Ajax_counter < 1
spinner[operation]()
else
# just show/hide a local spinner
spinner[operation]()
return ajax
# merges the data from various formats into a single hash object
Ajax_merge = ->
hash = {}
for params in arguments
if typeof(params) is 'string'
params = Hash.fromQueryString(params)
else if params instanceof Form
params = params.values()
for key of params
hash[key] = params[key]
return hash
# prepares HTML5 FormData with files to upload when needed
Ajax_prepare = (params, options)->
# sending XHR2 FormData object if the form has files
if (form = options.params) instanceof Form and form.first('input[type="file"]')
data = new global.FormData(form._)
params = Hash.fromQueryString(params)
for name, value of params
unless form.input(name)
data.append(name, value)
params = data
params
# makes an 'onreadystatechange' listener
Ajax_state = (ajax)->
xhr = ajax._
return ->
return undefined if xhr.readyState isnt 4 or xhr.canceled
try
ajax.status = xhr.status
catch e
ajax.status = 0
ajax.responseText = xhr.responseText
ajax.responseXML = xhr.responseXML
ajax.emit('complete')
ajax.emit(if ajax.successful() then 'success' else 'failure')
| 158900 | #
# The Ajax main unit
#
# Copyright (C) 2011 <NAME>
#
class Ajax
include: [core.Options, core.Events]
extend:
#
# default options
#
Options:
method: 'post' # default request method
encoding: 'utf-8' # default request encoding
evalResponse: false # forced response eval
evalJS: true # auto-eval text/javascript responses
evalJSON: true # auto-convert text/json data
urlEncoded: true # url-encode params and data
spinner: null # spinner reference a css-rule or an element object
params: null # params to send. string or a hash
jsonp: false # perform a JSONP request
headers: { # default headers
'X-Requested-With': 'XMLHttpRequest'
'Accept': 'text/javascript,text/html,application/xml,text/xml,*/*'
}
#
# A shortcut to make a quick GET request
#
# @param {String} url-address
# @param {Object} options
# @return {Ajax} request
#
get: (url, options)->
options or= {}
options.method = 'get' unless 'method' of options
new Ajax(url, options).send()
# public params
_: null # raw XMLHttpRequest object
url: null # the url address
status: null # HTTP response status code
responseText: null
responseXML: null
responseJSON: null
headerJSON: null # JSON data from the X-JSON header
#
# Basic Ajax constructor
#
# @param {String} url address
# @param {Object} options
# @return {Ajax} this
#
constructor: (url, options) ->
@url = url
@options = ext({}, Ajax.Options)
@options = ext(@options, options)
# attaching the standard listeners
@on 'complete', 'evalScripts'
@on
create: 'showSpinner'
complete: 'hideSpinner'
cancel: 'hideSpinner'
# catching the event listeners that are specified in the options
for key, method of @options
if key in ['success', 'failure', 'complete', 'create', 'request', 'progress', 'cancel']
@on key, method
return @
#
# Sets a request header key-value, or reads a response header
#
# @param {String} header name
# @param {String} header value
# @return {String|Ajax} header value or this request
#
header: (name, value)->
if arguments.length is 1
try # in case there is no request yet, or the name is bogus
return @_.getResponseHeader(name)
catch e
return undefined
else
@options.headers[name] = value
return @
#
# Checks if the status of the request is successful
#
# @return {Boolean} check result
#
successful: ->
@status >= 200 && @status < 400
#
# Sends the request to the server
#
# @return {Ajax} this
#
send: ->
options = @options
headers = @options.headers
params = Ajax_merge(Ajax.Options.params, options.params)
method = @options.method.toLowerCase()
url = @url
if method in ['put', 'delete']
params._method = method
method = 'post'
if method is 'post' and options.urlEncoded and !headers['Content-type']
headers['Content-type'] = 'application/x-www-form-urlencoded;charset='+ options.encoding
params = Hash.toQueryString(params)
if method is 'get'
if params
url = url + (if url.indexOf('?') is -1 then '?' else '&')
url += params
params = null
xhr = @_ = if @options.jsonp then new JSONP(@) else new XMLHttpRequest()
@emit 'create'
xhr.open(method, url, true) # <- it's always an async request!
xhr.onreadystatechange = Ajax_state(@)
if 'upload' of xhr # HTML5 upload progress
xhr.upload.onprogress =
xhr.upload.onload = bind((e)->
if e.lengthComputable
@emit 'progress',
loaded: e.loaded,
total: e.total
, @)
# sending the headers
for name of headers
xhr.setRequestHeader(name, headers[name])
# sending the data
xhr.send(Ajax_prepare(params, options))
@emit 'request'
xhr.onreadystatechange() if xhr instanceof JSONP
return @
#
# Cancels the request
#
# @return {Ajax} this
#
cancel: ->
return @ if @__canceled
if @_
@_.abort()
@_.onreadystatechange = ->
@_.canceled = true
return @emit('cancel')
#
# Overloading the original method so that
# it sent this ajax request and the raw XHR
# objects to the listner as the default arguments
# It also fires `ajax:eventname` dom-events on the
# `document` object so that they could be catched up
# in there, in case you need to have some global
# ajax events listener
#
# @param {String} event name
# @param {Object} event options
# @return {Ajax} this
#
emit: (name, options)->
options = ext(ajax: @, options)
super(name, options)
doc.emit("ajax:#{name}",options)
return @
# protected
#
# Tries to auto-handle JavaScript and JSON responses
#
# @return void
#
evalScripts: ->
content_type = @header('Content-type') || ''
options = @options
if options.evalResponse or (options.evalJS && /(ecma|java)script/i.test(content_type))
$.eval(@responseText)
else if options.evalJSON and /json/i.test(content_type)
@responseJSON = JSON.parse(@responseText)
if options = @header('X-JSON')
this.headerJSON = JSON.parse(options)
return;
#
# Tries to show the current spinner
#
# @return void
#
showSpinner: ->
Ajax_spinner(@, 'show')
#
# Tries to hide the current spinner
#
# @return void
#
hideSpinner: ->
Ajax_spinner(@, 'hide')
# private
# global spinner handling
Ajax_counter = 0
Ajax_spinner = (ajax, operation)->
spinner = ajax.options.spinner
spinner = spinner && $(spinner)[0]
shared = Ajax.Options.spinner
shared = shared && $(shared)[0]
if spinner
if spinner is shared
# counting the number of requests to handle the global spinner correctly
Ajax_counter += if operation is 'show' then 1 else -1
if operation is 'show' or Ajax_counter < 1
spinner[operation]()
else
# just show/hide a local spinner
spinner[operation]()
return ajax
# merges the data from various formats into a single hash object
Ajax_merge = ->
hash = {}
for params in arguments
if typeof(params) is 'string'
params = Hash.fromQueryString(params)
else if params instanceof Form
params = params.values()
for key of params
hash[key] = params[key]
return hash
# prepares HTML5 FormData with files to upload when needed
Ajax_prepare = (params, options)->
# sending XHR2 FormData object if the form has files
if (form = options.params) instanceof Form and form.first('input[type="file"]')
data = new global.FormData(form._)
params = Hash.fromQueryString(params)
for name, value of params
unless form.input(name)
data.append(name, value)
params = data
params
# makes an 'onreadystatechange' listener
Ajax_state = (ajax)->
xhr = ajax._
return ->
return undefined if xhr.readyState isnt 4 or xhr.canceled
try
ajax.status = xhr.status
catch e
ajax.status = 0
ajax.responseText = xhr.responseText
ajax.responseXML = xhr.responseXML
ajax.emit('complete')
ajax.emit(if ajax.successful() then 'success' else 'failure')
| true | #
# The Ajax main unit
#
# Copyright (C) 2011 PI:NAME:<NAME>END_PI
#
class Ajax
include: [core.Options, core.Events]
extend:
#
# default options
#
Options:
method: 'post' # default request method
encoding: 'utf-8' # default request encoding
evalResponse: false # forced response eval
evalJS: true # auto-eval text/javascript responses
evalJSON: true # auto-convert text/json data
urlEncoded: true # url-encode params and data
spinner: null # spinner reference a css-rule or an element object
params: null # params to send. string or a hash
jsonp: false # perform a JSONP request
headers: { # default headers
'X-Requested-With': 'XMLHttpRequest'
'Accept': 'text/javascript,text/html,application/xml,text/xml,*/*'
}
#
# A shortcut to make a quick GET request
#
# @param {String} url-address
# @param {Object} options
# @return {Ajax} request
#
get: (url, options)->
options or= {}
options.method = 'get' unless 'method' of options
new Ajax(url, options).send()
# public params
_: null # raw XMLHttpRequest object
url: null # the url address
status: null # HTTP response status code
responseText: null
responseXML: null
responseJSON: null
headerJSON: null # JSON data from the X-JSON header
#
# Basic Ajax constructor
#
# @param {String} url address
# @param {Object} options
# @return {Ajax} this
#
constructor: (url, options) ->
@url = url
@options = ext({}, Ajax.Options)
@options = ext(@options, options)
# attaching the standard listeners
@on 'complete', 'evalScripts'
@on
create: 'showSpinner'
complete: 'hideSpinner'
cancel: 'hideSpinner'
# catching the event listeners that are specified in the options
for key, method of @options
if key in ['success', 'failure', 'complete', 'create', 'request', 'progress', 'cancel']
@on key, method
return @
#
# Sets a request header key-value, or reads a response header
#
# @param {String} header name
# @param {String} header value
# @return {String|Ajax} header value or this request
#
header: (name, value)->
if arguments.length is 1
try # in case there is no request yet, or the name is bogus
return @_.getResponseHeader(name)
catch e
return undefined
else
@options.headers[name] = value
return @
#
# Checks if the status of the request is successful
#
# @return {Boolean} check result
#
successful: ->
@status >= 200 && @status < 400
#
# Sends the request to the server
#
# @return {Ajax} this
#
send: ->
options = @options
headers = @options.headers
params = Ajax_merge(Ajax.Options.params, options.params)
method = @options.method.toLowerCase()
url = @url
if method in ['put', 'delete']
params._method = method
method = 'post'
if method is 'post' and options.urlEncoded and !headers['Content-type']
headers['Content-type'] = 'application/x-www-form-urlencoded;charset='+ options.encoding
params = Hash.toQueryString(params)
if method is 'get'
if params
url = url + (if url.indexOf('?') is -1 then '?' else '&')
url += params
params = null
xhr = @_ = if @options.jsonp then new JSONP(@) else new XMLHttpRequest()
@emit 'create'
xhr.open(method, url, true) # <- it's always an async request!
xhr.onreadystatechange = Ajax_state(@)
if 'upload' of xhr # HTML5 upload progress
xhr.upload.onprogress =
xhr.upload.onload = bind((e)->
if e.lengthComputable
@emit 'progress',
loaded: e.loaded,
total: e.total
, @)
# sending the headers
for name of headers
xhr.setRequestHeader(name, headers[name])
# sending the data
xhr.send(Ajax_prepare(params, options))
@emit 'request'
xhr.onreadystatechange() if xhr instanceof JSONP
return @
#
# Cancels the request
#
# @return {Ajax} this
#
cancel: ->
return @ if @__canceled
if @_
@_.abort()
@_.onreadystatechange = ->
@_.canceled = true
return @emit('cancel')
#
# Overloading the original method so that
# it sent this ajax request and the raw XHR
# objects to the listner as the default arguments
# It also fires `ajax:eventname` dom-events on the
# `document` object so that they could be catched up
# in there, in case you need to have some global
# ajax events listener
#
# @param {String} event name
# @param {Object} event options
# @return {Ajax} this
#
emit: (name, options)->
options = ext(ajax: @, options)
super(name, options)
doc.emit("ajax:#{name}",options)
return @
# protected
#
# Tries to auto-handle JavaScript and JSON responses
#
# @return void
#
evalScripts: ->
content_type = @header('Content-type') || ''
options = @options
if options.evalResponse or (options.evalJS && /(ecma|java)script/i.test(content_type))
$.eval(@responseText)
else if options.evalJSON and /json/i.test(content_type)
@responseJSON = JSON.parse(@responseText)
if options = @header('X-JSON')
this.headerJSON = JSON.parse(options)
return;
#
# Tries to show the current spinner
#
# @return void
#
showSpinner: ->
Ajax_spinner(@, 'show')
#
# Tries to hide the current spinner
#
# @return void
#
hideSpinner: ->
Ajax_spinner(@, 'hide')
# private
# global spinner handling
Ajax_counter = 0
Ajax_spinner = (ajax, operation)->
spinner = ajax.options.spinner
spinner = spinner && $(spinner)[0]
shared = Ajax.Options.spinner
shared = shared && $(shared)[0]
if spinner
if spinner is shared
# counting the number of requests to handle the global spinner correctly
Ajax_counter += if operation is 'show' then 1 else -1
if operation is 'show' or Ajax_counter < 1
spinner[operation]()
else
# just show/hide a local spinner
spinner[operation]()
return ajax
# merges the data from various formats into a single hash object
Ajax_merge = ->
hash = {}
for params in arguments
if typeof(params) is 'string'
params = Hash.fromQueryString(params)
else if params instanceof Form
params = params.values()
for key of params
hash[key] = params[key]
return hash
# prepares HTML5 FormData with files to upload when needed
Ajax_prepare = (params, options)->
# sending XHR2 FormData object if the form has files
if (form = options.params) instanceof Form and form.first('input[type="file"]')
data = new global.FormData(form._)
params = Hash.fromQueryString(params)
for name, value of params
unless form.input(name)
data.append(name, value)
params = data
params
# makes an 'onreadystatechange' listener
Ajax_state = (ajax)->
xhr = ajax._
return ->
return undefined if xhr.readyState isnt 4 or xhr.canceled
try
ajax.status = xhr.status
catch e
ajax.status = 0
ajax.responseText = xhr.responseText
ajax.responseXML = xhr.responseXML
ajax.emit('complete')
ajax.emit(if ajax.successful() then 'success' else 'failure')
|
[
{
"context": "fix].namespace if namespace == undefined\n key = \"#{namespace}.#{key}\" if namespace\n prefix = key.split(':')[0]\n",
"end": 11222,
"score": 0.9325066804885864,
"start": 11206,
"tag": "KEY",
"value": "\"#{namespace}.#{"
},
{
"context": "mespace == undefined\n ... | lib/worker.coffee | waterfield/redeye | 0 | require 'fibers'
msgpack = require 'msgpack'
_ = require './util'
{ DependencyError, MultiError } = require './errors'
# One worker is constructed for every task coming
# through the work queue(s). It maintains a local cache
# of dependency values, a workspace for running the
# key code, and contains the core API for redeye.
# It runs worker code in a fiber, yielding the fiber
# every time asynchronous work (such as waiting for
# dependencies) must be done.
class Worker
# Break key into prefix and arguments, and set up worker cache.
constructor: (@id, @key, @queue, @old_deps, @manager) ->
[@prefix, @args...] = @key.split ':'
@convert_args()
@workspace = new Worker.Workspace
params = @manager.params[@prefix] || []
@workspace[param] = @args[i] for param, i in params
{ @pool } = @manager
@cache = {}
@deps = []
# API METHODS
# ===========
# `@async (callback) -> ... callback(err, value)`
#
# Uses paired `@yield` and `@resume` to perform an asynchronous
# function outside the worker fiber. The function should call the
# callback with arguments `error` and `value`, where `value`
# will be the result of the `@async` call. The `error`, if any, will
# be thrown from inside the fiber, to produce sensible stack traces.
async: (body) ->
body (err, value) =>
@resume err, value
@yield()
# `@sleep(seconds)`
#
# Pause the fiber for the specified number of seconds.
sleep: (n) ->
@async (callback) -> setTimeout callback, n*1000
# `@log(label, payload)`
#
# Use the `Manager#log` function to log a message for this key.
# The resulting message will include `@key` in the payload.
log: (label, payload) ->
@manager.log @key, label, payload
# `@get(prefix, args..., opts, callback)`
#
# Retrieve another key given the named prefix and its arguments.
# Three things can happen with this request under normal operation:
#
# * The key is already in our local `@cache`; its already-built
# value is just returned.
# * The key is available in the database. It is retrieved and built
# into an object if applicable. The dependency is marked in
# the database, and the built value is returned.
# * The key is not available in the database. The dependency is
# recorded and a new job will be enqueued (unless that job is
# already being run somewhere). Once the manager is notitied
# of completion of the key with the `ready` control message,
# `@get` will resume.
#
# The following options can be provided:
#
# * `as`: if provided, should be a class. The raw value of the key
# will be passed to its constructor. A common pattern for this is:
#
# class Wrapper extends Workspace
# constructor: (raw) ->
# super()
# _.extend @, raw
#
# By extending `Workspace`, the wrapper class has access to the
# worker's API methods.
#
# `@get` can return two kinds of errors:
#
# * `DependencyError`: the requested key had an error which is being
# bubbled up to this worker
# * `CycleError`: making the given request would result in a cycle
#
# Both kinds of errors can be caught and handled normally. Dependency
# errors are stored as the result of this key, and include a full backtrace
# through all workers' stacks.
get: (args...) ->
return @defer_get(args) if @in_each
{ prefix, opts, key } = @parse_args args
cached = @check_cache(key)
return cached if cached != undefined
@deps.push key
@require [key], (err, values) =>
if err
@resume err
else if values[0] != undefined
@resume null, values
else
@wait [key]
@got prefix, key, @build(@yield()[0], prefix, opts), opts
# `@keys(key_pattern)`
#
# Search for the given keys in the database and return them.
keys: (pattern) ->
@async (callback) =>
@db.keys pattern, callback
# `@atomic(key, value)
#
# Atomically set the given key to a value.
atomic: (key, value) ->
@async (callback) =>
@db.multi()
.setnx(key, value)
.get(key)
.exec (err, arr) =>
value = arr[1] unless err
callback err, value
# `@yield()`
#
# Suspend the worker fiber until `@resume` is called. If `@resume`
# is called with an error, throw that error on resume; otherwise,
# `@yield` will return the value passed to `@resume`. The error is
# thrown from inside the fiber in order to create sensible stack traces.
yield: ->
Worker.current = null
[ err, value ] = Fiber.yield()
throw err if err
value
# `@resume(error, value)`
#
# Resume a suspended worker fiber. If `error` is provided, it will
# be thrown from the fiber. Otherwise, `value` will be returned from
# the last call to `@yield`. If the fiber throws an error, record
# that error as the result of the worker for this key.
resume: (err, value) ->
return @implode() if @dirty
@try_acquire_db (err2) =>
if @waiting_for && !err
@stop_waiting()
return
Worker.current = this
try
@fiber.run [err || err2, value]
catch e
@error e
# `@run()`
#
# Start running the worker for the first time. Sets up the
# worker fiber, clears the worker, and starts running the
# worker body. Uses `@resume` so that errors are properly
# caught. Take the result of the worker body as the value
# of this key and passing it to `@finish`. If there is no
# worker body defined for this prefix, throw an error.
run: ->
@fiber = Fiber =>
if runner = @manager.runners[@prefix]
@finish runner.apply(@workspace, @args)
else
throw new Error "No runner for prefix '#{@prefix}'"
@resume()
# `@with key1: [vals...], key2: [vals...], -> ...`
#
# Iterate the keys over the cross-product of the provided values.
# For each iteration, call the given function. This function is used
# by `@all` and `@each`, but can also be used directly. The function
# will be called in the context of the workspace.
#
# In each iteration, the keys are recorded into the workspace object.
# That means if you can do something like the following:
#
# @with foo: ['bar', 'baz'], ->
# console.log @foo
#
# which would print 'bar', then 'baz'.
#
# Because `Workspace` provides a simplified API for accessing other
# worker keys and inputs, `@with` can be used to provide argument
# context like so:
#
# # @worker 'foo', 'id', -> ...
# @with id: [1,2], @foo
#
# which would first `@get('foo', 1)` and then `@get('foo', 2)`.
#
# NOTE: Please do not nest calls to `@with`, `@each`, or `@all`!
with: (hash, fun, keys) ->
@in_each = true
unless keys
unless fun
fun = hash
hash = {}
keys = _.keys(hash)
@context = {}
@context_list = []
@gets = []
if key = keys.shift()
for val in (hash[key] ? [])
@context[key] = val
@workspace[key] = val
@with hash, fun, keys
delete @context[key]
keys.unshift key
else
fun.apply @workspace
@in_each = false
# `@each key1: [vals...], key2: [vals...], -> ...`
#
# Uses the same syntax as `@with`. Each `@get` call from within
# the body is recorded. Before `@each` returns, it ensures all
# these dependencies are met, but does not bother to actually
# return them. Instead it will return the total number of `@get`
# dependencies. If one or more of the dependencies has an error,
# then this call will throw a `MultiError` with the error keys.
# Each error within the `MultiError` records the `context` under
# which it was requested with `@get`.
#
# All dependencies will be satisfied in parallel.
#
# TODO: This could be more efficient. Hard to check for errors though.
each: (hash, fun) ->
@all(hash, fun).length
# `@all key1: [vals...], key2: [vals...], -> ...`
#
# Uses the same syntax as `@with`. Each `@get` call from within
# the body is recorded. Before `@all` returns, it ensures all
# these dependencies are met, and then returns them all in an
# array. If one or more of the dependencies has an error,
# then this call will throw a `MultiError` with the error keys.
# Each error within the `MultiError` records the `context` under
# which it was requested with `@get`.
#
# All dependencies will be satisfied in parallel.
all: (hash, fun) ->
@with hash, fun
@record_all_opts()
@find_needed_keys()
@discover_missing_keys()
@build_all()
# `@worker()`
#
# Return the current worker object.
worker: ->
Worker.current
# INTERNAL METHODS
# ================
# Get a database client from the pool, set `@db`, and call back.
acquire_db: (callback) ->
if @db
err = new Error "Tried to acquire db when we already had one"
return callback err
@pool.acquire (err, @db) =>
callback err
# Release our database client back to the pool.
release_db: (callback) ->
unless @db
err = new Error "Tried to release db when we didn't have one"
return callback err
@pool.release @db
@db = null
callback?()
# Acquire a database connection, but don't panic if we already have one.
try_acquire_db: (callback) ->
if @db
callback()
else
@acquire_db callback
# Release our database connection and null out the fiber so that this
# worker object can be garbage collected.
implode: ->
@dirty = true # so callbacks will also implode
@release_db() if @db
@fiber = null
# The worker is done and this is its value. Convert using `toJSON` if present,
# set the key's value, then tell the queue that the key should be released.
finish: (value) ->
Worker.current = null
return @implode() if @dirty
value = value?.toJSON?() ? value
# if pack = @manager.opts[@prefix]?.pack
# value = @pack_fields value, pack if value && !value.error
value = JSON.stringify(value ? null)
@manager.finish @id, @key, value, (ok) =>
if ok
@fix_source_targets => @implode()
else
@implode()
# We may have dropped some dependencies; in that case, remove us as a
# target from the dropped ones.
fix_source_targets: (callback) ->
bad_deps = []
for dep in @old_deps
unless dep in @deps
bad_deps.push dep
return callback() unless bad_deps.length
m = @db.multi()
for dep in bad_deps
m.srem 'targets:'+dep, @key
@manager.unrequire dep, @key
m.exec callback
# Convert the given error message or object into a value
# suitable for exception bubbling, then set that error as the
# result of this key with `@finish`.
error: (err) ->
trace = err.stack ? err
slice = @manager.slice
error = err.get_tail?() ? [{ trace, @key, slice }]
@finish { error }
# Parse the @get arguments into the prefix, key arguments,
# and options.
parse_args: (args) ->
_.callback args
opts = _.opts args
key = args.join ':'
namespace = opts.namespace
namespace = @manager.opts[@prefix].namespace if namespace == undefined
key = "#{namespace}.#{key}" if namespace
prefix = key.split(':')[0]
{ prefix, opts, key }
# Look in both our local cache and in the LRU cache for the given
# key. If found locally, just return it. If found in the LRU cache,
# return it but also link as dependency. If not found, returns undefined.
check_cache: (key) ->
if (cached = @cache[key]) != undefined
cached
else if (value = @manager.check_helpers(key)) != undefined
if typeof(value) == 'function'
yielded = false
the_result = undefined
value (err, result) =>
if yielded
@fiber.run([err, result])
else
the_result = [err, result]
if the_result != undefined
Worker.current = this
[e, v] = the_result
throw e if e
return v
yielded = true
[e, v] = Fiber.yield()
Worker.current = this
throw e if e
v
else
[e, v] = value
throw e if e
v
else if (cached = @manager.check_cache(key)) != undefined
msg = source: key, target: @key
msg.slice = @manager.slice if @manager.slice
msg = JSON.stringify(msg ? null)
@db.multi()
.sadd('sources:'+@key, key)
.sadd('targets:'+key, @key)
.publish('redeye:require', msg)
.exec (err) -> throw err if err
@cache[key] = cached
else
undefined
# We built a fresh value from the database. Add it to our cache as
# well as the manager's LRU cache.
got: (prefix, key, value, opts) ->
@cache[key] = @manager.add_to_cache(prefix, key, value, opts.sticky)
# Inform the manager of this dependency.
require: (sources, callback) ->
@manager.require @queue, sources, @key, callback
# Tell the manager to resume us when all the given dependencies are ready.
# Once resumed, look up the value of all the dependencies, and resume with them.
wait: (deps) ->
@waiting_for = (new Buffer dep for dep in deps)
@release_db (err) =>
return @resume err if err
@manager.wait deps, @key
# We have resumed after the last `@wait`, so look up the keys we're waiting on
# and resume the fiber with them.
stop_waiting: ->
@db.mget @waiting_for, (err, arr) =>
# console.log "Worker#stop_waiting", { arr }
return @resume err if err
arr = for buf, index in arr
# console.log { buf, unpacked: msgpack.unpack(buf) }
if buf
JSON.parse buf
else
(err ||= []).push @waiting_for[index]
undefined
@waiting_for = null
if err
@resume "PLEASE CONTACT WATERFIELD ENERGY DEV TEAM ABOUT THIS ERROR\n#{@key} expected finished keys but got nulls: #{err.join ','}"
else
@resume null, arr
# Because we're in an `@each` or `@all` block, don't attempt
# to get the key yet; instead, just record the context and
# arguments at the time `@get` was called, to be retrieved in
# a batch later.
defer_get: (args) ->
@context_list.push _.clone(@context)
@gets.push args
# Check if the returned value is an error. If so, prepend the
# current context to the error trace and re-throw it.
#
# Otherwise, if there is an `as` option specified for the value's
# prefix, construct an object with the wrapper class.
build: (value, prefix, opts) ->
return value unless value?
@test_for_error value
# if pack = @manager.opts[prefix]?.pack
# value = @unpack_fields value, pack if value
if wrapper = opts.as || @manager.opts[prefix]?.as
new wrapper(value)
else
value
# Test if the given value looks like a redeye recorded error;
# that is, it is an object with an array 'error' field. If it
# is, throw a `DependencyError`.
test_for_error: (value) ->
if _.isArray value.error
throw new DependencyError @, value.error
# Convert the arguments for each parallel `@get` request into a hash containing
# `opts`, `prefix`, and `index`, where `index` is the index of the corresponding
# `get`. The hash is keyed by redeye key.
record_all_opts: ->
@key_prefixes = {}
@key_opts = {}
@all_keys = []
@pending = []
for args, index in @gets
opts = _.opts args
key = args.join ':'
prefix = key.split(':')[0]
@key_opts[key] = { prefix, opts, index }
@all_keys.push key
# From the keys requested by `@all`/`@each`, determine which ones are not already
# cached locally by the worker, and store them in `@needed`; this array holds alternately
# the lock name and the key itself, suitable for passing to `redis.mget`.
# Also use `Manager.require` to record each dependency.
find_needed_keys: ->
@needed = []
for key in @all_keys
continue if @check_cache(key) != undefined
@needed.push key
@deps.push key
# Group the needed keys and get them in batches.
discover_missing_keys: ->
_(@needed).in_groups_of 20, (@needed) =>
@find_missing_keys()
@get_missing_keys()
# From the keys in `@needed`, ask the database which are available by finding both the
# lock state and the value of the key. For any unavailable key, put that key in the `@missing`
# list. For keys which are already available, append the key and value to the `@pending` list.
find_missing_keys: ->
@missing = []
return unless @needed.length
@require @needed, (err, values) =>
return @resume err if err
for key, index in @needed
if (value = values[index]) != undefined
@pending.push [key, value]
else
@missing.push key
@resume()
@yield()
# For each missing key, if the key is unlocked, ask the queue to enqueue that
# key as a job. Finally, for all missing keys, yield and ask the queue to resume the
# worker when they are available. Take the provided values from resume and put
# them on the `@pending` list.
get_missing_keys: ->
return unless @missing.length
@wait @missing
for value, index in @yield()
@pending.push [@missing[index], value]
# Keys from redis or from resuming from the queue are present in the `@pending`
# list. For each, test the value for errors and build the key using its prefix
# and options. If one or more values are errors, add those errors to a new
# `MultiError` object and throw it. Make sure the context from each error key
# is recorded on its error object. If there are no errors, return the list of values.
build_all: ->
multi = null
for item in @pending
[key, value] = item
{ opts, prefix, index } = @key_opts[key]
try
@got prefix, key, @build(value, prefix, opts), opts
catch err
err.context = @context_list[index]
multi ||= new MultiError @
multi.add err
throw multi if multi
@cache[key] for key in @all_keys
# If any arguments look like integers, make them integers
convert_args: ->
_.standardize_args @args
# Pack a hash or array of hashes into an array using a list of fields in order.
pack_fields: (obj, fields) ->
if _.isArray obj
@pack_fields(elem, fields) for elem in obj
else
obj[field] for field in fields
# Unpack a list of values into a hash or array of hashes given a list of fields.
unpack_fields: (array, fields) ->
if _.isArray array[0]
@unpack_fields(elem, fields) for elem in array
else
hash = {}
for field, index in fields
hash[field] = array[index]
hash
module.exports = Worker
| 113134 | require 'fibers'
msgpack = require 'msgpack'
_ = require './util'
{ DependencyError, MultiError } = require './errors'
# One worker is constructed for every task coming
# through the work queue(s). It maintains a local cache
# of dependency values, a workspace for running the
# key code, and contains the core API for redeye.
# It runs worker code in a fiber, yielding the fiber
# every time asynchronous work (such as waiting for
# dependencies) must be done.
class Worker
# Break key into prefix and arguments, and set up worker cache.
constructor: (@id, @key, @queue, @old_deps, @manager) ->
[@prefix, @args...] = @key.split ':'
@convert_args()
@workspace = new Worker.Workspace
params = @manager.params[@prefix] || []
@workspace[param] = @args[i] for param, i in params
{ @pool } = @manager
@cache = {}
@deps = []
# API METHODS
# ===========
# `@async (callback) -> ... callback(err, value)`
#
# Uses paired `@yield` and `@resume` to perform an asynchronous
# function outside the worker fiber. The function should call the
# callback with arguments `error` and `value`, where `value`
# will be the result of the `@async` call. The `error`, if any, will
# be thrown from inside the fiber, to produce sensible stack traces.
async: (body) ->
body (err, value) =>
@resume err, value
@yield()
# `@sleep(seconds)`
#
# Pause the fiber for the specified number of seconds.
sleep: (n) ->
@async (callback) -> setTimeout callback, n*1000
# `@log(label, payload)`
#
# Use the `Manager#log` function to log a message for this key.
# The resulting message will include `@key` in the payload.
log: (label, payload) ->
@manager.log @key, label, payload
# `@get(prefix, args..., opts, callback)`
#
# Retrieve another key given the named prefix and its arguments.
# Three things can happen with this request under normal operation:
#
# * The key is already in our local `@cache`; its already-built
# value is just returned.
# * The key is available in the database. It is retrieved and built
# into an object if applicable. The dependency is marked in
# the database, and the built value is returned.
# * The key is not available in the database. The dependency is
# recorded and a new job will be enqueued (unless that job is
# already being run somewhere). Once the manager is notitied
# of completion of the key with the `ready` control message,
# `@get` will resume.
#
# The following options can be provided:
#
# * `as`: if provided, should be a class. The raw value of the key
# will be passed to its constructor. A common pattern for this is:
#
# class Wrapper extends Workspace
# constructor: (raw) ->
# super()
# _.extend @, raw
#
# By extending `Workspace`, the wrapper class has access to the
# worker's API methods.
#
# `@get` can return two kinds of errors:
#
# * `DependencyError`: the requested key had an error which is being
# bubbled up to this worker
# * `CycleError`: making the given request would result in a cycle
#
# Both kinds of errors can be caught and handled normally. Dependency
# errors are stored as the result of this key, and include a full backtrace
# through all workers' stacks.
get: (args...) ->
return @defer_get(args) if @in_each
{ prefix, opts, key } = @parse_args args
cached = @check_cache(key)
return cached if cached != undefined
@deps.push key
@require [key], (err, values) =>
if err
@resume err
else if values[0] != undefined
@resume null, values
else
@wait [key]
@got prefix, key, @build(@yield()[0], prefix, opts), opts
# `@keys(key_pattern)`
#
# Search for the given keys in the database and return them.
keys: (pattern) ->
@async (callback) =>
@db.keys pattern, callback
# `@atomic(key, value)
#
# Atomically set the given key to a value.
atomic: (key, value) ->
@async (callback) =>
@db.multi()
.setnx(key, value)
.get(key)
.exec (err, arr) =>
value = arr[1] unless err
callback err, value
# `@yield()`
#
# Suspend the worker fiber until `@resume` is called. If `@resume`
# is called with an error, throw that error on resume; otherwise,
# `@yield` will return the value passed to `@resume`. The error is
# thrown from inside the fiber in order to create sensible stack traces.
yield: ->
Worker.current = null
[ err, value ] = Fiber.yield()
throw err if err
value
# `@resume(error, value)`
#
# Resume a suspended worker fiber. If `error` is provided, it will
# be thrown from the fiber. Otherwise, `value` will be returned from
# the last call to `@yield`. If the fiber throws an error, record
# that error as the result of the worker for this key.
resume: (err, value) ->
return @implode() if @dirty
@try_acquire_db (err2) =>
if @waiting_for && !err
@stop_waiting()
return
Worker.current = this
try
@fiber.run [err || err2, value]
catch e
@error e
# `@run()`
#
# Start running the worker for the first time. Sets up the
# worker fiber, clears the worker, and starts running the
# worker body. Uses `@resume` so that errors are properly
# caught. Take the result of the worker body as the value
# of this key and passing it to `@finish`. If there is no
# worker body defined for this prefix, throw an error.
run: ->
@fiber = Fiber =>
if runner = @manager.runners[@prefix]
@finish runner.apply(@workspace, @args)
else
throw new Error "No runner for prefix '#{@prefix}'"
@resume()
# `@with key1: [vals...], key2: [vals...], -> ...`
#
# Iterate the keys over the cross-product of the provided values.
# For each iteration, call the given function. This function is used
# by `@all` and `@each`, but can also be used directly. The function
# will be called in the context of the workspace.
#
# In each iteration, the keys are recorded into the workspace object.
# That means if you can do something like the following:
#
# @with foo: ['bar', 'baz'], ->
# console.log @foo
#
# which would print 'bar', then 'baz'.
#
# Because `Workspace` provides a simplified API for accessing other
# worker keys and inputs, `@with` can be used to provide argument
# context like so:
#
# # @worker 'foo', 'id', -> ...
# @with id: [1,2], @foo
#
# which would first `@get('foo', 1)` and then `@get('foo', 2)`.
#
# NOTE: Please do not nest calls to `@with`, `@each`, or `@all`!
with: (hash, fun, keys) ->
@in_each = true
unless keys
unless fun
fun = hash
hash = {}
keys = _.keys(hash)
@context = {}
@context_list = []
@gets = []
if key = keys.shift()
for val in (hash[key] ? [])
@context[key] = val
@workspace[key] = val
@with hash, fun, keys
delete @context[key]
keys.unshift key
else
fun.apply @workspace
@in_each = false
# `@each key1: [vals...], key2: [vals...], -> ...`
#
# Uses the same syntax as `@with`. Each `@get` call from within
# the body is recorded. Before `@each` returns, it ensures all
# these dependencies are met, but does not bother to actually
# return them. Instead it will return the total number of `@get`
# dependencies. If one or more of the dependencies has an error,
# then this call will throw a `MultiError` with the error keys.
# Each error within the `MultiError` records the `context` under
# which it was requested with `@get`.
#
# All dependencies will be satisfied in parallel.
#
# TODO: This could be more efficient. Hard to check for errors though.
each: (hash, fun) ->
@all(hash, fun).length
# `@all key1: [vals...], key2: [vals...], -> ...`
#
# Uses the same syntax as `@with`. Each `@get` call from within
# the body is recorded. Before `@all` returns, it ensures all
# these dependencies are met, and then returns them all in an
# array. If one or more of the dependencies has an error,
# then this call will throw a `MultiError` with the error keys.
# Each error within the `MultiError` records the `context` under
# which it was requested with `@get`.
#
# All dependencies will be satisfied in parallel.
all: (hash, fun) ->
@with hash, fun
@record_all_opts()
@find_needed_keys()
@discover_missing_keys()
@build_all()
# `@worker()`
#
# Return the current worker object.
worker: ->
Worker.current
# INTERNAL METHODS
# ================
# Get a database client from the pool, set `@db`, and call back.
acquire_db: (callback) ->
if @db
err = new Error "Tried to acquire db when we already had one"
return callback err
@pool.acquire (err, @db) =>
callback err
# Release our database client back to the pool.
release_db: (callback) ->
unless @db
err = new Error "Tried to release db when we didn't have one"
return callback err
@pool.release @db
@db = null
callback?()
# Acquire a database connection, but don't panic if we already have one.
try_acquire_db: (callback) ->
if @db
callback()
else
@acquire_db callback
# Release our database connection and null out the fiber so that this
# worker object can be garbage collected.
implode: ->
@dirty = true # so callbacks will also implode
@release_db() if @db
@fiber = null
# The worker is done and this is its value. Convert using `toJSON` if present,
# set the key's value, then tell the queue that the key should be released.
finish: (value) ->
Worker.current = null
return @implode() if @dirty
value = value?.toJSON?() ? value
# if pack = @manager.opts[@prefix]?.pack
# value = @pack_fields value, pack if value && !value.error
value = JSON.stringify(value ? null)
@manager.finish @id, @key, value, (ok) =>
if ok
@fix_source_targets => @implode()
else
@implode()
# We may have dropped some dependencies; in that case, remove us as a
# target from the dropped ones.
fix_source_targets: (callback) ->
bad_deps = []
for dep in @old_deps
unless dep in @deps
bad_deps.push dep
return callback() unless bad_deps.length
m = @db.multi()
for dep in bad_deps
m.srem 'targets:'+dep, @key
@manager.unrequire dep, @key
m.exec callback
# Convert the given error message or object into a value
# suitable for exception bubbling, then set that error as the
# result of this key with `@finish`.
error: (err) ->
trace = err.stack ? err
slice = @manager.slice
error = err.get_tail?() ? [{ trace, @key, slice }]
@finish { error }
# Parse the @get arguments into the prefix, key arguments,
# and options.
parse_args: (args) ->
_.callback args
opts = _.opts args
key = args.join ':'
namespace = opts.namespace
namespace = @manager.opts[@prefix].namespace if namespace == undefined
key = <KEY>key<KEY>}" if namespace
prefix = key.split(':')[0]
{ prefix, opts, key }
# Look in both our local cache and in the LRU cache for the given
# key. If found locally, just return it. If found in the LRU cache,
# return it but also link as dependency. If not found, returns undefined.
check_cache: (key) ->
if (cached = @cache[key]) != undefined
cached
else if (value = @manager.check_helpers(key)) != undefined
if typeof(value) == 'function'
yielded = false
the_result = undefined
value (err, result) =>
if yielded
@fiber.run([err, result])
else
the_result = [err, result]
if the_result != undefined
Worker.current = this
[e, v] = the_result
throw e if e
return v
yielded = true
[e, v] = Fiber.yield()
Worker.current = this
throw e if e
v
else
[e, v] = value
throw e if e
v
else if (cached = @manager.check_cache(key)) != undefined
msg = source: key, target: @key
msg.slice = @manager.slice if @manager.slice
msg = JSON.stringify(msg ? null)
@db.multi()
.sadd('sources:'+@key, key)
.sadd('targets:'+key, @key)
.publish('redeye:require', msg)
.exec (err) -> throw err if err
@cache[key] = cached
else
undefined
# We built a fresh value from the database. Add it to our cache as
# well as the manager's LRU cache.
got: (prefix, key, value, opts) ->
@cache[key] = @manager.add_to_cache(prefix, key, value, opts.sticky)
# Inform the manager of this dependency.
require: (sources, callback) ->
@manager.require @queue, sources, @key, callback
# Tell the manager to resume us when all the given dependencies are ready.
# Once resumed, look up the value of all the dependencies, and resume with them.
wait: (deps) ->
@waiting_for = (new Buffer dep for dep in deps)
@release_db (err) =>
return @resume err if err
@manager.wait deps, @key
# We have resumed after the last `@wait`, so look up the keys we're waiting on
# and resume the fiber with them.
stop_waiting: ->
@db.mget @waiting_for, (err, arr) =>
# console.log "Worker#stop_waiting", { arr }
return @resume err if err
arr = for buf, index in arr
# console.log { buf, unpacked: msgpack.unpack(buf) }
if buf
JSON.parse buf
else
(err ||= []).push @waiting_for[index]
undefined
@waiting_for = null
if err
@resume "PLEASE CONTACT WATERFIELD ENERGY DEV TEAM ABOUT THIS ERROR\n#{@key} expected finished keys but got nulls: #{err.join ','}"
else
@resume null, arr
# Because we're in an `@each` or `@all` block, don't attempt
# to get the key yet; instead, just record the context and
# arguments at the time `@get` was called, to be retrieved in
# a batch later.
defer_get: (args) ->
@context_list.push _.clone(@context)
@gets.push args
# Check if the returned value is an error. If so, prepend the
# current context to the error trace and re-throw it.
#
# Otherwise, if there is an `as` option specified for the value's
# prefix, construct an object with the wrapper class.
build: (value, prefix, opts) ->
return value unless value?
@test_for_error value
# if pack = @manager.opts[prefix]?.pack
# value = @unpack_fields value, pack if value
if wrapper = opts.as || @manager.opts[prefix]?.as
new wrapper(value)
else
value
# Test if the given value looks like a redeye recorded error;
# that is, it is an object with an array 'error' field. If it
# is, throw a `DependencyError`.
test_for_error: (value) ->
if _.isArray value.error
throw new DependencyError @, value.error
# Convert the arguments for each parallel `@get` request into a hash containing
# `opts`, `prefix`, and `index`, where `index` is the index of the corresponding
# `get`. The hash is keyed by redeye key.
record_all_opts: ->
@key_prefixes = {}
@key_opts = {}
@all_keys = []
@pending = []
for args, index in @gets
opts = _.opts args
key = args.join ':'
prefix = key.split(':')[0]
@key_opts[key] = { prefix, opts, index }
@all_keys.push key
# From the keys requested by `@all`/`@each`, determine which ones are not already
# cached locally by the worker, and store them in `@needed`; this array holds alternately
# the lock name and the key itself, suitable for passing to `redis.mget`.
# Also use `Manager.require` to record each dependency.
find_needed_keys: ->
@needed = []
for key in @all_keys
continue if @check_cache(key) != undefined
@needed.push key
@deps.push key
# Group the needed keys and get them in batches.
discover_missing_keys: ->
_(@needed).in_groups_of 20, (@needed) =>
@find_missing_keys()
@get_missing_keys()
# From the keys in `@needed`, ask the database which are available by finding both the
# lock state and the value of the key. For any unavailable key, put that key in the `@missing`
# list. For keys which are already available, append the key and value to the `@pending` list.
find_missing_keys: ->
@missing = []
return unless @needed.length
@require @needed, (err, values) =>
return @resume err if err
for key, index in @needed
if (value = values[index]) != undefined
@pending.push [key, value]
else
@missing.push key
@resume()
@yield()
# For each missing key, if the key is unlocked, ask the queue to enqueue that
# key as a job. Finally, for all missing keys, yield and ask the queue to resume the
# worker when they are available. Take the provided values from resume and put
# them on the `@pending` list.
get_missing_keys: ->
return unless @missing.length
@wait @missing
for value, index in @yield()
@pending.push [@missing[index], value]
# Keys from redis or from resuming from the queue are present in the `@pending`
# list. For each, test the value for errors and build the key using its prefix
# and options. If one or more values are errors, add those errors to a new
# `MultiError` object and throw it. Make sure the context from each error key
# is recorded on its error object. If there are no errors, return the list of values.
build_all: ->
multi = null
for item in @pending
[key, value] = item
{ opts, prefix, index } = @key_opts[key]
try
@got prefix, key, @build(value, prefix, opts), opts
catch err
err.context = @context_list[index]
multi ||= new MultiError @
multi.add err
throw multi if multi
@cache[key] for key in @all_keys
# If any arguments look like integers, make them integers
convert_args: ->
_.standardize_args @args
# Pack a hash or array of hashes into an array using a list of fields in order.
pack_fields: (obj, fields) ->
if _.isArray obj
@pack_fields(elem, fields) for elem in obj
else
obj[field] for field in fields
# Unpack a list of values into a hash or array of hashes given a list of fields.
unpack_fields: (array, fields) ->
if _.isArray array[0]
@unpack_fields(elem, fields) for elem in array
else
hash = {}
for field, index in fields
hash[field] = array[index]
hash
module.exports = Worker
| true | require 'fibers'
msgpack = require 'msgpack'
_ = require './util'
{ DependencyError, MultiError } = require './errors'
# One worker is constructed for every task coming
# through the work queue(s). It maintains a local cache
# of dependency values, a workspace for running the
# key code, and contains the core API for redeye.
# It runs worker code in a fiber, yielding the fiber
# every time asynchronous work (such as waiting for
# dependencies) must be done.
class Worker
# Break key into prefix and arguments, and set up worker cache.
constructor: (@id, @key, @queue, @old_deps, @manager) ->
[@prefix, @args...] = @key.split ':'
@convert_args()
@workspace = new Worker.Workspace
params = @manager.params[@prefix] || []
@workspace[param] = @args[i] for param, i in params
{ @pool } = @manager
@cache = {}
@deps = []
# API METHODS
# ===========
# `@async (callback) -> ... callback(err, value)`
#
# Uses paired `@yield` and `@resume` to perform an asynchronous
# function outside the worker fiber. The function should call the
# callback with arguments `error` and `value`, where `value`
# will be the result of the `@async` call. The `error`, if any, will
# be thrown from inside the fiber, to produce sensible stack traces.
async: (body) ->
body (err, value) =>
@resume err, value
@yield()
# `@sleep(seconds)`
#
# Pause the fiber for the specified number of seconds.
sleep: (n) ->
@async (callback) -> setTimeout callback, n*1000
# `@log(label, payload)`
#
# Use the `Manager#log` function to log a message for this key.
# The resulting message will include `@key` in the payload.
log: (label, payload) ->
@manager.log @key, label, payload
# `@get(prefix, args..., opts, callback)`
#
# Retrieve another key given the named prefix and its arguments.
# Three things can happen with this request under normal operation:
#
# * The key is already in our local `@cache`; its already-built
# value is just returned.
# * The key is available in the database. It is retrieved and built
# into an object if applicable. The dependency is marked in
# the database, and the built value is returned.
# * The key is not available in the database. The dependency is
# recorded and a new job will be enqueued (unless that job is
# already being run somewhere). Once the manager is notitied
# of completion of the key with the `ready` control message,
# `@get` will resume.
#
# The following options can be provided:
#
# * `as`: if provided, should be a class. The raw value of the key
# will be passed to its constructor. A common pattern for this is:
#
# class Wrapper extends Workspace
# constructor: (raw) ->
# super()
# _.extend @, raw
#
# By extending `Workspace`, the wrapper class has access to the
# worker's API methods.
#
# `@get` can return two kinds of errors:
#
# * `DependencyError`: the requested key had an error which is being
# bubbled up to this worker
# * `CycleError`: making the given request would result in a cycle
#
# Both kinds of errors can be caught and handled normally. Dependency
# errors are stored as the result of this key, and include a full backtrace
# through all workers' stacks.
get: (args...) ->
return @defer_get(args) if @in_each
{ prefix, opts, key } = @parse_args args
cached = @check_cache(key)
return cached if cached != undefined
@deps.push key
@require [key], (err, values) =>
if err
@resume err
else if values[0] != undefined
@resume null, values
else
@wait [key]
@got prefix, key, @build(@yield()[0], prefix, opts), opts
# `@keys(key_pattern)`
#
# Search for the given keys in the database and return them.
keys: (pattern) ->
@async (callback) =>
@db.keys pattern, callback
# `@atomic(key, value)
#
# Atomically set the given key to a value.
atomic: (key, value) ->
@async (callback) =>
@db.multi()
.setnx(key, value)
.get(key)
.exec (err, arr) =>
value = arr[1] unless err
callback err, value
# `@yield()`
#
# Suspend the worker fiber until `@resume` is called. If `@resume`
# is called with an error, throw that error on resume; otherwise,
# `@yield` will return the value passed to `@resume`. The error is
# thrown from inside the fiber in order to create sensible stack traces.
yield: ->
Worker.current = null
[ err, value ] = Fiber.yield()
throw err if err
value
# `@resume(error, value)`
#
# Resume a suspended worker fiber. If `error` is provided, it will
# be thrown from the fiber. Otherwise, `value` will be returned from
# the last call to `@yield`. If the fiber throws an error, record
# that error as the result of the worker for this key.
resume: (err, value) ->
return @implode() if @dirty
@try_acquire_db (err2) =>
if @waiting_for && !err
@stop_waiting()
return
Worker.current = this
try
@fiber.run [err || err2, value]
catch e
@error e
# `@run()`
#
# Start running the worker for the first time. Sets up the
# worker fiber, clears the worker, and starts running the
# worker body. Uses `@resume` so that errors are properly
# caught. Take the result of the worker body as the value
# of this key and passing it to `@finish`. If there is no
# worker body defined for this prefix, throw an error.
run: ->
@fiber = Fiber =>
if runner = @manager.runners[@prefix]
@finish runner.apply(@workspace, @args)
else
throw new Error "No runner for prefix '#{@prefix}'"
@resume()
# `@with key1: [vals...], key2: [vals...], -> ...`
#
# Iterate the keys over the cross-product of the provided values.
# For each iteration, call the given function. This function is used
# by `@all` and `@each`, but can also be used directly. The function
# will be called in the context of the workspace.
#
# In each iteration, the keys are recorded into the workspace object.
# That means if you can do something like the following:
#
# @with foo: ['bar', 'baz'], ->
# console.log @foo
#
# which would print 'bar', then 'baz'.
#
# Because `Workspace` provides a simplified API for accessing other
# worker keys and inputs, `@with` can be used to provide argument
# context like so:
#
# # @worker 'foo', 'id', -> ...
# @with id: [1,2], @foo
#
# which would first `@get('foo', 1)` and then `@get('foo', 2)`.
#
# NOTE: Please do not nest calls to `@with`, `@each`, or `@all`!
with: (hash, fun, keys) ->
@in_each = true
unless keys
unless fun
fun = hash
hash = {}
keys = _.keys(hash)
@context = {}
@context_list = []
@gets = []
if key = keys.shift()
for val in (hash[key] ? [])
@context[key] = val
@workspace[key] = val
@with hash, fun, keys
delete @context[key]
keys.unshift key
else
fun.apply @workspace
@in_each = false
# `@each key1: [vals...], key2: [vals...], -> ...`
#
# Uses the same syntax as `@with`. Each `@get` call from within
# the body is recorded. Before `@each` returns, it ensures all
# these dependencies are met, but does not bother to actually
# return them. Instead it will return the total number of `@get`
# dependencies. If one or more of the dependencies has an error,
# then this call will throw a `MultiError` with the error keys.
# Each error within the `MultiError` records the `context` under
# which it was requested with `@get`.
#
# All dependencies will be satisfied in parallel.
#
# TODO: This could be more efficient. Hard to check for errors though.
each: (hash, fun) ->
@all(hash, fun).length
# `@all key1: [vals...], key2: [vals...], -> ...`
#
# Uses the same syntax as `@with`. Each `@get` call from within
# the body is recorded. Before `@all` returns, it ensures all
# these dependencies are met, and then returns them all in an
# array. If one or more of the dependencies has an error,
# then this call will throw a `MultiError` with the error keys.
# Each error within the `MultiError` records the `context` under
# which it was requested with `@get`.
#
# All dependencies will be satisfied in parallel.
all: (hash, fun) ->
@with hash, fun
@record_all_opts()
@find_needed_keys()
@discover_missing_keys()
@build_all()
# `@worker()`
#
# Return the current worker object.
worker: ->
Worker.current
# INTERNAL METHODS
# ================
# Get a database client from the pool, set `@db`, and call back.
acquire_db: (callback) ->
if @db
err = new Error "Tried to acquire db when we already had one"
return callback err
@pool.acquire (err, @db) =>
callback err
# Release our database client back to the pool.
release_db: (callback) ->
unless @db
err = new Error "Tried to release db when we didn't have one"
return callback err
@pool.release @db
@db = null
callback?()
# Acquire a database connection, but don't panic if we already have one.
try_acquire_db: (callback) ->
if @db
callback()
else
@acquire_db callback
# Release our database connection and null out the fiber so that this
# worker object can be garbage collected.
implode: ->
@dirty = true # so callbacks will also implode
@release_db() if @db
@fiber = null
# The worker is done and this is its value. Convert using `toJSON` if present,
# set the key's value, then tell the queue that the key should be released.
finish: (value) ->
Worker.current = null
return @implode() if @dirty
value = value?.toJSON?() ? value
# if pack = @manager.opts[@prefix]?.pack
# value = @pack_fields value, pack if value && !value.error
value = JSON.stringify(value ? null)
@manager.finish @id, @key, value, (ok) =>
if ok
@fix_source_targets => @implode()
else
@implode()
# We may have dropped some dependencies; in that case, remove us as a
# target from the dropped ones.
fix_source_targets: (callback) ->
bad_deps = []
for dep in @old_deps
unless dep in @deps
bad_deps.push dep
return callback() unless bad_deps.length
m = @db.multi()
for dep in bad_deps
m.srem 'targets:'+dep, @key
@manager.unrequire dep, @key
m.exec callback
# Convert the given error message or object into a value
# suitable for exception bubbling, then set that error as the
# result of this key with `@finish`.
error: (err) ->
trace = err.stack ? err
slice = @manager.slice
error = err.get_tail?() ? [{ trace, @key, slice }]
@finish { error }
# Parse the @get arguments into the prefix, key arguments,
# and options.
parse_args: (args) ->
_.callback args
opts = _.opts args
key = args.join ':'
namespace = opts.namespace
namespace = @manager.opts[@prefix].namespace if namespace == undefined
key = PI:KEY:<KEY>END_PIkeyPI:KEY:<KEY>END_PI}" if namespace
prefix = key.split(':')[0]
{ prefix, opts, key }
# Look in both our local cache and in the LRU cache for the given
# key. If found locally, just return it. If found in the LRU cache,
# return it but also link as dependency. If not found, returns undefined.
check_cache: (key) ->
if (cached = @cache[key]) != undefined
cached
else if (value = @manager.check_helpers(key)) != undefined
if typeof(value) == 'function'
yielded = false
the_result = undefined
value (err, result) =>
if yielded
@fiber.run([err, result])
else
the_result = [err, result]
if the_result != undefined
Worker.current = this
[e, v] = the_result
throw e if e
return v
yielded = true
[e, v] = Fiber.yield()
Worker.current = this
throw e if e
v
else
[e, v] = value
throw e if e
v
else if (cached = @manager.check_cache(key)) != undefined
msg = source: key, target: @key
msg.slice = @manager.slice if @manager.slice
msg = JSON.stringify(msg ? null)
@db.multi()
.sadd('sources:'+@key, key)
.sadd('targets:'+key, @key)
.publish('redeye:require', msg)
.exec (err) -> throw err if err
@cache[key] = cached
else
undefined
# We built a fresh value from the database. Add it to our cache as
# well as the manager's LRU cache.
got: (prefix, key, value, opts) ->
@cache[key] = @manager.add_to_cache(prefix, key, value, opts.sticky)
# Inform the manager of this dependency.
require: (sources, callback) ->
@manager.require @queue, sources, @key, callback
# Tell the manager to resume us when all the given dependencies are ready.
# Once resumed, look up the value of all the dependencies, and resume with them.
wait: (deps) ->
@waiting_for = (new Buffer dep for dep in deps)
@release_db (err) =>
return @resume err if err
@manager.wait deps, @key
# We have resumed after the last `@wait`, so look up the keys we're waiting on
# and resume the fiber with them.
stop_waiting: ->
@db.mget @waiting_for, (err, arr) =>
# console.log "Worker#stop_waiting", { arr }
return @resume err if err
arr = for buf, index in arr
# console.log { buf, unpacked: msgpack.unpack(buf) }
if buf
JSON.parse buf
else
(err ||= []).push @waiting_for[index]
undefined
@waiting_for = null
if err
@resume "PLEASE CONTACT WATERFIELD ENERGY DEV TEAM ABOUT THIS ERROR\n#{@key} expected finished keys but got nulls: #{err.join ','}"
else
@resume null, arr
# Because we're in an `@each` or `@all` block, don't attempt
# to get the key yet; instead, just record the context and
# arguments at the time `@get` was called, to be retrieved in
# a batch later.
defer_get: (args) ->
@context_list.push _.clone(@context)
@gets.push args
# Check if the returned value is an error. If so, prepend the
# current context to the error trace and re-throw it.
#
# Otherwise, if there is an `as` option specified for the value's
# prefix, construct an object with the wrapper class.
build: (value, prefix, opts) ->
return value unless value?
@test_for_error value
# if pack = @manager.opts[prefix]?.pack
# value = @unpack_fields value, pack if value
if wrapper = opts.as || @manager.opts[prefix]?.as
new wrapper(value)
else
value
# Test if the given value looks like a redeye recorded error;
# that is, it is an object with an array 'error' field. If it
# is, throw a `DependencyError`.
test_for_error: (value) ->
if _.isArray value.error
throw new DependencyError @, value.error
# Convert the arguments for each parallel `@get` request into a hash containing
# `opts`, `prefix`, and `index`, where `index` is the index of the corresponding
# `get`. The hash is keyed by redeye key.
record_all_opts: ->
@key_prefixes = {}
@key_opts = {}
@all_keys = []
@pending = []
for args, index in @gets
opts = _.opts args
key = args.join ':'
prefix = key.split(':')[0]
@key_opts[key] = { prefix, opts, index }
@all_keys.push key
# From the keys requested by `@all`/`@each`, determine which ones are not already
# cached locally by the worker, and store them in `@needed`; this array holds alternately
# the lock name and the key itself, suitable for passing to `redis.mget`.
# Also use `Manager.require` to record each dependency.
find_needed_keys: ->
@needed = []
for key in @all_keys
continue if @check_cache(key) != undefined
@needed.push key
@deps.push key
# Group the needed keys and get them in batches.
discover_missing_keys: ->
_(@needed).in_groups_of 20, (@needed) =>
@find_missing_keys()
@get_missing_keys()
# From the keys in `@needed`, ask the database which are available by finding both the
# lock state and the value of the key. For any unavailable key, put that key in the `@missing`
# list. For keys which are already available, append the key and value to the `@pending` list.
find_missing_keys: ->
@missing = []
return unless @needed.length
@require @needed, (err, values) =>
return @resume err if err
for key, index in @needed
if (value = values[index]) != undefined
@pending.push [key, value]
else
@missing.push key
@resume()
@yield()
# For each missing key, if the key is unlocked, ask the queue to enqueue that
# key as a job. Finally, for all missing keys, yield and ask the queue to resume the
# worker when they are available. Take the provided values from resume and put
# them on the `@pending` list.
get_missing_keys: ->
return unless @missing.length
@wait @missing
for value, index in @yield()
@pending.push [@missing[index], value]
# Keys from redis or from resuming from the queue are present in the `@pending`
# list. For each, test the value for errors and build the key using its prefix
# and options. If one or more values are errors, add those errors to a new
# `MultiError` object and throw it. Make sure the context from each error key
# is recorded on its error object. If there are no errors, return the list of values.
build_all: ->
multi = null
for item in @pending
[key, value] = item
{ opts, prefix, index } = @key_opts[key]
try
@got prefix, key, @build(value, prefix, opts), opts
catch err
err.context = @context_list[index]
multi ||= new MultiError @
multi.add err
throw multi if multi
@cache[key] for key in @all_keys
# If any arguments look like integers, make them integers
convert_args: ->
_.standardize_args @args
# Pack a hash or array of hashes into an array using a list of fields in order.
pack_fields: (obj, fields) ->
if _.isArray obj
@pack_fields(elem, fields) for elem in obj
else
obj[field] for field in fields
# Unpack a list of values into a hash or array of hashes given a list of fields.
unpack_fields: (array, fields) ->
if _.isArray array[0]
@unpack_fields(elem, fields) for elem in array
else
hash = {}
for field, index in fields
hash[field] = array[index]
hash
module.exports = Worker
|
[
{
"context": "angular: [\n { key: \"options.on\" }\n]\n",
"end": 31,
"score": 0.9868588447570801,
"start": 21,
"tag": "KEY",
"value": "options.on"
}
] | configs/default/form.cson | octoblu/meshblu-connector-display | 0 | angular: [
{ key: "options.on" }
]
| 196601 | angular: [
{ key: "<KEY>" }
]
| true | angular: [
{ key: "PI:KEY:<KEY>END_PI" }
]
|
[
{
"context": "formdata {method:'find-by-vehicle-type',keyword:'yueye'}\n index = req.params.index\n # we no need to ch",
"end": 1059,
"score": 0.4900968670845032,
"start": 1055,
"tag": "KEY",
"value": "ueye"
}
] | coffees/route-neighborCar.coffee | android1and1/easti | 0 | # 2018-12-19 game is "5min=1app".
express = require 'express'
router = express.Router()
nohm = undefined
schema = undefined
client = (require 'redis').createClient()
client.on 'error',(error)->
console.log '::debug info - route neighborCar::',error.message
client.on 'connect',->
md = require '../modules/md-neighborCar'
nohm = (require 'nohm').Nohm
nohm.setPrefix 'gaikai'
nohm.setClient @
schema = nohm.register md
# till here,has 'global' variable - ''
router.get '/',(req,res,next)->
res.redirect 302,'/neighborCar/list'
router.get '/list',(req,res,next)->
# top10 sorted by id number.
allids = await schema.sort {field:'whatistime',direction:'DESC',limit:[0,10]}
allitems = []
for i in allids
ins = await nohm.factory 'neighborCar',i
allitems.push ins.allProperties()
res.render 'neighborCar/list.pug' ,{title:'Top 10 List',top10:allitems}
router.post '/find-by/:index',(req,res,next)->
# final,i need the architech like this:
# from client,give server formdata {method:'find-by-vehicle-type',keyword:'yueye'}
index = req.params.index
# we no need to check if index is undefined or null,because only our scripts can touch it.
keyword = req.body.keyword
opts = {}
opts[index] = keyword
info = []
try
items = await schema.findAndLoad opts
for item in items
info.push item.allProperties()
catch error
return res.json {'error':'No This Index.'}
res.render 'neighborCar/results-list.pug',{list:info }
router.get '/update/:id',(req,res,next)->
res.send 'TODO,parse posted then response status.'
###
id = req.params.id
res.json form: '<form method="POST" action="" class="form-horizontal"><div class="form-group"><label for="seesee"> See That:</label><input class="text" name="seesee" id="seesee" /></div><button type="submit" class="btn btn-success"> Submit!</button></form>'
###
router.put '/vote/:id',(req,res,next)->
id = req.params.id
try
item = await nohm.factory 'neighborCar',id
num = item.property 'visits'
num = parseInt num
item.property 'visits',num + 1
old = item.property 'memo'
memo = '<address><strong>'
memo += new Date
memo += '</strong><br>'
memo += 'has vote once.'
memo += '<br></address>'
item.property 'memo',old + memo
await item.save()
res.json {status:'visits number added once.'}
catch error
res.json {error:'occurs error during add visits number,reason:' + error.message}
router.post '/find-by-brand',(req,res,next)->
brand = req.body.keyword
list = []
try
items = await schema.findAndLoad {'brand':brand}
for item in items
item.property 'visits',''
await item.save()
list.push item.allProperties()
catch error
return res.json {'error':'No This Brand.'}
res.render 'neighborCar/results-list',{list:list}
router.get '/register-car',(req,res,next)->
res.render 'neighborCar/register-car.pug',{title:'Register Car(Neighbors)'}
router.get '/update/:id',(req,res,next)->
id = req.param.id
try
item = await nohm.factory 'neighborCar',id
properties = item.allProperties()
res.render 'neighborCar/base-item-form.pug',{title:'Update Car',properties:properties}
router.get '/purge-db',(req,res,next)->
res.render 'neighborCar/purge-db.pug'
router.delete '/delete/:id',(req,res,next)->
id = req.params.id
try
item = await nohm.factory 'neighborCar',id
item.remove()
res.json status:'item -#' + item.id + ' has deleted.'
catch error
res.json {status:'error about deleting.the item - ' + item.id + ' has NOT deleted.'}
router.delete '/purge-db',(req,res,next)->
# quanteetee user from '/neighborCar/purge-db'(GET),click button.
if req.xhr
try
await nohm.purgeDb client
catch error
return res.send 'purge execution failed. all.'
res.send 'purge all itmes in db:wiki.'
else
res.send 'nosense!'
# add!
router.post '/register-car',(req,res,next)->
ins = await nohm.factory 'neighborCar'
body = req.body
ins.property 'visits',1
ins.property
brand:body.brand
license_plate_number: body.license_plate_number
color: body.color
vehicle_model: body.vehicle_model
whatistime: Date.parse(new Date)
where_seen:body.where_seen
memo: body.memo
try
await ins.save()
catch error
console.log ins.errors
return res.send 'save failed.'
res.send 'saved.'
neighborCarFactory = (app)->
return (pathname)->
app.use pathname,router
module.exports = neighborCarFactory
| 90420 | # 2018-12-19 game is "5min=1app".
express = require 'express'
router = express.Router()
nohm = undefined
schema = undefined
client = (require 'redis').createClient()
client.on 'error',(error)->
console.log '::debug info - route neighborCar::',error.message
client.on 'connect',->
md = require '../modules/md-neighborCar'
nohm = (require 'nohm').Nohm
nohm.setPrefix 'gaikai'
nohm.setClient @
schema = nohm.register md
# till here,has 'global' variable - ''
router.get '/',(req,res,next)->
res.redirect 302,'/neighborCar/list'
router.get '/list',(req,res,next)->
# top10 sorted by id number.
allids = await schema.sort {field:'whatistime',direction:'DESC',limit:[0,10]}
allitems = []
for i in allids
ins = await nohm.factory 'neighborCar',i
allitems.push ins.allProperties()
res.render 'neighborCar/list.pug' ,{title:'Top 10 List',top10:allitems}
router.post '/find-by/:index',(req,res,next)->
# final,i need the architech like this:
# from client,give server formdata {method:'find-by-vehicle-type',keyword:'y<KEY>'}
index = req.params.index
# we no need to check if index is undefined or null,because only our scripts can touch it.
keyword = req.body.keyword
opts = {}
opts[index] = keyword
info = []
try
items = await schema.findAndLoad opts
for item in items
info.push item.allProperties()
catch error
return res.json {'error':'No This Index.'}
res.render 'neighborCar/results-list.pug',{list:info }
router.get '/update/:id',(req,res,next)->
res.send 'TODO,parse posted then response status.'
###
id = req.params.id
res.json form: '<form method="POST" action="" class="form-horizontal"><div class="form-group"><label for="seesee"> See That:</label><input class="text" name="seesee" id="seesee" /></div><button type="submit" class="btn btn-success"> Submit!</button></form>'
###
router.put '/vote/:id',(req,res,next)->
id = req.params.id
try
item = await nohm.factory 'neighborCar',id
num = item.property 'visits'
num = parseInt num
item.property 'visits',num + 1
old = item.property 'memo'
memo = '<address><strong>'
memo += new Date
memo += '</strong><br>'
memo += 'has vote once.'
memo += '<br></address>'
item.property 'memo',old + memo
await item.save()
res.json {status:'visits number added once.'}
catch error
res.json {error:'occurs error during add visits number,reason:' + error.message}
router.post '/find-by-brand',(req,res,next)->
brand = req.body.keyword
list = []
try
items = await schema.findAndLoad {'brand':brand}
for item in items
item.property 'visits',''
await item.save()
list.push item.allProperties()
catch error
return res.json {'error':'No This Brand.'}
res.render 'neighborCar/results-list',{list:list}
router.get '/register-car',(req,res,next)->
res.render 'neighborCar/register-car.pug',{title:'Register Car(Neighbors)'}
router.get '/update/:id',(req,res,next)->
id = req.param.id
try
item = await nohm.factory 'neighborCar',id
properties = item.allProperties()
res.render 'neighborCar/base-item-form.pug',{title:'Update Car',properties:properties}
router.get '/purge-db',(req,res,next)->
res.render 'neighborCar/purge-db.pug'
router.delete '/delete/:id',(req,res,next)->
id = req.params.id
try
item = await nohm.factory 'neighborCar',id
item.remove()
res.json status:'item -#' + item.id + ' has deleted.'
catch error
res.json {status:'error about deleting.the item - ' + item.id + ' has NOT deleted.'}
router.delete '/purge-db',(req,res,next)->
# quanteetee user from '/neighborCar/purge-db'(GET),click button.
if req.xhr
try
await nohm.purgeDb client
catch error
return res.send 'purge execution failed. all.'
res.send 'purge all itmes in db:wiki.'
else
res.send 'nosense!'
# add!
router.post '/register-car',(req,res,next)->
ins = await nohm.factory 'neighborCar'
body = req.body
ins.property 'visits',1
ins.property
brand:body.brand
license_plate_number: body.license_plate_number
color: body.color
vehicle_model: body.vehicle_model
whatistime: Date.parse(new Date)
where_seen:body.where_seen
memo: body.memo
try
await ins.save()
catch error
console.log ins.errors
return res.send 'save failed.'
res.send 'saved.'
neighborCarFactory = (app)->
return (pathname)->
app.use pathname,router
module.exports = neighborCarFactory
| true | # 2018-12-19 game is "5min=1app".
express = require 'express'
router = express.Router()
nohm = undefined
schema = undefined
client = (require 'redis').createClient()
client.on 'error',(error)->
console.log '::debug info - route neighborCar::',error.message
client.on 'connect',->
md = require '../modules/md-neighborCar'
nohm = (require 'nohm').Nohm
nohm.setPrefix 'gaikai'
nohm.setClient @
schema = nohm.register md
# till here,has 'global' variable - ''
router.get '/',(req,res,next)->
res.redirect 302,'/neighborCar/list'
router.get '/list',(req,res,next)->
# top10 sorted by id number.
allids = await schema.sort {field:'whatistime',direction:'DESC',limit:[0,10]}
allitems = []
for i in allids
ins = await nohm.factory 'neighborCar',i
allitems.push ins.allProperties()
res.render 'neighborCar/list.pug' ,{title:'Top 10 List',top10:allitems}
router.post '/find-by/:index',(req,res,next)->
# final,i need the architech like this:
# from client,give server formdata {method:'find-by-vehicle-type',keyword:'yPI:KEY:<KEY>END_PI'}
index = req.params.index
# we no need to check if index is undefined or null,because only our scripts can touch it.
keyword = req.body.keyword
opts = {}
opts[index] = keyword
info = []
try
items = await schema.findAndLoad opts
for item in items
info.push item.allProperties()
catch error
return res.json {'error':'No This Index.'}
res.render 'neighborCar/results-list.pug',{list:info }
router.get '/update/:id',(req,res,next)->
res.send 'TODO,parse posted then response status.'
###
id = req.params.id
res.json form: '<form method="POST" action="" class="form-horizontal"><div class="form-group"><label for="seesee"> See That:</label><input class="text" name="seesee" id="seesee" /></div><button type="submit" class="btn btn-success"> Submit!</button></form>'
###
router.put '/vote/:id',(req,res,next)->
id = req.params.id
try
item = await nohm.factory 'neighborCar',id
num = item.property 'visits'
num = parseInt num
item.property 'visits',num + 1
old = item.property 'memo'
memo = '<address><strong>'
memo += new Date
memo += '</strong><br>'
memo += 'has vote once.'
memo += '<br></address>'
item.property 'memo',old + memo
await item.save()
res.json {status:'visits number added once.'}
catch error
res.json {error:'occurs error during add visits number,reason:' + error.message}
router.post '/find-by-brand',(req,res,next)->
brand = req.body.keyword
list = []
try
items = await schema.findAndLoad {'brand':brand}
for item in items
item.property 'visits',''
await item.save()
list.push item.allProperties()
catch error
return res.json {'error':'No This Brand.'}
res.render 'neighborCar/results-list',{list:list}
router.get '/register-car',(req,res,next)->
res.render 'neighborCar/register-car.pug',{title:'Register Car(Neighbors)'}
router.get '/update/:id',(req,res,next)->
id = req.param.id
try
item = await nohm.factory 'neighborCar',id
properties = item.allProperties()
res.render 'neighborCar/base-item-form.pug',{title:'Update Car',properties:properties}
router.get '/purge-db',(req,res,next)->
res.render 'neighborCar/purge-db.pug'
router.delete '/delete/:id',(req,res,next)->
id = req.params.id
try
item = await nohm.factory 'neighborCar',id
item.remove()
res.json status:'item -#' + item.id + ' has deleted.'
catch error
res.json {status:'error about deleting.the item - ' + item.id + ' has NOT deleted.'}
router.delete '/purge-db',(req,res,next)->
# quanteetee user from '/neighborCar/purge-db'(GET),click button.
if req.xhr
try
await nohm.purgeDb client
catch error
return res.send 'purge execution failed. all.'
res.send 'purge all itmes in db:wiki.'
else
res.send 'nosense!'
# add!
router.post '/register-car',(req,res,next)->
ins = await nohm.factory 'neighborCar'
body = req.body
ins.property 'visits',1
ins.property
brand:body.brand
license_plate_number: body.license_plate_number
color: body.color
vehicle_model: body.vehicle_model
whatistime: Date.parse(new Date)
where_seen:body.where_seen
memo: body.memo
try
await ins.save()
catch error
console.log ins.errors
return res.send 'save failed.'
res.send 'saved.'
neighborCarFactory = (app)->
return (pathname)->
app.use pathname,router
module.exports = neighborCarFactory
|
[
{
"context": "\t\t\tSellers.insert\n\t\t\t\t\tnumber: number\n\t\t\t\t\tname: \"Säljare #\"+number\n\t\t\t\t\tisHelper: false\n\t\t\t\tnumber++\n\t\t\n\t\t",
"end": 386,
"score": 0.9996117353439331,
"start": 379,
"tag": "NAME",
"value": "Säljare"
}
] | client/modals/generateRandomData.coffee | PeppeL-G/loppis | 0 | templateName = 'modal_generateRandomData'
Template[templateName].events
'submit form': (event, template) ->
event.preventDefault()
# Add sellers.
numberOfSellers = template.find('.numberOfSellers').value
if numberOfSellers != ''
number = Sellers.find().count()+1
for i in [1..numberOfSellers]
Sellers.insert
number: number
name: "Säljare #"+number
isHelper: false
number++
# Add purchases.
numberOfPurchases = template.find('.numberOfPurchases').value
if numberOfPurchases == ''
Modal.hide()
return
if Sellers.find().count() == 0
alert("Kan inte lägga till säljningar om det inte finns några säljare!")
Modal.hide()
return
sellers = Sellers.find().fetch()
options =
sort:
[['number', 'desc']]
prevPurchase = Purchases.findOne({}, options)
if prevPurchase
number = prevPurchase.getNumber()+1
else
number = 1
for i in [1..numberOfPurchases]
Purchases.insert
number: number
sellerNumber: sellers[Math.floor(Math.random()*sellers.length)].getNumber()
price: Math.ceil(Math.random()*300)
number++
Modal.hide() | 160624 | templateName = 'modal_generateRandomData'
Template[templateName].events
'submit form': (event, template) ->
event.preventDefault()
# Add sellers.
numberOfSellers = template.find('.numberOfSellers').value
if numberOfSellers != ''
number = Sellers.find().count()+1
for i in [1..numberOfSellers]
Sellers.insert
number: number
name: "<NAME> #"+number
isHelper: false
number++
# Add purchases.
numberOfPurchases = template.find('.numberOfPurchases').value
if numberOfPurchases == ''
Modal.hide()
return
if Sellers.find().count() == 0
alert("Kan inte lägga till säljningar om det inte finns några säljare!")
Modal.hide()
return
sellers = Sellers.find().fetch()
options =
sort:
[['number', 'desc']]
prevPurchase = Purchases.findOne({}, options)
if prevPurchase
number = prevPurchase.getNumber()+1
else
number = 1
for i in [1..numberOfPurchases]
Purchases.insert
number: number
sellerNumber: sellers[Math.floor(Math.random()*sellers.length)].getNumber()
price: Math.ceil(Math.random()*300)
number++
Modal.hide() | true | templateName = 'modal_generateRandomData'
Template[templateName].events
'submit form': (event, template) ->
event.preventDefault()
# Add sellers.
numberOfSellers = template.find('.numberOfSellers').value
if numberOfSellers != ''
number = Sellers.find().count()+1
for i in [1..numberOfSellers]
Sellers.insert
number: number
name: "PI:NAME:<NAME>END_PI #"+number
isHelper: false
number++
# Add purchases.
numberOfPurchases = template.find('.numberOfPurchases').value
if numberOfPurchases == ''
Modal.hide()
return
if Sellers.find().count() == 0
alert("Kan inte lägga till säljningar om det inte finns några säljare!")
Modal.hide()
return
sellers = Sellers.find().fetch()
options =
sort:
[['number', 'desc']]
prevPurchase = Purchases.findOne({}, options)
if prevPurchase
number = prevPurchase.getNumber()+1
else
number = 1
for i in [1..numberOfPurchases]
Purchases.insert
number: number
sellerNumber: sellers[Math.floor(Math.random()*sellers.length)].getNumber()
price: Math.ceil(Math.random()*300)
number++
Modal.hide() |
[
{
"context": " File : bigbang_spec.coffee\n# Maintainer : Felix C. Stegerman <flx@obfusk.net>\n# Date : 2014-04-05\n#\n# C",
"end": 143,
"score": 0.9998846054077148,
"start": 125,
"tag": "NAME",
"value": "Felix C. Stegerman"
},
{
"context": "g_spec.coffee\n# Maintainer... | spec/bigbang_spec.coffee | obfusk/bigbang.coffee | 1 | # -- ; {{{1
#
# File : bigbang_spec.coffee
# Maintainer : Felix C. Stegerman <flx@obfusk.net>
# Date : 2014-04-05
#
# Copyright : Copyright (C) 2014 Felix C. Stegerman
# Licence : LGPLv3+
#
# -- ; }}}1
B = bigbang
anim = B.polyRequestAnimationFrame()
anim8 = B.polyRequestAnimationFrame delay: 125
between = (x, m, n) ->
expect(x).toBeGreaterThan m
expect(x).toBeLessThan n
describe 'polyRequestAnimationFrame', -> # {{{1
it 'calls back w/ approx. 60 fps', (done) ->
i = 0; ts = []
f = (t) ->
ts.push t; ++i
if i == 50 then end() else anim f
end = ->
expect(i).toBe 50
expect(ts.length).toBe 50
between ts[49] - ts[0], 800, 900 # ~60 fps; 17ms * 50 = 850ms
done()
anim f
# }}}1
# NB: reliance on $._data may break in future
describe 'bigbang', -> # {{{1
canvas = log = pix = null
trig = (t, f) -> (as...) ->
e = $.Event t; f e, as...; canvas.trigger e
key = trig 'keydown', (e, which, shift = false) ->
e.which = which; e.shiftKey = shift
click = trig 'click', (e, ox, oy) -> e.offsetX = ox; e.offsetY = oy
foo = trig 'foo', (e, x) -> e.x = x
bar = trig 'bar', (e, x, y) -> e.x = x; e.y = y
beforeEach (done) ->
anim ->
canvas = $('<canvas>').css width: '400px', height: '300px'
log = []
pix = []
done()
describe 'works as advertised:', ->
it 'can count from 0 to 9; ticking, checking and drawing', # {{{2
(done) ->
w = 0
t = (n) -> log.push ['t',n]; n + 1
q = (n) -> log.push ['q',n]; n == 9
d = (n) -> (c) -> c.push n
s = (n) ->
expect(n).toBe 9
expect(log).toEqual [['q',0],['t',0],['q',1],['t',1],
['q',2],['t',2],['q',3],['t',3],
['q',4],['t',4],['q',5],['t',5],
['q',6],['t',6],['q',7],['t',7],
['q',8],['t',8],['q',9]]
expect(pix).toEqual [0..9]
done()
bigbang
world: w, canvas: pix, on_tick: t, stop_when: q, to_draw: d,
on_stop: s, animate: anim
# }}}2
it 'takes ~2 secs to do 40 ticks at 20 fps', (done) -> # {{{2
w = 0
t = (n) -> n + 1
q = (n) -> n == 40
d = (n) -> (c) -> null
s = (n) ->
between Math.round((+new Date - t1) / 100), 18, 25 # ~2 secs
done()
t1 = +new Date
bigbang
world: w, canvas: pix, on_tick: t, stop_when: q, to_draw: d,
on_stop: s, fps: 20, animate: anim
# }}}2
it 'can stop_with', (done) -> # {{{2
w = 0
t = (n) ->
log.push ['t',n]
if n == 6 then B.stop_with 99 else n + 1
d = (n) -> (c) -> c.push n
s = (n) ->
expect(n).toBe 99
expect(log).toEqual [['t',0],['t',1],['t',2],['t',3],
['t',4],['t',5],['t',6]]
expect(pix).toEqual [0..6].concat [99]
done()
bigbang
world: w, canvas: pix, on_tick: t, to_draw: d, on_stop: s,
animate: anim
# }}}2
it 'uses last_draw', (done) -> # {{{2
w = 0
t = (n) -> if n == 6 then B.stop_with 99 else n + 1
d = (n) -> (c) -> c.push n
l = (n) -> (c) -> c.push -n
s = (n) ->
expect(n).toBe 99
expect(pix).toEqual [0..6].concat [-99]
done()
bigbang
world: w, canvas: pix, on_tick: t, to_draw: d, last_draw: l,
on_stop: s, animate: anim
# }}}2
it 'returns state functions', (done) -> # {{{2
w = 0
t = (n) -> n + 1
q = (n) -> n == 9
d = (n) -> (c) -> c.push n
s = (n) ->
expect(n).toBe 9
expect(pix).toEqual [0..9]
expect(bb.world()).toBe 9
expect(bb.done()).toBe true
done()
bb = bigbang
world: w, canvas: pix, on_tick: t, stop_when: q, to_draw: d,
on_stop: s, animate: anim
expect(bb.world()).toBe 0
expect(bb.done()).toBe false
# }}}2
describe 'handles keys, clicks and other events:', ->
it 'handles keys (tickless) and cleans up', (done) -> # {{{2
w = 0
d = (n) -> (c) -> pix.push n
k = (n, k) ->
log.push [n,k]
if k == 'space' then B.stop_with 99 else n + 1
s = (n) ->
expect(n).toBe 99
expect(log).toEqual [[0,'a'],[1,'z'],[2,'TAB'],[3,'space']]
expect(pix).toEqual [0,1,2,3,99]
expect($._data canvas[0], 'events').not.toBeDefined()
done()
bigbang
world: w, canvas: canvas, to_draw: d, on_key: k, on_stop: s
key 65; key -1; key 90; key 9, true; key 32; key 48
# }}}2
it 'handles clicks (tickless) and cleans up', (done) -> # {{{2
w = 0
d = (n) -> (c) -> pix.push n
c = (n, x, y) ->
log.push [n,x,y]
if _.isEqual [x,y], [37,42] then B.stop_with 99 else n + 1
s = (n) ->
expect(n).toBe 99
expect(log).toEqual [[0,10,7],[1,7,10],[2,100,100],[3,37,42]]
expect(pix).toEqual [0,1,2,3,99]
expect($._data canvas[0], 'events').not.toBeDefined()
done()
bigbang
world: w, canvas: canvas, to_draw: d, on_click: c, on_stop: s
click 10, 7; click 7, 10; click 100, 100; click 37, 42
# }}}2
it 'handles on (tickless); uses setup, teardown', (done) -> # {{{2
w = 0
d = (n) -> (c) -> pix.push n
f = (n, x) ->
log.push ['f',n,x]
if x == 'bye' then B.stop_with 99 else n + 1
g = (n, x, y) -> log.push ['g',n,x,y]; n * 2
o = foo: f, bar: g
u = (c,hs) ->
h_foo = (e) -> hs.foo e.x
h_bar = (e) -> hs.bar e.x, e.y
canvas.on 'foo', h_foo
canvas.on 'bar', h_bar
log.push ['u']; {h_foo,h_bar}
t = (c, hs, sv) ->
events = _.keys($._data canvas[0], 'events').sort()
expect(events).toEqual ['bar', 'foo']
canvas.off 'foo', sv.h_foo
canvas.off 'bar', sv.h_bar
log.push ['t',_.keys(sv).sort()]; 'teardown'
s = (n, tv) ->
expect(n).toBe 99
expect(tv).toBe 'teardown'
expect(log).toEqual [['u'],
['f',0,'hi'],['g',1,'2','OK'],
['g',2,37,'y'],['f',4,'bye'],
['t',['h_bar','h_foo']]]
expect(pix).toEqual [0,1,2,4,99]
expect($._data canvas[0], 'events').not.toBeDefined()
done()
bigbang
world: w, canvas: canvas, to_draw: d, on: o, setup: u,
teardown: t, on_stop: s
foo 'hi'; bar '2', 'OK'; bar 37, 'y'; foo 'bye'; bar 'NO', 'NO'
# }}}2
describe 'queues:', ->
beforeEach (done) -> anim8 -> done()
it 'queue works w/ keys [if timing OK]', (done) -> # {{{2
ts = []
w = 0
t = (n) -> log.push n; n + 1
k = (n, k) -> log.push [n,k]; n + 2
d = (n) -> (c) -> pix.push n; ts.push +new Date
q = (n) -> n >= 12
s = (n) ->
ds = ts.map (x) -> x - ts[0]
expect(log).toEqual [[0,'a'],[2,'b'],4,5,6,[7,'y'],[9,'z'],11]
expect(pix).toEqual [0,2,4,5,6,7,9,11,12]
expect(Math.abs(ds[1] - 125)).toBeLessThan 20
expect(Math.abs(ds[2] - 125)).toBeLessThan 20
expect(Math.abs(ds[6] - 875)).toBeLessThan 20
expect(Math.abs(ds[7] - 875)).toBeLessThan 20
expect(ts[2] - ts[1]).toBeLessThan 5
expect(ts[7] - ts[6]).toBeLessThan 5
done()
bigbang
world: w, canvas: canvas, on_tick: t, on_key: k, stop_when: q,
to_draw: d, on_stop: s, fps: 4, animate: anim8
setTimeout (-> key 65), 50
setTimeout (-> key 66), 80
setTimeout (-> key 89), 795
setTimeout (-> key 90), 825
# }}}2
it 'queue:false works w/ keys [if timing OK]', (done) -> # {{{2
ts = []
w = 0
t = (n) -> log.push n; n + 1
k = (n, k) -> log.push [n,k]; n + 2
d = (n) -> (c) -> pix.push n; ts.push +new Date
q = (n) -> n >= 12
s = (n) ->
ds = ts.map (x) -> x - ts[0]
expect(log).toEqual [[0,'a'],[2,'b'],4,5,6,[7,'y'],[9,'z'],11]
expect(pix).toEqual [0,2,4,5,6,7,9,11,12]
expect(Math.abs(ds[1] - 50)).toBeLessThan 20
expect(Math.abs(ds[2] - 80)).toBeLessThan 20
expect(Math.abs(ds[6] - 795)).toBeLessThan 20
expect(Math.abs(ds[7] - 825)).toBeLessThan 20
expect(Math.abs(ts[2] - ts[1])).toBeLessThan 50
expect(Math.abs(ts[7] - ts[6])).toBeLessThan 50
done()
bigbang
world: w, canvas: canvas, on_tick: t, on_key: k, stop_when: q,
to_draw: d, on_stop: s, fps: 4, queue: false, animate: anim8
setTimeout (-> key 65), 50
setTimeout (-> key 66), 80
setTimeout (-> key 89), 795
setTimeout (-> key 90), 825
# }}}2
it 'queue:1 works w/ keys [if timing OK]', (done) -> # {{{2
w = 0
t = (n) -> log.push n; n + 1
k = (n, k) -> log.push [n,k]; n + 2
d = (n) -> (c) -> pix.push n
q = (n) -> n >= 12
s = (n) ->
expect(log).toEqual [[0,'a'],[2,'b'],4,5,6,[7,'y'],[9,'z'],11]
expect(pix).toEqual [0,4,5,6,7,11,12]
done()
bigbang
world: w, canvas: canvas, on_tick: t, on_key: k, stop_when: q,
to_draw: d, on_stop: s, fps: 4, queue: 1, animate: anim8
setTimeout (-> key 65), 50
setTimeout (-> key 66), 80
setTimeout (-> key 89), 795
setTimeout (-> key 90), 825
# }}}2
# }}}1
describe 'empty_scene', ->
it 'sets width and height', ->
x = {}; B.empty_scene(800, 600)(x)
expect(x.width).toBe 800
expect(x.height).toBe 600
describe 'place_text', -> # {{{1
log = scene = canvas = ctx = null
beforeEach ->
log = []
scene = (c) -> log.push c
canvas = getContext: -> ctx
ctx =
save: -> log.push 'save'
restore: -> log.push 'restore'
fillText: (s,x,y) -> this._fillText = {s,x,y}
B.place_text('Foo', 100, 200, '1em', 'red', scene)(canvas)
it 'calls scene, saves, and restores', ->
expect(log).toEqual [canvas, 'save', 'restore']
it 'sets font', ->
expect(ctx.font).toBe '1em sans-serif'
it 'sets fillStyle', ->
expect(ctx.fillStyle).toBe 'red'
it 'sets textBaseline', ->
expect(ctx.textBaseline).toBe 'bottom'
it 'calls fillText w/ appropriate arguments', ->
{w,h} = B.measure_text $, 'Foo', '1em', 'sans-serif'
expect(ctx._fillText.s).toBe 'Foo'
expect(ctx._fillText.x).toBe Math.round(100 - w / 2)
expect(ctx._fillText.y).toBe Math.round(200 + h / 2)
# }}}1
describe 'place_image', -> # {{{1
i = width: 100, height: 200
log = scene = canvas = ctx = null
beforeEach ->
log = []
scene = (c) -> log.push c
canvas = getContext: -> ctx
ctx = drawImage: (i,x,y) -> this._drawImage = {i,x,y}
B.place_image(i, 300, 400, scene)(canvas)
it 'calls scene', ->
expect(log).toEqual [canvas]
it 'calls drawImage w/ appropriate arguments', ->
expect(ctx._drawImage).toEqual { i, x: 250, y: 300 }
# }}}1
# ...
describe 'handle_keys', -> # {{{1
elem = log = fake$ = null
event = (f, which, shift = false, g = null) ->
c = B.handle_keys elem, ((k) -> f(c)(k)), fake$
e = $.Event 'keydown'; e.which = which; e.shiftKey = shift; g? e
elem.trigger e
beforeEach ->
elem = $('<div>').css width: '400px', height: '300px'
log = []
fake$ = (x) ->
on: (e,h) -> log.push ['on' ,x,e]; $(x).on e, h
off: (e,h) -> log.push ['off',x,e]; $(x).off e, h
it 'passes "a" when a is pressed', (done) ->
f = (c) -> (k) -> expect(k).toBe 'a'; done()
event f, 65
it 'passes "Z" when z+shift is pressed', (done) ->
f = (c) -> (k) -> expect(k).toBe 'Z'; done()
event f, 90, true
it 'passes "1" when a is pressed', (done) ->
f = (c) -> (k) -> expect(k).toBe '1'; done()
event f, 49
it 'passes "SHIFT_8" when z+shift is pressed', (done) ->
f = (c) -> (k) -> expect(k).toBe 'SHIFT_8'; done()
event f, 56, true
it 'passes "space" when space is pressed', (done) ->
f = (c) -> (k) -> expect(k).toBe 'space'; done()
event f, 32
it 'passes "LEFT" when left+shift is pressed', (done) ->
f = (c) -> (k) -> expect(k).toBe 'LEFT'; done()
event f, 37, true
it 'is triggered quickly', (done) ->
called = false
f = (c) -> (k) -> called = true
setTimeout (-> expect(called).toBe true; done()), 50
event f, 65
it 'ignores keydown when which = -1', (done) ->
called = false
f = (c) -> (k) -> called = true
setTimeout (-> expect(called).toBe false; done()), 50
event f, -1
it 'ignores keydown when altKey = true', (done) ->
called = false
f = (c) -> (k) -> called = true
setTimeout (-> expect(called).toBe false; done()), 50
event f, 32, false, (e) -> e.altKey = true
it 'calls on and off properly', (done) ->
f = (c) -> (k) ->
expect(log.length).toBe 1
c()
expect(log.length).toBe 2
expect(log).toEqual [['on' , elem, 'keydown'],
['off', elem, 'keydown']]
done()
event f, 65
# }}}1
describe 'key_to_string', -> # {{{1
it 'converts to a', ->
expect(B.key_to_string 65, false).toBe 'a'
it 'converts to z', ->
expect(B.key_to_string 90, false).toBe 'z'
it 'converts to A', ->
expect(B.key_to_string 65, true).toBe 'A'
it 'converts to Z', ->
expect(B.key_to_string 90, true).toBe 'Z'
it 'converts to space', ->
expect(B.key_to_string 32, false).toBe 'space'
it 'converts to SPACE', ->
expect(B.key_to_string 32, true).toBe 'SPACE'
# }}}1
describe 'handle_click', -> # {{{1
elem = log = fake$ = null
event = (f, ox, oy) ->
c = B.handle_click elem, ((x,y) -> f(c)(x,y)), fake$
e = $.Event 'click'; e.offsetX = ox; e.offsetY = oy
elem.trigger e
beforeEach ->
elem = $('<div>').css
width: '400px', height: '300px', border: '10px solid red'
log = []
fake$ = (x) ->
on: (e,h) -> log.push ['on' ,x,e]; $(x).on e, h
off: (e,h) -> log.push ['off',x,e]; $(x).off e, h
it 'passes "{x:10,y:20}" when (20,30) is clicked w/ 10px border',
(done) ->
f = (c) -> (x,y) -> expect({x,y}).toEqual {x:10,y:20}; done()
event f, 20, 30
it 'calls on and off properly', (done) ->
f = (c) -> (x,y) ->
expect(log.length).toBe 1
c()
expect(log.length).toBe 2
expect(log).toEqual [['on' , elem, 'click'],
['off', elem, 'click']]
done()
event f, 10, 10
# }}}1
describe 'mouse_position', -> # {{{1
elem = null
beforeEach ->
elem = $('<div>').css
width: '400px', height: '300px'
margin: '10px', padding: '20px', border: '30px solid red'
$('body').append elem
afterEach ->
elem.remove()
it 'handles padding and border', (done) ->
elem.on 'click', (e) ->
expect(B.mouse_position e).toEqual x: 5, y: 10
done()
e = $.Event 'click'; e.offsetX = 55; e.offsetY = 60
elem.trigger e
# }}}1
# FIXME: these tests might be to brittle; current margins based on
# tests w/ phantomjs, chromium, firefox; font settings WILL affect
# this test
describe 'measure_text', -> # {{{1
it 'calculates height and with of text', ->
a = [$, 'Foo', '1em', 'sans-serif']
b = [$, 'Foo', '2em', 'sans-serif']
c = [$, 'Foo', '50px', 'serif']
{w:aw,h:ah} = B.measure_text a...
{w:bw,h:bh} = B.measure_text b...
{w:cw,h:ch} = B.measure_text c...
between aw, 21, 30; between ah, 17, 23
between bw, 45, 59; between bh, 36, 43
between cw, 70, 96; between ch, 57, 65
# }}}1
# vim: set tw=70 sw=2 sts=2 et fdm=marker :
| 71470 | # -- ; {{{1
#
# File : bigbang_spec.coffee
# Maintainer : <NAME> <<EMAIL>>
# Date : 2014-04-05
#
# Copyright : Copyright (C) 2014 <NAME>
# Licence : LGPLv3+
#
# -- ; }}}1
B = bigbang
anim = B.polyRequestAnimationFrame()
anim8 = B.polyRequestAnimationFrame delay: 125
between = (x, m, n) ->
expect(x).toBeGreaterThan m
expect(x).toBeLessThan n
describe 'polyRequestAnimationFrame', -> # {{{1
it 'calls back w/ approx. 60 fps', (done) ->
i = 0; ts = []
f = (t) ->
ts.push t; ++i
if i == 50 then end() else anim f
end = ->
expect(i).toBe 50
expect(ts.length).toBe 50
between ts[49] - ts[0], 800, 900 # ~60 fps; 17ms * 50 = 850ms
done()
anim f
# }}}1
# NB: reliance on $._data may break in future
describe 'bigbang', -> # {{{1
canvas = log = pix = null
trig = (t, f) -> (as...) ->
e = $.Event t; f e, as...; canvas.trigger e
key = trig 'keydown', (e, which, shift = false) ->
e.which = which; e.shiftKey = shift
click = trig 'click', (e, ox, oy) -> e.offsetX = ox; e.offsetY = oy
foo = trig 'foo', (e, x) -> e.x = x
bar = trig 'bar', (e, x, y) -> e.x = x; e.y = y
beforeEach (done) ->
anim ->
canvas = $('<canvas>').css width: '400px', height: '300px'
log = []
pix = []
done()
describe 'works as advertised:', ->
it 'can count from 0 to 9; ticking, checking and drawing', # {{{2
(done) ->
w = 0
t = (n) -> log.push ['t',n]; n + 1
q = (n) -> log.push ['q',n]; n == 9
d = (n) -> (c) -> c.push n
s = (n) ->
expect(n).toBe 9
expect(log).toEqual [['q',0],['t',0],['q',1],['t',1],
['q',2],['t',2],['q',3],['t',3],
['q',4],['t',4],['q',5],['t',5],
['q',6],['t',6],['q',7],['t',7],
['q',8],['t',8],['q',9]]
expect(pix).toEqual [0..9]
done()
bigbang
world: w, canvas: pix, on_tick: t, stop_when: q, to_draw: d,
on_stop: s, animate: anim
# }}}2
it 'takes ~2 secs to do 40 ticks at 20 fps', (done) -> # {{{2
w = 0
t = (n) -> n + 1
q = (n) -> n == 40
d = (n) -> (c) -> null
s = (n) ->
between Math.round((+new Date - t1) / 100), 18, 25 # ~2 secs
done()
t1 = +new Date
bigbang
world: w, canvas: pix, on_tick: t, stop_when: q, to_draw: d,
on_stop: s, fps: 20, animate: anim
# }}}2
it 'can stop_with', (done) -> # {{{2
w = 0
t = (n) ->
log.push ['t',n]
if n == 6 then B.stop_with 99 else n + 1
d = (n) -> (c) -> c.push n
s = (n) ->
expect(n).toBe 99
expect(log).toEqual [['t',0],['t',1],['t',2],['t',3],
['t',4],['t',5],['t',6]]
expect(pix).toEqual [0..6].concat [99]
done()
bigbang
world: w, canvas: pix, on_tick: t, to_draw: d, on_stop: s,
animate: anim
# }}}2
it 'uses last_draw', (done) -> # {{{2
w = 0
t = (n) -> if n == 6 then B.stop_with 99 else n + 1
d = (n) -> (c) -> c.push n
l = (n) -> (c) -> c.push -n
s = (n) ->
expect(n).toBe 99
expect(pix).toEqual [0..6].concat [-99]
done()
bigbang
world: w, canvas: pix, on_tick: t, to_draw: d, last_draw: l,
on_stop: s, animate: anim
# }}}2
it 'returns state functions', (done) -> # {{{2
w = 0
t = (n) -> n + 1
q = (n) -> n == 9
d = (n) -> (c) -> c.push n
s = (n) ->
expect(n).toBe 9
expect(pix).toEqual [0..9]
expect(bb.world()).toBe 9
expect(bb.done()).toBe true
done()
bb = bigbang
world: w, canvas: pix, on_tick: t, stop_when: q, to_draw: d,
on_stop: s, animate: anim
expect(bb.world()).toBe 0
expect(bb.done()).toBe false
# }}}2
describe 'handles keys, clicks and other events:', ->
it 'handles keys (tickless) and cleans up', (done) -> # {{{2
w = 0
d = (n) -> (c) -> pix.push n
k = (n, k) ->
log.push [n,k]
if k == 'space' then B.stop_with 99 else n + 1
s = (n) ->
expect(n).toBe 99
expect(log).toEqual [[0,'a'],[1,'z'],[2,'TAB'],[3,'space']]
expect(pix).toEqual [0,1,2,3,99]
expect($._data canvas[0], 'events').not.toBeDefined()
done()
bigbang
world: w, canvas: canvas, to_draw: d, on_key: k, on_stop: s
key 65; key -1; key 90; key 9, true; key 32; key 48
# }}}2
it 'handles clicks (tickless) and cleans up', (done) -> # {{{2
w = 0
d = (n) -> (c) -> pix.push n
c = (n, x, y) ->
log.push [n,x,y]
if _.isEqual [x,y], [37,42] then B.stop_with 99 else n + 1
s = (n) ->
expect(n).toBe 99
expect(log).toEqual [[0,10,7],[1,7,10],[2,100,100],[3,37,42]]
expect(pix).toEqual [0,1,2,3,99]
expect($._data canvas[0], 'events').not.toBeDefined()
done()
bigbang
world: w, canvas: canvas, to_draw: d, on_click: c, on_stop: s
click 10, 7; click 7, 10; click 100, 100; click 37, 42
# }}}2
it 'handles on (tickless); uses setup, teardown', (done) -> # {{{2
w = 0
d = (n) -> (c) -> pix.push n
f = (n, x) ->
log.push ['f',n,x]
if x == 'bye' then B.stop_with 99 else n + 1
g = (n, x, y) -> log.push ['g',n,x,y]; n * 2
o = foo: f, bar: g
u = (c,hs) ->
h_foo = (e) -> hs.foo e.x
h_bar = (e) -> hs.bar e.x, e.y
canvas.on 'foo', h_foo
canvas.on 'bar', h_bar
log.push ['u']; {h_foo,h_bar}
t = (c, hs, sv) ->
events = _.keys($._data canvas[0], 'events').sort()
expect(events).toEqual ['bar', 'foo']
canvas.off 'foo', sv.h_foo
canvas.off 'bar', sv.h_bar
log.push ['t',_.keys(sv).sort()]; 'teardown'
s = (n, tv) ->
expect(n).toBe 99
expect(tv).toBe 'teardown'
expect(log).toEqual [['u'],
['f',0,'hi'],['g',1,'2','OK'],
['g',2,37,'y'],['f',4,'bye'],
['t',['h_bar','h_foo']]]
expect(pix).toEqual [0,1,2,4,99]
expect($._data canvas[0], 'events').not.toBeDefined()
done()
bigbang
world: w, canvas: canvas, to_draw: d, on: o, setup: u,
teardown: t, on_stop: s
foo 'hi'; bar '2', 'OK'; bar 37, 'y'; foo 'bye'; bar 'NO', 'NO'
# }}}2
describe 'queues:', ->
beforeEach (done) -> anim8 -> done()
it 'queue works w/ keys [if timing OK]', (done) -> # {{{2
ts = []
w = 0
t = (n) -> log.push n; n + 1
k = (n, k) -> log.push [n,k]; n + 2
d = (n) -> (c) -> pix.push n; ts.push +new Date
q = (n) -> n >= 12
s = (n) ->
ds = ts.map (x) -> x - ts[0]
expect(log).toEqual [[0,'a'],[2,'b'],4,5,6,[7,'y'],[9,'z'],11]
expect(pix).toEqual [0,2,4,5,6,7,9,11,12]
expect(Math.abs(ds[1] - 125)).toBeLessThan 20
expect(Math.abs(ds[2] - 125)).toBeLessThan 20
expect(Math.abs(ds[6] - 875)).toBeLessThan 20
expect(Math.abs(ds[7] - 875)).toBeLessThan 20
expect(ts[2] - ts[1]).toBeLessThan 5
expect(ts[7] - ts[6]).toBeLessThan 5
done()
bigbang
world: w, canvas: canvas, on_tick: t, on_key: k, stop_when: q,
to_draw: d, on_stop: s, fps: 4, animate: anim8
setTimeout (-> key 65), 50
setTimeout (-> key 66), 80
setTimeout (-> key 89), 795
setTimeout (-> key 90), 825
# }}}2
it 'queue:false works w/ keys [if timing OK]', (done) -> # {{{2
ts = []
w = 0
t = (n) -> log.push n; n + 1
k = (n, k) -> log.push [n,k]; n + 2
d = (n) -> (c) -> pix.push n; ts.push +new Date
q = (n) -> n >= 12
s = (n) ->
ds = ts.map (x) -> x - ts[0]
expect(log).toEqual [[0,'a'],[2,'b'],4,5,6,[7,'y'],[9,'z'],11]
expect(pix).toEqual [0,2,4,5,6,7,9,11,12]
expect(Math.abs(ds[1] - 50)).toBeLessThan 20
expect(Math.abs(ds[2] - 80)).toBeLessThan 20
expect(Math.abs(ds[6] - 795)).toBeLessThan 20
expect(Math.abs(ds[7] - 825)).toBeLessThan 20
expect(Math.abs(ts[2] - ts[1])).toBeLessThan 50
expect(Math.abs(ts[7] - ts[6])).toBeLessThan 50
done()
bigbang
world: w, canvas: canvas, on_tick: t, on_key: k, stop_when: q,
to_draw: d, on_stop: s, fps: 4, queue: false, animate: anim8
setTimeout (-> key 65), 50
setTimeout (-> key 66), 80
setTimeout (-> key 89), 795
setTimeout (-> key 90), 825
# }}}2
it 'queue:1 works w/ keys [if timing OK]', (done) -> # {{{2
w = 0
t = (n) -> log.push n; n + 1
k = (n, k) -> log.push [n,k]; n + 2
d = (n) -> (c) -> pix.push n
q = (n) -> n >= 12
s = (n) ->
expect(log).toEqual [[0,'a'],[2,'b'],4,5,6,[7,'y'],[9,'z'],11]
expect(pix).toEqual [0,4,5,6,7,11,12]
done()
bigbang
world: w, canvas: canvas, on_tick: t, on_key: k, stop_when: q,
to_draw: d, on_stop: s, fps: 4, queue: 1, animate: anim8
setTimeout (-> key 65), 50
setTimeout (-> key 66), 80
setTimeout (-> key 89), 795
setTimeout (-> key 90), 825
# }}}2
# }}}1
describe 'empty_scene', ->
it 'sets width and height', ->
x = {}; B.empty_scene(800, 600)(x)
expect(x.width).toBe 800
expect(x.height).toBe 600
describe 'place_text', -> # {{{1
log = scene = canvas = ctx = null
beforeEach ->
log = []
scene = (c) -> log.push c
canvas = getContext: -> ctx
ctx =
save: -> log.push 'save'
restore: -> log.push 'restore'
fillText: (s,x,y) -> this._fillText = {s,x,y}
B.place_text('Foo', 100, 200, '1em', 'red', scene)(canvas)
it 'calls scene, saves, and restores', ->
expect(log).toEqual [canvas, 'save', 'restore']
it 'sets font', ->
expect(ctx.font).toBe '1em sans-serif'
it 'sets fillStyle', ->
expect(ctx.fillStyle).toBe 'red'
it 'sets textBaseline', ->
expect(ctx.textBaseline).toBe 'bottom'
it 'calls fillText w/ appropriate arguments', ->
{w,h} = B.measure_text $, 'Foo', '1em', 'sans-serif'
expect(ctx._fillText.s).toBe 'Foo'
expect(ctx._fillText.x).toBe Math.round(100 - w / 2)
expect(ctx._fillText.y).toBe Math.round(200 + h / 2)
# }}}1
describe 'place_image', -> # {{{1
i = width: 100, height: 200
log = scene = canvas = ctx = null
beforeEach ->
log = []
scene = (c) -> log.push c
canvas = getContext: -> ctx
ctx = drawImage: (i,x,y) -> this._drawImage = {i,x,y}
B.place_image(i, 300, 400, scene)(canvas)
it 'calls scene', ->
expect(log).toEqual [canvas]
it 'calls drawImage w/ appropriate arguments', ->
expect(ctx._drawImage).toEqual { i, x: 250, y: 300 }
# }}}1
# ...
describe 'handle_keys', -> # {{{1
elem = log = fake$ = null
event = (f, which, shift = false, g = null) ->
c = B.handle_keys elem, ((k) -> f(c)(k)), fake$
e = $.Event 'keydown'; e.which = which; e.shiftKey = shift; g? e
elem.trigger e
beforeEach ->
elem = $('<div>').css width: '400px', height: '300px'
log = []
fake$ = (x) ->
on: (e,h) -> log.push ['on' ,x,e]; $(x).on e, h
off: (e,h) -> log.push ['off',x,e]; $(x).off e, h
it 'passes "a" when a is pressed', (done) ->
f = (c) -> (k) -> expect(k).toBe 'a'; done()
event f, 65
it 'passes "Z" when z+shift is pressed', (done) ->
f = (c) -> (k) -> expect(k).toBe 'Z'; done()
event f, 90, true
it 'passes "1" when a is pressed', (done) ->
f = (c) -> (k) -> expect(k).toBe '1'; done()
event f, 49
it 'passes "SHIFT_8" when z+shift is pressed', (done) ->
f = (c) -> (k) -> expect(k).toBe 'SHIFT_8'; done()
event f, 56, true
it 'passes "space" when space is pressed', (done) ->
f = (c) -> (k) -> expect(k).toBe 'space'; done()
event f, 32
it 'passes "LEFT" when left+shift is pressed', (done) ->
f = (c) -> (k) -> expect(k).toBe 'LEFT'; done()
event f, 37, true
it 'is triggered quickly', (done) ->
called = false
f = (c) -> (k) -> called = true
setTimeout (-> expect(called).toBe true; done()), 50
event f, 65
it 'ignores keydown when which = -1', (done) ->
called = false
f = (c) -> (k) -> called = true
setTimeout (-> expect(called).toBe false; done()), 50
event f, -1
it 'ignores keydown when altKey = true', (done) ->
called = false
f = (c) -> (k) -> called = true
setTimeout (-> expect(called).toBe false; done()), 50
event f, 32, false, (e) -> e.altKey = true
it 'calls on and off properly', (done) ->
f = (c) -> (k) ->
expect(log.length).toBe 1
c()
expect(log.length).toBe 2
expect(log).toEqual [['on' , elem, 'keydown'],
['off', elem, 'keydown']]
done()
event f, 65
# }}}1
describe 'key_to_string', -> # {{{1
it 'converts to a', ->
expect(B.key_to_string 65, false).toBe 'a'
it 'converts to z', ->
expect(B.key_to_string 90, false).toBe 'z'
it 'converts to A', ->
expect(B.key_to_string 65, true).toBe 'A'
it 'converts to Z', ->
expect(B.key_to_string 90, true).toBe 'Z'
it 'converts to space', ->
expect(B.key_to_string 32, false).toBe 'space'
it 'converts to SPACE', ->
expect(B.key_to_string 32, true).toBe 'SPACE'
# }}}1
describe 'handle_click', -> # {{{1
elem = log = fake$ = null
event = (f, ox, oy) ->
c = B.handle_click elem, ((x,y) -> f(c)(x,y)), fake$
e = $.Event 'click'; e.offsetX = ox; e.offsetY = oy
elem.trigger e
beforeEach ->
elem = $('<div>').css
width: '400px', height: '300px', border: '10px solid red'
log = []
fake$ = (x) ->
on: (e,h) -> log.push ['on' ,x,e]; $(x).on e, h
off: (e,h) -> log.push ['off',x,e]; $(x).off e, h
it 'passes "{x:10,y:20}" when (20,30) is clicked w/ 10px border',
(done) ->
f = (c) -> (x,y) -> expect({x,y}).toEqual {x:10,y:20}; done()
event f, 20, 30
it 'calls on and off properly', (done) ->
f = (c) -> (x,y) ->
expect(log.length).toBe 1
c()
expect(log.length).toBe 2
expect(log).toEqual [['on' , elem, 'click'],
['off', elem, 'click']]
done()
event f, 10, 10
# }}}1
describe 'mouse_position', -> # {{{1
elem = null
beforeEach ->
elem = $('<div>').css
width: '400px', height: '300px'
margin: '10px', padding: '20px', border: '30px solid red'
$('body').append elem
afterEach ->
elem.remove()
it 'handles padding and border', (done) ->
elem.on 'click', (e) ->
expect(B.mouse_position e).toEqual x: 5, y: 10
done()
e = $.Event 'click'; e.offsetX = 55; e.offsetY = 60
elem.trigger e
# }}}1
# FIXME: these tests might be to brittle; current margins based on
# tests w/ phantomjs, chromium, firefox; font settings WILL affect
# this test
describe 'measure_text', -> # {{{1
it 'calculates height and with of text', ->
a = [$, 'Foo', '1em', 'sans-serif']
b = [$, 'Foo', '2em', 'sans-serif']
c = [$, 'Foo', '50px', 'serif']
{w:aw,h:ah} = B.measure_text a...
{w:bw,h:bh} = B.measure_text b...
{w:cw,h:ch} = B.measure_text c...
between aw, 21, 30; between ah, 17, 23
between bw, 45, 59; between bh, 36, 43
between cw, 70, 96; between ch, 57, 65
# }}}1
# vim: set tw=70 sw=2 sts=2 et fdm=marker :
| true | # -- ; {{{1
#
# File : bigbang_spec.coffee
# Maintainer : PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
# Date : 2014-04-05
#
# Copyright : Copyright (C) 2014 PI:NAME:<NAME>END_PI
# Licence : LGPLv3+
#
# -- ; }}}1
B = bigbang
anim = B.polyRequestAnimationFrame()
anim8 = B.polyRequestAnimationFrame delay: 125
between = (x, m, n) ->
expect(x).toBeGreaterThan m
expect(x).toBeLessThan n
describe 'polyRequestAnimationFrame', -> # {{{1
it 'calls back w/ approx. 60 fps', (done) ->
i = 0; ts = []
f = (t) ->
ts.push t; ++i
if i == 50 then end() else anim f
end = ->
expect(i).toBe 50
expect(ts.length).toBe 50
between ts[49] - ts[0], 800, 900 # ~60 fps; 17ms * 50 = 850ms
done()
anim f
# }}}1
# NB: reliance on $._data may break in future
describe 'bigbang', -> # {{{1
canvas = log = pix = null
trig = (t, f) -> (as...) ->
e = $.Event t; f e, as...; canvas.trigger e
key = trig 'keydown', (e, which, shift = false) ->
e.which = which; e.shiftKey = shift
click = trig 'click', (e, ox, oy) -> e.offsetX = ox; e.offsetY = oy
foo = trig 'foo', (e, x) -> e.x = x
bar = trig 'bar', (e, x, y) -> e.x = x; e.y = y
beforeEach (done) ->
anim ->
canvas = $('<canvas>').css width: '400px', height: '300px'
log = []
pix = []
done()
describe 'works as advertised:', ->
it 'can count from 0 to 9; ticking, checking and drawing', # {{{2
(done) ->
w = 0
t = (n) -> log.push ['t',n]; n + 1
q = (n) -> log.push ['q',n]; n == 9
d = (n) -> (c) -> c.push n
s = (n) ->
expect(n).toBe 9
expect(log).toEqual [['q',0],['t',0],['q',1],['t',1],
['q',2],['t',2],['q',3],['t',3],
['q',4],['t',4],['q',5],['t',5],
['q',6],['t',6],['q',7],['t',7],
['q',8],['t',8],['q',9]]
expect(pix).toEqual [0..9]
done()
bigbang
world: w, canvas: pix, on_tick: t, stop_when: q, to_draw: d,
on_stop: s, animate: anim
# }}}2
it 'takes ~2 secs to do 40 ticks at 20 fps', (done) -> # {{{2
w = 0
t = (n) -> n + 1
q = (n) -> n == 40
d = (n) -> (c) -> null
s = (n) ->
between Math.round((+new Date - t1) / 100), 18, 25 # ~2 secs
done()
t1 = +new Date
bigbang
world: w, canvas: pix, on_tick: t, stop_when: q, to_draw: d,
on_stop: s, fps: 20, animate: anim
# }}}2
it 'can stop_with', (done) -> # {{{2
w = 0
t = (n) ->
log.push ['t',n]
if n == 6 then B.stop_with 99 else n + 1
d = (n) -> (c) -> c.push n
s = (n) ->
expect(n).toBe 99
expect(log).toEqual [['t',0],['t',1],['t',2],['t',3],
['t',4],['t',5],['t',6]]
expect(pix).toEqual [0..6].concat [99]
done()
bigbang
world: w, canvas: pix, on_tick: t, to_draw: d, on_stop: s,
animate: anim
# }}}2
it 'uses last_draw', (done) -> # {{{2
w = 0
t = (n) -> if n == 6 then B.stop_with 99 else n + 1
d = (n) -> (c) -> c.push n
l = (n) -> (c) -> c.push -n
s = (n) ->
expect(n).toBe 99
expect(pix).toEqual [0..6].concat [-99]
done()
bigbang
world: w, canvas: pix, on_tick: t, to_draw: d, last_draw: l,
on_stop: s, animate: anim
# }}}2
it 'returns state functions', (done) -> # {{{2
w = 0
t = (n) -> n + 1
q = (n) -> n == 9
d = (n) -> (c) -> c.push n
s = (n) ->
expect(n).toBe 9
expect(pix).toEqual [0..9]
expect(bb.world()).toBe 9
expect(bb.done()).toBe true
done()
bb = bigbang
world: w, canvas: pix, on_tick: t, stop_when: q, to_draw: d,
on_stop: s, animate: anim
expect(bb.world()).toBe 0
expect(bb.done()).toBe false
# }}}2
describe 'handles keys, clicks and other events:', ->
it 'handles keys (tickless) and cleans up', (done) -> # {{{2
w = 0
d = (n) -> (c) -> pix.push n
k = (n, k) ->
log.push [n,k]
if k == 'space' then B.stop_with 99 else n + 1
s = (n) ->
expect(n).toBe 99
expect(log).toEqual [[0,'a'],[1,'z'],[2,'TAB'],[3,'space']]
expect(pix).toEqual [0,1,2,3,99]
expect($._data canvas[0], 'events').not.toBeDefined()
done()
bigbang
world: w, canvas: canvas, to_draw: d, on_key: k, on_stop: s
key 65; key -1; key 90; key 9, true; key 32; key 48
# }}}2
it 'handles clicks (tickless) and cleans up', (done) -> # {{{2
w = 0
d = (n) -> (c) -> pix.push n
c = (n, x, y) ->
log.push [n,x,y]
if _.isEqual [x,y], [37,42] then B.stop_with 99 else n + 1
s = (n) ->
expect(n).toBe 99
expect(log).toEqual [[0,10,7],[1,7,10],[2,100,100],[3,37,42]]
expect(pix).toEqual [0,1,2,3,99]
expect($._data canvas[0], 'events').not.toBeDefined()
done()
bigbang
world: w, canvas: canvas, to_draw: d, on_click: c, on_stop: s
click 10, 7; click 7, 10; click 100, 100; click 37, 42
# }}}2
it 'handles on (tickless); uses setup, teardown', (done) -> # {{{2
w = 0
d = (n) -> (c) -> pix.push n
f = (n, x) ->
log.push ['f',n,x]
if x == 'bye' then B.stop_with 99 else n + 1
g = (n, x, y) -> log.push ['g',n,x,y]; n * 2
o = foo: f, bar: g
u = (c,hs) ->
h_foo = (e) -> hs.foo e.x
h_bar = (e) -> hs.bar e.x, e.y
canvas.on 'foo', h_foo
canvas.on 'bar', h_bar
log.push ['u']; {h_foo,h_bar}
t = (c, hs, sv) ->
events = _.keys($._data canvas[0], 'events').sort()
expect(events).toEqual ['bar', 'foo']
canvas.off 'foo', sv.h_foo
canvas.off 'bar', sv.h_bar
log.push ['t',_.keys(sv).sort()]; 'teardown'
s = (n, tv) ->
expect(n).toBe 99
expect(tv).toBe 'teardown'
expect(log).toEqual [['u'],
['f',0,'hi'],['g',1,'2','OK'],
['g',2,37,'y'],['f',4,'bye'],
['t',['h_bar','h_foo']]]
expect(pix).toEqual [0,1,2,4,99]
expect($._data canvas[0], 'events').not.toBeDefined()
done()
bigbang
world: w, canvas: canvas, to_draw: d, on: o, setup: u,
teardown: t, on_stop: s
foo 'hi'; bar '2', 'OK'; bar 37, 'y'; foo 'bye'; bar 'NO', 'NO'
# }}}2
describe 'queues:', ->
beforeEach (done) -> anim8 -> done()
it 'queue works w/ keys [if timing OK]', (done) -> # {{{2
ts = []
w = 0
t = (n) -> log.push n; n + 1
k = (n, k) -> log.push [n,k]; n + 2
d = (n) -> (c) -> pix.push n; ts.push +new Date
q = (n) -> n >= 12
s = (n) ->
ds = ts.map (x) -> x - ts[0]
expect(log).toEqual [[0,'a'],[2,'b'],4,5,6,[7,'y'],[9,'z'],11]
expect(pix).toEqual [0,2,4,5,6,7,9,11,12]
expect(Math.abs(ds[1] - 125)).toBeLessThan 20
expect(Math.abs(ds[2] - 125)).toBeLessThan 20
expect(Math.abs(ds[6] - 875)).toBeLessThan 20
expect(Math.abs(ds[7] - 875)).toBeLessThan 20
expect(ts[2] - ts[1]).toBeLessThan 5
expect(ts[7] - ts[6]).toBeLessThan 5
done()
bigbang
world: w, canvas: canvas, on_tick: t, on_key: k, stop_when: q,
to_draw: d, on_stop: s, fps: 4, animate: anim8
setTimeout (-> key 65), 50
setTimeout (-> key 66), 80
setTimeout (-> key 89), 795
setTimeout (-> key 90), 825
# }}}2
it 'queue:false works w/ keys [if timing OK]', (done) -> # {{{2
ts = []
w = 0
t = (n) -> log.push n; n + 1
k = (n, k) -> log.push [n,k]; n + 2
d = (n) -> (c) -> pix.push n; ts.push +new Date
q = (n) -> n >= 12
s = (n) ->
ds = ts.map (x) -> x - ts[0]
expect(log).toEqual [[0,'a'],[2,'b'],4,5,6,[7,'y'],[9,'z'],11]
expect(pix).toEqual [0,2,4,5,6,7,9,11,12]
expect(Math.abs(ds[1] - 50)).toBeLessThan 20
expect(Math.abs(ds[2] - 80)).toBeLessThan 20
expect(Math.abs(ds[6] - 795)).toBeLessThan 20
expect(Math.abs(ds[7] - 825)).toBeLessThan 20
expect(Math.abs(ts[2] - ts[1])).toBeLessThan 50
expect(Math.abs(ts[7] - ts[6])).toBeLessThan 50
done()
bigbang
world: w, canvas: canvas, on_tick: t, on_key: k, stop_when: q,
to_draw: d, on_stop: s, fps: 4, queue: false, animate: anim8
setTimeout (-> key 65), 50
setTimeout (-> key 66), 80
setTimeout (-> key 89), 795
setTimeout (-> key 90), 825
# }}}2
it 'queue:1 works w/ keys [if timing OK]', (done) -> # {{{2
w = 0
t = (n) -> log.push n; n + 1
k = (n, k) -> log.push [n,k]; n + 2
d = (n) -> (c) -> pix.push n
q = (n) -> n >= 12
s = (n) ->
expect(log).toEqual [[0,'a'],[2,'b'],4,5,6,[7,'y'],[9,'z'],11]
expect(pix).toEqual [0,4,5,6,7,11,12]
done()
bigbang
world: w, canvas: canvas, on_tick: t, on_key: k, stop_when: q,
to_draw: d, on_stop: s, fps: 4, queue: 1, animate: anim8
setTimeout (-> key 65), 50
setTimeout (-> key 66), 80
setTimeout (-> key 89), 795
setTimeout (-> key 90), 825
# }}}2
# }}}1
describe 'empty_scene', ->
it 'sets width and height', ->
x = {}; B.empty_scene(800, 600)(x)
expect(x.width).toBe 800
expect(x.height).toBe 600
describe 'place_text', -> # {{{1
log = scene = canvas = ctx = null
beforeEach ->
log = []
scene = (c) -> log.push c
canvas = getContext: -> ctx
ctx =
save: -> log.push 'save'
restore: -> log.push 'restore'
fillText: (s,x,y) -> this._fillText = {s,x,y}
B.place_text('Foo', 100, 200, '1em', 'red', scene)(canvas)
it 'calls scene, saves, and restores', ->
expect(log).toEqual [canvas, 'save', 'restore']
it 'sets font', ->
expect(ctx.font).toBe '1em sans-serif'
it 'sets fillStyle', ->
expect(ctx.fillStyle).toBe 'red'
it 'sets textBaseline', ->
expect(ctx.textBaseline).toBe 'bottom'
it 'calls fillText w/ appropriate arguments', ->
{w,h} = B.measure_text $, 'Foo', '1em', 'sans-serif'
expect(ctx._fillText.s).toBe 'Foo'
expect(ctx._fillText.x).toBe Math.round(100 - w / 2)
expect(ctx._fillText.y).toBe Math.round(200 + h / 2)
# }}}1
describe 'place_image', -> # {{{1
i = width: 100, height: 200
log = scene = canvas = ctx = null
beforeEach ->
log = []
scene = (c) -> log.push c
canvas = getContext: -> ctx
ctx = drawImage: (i,x,y) -> this._drawImage = {i,x,y}
B.place_image(i, 300, 400, scene)(canvas)
it 'calls scene', ->
expect(log).toEqual [canvas]
it 'calls drawImage w/ appropriate arguments', ->
expect(ctx._drawImage).toEqual { i, x: 250, y: 300 }
# }}}1
# ...
describe 'handle_keys', -> # {{{1
elem = log = fake$ = null
event = (f, which, shift = false, g = null) ->
c = B.handle_keys elem, ((k) -> f(c)(k)), fake$
e = $.Event 'keydown'; e.which = which; e.shiftKey = shift; g? e
elem.trigger e
beforeEach ->
elem = $('<div>').css width: '400px', height: '300px'
log = []
fake$ = (x) ->
on: (e,h) -> log.push ['on' ,x,e]; $(x).on e, h
off: (e,h) -> log.push ['off',x,e]; $(x).off e, h
it 'passes "a" when a is pressed', (done) ->
f = (c) -> (k) -> expect(k).toBe 'a'; done()
event f, 65
it 'passes "Z" when z+shift is pressed', (done) ->
f = (c) -> (k) -> expect(k).toBe 'Z'; done()
event f, 90, true
it 'passes "1" when a is pressed', (done) ->
f = (c) -> (k) -> expect(k).toBe '1'; done()
event f, 49
it 'passes "SHIFT_8" when z+shift is pressed', (done) ->
f = (c) -> (k) -> expect(k).toBe 'SHIFT_8'; done()
event f, 56, true
it 'passes "space" when space is pressed', (done) ->
f = (c) -> (k) -> expect(k).toBe 'space'; done()
event f, 32
it 'passes "LEFT" when left+shift is pressed', (done) ->
f = (c) -> (k) -> expect(k).toBe 'LEFT'; done()
event f, 37, true
it 'is triggered quickly', (done) ->
called = false
f = (c) -> (k) -> called = true
setTimeout (-> expect(called).toBe true; done()), 50
event f, 65
it 'ignores keydown when which = -1', (done) ->
called = false
f = (c) -> (k) -> called = true
setTimeout (-> expect(called).toBe false; done()), 50
event f, -1
it 'ignores keydown when altKey = true', (done) ->
called = false
f = (c) -> (k) -> called = true
setTimeout (-> expect(called).toBe false; done()), 50
event f, 32, false, (e) -> e.altKey = true
it 'calls on and off properly', (done) ->
f = (c) -> (k) ->
expect(log.length).toBe 1
c()
expect(log.length).toBe 2
expect(log).toEqual [['on' , elem, 'keydown'],
['off', elem, 'keydown']]
done()
event f, 65
# }}}1
describe 'key_to_string', -> # {{{1
it 'converts to a', ->
expect(B.key_to_string 65, false).toBe 'a'
it 'converts to z', ->
expect(B.key_to_string 90, false).toBe 'z'
it 'converts to A', ->
expect(B.key_to_string 65, true).toBe 'A'
it 'converts to Z', ->
expect(B.key_to_string 90, true).toBe 'Z'
it 'converts to space', ->
expect(B.key_to_string 32, false).toBe 'space'
it 'converts to SPACE', ->
expect(B.key_to_string 32, true).toBe 'SPACE'
# }}}1
describe 'handle_click', -> # {{{1
elem = log = fake$ = null
event = (f, ox, oy) ->
c = B.handle_click elem, ((x,y) -> f(c)(x,y)), fake$
e = $.Event 'click'; e.offsetX = ox; e.offsetY = oy
elem.trigger e
beforeEach ->
elem = $('<div>').css
width: '400px', height: '300px', border: '10px solid red'
log = []
fake$ = (x) ->
on: (e,h) -> log.push ['on' ,x,e]; $(x).on e, h
off: (e,h) -> log.push ['off',x,e]; $(x).off e, h
it 'passes "{x:10,y:20}" when (20,30) is clicked w/ 10px border',
(done) ->
f = (c) -> (x,y) -> expect({x,y}).toEqual {x:10,y:20}; done()
event f, 20, 30
it 'calls on and off properly', (done) ->
f = (c) -> (x,y) ->
expect(log.length).toBe 1
c()
expect(log.length).toBe 2
expect(log).toEqual [['on' , elem, 'click'],
['off', elem, 'click']]
done()
event f, 10, 10
# }}}1
describe 'mouse_position', -> # {{{1
elem = null
beforeEach ->
elem = $('<div>').css
width: '400px', height: '300px'
margin: '10px', padding: '20px', border: '30px solid red'
$('body').append elem
afterEach ->
elem.remove()
it 'handles padding and border', (done) ->
elem.on 'click', (e) ->
expect(B.mouse_position e).toEqual x: 5, y: 10
done()
e = $.Event 'click'; e.offsetX = 55; e.offsetY = 60
elem.trigger e
# }}}1
# FIXME: these tests might be to brittle; current margins based on
# tests w/ phantomjs, chromium, firefox; font settings WILL affect
# this test
describe 'measure_text', -> # {{{1
it 'calculates height and with of text', ->
a = [$, 'Foo', '1em', 'sans-serif']
b = [$, 'Foo', '2em', 'sans-serif']
c = [$, 'Foo', '50px', 'serif']
{w:aw,h:ah} = B.measure_text a...
{w:bw,h:bh} = B.measure_text b...
{w:cw,h:ch} = B.measure_text c...
between aw, 21, 30; between ah, 17, 23
between bw, 45, 59; between bh, 36, 43
between cw, 70, 96; between ch, 57, 65
# }}}1
# vim: set tw=70 sw=2 sts=2 et fdm=marker :
|
[
{
"context": "e = @\n checkAuthTimeout = null\n emailKey = 'ccEmail'\n $service.status = \n shouldPromptEmail",
"end": 112,
"score": 0.9985605478286743,
"start": 105,
"tag": "KEY",
"value": "ccEmail"
}
] | app/assets/javascripts/shared/services/email_collector_service.js.coffee | Exygy/Children-s-Council | 1 | EmailCollectorService = ($auth, $window) ->
$service = @
checkAuthTimeout = null
emailKey = 'ccEmail'
$service.status =
shouldPromptEmailCta: true
limit: 5
$service.checkEmailStatus = () ->
if !checkAuthTimeout
# there could be a delay until $auth.currentUser() returns the actual user, checking twice
checkAuthTimeout = setTimeout () ->
$service.checkEmailStatus()
checkAuthTimeout = null
, 1000
if $auth.currentUser()
$service.status.shouldPromptEmailCta = false
$service.status.limit = 15
return
email = $window.localStorage.getItem emailKey
if email == null
$service.status.shouldPromptEmailCta = true
$service.status.limit = 5
else
$service.status.shouldPromptEmailCta = false
$service.status.limit = 15
$service.storeEmail = (email) ->
if !email
return
$window.localStorage.setItem emailKey, email
$service.status.shouldPromptEmailCta = false
$service.status.limit = 15
$service
EmailCollectorService.$inject = ['$auth', '$window']
angular.module('CCR').service('EmailCollectorService', EmailCollectorService)
| 136851 | EmailCollectorService = ($auth, $window) ->
$service = @
checkAuthTimeout = null
emailKey = '<KEY>'
$service.status =
shouldPromptEmailCta: true
limit: 5
$service.checkEmailStatus = () ->
if !checkAuthTimeout
# there could be a delay until $auth.currentUser() returns the actual user, checking twice
checkAuthTimeout = setTimeout () ->
$service.checkEmailStatus()
checkAuthTimeout = null
, 1000
if $auth.currentUser()
$service.status.shouldPromptEmailCta = false
$service.status.limit = 15
return
email = $window.localStorage.getItem emailKey
if email == null
$service.status.shouldPromptEmailCta = true
$service.status.limit = 5
else
$service.status.shouldPromptEmailCta = false
$service.status.limit = 15
$service.storeEmail = (email) ->
if !email
return
$window.localStorage.setItem emailKey, email
$service.status.shouldPromptEmailCta = false
$service.status.limit = 15
$service
EmailCollectorService.$inject = ['$auth', '$window']
angular.module('CCR').service('EmailCollectorService', EmailCollectorService)
| true | EmailCollectorService = ($auth, $window) ->
$service = @
checkAuthTimeout = null
emailKey = 'PI:KEY:<KEY>END_PI'
$service.status =
shouldPromptEmailCta: true
limit: 5
$service.checkEmailStatus = () ->
if !checkAuthTimeout
# there could be a delay until $auth.currentUser() returns the actual user, checking twice
checkAuthTimeout = setTimeout () ->
$service.checkEmailStatus()
checkAuthTimeout = null
, 1000
if $auth.currentUser()
$service.status.shouldPromptEmailCta = false
$service.status.limit = 15
return
email = $window.localStorage.getItem emailKey
if email == null
$service.status.shouldPromptEmailCta = true
$service.status.limit = 5
else
$service.status.shouldPromptEmailCta = false
$service.status.limit = 15
$service.storeEmail = (email) ->
if !email
return
$window.localStorage.setItem emailKey, email
$service.status.shouldPromptEmailCta = false
$service.status.limit = 15
$service
EmailCollectorService.$inject = ['$auth', '$window']
angular.module('CCR').service('EmailCollectorService', EmailCollectorService)
|
[
{
"context": "# Copyright © 2014–6 Brad Ackerman.\n#\n# Licensed under the Apache License, Version 2",
"end": 34,
"score": 0.9998375177383423,
"start": 21,
"tag": "NAME",
"value": "Brad Ackerman"
}
] | assets/coffee/reprocess.coffee | backerman/eveindy | 2 | # Copyright © 2014–6 Brad Ackerman.
#
# 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.
# Constants for this file.
reprocessOutput = [
"Tritanium"
"Pyerite"
"Mexallon"
"Isogen"
"Nocxium"
"Megacyte"
"Zydrine"
]
# Price calculation functions
buyCalc = (item, mult) ->
item?.bestBuy * mult
sellCalc = (item, mult) ->
item?.bestSell * mult
midpointCalc = (item, mult) ->
switch
when item?.bestBuy and item?.bestSell
Math.round((item?.bestBuy + item?.bestSell)/2 * mult * 100) / 100
when i?.bestBuy
Math.round(item.bestBuy * mult * 100) / 100
when i?.bestSell
Math.round(item.bestSell * mult * 100) / 100
else undefined
angular.module 'eveindy'
.controller 'ReprocessCtrl', [
'Server', 'Session', '$scope', 'numberFilter', '$timeout', '$sce',
class ReprocessCtrl
constructor: (
@Server, @Session, @$scope, @numberFilter, @$timeout, @$sce) ->
@standing = 0.0
@taxRate = 0.0
@scrapSkill = 0
@$scope.$on 'login-status', @_updateLoginStatus
@_updateLoginStatus()
@priceCalc = "midpoint"
@priceCalcFn = midpointCalc
@mineralValue = "imputed"
@reproMultiplier = 1.00
@imputed = {}
# We have the separate array because it makes things easier in the view.
@imputedArray = []
@Server.getReprocessPrices()
.then (response) =>
@jitaPrices = response.data
@recalculateMineralPrices()
_updateLoginStatus: () =>
@authenticated = @Session.authenticated
@chars = @Session.availableCharacters()
@selectedToon = @chars[0] if @authenticated
getStations: (search) ->
@Server.getAutocomplete(search)
.then (response) =>
((i) =>
i.class="security-" + switch
when i.security >= 0.5 then "high"
when i.security > 0.0 then "low"
else "null"
# Server uses 0..1; we use 0..100.
# FIXME: Converted both here (autocomplete) and on server
# (reprocess). Pick one.
i.name = @$sce.trustAsHtml i.name
i.constellation = @$sce.trustAsHtml i.constellation
i.region = @$sce.trustAsHtml i.region
i.reprocessingEfficiency *= 100
i
)(item) for item in response.data
locationSelected: (loc) ->
@corporationName = loc.owner
@stationID = loc.id
@stationOwnerID = loc.ownerID
@stationType = if loc.isOutpost then "player" else "npc"
@reprocessingEfficiency = loc.reprocessingEfficiency
@characterSelected()
# Character selection has changed.
characterSelected: () ->
id = @selectedToon.id
@scrapSkill = @selectedToon.skills.filter( (s) ->
s.name is "Scrapmetal Processing"
)?[0]?.level || 0
if @stationType is "npc"
@Server.getEffectiveStandings id, @stationOwnerID
.then (response) =>
@standing = response.data.standing
@updateTaxRate()
else
# Taxes at outposts are not available from the public API, so guess.
@standing = 0.00
@updateTaxRate()
# Update mineral value calculation method.
updatePriceCalc: () ->
@priceCalcFn = switch @priceCalc
when 'midpoint' then midpointCalc
when 'buy' then buyCalc
when 'sell' then sellCalc
else midpointCalc # default if bad data
@recalculateMineralPrices()
# Do the recalculation of imputed reprocessing value.
recalculateMineralPrices: () ->
@imputed = {}
@imputedArray = []
for name, item of @jitaPrices
newPrice = @priceCalcFn item, @reproMultiplier
@imputed[name] = newPrice
@imputedArray.push {name: name, price: newPrice}
# Update reprocessing values if we have those results yet.
if @reprocessingOutput
@updateReprocessedValues(@reprocessingOutput)
submitPaste: ->
@Server.parsePastebin(@pastebin)
.then (response) =>
# FIXME: Transition service in ui-bootstrap triggering $digest
# error.
@hidePasteInput = true
@$timeout (() => @inventory = response.data), 0, false
# flag to display spinner
@searchingMarket = true
# Get market prices
@Server.searchStationMarket(@stationID, response.data)
.then (response) =>
@searchingMarket = false
# Update items with the best buy order price
do (parse = (i) =>
result = response.data[i.Item.Name]
if result and result.bestBuy > 0
bi = result.buyInfo
i.buyPrice = result.bestBuy * i.Quantity
i.buyInfo = @$sce.trustAsHtml "<table class=\"orderinfo\">
<tr>
<th>\# units:</th>
<td>#{bi.quantity}</td>
</tr>
<tr>
<th>Min. qty.:</th>
<td>#{bi.minQuantity}</td>
</tr>
<tr>
<th>Price ea.:</th>
<td>#{@numberFilter(result.bestBuy, 2)} ISK</td>
</tr>
<tr>
<th>
Location:</th>
<td>
#{bi.station.name} (#{bi.within})</td>
</tr>
</table>"
else
i.noSale = true
i.buyPrice = 0.0) =>
parse item for item in @inventory
# Get reprocessing value
@Server.reprocessItems \
@reprocessingEfficiency, @taxRate, @scrapSkill, response.data
.then (response) =>
@reprocessingOutput = response.data
@updateReprocessedValues(@reprocessingOutput)
clearInventory: () ->
@hidePasteInput = false
@pastebin = ""
@inventory = []
updateReprocessedValues: (response) ->
for item in @inventory
result = response.items[item.Item.Name]
item.reproValue = 0
if result?.length > 0
for m in result
imputedCost = @imputed[m.Item.Name]
if !imputedCost
imputedCost = \
@priceCalcFn response.prices[m.Item.Name], @reproMultiplier
item.reproValue += m.Quantity * imputedCost
else
item.noReprocess = true
formatPrice: (item) ->
switch
when item.noSale then "-"
when item.buyPrice > 0 then @numberFilter(item.buyPrice, 2)
else "-"
formatRepro: (item) ->
switch
when item.noReprocess then "-"
when item.reproValue > 0 then @numberFilter(item.reproValue, 2)
else "-"
# updateTaxRate sets the tax rate based on the user's standing with
# a station's NPC corporation owners.
updateTaxRate: ->
@taxRate = Math.max(0.0, 5.0-0.75*@standing)
]
| 15185 | # Copyright © 2014–6 <NAME>.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Constants for this file.
reprocessOutput = [
"Tritanium"
"Pyerite"
"Mexallon"
"Isogen"
"Nocxium"
"Megacyte"
"Zydrine"
]
# Price calculation functions
buyCalc = (item, mult) ->
item?.bestBuy * mult
sellCalc = (item, mult) ->
item?.bestSell * mult
midpointCalc = (item, mult) ->
switch
when item?.bestBuy and item?.bestSell
Math.round((item?.bestBuy + item?.bestSell)/2 * mult * 100) / 100
when i?.bestBuy
Math.round(item.bestBuy * mult * 100) / 100
when i?.bestSell
Math.round(item.bestSell * mult * 100) / 100
else undefined
angular.module 'eveindy'
.controller 'ReprocessCtrl', [
'Server', 'Session', '$scope', 'numberFilter', '$timeout', '$sce',
class ReprocessCtrl
constructor: (
@Server, @Session, @$scope, @numberFilter, @$timeout, @$sce) ->
@standing = 0.0
@taxRate = 0.0
@scrapSkill = 0
@$scope.$on 'login-status', @_updateLoginStatus
@_updateLoginStatus()
@priceCalc = "midpoint"
@priceCalcFn = midpointCalc
@mineralValue = "imputed"
@reproMultiplier = 1.00
@imputed = {}
# We have the separate array because it makes things easier in the view.
@imputedArray = []
@Server.getReprocessPrices()
.then (response) =>
@jitaPrices = response.data
@recalculateMineralPrices()
_updateLoginStatus: () =>
@authenticated = @Session.authenticated
@chars = @Session.availableCharacters()
@selectedToon = @chars[0] if @authenticated
getStations: (search) ->
@Server.getAutocomplete(search)
.then (response) =>
((i) =>
i.class="security-" + switch
when i.security >= 0.5 then "high"
when i.security > 0.0 then "low"
else "null"
# Server uses 0..1; we use 0..100.
# FIXME: Converted both here (autocomplete) and on server
# (reprocess). Pick one.
i.name = @$sce.trustAsHtml i.name
i.constellation = @$sce.trustAsHtml i.constellation
i.region = @$sce.trustAsHtml i.region
i.reprocessingEfficiency *= 100
i
)(item) for item in response.data
locationSelected: (loc) ->
@corporationName = loc.owner
@stationID = loc.id
@stationOwnerID = loc.ownerID
@stationType = if loc.isOutpost then "player" else "npc"
@reprocessingEfficiency = loc.reprocessingEfficiency
@characterSelected()
# Character selection has changed.
characterSelected: () ->
id = @selectedToon.id
@scrapSkill = @selectedToon.skills.filter( (s) ->
s.name is "Scrapmetal Processing"
)?[0]?.level || 0
if @stationType is "npc"
@Server.getEffectiveStandings id, @stationOwnerID
.then (response) =>
@standing = response.data.standing
@updateTaxRate()
else
# Taxes at outposts are not available from the public API, so guess.
@standing = 0.00
@updateTaxRate()
# Update mineral value calculation method.
updatePriceCalc: () ->
@priceCalcFn = switch @priceCalc
when 'midpoint' then midpointCalc
when 'buy' then buyCalc
when 'sell' then sellCalc
else midpointCalc # default if bad data
@recalculateMineralPrices()
# Do the recalculation of imputed reprocessing value.
recalculateMineralPrices: () ->
@imputed = {}
@imputedArray = []
for name, item of @jitaPrices
newPrice = @priceCalcFn item, @reproMultiplier
@imputed[name] = newPrice
@imputedArray.push {name: name, price: newPrice}
# Update reprocessing values if we have those results yet.
if @reprocessingOutput
@updateReprocessedValues(@reprocessingOutput)
submitPaste: ->
@Server.parsePastebin(@pastebin)
.then (response) =>
# FIXME: Transition service in ui-bootstrap triggering $digest
# error.
@hidePasteInput = true
@$timeout (() => @inventory = response.data), 0, false
# flag to display spinner
@searchingMarket = true
# Get market prices
@Server.searchStationMarket(@stationID, response.data)
.then (response) =>
@searchingMarket = false
# Update items with the best buy order price
do (parse = (i) =>
result = response.data[i.Item.Name]
if result and result.bestBuy > 0
bi = result.buyInfo
i.buyPrice = result.bestBuy * i.Quantity
i.buyInfo = @$sce.trustAsHtml "<table class=\"orderinfo\">
<tr>
<th>\# units:</th>
<td>#{bi.quantity}</td>
</tr>
<tr>
<th>Min. qty.:</th>
<td>#{bi.minQuantity}</td>
</tr>
<tr>
<th>Price ea.:</th>
<td>#{@numberFilter(result.bestBuy, 2)} ISK</td>
</tr>
<tr>
<th>
Location:</th>
<td>
#{bi.station.name} (#{bi.within})</td>
</tr>
</table>"
else
i.noSale = true
i.buyPrice = 0.0) =>
parse item for item in @inventory
# Get reprocessing value
@Server.reprocessItems \
@reprocessingEfficiency, @taxRate, @scrapSkill, response.data
.then (response) =>
@reprocessingOutput = response.data
@updateReprocessedValues(@reprocessingOutput)
clearInventory: () ->
@hidePasteInput = false
@pastebin = ""
@inventory = []
updateReprocessedValues: (response) ->
for item in @inventory
result = response.items[item.Item.Name]
item.reproValue = 0
if result?.length > 0
for m in result
imputedCost = @imputed[m.Item.Name]
if !imputedCost
imputedCost = \
@priceCalcFn response.prices[m.Item.Name], @reproMultiplier
item.reproValue += m.Quantity * imputedCost
else
item.noReprocess = true
formatPrice: (item) ->
switch
when item.noSale then "-"
when item.buyPrice > 0 then @numberFilter(item.buyPrice, 2)
else "-"
formatRepro: (item) ->
switch
when item.noReprocess then "-"
when item.reproValue > 0 then @numberFilter(item.reproValue, 2)
else "-"
# updateTaxRate sets the tax rate based on the user's standing with
# a station's NPC corporation owners.
updateTaxRate: ->
@taxRate = Math.max(0.0, 5.0-0.75*@standing)
]
| true | # Copyright © 2014–6 PI:NAME:<NAME>END_PI.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Constants for this file.
reprocessOutput = [
"Tritanium"
"Pyerite"
"Mexallon"
"Isogen"
"Nocxium"
"Megacyte"
"Zydrine"
]
# Price calculation functions
buyCalc = (item, mult) ->
item?.bestBuy * mult
sellCalc = (item, mult) ->
item?.bestSell * mult
midpointCalc = (item, mult) ->
switch
when item?.bestBuy and item?.bestSell
Math.round((item?.bestBuy + item?.bestSell)/2 * mult * 100) / 100
when i?.bestBuy
Math.round(item.bestBuy * mult * 100) / 100
when i?.bestSell
Math.round(item.bestSell * mult * 100) / 100
else undefined
angular.module 'eveindy'
.controller 'ReprocessCtrl', [
'Server', 'Session', '$scope', 'numberFilter', '$timeout', '$sce',
class ReprocessCtrl
constructor: (
@Server, @Session, @$scope, @numberFilter, @$timeout, @$sce) ->
@standing = 0.0
@taxRate = 0.0
@scrapSkill = 0
@$scope.$on 'login-status', @_updateLoginStatus
@_updateLoginStatus()
@priceCalc = "midpoint"
@priceCalcFn = midpointCalc
@mineralValue = "imputed"
@reproMultiplier = 1.00
@imputed = {}
# We have the separate array because it makes things easier in the view.
@imputedArray = []
@Server.getReprocessPrices()
.then (response) =>
@jitaPrices = response.data
@recalculateMineralPrices()
_updateLoginStatus: () =>
@authenticated = @Session.authenticated
@chars = @Session.availableCharacters()
@selectedToon = @chars[0] if @authenticated
getStations: (search) ->
@Server.getAutocomplete(search)
.then (response) =>
((i) =>
i.class="security-" + switch
when i.security >= 0.5 then "high"
when i.security > 0.0 then "low"
else "null"
# Server uses 0..1; we use 0..100.
# FIXME: Converted both here (autocomplete) and on server
# (reprocess). Pick one.
i.name = @$sce.trustAsHtml i.name
i.constellation = @$sce.trustAsHtml i.constellation
i.region = @$sce.trustAsHtml i.region
i.reprocessingEfficiency *= 100
i
)(item) for item in response.data
locationSelected: (loc) ->
@corporationName = loc.owner
@stationID = loc.id
@stationOwnerID = loc.ownerID
@stationType = if loc.isOutpost then "player" else "npc"
@reprocessingEfficiency = loc.reprocessingEfficiency
@characterSelected()
# Character selection has changed.
characterSelected: () ->
id = @selectedToon.id
@scrapSkill = @selectedToon.skills.filter( (s) ->
s.name is "Scrapmetal Processing"
)?[0]?.level || 0
if @stationType is "npc"
@Server.getEffectiveStandings id, @stationOwnerID
.then (response) =>
@standing = response.data.standing
@updateTaxRate()
else
# Taxes at outposts are not available from the public API, so guess.
@standing = 0.00
@updateTaxRate()
# Update mineral value calculation method.
updatePriceCalc: () ->
@priceCalcFn = switch @priceCalc
when 'midpoint' then midpointCalc
when 'buy' then buyCalc
when 'sell' then sellCalc
else midpointCalc # default if bad data
@recalculateMineralPrices()
# Do the recalculation of imputed reprocessing value.
recalculateMineralPrices: () ->
@imputed = {}
@imputedArray = []
for name, item of @jitaPrices
newPrice = @priceCalcFn item, @reproMultiplier
@imputed[name] = newPrice
@imputedArray.push {name: name, price: newPrice}
# Update reprocessing values if we have those results yet.
if @reprocessingOutput
@updateReprocessedValues(@reprocessingOutput)
submitPaste: ->
@Server.parsePastebin(@pastebin)
.then (response) =>
# FIXME: Transition service in ui-bootstrap triggering $digest
# error.
@hidePasteInput = true
@$timeout (() => @inventory = response.data), 0, false
# flag to display spinner
@searchingMarket = true
# Get market prices
@Server.searchStationMarket(@stationID, response.data)
.then (response) =>
@searchingMarket = false
# Update items with the best buy order price
do (parse = (i) =>
result = response.data[i.Item.Name]
if result and result.bestBuy > 0
bi = result.buyInfo
i.buyPrice = result.bestBuy * i.Quantity
i.buyInfo = @$sce.trustAsHtml "<table class=\"orderinfo\">
<tr>
<th>\# units:</th>
<td>#{bi.quantity}</td>
</tr>
<tr>
<th>Min. qty.:</th>
<td>#{bi.minQuantity}</td>
</tr>
<tr>
<th>Price ea.:</th>
<td>#{@numberFilter(result.bestBuy, 2)} ISK</td>
</tr>
<tr>
<th>
Location:</th>
<td>
#{bi.station.name} (#{bi.within})</td>
</tr>
</table>"
else
i.noSale = true
i.buyPrice = 0.0) =>
parse item for item in @inventory
# Get reprocessing value
@Server.reprocessItems \
@reprocessingEfficiency, @taxRate, @scrapSkill, response.data
.then (response) =>
@reprocessingOutput = response.data
@updateReprocessedValues(@reprocessingOutput)
clearInventory: () ->
@hidePasteInput = false
@pastebin = ""
@inventory = []
updateReprocessedValues: (response) ->
for item in @inventory
result = response.items[item.Item.Name]
item.reproValue = 0
if result?.length > 0
for m in result
imputedCost = @imputed[m.Item.Name]
if !imputedCost
imputedCost = \
@priceCalcFn response.prices[m.Item.Name], @reproMultiplier
item.reproValue += m.Quantity * imputedCost
else
item.noReprocess = true
formatPrice: (item) ->
switch
when item.noSale then "-"
when item.buyPrice > 0 then @numberFilter(item.buyPrice, 2)
else "-"
formatRepro: (item) ->
switch
when item.noReprocess then "-"
when item.reproValue > 0 then @numberFilter(item.reproValue, 2)
else "-"
# updateTaxRate sets the tax rate based on the user's standing with
# a station's NPC corporation owners.
updateTaxRate: ->
@taxRate = Math.max(0.0, 5.0-0.75*@standing)
]
|
[
{
"context": "rops.task.tool_config.options\n answer._key ?= Math.random()\n checked = answer.value is @props.annotation",
"end": 2223,
"score": 0.9781932234764099,
"start": 2210,
"tag": "KEY",
"value": "Math.random()"
}
] | app/assets/javascripts/components/core-tools/pick-one.cjsx | ogugugugugua/PRED-Crowdsourcing-2020 | 88 | React = require 'react'
GenericTask = require './generic'
LabeledRadioButton = require 'components/buttons/labeled-radio-button'
# Markdown = require '../../components/markdown'
NOOP = Function.prototype
# Summary = React.createClass
# displayName: 'SingleChoiceSummary'
# getDefaultProps: ->
# task: null
# annotation: null
# expanded: false
# getInitialState: ->
# expanded: @props.expanded
# render: ->
# <div className="classification-task-summary">
# <div className="question">
# {@props.task.question}
# {if @state.expanded
# <button type="button" className="toggle-more" onClick={@setState.bind this, expanded: false, null}>Less</button>
# else
# <button type="button" className="toggle-more" onClick={@setState.bind this, expanded: true, null}>More</button>}
# </div>
# <div className="answers">
# {if @state.expanded
# for answer, i in @props.task.answers
# answer._key ?= Math.random()
# <div key={answer._key} className="answer">
# {if i is @props.annotation.value
# <i className="fa fa-check-circle-o fa-fw"></i>
# else
# <i className="fa fa-circle-o fa-fw"></i>}
# {@props.task.answers[i].label}
# </div>
# else if @props.annotation.value?
# <div className="answer">
# <i className="fa fa-check-circle-o fa-fw"></i>
# {@props.task.answers[@props.annotation.value].label}
# </div>
# else
# <div className="answer">No answer</div>}
# </div>
# </div>
module.exports = React.createClass
displayName: 'SingleChoiceTask'
statics:
# Summary: Summary # don't use Summary (yet?)
getDefaultAnnotation: ->
value: null
getDefaultProps: ->
task: null
annotation: null
onChange: NOOP
propTypes: ->
task: React.PropTypes.object.isRequired
annotation: React.PropTypes.object.isRequired
onChange: React.PropTypes.func.isRequired
render: ->
answers = for answer in @props.task.tool_config.options
answer._key ?= Math.random()
checked = answer.value is @props.annotation.value
classes = ['minor-button']
classes.push 'active' if checked
<LabeledRadioButton key={answer._key} classes={classes.join ' '} value={answer.value} checked={checked} onChange={@handleChange.bind this, answer.value} label={answer.label} />
<GenericTask ref="inputs" {...@props} question={@props.task.instruction} answers={answers} />
handleChange: (index, e) ->
if e.target.checked
@props.onChange({
value: e.target.value
})
@forceUpdate() # update the radiobuttons after selection
window.React = React
| 10003 | React = require 'react'
GenericTask = require './generic'
LabeledRadioButton = require 'components/buttons/labeled-radio-button'
# Markdown = require '../../components/markdown'
NOOP = Function.prototype
# Summary = React.createClass
# displayName: 'SingleChoiceSummary'
# getDefaultProps: ->
# task: null
# annotation: null
# expanded: false
# getInitialState: ->
# expanded: @props.expanded
# render: ->
# <div className="classification-task-summary">
# <div className="question">
# {@props.task.question}
# {if @state.expanded
# <button type="button" className="toggle-more" onClick={@setState.bind this, expanded: false, null}>Less</button>
# else
# <button type="button" className="toggle-more" onClick={@setState.bind this, expanded: true, null}>More</button>}
# </div>
# <div className="answers">
# {if @state.expanded
# for answer, i in @props.task.answers
# answer._key ?= Math.random()
# <div key={answer._key} className="answer">
# {if i is @props.annotation.value
# <i className="fa fa-check-circle-o fa-fw"></i>
# else
# <i className="fa fa-circle-o fa-fw"></i>}
# {@props.task.answers[i].label}
# </div>
# else if @props.annotation.value?
# <div className="answer">
# <i className="fa fa-check-circle-o fa-fw"></i>
# {@props.task.answers[@props.annotation.value].label}
# </div>
# else
# <div className="answer">No answer</div>}
# </div>
# </div>
module.exports = React.createClass
displayName: 'SingleChoiceTask'
statics:
# Summary: Summary # don't use Summary (yet?)
getDefaultAnnotation: ->
value: null
getDefaultProps: ->
task: null
annotation: null
onChange: NOOP
propTypes: ->
task: React.PropTypes.object.isRequired
annotation: React.PropTypes.object.isRequired
onChange: React.PropTypes.func.isRequired
render: ->
answers = for answer in @props.task.tool_config.options
answer._key ?= <KEY>
checked = answer.value is @props.annotation.value
classes = ['minor-button']
classes.push 'active' if checked
<LabeledRadioButton key={answer._key} classes={classes.join ' '} value={answer.value} checked={checked} onChange={@handleChange.bind this, answer.value} label={answer.label} />
<GenericTask ref="inputs" {...@props} question={@props.task.instruction} answers={answers} />
handleChange: (index, e) ->
if e.target.checked
@props.onChange({
value: e.target.value
})
@forceUpdate() # update the radiobuttons after selection
window.React = React
| true | React = require 'react'
GenericTask = require './generic'
LabeledRadioButton = require 'components/buttons/labeled-radio-button'
# Markdown = require '../../components/markdown'
NOOP = Function.prototype
# Summary = React.createClass
# displayName: 'SingleChoiceSummary'
# getDefaultProps: ->
# task: null
# annotation: null
# expanded: false
# getInitialState: ->
# expanded: @props.expanded
# render: ->
# <div className="classification-task-summary">
# <div className="question">
# {@props.task.question}
# {if @state.expanded
# <button type="button" className="toggle-more" onClick={@setState.bind this, expanded: false, null}>Less</button>
# else
# <button type="button" className="toggle-more" onClick={@setState.bind this, expanded: true, null}>More</button>}
# </div>
# <div className="answers">
# {if @state.expanded
# for answer, i in @props.task.answers
# answer._key ?= Math.random()
# <div key={answer._key} className="answer">
# {if i is @props.annotation.value
# <i className="fa fa-check-circle-o fa-fw"></i>
# else
# <i className="fa fa-circle-o fa-fw"></i>}
# {@props.task.answers[i].label}
# </div>
# else if @props.annotation.value?
# <div className="answer">
# <i className="fa fa-check-circle-o fa-fw"></i>
# {@props.task.answers[@props.annotation.value].label}
# </div>
# else
# <div className="answer">No answer</div>}
# </div>
# </div>
module.exports = React.createClass
displayName: 'SingleChoiceTask'
statics:
# Summary: Summary # don't use Summary (yet?)
getDefaultAnnotation: ->
value: null
getDefaultProps: ->
task: null
annotation: null
onChange: NOOP
propTypes: ->
task: React.PropTypes.object.isRequired
annotation: React.PropTypes.object.isRequired
onChange: React.PropTypes.func.isRequired
render: ->
answers = for answer in @props.task.tool_config.options
answer._key ?= PI:KEY:<KEY>END_PI
checked = answer.value is @props.annotation.value
classes = ['minor-button']
classes.push 'active' if checked
<LabeledRadioButton key={answer._key} classes={classes.join ' '} value={answer.value} checked={checked} onChange={@handleChange.bind this, answer.value} label={answer.label} />
<GenericTask ref="inputs" {...@props} question={@props.task.instruction} answers={answers} />
handleChange: (index, e) ->
if e.target.checked
@props.onChange({
value: e.target.value
})
@forceUpdate() # update the radiobuttons after selection
window.React = React
|
[
{
"context": "alForage.bind $scope, {\n key: 'selectedCrunchService'\n defaultValue: configService.",
"end": 650,
"score": 0.9951270818710327,
"start": 629,
"tag": "KEY",
"value": "selectedCrunchService"
}
] | web/app/scripts/directives/crunchEditor.coffee | ExpediaGroup/parsec | 1 | #
# This directive generates a Crunch editor and result output
#
Parsec.Directives.directive 'crunchEditor',
($compile, crunchService, configService) ->
{
restrict: 'EA'
scope: {
query: '='
showPerformance: '@'
}
templateUrl: '/partials/crunchEditor.html'
controller: ($scope, $localForage, configService) ->
$scope.serviceList = configService.crunch.serviceList
$localForage.removeItem $scope, 'selectedCrunchService'
$localForage.bind $scope, {
key: 'selectedCrunchService'
defaultValue: configService.crunch.serviceList[0]
}
$scope._showPerformance = true unless $scope.showPerformance == 'false'
# Settings for the Query Editor
$scope.aceOptions =
useWrapMode : true
showGutter: true
showPrintMargin: false
mode: 'crunch'
theme: 'dawn'
onLoad: (editor) ->
editor.navigateFileEnd()
editor.focus()
editor.setOption("maxLines", 48)
editor.setOption("minLines", 10)
editor.$blockScrolling = Infinity
editor.commands.addCommand {
name: 'executeQuery',
bindKey:
win: 'Ctrl-E',
mac: 'Command-E',
sender: 'editor|cli'
exec: (env, args, request) ->
$scope.execute()
}
$scope.result = null
$scope.execute = ->
# Update tab settings
$scope.query.isExecuting = true
$scope.result = null
p = crunchService.executeQuery $scope.query.text, $scope.selectedCrunchService.url
p.then (result) ->
$scope.query.isExecuting = false
$scope.query.isFresh = true
$scope.result = result
p.catch (error) ->
$scope.query.isExecuting = false
console.log(error)
$scope.$on 'executeCrunchNow', -> $scope.execute()
}
| 97699 | #
# This directive generates a Crunch editor and result output
#
Parsec.Directives.directive 'crunchEditor',
($compile, crunchService, configService) ->
{
restrict: 'EA'
scope: {
query: '='
showPerformance: '@'
}
templateUrl: '/partials/crunchEditor.html'
controller: ($scope, $localForage, configService) ->
$scope.serviceList = configService.crunch.serviceList
$localForage.removeItem $scope, 'selectedCrunchService'
$localForage.bind $scope, {
key: '<KEY>'
defaultValue: configService.crunch.serviceList[0]
}
$scope._showPerformance = true unless $scope.showPerformance == 'false'
# Settings for the Query Editor
$scope.aceOptions =
useWrapMode : true
showGutter: true
showPrintMargin: false
mode: 'crunch'
theme: 'dawn'
onLoad: (editor) ->
editor.navigateFileEnd()
editor.focus()
editor.setOption("maxLines", 48)
editor.setOption("minLines", 10)
editor.$blockScrolling = Infinity
editor.commands.addCommand {
name: 'executeQuery',
bindKey:
win: 'Ctrl-E',
mac: 'Command-E',
sender: 'editor|cli'
exec: (env, args, request) ->
$scope.execute()
}
$scope.result = null
$scope.execute = ->
# Update tab settings
$scope.query.isExecuting = true
$scope.result = null
p = crunchService.executeQuery $scope.query.text, $scope.selectedCrunchService.url
p.then (result) ->
$scope.query.isExecuting = false
$scope.query.isFresh = true
$scope.result = result
p.catch (error) ->
$scope.query.isExecuting = false
console.log(error)
$scope.$on 'executeCrunchNow', -> $scope.execute()
}
| true | #
# This directive generates a Crunch editor and result output
#
Parsec.Directives.directive 'crunchEditor',
($compile, crunchService, configService) ->
{
restrict: 'EA'
scope: {
query: '='
showPerformance: '@'
}
templateUrl: '/partials/crunchEditor.html'
controller: ($scope, $localForage, configService) ->
$scope.serviceList = configService.crunch.serviceList
$localForage.removeItem $scope, 'selectedCrunchService'
$localForage.bind $scope, {
key: 'PI:KEY:<KEY>END_PI'
defaultValue: configService.crunch.serviceList[0]
}
$scope._showPerformance = true unless $scope.showPerformance == 'false'
# Settings for the Query Editor
$scope.aceOptions =
useWrapMode : true
showGutter: true
showPrintMargin: false
mode: 'crunch'
theme: 'dawn'
onLoad: (editor) ->
editor.navigateFileEnd()
editor.focus()
editor.setOption("maxLines", 48)
editor.setOption("minLines", 10)
editor.$blockScrolling = Infinity
editor.commands.addCommand {
name: 'executeQuery',
bindKey:
win: 'Ctrl-E',
mac: 'Command-E',
sender: 'editor|cli'
exec: (env, args, request) ->
$scope.execute()
}
$scope.result = null
$scope.execute = ->
# Update tab settings
$scope.query.isExecuting = true
$scope.result = null
p = crunchService.executeQuery $scope.query.text, $scope.selectedCrunchService.url
p.then (result) ->
$scope.query.isExecuting = false
$scope.query.isFresh = true
$scope.result = result
p.catch (error) ->
$scope.query.isExecuting = false
console.log(error)
$scope.$on 'executeCrunchNow', -> $scope.execute()
}
|
[
{
"context": "ubot yelp me thai near Palo Alto\n#\n#\n# Author:\n# Chris Streeter (streeter)\n#\n\nconsumer_key = process.env.HUBOT_YE",
"end": 1371,
"score": 0.9998523592948914,
"start": 1357,
"tag": "NAME",
"value": "Chris Streeter"
},
{
"context": " near Palo Alto\n#\n#\n# Autho... | src/scripts/yelp.coffee | Reelhouse/hubot-scripts | 1,450 | # Description:
# With the Yelp API v2.0, search for nearby restaurants.
#
# Dependencies:
# "yelp": "0.1.1"
#
# Configuration:
# HUBOT_YELP_CONSUMER_KEY
# HUBOT_YELP_CONSUMER_SECRET
# HUBOT_YELP_TOKEN
# HUBOT_YELP_TOKEN_SECRET
# HUBOT_YELP_SEARCH_ADDRESS
# HUBOT_YELP_SEARCH_RADIUS
# HUBOT_YELP_SORT
# HUBOT_YELP_DEFAULT_SUGGESTION
#
# Get your Yelp tokens at http://www.yelp.com/developers/getting_started/api_access
# The search address can be a full address, city, or zipcode
# The search radius should be specified in meters, it defaults to 600.
# The sort parameter can be best matched (0 - default), distance (1) or highest rated (2).
# See http://www.yelp.com/developers/documentation/v2/search_api#searchGP for
# more information about the search radius and sort.
#
# Commands:
# hubot what's (to eat)? for <query> near <place>?
# hubot what's (to eat)? for <query>?
# hubot where should (I|we|<person>) (eat|go for) <query> near <place>?
# hubot where should (I|we|<person>) (eat|go for) <query>?
# hubot yelp me <query> (near <place>)?
#
# Examples:
# hubot what's for lunch near Palo Alto
# hubot what's to eat for lunch
# hubot where should chris eat steak?
# hubot where should I go for thai near Palo Alto?
# hubot where should we eat
# hubot yelp me thai near Palo Alto
#
#
# Author:
# Chris Streeter (streeter)
#
consumer_key = process.env.HUBOT_YELP_CONSUMER_KEY
consumer_secret = process.env.HUBOT_YELP_CONSUMER_SECRET
token = process.env.HUBOT_YELP_TOKEN
token_secret = process.env.HUBOT_YELP_TOKEN_SECRET
# Default search parameters
start_address = process.env.HUBOT_YELP_SEARCH_ADDRESS or "Palo Alto"
radius = process.env.HUBOT_YELP_SEARCH_RADIUS or 600
sort = process.env.HUBOT_YELP_SORT or 0
default_suggestion = process.env.HUBOT_YELP_DEFAULT_SUGGESTION or "Chipotle"
trim_re = /^\s+|\s+$|[\.!\?]+$/g
# Create the API client
yelp = require("yelp").createClient consumer_key: consumer_key, consumer_secret: consumer_secret, token: token, token_secret: token_secret
lunchMe = (msg, query, random = true) ->
# Clean up the query
query = "food" if typeof query == "undefined"
query = query.replace(trim_re, '')
query = "food" if query == ""
# Extract a location from the query
split = query.split(/\snear\s/i)
query = split[0]
location = split[1]
location = start_address if (typeof location == "undefined" || location == "")
# Perform the search
#msg.send("Looking for #{query} around #{location}...")
yelp.search category_filter: "restaurants", term: query, radius_filter: radius, sort: sort, limit: 20, location: location, (error, data) ->
if error != null
return msg.send "There was an error searching for #{query}. Maybe try #{default_suggestion}?"
if data.total == 0
return msg.send "I couldn't find any #{query} for you. Maybe try #{default_suggestion}?"
if random
business = data.businesses[Math.floor(Math.random() * data.businesses.length)]
else
business = data.businesses[0]
msg.send("How about " + business.name + "? " + business.url)
module.exports = (robot) ->
robot.respond /where should \w+ (eat|go for)(.*)/i, (msg) ->
query = msg.match[2]
lunchMe msg, query
robot.respond /what\'?s( to eat)? for(.*)/i, (msg) ->
query = msg.match[2]
lunchMe msg, query
robot.respond /yelp me(.*)/i, (msg) ->
query = msg.match[1]
lunchMe msg, query, false
| 171120 | # Description:
# With the Yelp API v2.0, search for nearby restaurants.
#
# Dependencies:
# "yelp": "0.1.1"
#
# Configuration:
# HUBOT_YELP_CONSUMER_KEY
# HUBOT_YELP_CONSUMER_SECRET
# HUBOT_YELP_TOKEN
# HUBOT_YELP_TOKEN_SECRET
# HUBOT_YELP_SEARCH_ADDRESS
# HUBOT_YELP_SEARCH_RADIUS
# HUBOT_YELP_SORT
# HUBOT_YELP_DEFAULT_SUGGESTION
#
# Get your Yelp tokens at http://www.yelp.com/developers/getting_started/api_access
# The search address can be a full address, city, or zipcode
# The search radius should be specified in meters, it defaults to 600.
# The sort parameter can be best matched (0 - default), distance (1) or highest rated (2).
# See http://www.yelp.com/developers/documentation/v2/search_api#searchGP for
# more information about the search radius and sort.
#
# Commands:
# hubot what's (to eat)? for <query> near <place>?
# hubot what's (to eat)? for <query>?
# hubot where should (I|we|<person>) (eat|go for) <query> near <place>?
# hubot where should (I|we|<person>) (eat|go for) <query>?
# hubot yelp me <query> (near <place>)?
#
# Examples:
# hubot what's for lunch near Palo Alto
# hubot what's to eat for lunch
# hubot where should chris eat steak?
# hubot where should I go for thai near Palo Alto?
# hubot where should we eat
# hubot yelp me thai near Palo Alto
#
#
# Author:
# <NAME> (streeter)
#
consumer_key = process.env.HUBOT_YELP_CONSUMER_KEY
consumer_secret = process.env.HUBOT_YELP_CONSUMER_SECRET
token = process.env.HUBOT_YELP_TOKEN
token_secret = process.env.HUBOT_YELP_TOKEN_SECRET
# Default search parameters
start_address = process.env.HUBOT_YELP_SEARCH_ADDRESS or "Palo Alto"
radius = process.env.HUBOT_YELP_SEARCH_RADIUS or 600
sort = process.env.HUBOT_YELP_SORT or 0
default_suggestion = process.env.HUBOT_YELP_DEFAULT_SUGGESTION or "Chipotle"
trim_re = /^\s+|\s+$|[\.!\?]+$/g
# Create the API client
yelp = require("yelp").createClient consumer_key: consumer_key, consumer_secret: consumer_secret, token: token, token_secret: token_secret
lunchMe = (msg, query, random = true) ->
# Clean up the query
query = "food" if typeof query == "undefined"
query = query.replace(trim_re, '')
query = "food" if query == ""
# Extract a location from the query
split = query.split(/\snear\s/i)
query = split[0]
location = split[1]
location = start_address if (typeof location == "undefined" || location == "")
# Perform the search
#msg.send("Looking for #{query} around #{location}...")
yelp.search category_filter: "restaurants", term: query, radius_filter: radius, sort: sort, limit: 20, location: location, (error, data) ->
if error != null
return msg.send "There was an error searching for #{query}. Maybe try #{default_suggestion}?"
if data.total == 0
return msg.send "I couldn't find any #{query} for you. Maybe try #{default_suggestion}?"
if random
business = data.businesses[Math.floor(Math.random() * data.businesses.length)]
else
business = data.businesses[0]
msg.send("How about " + business.name + "? " + business.url)
module.exports = (robot) ->
robot.respond /where should \w+ (eat|go for)(.*)/i, (msg) ->
query = msg.match[2]
lunchMe msg, query
robot.respond /what\'?s( to eat)? for(.*)/i, (msg) ->
query = msg.match[2]
lunchMe msg, query
robot.respond /yelp me(.*)/i, (msg) ->
query = msg.match[1]
lunchMe msg, query, false
| true | # Description:
# With the Yelp API v2.0, search for nearby restaurants.
#
# Dependencies:
# "yelp": "0.1.1"
#
# Configuration:
# HUBOT_YELP_CONSUMER_KEY
# HUBOT_YELP_CONSUMER_SECRET
# HUBOT_YELP_TOKEN
# HUBOT_YELP_TOKEN_SECRET
# HUBOT_YELP_SEARCH_ADDRESS
# HUBOT_YELP_SEARCH_RADIUS
# HUBOT_YELP_SORT
# HUBOT_YELP_DEFAULT_SUGGESTION
#
# Get your Yelp tokens at http://www.yelp.com/developers/getting_started/api_access
# The search address can be a full address, city, or zipcode
# The search radius should be specified in meters, it defaults to 600.
# The sort parameter can be best matched (0 - default), distance (1) or highest rated (2).
# See http://www.yelp.com/developers/documentation/v2/search_api#searchGP for
# more information about the search radius and sort.
#
# Commands:
# hubot what's (to eat)? for <query> near <place>?
# hubot what's (to eat)? for <query>?
# hubot where should (I|we|<person>) (eat|go for) <query> near <place>?
# hubot where should (I|we|<person>) (eat|go for) <query>?
# hubot yelp me <query> (near <place>)?
#
# Examples:
# hubot what's for lunch near Palo Alto
# hubot what's to eat for lunch
# hubot where should chris eat steak?
# hubot where should I go for thai near Palo Alto?
# hubot where should we eat
# hubot yelp me thai near Palo Alto
#
#
# Author:
# PI:NAME:<NAME>END_PI (streeter)
#
consumer_key = process.env.HUBOT_YELP_CONSUMER_KEY
consumer_secret = process.env.HUBOT_YELP_CONSUMER_SECRET
token = process.env.HUBOT_YELP_TOKEN
token_secret = process.env.HUBOT_YELP_TOKEN_SECRET
# Default search parameters
start_address = process.env.HUBOT_YELP_SEARCH_ADDRESS or "Palo Alto"
radius = process.env.HUBOT_YELP_SEARCH_RADIUS or 600
sort = process.env.HUBOT_YELP_SORT or 0
default_suggestion = process.env.HUBOT_YELP_DEFAULT_SUGGESTION or "Chipotle"
trim_re = /^\s+|\s+$|[\.!\?]+$/g
# Create the API client
yelp = require("yelp").createClient consumer_key: consumer_key, consumer_secret: consumer_secret, token: token, token_secret: token_secret
lunchMe = (msg, query, random = true) ->
# Clean up the query
query = "food" if typeof query == "undefined"
query = query.replace(trim_re, '')
query = "food" if query == ""
# Extract a location from the query
split = query.split(/\snear\s/i)
query = split[0]
location = split[1]
location = start_address if (typeof location == "undefined" || location == "")
# Perform the search
#msg.send("Looking for #{query} around #{location}...")
yelp.search category_filter: "restaurants", term: query, radius_filter: radius, sort: sort, limit: 20, location: location, (error, data) ->
if error != null
return msg.send "There was an error searching for #{query}. Maybe try #{default_suggestion}?"
if data.total == 0
return msg.send "I couldn't find any #{query} for you. Maybe try #{default_suggestion}?"
if random
business = data.businesses[Math.floor(Math.random() * data.businesses.length)]
else
business = data.businesses[0]
msg.send("How about " + business.name + "? " + business.url)
module.exports = (robot) ->
robot.respond /where should \w+ (eat|go for)(.*)/i, (msg) ->
query = msg.match[2]
lunchMe msg, query
robot.respond /what\'?s( to eat)? for(.*)/i, (msg) ->
query = msg.match[2]
lunchMe msg, query
robot.respond /yelp me(.*)/i, (msg) ->
query = msg.match[1]
lunchMe msg, query, false
|
[
{
"context": "n threejs so just copy past your shadertoy :)\n# By David Ronai / Makio64 / makiopolis.com\n#\n\nStage = require(\"ma",
"end": 177,
"score": 0.9998680949211121,
"start": 166,
"tag": "NAME",
"value": "David Ronai"
},
{
"context": "ust copy past your shadertoy :)\n# By Da... | src/coffee/makio/3d/FragmentPlane.coffee | Makio64/pizzaparty_vj | 1 | #
# Plane with a fragment shader, based on Shadertoy Model
# It also replace the shadertoy stuffs by the one need in threejs so just copy past your shadertoy :)
# By David Ronai / Makio64 / makiopolis.com
#
Stage = require("makio/core/Stage")
class FragmentPlane extends THREE.Mesh
constructor:(fs)->
material = @createMaterial(fs)
geometry = @createGeometry()
super(geometry,material)
Stage.onUpdate.add(@update)
return
update:(dt)=>
@uniforms.iGlobalTime.value += dt/1000
return
createMaterial:(fs)->
@uniforms = {
iGlobalTime: { type: "f", value: 0.0 },
iResolution: { type: "v2", value: new THREE.Vector2(window.innerWidth,window.innerHeight) }
}
vs = "precision highp float; attribute vec3 position;attribute vec3 previous;attribute vec3 next;attribute float side;attribute float width;attribute vec2 uv;"
vs += "uniform mat4 modelMatrix; uniform mat4 modelViewMatrix; uniform mat4 projectionMatrix; uniform mat4 viewMatrix; uniform mat3 normalMatrix; uniform vec3 cameraPosition;"
vs += "void main() { gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );}"
material = new THREE.RawShaderMaterial(
uniforms: @uniforms
fragmentShader: @addUniforms(fs)
vertexShader: vs
)
return material
addUniforms:(fs)->
fs = fs.replace("void mainImage( out vec4 fragColor, in vec2 fragCoord )\n{","void main(){ vec2 fragCoord = gl_FragCoord.xy; ")
fs = fs.replace("fragColor","gl_FragColor")
console.log(fs)
return "precision highp float; uniform vec2 iResolution;\nuniform float iGlobalTime;\n" + fs
createGeometry:()->
geometry = new THREE.PlaneGeometry(100,5)
return geometry
dispose:()->
Stage3d.remove(@)
Stage.onUpdate.remove(@update)
@geometry.dispose()
@material.dispose()
return
module.exports = FragmentPlane
| 115434 | #
# Plane with a fragment shader, based on Shadertoy Model
# It also replace the shadertoy stuffs by the one need in threejs so just copy past your shadertoy :)
# By <NAME> / Makio64 / <EMAIL>
#
Stage = require("makio/core/Stage")
class FragmentPlane extends THREE.Mesh
constructor:(fs)->
material = @createMaterial(fs)
geometry = @createGeometry()
super(geometry,material)
Stage.onUpdate.add(@update)
return
update:(dt)=>
@uniforms.iGlobalTime.value += dt/1000
return
createMaterial:(fs)->
@uniforms = {
iGlobalTime: { type: "f", value: 0.0 },
iResolution: { type: "v2", value: new THREE.Vector2(window.innerWidth,window.innerHeight) }
}
vs = "precision highp float; attribute vec3 position;attribute vec3 previous;attribute vec3 next;attribute float side;attribute float width;attribute vec2 uv;"
vs += "uniform mat4 modelMatrix; uniform mat4 modelViewMatrix; uniform mat4 projectionMatrix; uniform mat4 viewMatrix; uniform mat3 normalMatrix; uniform vec3 cameraPosition;"
vs += "void main() { gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );}"
material = new THREE.RawShaderMaterial(
uniforms: @uniforms
fragmentShader: @addUniforms(fs)
vertexShader: vs
)
return material
addUniforms:(fs)->
fs = fs.replace("void mainImage( out vec4 fragColor, in vec2 fragCoord )\n{","void main(){ vec2 fragCoord = gl_FragCoord.xy; ")
fs = fs.replace("fragColor","gl_FragColor")
console.log(fs)
return "precision highp float; uniform vec2 iResolution;\nuniform float iGlobalTime;\n" + fs
createGeometry:()->
geometry = new THREE.PlaneGeometry(100,5)
return geometry
dispose:()->
Stage3d.remove(@)
Stage.onUpdate.remove(@update)
@geometry.dispose()
@material.dispose()
return
module.exports = FragmentPlane
| true | #
# Plane with a fragment shader, based on Shadertoy Model
# It also replace the shadertoy stuffs by the one need in threejs so just copy past your shadertoy :)
# By PI:NAME:<NAME>END_PI / Makio64 / PI:EMAIL:<EMAIL>END_PI
#
Stage = require("makio/core/Stage")
class FragmentPlane extends THREE.Mesh
constructor:(fs)->
material = @createMaterial(fs)
geometry = @createGeometry()
super(geometry,material)
Stage.onUpdate.add(@update)
return
update:(dt)=>
@uniforms.iGlobalTime.value += dt/1000
return
createMaterial:(fs)->
@uniforms = {
iGlobalTime: { type: "f", value: 0.0 },
iResolution: { type: "v2", value: new THREE.Vector2(window.innerWidth,window.innerHeight) }
}
vs = "precision highp float; attribute vec3 position;attribute vec3 previous;attribute vec3 next;attribute float side;attribute float width;attribute vec2 uv;"
vs += "uniform mat4 modelMatrix; uniform mat4 modelViewMatrix; uniform mat4 projectionMatrix; uniform mat4 viewMatrix; uniform mat3 normalMatrix; uniform vec3 cameraPosition;"
vs += "void main() { gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );}"
material = new THREE.RawShaderMaterial(
uniforms: @uniforms
fragmentShader: @addUniforms(fs)
vertexShader: vs
)
return material
addUniforms:(fs)->
fs = fs.replace("void mainImage( out vec4 fragColor, in vec2 fragCoord )\n{","void main(){ vec2 fragCoord = gl_FragCoord.xy; ")
fs = fs.replace("fragColor","gl_FragColor")
console.log(fs)
return "precision highp float; uniform vec2 iResolution;\nuniform float iGlobalTime;\n" + fs
createGeometry:()->
geometry = new THREE.PlaneGeometry(100,5)
return geometry
dispose:()->
Stage3d.remove(@)
Stage.onUpdate.remove(@update)
@geometry.dispose()
@material.dispose()
return
module.exports = FragmentPlane
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.