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": "ове\"\nPAGES: \"Страници\"\nPOSTS: \"Постове\"\nAUTHORS: \"Автори\"\nSEARCH: \"Търси\"\nSEARCH_START: \"Type a keyword\"\nS",
"end": 372,
"score": 0.9997928142547607,
"start": 366,
"tag": "NAME",
"value": "Автори"
},
{
"context": ": \"Страници\"\nTITLE_POSTS: \"Постове\... | src/i18n/bg.cson | ferromariano/Hybrid-2.0 | 1 | PULL_TO_REFRESH: "Дръпни за рефреш!"
RETRY: "Отново"
CANCEL: "Отказ"
SUBMIT: "Изпращане"
BACK: "Назад"
ERROR: "Something wrong happened, please try again."
ATTEMPT_TO_CONNECT: "Attempt to connect {{attempt}} of {{attemptMax}}."
OK: "Ок"
YES: "Да"
NO: "Не"
EMPTY_LIST: "There is nothing here!"
MENU: "Меню"
TAGS: "Тагове"
PAGES: "Страници"
POSTS: "Постове"
AUTHORS: "Автори"
SEARCH: "Търси"
SEARCH_START: "Type a keyword"
SOCIAL_NETWORKS: "Social Networks"
CATEGORIES: "Categories"
SETTINGS: "Настройки"
ZOOM: "Zoom"
FEATURED: "Опций"
OPEN_IN_BROWSER: "Отвори в браузъра"
ABOUT: "Относно"
COMMENTS: "Коментари"
CUSTOM_POSTS: "Custom posts"
CUSTOM_TAXO: "Custom Taxonomy"
CUSTOM_TAXO_TITLE: "{{term}}: {{name}}"
PUSH_NOTIFS: "Push notifications"
PUSH_NOTIF_TITLE: "New content!"
PUSH_NOTIF_TEXT: "A new Post/Page: '{{postTitle}}' has been released on {{appTitle}}, do you want to open it?"
BOOKMARKS: "Bookmarks"
BOOKMARKS_EMPTY: "Nothing bookmarked yet!"
BOOKMARK_ADDED: "Bookmarked!"
BOOKMARK_REMOVED: "Bookmark removed!"
CACHE_CLEAR: "Clear cache"
CACHE_CLEAR_PROMPT: "This cannot be undone!"
CACHE_CLEARED: "Cache cleared"
TITLE_TAGS: "Тагове"
TITLE_TAG: "Таг: {{name}}"
TITLE_CATEGORIES: "Категории"
TITLE_CATEGORY: "Категория: {{name}}"
TITLE_HOME: "Начало"
TITLE_SEARCH: "Search"
TITLE_PAGES: "Страници"
TITLE_POSTS: "Постове"
TITLE_USERS: "Автори"
TITLE_USER: "Автор"
TITLE_USER_POSTS: "Автор: {{name}}"
SHARE_SUCCESS: "Successfully shared!"
SHARE_ERROR: "Sharing failed"
# CUSTOM NO NEED TO TRANSLATE IN OTHER LANGUAGES
TITLE_MOVIE: "Movies"
TITLE_ACTOR: "Actors" | 76026 | PULL_TO_REFRESH: "Дръпни за рефреш!"
RETRY: "Отново"
CANCEL: "Отказ"
SUBMIT: "Изпращане"
BACK: "Назад"
ERROR: "Something wrong happened, please try again."
ATTEMPT_TO_CONNECT: "Attempt to connect {{attempt}} of {{attemptMax}}."
OK: "Ок"
YES: "Да"
NO: "Не"
EMPTY_LIST: "There is nothing here!"
MENU: "Меню"
TAGS: "Тагове"
PAGES: "Страници"
POSTS: "Постове"
AUTHORS: "<NAME>"
SEARCH: "Търси"
SEARCH_START: "Type a keyword"
SOCIAL_NETWORKS: "Social Networks"
CATEGORIES: "Categories"
SETTINGS: "Настройки"
ZOOM: "Zoom"
FEATURED: "Опций"
OPEN_IN_BROWSER: "Отвори в браузъра"
ABOUT: "Относно"
COMMENTS: "Коментари"
CUSTOM_POSTS: "Custom posts"
CUSTOM_TAXO: "Custom Taxonomy"
CUSTOM_TAXO_TITLE: "{{term}}: {{name}}"
PUSH_NOTIFS: "Push notifications"
PUSH_NOTIF_TITLE: "New content!"
PUSH_NOTIF_TEXT: "A new Post/Page: '{{postTitle}}' has been released on {{appTitle}}, do you want to open it?"
BOOKMARKS: "Bookmarks"
BOOKMARKS_EMPTY: "Nothing bookmarked yet!"
BOOKMARK_ADDED: "Bookmarked!"
BOOKMARK_REMOVED: "Bookmark removed!"
CACHE_CLEAR: "Clear cache"
CACHE_CLEAR_PROMPT: "This cannot be undone!"
CACHE_CLEARED: "Cache cleared"
TITLE_TAGS: "Тагове"
TITLE_TAG: "Таг: {{name}}"
TITLE_CATEGORIES: "Категории"
TITLE_CATEGORY: "Категория: {{name}}"
TITLE_HOME: "Начало"
TITLE_SEARCH: "Search"
TITLE_PAGES: "Страници"
TITLE_POSTS: "Постове"
TITLE_USERS: "<NAME>"
TITLE_USER: "<NAME>"
TITLE_USER_POSTS: "А<NAME>: {{name}}"
SHARE_SUCCESS: "Successfully shared!"
SHARE_ERROR: "Sharing failed"
# CUSTOM NO NEED TO TRANSLATE IN OTHER LANGUAGES
TITLE_MOVIE: "Movies"
TITLE_ACTOR: "Actors" | true | PULL_TO_REFRESH: "Дръпни за рефреш!"
RETRY: "Отново"
CANCEL: "Отказ"
SUBMIT: "Изпращане"
BACK: "Назад"
ERROR: "Something wrong happened, please try again."
ATTEMPT_TO_CONNECT: "Attempt to connect {{attempt}} of {{attemptMax}}."
OK: "Ок"
YES: "Да"
NO: "Не"
EMPTY_LIST: "There is nothing here!"
MENU: "Меню"
TAGS: "Тагове"
PAGES: "Страници"
POSTS: "Постове"
AUTHORS: "PI:NAME:<NAME>END_PI"
SEARCH: "Търси"
SEARCH_START: "Type a keyword"
SOCIAL_NETWORKS: "Social Networks"
CATEGORIES: "Categories"
SETTINGS: "Настройки"
ZOOM: "Zoom"
FEATURED: "Опций"
OPEN_IN_BROWSER: "Отвори в браузъра"
ABOUT: "Относно"
COMMENTS: "Коментари"
CUSTOM_POSTS: "Custom posts"
CUSTOM_TAXO: "Custom Taxonomy"
CUSTOM_TAXO_TITLE: "{{term}}: {{name}}"
PUSH_NOTIFS: "Push notifications"
PUSH_NOTIF_TITLE: "New content!"
PUSH_NOTIF_TEXT: "A new Post/Page: '{{postTitle}}' has been released on {{appTitle}}, do you want to open it?"
BOOKMARKS: "Bookmarks"
BOOKMARKS_EMPTY: "Nothing bookmarked yet!"
BOOKMARK_ADDED: "Bookmarked!"
BOOKMARK_REMOVED: "Bookmark removed!"
CACHE_CLEAR: "Clear cache"
CACHE_CLEAR_PROMPT: "This cannot be undone!"
CACHE_CLEARED: "Cache cleared"
TITLE_TAGS: "Тагове"
TITLE_TAG: "Таг: {{name}}"
TITLE_CATEGORIES: "Категории"
TITLE_CATEGORY: "Категория: {{name}}"
TITLE_HOME: "Начало"
TITLE_SEARCH: "Search"
TITLE_PAGES: "Страници"
TITLE_POSTS: "Постове"
TITLE_USERS: "PI:NAME:<NAME>END_PI"
TITLE_USER: "PI:NAME:<NAME>END_PI"
TITLE_USER_POSTS: "АPI:NAME:<NAME>END_PI: {{name}}"
SHARE_SUCCESS: "Successfully shared!"
SHARE_ERROR: "Sharing failed"
# CUSTOM NO NEED TO TRANSLATE IN OTHER LANGUAGES
TITLE_MOVIE: "Movies"
TITLE_ACTOR: "Actors" |
[
{
"context": "Darwin)\nComment: GPGTools - https://gpgtools.org\n\niQIcBAEBCgAGBQJS+lEMAAoJEC/gHEVDSNo5fPQP/26TTyQNn0/cJ0Tq09/9fPxx\nI9whHgo7fVae/MQlIFU/tjpv0ytPZf1lyJG2wkqiGf0lj30WdjpqkmJ4yPBx1H5U\nMPuWTOfomXv7WHQlEfGNKRS5kDlEgrhS25P0AD9DA+vDGKooPwmDt2oAZGfAKU/c\n80NSINj+Uv0qNv1YJKoJGmGdZ5yNVs0jeNYKwwpzAyIxmZo... | test/files/t2.iced | AngelKey/Angelkey.pgputils | 20 |
{decode,clearsign_header} = require('../../lib/main').armor
#===========================================================================
exports.test_clearsign_header = (T, cb) ->
C = {}
data = "this is the data\n"
hasher_name = "SHA512"
b = clearsign_header C, data, hasher_name
expected = "-----BEGIN PGP SIGNED MESSAGE-----\nHash: SHA512\n\nthis is the data\n"
T.equal b, expected, "got the right output"
cb()
#===========================================================================
exports.test_parse_clearsign = (T,cb) ->
msg = """
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA512
hi
-----BEGIN PGP SIGNATURE-----
Version: GnuPG/MacGPG2 v2.0.22 (Darwin)
Comment: GPGTools - https://gpgtools.org
iQIcBAEBCgAGBQJS+lEMAAoJEC/gHEVDSNo5fPQP/26TTyQNn0/cJ0Tq09/9fPxx
I9whHgo7fVae/MQlIFU/tjpv0ytPZf1lyJG2wkqiGf0lj30WdjpqkmJ4yPBx1H5U
MPuWTOfomXv7WHQlEfGNKRS5kDlEgrhS25P0AD9DA+vDGKooPwmDt2oAZGfAKU/c
80NSINj+Uv0qNv1YJKoJGmGdZ5yNVs0jeNYKwwpzAyIxmZoBc8FOE4R93/vU/4P8
IGLQ1v+7HGoeeKob3VTYpghAOl22+6N2A/Pf5eZYW/WU/S/+B6YxkTjYjm1CV9am
pOyYfTV2+h8UVuX179nvFmwopXlcndorCnMP3MdfTL7SmxgQ09vpP1kIXrkCFaEk
CSeJARYSepIgi39ByasKk62wT0Ifh5HY+8zCl9+wQLwUr13M4KM2QNCeGA94hkE8
6HTsAl0H9g8XUTdrKd5PC+DJXFWEEpMUxyk1t6Iu2cxokk/pD209O0re1l70j0vG
fWifTgNgDVtJ25LG/QEIuazrzGWyr9oolIXnqn2t1Ik5kq+lkN+rXjrzgtoeyGIT
YC0UW99E+Vo7361LcmDe1GmZbPA8YaQHivAlj9JjPgTqyauF+NxqHvfRmO2gV/Mo
bW5l52fDecwu4quUxls+5t8Uxu/Uotp7yuwqkHVdNGrRMfHL29WwhTTH+YI/9hpA
8Gt19y4yuMXbs/Cmv74H
=CoJG
-----END PGP SIGNATURE-----
"""
[err,m2] = decode(msg)
T.no_error err
T.assert m2.clearsign?, "got a clearsign portion"
T.assert (msg.indexOf(m2.payload) >= 0), "found the payload"
T.equal m2?.clearsign?.headers?.hash, "SHA512", "hash was right"
T.assert (msg.indexOf(m2.clearsign.lines.join("\n")) >=0), "found the clearsign portion"
cb()
#===========================================================================
msg = """
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA512
When, in disgrace with fortune and men's eyes,
I all alone beweep my outcast state,
And trouble deaf heaven with my bootless cries,
And look upon myself, and curse my fate,
Wishing me like to one more rich in hope,
Featur'd like him, like him with friends possess'd,
Desiring this man's art and that man's scope,
With what I most enjoy contented least;
Yet in these thoughts myself almost despising,
Haply I think on thee, and then my state,
Like to the lark at break of day arising
- From sullen earth, sings hymns at heaven's gate;
For thy sweet love remember'd such wealth brings
That then I scorn to change my state with kings.
-----BEGIN PGP SIGNATURE-----
Version: GnuPG/MacGPG2 v2.0.22 (Darwin)
Comment: GPGTools - https://gpgtools.org
iQIcBAEBCgAGBQJS+ptgAAoJEC/gHEVDSNo5QfMQAK9xjGapMr+O4YSRl8i6Dc2C
Dy7+ccQZBV5wYjQkF6eg3VC8P0iqnV4NDJ/1bnn5K4lHsu+vPHm1GK/HVemHncSM
FIjwUjrhfqKRVlG8WcxgME9EjCeONZErENffnd1RVluDUdN0tS46mJtviLbg7yYQ
r2kVWObFzH+p9PvEKvoJGASuSrDrbBQ0rq+DO0tof4maI8loses7wMc7R2MBkJ+W
+Ph2LqLilJQ25WoOjixmFF+TC15MqKDTPB1Zx9RC+T16hkHDEvTcfxpFuLUOouYa
YnHQ2KN7/ojfgAhyO1BQwSSrGsKMqFw7lY/2mtJlWWV9I8D+cI9RWdjW8SoMKoY+
eeAKzjMKpOtYXvXiZoFivuFxyhclgnj2JbzCxwhgbrbCGkIQBof70K6Dfu0I6VpS
qq2ZaOto8LqcsaQ13KWNQwsotP4fSXsB72mPBQ46WKjXWoQYyheazCrAuzLuZqCJ
QBwrLwWdAWahf7kg5gOFlxLFgWLDcyTSj1/lmYtazWGHSVI0B/u699N3PhIGlaaT
4UT6qdHSjls+FmcL+66rSu5svMOlDdsuHFXvWPt7FhRM9ZXGwQP7LdpQ6UOeYTqf
Al9DZ/j7kPPbK2tEHdx9Kq4m4sniFlLt/kAMOtfNiu7zwnVEx2L9IPgjyXtshT6H
AtaeSVJvRwvf1PFes2er
=h/Au
-----END PGP SIGNATURE-----
"""
#===========================================================================
exports.test_parse_clearsign_2 = (T,cb) ->
[err,m2] = decode(msg)
T.no_error err
T.assert m2.clearsign?, "got a clearsign portion"
T.assert (msg.indexOf(m2.payload) >= 0), "found the payload"
T.equal m2?.clearsign?.headers?.hash, "SHA512", "hash was right"
T.assert (msg.indexOf(m2.clearsign.lines.join("\n")) >=0), "found the clearsign portion"
cb()
#===========================================================================
exports.test_bad_armor = (T,cb) ->
msg = """-----BEGIN PGP MESSAGE-----
Version: GnuPG/MacGPG2 v2.0.22 (Darwin)
Comment: GPGTools - https://gpgtools.org
hQEMA+bZw3a+syp5AQf6A1kTq0lwT+L1WCr7N2twHbvOnAorb+PJiVHIp2hTW2gr
U3fm/0/SxTdTJRaZsAjbVLH4jYg6cXyNIxdE5uw2ywxQ9Zi8iWylDixsPT5bD6Q7
xlFLhr4BTt7P/oTUMANybuFU6ntss8jbzKZ7SdHbylLrkaUylSWqH1d7bffMxCAl
JOOAHBOXowpcswAurwQpaDZGX3rGUXjAcMDS5ykr/tgHIwo25A+WbIdNCYMkYm0d
BT83PUMIZm351LJWIv/tBqraNc9kEyftAMbVlh5xC0EfPt+ipyRJDh5XKTvh0xQW
T6nM9Z0qLVwUhaG9RqRM1H6D083IE9fKF6sFdce7MtI/ARo3wPa7qll1hyY5vfaT
baAzKLJPcPDf1vu2+S1c1kt5ljvao8MCCebgK7E8CPT/ajLr1xU05G7Eg0zrkstk
=ni0M
-----END PGP MESSAGE-----"""
[err,_] = decode(msg)
T.assert err?, "we got an error back"
T.equal err.toString(), "Error: bad PGP armor found; expected a newline"
cb()
#===========================================================================
exports.test_armor_with_charset = (T,cb) ->
msg = """-----BEGIN PGP PRIVATE KEY BLOCK-----
Charset: UTF-8
Version: End-To-End v0.3.1338
xf8AAAB3BFOsKbATCCqGSM49AwEHAgMEhEKmGdZix3AbyoAVe6Bd4WZE8jGVUbKh
NCaDyKaE7rKk5JZa2hIyaJN8wEOIJ3hWgPBTK13n+zvrllSNRz9+7gAA/iCIKxxK
M3Q81TyXQASN345AWSmjb/evQfwFBreq1M57D0DN/wAAABI8dGhlbWF4QGdtYWls
LmNvbT7C/wAAAGYEEBMIABj/AAAABYJTrCmw/wAAAAmQh6GhxI25BWcAAEphAQCY
dab0CXAU1JCEUDegFih6n1LJjlQ8rr9jkdkplfZKyAD/Z/204vz6ICHYB8rhHOC6
127D8KHdLYaR8KKNPEDw6m/H/wAAAHsEU6wpsBIIKoZIzj0DAQcCAwRiCoBfuydu
cp3FChW9Q4Yz6cXU2okTyGv2hHsnQ2P5tilLSBp2cv4TnV4LIawNsP+gsesoXSln
hFb+sAdaTvwxAwEIBwAA/AvHI+wsE9cFyxe6tHePCa+/KCrRia6Jz9VYMkTJKxcD
DyjC/wAAAGYEGBMIABj/AAAABYJTrCmw/wAAAAmQh6GhxI25BWcAAASlAP985Usk
lzOHK4VuqatRW35xBICiymeQX+aDXbU/6OL1cwD7Bj+TmwRDQe9b3yAV8ktaZM/L
3Uc+HTz2Cp9wtwSPXXfG/wAAAFIEU6wpsBMIKoZIzj0DAQcCAwSEQqYZ1mLHcBvK
gBV7oF3hZkTyMZVRsqE0JoPIpoTusqTkllraEjJok3zAQ4gneFaA8FMrXef7O+uW
VI1HP37uzf8AAAASPHRoZW1heEBnbWFpbC5jb20+wv8AAABmBBATCAAY/wAAAAWC
U6wpsP8AAAAJkIehocSNuQVnAABKYQEAmHWm9AlwFNSQhFA3oBYoep9SyY5UPK6/
Y5HZKZX2SsgA/2f9tOL8+iAh2AfK4Rzgutduw/Ch3S2GkfCijTxA8Opvzv8AAABW
BFOsKbASCCqGSM49AwEHAgMEYgqAX7snbnKdxQoVvUOGM+nF1NqJE8hr9oR7J0Nj
+bYpS0gadnL+E51eCyGsDbD/oLHrKF0pZ4RW/rAHWk78MQMBCAfC/wAAAGYEGBMI
ABj/AAAABYJTrCmw/wAAAAmQh6GhxI25BWcAAASlAPsFvd0AeDmF2wBJd4l1g0oV
TfplxTTTYO6DJP5McmTtKwD+P7WgGuy0IssdwD7bU//zlOvl9nyztxojitGtDtT2
CNU=
=TRLE
-----END PGP PRIVATE KEY BLOCK-----"""
[err,_] = decode(msg)
T.no_error err
cb()
exports.test_high_char = (T,cb) ->
msg = """-----BEGIN PGP PRIVATE KEY BLOCK-----
Comment: GPGTools - but wait unicode! ->\u{1F525}<-
Version: End-To-End v0.3.1338
xf8AAAB3BFOsKbATCCqGSM49AwEHAgMEhEKmGdZix3AbyoAVe6Bd4WZE8jGVUbKh
NCaDyKaE7rKk5JZa2hIyaJN8wEOIJ3hWgPBTK13n+zvrllSNRz9+7gAA/iCIKxxK
M3Q81TyXQASN345AWSmjb/evQfwFBreq1M57D0DN/wAAABI8dGhlbWF4QGdtYWls
LmNvbT7C/wAAAGYEEBMIABj/AAAABYJTrCmw/wAAAAmQh6GhxI25BWcAAEphAQCY
dab0CXAU1JCEUDegFih6n1LJjlQ8rr9jkdkplfZKyAD/Z/204vz6ICHYB8rhHOC6
127D8KHdLYaR8KKNPEDw6m/H/wAAAHsEU6wpsBIIKoZIzj0DAQcCAwRiCoBfuydu
cp3FChW9Q4Yz6cXU2okTyGv2hHsnQ2P5tilLSBp2cv4TnV4LIawNsP+gsesoXSln
hFb+sAdaTvwxAwEIBwAA/AvHI+wsE9cFyxe6tHePCa+/KCrRia6Jz9VYMkTJKxcD
DyjC/wAAAGYEGBMIABj/AAAABYJTrCmw/wAAAAmQh6GhxI25BWcAAASlAP985Usk
lzOHK4VuqatRW35xBICiymeQX+aDXbU/6OL1cwD7Bj+TmwRDQe9b3yAV8ktaZM/L
3Uc+HTz2Cp9wtwSPXXfG/wAAAFIEU6wpsBMIKoZIzj0DAQcCAwSEQqYZ1mLHcBvK
gBV7oF3hZkTyMZVRsqE0JoPIpoTusqTkllraEjJok3zAQ4gneFaA8FMrXef7O+uW
VI1HP37uzf8AAAASPHRoZW1heEBnbWFpbC5jb20+wv8AAABmBBATCAAY/wAAAAWC
U6wpsP8AAAAJkIehocSNuQVnAABKYQEAmHWm9AlwFNSQhFA3oBYoep9SyY5UPK6/
Y5HZKZX2SsgA/2f9tOL8+iAh2AfK4Rzgutduw/Ch3S2GkfCijTxA8Opvzv8AAABW
BFOsKbASCCqGSM49AwEHAgMEYgqAX7snbnKdxQoVvUOGM+nF1NqJE8hr9oR7J0Nj
+bYpS0gadnL+E51eCyGsDbD/oLHrKF0pZ4RW/rAHWk78MQMBCAfC/wAAAGYEGBMI
ABj/AAAABYJTrCmw/wAAAAmQh6GhxI25BWcAAASlAPsFvd0AeDmF2wBJd4l1g0oV
TfplxTTTYO6DJP5McmTtKwD+P7WgGuy0IssdwD7bU//zlOvl9nyztxojitGtDtT2
CNU=
=TRLE
-----END PGP PRIVATE KEY BLOCK-----"""
[err,_] = decode(msg)
T.assert err?, "we got an error back"
T.equal err.toString(), "Error: invalid character in armor"
cb()
exports.test_high_char_clearsigned = (T,cb) ->
msg = """-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA256
clearsign works \u{1f4a9}
-----BEGIN PGP SIGNATURE-----
iQEzBAEBCAAdFiEEWKJF09iyXBX2zj//cYdraK1ILTIFAliA9I4ACgkQcYdraK1I
LTI/Egf/RRhKMRTuYoGab7MWKdDzgpFCl/oBGbxb6FyZT2gbWH+ZHY6C7Q+XGl75
2hIQhtqb6h/9not0i8NRBoZBhXaB3UNVjYXViznXUCFHraxVB3Jw/9RO+ngpOySJ
zg5aI+NLpx64TDmr0OBJyoodcvwtGqyACLflhC/iHmy8bOCAYfhQ2PaGWEB5dPOh
XAZ7l7hzXBc8NFfqUVFjEDS6Ze9qciDYpHrGdbk1uAzdpTyLbj1oQUZnHSjfmRIc
f2/zCEeRz+f5ziqjlI6XtniWNR6PWDq/cMfKeVpLPTDN8p22dP/6/rw/kl9QHkqE
kL/gpzhxmthXleUat8zNkK/xrgzjxA==
=FQwn
-----END PGP SIGNATURE-----
"""
[err, decoded] = decode(msg)
T.no_error err
T.equal decoded.clearsign.body, "clearsign works \u{1f4a9}\n"
cb()
exports.test_header_white_space = (T,cb) ->
msg = """-----BEGIN PGP PUBLIC KEY BLOCK-----
mI0EWcknrwEEAK2X5lKA76pf6i5D1aVcApUAH6NnZ4NkFeSxKT92soiSWkFn+I/G
VKJfTvx2dzxOAB4rvyFjUzjgAwhK3FblCnfXwgPAh6/vukF/YBwynCVyNxOVAVHY
gCkw/+7zIM24RUxzI3V9wzJ6i/SpfNnWKkKqJXIt4Xzv3Rs/UXk5DMY5ABEBAAG0
I01heCBUZXN0IDc3NyA8dGhlbWF4Kzc3N0BnbWFpbC5jb20+iLgEEwECACIFAlnJ
J68CGwMGCwkIBwMCBhUIAgkKCwQWAgMBAh4BAheAAAoJEM5jclcHa4v8ssQD/RJA
JTrfydAkLzffGgZyKafs/aTraVDNtDv1sF+5iBtZvOB0FFjzivl3BGlplEqnPquB
bg8/OQuxFLYM/f8+WgP5MDqBce8s6h5kGZPj73zP4GQLZWojS5/H3J1sDBmNTSnd
ByELhvVxJmJiHdz2jMb74+thB/ZK4xf+zAkRF4WZuI0EWcknrwEEALk0Bsp/xJ+4
75hswySLZmvNh79CyIC0K1gzXiEPDwqGy6xT1PbXLJ5HcXna4HJdNAgXf1T/n+zR
19xJMAB6NSv2zigRaYAyy4It2p2cRPHseWWTcP7lMUpwqtQsnqNKJ14RuAaMOQtG
xSaQMgMGZx6lxFWNaK40SxSnqFRtfRs9ABEBAAGInwQYAQIACQUCWcknrwIbDAAK
CRDOY3JXB2uL/PX/A/9HvpLPVDrEMr9+vzmS8Ez0br2kgeoPh7yOAlEotS7OBNWU
UzzykQlAfLl74336wrkSZfa2GnBBJQHvlnLosnmbGCzsd3KMkuJv90hxxt1rqjN6
3GFiwBVdsSuyEb3uQJ/ytAyVozwwxjMQZ+gJTYfK8syPdf2T1W6cv7lfHp8E8g==
=sJQD
-----END PGP PUBLIC KEY BLOCK-----"""
k = msg.split('\n')
line0 = k[0]
k1 = [(line0 + " " )].concat(k[1...]).join("\n")
[err, decoded] = decode(k1)
T.no_error err
k2 = [(line0 + " [10/20]" )].concat(k[1...]).join("\n")
[err, decoded] = decode(k2)
T.assert err?, "error found!"
cb()
| 212524 |
{decode,clearsign_header} = require('../../lib/main').armor
#===========================================================================
exports.test_clearsign_header = (T, cb) ->
C = {}
data = "this is the data\n"
hasher_name = "SHA512"
b = clearsign_header C, data, hasher_name
expected = "-----BEGIN PGP SIGNED MESSAGE-----\nHash: SHA512\n\nthis is the data\n"
T.equal b, expected, "got the right output"
cb()
#===========================================================================
exports.test_parse_clearsign = (T,cb) ->
msg = """
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA512
hi
-----BEGIN PGP SIGNATURE-----
Version: GnuPG/MacGPG2 v2.0.22 (Darwin)
Comment: GPGTools - https://gpgtools.org
<KEY>
CSeJARYSepIgi39<KEY>
-----END PGP SIGNATURE-----
"""
[err,m2] = decode(msg)
T.no_error err
T.assert m2.clearsign?, "got a clearsign portion"
T.assert (msg.indexOf(m2.payload) >= 0), "found the payload"
T.equal m2?.clearsign?.headers?.hash, "SHA512", "hash was right"
T.assert (msg.indexOf(m2.clearsign.lines.join("\n")) >=0), "found the clearsign portion"
cb()
#===========================================================================
msg = """
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA512
When, in disgrace with fortune and men's eyes,
I all alone beweep my outcast state,
And trouble deaf heaven with my bootless cries,
And look upon myself, and curse my fate,
Wishing me like to one more rich in hope,
Featur'd like him, like him with friends possess'd,
Desiring this man's art and that man's scope,
With what I most enjoy contented least;
Yet in these thoughts myself almost despising,
Haply I think on thee, and then my state,
Like to the lark at break of day arising
- From sullen earth, sings hymns at heaven's gate;
For thy sweet love remember'd such wealth brings
That then I scorn to change my state with kings.
-----BEGIN PGP SIGNATURE-----
Version: GnuPG/MacGPG2 v2.0.22 (Darwin)
Comment: GPGTools - https://gpgtools.org
<KEY>
AtaeSVJv<KEY>1PFes2er
=h/Au
-----END PGP SIGNATURE-----
"""
#===========================================================================
exports.test_parse_clearsign_2 = (T,cb) ->
[err,m2] = decode(msg)
T.no_error err
T.assert m2.clearsign?, "got a clearsign portion"
T.assert (msg.indexOf(m2.payload) >= 0), "found the payload"
T.equal m2?.clearsign?.headers?.hash, "SHA512", "hash was right"
T.assert (msg.indexOf(m2.clearsign.lines.join("\n")) >=0), "found the clearsign portion"
cb()
#===========================================================================
exports.test_bad_armor = (T,cb) ->
msg = """-----BEGIN PGP MESSAGE-----
Version: GnuPG/MacGPG2 v2.0.22 (Darwin)
Comment: GPGTools - https://gpgtools.org
hQEMA+bZw3a+syp5AQf6A1kTq0lwT+L1WCr7N2twHbvOnAorb+PJiVHIp2hTW2gr
U<KEY>fm/<KEY>/SxTdTJR<KEY>Zs<KEY>jbVLH4jYg<KEY>Xy<KEY>E<KEY>uw<KEY>
xl<KEY>
J<KEY>BOX<KEY>sw<KEY>w<KEY>pa<KEY>GUX<KEY>ykr/tgHIwo2<KEY>A+WbIdNCYMkYm<KEY>
-----END PGP MESSAGE-----"""
[err,_] = decode(msg)
T.assert err?, "we got an error back"
T.equal err.toString(), "Error: bad PGP armor found; expected a newline"
cb()
#===========================================================================
exports.test_armor_with_charset = (T,cb) ->
msg = """-----BEGIN PGP PRIVATE KEY BLOCK-----
Charset: UTF-8
Version: End-To-End v0.3.1338
<KEY>
-----END PGP PRIVATE KEY BLOCK-----"""
[err,_] = decode(msg)
T.no_error err
cb()
exports.test_high_char = (T,cb) ->
msg = """-----BEGIN PGP PRIVATE KEY BLOCK-----
Comment: GPGTools - but wait unicode! ->\u{1F525}<-
Version: End-To-End v0.3.1338
<KEY>txojitGtDtT2
CNU=
=TRLE
-----END PGP PRIVATE KEY BLOCK-----"""
[err,_] = decode(msg)
T.assert err?, "we got an error back"
T.equal err.toString(), "Error: invalid character in armor"
cb()
exports.test_high_char_clearsigned = (T,cb) ->
msg = """-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA256
clearsign works \u{1f4a9}
-----BEGIN PGP SIGNATURE-----
<KEY>
-----END PGP SIGNATURE-----
"""
[err, decoded] = decode(msg)
T.no_error err
T.equal decoded.clearsign.body, "clearsign works \u{1f4a9}\n"
cb()
exports.test_header_white_space = (T,cb) ->
msg = """-----BEGIN PGP PUBLIC KEY BLOCK-----
mI0EW<KEY>
-----END PGP PUBLIC KEY BLOCK-----"""
k = msg.split('\n')
line0 = k[0]
k1 = [(line0 + " " )].concat(k[1...]).join("\n")
[err, decoded] = decode(k1)
T.no_error err
k2 = [(line0 + " [10/20]" )].concat(k[1...]).join("\n")
[err, decoded] = decode(k2)
T.assert err?, "error found!"
cb()
| true |
{decode,clearsign_header} = require('../../lib/main').armor
#===========================================================================
exports.test_clearsign_header = (T, cb) ->
C = {}
data = "this is the data\n"
hasher_name = "SHA512"
b = clearsign_header C, data, hasher_name
expected = "-----BEGIN PGP SIGNED MESSAGE-----\nHash: SHA512\n\nthis is the data\n"
T.equal b, expected, "got the right output"
cb()
#===========================================================================
exports.test_parse_clearsign = (T,cb) ->
msg = """
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA512
hi
-----BEGIN PGP SIGNATURE-----
Version: GnuPG/MacGPG2 v2.0.22 (Darwin)
Comment: GPGTools - https://gpgtools.org
PI:KEY:<KEY>END_PI
CSeJARYSepIgi39PI:KEY:<KEY>END_PI
-----END PGP SIGNATURE-----
"""
[err,m2] = decode(msg)
T.no_error err
T.assert m2.clearsign?, "got a clearsign portion"
T.assert (msg.indexOf(m2.payload) >= 0), "found the payload"
T.equal m2?.clearsign?.headers?.hash, "SHA512", "hash was right"
T.assert (msg.indexOf(m2.clearsign.lines.join("\n")) >=0), "found the clearsign portion"
cb()
#===========================================================================
msg = """
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA512
When, in disgrace with fortune and men's eyes,
I all alone beweep my outcast state,
And trouble deaf heaven with my bootless cries,
And look upon myself, and curse my fate,
Wishing me like to one more rich in hope,
Featur'd like him, like him with friends possess'd,
Desiring this man's art and that man's scope,
With what I most enjoy contented least;
Yet in these thoughts myself almost despising,
Haply I think on thee, and then my state,
Like to the lark at break of day arising
- From sullen earth, sings hymns at heaven's gate;
For thy sweet love remember'd such wealth brings
That then I scorn to change my state with kings.
-----BEGIN PGP SIGNATURE-----
Version: GnuPG/MacGPG2 v2.0.22 (Darwin)
Comment: GPGTools - https://gpgtools.org
PI:KEY:<KEY>END_PI
AtaeSVJvPI:KEY:<KEY>END_PI1PFes2er
=h/Au
-----END PGP SIGNATURE-----
"""
#===========================================================================
exports.test_parse_clearsign_2 = (T,cb) ->
[err,m2] = decode(msg)
T.no_error err
T.assert m2.clearsign?, "got a clearsign portion"
T.assert (msg.indexOf(m2.payload) >= 0), "found the payload"
T.equal m2?.clearsign?.headers?.hash, "SHA512", "hash was right"
T.assert (msg.indexOf(m2.clearsign.lines.join("\n")) >=0), "found the clearsign portion"
cb()
#===========================================================================
exports.test_bad_armor = (T,cb) ->
msg = """-----BEGIN PGP MESSAGE-----
Version: GnuPG/MacGPG2 v2.0.22 (Darwin)
Comment: GPGTools - https://gpgtools.org
hQEMA+bZw3a+syp5AQf6A1kTq0lwT+L1WCr7N2twHbvOnAorb+PJiVHIp2hTW2gr
UPI:KEY:<KEY>END_PIfm/PI:KEY:<KEY>END_PI/SxTdTJRPI:KEY:<KEY>END_PIZsPI:KEY:<KEY>END_PIjbVLH4jYgPI:KEY:<KEY>END_PIXyPI:KEY:<KEY>END_PIEPI:KEY:<KEY>END_PIuwPI:KEY:<KEY>END_PI
xlPI:KEY:<KEY>END_PI
JPI:KEY:<KEY>END_PIBOXPI:KEY:<KEY>END_PIswPI:KEY:<KEY>END_PIwPI:KEY:<KEY>END_PIpaPI:KEY:<KEY>END_PIGUXPI:KEY:<KEY>END_PIykr/tgHIwo2PI:KEY:<KEY>END_PIA+WbIdNCYMkYmPI:KEY:<KEY>END_PI
-----END PGP MESSAGE-----"""
[err,_] = decode(msg)
T.assert err?, "we got an error back"
T.equal err.toString(), "Error: bad PGP armor found; expected a newline"
cb()
#===========================================================================
exports.test_armor_with_charset = (T,cb) ->
msg = """-----BEGIN PGP PRIVATE KEY BLOCK-----
Charset: UTF-8
Version: End-To-End v0.3.1338
PI:KEY:<KEY>END_PI
-----END PGP PRIVATE KEY BLOCK-----"""
[err,_] = decode(msg)
T.no_error err
cb()
exports.test_high_char = (T,cb) ->
msg = """-----BEGIN PGP PRIVATE KEY BLOCK-----
Comment: GPGTools - but wait unicode! ->\u{1F525}<-
Version: End-To-End v0.3.1338
PI:KEY:<KEY>END_PItxojitGtDtT2
CNU=
=TRLE
-----END PGP PRIVATE KEY BLOCK-----"""
[err,_] = decode(msg)
T.assert err?, "we got an error back"
T.equal err.toString(), "Error: invalid character in armor"
cb()
exports.test_high_char_clearsigned = (T,cb) ->
msg = """-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA256
clearsign works \u{1f4a9}
-----BEGIN PGP SIGNATURE-----
PI:KEY:<KEY>END_PI
-----END PGP SIGNATURE-----
"""
[err, decoded] = decode(msg)
T.no_error err
T.equal decoded.clearsign.body, "clearsign works \u{1f4a9}\n"
cb()
exports.test_header_white_space = (T,cb) ->
msg = """-----BEGIN PGP PUBLIC KEY BLOCK-----
mI0EWPI:KEY:<KEY>END_PI
-----END PGP PUBLIC KEY BLOCK-----"""
k = msg.split('\n')
line0 = k[0]
k1 = [(line0 + " " )].concat(k[1...]).join("\n")
[err, decoded] = decode(k1)
T.no_error err
k2 = [(line0 + " [10/20]" )].concat(k[1...]).join("\n")
[err, decoded] = decode(k2)
T.assert err?, "error found!"
cb()
|
[
{
"context": "e\n needToRewrite: false #true\n mainKeyName: \"科室名\"\n}\n\njson = JSONUtils.getJSON(funcOpts)\n\ndata = js",
"end": 318,
"score": 0.7195732593536377,
"start": 317,
"tag": "KEY",
"value": "名"
}
] | tests/testMakeReport.coffee | Tostig0916/hqcoffee | 2 | path = require 'path'
{MakePPTReport} = require path.join __dirname, '..','usepptxgen', 'pptxgenUtils'
{JSONUtils} = require path.join __dirname, '..', 'analyze', 'jsonUtils'
# 从数据表读取数据,再生成报告用的JSON
funcOpts = {
basename: "jsszyy"
headerRows: 1
sheetStubs: true
needToRewrite: false #true
mainKeyName: "科室名"
}
json = JSONUtils.getJSON(funcOpts)
data = json["雷达图"]
jsonReport = {
"专科散点图": {
settings:{
chartType: "bar3d" #"scatter"
}
data: data
}
"专科线图": {
settings:{
chartType:"line"
}
data
}
"专科雷达图": {
settings:{
chartType:"radar"
}
data
}
}
funcOpts.json = jsonReport
funcOpts.needToRewrite = true
#console.log funcOpts, MakePPTReport
MakePPTReport.newReport(funcOpts) | 133518 | path = require 'path'
{MakePPTReport} = require path.join __dirname, '..','usepptxgen', 'pptxgenUtils'
{JSONUtils} = require path.join __dirname, '..', 'analyze', 'jsonUtils'
# 从数据表读取数据,再生成报告用的JSON
funcOpts = {
basename: "jsszyy"
headerRows: 1
sheetStubs: true
needToRewrite: false #true
mainKeyName: "科室<KEY>"
}
json = JSONUtils.getJSON(funcOpts)
data = json["雷达图"]
jsonReport = {
"专科散点图": {
settings:{
chartType: "bar3d" #"scatter"
}
data: data
}
"专科线图": {
settings:{
chartType:"line"
}
data
}
"专科雷达图": {
settings:{
chartType:"radar"
}
data
}
}
funcOpts.json = jsonReport
funcOpts.needToRewrite = true
#console.log funcOpts, MakePPTReport
MakePPTReport.newReport(funcOpts) | true | path = require 'path'
{MakePPTReport} = require path.join __dirname, '..','usepptxgen', 'pptxgenUtils'
{JSONUtils} = require path.join __dirname, '..', 'analyze', 'jsonUtils'
# 从数据表读取数据,再生成报告用的JSON
funcOpts = {
basename: "jsszyy"
headerRows: 1
sheetStubs: true
needToRewrite: false #true
mainKeyName: "科室PI:KEY:<KEY>END_PI"
}
json = JSONUtils.getJSON(funcOpts)
data = json["雷达图"]
jsonReport = {
"专科散点图": {
settings:{
chartType: "bar3d" #"scatter"
}
data: data
}
"专科线图": {
settings:{
chartType:"line"
}
data
}
"专科雷达图": {
settings:{
chartType:"radar"
}
data
}
}
funcOpts.json = jsonReport
funcOpts.needToRewrite = true
#console.log funcOpts, MakePPTReport
MakePPTReport.newReport(funcOpts) |
[
{
"context": "size for `em`- and `rem`-based sizing.\n#\n# @author Chris Sauve (lemonmade)\n# @since 0.0.1\n# @access private\n# @r",
"end": 2901,
"score": 0.9998776912689209,
"start": 2890,
"tag": "NAME",
"value": "Chris Sauve"
},
{
"context": " and `rem`-based sizing.\n#\n# @author... | src/coffee/poptart.coffee | bigfoot-js/poptart | 0 | obj = require("bigfoot-obj")
dom = require("bigfoot-dom")
ATTR_CSS_MAX_WIDTH = "data-poptart-max-width"
ATTR_CSS_MAX_HEIGHT = "data-poptart-max-height"
POSITIONS =
BOTTOM: "bottom"
TOP: "top"
registeredSelectors = {}
activePopover = {}
positionPopovers = undefined
triggerPopover = (source, settings) ->
markup = settings.callback(source)
div = document.createElement("div")
div.innerHTML = markup
popover = div.firstChild
setTimeout ->
style = window.getComputedStyle(popover)
setTimeout ->
popover.setAttribute(ATTR_CSS_MAX_WIDTH, calculateMaxWidthPixelDimension(style.maxWidth))
popover.setAttribute(ATTR_CSS_MAX_HEIGHT, calculateMaxWidthPixelDimension(style.maxHeight))
popover.style.maxWidth = "none"
positionPopovers = popoverPositioner(settings)
positionPopovers()
popover.classList.add(settings.activeClass)
, 0
activePopover.popover = popover
activePopover.source = source
source.parentNode.appendChild(popover)
window.addEventListener "resize", positionPopovers
window.addEventListener "scroll", positionPopovers
, 0
popover
removePopovers = (settings) ->
return unless activePopover.popover
popover = activePopover.popover
remove = (event) ->
popover.parentNode?.removeChild(popover)
popover.addEventListener "transitionend", remove
popover.addEventListener "webkitTransitionend", remove
popover.classList.remove("is-active")
activePopover = {}
posititionPopovers = undefined
window.removeEventListener "resize", positionPopovers
window.removeEventListener "scroll", positionPopovers
nodeIsDescendantOfNode = (node, ancestorNode) ->
return false unless ancestorNode
while node != document.body
return true if node == ancestorNode
node = node.parentNode
false
nodeIsPopoverDescendant = (node) -> nodeIsDescendantOfNode(node, activePopover.popover)
nodeIsSourceDescendant = (node) -> nodeIsDescendantOfNode(node, activePopover.source)
clickHandler = (event) ->
tryTriggering = !nodeIsSourceDescendant(event.target)
if activePopover.popover && !nodeIsPopoverDescendant(event.target)
removePopovers()
if tryTriggering
popover = Popover.triggerPopoverFor(event.target)
!!popover # prevent default if a popover was triggered
availableSpace = (node) ->
rect = node.getBoundingClientRect()
[topSpace, leftSpace] = [rect.top + 0.5 * rect.height, rect.left + 0.5 * rect.width]
source =
height: rect.height
width: rect.width
windowDimensions =
height: window.innerHeight
width: window.innerWidth
top: topSpace
bottom: windowDimensions.height - topSpace
left: leftSpace
leftRelative: leftSpace / windowDimensions.width
right: windowDimensions.width - leftSpace
window: windowDimensions
source: source
#*
# Calculates the base font size for `em`- and `rem`-based sizing.
#
# @author Chris Sauve (lemonmade)
# @since 0.0.1
# @access private
# @returns {Number} - The base font size in pixels.
baseFontSize = ->
el = document.createElement("div")
el.style.cssText = "display:inline-block;padding:0;line-height:1;position:absolute;visibility:hidden;font-size:1em;"
el.appendChild(document.createElement("M"))
document.body.appendChild(el)
size = el.offsetHeight
document.body.removeChild(el)
size
calculateMaxWidthPixelDimension = (dim, node) ->
calculatePixelDimension(dim, node) || 10000
calculatePixelDimension = (dim, node, makeFFPercentageAdjustment = true) ->
# No value set, make it non-restricting
return 0 if dim == "none"
return parseFloat(dim) * baseFontSize() if dim.indexOf("rem") >= 0
return parseFloat(dim) * parseFloat(window.getComputedStyle(node).fontSize) if dim.indexOf("em") >= 0
return parseFloat(dim) / 100 if dim.indexOf("%") >= 0 || dim.indexOf("vw") >= 0
# Set in px
dim = parseFloat(dim)
# Weird issue in FF where %-based widths would be resolved
# to px before being reported. Assume that smallest possible
# expicitly-set max width is 60px, otherwise, it's the result
# of this calculation.
dim = dim / parseFloat(node.parentNode.offsetWidth) if dim <= 60 && makeFFPercentageAdjustment
dim
oppositeOf = (pos) ->
if pos == POSITIONS.BOTTOM then POSITIONS.TOP else POSITIONS.BOTTOM
setPopoverWidth = (maxWidthRelativeTo, preferredPosition) ->
maxWidth = parseFloat(activePopover.popover.getAttribute(ATTR_CSS_MAX_WIDTH))
wrap = dom.find(activePopover.popover, ".bigfoot-footnote__wrapper")
if maxWidth <= 1
# Max width in CSS set as a percentage
# If a relative element has been set for max width, the actual max width
# by which to multiply the percentage is the lesser of the element's width
# and the width of the viewport
relativeToWidth = do ->
# Width of user-specified element width, set to non-constraining
# value in case it does not exist
userSpecifiedRelativeElWidth = 10000
if maxWidthRelativeTo
el = dom.one(maxWidthRelativeTo)
userSpecifiedRelativeElWidth = el.offsetWidth if el
Math.min(window.innerWidth, userSpecifiedRelativeElWidth)
# Applicable constraining width times the percentage in CSS
maxWidth = relativeToWidth * maxWidth
# Set the max width to the smaller of the calculated width based on the
# percentage/ other value and the width of the actual content (prevents
# excess width for small footnotes)
maxWidth = Math.min(maxWidth, dom.find(activePopover.popover, ".bigfoot-footnote__content").offsetWidth + 1)
# Set this on the main wrapper. This allows the bigfoot-footnote div
# to be displayed as inline-block, wrapping it around the content.
wrap.style.maxWidth = "#{maxWidth}px"
setPopoverHeight = (space, position) ->
maxHeight = parseFloat(activePopover.popover.getAttribute(ATTR_CSS_MAX_HEIGHT))
popover = activePopover.popover
popoverStyles = window.getComputedStyle(popover)
marginSize = calculatePixelDimension(popoverStyles.marginTop, popover, false) + calculatePixelDimension(popoverStyles.marginBottom, popover, false)
popoverHeight = popover.offsetHeight + marginSize
opposite = oppositeOf(position)
position = opposite if space[position] < popoverHeight && space[position] < space[opposite]
transformOrigin = "#{space.leftRelative * 100}% top 0"
if position == POSITIONS.TOP
popover.classList.add("is-positioned-top")
popover.classList.remove("is-positioned-bottom")
maxHeight = Math.min(maxHeight, space.top - marginSize)
transformOrigin = "#{space.leftRelative * 100}% bottom 0"
else
popover.classList.add("is-positioned-bottom")
popover.classList.remove("is-positioned-top")
maxHeight = Math.min(maxHeight, space.bottom - marginSize)
popover.style.transformOrigin = transformOrigin
content = dom.find(popover, ".bigfoot-footnote__content")
content.style.maxHeight = "#{maxHeight}px"
positionTooltip = (space, popover) ->
tooltip = dom.find(activePopover.popover, ".bigfoot-footnote__tooltip")
tooltip.style.left = "#{popover.offsetWidth * space.leftRelative + 2}px" if tooltip
popoverPositioner = (settings) ->
(event) ->
type = event?.type || "resize"
return unless settings.positionPopovers && activePopover.popover
[popover, source] = [activePopover.popover, activePopover.source]
sourceStyles = window.getComputedStyle(source)
space = availableSpace(source)
setPopoverHeight(space, settings.preferredPosition)
setPopoverWidth(settings.maxWidthRelativeTo) if type == "resize"
positionTooltip(space, popover)
popover.style.marginLeft = "#{-1 * space.leftRelative * popover.offsetWidth + space.source.width / 2 + calculatePixelDimension(sourceStyles.marginLeft, source)}px"
popoverDefaults =
preferredPosition: POSITIONS.BOTTOM
positionPopovers: true
debounce: false
preventPageScroll: true
activeClass: "is-active"
inactiveClass: "popover--is-inactive"
class Poptart
@POSITIONS = POSITIONS
@registerPopover: (selector, options, callback) ->
if typeof options == "function"
options =
callback: options
else
options.callback = options
settings = obj.merge(obj.clone(popoverDefaults), options)
registeredSelectors[selector] = settings
@triggerPopoverFor: (node) ->
settings = undefined
for selector, setting of registeredSelectors
if event.target.webkitMatchesSelector(selector)
settings = setting
break
triggerPopover(node, settings) if settings
document.addEventListener "click", clickHandler
document.addEventListener "touchend", clickHandler
module.exports = Poptart
| 63516 | obj = require("bigfoot-obj")
dom = require("bigfoot-dom")
ATTR_CSS_MAX_WIDTH = "data-poptart-max-width"
ATTR_CSS_MAX_HEIGHT = "data-poptart-max-height"
POSITIONS =
BOTTOM: "bottom"
TOP: "top"
registeredSelectors = {}
activePopover = {}
positionPopovers = undefined
triggerPopover = (source, settings) ->
markup = settings.callback(source)
div = document.createElement("div")
div.innerHTML = markup
popover = div.firstChild
setTimeout ->
style = window.getComputedStyle(popover)
setTimeout ->
popover.setAttribute(ATTR_CSS_MAX_WIDTH, calculateMaxWidthPixelDimension(style.maxWidth))
popover.setAttribute(ATTR_CSS_MAX_HEIGHT, calculateMaxWidthPixelDimension(style.maxHeight))
popover.style.maxWidth = "none"
positionPopovers = popoverPositioner(settings)
positionPopovers()
popover.classList.add(settings.activeClass)
, 0
activePopover.popover = popover
activePopover.source = source
source.parentNode.appendChild(popover)
window.addEventListener "resize", positionPopovers
window.addEventListener "scroll", positionPopovers
, 0
popover
removePopovers = (settings) ->
return unless activePopover.popover
popover = activePopover.popover
remove = (event) ->
popover.parentNode?.removeChild(popover)
popover.addEventListener "transitionend", remove
popover.addEventListener "webkitTransitionend", remove
popover.classList.remove("is-active")
activePopover = {}
posititionPopovers = undefined
window.removeEventListener "resize", positionPopovers
window.removeEventListener "scroll", positionPopovers
nodeIsDescendantOfNode = (node, ancestorNode) ->
return false unless ancestorNode
while node != document.body
return true if node == ancestorNode
node = node.parentNode
false
nodeIsPopoverDescendant = (node) -> nodeIsDescendantOfNode(node, activePopover.popover)
nodeIsSourceDescendant = (node) -> nodeIsDescendantOfNode(node, activePopover.source)
clickHandler = (event) ->
tryTriggering = !nodeIsSourceDescendant(event.target)
if activePopover.popover && !nodeIsPopoverDescendant(event.target)
removePopovers()
if tryTriggering
popover = Popover.triggerPopoverFor(event.target)
!!popover # prevent default if a popover was triggered
availableSpace = (node) ->
rect = node.getBoundingClientRect()
[topSpace, leftSpace] = [rect.top + 0.5 * rect.height, rect.left + 0.5 * rect.width]
source =
height: rect.height
width: rect.width
windowDimensions =
height: window.innerHeight
width: window.innerWidth
top: topSpace
bottom: windowDimensions.height - topSpace
left: leftSpace
leftRelative: leftSpace / windowDimensions.width
right: windowDimensions.width - leftSpace
window: windowDimensions
source: source
#*
# Calculates the base font size for `em`- and `rem`-based sizing.
#
# @author <NAME> (lemonmade)
# @since 0.0.1
# @access private
# @returns {Number} - The base font size in pixels.
baseFontSize = ->
el = document.createElement("div")
el.style.cssText = "display:inline-block;padding:0;line-height:1;position:absolute;visibility:hidden;font-size:1em;"
el.appendChild(document.createElement("M"))
document.body.appendChild(el)
size = el.offsetHeight
document.body.removeChild(el)
size
calculateMaxWidthPixelDimension = (dim, node) ->
calculatePixelDimension(dim, node) || 10000
calculatePixelDimension = (dim, node, makeFFPercentageAdjustment = true) ->
# No value set, make it non-restricting
return 0 if dim == "none"
return parseFloat(dim) * baseFontSize() if dim.indexOf("rem") >= 0
return parseFloat(dim) * parseFloat(window.getComputedStyle(node).fontSize) if dim.indexOf("em") >= 0
return parseFloat(dim) / 100 if dim.indexOf("%") >= 0 || dim.indexOf("vw") >= 0
# Set in px
dim = parseFloat(dim)
# Weird issue in FF where %-based widths would be resolved
# to px before being reported. Assume that smallest possible
# expicitly-set max width is 60px, otherwise, it's the result
# of this calculation.
dim = dim / parseFloat(node.parentNode.offsetWidth) if dim <= 60 && makeFFPercentageAdjustment
dim
oppositeOf = (pos) ->
if pos == POSITIONS.BOTTOM then POSITIONS.TOP else POSITIONS.BOTTOM
setPopoverWidth = (maxWidthRelativeTo, preferredPosition) ->
maxWidth = parseFloat(activePopover.popover.getAttribute(ATTR_CSS_MAX_WIDTH))
wrap = dom.find(activePopover.popover, ".bigfoot-footnote__wrapper")
if maxWidth <= 1
# Max width in CSS set as a percentage
# If a relative element has been set for max width, the actual max width
# by which to multiply the percentage is the lesser of the element's width
# and the width of the viewport
relativeToWidth = do ->
# Width of user-specified element width, set to non-constraining
# value in case it does not exist
userSpecifiedRelativeElWidth = 10000
if maxWidthRelativeTo
el = dom.one(maxWidthRelativeTo)
userSpecifiedRelativeElWidth = el.offsetWidth if el
Math.min(window.innerWidth, userSpecifiedRelativeElWidth)
# Applicable constraining width times the percentage in CSS
maxWidth = relativeToWidth * maxWidth
# Set the max width to the smaller of the calculated width based on the
# percentage/ other value and the width of the actual content (prevents
# excess width for small footnotes)
maxWidth = Math.min(maxWidth, dom.find(activePopover.popover, ".bigfoot-footnote__content").offsetWidth + 1)
# Set this on the main wrapper. This allows the bigfoot-footnote div
# to be displayed as inline-block, wrapping it around the content.
wrap.style.maxWidth = "#{maxWidth}px"
setPopoverHeight = (space, position) ->
maxHeight = parseFloat(activePopover.popover.getAttribute(ATTR_CSS_MAX_HEIGHT))
popover = activePopover.popover
popoverStyles = window.getComputedStyle(popover)
marginSize = calculatePixelDimension(popoverStyles.marginTop, popover, false) + calculatePixelDimension(popoverStyles.marginBottom, popover, false)
popoverHeight = popover.offsetHeight + marginSize
opposite = oppositeOf(position)
position = opposite if space[position] < popoverHeight && space[position] < space[opposite]
transformOrigin = "#{space.leftRelative * 100}% top 0"
if position == POSITIONS.TOP
popover.classList.add("is-positioned-top")
popover.classList.remove("is-positioned-bottom")
maxHeight = Math.min(maxHeight, space.top - marginSize)
transformOrigin = "#{space.leftRelative * 100}% bottom 0"
else
popover.classList.add("is-positioned-bottom")
popover.classList.remove("is-positioned-top")
maxHeight = Math.min(maxHeight, space.bottom - marginSize)
popover.style.transformOrigin = transformOrigin
content = dom.find(popover, ".bigfoot-footnote__content")
content.style.maxHeight = "#{maxHeight}px"
positionTooltip = (space, popover) ->
tooltip = dom.find(activePopover.popover, ".bigfoot-footnote__tooltip")
tooltip.style.left = "#{popover.offsetWidth * space.leftRelative + 2}px" if tooltip
popoverPositioner = (settings) ->
(event) ->
type = event?.type || "resize"
return unless settings.positionPopovers && activePopover.popover
[popover, source] = [activePopover.popover, activePopover.source]
sourceStyles = window.getComputedStyle(source)
space = availableSpace(source)
setPopoverHeight(space, settings.preferredPosition)
setPopoverWidth(settings.maxWidthRelativeTo) if type == "resize"
positionTooltip(space, popover)
popover.style.marginLeft = "#{-1 * space.leftRelative * popover.offsetWidth + space.source.width / 2 + calculatePixelDimension(sourceStyles.marginLeft, source)}px"
popoverDefaults =
preferredPosition: POSITIONS.BOTTOM
positionPopovers: true
debounce: false
preventPageScroll: true
activeClass: "is-active"
inactiveClass: "popover--is-inactive"
class Poptart
@POSITIONS = POSITIONS
@registerPopover: (selector, options, callback) ->
if typeof options == "function"
options =
callback: options
else
options.callback = options
settings = obj.merge(obj.clone(popoverDefaults), options)
registeredSelectors[selector] = settings
@triggerPopoverFor: (node) ->
settings = undefined
for selector, setting of registeredSelectors
if event.target.webkitMatchesSelector(selector)
settings = setting
break
triggerPopover(node, settings) if settings
document.addEventListener "click", clickHandler
document.addEventListener "touchend", clickHandler
module.exports = Poptart
| true | obj = require("bigfoot-obj")
dom = require("bigfoot-dom")
ATTR_CSS_MAX_WIDTH = "data-poptart-max-width"
ATTR_CSS_MAX_HEIGHT = "data-poptart-max-height"
POSITIONS =
BOTTOM: "bottom"
TOP: "top"
registeredSelectors = {}
activePopover = {}
positionPopovers = undefined
triggerPopover = (source, settings) ->
markup = settings.callback(source)
div = document.createElement("div")
div.innerHTML = markup
popover = div.firstChild
setTimeout ->
style = window.getComputedStyle(popover)
setTimeout ->
popover.setAttribute(ATTR_CSS_MAX_WIDTH, calculateMaxWidthPixelDimension(style.maxWidth))
popover.setAttribute(ATTR_CSS_MAX_HEIGHT, calculateMaxWidthPixelDimension(style.maxHeight))
popover.style.maxWidth = "none"
positionPopovers = popoverPositioner(settings)
positionPopovers()
popover.classList.add(settings.activeClass)
, 0
activePopover.popover = popover
activePopover.source = source
source.parentNode.appendChild(popover)
window.addEventListener "resize", positionPopovers
window.addEventListener "scroll", positionPopovers
, 0
popover
removePopovers = (settings) ->
return unless activePopover.popover
popover = activePopover.popover
remove = (event) ->
popover.parentNode?.removeChild(popover)
popover.addEventListener "transitionend", remove
popover.addEventListener "webkitTransitionend", remove
popover.classList.remove("is-active")
activePopover = {}
posititionPopovers = undefined
window.removeEventListener "resize", positionPopovers
window.removeEventListener "scroll", positionPopovers
nodeIsDescendantOfNode = (node, ancestorNode) ->
return false unless ancestorNode
while node != document.body
return true if node == ancestorNode
node = node.parentNode
false
nodeIsPopoverDescendant = (node) -> nodeIsDescendantOfNode(node, activePopover.popover)
nodeIsSourceDescendant = (node) -> nodeIsDescendantOfNode(node, activePopover.source)
clickHandler = (event) ->
tryTriggering = !nodeIsSourceDescendant(event.target)
if activePopover.popover && !nodeIsPopoverDescendant(event.target)
removePopovers()
if tryTriggering
popover = Popover.triggerPopoverFor(event.target)
!!popover # prevent default if a popover was triggered
availableSpace = (node) ->
rect = node.getBoundingClientRect()
[topSpace, leftSpace] = [rect.top + 0.5 * rect.height, rect.left + 0.5 * rect.width]
source =
height: rect.height
width: rect.width
windowDimensions =
height: window.innerHeight
width: window.innerWidth
top: topSpace
bottom: windowDimensions.height - topSpace
left: leftSpace
leftRelative: leftSpace / windowDimensions.width
right: windowDimensions.width - leftSpace
window: windowDimensions
source: source
#*
# Calculates the base font size for `em`- and `rem`-based sizing.
#
# @author PI:NAME:<NAME>END_PI (lemonmade)
# @since 0.0.1
# @access private
# @returns {Number} - The base font size in pixels.
baseFontSize = ->
el = document.createElement("div")
el.style.cssText = "display:inline-block;padding:0;line-height:1;position:absolute;visibility:hidden;font-size:1em;"
el.appendChild(document.createElement("M"))
document.body.appendChild(el)
size = el.offsetHeight
document.body.removeChild(el)
size
calculateMaxWidthPixelDimension = (dim, node) ->
calculatePixelDimension(dim, node) || 10000
calculatePixelDimension = (dim, node, makeFFPercentageAdjustment = true) ->
# No value set, make it non-restricting
return 0 if dim == "none"
return parseFloat(dim) * baseFontSize() if dim.indexOf("rem") >= 0
return parseFloat(dim) * parseFloat(window.getComputedStyle(node).fontSize) if dim.indexOf("em") >= 0
return parseFloat(dim) / 100 if dim.indexOf("%") >= 0 || dim.indexOf("vw") >= 0
# Set in px
dim = parseFloat(dim)
# Weird issue in FF where %-based widths would be resolved
# to px before being reported. Assume that smallest possible
# expicitly-set max width is 60px, otherwise, it's the result
# of this calculation.
dim = dim / parseFloat(node.parentNode.offsetWidth) if dim <= 60 && makeFFPercentageAdjustment
dim
oppositeOf = (pos) ->
if pos == POSITIONS.BOTTOM then POSITIONS.TOP else POSITIONS.BOTTOM
setPopoverWidth = (maxWidthRelativeTo, preferredPosition) ->
maxWidth = parseFloat(activePopover.popover.getAttribute(ATTR_CSS_MAX_WIDTH))
wrap = dom.find(activePopover.popover, ".bigfoot-footnote__wrapper")
if maxWidth <= 1
# Max width in CSS set as a percentage
# If a relative element has been set for max width, the actual max width
# by which to multiply the percentage is the lesser of the element's width
# and the width of the viewport
relativeToWidth = do ->
# Width of user-specified element width, set to non-constraining
# value in case it does not exist
userSpecifiedRelativeElWidth = 10000
if maxWidthRelativeTo
el = dom.one(maxWidthRelativeTo)
userSpecifiedRelativeElWidth = el.offsetWidth if el
Math.min(window.innerWidth, userSpecifiedRelativeElWidth)
# Applicable constraining width times the percentage in CSS
maxWidth = relativeToWidth * maxWidth
# Set the max width to the smaller of the calculated width based on the
# percentage/ other value and the width of the actual content (prevents
# excess width for small footnotes)
maxWidth = Math.min(maxWidth, dom.find(activePopover.popover, ".bigfoot-footnote__content").offsetWidth + 1)
# Set this on the main wrapper. This allows the bigfoot-footnote div
# to be displayed as inline-block, wrapping it around the content.
wrap.style.maxWidth = "#{maxWidth}px"
setPopoverHeight = (space, position) ->
maxHeight = parseFloat(activePopover.popover.getAttribute(ATTR_CSS_MAX_HEIGHT))
popover = activePopover.popover
popoverStyles = window.getComputedStyle(popover)
marginSize = calculatePixelDimension(popoverStyles.marginTop, popover, false) + calculatePixelDimension(popoverStyles.marginBottom, popover, false)
popoverHeight = popover.offsetHeight + marginSize
opposite = oppositeOf(position)
position = opposite if space[position] < popoverHeight && space[position] < space[opposite]
transformOrigin = "#{space.leftRelative * 100}% top 0"
if position == POSITIONS.TOP
popover.classList.add("is-positioned-top")
popover.classList.remove("is-positioned-bottom")
maxHeight = Math.min(maxHeight, space.top - marginSize)
transformOrigin = "#{space.leftRelative * 100}% bottom 0"
else
popover.classList.add("is-positioned-bottom")
popover.classList.remove("is-positioned-top")
maxHeight = Math.min(maxHeight, space.bottom - marginSize)
popover.style.transformOrigin = transformOrigin
content = dom.find(popover, ".bigfoot-footnote__content")
content.style.maxHeight = "#{maxHeight}px"
positionTooltip = (space, popover) ->
tooltip = dom.find(activePopover.popover, ".bigfoot-footnote__tooltip")
tooltip.style.left = "#{popover.offsetWidth * space.leftRelative + 2}px" if tooltip
popoverPositioner = (settings) ->
(event) ->
type = event?.type || "resize"
return unless settings.positionPopovers && activePopover.popover
[popover, source] = [activePopover.popover, activePopover.source]
sourceStyles = window.getComputedStyle(source)
space = availableSpace(source)
setPopoverHeight(space, settings.preferredPosition)
setPopoverWidth(settings.maxWidthRelativeTo) if type == "resize"
positionTooltip(space, popover)
popover.style.marginLeft = "#{-1 * space.leftRelative * popover.offsetWidth + space.source.width / 2 + calculatePixelDimension(sourceStyles.marginLeft, source)}px"
popoverDefaults =
preferredPosition: POSITIONS.BOTTOM
positionPopovers: true
debounce: false
preventPageScroll: true
activeClass: "is-active"
inactiveClass: "popover--is-inactive"
class Poptart
@POSITIONS = POSITIONS
@registerPopover: (selector, options, callback) ->
if typeof options == "function"
options =
callback: options
else
options.callback = options
settings = obj.merge(obj.clone(popoverDefaults), options)
registeredSelectors[selector] = settings
@triggerPopoverFor: (node) ->
settings = undefined
for selector, setting of registeredSelectors
if event.target.webkitMatchesSelector(selector)
settings = setting
break
triggerPopover(node, settings) if settings
document.addEventListener "click", clickHandler
document.addEventListener "touchend", clickHandler
module.exports = Poptart
|
[
{
"context": "http://localhost:7001/account'\n siteUrl: 'http://115.28.192.208:7001'\n weiboLogin: \"http://localhost:7001/accoun",
"end": 356,
"score": 0.9996227622032166,
"start": 342,
"tag": "IP_ADDRESS",
"value": "115.28.192.208"
}
] | talk-account/config/default.coffee | lzh5531773/talk | 1 | countries = require './util/countries'
module.exports =
env: 'static'
debug: true
cdn: '/account'
isMinified: no
webpackDevPort: 8011
useCDN: no
checkToken: 'Check token for heartbeat'
resourceDomain: 'http://localhost:7001/account'
useAnalytics: no
# URL
accountUrl: 'http://localhost:7001/account'
siteUrl: 'http://115.28.192.208:7001'
weiboLogin: "http://localhost:7001/account/union/weibo?method=bind&next_url=#{encodeURIComponent 'http://localhost:7001/v2/weibo/landing'}",
firimLogin: "http://localhost:7001/account/union/firim?method=bind&next_url=#{encodeURIComponent 'http://localhost:7001/v2/firim/landing'}",
githubLogin: "http://localhost:7001/account/union/github?method=bind&service=talk&nologin=1&next_url=#{encodeURIComponent 'http://localhost:7001/v2/github/landing'}",
trelloLogin: "http://localhost:7001/account/union/trello?method=bind&next_url=#{encodeURIComponent 'http://localhost:7001/v2/trello/landing'}",
teambitionLogin: "http://localhost:7001/account/union/teambition?method=bind&next_url=#{encodeURIComponent 'http://localhost:7001/v2/teambtion/landing'}",
# Cookies
cookieDomain: '.localhost'
accountCookieId: 'aid'
accountCookieSecret: 'Cookie secret of account'
accountCookieExpires: 2592000
# Connections
mongo:
address: 'mongodb://localhost:27017/talk_account'
redis:
host: 'localhost'
# Client
client:
countries: countries
| 25693 | countries = require './util/countries'
module.exports =
env: 'static'
debug: true
cdn: '/account'
isMinified: no
webpackDevPort: 8011
useCDN: no
checkToken: 'Check token for heartbeat'
resourceDomain: 'http://localhost:7001/account'
useAnalytics: no
# URL
accountUrl: 'http://localhost:7001/account'
siteUrl: 'http://172.16.58.3:7001'
weiboLogin: "http://localhost:7001/account/union/weibo?method=bind&next_url=#{encodeURIComponent 'http://localhost:7001/v2/weibo/landing'}",
firimLogin: "http://localhost:7001/account/union/firim?method=bind&next_url=#{encodeURIComponent 'http://localhost:7001/v2/firim/landing'}",
githubLogin: "http://localhost:7001/account/union/github?method=bind&service=talk&nologin=1&next_url=#{encodeURIComponent 'http://localhost:7001/v2/github/landing'}",
trelloLogin: "http://localhost:7001/account/union/trello?method=bind&next_url=#{encodeURIComponent 'http://localhost:7001/v2/trello/landing'}",
teambitionLogin: "http://localhost:7001/account/union/teambition?method=bind&next_url=#{encodeURIComponent 'http://localhost:7001/v2/teambtion/landing'}",
# Cookies
cookieDomain: '.localhost'
accountCookieId: 'aid'
accountCookieSecret: 'Cookie secret of account'
accountCookieExpires: 2592000
# Connections
mongo:
address: 'mongodb://localhost:27017/talk_account'
redis:
host: 'localhost'
# Client
client:
countries: countries
| true | countries = require './util/countries'
module.exports =
env: 'static'
debug: true
cdn: '/account'
isMinified: no
webpackDevPort: 8011
useCDN: no
checkToken: 'Check token for heartbeat'
resourceDomain: 'http://localhost:7001/account'
useAnalytics: no
# URL
accountUrl: 'http://localhost:7001/account'
siteUrl: 'http://PI:IP_ADDRESS:172.16.58.3END_PI:7001'
weiboLogin: "http://localhost:7001/account/union/weibo?method=bind&next_url=#{encodeURIComponent 'http://localhost:7001/v2/weibo/landing'}",
firimLogin: "http://localhost:7001/account/union/firim?method=bind&next_url=#{encodeURIComponent 'http://localhost:7001/v2/firim/landing'}",
githubLogin: "http://localhost:7001/account/union/github?method=bind&service=talk&nologin=1&next_url=#{encodeURIComponent 'http://localhost:7001/v2/github/landing'}",
trelloLogin: "http://localhost:7001/account/union/trello?method=bind&next_url=#{encodeURIComponent 'http://localhost:7001/v2/trello/landing'}",
teambitionLogin: "http://localhost:7001/account/union/teambition?method=bind&next_url=#{encodeURIComponent 'http://localhost:7001/v2/teambtion/landing'}",
# Cookies
cookieDomain: '.localhost'
accountCookieId: 'aid'
accountCookieSecret: 'Cookie secret of account'
accountCookieExpires: 2592000
# Connections
mongo:
address: 'mongodb://localhost:27017/talk_account'
redis:
host: 'localhost'
# Client
client:
countries: countries
|
[
{
"context": "duct/i, (res) ->\n res.send \"https://github.com/Data4Democracy/read-this-first/blob/master/Code-of-Conduct.md\"\n\n",
"end": 717,
"score": 0.9994180202484131,
"start": 703,
"tag": "USERNAME",
"value": "Data4Democracy"
},
{
"context": "docs/i, (res) ->\n res.send ... | scripts/commands.coffee | Data4Democracy/slackbot | 0 | # Description:
# Remind members about our code of conduct
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# hubot !conduct - Remind the channel about the D4D code of conduct
# hubot !docs - list important documents
# hubot !idea - Steps to getting a new project started
# hubot !new project
# hubot !project lead
# hubot !nonprofit - Details D4D's nonprofit status
# hubot !feedback - Instructions of how to leave feedback and report bugs for the slackbot
# hubot !onboard - Displays onboarding instructions
onboardingMessage = require('../lib/onboarding-message')
module.exports = (robot) ->
robot.hear /!conduct/i, (res) ->
res.send "https://github.com/Data4Democracy/read-this-first/blob/master/Code-of-Conduct.md"
robot.hear /!docs/i, (res) ->
res.send "https://github.com/Data4Democracy/read-this-first"
robot.hear /!idea/i, (res) ->
res.send "https://github.com/Data4Democracy/project-ideas"
robot.hear /!new project/i, (res) ->
res.send "https://github.com/Data4Democracy/read-this-first/blob/master/new-project-template.md"
robot.hear /!project lead/i, (res) ->
res.send "https://github.com/Data4Democracy/read-this-first/blob/master/lead-role-description.md"
res.send "https://github.com/Data4Democracy/read-this-first/blob/master/example_lead_routine.md"
robot.hear /!feedback/i, (res) ->
res.send "Please leave feedback for anything related to the bot in a GitHub issue inside the bot repository."
res.send "https://github.com/Data4Democracy/slackbot/"
robot.hear /!nonprofit/i, (res) ->
res.send "Data for Democracy applied for independent non-profit status in early 2018 and receives grant funds and donations through its fiscal sponsor, The Hopewell Fund. We have recently convened a community body to seek board members. If you are interested, please email team@datafordemocracy.org"
robot.hear /!onboard/i, (res) ->
res.send onboardingMessage
| 37494 | # Description:
# Remind members about our code of conduct
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# hubot !conduct - Remind the channel about the D4D code of conduct
# hubot !docs - list important documents
# hubot !idea - Steps to getting a new project started
# hubot !new project
# hubot !project lead
# hubot !nonprofit - Details D4D's nonprofit status
# hubot !feedback - Instructions of how to leave feedback and report bugs for the slackbot
# hubot !onboard - Displays onboarding instructions
onboardingMessage = require('../lib/onboarding-message')
module.exports = (robot) ->
robot.hear /!conduct/i, (res) ->
res.send "https://github.com/Data4Democracy/read-this-first/blob/master/Code-of-Conduct.md"
robot.hear /!docs/i, (res) ->
res.send "https://github.com/Data4Democracy/read-this-first"
robot.hear /!idea/i, (res) ->
res.send "https://github.com/Data4Democracy/project-ideas"
robot.hear /!new project/i, (res) ->
res.send "https://github.com/Data4Democracy/read-this-first/blob/master/new-project-template.md"
robot.hear /!project lead/i, (res) ->
res.send "https://github.com/Data4Democracy/read-this-first/blob/master/lead-role-description.md"
res.send "https://github.com/Data4Democracy/read-this-first/blob/master/example_lead_routine.md"
robot.hear /!feedback/i, (res) ->
res.send "Please leave feedback for anything related to the bot in a GitHub issue inside the bot repository."
res.send "https://github.com/Data4Democracy/slackbot/"
robot.hear /!nonprofit/i, (res) ->
res.send "Data for Democracy applied for independent non-profit status in early 2018 and receives grant funds and donations through its fiscal sponsor, The Hopewell Fund. We have recently convened a community body to seek board members. If you are interested, please email <EMAIL>"
robot.hear /!onboard/i, (res) ->
res.send onboardingMessage
| true | # Description:
# Remind members about our code of conduct
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# hubot !conduct - Remind the channel about the D4D code of conduct
# hubot !docs - list important documents
# hubot !idea - Steps to getting a new project started
# hubot !new project
# hubot !project lead
# hubot !nonprofit - Details D4D's nonprofit status
# hubot !feedback - Instructions of how to leave feedback and report bugs for the slackbot
# hubot !onboard - Displays onboarding instructions
onboardingMessage = require('../lib/onboarding-message')
module.exports = (robot) ->
robot.hear /!conduct/i, (res) ->
res.send "https://github.com/Data4Democracy/read-this-first/blob/master/Code-of-Conduct.md"
robot.hear /!docs/i, (res) ->
res.send "https://github.com/Data4Democracy/read-this-first"
robot.hear /!idea/i, (res) ->
res.send "https://github.com/Data4Democracy/project-ideas"
robot.hear /!new project/i, (res) ->
res.send "https://github.com/Data4Democracy/read-this-first/blob/master/new-project-template.md"
robot.hear /!project lead/i, (res) ->
res.send "https://github.com/Data4Democracy/read-this-first/blob/master/lead-role-description.md"
res.send "https://github.com/Data4Democracy/read-this-first/blob/master/example_lead_routine.md"
robot.hear /!feedback/i, (res) ->
res.send "Please leave feedback for anything related to the bot in a GitHub issue inside the bot repository."
res.send "https://github.com/Data4Democracy/slackbot/"
robot.hear /!nonprofit/i, (res) ->
res.send "Data for Democracy applied for independent non-profit status in early 2018 and receives grant funds and donations through its fiscal sponsor, The Hopewell Fund. We have recently convened a community body to seek board members. If you are interested, please email PI:EMAIL:<EMAIL>END_PI"
robot.hear /!onboard/i, (res) ->
res.send onboardingMessage
|
[
{
"context": "NDPOINTS = require('./api/endpoints')\n\nENV_KEY = 'StahkPhotos-Env'\n\nSTATIC_ROUTES =\n '/integrate': 'integrate'\n '",
"end": 191,
"score": 0.9995172619819641,
"start": 176,
"tag": "KEY",
"value": "StahkPhotos-Env"
}
] | src/backend/router.coffee | geekjuice/StahkPhotos | 8 | ###
Router
###
_ = require('lodash')
errorHandler = require('errorhandler')
Enviro = require('./lib/enviro')
ENDPOINTS = require('./api/endpoints')
ENV_KEY = 'StahkPhotos-Env'
STATIC_ROUTES =
'/integrate': 'integrate'
'/': 'index'
_route = (file) ->
(req, res, next) ->
res.sendFile("#{__dirname}/public/#{file}.html")
module.exports = (app) ->
## Photo Endpoints
for ENDPOINT in ENDPOINTS
app.use "/#{ENDPOINT}", require("./api/#{ENDPOINT}API")
## List Endpoints
app.use "/endpoints", (req, res, next) ->
res.json
endpoints: ENDPOINTS
fetchedAt: +(new Date)
status: 200
## Random Endpoint
app.use '/random/:debug?', (req, res) ->
{ debug } = req.params
res.redirect("/#{_.sample(ENDPOINTS)}/random/#{debug or ''}")
## Static Routes
for route, file of STATIC_ROUTES
app.use route, _route(file)
## Catch 404
app.get '*', (req, res, next) ->
err = new Error('Not Found')
err.status = 404
next(err)
## Error Handlers
switch
when Enviro.isLocal() or Enviro.isQA()
app.use(errorHandler())
when Enviro.isProd()
app.use (err, req, res, next) ->
res.status(err.status or 500)
res.render 'error',
message: err.message,
error: {}
| 2443 | ###
Router
###
_ = require('lodash')
errorHandler = require('errorhandler')
Enviro = require('./lib/enviro')
ENDPOINTS = require('./api/endpoints')
ENV_KEY = '<KEY>'
STATIC_ROUTES =
'/integrate': 'integrate'
'/': 'index'
_route = (file) ->
(req, res, next) ->
res.sendFile("#{__dirname}/public/#{file}.html")
module.exports = (app) ->
## Photo Endpoints
for ENDPOINT in ENDPOINTS
app.use "/#{ENDPOINT}", require("./api/#{ENDPOINT}API")
## List Endpoints
app.use "/endpoints", (req, res, next) ->
res.json
endpoints: ENDPOINTS
fetchedAt: +(new Date)
status: 200
## Random Endpoint
app.use '/random/:debug?', (req, res) ->
{ debug } = req.params
res.redirect("/#{_.sample(ENDPOINTS)}/random/#{debug or ''}")
## Static Routes
for route, file of STATIC_ROUTES
app.use route, _route(file)
## Catch 404
app.get '*', (req, res, next) ->
err = new Error('Not Found')
err.status = 404
next(err)
## Error Handlers
switch
when Enviro.isLocal() or Enviro.isQA()
app.use(errorHandler())
when Enviro.isProd()
app.use (err, req, res, next) ->
res.status(err.status or 500)
res.render 'error',
message: err.message,
error: {}
| true | ###
Router
###
_ = require('lodash')
errorHandler = require('errorhandler')
Enviro = require('./lib/enviro')
ENDPOINTS = require('./api/endpoints')
ENV_KEY = 'PI:KEY:<KEY>END_PI'
STATIC_ROUTES =
'/integrate': 'integrate'
'/': 'index'
_route = (file) ->
(req, res, next) ->
res.sendFile("#{__dirname}/public/#{file}.html")
module.exports = (app) ->
## Photo Endpoints
for ENDPOINT in ENDPOINTS
app.use "/#{ENDPOINT}", require("./api/#{ENDPOINT}API")
## List Endpoints
app.use "/endpoints", (req, res, next) ->
res.json
endpoints: ENDPOINTS
fetchedAt: +(new Date)
status: 200
## Random Endpoint
app.use '/random/:debug?', (req, res) ->
{ debug } = req.params
res.redirect("/#{_.sample(ENDPOINTS)}/random/#{debug or ''}")
## Static Routes
for route, file of STATIC_ROUTES
app.use route, _route(file)
## Catch 404
app.get '*', (req, res, next) ->
err = new Error('Not Found')
err.status = 404
next(err)
## Error Handlers
switch
when Enviro.isLocal() or Enviro.isQA()
app.use(errorHandler())
when Enviro.isProd()
app.use (err, req, res, next) ->
res.status(err.status or 500)
res.render 'error',
message: err.message,
error: {}
|
[
{
"context": "uire '../index'\ntwitterKeys = {\n consumer_key : 'XXXXXXXXXXXXXXXXXXXXXXXXX',\n consumer_secret : 'XXXXXXXXXXXXXXXXXXXXXXXXXX",
"end": 199,
"score": 0.9985719919204712,
"start": 174,
"tag": "KEY",
"value": "XXXXXXXXXXXXXXXXXXXXXXXXX"
},
{
"context": "'XXXXXXXXXXXXXXX... | test/search-tweets.test.coffee | Lissy93/fetch-tweets | 1 | # Testing frameworks and tools
expect = require('chai').expect
sinon = require('sinon')
# Modules to test
fetchTweets = require '../index'
twitterKeys = {
consumer_key : 'XXXXXXXXXXXXXXXXXXXXXXXXX',
consumer_secret : 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
};
# Fake data to use as sinon stubs
fakeData1 = require './fake-data/search-tweets-fake-data1'
fakeData2 = require './fake-data/search-tweets-fake-data2'
fakeData3 = require './fake-data/search-tweets-fake-data3'
# Set up sinon stubs
ftModuleShort = new fetchTweets(twitterKeys)
ftModuleLong = new fetchTweets(twitterKeys, false) # will return full output
callback1 = sinon.stub(ftModuleShort, "byTopic")
callback1.withArgs({q: 'awesome', count: 3}).returns(fakeData1);
callback1.withArgs('banana').returns(fakeData3);
callback2 = sinon.stub(ftModuleLong, "byTopic")
callback2.withArgs({q: 'javascript', count: 5}).returns(fakeData2);
describe 'Check the search tweets methods work as they should', ()->
it 'Should accept a json object with Twtter options', ()->
expect(callback1({q: 'awesome', count: 3})).equal(fakeData1)
it 'Should return full output for specified object', ()->
expect(callback2({q: 'javascript', count: 5})).equal(fakeData2)
it 'Should also accept a plain string input', ()->
expect(callback1('banana')).equal(fakeData3)
| 88058 | # Testing frameworks and tools
expect = require('chai').expect
sinon = require('sinon')
# Modules to test
fetchTweets = require '../index'
twitterKeys = {
consumer_key : '<KEY>',
consumer_secret : '<KEY>'
};
# Fake data to use as sinon stubs
fakeData1 = require './fake-data/search-tweets-fake-data1'
fakeData2 = require './fake-data/search-tweets-fake-data2'
fakeData3 = require './fake-data/search-tweets-fake-data3'
# Set up sinon stubs
ftModuleShort = new fetchTweets(twitterKeys)
ftModuleLong = new fetchTweets(twitterKeys, false) # will return full output
callback1 = sinon.stub(ftModuleShort, "byTopic")
callback1.withArgs({q: 'awesome', count: 3}).returns(fakeData1);
callback1.withArgs('banana').returns(fakeData3);
callback2 = sinon.stub(ftModuleLong, "byTopic")
callback2.withArgs({q: 'javascript', count: 5}).returns(fakeData2);
describe 'Check the search tweets methods work as they should', ()->
it 'Should accept a json object with Twtter options', ()->
expect(callback1({q: 'awesome', count: 3})).equal(fakeData1)
it 'Should return full output for specified object', ()->
expect(callback2({q: 'javascript', count: 5})).equal(fakeData2)
it 'Should also accept a plain string input', ()->
expect(callback1('banana')).equal(fakeData3)
| true | # Testing frameworks and tools
expect = require('chai').expect
sinon = require('sinon')
# Modules to test
fetchTweets = require '../index'
twitterKeys = {
consumer_key : 'PI:KEY:<KEY>END_PI',
consumer_secret : 'PI:KEY:<KEY>END_PI'
};
# Fake data to use as sinon stubs
fakeData1 = require './fake-data/search-tweets-fake-data1'
fakeData2 = require './fake-data/search-tweets-fake-data2'
fakeData3 = require './fake-data/search-tweets-fake-data3'
# Set up sinon stubs
ftModuleShort = new fetchTweets(twitterKeys)
ftModuleLong = new fetchTweets(twitterKeys, false) # will return full output
callback1 = sinon.stub(ftModuleShort, "byTopic")
callback1.withArgs({q: 'awesome', count: 3}).returns(fakeData1);
callback1.withArgs('banana').returns(fakeData3);
callback2 = sinon.stub(ftModuleLong, "byTopic")
callback2.withArgs({q: 'javascript', count: 5}).returns(fakeData2);
describe 'Check the search tweets methods work as they should', ()->
it 'Should accept a json object with Twtter options', ()->
expect(callback1({q: 'awesome', count: 3})).equal(fakeData1)
it 'Should return full output for specified object', ()->
expect(callback2({q: 'javascript', count: 5})).equal(fakeData2)
it 'Should also accept a plain string input', ()->
expect(callback1('banana')).equal(fakeData3)
|
[
{
"context": "th.split '.'\n len = path.length\n\n key = path.pop()\n obj = @\n\n if len > 1\n if withoutDel",
"end": 2316,
"score": 0.7521904706954956,
"start": 2313,
"tag": "KEY",
"value": "pop"
}
] | src/observable/observable_base.coffee | creasty-sandbox/leaf | 0 |
class Leaf.ObservableBase extends Leaf.Class
__observable: true
@mixin Leaf.Cacheable, Leaf.Accessible
constructor: (data) ->
@initMixin Leaf.Cacheable, Leaf.Accessible
@_dependents = {}
@_tracked = {}
@_tracking = {}
@_delegates = {}
@_propagateHandlers = {}
@_emitter = new Leaf.EventEmitter()
@compiler = new Leaf.ExpressionCompiler @
@setData data
setData: (data, accessor) ->
regulateKeypath: (keypath) ->
return '' unless keypath?
String(keypath)
.replace(/^this\.?/, '')
.replace(/\[(\d+)\]/g, '.$1')
_buildKeypath: (paths...) -> _.compact(paths).join '.'
# Propagation
#-----------------------------------------------
_catchPropagatedEvents: (key) ->
return if @_propagateHandlers[key]
obj = @_data[key]
return unless obj && obj.__observable
general = (e, args...) =>
e = e.clone()
e.keypath = @_buildKeypath key, e.keypath
e.propagated = true
e.propagatedKeypath = e.keypath.split('.')[0...-1].join '.'
@trigger e, args...
detach = (e) =>
@unset @_buildKeypath(key, e.keypath)
handler = @_propagateHandlers[key] = { general, detach }
obj.on 'detach', handler.detach
obj.on handler.general
_uncatchPropagatedEvents: (key) ->
return unless @_propagateHandlers[key]
obj = @_data[key]
handler = @_propagateHandlers[key]
@_propagateHandlers[key] = null
obj.off 'detach', handler.detach
obj.off handler.general
# Batch
#-----------------------------------------------
beginBatch: ->
@_inBatch = true
@_batchTracker ?= new Leaf.AffectedKeypathTracker @, 'set'
endBatch: ->
return unless @_inBatch
tracker = @_batchTracker
@_inBatch = false
@_batchTracker = null
keypaths = tracker.getAffectedKeypaths()
_(keypaths).forEach (keypath) =>
{ obj, key } = @getTerminalObjectForKeypath keypath
event = new Leaf.Event
name: 'set'
keypath: key
if obj && obj.__observable
obj.trigger event, obj._get(key)
# Getter
#-----------------------------------------------
getTerminalObjectForKeypath: (keypath, withoutDelegation) ->
keypath = @regulateKeypath keypath
path = keypath.split '.'
len = path.length
key = path.pop()
obj = @
if len > 1
if withoutDelegation
obj = obj._data[p] while obj && obj.__observable && (p = path.shift())
else
obj = obj._delegates[p]?.obj._data[p] ? obj._data[p] while obj && obj.__observable && (p = path.shift())
else if !withoutDelegation
obj = @_delegates[key]?.obj ? @
{ obj, key }
_get: (key) ->
return @ unless key?
return @_delegates[key].obj._get key if @_delegates[key]
e = new Leaf.Event
name: 'get'
keypath: key
@trigger e
val = @_data[key]
if _.isFunction val
tracker = new Leaf.AffectedKeypathTracker @, 'get' unless @_dependents[key]
fn = val
val = fn.call @
fn._cachedValue = val
if tracker
dependents = tracker.getAffectedKeypaths()
@_dependents[key] = dependents
_(dependents).forEach (dependent) =>
@on 'set', (e) =>
return unless dependent == e.keypath
event = new Leaf.Event
name: 'update'
keypath: key
oldValue = fn._cachedValue
newValue = fn.call @
fn._cachedValue = newValue
@trigger event, newValue, oldValue
val
get: (keypath) ->
{ obj, key } = @getTerminalObjectForKeypath keypath
obj?._get key
# Setter
#-----------------------------------------------
_set: (key, val, options = {}) ->
return unless key
if (delegate = @_delegates[key])
if options.withoutDelegation
@undelegate key
else
return delegate.obj._set key, val, options
options.notify ?= true
@_accessor key
oldValue = @_get key
if _.isFunction @_data[key]
@_data[key].call @, val
else
val = Leaf.Observable val
@_uncatchPropagatedEvents key
@_data[key] = val
@_catchPropagatedEvents key
if options.notify
e = new Leaf.Event
name: 'set'
keypath: key
@trigger e, val, oldValue
val
set: ->
{ keypath, val, options, pairs } = _.polymorphic
'oo?': 'pairs options'
's.o?': 'keypath val options'
, arguments
if pairs
for own k, v of pairs
if _.isPlainObject v
@get(k)?.set v, options
else
@set k, v, options
return @
{ obj, key } = @getTerminalObjectForKeypath keypath, options?.withoutDelegation
obj?._set key, val, options
_unset: (key, options) ->
@_set key, undefined, options
unset: (keypath, options) ->
{ obj, key } = @getTerminalObjectForKeypath keypath
obj?._unset key, options
# Event
#-----------------------------------------------
trigger: ->
@_emitter.trigger arguments...
@
on: ->
@_emitter.on arguments...
@
once: ->
@_emitter.once arguments...
@
off: ->
@_emitter.off arguments...
@
# Notify update
#-----------------------------------------------
_update: (key) ->
e = new Leaf.Event
name: 'update'
keypath: key
@trigger e
update: (keypath) ->
{ obj, key } = @getTerminalObjectForKeypath keypath
obj?._update key
observe: ->
{ keypath, callback } = _.polymorphic
's?f': 'keypath callback'
, arguments
keypath = @regulateKeypath keypath
_callback = callback
callback = _.bindContext callback, @, "observer:#{keypath}", (e) =>
if !@_inBatch && (
!keypath \
|| e.keypath == keypath \
|| "#{e.keypath}.".indexOf("#{keypath}.") == 0
)
_callback arguments...
@on 'set', callback
@on 'update', callback
unobserve: ->
{ keypath, callback } = _.polymorphic
's?f': 'keypath callback'
, arguments
keypath = @regulateKeypath keypath
callback = _.bindContext callback, @, "observer:#{keypath}"
@off 'set', callback
@off 'update', callback
# Clone
#-----------------------------------------------
clone: ->
o = new @constructor @_data
o.set key, @_get(key) for own key of @_delegates when obj
o
syncedClone: ->
o = new @constructor()
o.delegate key, @ for own key of @_data
o.delegate key, obj.obj for own key, obj of @_delegates when obj
o
# Delegation
#-----------------------------------------------
delegate: (key, obj) ->
delegate =
obj: obj
handler: => @trigger arguments...
@undelegate key
@_accessor key
@_delegates[key] = delegate
delegate.obj.on delegate.handler
undelegate: (key) ->
return unless (delegate = @_delegates[key])
@_delegates[key] = null
delegate.obj.off delegate.handler
# Detach / destroy
#-----------------------------------------------
detach: ->
@trigger 'detach', @
destroy: ->
@detatch()
@trigger 'destroy', @
@_destroy()
_destroy: ->
@_data = null
@unsetCache @toLeafID()
| 11534 |
class Leaf.ObservableBase extends Leaf.Class
__observable: true
@mixin Leaf.Cacheable, Leaf.Accessible
constructor: (data) ->
@initMixin Leaf.Cacheable, Leaf.Accessible
@_dependents = {}
@_tracked = {}
@_tracking = {}
@_delegates = {}
@_propagateHandlers = {}
@_emitter = new Leaf.EventEmitter()
@compiler = new Leaf.ExpressionCompiler @
@setData data
setData: (data, accessor) ->
regulateKeypath: (keypath) ->
return '' unless keypath?
String(keypath)
.replace(/^this\.?/, '')
.replace(/\[(\d+)\]/g, '.$1')
_buildKeypath: (paths...) -> _.compact(paths).join '.'
# Propagation
#-----------------------------------------------
_catchPropagatedEvents: (key) ->
return if @_propagateHandlers[key]
obj = @_data[key]
return unless obj && obj.__observable
general = (e, args...) =>
e = e.clone()
e.keypath = @_buildKeypath key, e.keypath
e.propagated = true
e.propagatedKeypath = e.keypath.split('.')[0...-1].join '.'
@trigger e, args...
detach = (e) =>
@unset @_buildKeypath(key, e.keypath)
handler = @_propagateHandlers[key] = { general, detach }
obj.on 'detach', handler.detach
obj.on handler.general
_uncatchPropagatedEvents: (key) ->
return unless @_propagateHandlers[key]
obj = @_data[key]
handler = @_propagateHandlers[key]
@_propagateHandlers[key] = null
obj.off 'detach', handler.detach
obj.off handler.general
# Batch
#-----------------------------------------------
beginBatch: ->
@_inBatch = true
@_batchTracker ?= new Leaf.AffectedKeypathTracker @, 'set'
endBatch: ->
return unless @_inBatch
tracker = @_batchTracker
@_inBatch = false
@_batchTracker = null
keypaths = tracker.getAffectedKeypaths()
_(keypaths).forEach (keypath) =>
{ obj, key } = @getTerminalObjectForKeypath keypath
event = new Leaf.Event
name: 'set'
keypath: key
if obj && obj.__observable
obj.trigger event, obj._get(key)
# Getter
#-----------------------------------------------
getTerminalObjectForKeypath: (keypath, withoutDelegation) ->
keypath = @regulateKeypath keypath
path = keypath.split '.'
len = path.length
key = path.<KEY>()
obj = @
if len > 1
if withoutDelegation
obj = obj._data[p] while obj && obj.__observable && (p = path.shift())
else
obj = obj._delegates[p]?.obj._data[p] ? obj._data[p] while obj && obj.__observable && (p = path.shift())
else if !withoutDelegation
obj = @_delegates[key]?.obj ? @
{ obj, key }
_get: (key) ->
return @ unless key?
return @_delegates[key].obj._get key if @_delegates[key]
e = new Leaf.Event
name: 'get'
keypath: key
@trigger e
val = @_data[key]
if _.isFunction val
tracker = new Leaf.AffectedKeypathTracker @, 'get' unless @_dependents[key]
fn = val
val = fn.call @
fn._cachedValue = val
if tracker
dependents = tracker.getAffectedKeypaths()
@_dependents[key] = dependents
_(dependents).forEach (dependent) =>
@on 'set', (e) =>
return unless dependent == e.keypath
event = new Leaf.Event
name: 'update'
keypath: key
oldValue = fn._cachedValue
newValue = fn.call @
fn._cachedValue = newValue
@trigger event, newValue, oldValue
val
get: (keypath) ->
{ obj, key } = @getTerminalObjectForKeypath keypath
obj?._get key
# Setter
#-----------------------------------------------
_set: (key, val, options = {}) ->
return unless key
if (delegate = @_delegates[key])
if options.withoutDelegation
@undelegate key
else
return delegate.obj._set key, val, options
options.notify ?= true
@_accessor key
oldValue = @_get key
if _.isFunction @_data[key]
@_data[key].call @, val
else
val = Leaf.Observable val
@_uncatchPropagatedEvents key
@_data[key] = val
@_catchPropagatedEvents key
if options.notify
e = new Leaf.Event
name: 'set'
keypath: key
@trigger e, val, oldValue
val
set: ->
{ keypath, val, options, pairs } = _.polymorphic
'oo?': 'pairs options'
's.o?': 'keypath val options'
, arguments
if pairs
for own k, v of pairs
if _.isPlainObject v
@get(k)?.set v, options
else
@set k, v, options
return @
{ obj, key } = @getTerminalObjectForKeypath keypath, options?.withoutDelegation
obj?._set key, val, options
_unset: (key, options) ->
@_set key, undefined, options
unset: (keypath, options) ->
{ obj, key } = @getTerminalObjectForKeypath keypath
obj?._unset key, options
# Event
#-----------------------------------------------
trigger: ->
@_emitter.trigger arguments...
@
on: ->
@_emitter.on arguments...
@
once: ->
@_emitter.once arguments...
@
off: ->
@_emitter.off arguments...
@
# Notify update
#-----------------------------------------------
_update: (key) ->
e = new Leaf.Event
name: 'update'
keypath: key
@trigger e
update: (keypath) ->
{ obj, key } = @getTerminalObjectForKeypath keypath
obj?._update key
observe: ->
{ keypath, callback } = _.polymorphic
's?f': 'keypath callback'
, arguments
keypath = @regulateKeypath keypath
_callback = callback
callback = _.bindContext callback, @, "observer:#{keypath}", (e) =>
if !@_inBatch && (
!keypath \
|| e.keypath == keypath \
|| "#{e.keypath}.".indexOf("#{keypath}.") == 0
)
_callback arguments...
@on 'set', callback
@on 'update', callback
unobserve: ->
{ keypath, callback } = _.polymorphic
's?f': 'keypath callback'
, arguments
keypath = @regulateKeypath keypath
callback = _.bindContext callback, @, "observer:#{keypath}"
@off 'set', callback
@off 'update', callback
# Clone
#-----------------------------------------------
clone: ->
o = new @constructor @_data
o.set key, @_get(key) for own key of @_delegates when obj
o
syncedClone: ->
o = new @constructor()
o.delegate key, @ for own key of @_data
o.delegate key, obj.obj for own key, obj of @_delegates when obj
o
# Delegation
#-----------------------------------------------
delegate: (key, obj) ->
delegate =
obj: obj
handler: => @trigger arguments...
@undelegate key
@_accessor key
@_delegates[key] = delegate
delegate.obj.on delegate.handler
undelegate: (key) ->
return unless (delegate = @_delegates[key])
@_delegates[key] = null
delegate.obj.off delegate.handler
# Detach / destroy
#-----------------------------------------------
detach: ->
@trigger 'detach', @
destroy: ->
@detatch()
@trigger 'destroy', @
@_destroy()
_destroy: ->
@_data = null
@unsetCache @toLeafID()
| true |
class Leaf.ObservableBase extends Leaf.Class
__observable: true
@mixin Leaf.Cacheable, Leaf.Accessible
constructor: (data) ->
@initMixin Leaf.Cacheable, Leaf.Accessible
@_dependents = {}
@_tracked = {}
@_tracking = {}
@_delegates = {}
@_propagateHandlers = {}
@_emitter = new Leaf.EventEmitter()
@compiler = new Leaf.ExpressionCompiler @
@setData data
setData: (data, accessor) ->
regulateKeypath: (keypath) ->
return '' unless keypath?
String(keypath)
.replace(/^this\.?/, '')
.replace(/\[(\d+)\]/g, '.$1')
_buildKeypath: (paths...) -> _.compact(paths).join '.'
# Propagation
#-----------------------------------------------
_catchPropagatedEvents: (key) ->
return if @_propagateHandlers[key]
obj = @_data[key]
return unless obj && obj.__observable
general = (e, args...) =>
e = e.clone()
e.keypath = @_buildKeypath key, e.keypath
e.propagated = true
e.propagatedKeypath = e.keypath.split('.')[0...-1].join '.'
@trigger e, args...
detach = (e) =>
@unset @_buildKeypath(key, e.keypath)
handler = @_propagateHandlers[key] = { general, detach }
obj.on 'detach', handler.detach
obj.on handler.general
_uncatchPropagatedEvents: (key) ->
return unless @_propagateHandlers[key]
obj = @_data[key]
handler = @_propagateHandlers[key]
@_propagateHandlers[key] = null
obj.off 'detach', handler.detach
obj.off handler.general
# Batch
#-----------------------------------------------
beginBatch: ->
@_inBatch = true
@_batchTracker ?= new Leaf.AffectedKeypathTracker @, 'set'
endBatch: ->
return unless @_inBatch
tracker = @_batchTracker
@_inBatch = false
@_batchTracker = null
keypaths = tracker.getAffectedKeypaths()
_(keypaths).forEach (keypath) =>
{ obj, key } = @getTerminalObjectForKeypath keypath
event = new Leaf.Event
name: 'set'
keypath: key
if obj && obj.__observable
obj.trigger event, obj._get(key)
# Getter
#-----------------------------------------------
getTerminalObjectForKeypath: (keypath, withoutDelegation) ->
keypath = @regulateKeypath keypath
path = keypath.split '.'
len = path.length
key = path.PI:KEY:<KEY>END_PI()
obj = @
if len > 1
if withoutDelegation
obj = obj._data[p] while obj && obj.__observable && (p = path.shift())
else
obj = obj._delegates[p]?.obj._data[p] ? obj._data[p] while obj && obj.__observable && (p = path.shift())
else if !withoutDelegation
obj = @_delegates[key]?.obj ? @
{ obj, key }
_get: (key) ->
return @ unless key?
return @_delegates[key].obj._get key if @_delegates[key]
e = new Leaf.Event
name: 'get'
keypath: key
@trigger e
val = @_data[key]
if _.isFunction val
tracker = new Leaf.AffectedKeypathTracker @, 'get' unless @_dependents[key]
fn = val
val = fn.call @
fn._cachedValue = val
if tracker
dependents = tracker.getAffectedKeypaths()
@_dependents[key] = dependents
_(dependents).forEach (dependent) =>
@on 'set', (e) =>
return unless dependent == e.keypath
event = new Leaf.Event
name: 'update'
keypath: key
oldValue = fn._cachedValue
newValue = fn.call @
fn._cachedValue = newValue
@trigger event, newValue, oldValue
val
get: (keypath) ->
{ obj, key } = @getTerminalObjectForKeypath keypath
obj?._get key
# Setter
#-----------------------------------------------
_set: (key, val, options = {}) ->
return unless key
if (delegate = @_delegates[key])
if options.withoutDelegation
@undelegate key
else
return delegate.obj._set key, val, options
options.notify ?= true
@_accessor key
oldValue = @_get key
if _.isFunction @_data[key]
@_data[key].call @, val
else
val = Leaf.Observable val
@_uncatchPropagatedEvents key
@_data[key] = val
@_catchPropagatedEvents key
if options.notify
e = new Leaf.Event
name: 'set'
keypath: key
@trigger e, val, oldValue
val
set: ->
{ keypath, val, options, pairs } = _.polymorphic
'oo?': 'pairs options'
's.o?': 'keypath val options'
, arguments
if pairs
for own k, v of pairs
if _.isPlainObject v
@get(k)?.set v, options
else
@set k, v, options
return @
{ obj, key } = @getTerminalObjectForKeypath keypath, options?.withoutDelegation
obj?._set key, val, options
_unset: (key, options) ->
@_set key, undefined, options
unset: (keypath, options) ->
{ obj, key } = @getTerminalObjectForKeypath keypath
obj?._unset key, options
# Event
#-----------------------------------------------
trigger: ->
@_emitter.trigger arguments...
@
on: ->
@_emitter.on arguments...
@
once: ->
@_emitter.once arguments...
@
off: ->
@_emitter.off arguments...
@
# Notify update
#-----------------------------------------------
_update: (key) ->
e = new Leaf.Event
name: 'update'
keypath: key
@trigger e
update: (keypath) ->
{ obj, key } = @getTerminalObjectForKeypath keypath
obj?._update key
observe: ->
{ keypath, callback } = _.polymorphic
's?f': 'keypath callback'
, arguments
keypath = @regulateKeypath keypath
_callback = callback
callback = _.bindContext callback, @, "observer:#{keypath}", (e) =>
if !@_inBatch && (
!keypath \
|| e.keypath == keypath \
|| "#{e.keypath}.".indexOf("#{keypath}.") == 0
)
_callback arguments...
@on 'set', callback
@on 'update', callback
unobserve: ->
{ keypath, callback } = _.polymorphic
's?f': 'keypath callback'
, arguments
keypath = @regulateKeypath keypath
callback = _.bindContext callback, @, "observer:#{keypath}"
@off 'set', callback
@off 'update', callback
# Clone
#-----------------------------------------------
clone: ->
o = new @constructor @_data
o.set key, @_get(key) for own key of @_delegates when obj
o
syncedClone: ->
o = new @constructor()
o.delegate key, @ for own key of @_data
o.delegate key, obj.obj for own key, obj of @_delegates when obj
o
# Delegation
#-----------------------------------------------
delegate: (key, obj) ->
delegate =
obj: obj
handler: => @trigger arguments...
@undelegate key
@_accessor key
@_delegates[key] = delegate
delegate.obj.on delegate.handler
undelegate: (key) ->
return unless (delegate = @_delegates[key])
@_delegates[key] = null
delegate.obj.off delegate.handler
# Detach / destroy
#-----------------------------------------------
detach: ->
@trigger 'detach', @
destroy: ->
@detatch()
@trigger 'destroy', @
@_destroy()
_destroy: ->
@_data = null
@unsetCache @toLeafID()
|
[
{
"context": "\n @el.find(\".zooniverse-login-form input[name='username']\")\n .attr 'placeholder', 'Username'\n\n @e",
"end": 345,
"score": 0.9954664707183838,
"start": 337,
"tag": "USERNAME",
"value": "username"
},
{
"context": "ut[name='username']\")\n .attr 'place... | zooniverse/profile.coffee | zooniverse/floatingforests | 1 | ProfileOverrides =
el: $(".zooniverse-profile")
init: ->
@appendHTML()
@setInputPlaceholders()
appendHTML: ->
@el
.wrapInner "<div class='content'></div>"
.prepend "<div class='secondary-header'><h1>Your Profile</h1></div>"
setInputPlaceholders: ->
@el.find(".zooniverse-login-form input[name='username']")
.attr 'placeholder', 'Username'
@el.find(".zooniverse-login-form input[name='password']")
.attr 'placeholder', 'Password'
module?.exports = ProfileOverrides | 56246 | ProfileOverrides =
el: $(".zooniverse-profile")
init: ->
@appendHTML()
@setInputPlaceholders()
appendHTML: ->
@el
.wrapInner "<div class='content'></div>"
.prepend "<div class='secondary-header'><h1>Your Profile</h1></div>"
setInputPlaceholders: ->
@el.find(".zooniverse-login-form input[name='username']")
.attr 'placeholder', 'Username'
@el.find(".zooniverse-login-form input[name='<PASSWORD>']")
.attr 'placeholder', '<PASSWORD>'
module?.exports = ProfileOverrides | true | ProfileOverrides =
el: $(".zooniverse-profile")
init: ->
@appendHTML()
@setInputPlaceholders()
appendHTML: ->
@el
.wrapInner "<div class='content'></div>"
.prepend "<div class='secondary-header'><h1>Your Profile</h1></div>"
setInputPlaceholders: ->
@el.find(".zooniverse-login-form input[name='username']")
.attr 'placeholder', 'Username'
@el.find(".zooniverse-login-form input[name='PI:PASSWORD:<PASSWORD>END_PI']")
.attr 'placeholder', 'PI:PASSWORD:<PASSWORD>END_PI'
module?.exports = ProfileOverrides |
[
{
"context": "nity game managed by Hubot\n# https://github.com/coryallegory/hubot-cah\n#\n# Dependencies:\n# None\n#\n# Commands",
"end": 101,
"score": 0.966946005821228,
"start": 89,
"tag": "USERNAME",
"value": "coryallegory"
},
{
"context": "ck card and assign a new Card Czar\n... | src/hubot-cah.coffee | coryallegory/hubot-cah | 6 | #
# Description:
# Cards Against Humanity game managed by Hubot
# https://github.com/coryallegory/hubot-cah
#
# Dependencies:
# None
#
# Commands:
# hubot cah help - List cah commands
# hubot cah black - Display a random black card
# hubot cah white - Display a random white card
# hubot cah play - Add yourself to the game
# hubot cah retire - Remove yourself as an active player
# hubot cah czar - Display name of the current Card Czar
# hubot cah players - List active players
# hubot cah leaders - Top five score leaders
# hubot cah score - Display your score
# hubot cah hand - List cards in your hand
# hubot cah submit <#> <#> ... - Indicate white cards to be submitted as an answer, where # indicates card index in hand and amount of white cards submitted corresponds to the amount required by the current black card
# hubot cah answers - List the current white card submissions for the current black card (Card Czar only)
# hubot cah choose <#> - Choose a winning answer (Card Czar only)
# hubot cah status - Display summary of current game
# hubot cah skip - Discard current black card and assign a new Card Czar
#
# Author:
# Cory Metcalfe (corymetcalfe@gmail.com)
#
helpSummary = "_hubot-cah commands:_"
helpSummary += "\ncah help - List cah commands"
helpSummary += "\ncah black - Display a random black card"
helpSummary += "\ncah white - Display a random white card"
helpSummary += "\ncah play - Add yourself to the game"
helpSummary += "\ncah retire - Remove yourself as an active player"
helpSummary += "\ncah czar - Display name of the current Card Czar"
helpSummary += "\ncah players - List active players"
helpSummary += "\ncah leaders - Top five score leaders"
helpSummary += "\ncah score - Display your score"
helpSummary += "\ncah hand - List cards in your hand"
helpSummary += "\ncah submit <#> <#> ... - Indicate white cards to be submitted as an answer, where # indicates card index in hand and amount of white cards submitted corresponds to the amount required by the current black card"
helpSummary += "\ncah answers - List the current white card submissions for the current black card (Card Czar only)"
helpSummary += "\ncah choose <#> - Choose a winning answer (Card Czar only)"
helpSummary += "\ncah status - Display summary of current game"
helpSummary += "\ncah skip - Discard current black card and assign a new Card Czar"
blackBlank = "_____"
blackCards = require('./blackcards.coffee')
whiteCards = require('./whitecards.coffee')
# @return black card text string
random_black_card = () ->
cardIndex = Math.floor(Math.random()*blackCards.length)
return blackCards[cardIndex]
# @return white card text string
random_white_card = () ->
cardIndex = Math.floor(Math.random()*whiteCards.length)
return whiteCards[cardIndex]
db = {
scores: {}, # {<name>: <score>, ...}
activePlayers: [], # [<player name>, ...]
blackCard: random_black_card(), # <card text>
czar: null, # <player name>
hands: {}, # {<name>: [<card text>, <card text>, ...], ...}
answers: [], # [ [<player name>, [<card text>, ...]], ... ]
}
# prune inactive player hands, ensure everyone has five cards
fix_hands = () ->
newHands = {}
for own name, cardArray of db.hands
if name in db.activePlayers
while cardArray.length < 5
cardArray.push random_white_card()
newHands[name] = cardArray
db["hands"] = newHands
# add player to active list
# fix their hand so it contains five cards
# if only player, make them czar
# @param playerName: name of player coming into game
add_player = (playerName) ->
if playerName not in db.activePlayers
db.activePlayers.push playerName
if !db.scores[playerName]?
db.scores[playerName] = 0
cards = []
while cards.length < 5
cards.push random_white_card()
db.hands[playerName] = cards
if db.activePlayers.length == 1
db.czar = playerName
db.blackCard = random_black_card()
# remove player from active list
# remove any associated hands
# if they were czar, assign a new one
# @param playerName: name of player leaving the game
remove_player = (playerName) ->
i = db.activePlayers.indexOf(playerName)
if i >= 0
db.activePlayers.splice(i,1)
if db.hands[playerName]?
delete db.hands[playerName]
if db.czar == playerName
if db.activePlayers.length == 0
db.czar = null
else if i >= db.activePlayers.length
db.czar = db.activePlayers[0]
else
db.czar = db.activePlayers[i]
# combine black and white cards into complete phrase
# @param blackCard: black card text string
# @param whiteCards: array of white card text strings
# @return completed string
generate_phrase = (blackCard, whiteCards) ->
phrase = ""
blackBits = blackCard.split blackBlank
if blackBits.length == 1
phrase += "#{blackCard} *#{whiteCards[0]}*"
else
wi = 0
bi = 0
if blackCard.substring(0, blackBlank.length) == blackBlank
phrase += "*#{whiteCards[0].match(/(.*[a-zA-Z0-9])[^a-zA-Z0-9]*$/i)[0]}*"
wi = 1
while wi < whiteCards.length or bi < blackBits.length
if bi < blackBits.length
phrase += blackBits[bi]
bi++
if wi < whiteCards.length
phrase += "*#{whiteCards[wi].match(/(.*[a-zA-Z0-9])[^a-zA-Z0-9]*$/i)[0]}*"
wi++
return phrase
# remove cards from player hand and add to answers
# @param playerName: player submitting answer
# @param handIndices: indices of cards in player hand
submit_answer = (playerName, handIndices) ->
playerHand = db.hands[playerName]
cards = []
for i in handIndices
cards.push playerHand[i]
for card in cards
i = playerHand.indexOf(card)
playerHand.splice(i,1)
db.answers.push [playerName, cards]
# specify winning card and reset game for next round
# @param answerIndex: if value outside db.answers array range, no winner this round
# @return string for public display
czar_choose_winner = (answerIndex) ->
responseString = "Next round:"
if 0 <= answerIndex and answerIndex < db.answers.length
responseString = "*#{db.blackCard}*"
for answer in db.answers
responseString += "\n#{answer[1][0]}"
responseString += ", #{answer[1][i]}" for i in [1...answer[1].length]
winner = db.answers[answerIndex][0]
cards = db.answers[answerIndex][1]
winningPhrase = generate_phrase(db.blackCard, cards)
responseString += "\n\n#{winner} earns a point for\n*#{winningPhrase}*"
if !db.scores[winner]?
db.scores[winner] = 1
else
db.scores[winner] = db.scores[winner] + 1
db["answers"] = []
fix_hands()
db["blackCard"] = random_black_card()
if db.activePlayers.length == 0
db.czar = null
else if !db.czar?
db.czar = db.activePlayers[0]
else
czarIndex = db.activePlayers.indexOf db.czar
if czarIndex < 0 or czarIndex == db.activePlayers.length-1
db.czar = db.activePlayers[0]
else
db.czar = db.activePlayers[czarIndex+1]
return responseString + "\n\nNext round:\n" + game_state_string()
# generate string describing game state
# czar, black card, number of submissions
game_state_string = () ->
if !db.czar?
return "Waiting for players."
else
return "*#{db.blackCard}* [#{db.czar}, #{db.answers.length}/#{db.activePlayers.length-1}]"
# @param msg: message object
# @return name of message sender
sender = (msg) ->
return msg.message.user.name
module.exports = (robot) ->
robot.respond /cah help$/i, (msg) ->
msg.send helpSummary
robot.respond /cah black$/i, (msg) ->
msg.send random_black_card()
robot.respond /cah white$/i, (msg) ->
msg.send random_white_card()
robot.respond /cah play$/i, (msg) ->
name = sender(msg)
add_player(name)
msg.reply "You are now an active CAH player."
robot.respond /cah retire$/i, (msg) ->
name = sender(msg)
remove_player(name)
msg.reply "You are no longer a CAH player. Your score will be preserved should you decide to play again."
robot.respond /cah czar$/i, (msg) ->
if db.czar?
msg.send db.czar
else
msg.send "No Card Czar yet, waiting for players."
robot.respond /cah players$/i, (msg) ->
if db.activePlayers.length < 1
msg.send "Waiting for players."
else
responseString = "CAH Players: #{db.activePlayers[0]}"
for i in [1...db.activePlayers.length] by 1
responseString += ", #{db.activePlayers[i]}"
msg.send responseString
robot.respond /cah leaders$/i, (msg) ->
scoreTuples = []
for name,score of db.scores
scoreTuples.push([name,score])
scoreTuples.sort (a,b) ->
a = a[1]
b = b[1]
return a < b ? -1 : (a > b ? 1 : 0)
responseString = "CAH Leaders:"
for i in [0...5] by 1
if i >= scoreTuples.length
break
responseString += "\n#{scoreTuples[i][1]} #{scoreTuples[i][0]}"
msg.send responseString
robot.respond /cah score$/i, (msg) ->
score = db.scores[sender(msg)]
if score?
msg.reply score
else
msg.reply "No CAH score on record."
robot.respond /cah hand$/i, (msg) ->
cards = db.hands[sender(msg)]
responseString = "Your white CAH cards:"
if cards?
for i in [0...cards.length] by 1
responseString += "\n#{i}: #{cards[i]}"
msg.reply responseString
robot.respond /cah submit(?: ([0-4]+))+$/i, (msg) ->
if sender(msg) == db.czar
msg.reply "You are currently the Card Czar!"
return
if db.hands[sender(msg)].length < 5
msg.reply "You have already submitted cards for this round."
return
numString = msg.match[0].split("submit ")[1]
nums = numString.split(" ")
expectedCount = db.blackCard.split(blackBlank).length - 1
if expectedCount == 0
expectedCount = 1
if nums.length != expectedCount
msg.reply "You submitted #{nums.length} cards, #{expectedCount} expected."
else
for i in [0...nums.length] by 1
nums[i] = parseInt(nums[i])
if nums[i] >= db.hands[sender(msg)].length
msg.reply "#{nums[i]} is not a valid card number."
return
for i in [0...nums.length] by 1
for j in [i+1...nums.length] by 1
if nums[i] == nums[j]
msg.reply "You cannot submit a single card more than once."
return
submit_answer(sender(msg), nums)
msg.reply "Submission accepted."
robot.respond /cah answers$/i, (msg) ->
if sender(msg) != db.czar
msg.reply "Only the Card Czar may see the white card submissions."
else
answers = db.answers
responseString = "White card submissions thus far:"
for i in [0...answers.length] by 1
cards = answers[i][1]
responseString += "\n#{i}: #{generate_phrase(db.blackCard, cards)}"
msg.reply responseString
robot.respond /cah choose ([0-9]+)$/i, (msg) ->
if sender(msg) != db.czar
msg.reply "Only the Card Czar may choose a winner."
else if db.answers.length == 0
msg.reply "No submissions to choose from yet."
else
num = parseInt(msg.match[1])
if num < 0 or num >= db.answers.length
msg.reply "That is not an valid choice, try again."
else
msg.send czar_choose_winner num
robot.respond /cah status$/i, (msg) ->
msg.send game_state_string()
robot.respond /cah skip$/i, (msg) ->
msg.send czar_choose_winner -1
| 152551 | #
# Description:
# Cards Against Humanity game managed by Hubot
# https://github.com/coryallegory/hubot-cah
#
# Dependencies:
# None
#
# Commands:
# hubot cah help - List cah commands
# hubot cah black - Display a random black card
# hubot cah white - Display a random white card
# hubot cah play - Add yourself to the game
# hubot cah retire - Remove yourself as an active player
# hubot cah czar - Display name of the current Card Czar
# hubot cah players - List active players
# hubot cah leaders - Top five score leaders
# hubot cah score - Display your score
# hubot cah hand - List cards in your hand
# hubot cah submit <#> <#> ... - Indicate white cards to be submitted as an answer, where # indicates card index in hand and amount of white cards submitted corresponds to the amount required by the current black card
# hubot cah answers - List the current white card submissions for the current black card (Card Czar only)
# hubot cah choose <#> - Choose a winning answer (Card Czar only)
# hubot cah status - Display summary of current game
# hubot cah skip - Discard current black card and assign a new Card Czar
#
# Author:
# <NAME> (<EMAIL>)
#
helpSummary = "_hubot-cah commands:_"
helpSummary += "\ncah help - List cah commands"
helpSummary += "\ncah black - Display a random black card"
helpSummary += "\ncah white - Display a random white card"
helpSummary += "\ncah play - Add yourself to the game"
helpSummary += "\ncah retire - Remove yourself as an active player"
helpSummary += "\ncah czar - Display name of the current Card Czar"
helpSummary += "\ncah players - List active players"
helpSummary += "\ncah leaders - Top five score leaders"
helpSummary += "\ncah score - Display your score"
helpSummary += "\ncah hand - List cards in your hand"
helpSummary += "\ncah submit <#> <#> ... - Indicate white cards to be submitted as an answer, where # indicates card index in hand and amount of white cards submitted corresponds to the amount required by the current black card"
helpSummary += "\ncah answers - List the current white card submissions for the current black card (Card Czar only)"
helpSummary += "\ncah choose <#> - Choose a winning answer (Card Czar only)"
helpSummary += "\ncah status - Display summary of current game"
helpSummary += "\ncah skip - Discard current black card and assign a new Card Czar"
blackBlank = "_____"
blackCards = require('./blackcards.coffee')
whiteCards = require('./whitecards.coffee')
# @return black card text string
random_black_card = () ->
cardIndex = Math.floor(Math.random()*blackCards.length)
return blackCards[cardIndex]
# @return white card text string
random_white_card = () ->
cardIndex = Math.floor(Math.random()*whiteCards.length)
return whiteCards[cardIndex]
db = {
scores: {}, # {<name>: <score>, ...}
activePlayers: [], # [<player name>, ...]
blackCard: random_black_card(), # <card text>
czar: null, # <player name>
hands: {}, # {<name>: [<card text>, <card text>, ...], ...}
answers: [], # [ [<player name>, [<card text>, ...]], ... ]
}
# prune inactive player hands, ensure everyone has five cards
fix_hands = () ->
newHands = {}
for own name, cardArray of db.hands
if name in db.activePlayers
while cardArray.length < 5
cardArray.push random_white_card()
newHands[name] = cardArray
db["hands"] = newHands
# add player to active list
# fix their hand so it contains five cards
# if only player, make them czar
# @param playerName: name of player coming into game
add_player = (playerName) ->
if playerName not in db.activePlayers
db.activePlayers.push playerName
if !db.scores[playerName]?
db.scores[playerName] = 0
cards = []
while cards.length < 5
cards.push random_white_card()
db.hands[playerName] = cards
if db.activePlayers.length == 1
db.czar = playerName
db.blackCard = random_black_card()
# remove player from active list
# remove any associated hands
# if they were czar, assign a new one
# @param playerName: name of player leaving the game
remove_player = (playerName) ->
i = db.activePlayers.indexOf(playerName)
if i >= 0
db.activePlayers.splice(i,1)
if db.hands[playerName]?
delete db.hands[playerName]
if db.czar == playerName
if db.activePlayers.length == 0
db.czar = null
else if i >= db.activePlayers.length
db.czar = db.activePlayers[0]
else
db.czar = db.activePlayers[i]
# combine black and white cards into complete phrase
# @param blackCard: black card text string
# @param whiteCards: array of white card text strings
# @return completed string
generate_phrase = (blackCard, whiteCards) ->
phrase = ""
blackBits = blackCard.split blackBlank
if blackBits.length == 1
phrase += "#{blackCard} *#{whiteCards[0]}*"
else
wi = 0
bi = 0
if blackCard.substring(0, blackBlank.length) == blackBlank
phrase += "*#{whiteCards[0].match(/(.*[a-zA-Z0-9])[^a-zA-Z0-9]*$/i)[0]}*"
wi = 1
while wi < whiteCards.length or bi < blackBits.length
if bi < blackBits.length
phrase += blackBits[bi]
bi++
if wi < whiteCards.length
phrase += "*#{whiteCards[wi].match(/(.*[a-zA-Z0-9])[^a-zA-Z0-9]*$/i)[0]}*"
wi++
return phrase
# remove cards from player hand and add to answers
# @param playerName: player submitting answer
# @param handIndices: indices of cards in player hand
submit_answer = (playerName, handIndices) ->
playerHand = db.hands[playerName]
cards = []
for i in handIndices
cards.push playerHand[i]
for card in cards
i = playerHand.indexOf(card)
playerHand.splice(i,1)
db.answers.push [playerName, cards]
# specify winning card and reset game for next round
# @param answerIndex: if value outside db.answers array range, no winner this round
# @return string for public display
czar_choose_winner = (answerIndex) ->
responseString = "Next round:"
if 0 <= answerIndex and answerIndex < db.answers.length
responseString = "*#{db.blackCard}*"
for answer in db.answers
responseString += "\n#{answer[1][0]}"
responseString += ", #{answer[1][i]}" for i in [1...answer[1].length]
winner = db.answers[answerIndex][0]
cards = db.answers[answerIndex][1]
winningPhrase = generate_phrase(db.blackCard, cards)
responseString += "\n\n#{winner} earns a point for\n*#{winningPhrase}*"
if !db.scores[winner]?
db.scores[winner] = 1
else
db.scores[winner] = db.scores[winner] + 1
db["answers"] = []
fix_hands()
db["blackCard"] = random_black_card()
if db.activePlayers.length == 0
db.czar = null
else if !db.czar?
db.czar = db.activePlayers[0]
else
czarIndex = db.activePlayers.indexOf db.czar
if czarIndex < 0 or czarIndex == db.activePlayers.length-1
db.czar = db.activePlayers[0]
else
db.czar = db.activePlayers[czarIndex+1]
return responseString + "\n\nNext round:\n" + game_state_string()
# generate string describing game state
# czar, black card, number of submissions
game_state_string = () ->
if !db.czar?
return "Waiting for players."
else
return "*#{db.blackCard}* [#{db.czar}, #{db.answers.length}/#{db.activePlayers.length-1}]"
# @param msg: message object
# @return name of message sender
sender = (msg) ->
return msg.message.user.name
module.exports = (robot) ->
robot.respond /cah help$/i, (msg) ->
msg.send helpSummary
robot.respond /cah black$/i, (msg) ->
msg.send random_black_card()
robot.respond /cah white$/i, (msg) ->
msg.send random_white_card()
robot.respond /cah play$/i, (msg) ->
name = sender(msg)
add_player(name)
msg.reply "You are now an active CAH player."
robot.respond /cah retire$/i, (msg) ->
name = sender(msg)
remove_player(name)
msg.reply "You are no longer a CAH player. Your score will be preserved should you decide to play again."
robot.respond /cah czar$/i, (msg) ->
if db.czar?
msg.send db.czar
else
msg.send "No Card Czar yet, waiting for players."
robot.respond /cah players$/i, (msg) ->
if db.activePlayers.length < 1
msg.send "Waiting for players."
else
responseString = "CAH Players: #{db.activePlayers[0]}"
for i in [1...db.activePlayers.length] by 1
responseString += ", #{db.activePlayers[i]}"
msg.send responseString
robot.respond /cah leaders$/i, (msg) ->
scoreTuples = []
for name,score of db.scores
scoreTuples.push([name,score])
scoreTuples.sort (a,b) ->
a = a[1]
b = b[1]
return a < b ? -1 : (a > b ? 1 : 0)
responseString = "CAH Leaders:"
for i in [0...5] by 1
if i >= scoreTuples.length
break
responseString += "\n#{scoreTuples[i][1]} #{scoreTuples[i][0]}"
msg.send responseString
robot.respond /cah score$/i, (msg) ->
score = db.scores[sender(msg)]
if score?
msg.reply score
else
msg.reply "No CAH score on record."
robot.respond /cah hand$/i, (msg) ->
cards = db.hands[sender(msg)]
responseString = "Your white CAH cards:"
if cards?
for i in [0...cards.length] by 1
responseString += "\n#{i}: #{cards[i]}"
msg.reply responseString
robot.respond /cah submit(?: ([0-4]+))+$/i, (msg) ->
if sender(msg) == db.czar
msg.reply "You are currently the Card Czar!"
return
if db.hands[sender(msg)].length < 5
msg.reply "You have already submitted cards for this round."
return
numString = msg.match[0].split("submit ")[1]
nums = numString.split(" ")
expectedCount = db.blackCard.split(blackBlank).length - 1
if expectedCount == 0
expectedCount = 1
if nums.length != expectedCount
msg.reply "You submitted #{nums.length} cards, #{expectedCount} expected."
else
for i in [0...nums.length] by 1
nums[i] = parseInt(nums[i])
if nums[i] >= db.hands[sender(msg)].length
msg.reply "#{nums[i]} is not a valid card number."
return
for i in [0...nums.length] by 1
for j in [i+1...nums.length] by 1
if nums[i] == nums[j]
msg.reply "You cannot submit a single card more than once."
return
submit_answer(sender(msg), nums)
msg.reply "Submission accepted."
robot.respond /cah answers$/i, (msg) ->
if sender(msg) != db.czar
msg.reply "Only the Card Czar may see the white card submissions."
else
answers = db.answers
responseString = "White card submissions thus far:"
for i in [0...answers.length] by 1
cards = answers[i][1]
responseString += "\n#{i}: #{generate_phrase(db.blackCard, cards)}"
msg.reply responseString
robot.respond /cah choose ([0-9]+)$/i, (msg) ->
if sender(msg) != db.czar
msg.reply "Only the Card Czar may choose a winner."
else if db.answers.length == 0
msg.reply "No submissions to choose from yet."
else
num = parseInt(msg.match[1])
if num < 0 or num >= db.answers.length
msg.reply "That is not an valid choice, try again."
else
msg.send czar_choose_winner num
robot.respond /cah status$/i, (msg) ->
msg.send game_state_string()
robot.respond /cah skip$/i, (msg) ->
msg.send czar_choose_winner -1
| true | #
# Description:
# Cards Against Humanity game managed by Hubot
# https://github.com/coryallegory/hubot-cah
#
# Dependencies:
# None
#
# Commands:
# hubot cah help - List cah commands
# hubot cah black - Display a random black card
# hubot cah white - Display a random white card
# hubot cah play - Add yourself to the game
# hubot cah retire - Remove yourself as an active player
# hubot cah czar - Display name of the current Card Czar
# hubot cah players - List active players
# hubot cah leaders - Top five score leaders
# hubot cah score - Display your score
# hubot cah hand - List cards in your hand
# hubot cah submit <#> <#> ... - Indicate white cards to be submitted as an answer, where # indicates card index in hand and amount of white cards submitted corresponds to the amount required by the current black card
# hubot cah answers - List the current white card submissions for the current black card (Card Czar only)
# hubot cah choose <#> - Choose a winning answer (Card Czar only)
# hubot cah status - Display summary of current game
# hubot cah skip - Discard current black card and assign a new Card Czar
#
# Author:
# PI:NAME:<NAME>END_PI (PI:EMAIL:<EMAIL>END_PI)
#
helpSummary = "_hubot-cah commands:_"
helpSummary += "\ncah help - List cah commands"
helpSummary += "\ncah black - Display a random black card"
helpSummary += "\ncah white - Display a random white card"
helpSummary += "\ncah play - Add yourself to the game"
helpSummary += "\ncah retire - Remove yourself as an active player"
helpSummary += "\ncah czar - Display name of the current Card Czar"
helpSummary += "\ncah players - List active players"
helpSummary += "\ncah leaders - Top five score leaders"
helpSummary += "\ncah score - Display your score"
helpSummary += "\ncah hand - List cards in your hand"
helpSummary += "\ncah submit <#> <#> ... - Indicate white cards to be submitted as an answer, where # indicates card index in hand and amount of white cards submitted corresponds to the amount required by the current black card"
helpSummary += "\ncah answers - List the current white card submissions for the current black card (Card Czar only)"
helpSummary += "\ncah choose <#> - Choose a winning answer (Card Czar only)"
helpSummary += "\ncah status - Display summary of current game"
helpSummary += "\ncah skip - Discard current black card and assign a new Card Czar"
blackBlank = "_____"
blackCards = require('./blackcards.coffee')
whiteCards = require('./whitecards.coffee')
# @return black card text string
random_black_card = () ->
cardIndex = Math.floor(Math.random()*blackCards.length)
return blackCards[cardIndex]
# @return white card text string
random_white_card = () ->
cardIndex = Math.floor(Math.random()*whiteCards.length)
return whiteCards[cardIndex]
db = {
scores: {}, # {<name>: <score>, ...}
activePlayers: [], # [<player name>, ...]
blackCard: random_black_card(), # <card text>
czar: null, # <player name>
hands: {}, # {<name>: [<card text>, <card text>, ...], ...}
answers: [], # [ [<player name>, [<card text>, ...]], ... ]
}
# prune inactive player hands, ensure everyone has five cards
fix_hands = () ->
newHands = {}
for own name, cardArray of db.hands
if name in db.activePlayers
while cardArray.length < 5
cardArray.push random_white_card()
newHands[name] = cardArray
db["hands"] = newHands
# add player to active list
# fix their hand so it contains five cards
# if only player, make them czar
# @param playerName: name of player coming into game
add_player = (playerName) ->
if playerName not in db.activePlayers
db.activePlayers.push playerName
if !db.scores[playerName]?
db.scores[playerName] = 0
cards = []
while cards.length < 5
cards.push random_white_card()
db.hands[playerName] = cards
if db.activePlayers.length == 1
db.czar = playerName
db.blackCard = random_black_card()
# remove player from active list
# remove any associated hands
# if they were czar, assign a new one
# @param playerName: name of player leaving the game
remove_player = (playerName) ->
i = db.activePlayers.indexOf(playerName)
if i >= 0
db.activePlayers.splice(i,1)
if db.hands[playerName]?
delete db.hands[playerName]
if db.czar == playerName
if db.activePlayers.length == 0
db.czar = null
else if i >= db.activePlayers.length
db.czar = db.activePlayers[0]
else
db.czar = db.activePlayers[i]
# combine black and white cards into complete phrase
# @param blackCard: black card text string
# @param whiteCards: array of white card text strings
# @return completed string
generate_phrase = (blackCard, whiteCards) ->
phrase = ""
blackBits = blackCard.split blackBlank
if blackBits.length == 1
phrase += "#{blackCard} *#{whiteCards[0]}*"
else
wi = 0
bi = 0
if blackCard.substring(0, blackBlank.length) == blackBlank
phrase += "*#{whiteCards[0].match(/(.*[a-zA-Z0-9])[^a-zA-Z0-9]*$/i)[0]}*"
wi = 1
while wi < whiteCards.length or bi < blackBits.length
if bi < blackBits.length
phrase += blackBits[bi]
bi++
if wi < whiteCards.length
phrase += "*#{whiteCards[wi].match(/(.*[a-zA-Z0-9])[^a-zA-Z0-9]*$/i)[0]}*"
wi++
return phrase
# remove cards from player hand and add to answers
# @param playerName: player submitting answer
# @param handIndices: indices of cards in player hand
submit_answer = (playerName, handIndices) ->
playerHand = db.hands[playerName]
cards = []
for i in handIndices
cards.push playerHand[i]
for card in cards
i = playerHand.indexOf(card)
playerHand.splice(i,1)
db.answers.push [playerName, cards]
# specify winning card and reset game for next round
# @param answerIndex: if value outside db.answers array range, no winner this round
# @return string for public display
czar_choose_winner = (answerIndex) ->
responseString = "Next round:"
if 0 <= answerIndex and answerIndex < db.answers.length
responseString = "*#{db.blackCard}*"
for answer in db.answers
responseString += "\n#{answer[1][0]}"
responseString += ", #{answer[1][i]}" for i in [1...answer[1].length]
winner = db.answers[answerIndex][0]
cards = db.answers[answerIndex][1]
winningPhrase = generate_phrase(db.blackCard, cards)
responseString += "\n\n#{winner} earns a point for\n*#{winningPhrase}*"
if !db.scores[winner]?
db.scores[winner] = 1
else
db.scores[winner] = db.scores[winner] + 1
db["answers"] = []
fix_hands()
db["blackCard"] = random_black_card()
if db.activePlayers.length == 0
db.czar = null
else if !db.czar?
db.czar = db.activePlayers[0]
else
czarIndex = db.activePlayers.indexOf db.czar
if czarIndex < 0 or czarIndex == db.activePlayers.length-1
db.czar = db.activePlayers[0]
else
db.czar = db.activePlayers[czarIndex+1]
return responseString + "\n\nNext round:\n" + game_state_string()
# generate string describing game state
# czar, black card, number of submissions
game_state_string = () ->
if !db.czar?
return "Waiting for players."
else
return "*#{db.blackCard}* [#{db.czar}, #{db.answers.length}/#{db.activePlayers.length-1}]"
# @param msg: message object
# @return name of message sender
sender = (msg) ->
return msg.message.user.name
module.exports = (robot) ->
robot.respond /cah help$/i, (msg) ->
msg.send helpSummary
robot.respond /cah black$/i, (msg) ->
msg.send random_black_card()
robot.respond /cah white$/i, (msg) ->
msg.send random_white_card()
robot.respond /cah play$/i, (msg) ->
name = sender(msg)
add_player(name)
msg.reply "You are now an active CAH player."
robot.respond /cah retire$/i, (msg) ->
name = sender(msg)
remove_player(name)
msg.reply "You are no longer a CAH player. Your score will be preserved should you decide to play again."
robot.respond /cah czar$/i, (msg) ->
if db.czar?
msg.send db.czar
else
msg.send "No Card Czar yet, waiting for players."
robot.respond /cah players$/i, (msg) ->
if db.activePlayers.length < 1
msg.send "Waiting for players."
else
responseString = "CAH Players: #{db.activePlayers[0]}"
for i in [1...db.activePlayers.length] by 1
responseString += ", #{db.activePlayers[i]}"
msg.send responseString
robot.respond /cah leaders$/i, (msg) ->
scoreTuples = []
for name,score of db.scores
scoreTuples.push([name,score])
scoreTuples.sort (a,b) ->
a = a[1]
b = b[1]
return a < b ? -1 : (a > b ? 1 : 0)
responseString = "CAH Leaders:"
for i in [0...5] by 1
if i >= scoreTuples.length
break
responseString += "\n#{scoreTuples[i][1]} #{scoreTuples[i][0]}"
msg.send responseString
robot.respond /cah score$/i, (msg) ->
score = db.scores[sender(msg)]
if score?
msg.reply score
else
msg.reply "No CAH score on record."
robot.respond /cah hand$/i, (msg) ->
cards = db.hands[sender(msg)]
responseString = "Your white CAH cards:"
if cards?
for i in [0...cards.length] by 1
responseString += "\n#{i}: #{cards[i]}"
msg.reply responseString
robot.respond /cah submit(?: ([0-4]+))+$/i, (msg) ->
if sender(msg) == db.czar
msg.reply "You are currently the Card Czar!"
return
if db.hands[sender(msg)].length < 5
msg.reply "You have already submitted cards for this round."
return
numString = msg.match[0].split("submit ")[1]
nums = numString.split(" ")
expectedCount = db.blackCard.split(blackBlank).length - 1
if expectedCount == 0
expectedCount = 1
if nums.length != expectedCount
msg.reply "You submitted #{nums.length} cards, #{expectedCount} expected."
else
for i in [0...nums.length] by 1
nums[i] = parseInt(nums[i])
if nums[i] >= db.hands[sender(msg)].length
msg.reply "#{nums[i]} is not a valid card number."
return
for i in [0...nums.length] by 1
for j in [i+1...nums.length] by 1
if nums[i] == nums[j]
msg.reply "You cannot submit a single card more than once."
return
submit_answer(sender(msg), nums)
msg.reply "Submission accepted."
robot.respond /cah answers$/i, (msg) ->
if sender(msg) != db.czar
msg.reply "Only the Card Czar may see the white card submissions."
else
answers = db.answers
responseString = "White card submissions thus far:"
for i in [0...answers.length] by 1
cards = answers[i][1]
responseString += "\n#{i}: #{generate_phrase(db.blackCard, cards)}"
msg.reply responseString
robot.respond /cah choose ([0-9]+)$/i, (msg) ->
if sender(msg) != db.czar
msg.reply "Only the Card Czar may choose a winner."
else if db.answers.length == 0
msg.reply "No submissions to choose from yet."
else
num = parseInt(msg.match[1])
if num < 0 or num >= db.answers.length
msg.reply "That is not an valid choice, try again."
else
msg.send czar_choose_winner num
robot.respond /cah status$/i, (msg) ->
msg.send game_state_string()
robot.respond /cah skip$/i, (msg) ->
msg.send czar_choose_winner -1
|
[
{
"context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission",
"end": 18,
"score": 0.9992457032203674,
"start": 12,
"tag": "NAME",
"value": "Joyent"
}
] | lib/os.coffee | lxe/io.coffee | 0 | # Copyright Joyent, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
"use strict"
binding = process.binding("os")
util = require("util")
isWindows = process.platform is "win32"
exports.hostname = binding.getHostname
exports.loadavg = binding.getLoadAvg
exports.uptime = binding.getUptime
exports.freemem = binding.getFreeMem
exports.totalmem = binding.getTotalMem
exports.cpus = binding.getCPUs
exports.type = binding.getOSType
exports.release = binding.getOSRelease
exports.networkInterfaces = binding.getInterfaceAddresses
exports.arch = ->
process.arch
exports.platform = ->
process.platform
exports.tmpdir = ->
if isWindows
process.env.TEMP or process.env.TMP or (process.env.SystemRoot or process.env.windir) + "\\temp"
else
process.env.TMPDIR or process.env.TMP or process.env.TEMP or "/tmp"
exports.tmpDir = exports.tmpdir
exports.getNetworkInterfaces = util.deprecate(->
exports.networkInterfaces()
, "getNetworkInterfaces is now called `os.networkInterfaces`.")
exports.EOL = (if isWindows then "\r\n" else "\n")
if binding.isBigEndian
exports.endianness = ->
"BE"
else
exports.endianness = ->
"LE"
| 13999 | # 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.
"use strict"
binding = process.binding("os")
util = require("util")
isWindows = process.platform is "win32"
exports.hostname = binding.getHostname
exports.loadavg = binding.getLoadAvg
exports.uptime = binding.getUptime
exports.freemem = binding.getFreeMem
exports.totalmem = binding.getTotalMem
exports.cpus = binding.getCPUs
exports.type = binding.getOSType
exports.release = binding.getOSRelease
exports.networkInterfaces = binding.getInterfaceAddresses
exports.arch = ->
process.arch
exports.platform = ->
process.platform
exports.tmpdir = ->
if isWindows
process.env.TEMP or process.env.TMP or (process.env.SystemRoot or process.env.windir) + "\\temp"
else
process.env.TMPDIR or process.env.TMP or process.env.TEMP or "/tmp"
exports.tmpDir = exports.tmpdir
exports.getNetworkInterfaces = util.deprecate(->
exports.networkInterfaces()
, "getNetworkInterfaces is now called `os.networkInterfaces`.")
exports.EOL = (if isWindows then "\r\n" else "\n")
if binding.isBigEndian
exports.endianness = ->
"BE"
else
exports.endianness = ->
"LE"
| 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.
"use strict"
binding = process.binding("os")
util = require("util")
isWindows = process.platform is "win32"
exports.hostname = binding.getHostname
exports.loadavg = binding.getLoadAvg
exports.uptime = binding.getUptime
exports.freemem = binding.getFreeMem
exports.totalmem = binding.getTotalMem
exports.cpus = binding.getCPUs
exports.type = binding.getOSType
exports.release = binding.getOSRelease
exports.networkInterfaces = binding.getInterfaceAddresses
exports.arch = ->
process.arch
exports.platform = ->
process.platform
exports.tmpdir = ->
if isWindows
process.env.TEMP or process.env.TMP or (process.env.SystemRoot or process.env.windir) + "\\temp"
else
process.env.TMPDIR or process.env.TMP or process.env.TEMP or "/tmp"
exports.tmpDir = exports.tmpdir
exports.getNetworkInterfaces = util.deprecate(->
exports.networkInterfaces()
, "getNetworkInterfaces is now called `os.networkInterfaces`.")
exports.EOL = (if isWindows then "\r\n" else "\n")
if binding.isBigEndian
exports.endianness = ->
"BE"
else
exports.endianness = ->
"LE"
|
[
{
"context": "fields--MD Text Field and MD Text Area.\n * @author Derek Gransaull <derek@dgtlife.com>\n * @copyright DGTLife, LLC 20",
"end": 162,
"score": 0.9998794198036194,
"start": 147,
"tag": "NAME",
"value": "Derek Gransaull"
},
{
"context": "eld and MD Text Area.\n * @author D... | client/imports/ui/md-text-input/md-text-input.coffee | dgtlife/material-for-meteor | 12 | ###
* @file Defines the on-render callbacks and event handlers, for the MD text
* input fields--MD Text Field and MD Text Area.
* @author Derek Gransaull <derek@dgtlife.com>
* @copyright DGTLife, LLC 2015
###
{ Template } = require 'meteor/templating'
eqS = require('../../api/md-utils.js').eqS
setLabelAndUnderlineFocused =
require('../../api/md-text-input-api.js').setLabelAndUnderlineFocused
setLabelAndUnderlineUnfocused =
require('../../api/md-text-input-api.js').setLabelAndUnderlineUnfocused
unfocusLabelOnValueChange =
require('../../api/md-text-input-api.js').unfocusLabelOnValueChange
setHeightOfTextarea =
require('../../api/md-text-input-api.js').setHeightOfTextarea
setStyleOfNonFloatableLabelOnInput =
require('../../api/md-label-api.coffee').setStyleOfNonFloatableLabelOnInput
setStyleOfLabelUnfocused =
require('../../api/md-label-api.coffee').setStyleOfLabelUnfocused
require './md-text-input.jade'
require '../md-label/md-label.js'
require '../md-underline/md-underline.js'
# On-render callback for MD Text Field.
Template.md_text_field.onRendered ->
field = @firstNode
# Set the underline style for the disabled case.
if @data.disabled is 'true'
eqS(field, '[data-underline]').classList.add 'disabled'
# Set the label position, after the embedded input is loaded.
input = eqS field, '[data-text-field-input]'
input.onload = setStyleOfLabelUnfocused field
# Activate an observer in order to detect value changes and set the label
# style.
# ToDo: Commented out on 4/29/2017 as it interfered with text field validation
# styling. I forgot why I put this here. I need to figure out why.
# unfocusLabelOnValueChange field
# Event handlers for MD Text Field
Template.md_text_field.events
'focus [data-text-field-input]': (event) ->
field = event.currentTarget.parentElement.parentElement.parentElement
setLabelAndUnderlineFocused field
'blur [data-text-field-input]': (event) ->
field = event.currentTarget.parentElement.parentElement.parentElement
setLabelAndUnderlineUnfocused field
'input [data-text-field-input]': (event) ->
input = event.currentTarget
field = event.currentTarget.parentElement.parentElement.parentElement
setStyleOfNonFloatableLabelOnInput field
# Mirror the input value to the field value.
field.setAttribute('data-value', input.value)
# On-render callback for MD Text Area.
Template.md_text_area.onRendered ->
field = @firstNode
# Set underline style for the disabled case.
if @data.disabled is 'true'
eqS(field, '[data-underline]').classList.add 'disabled'
# Set the label position.
setStyleOfLabelUnfocused field
# Set the height of the text area, after the input is loaded.
eqS(field, '[data-text-area-input]').onload = setHeightOfTextarea field
# Reset the height when the window size changes to capture any effects of
# responsive changes that affect the height of the text block size detector.
window.addEventListener 'resize', ->
setHeightOfTextarea field
# Event handlers for MD Text Area
Template.md_text_area.events
'focus [data-text-area-input]': (event) ->
# Set the label and underline styles, and maintain size.
field = event.currentTarget.parentElement.parentElement
setLabelAndUnderlineFocused field
'blur [data-text-area-input]': (event) ->
# Reset the label and underline styles, and maintain size.
field = event.currentTarget.parentElement.parentElement
setLabelAndUnderlineUnfocused field
'input [data-text-area-input]': (event) ->
input = event.currentTarget
field = event.currentTarget.parentElement.parentElement
# Set the label and underline styles.
setStyleOfNonFloatableLabelOnInput field
# Mirror the input into the size detector.
eqS(input.parentElement, '[data-size-detector]').innerText = input.value
# Auto-grow the textarea as input wraps.
setHeightOfTextarea field
| 215613 | ###
* @file Defines the on-render callbacks and event handlers, for the MD text
* input fields--MD Text Field and MD Text Area.
* @author <NAME> <<EMAIL>>
* @copyright DGTLife, LLC 2015
###
{ Template } = require 'meteor/templating'
eqS = require('../../api/md-utils.js').eqS
setLabelAndUnderlineFocused =
require('../../api/md-text-input-api.js').setLabelAndUnderlineFocused
setLabelAndUnderlineUnfocused =
require('../../api/md-text-input-api.js').setLabelAndUnderlineUnfocused
unfocusLabelOnValueChange =
require('../../api/md-text-input-api.js').unfocusLabelOnValueChange
setHeightOfTextarea =
require('../../api/md-text-input-api.js').setHeightOfTextarea
setStyleOfNonFloatableLabelOnInput =
require('../../api/md-label-api.coffee').setStyleOfNonFloatableLabelOnInput
setStyleOfLabelUnfocused =
require('../../api/md-label-api.coffee').setStyleOfLabelUnfocused
require './md-text-input.jade'
require '../md-label/md-label.js'
require '../md-underline/md-underline.js'
# On-render callback for MD Text Field.
Template.md_text_field.onRendered ->
field = @firstNode
# Set the underline style for the disabled case.
if @data.disabled is 'true'
eqS(field, '[data-underline]').classList.add 'disabled'
# Set the label position, after the embedded input is loaded.
input = eqS field, '[data-text-field-input]'
input.onload = setStyleOfLabelUnfocused field
# Activate an observer in order to detect value changes and set the label
# style.
# ToDo: Commented out on 4/29/2017 as it interfered with text field validation
# styling. I forgot why I put this here. I need to figure out why.
# unfocusLabelOnValueChange field
# Event handlers for MD Text Field
Template.md_text_field.events
'focus [data-text-field-input]': (event) ->
field = event.currentTarget.parentElement.parentElement.parentElement
setLabelAndUnderlineFocused field
'blur [data-text-field-input]': (event) ->
field = event.currentTarget.parentElement.parentElement.parentElement
setLabelAndUnderlineUnfocused field
'input [data-text-field-input]': (event) ->
input = event.currentTarget
field = event.currentTarget.parentElement.parentElement.parentElement
setStyleOfNonFloatableLabelOnInput field
# Mirror the input value to the field value.
field.setAttribute('data-value', input.value)
# On-render callback for MD Text Area.
Template.md_text_area.onRendered ->
field = @firstNode
# Set underline style for the disabled case.
if @data.disabled is 'true'
eqS(field, '[data-underline]').classList.add 'disabled'
# Set the label position.
setStyleOfLabelUnfocused field
# Set the height of the text area, after the input is loaded.
eqS(field, '[data-text-area-input]').onload = setHeightOfTextarea field
# Reset the height when the window size changes to capture any effects of
# responsive changes that affect the height of the text block size detector.
window.addEventListener 'resize', ->
setHeightOfTextarea field
# Event handlers for MD Text Area
Template.md_text_area.events
'focus [data-text-area-input]': (event) ->
# Set the label and underline styles, and maintain size.
field = event.currentTarget.parentElement.parentElement
setLabelAndUnderlineFocused field
'blur [data-text-area-input]': (event) ->
# Reset the label and underline styles, and maintain size.
field = event.currentTarget.parentElement.parentElement
setLabelAndUnderlineUnfocused field
'input [data-text-area-input]': (event) ->
input = event.currentTarget
field = event.currentTarget.parentElement.parentElement
# Set the label and underline styles.
setStyleOfNonFloatableLabelOnInput field
# Mirror the input into the size detector.
eqS(input.parentElement, '[data-size-detector]').innerText = input.value
# Auto-grow the textarea as input wraps.
setHeightOfTextarea field
| true | ###
* @file Defines the on-render callbacks and event handlers, for the MD text
* input fields--MD Text Field and MD Text Area.
* @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
* @copyright DGTLife, LLC 2015
###
{ Template } = require 'meteor/templating'
eqS = require('../../api/md-utils.js').eqS
setLabelAndUnderlineFocused =
require('../../api/md-text-input-api.js').setLabelAndUnderlineFocused
setLabelAndUnderlineUnfocused =
require('../../api/md-text-input-api.js').setLabelAndUnderlineUnfocused
unfocusLabelOnValueChange =
require('../../api/md-text-input-api.js').unfocusLabelOnValueChange
setHeightOfTextarea =
require('../../api/md-text-input-api.js').setHeightOfTextarea
setStyleOfNonFloatableLabelOnInput =
require('../../api/md-label-api.coffee').setStyleOfNonFloatableLabelOnInput
setStyleOfLabelUnfocused =
require('../../api/md-label-api.coffee').setStyleOfLabelUnfocused
require './md-text-input.jade'
require '../md-label/md-label.js'
require '../md-underline/md-underline.js'
# On-render callback for MD Text Field.
Template.md_text_field.onRendered ->
field = @firstNode
# Set the underline style for the disabled case.
if @data.disabled is 'true'
eqS(field, '[data-underline]').classList.add 'disabled'
# Set the label position, after the embedded input is loaded.
input = eqS field, '[data-text-field-input]'
input.onload = setStyleOfLabelUnfocused field
# Activate an observer in order to detect value changes and set the label
# style.
# ToDo: Commented out on 4/29/2017 as it interfered with text field validation
# styling. I forgot why I put this here. I need to figure out why.
# unfocusLabelOnValueChange field
# Event handlers for MD Text Field
Template.md_text_field.events
'focus [data-text-field-input]': (event) ->
field = event.currentTarget.parentElement.parentElement.parentElement
setLabelAndUnderlineFocused field
'blur [data-text-field-input]': (event) ->
field = event.currentTarget.parentElement.parentElement.parentElement
setLabelAndUnderlineUnfocused field
'input [data-text-field-input]': (event) ->
input = event.currentTarget
field = event.currentTarget.parentElement.parentElement.parentElement
setStyleOfNonFloatableLabelOnInput field
# Mirror the input value to the field value.
field.setAttribute('data-value', input.value)
# On-render callback for MD Text Area.
Template.md_text_area.onRendered ->
field = @firstNode
# Set underline style for the disabled case.
if @data.disabled is 'true'
eqS(field, '[data-underline]').classList.add 'disabled'
# Set the label position.
setStyleOfLabelUnfocused field
# Set the height of the text area, after the input is loaded.
eqS(field, '[data-text-area-input]').onload = setHeightOfTextarea field
# Reset the height when the window size changes to capture any effects of
# responsive changes that affect the height of the text block size detector.
window.addEventListener 'resize', ->
setHeightOfTextarea field
# Event handlers for MD Text Area
Template.md_text_area.events
'focus [data-text-area-input]': (event) ->
# Set the label and underline styles, and maintain size.
field = event.currentTarget.parentElement.parentElement
setLabelAndUnderlineFocused field
'blur [data-text-area-input]': (event) ->
# Reset the label and underline styles, and maintain size.
field = event.currentTarget.parentElement.parentElement
setLabelAndUnderlineUnfocused field
'input [data-text-area-input]': (event) ->
input = event.currentTarget
field = event.currentTarget.parentElement.parentElement
# Set the label and underline styles.
setStyleOfNonFloatableLabelOnInput field
# Mirror the input into the size detector.
eqS(input.parentElement, '[data-size-detector]').innerText = input.value
# Auto-grow the textarea as input wraps.
setHeightOfTextarea field
|
[
{
"context": "# Antoine Dodson's greatest hits... errr... only hit \n#\n# hide ya ",
"end": 16,
"score": 0.9994232654571533,
"start": 2,
"tag": "NAME",
"value": "Antoine Dodson"
}
] | src/scripts/hideyakids.coffee | iangreenleaf/hubot-scripts | 2 | # Antoine Dodson's greatest hits... errr... only hit
#
# hide ya kids - Hide `em!
#
module.exports = (robot) ->
robot.hear /hide ya kids/i, (msg) ->
msg.send "http://www.youtube.com/watch?v=hMtZfW2z9dw"
| 114907 | # <NAME>'s greatest hits... errr... only hit
#
# hide ya kids - Hide `em!
#
module.exports = (robot) ->
robot.hear /hide ya kids/i, (msg) ->
msg.send "http://www.youtube.com/watch?v=hMtZfW2z9dw"
| true | # PI:NAME:<NAME>END_PI's greatest hits... errr... only hit
#
# hide ya kids - Hide `em!
#
module.exports = (robot) ->
robot.hear /hide ya kids/i, (msg) ->
msg.send "http://www.youtube.com/watch?v=hMtZfW2z9dw"
|
[
{
"context": "rd on fetch\", ->\n User.refresh [\n first: \"John\"\n last: \"Williams\"\n id: \"IDD\"\n ]\n ",
"end": 1198,
"score": 0.9996997714042664,
"start": 1194,
"tag": "NAME",
"value": "John"
},
{
"context": " User.refresh [\n first: \"John\"\n ... | spec/ajax_browserspec.coffee | ryggrad/Ryggrad | 0 | # This spec has to be run in a browser. Unfortunately phantomjs does not like it and I have yet to figure out why exactly.
describe "Ryggrad.Ajax", ->
User = undefined
jqXHR = undefined
spy = undefined
stubbedAjax = undefined
beforeEach ->
Ryggrad.Ajax.clearQueue()
class User extends Ryggrad.Model
@configure("User", "first", "last")
@extend Ryggrad.Model.Ajax
jqXHR = $.Deferred()
$.extend jqXHR,
readyState: 0
setRequestHeader: ->
this
getAllResponseHeaders: ->
getResponseHeader: ->
overrideMimeType: ->
this
abort: ->
@reject arguments
this
success: jqXHR.done
error: jqXHR.fail
complete: jqXHR.done
stubbedAjax = sinon.stub jQuery, 'ajax'
stubbedAjax.returns(jqXHR)
afterEach ->
stubbedAjax.restore()
it "can GET a collection on fetch", ->
User.fetch()
stubbedAjax.should.have.been.calledWith
data: undefined
dataType: "json"
headers: "X-Requested-With": "XMLHttpRequest"
processData: false
type: "GET"
url: "/users"
it "can GET a record on fetch", ->
User.refresh [
first: "John"
last: "Williams"
id: "IDD"
]
User.fetch id: "IDD"
stubbedAjax.should.have.been.calledWith
data: undefined
dataType: "json"
headers: "X-Requested-With": "XMLHttpRequest"
processData: false
type: "GET"
url: "/users/IDD"
it "allows undeclared attributes from server", ->
User.refresh [
id: "12345"
first: "Hans"
last: "Zimmer"
created_by: "spine_user"
created_at: "2013-07-14T14:00:00-04:00"
updated_at: "2013-07-14T14:00:00-04:00"
]
User.first().created_by.should.equal "spine_user"
it "should send POST on create", ->
User.create
first: "Hans"
last: "Zimmer"
id: "IDD"
stubbedAjax.should.have.been.calledWith
type: "POST"
headers:
"X-Requested-With": "XMLHttpRequest"
contentType: "application/json"
dataType: "json"
data: "{\"first\":\"Hans\",\"last\":\"Zimmer\",\"id\":\"IDD\"}"
url: "/users"
processData: false
it "should send PUT on update", ->
User.refresh [
first: "John"
last: "Williams"
id: "IDD"
]
User.first().updateAttributes
first: "John2"
last: "Williams2"
stubbedAjax.should.have.been.calledWith
type: "PUT"
headers:
"X-Requested-With": "XMLHttpRequest"
contentType: "application/json"
dataType: "json"
data: "{\"first\":\"John2\",\"last\":\"Williams2\",\"id\":\"IDD\"}"
url: "/users/IDD"
processData: false
it "should send DELETE on destroy", ->
User.refresh [
first: "John"
last: "Williams"
id: "IDD"
]
User.first().destroy()
stubbedAjax.should.have.been.calledWith
data: undefined
dataType: "json"
headers:
"X-Requested-With": "XMLHttpRequest"
processData: false
type: "DELETE",
url: "/users/IDD"
it "should update record after PUT/POST", ->
User.create
first: "Hans"
last: "Zimmer"
id: "IDD"
newAtts =
first: "Hans2"
last: "Zimmer2"
id: "IDD"
jqXHR.resolve newAtts
User.first().attributes().first.should.equal newAtts.first
it "should update record with undeclared attributes from server", ->
User.create
first: "Hans"
last: "Zimmer"
serverAttrs =
id: "12345"
first: "Hans"
last: "Zimmer"
created_by: "spine_user"
created_at: "2013-07-14T14:00:00-04:00"
updated_at: "2013-07-14T14:00:00-04:00"
jqXHR.resolve serverAttrs
User.first().created_by.should.equal "spine_user"
it "should change record ID after PUT/POST", ->
User.create id: "IDD"
newAtts = id: "IDD2"
jqXHR.resolve newAtts
User.first().id.should.equal "IDD2"
User.irecords["IDD2"].id.should.equal User.first().id
it "can update record IDs for already queued requests", ->
u = User.create()
u.first = "Todd"
u.last = "Shaw"
u.save()
newAtts = id: "IDD"
jqXHR.resolve newAtts
stubbedAjax.should.have.been.calledWith
contentType: "application/json"
data: "{\"first\":\"Todd\",\"last\":\"Shaw\",\"id\":\"IDD\"}"
dataType: "json"
headers:
"X-Requested-With": "XMLHttpRequest"
processData: false
type: "PUT"
url: "/users/IDD"
it "should not recreate records after DELETE", ->
User.refresh [
first: "Phillip"
last: "Fry"
id: "MYID"
]
User.first().destroy()
User.count().should.equal 0
jqXHR.resolve
id: "MYID"
name: "Phillip"
last: "Fry"
User.count().should.equal 0
it "should send requests synchronously", ->
User.create first: "First"
stubbedAjax.should.have.been.called
stubbedAjax.reset()
User.create first: "Second"
stubbedAjax.should.not.have.been.called
jqXHR.resolve()
stubbedAjax.should.have.been.called
it "should return promise objects", ->
User.refresh [
first: "John"
last: "Williams"
id: "IDD"
]
user = User.find("IDD")
user.ajax().update().done spy
jqXHR.resolve()
stubbedAjax.should.have.been.called
it "should allow promise objects to abort the request and dequeue", ->
User.refresh [
first: "John"
last: "Williams"
id: "IDD"
]
user = User.find("IDD")
spy = sinon.spy()
user.ajax().update().fail spy
Ryggrad.Ajax.queue().length.should.equal 1
jqXHR.abort()
Ryggrad.Ajax.queue().length.should.equal 0
stubbedAjax.should.have.been.called
it "should not replace AJAX results when dequeue", ->
User.refresh [],
clear: true
jqXHR.resolve [id: "IDD"]
User.fetch()
User.exists("IDD").should.be.truthy
it "should have success callbacks", ->
User.create
first: "Second"
success: spy
jqXHR.resolve()
stubbedAjax.should.have.been.called
it "should have error callbacks", ->
User.create
first: "Second"
,
error: spy
jqXHR.reject()
stubbedAjax.should.have.been.called
it "should cancel ajax on change", ->
User.create {first: "Second"}, ajax: false
jqXHR.resolve()
stubbedAjax.should.not.have.been.called
it "should expose the defaults object", ->
Ryggrad.Ajax.defaults.should.be.defined
it "can get a url property with optional host from a model and model instances", ->
User.url = "/people"
Ryggrad.Ajax.getURL(User).should.be "/people"
user = new User(id: 1)
user.url().should.be "/people/1"
user.url("custom").should.be "/people/1/custom"
Ryggrad.Model.host = "http://example.com"
user.url().should.be "http://example.com/people/1"
it "can override POST url with options on create", ->
User.create
first: "Adam"
id: "123"
,
url: "/people"
stubbedAjax.should.have.been.calledWith
type: "POST"
headers:
"X-Requested-With": "XMLHttpRequest"
dataType: "json"
data: "{\"first\":\"Adam\",\"id\":\"123\"}"
contentType: "application/json"
url: "/people"
processData: false
it "can override GET url with options on fetch", ->
User.fetch url: "/people"
stubbedAjax.should.have.been.calledWith
type: "GET"
headers:
"X-Requested-With": "XMLHttpRequest"
dataType: "json"
url: "/people"
processData: false
data: undefined
it "can override PUT url with options on update", ->
user = User.create(
first: "Adam"
id: "123"
,
ajax: false
)
user.updateAttributes
first: "Odam"
,
url: "/people"
stubbedAjax.should.have.been.calledWith
type: "PUT"
headers:
"X-Requested-With": "XMLHttpRequest"
dataType: "json"
data: "{\"first\":\"Odam\",\"id\":\"123\"}"
contentType: "application/json"
url: "/people"
processData: false
it "can override DELETE url with options on destroy", ->
user = User.create(
first: "Adam"
id: "123"
,
ajax: false
)
user.destroy url: "/people"
stubbedAjax.should.have.been.calledWith
type: "DELETE"
headers:
"X-Requested-With": "XMLHttpRequest"
dataType: "json"
url: "/people"
processData: false
data: undefined
it "should have a url function", ->
Ryggrad.Model.host = ""
User.url().should.be "/users"
User.url("search").should.be "/users/search"
user = new User(id: 1)
user.url().should.be "/users/1"
user.url("custom").should.be "/users/1/custom"
Ryggrad.Model.host = "http://example.com"
User.url().should.be "http://example.com/users"
user.url().should.be "http://example.com/users/1"
it "can gather scope for the url from the model", ->
Ryggrad.Model.host = ""
User.scope = "admin"
User.url().should.be "/admin/users"
User.url("custom").should.be "/admin/users/custom"
user = new User(id: 1)
user.url().should.be "/admin/users/1"
User.scope = ->
"/roots/1"
User.url().should.be "/roots/1/users"
user.url().should.be "/roots/1/users/1"
user.url("custom").should.be "/roots/1/users/1/custom"
Ryggrad.Model.host = "http://example.com"
User.url().should.be "http://example.com/roots/1/users"
user.url().should.be "http://example.com/roots/1/users/1"
it "can gather scope for the url from a model instance", ->
Ryggrad.Model.host = ""
User.url().should.be "/users"
user = new User(id: 1)
user.scope = "admin"
user.url().should.be "/admin/users/1"
user.scope = ->
"/roots/1"
User.url().should.be "/users"
user.url().should.be "/roots/1/users/1"
user.url("custom").should.be "/roots/1/users/1/custom"
Ryggrad.Model.host = "http://example.com"
User.url().should.be "http://example.com/users"
user.url().should.be "http://example.com/roots/1/users/1"
it "should allow the scope for url on model to be superseeded by an instance", ->
Ryggrad.Model.host = ""
User.scope = "admin"
User.url().should.be "/admin/users"
user = new User(id: 1)
user.url().should.be "/admin/users/1"
user.scope = ->
"/roots/1"
User.url().should.be "/admin/users"
user.url().should.be "/roots/1/users/1"
Ryggrad.Model.host = "http://example.com"
User.url().should.be "http://example.com/admin/users"
user.url().should.be "http://example.com/roots/1/users/1"
it "should work with relative urls", ->
User.url = "../api/user"
Ryggrad.Ajax.getURL(User).should.be "../api/user"
user = new User(id: 1)
Ryggrad.Ajax.getURL(user).should.be "../api/user/1"
it "should get the collection url from the model instance", ->
Ryggrad.Model.host = ""
User.scope = "admin"
user = new User(id: 1)
Ryggrad.Ajax.getCollectionURL(user).should.be "/admin/users"
user.scope = "/root"
Ryggrad.Ajax.getCollectionURL(user).should.be "/root/users"
user.scope = ->
"/roots/" + @id
Ryggrad.Ajax.getCollectionURL(user).should.be "/roots/1/users"
| 28540 | # This spec has to be run in a browser. Unfortunately phantomjs does not like it and I have yet to figure out why exactly.
describe "Ryggrad.Ajax", ->
User = undefined
jqXHR = undefined
spy = undefined
stubbedAjax = undefined
beforeEach ->
Ryggrad.Ajax.clearQueue()
class User extends Ryggrad.Model
@configure("User", "first", "last")
@extend Ryggrad.Model.Ajax
jqXHR = $.Deferred()
$.extend jqXHR,
readyState: 0
setRequestHeader: ->
this
getAllResponseHeaders: ->
getResponseHeader: ->
overrideMimeType: ->
this
abort: ->
@reject arguments
this
success: jqXHR.done
error: jqXHR.fail
complete: jqXHR.done
stubbedAjax = sinon.stub jQuery, 'ajax'
stubbedAjax.returns(jqXHR)
afterEach ->
stubbedAjax.restore()
it "can GET a collection on fetch", ->
User.fetch()
stubbedAjax.should.have.been.calledWith
data: undefined
dataType: "json"
headers: "X-Requested-With": "XMLHttpRequest"
processData: false
type: "GET"
url: "/users"
it "can GET a record on fetch", ->
User.refresh [
first: "<NAME>"
last: "<NAME>"
id: "IDD"
]
User.fetch id: "IDD"
stubbedAjax.should.have.been.calledWith
data: undefined
dataType: "json"
headers: "X-Requested-With": "XMLHttpRequest"
processData: false
type: "GET"
url: "/users/IDD"
it "allows undeclared attributes from server", ->
User.refresh [
id: "12345"
first: "<NAME>"
last: "<NAME>"
created_by: "spine_user"
created_at: "2013-07-14T14:00:00-04:00"
updated_at: "2013-07-14T14:00:00-04:00"
]
User.first().created_by.should.equal "spine_user"
it "should send POST on create", ->
User.create
first: "<NAME>"
last: "<NAME>"
id: "IDD"
stubbedAjax.should.have.been.calledWith
type: "POST"
headers:
"X-Requested-With": "XMLHttpRequest"
contentType: "application/json"
dataType: "json"
data: "{\"first\":\"<NAME>\",\"last\":\"<NAME>\",\"id\":\"IDD\"}"
url: "/users"
processData: false
it "should send PUT on update", ->
User.refresh [
first: "<NAME>"
last: "<NAME>"
id: "IDD"
]
User.first().updateAttributes
first: "<NAME>"
last: "<NAME>"
stubbedAjax.should.have.been.calledWith
type: "PUT"
headers:
"X-Requested-With": "XMLHttpRequest"
contentType: "application/json"
dataType: "json"
data: "{\"first\":\"<NAME>\",\"last\":\"<NAME>\",\"id\":\"IDD\"}"
url: "/users/IDD"
processData: false
it "should send DELETE on destroy", ->
User.refresh [
first: "<NAME>"
last: "<NAME>"
id: "IDD"
]
User.first().destroy()
stubbedAjax.should.have.been.calledWith
data: undefined
dataType: "json"
headers:
"X-Requested-With": "XMLHttpRequest"
processData: false
type: "DELETE",
url: "/users/IDD"
it "should update record after PUT/POST", ->
User.create
first: "<NAME>"
last: "<NAME>"
id: "IDD"
newAtts =
first: "<NAME>"
last: "<NAME>"
id: "IDD"
jqXHR.resolve newAtts
User.first().attributes().first.should.equal newAtts.first
it "should update record with undeclared attributes from server", ->
User.create
first: "<NAME>"
last: "<NAME>"
serverAttrs =
id: "12345"
first: "<NAME>"
last: "<NAME>"
created_by: "spine_user"
created_at: "2013-07-14T14:00:00-04:00"
updated_at: "2013-07-14T14:00:00-04:00"
jqXHR.resolve serverAttrs
User.first().created_by.should.equal "spine_user"
it "should change record ID after PUT/POST", ->
User.create id: "IDD"
newAtts = id: "IDD2"
jqXHR.resolve newAtts
User.first().id.should.equal "IDD2"
User.irecords["IDD2"].id.should.equal User.first().id
it "can update record IDs for already queued requests", ->
u = User.create()
u.first = "<NAME>"
u.last = "<NAME>"
u.save()
newAtts = id: "IDD"
jqXHR.resolve newAtts
stubbedAjax.should.have.been.calledWith
contentType: "application/json"
data: "{\"first\":\"<NAME>\",\"last\":\"<NAME>\",\"id\":\"IDD\"}"
dataType: "json"
headers:
"X-Requested-With": "XMLHttpRequest"
processData: false
type: "PUT"
url: "/users/IDD"
it "should not recreate records after DELETE", ->
User.refresh [
first: "<NAME>"
last: "<NAME>"
id: "MYID"
]
User.first().destroy()
User.count().should.equal 0
jqXHR.resolve
id: "MYID"
name: "<NAME>"
last: "<NAME>"
User.count().should.equal 0
it "should send requests synchronously", ->
User.create first: "First"
stubbedAjax.should.have.been.called
stubbedAjax.reset()
User.create first: "Second"
stubbedAjax.should.not.have.been.called
jqXHR.resolve()
stubbedAjax.should.have.been.called
it "should return promise objects", ->
User.refresh [
first: "<NAME>"
last: "<NAME>"
id: "IDD"
]
user = User.find("IDD")
user.ajax().update().done spy
jqXHR.resolve()
stubbedAjax.should.have.been.called
it "should allow promise objects to abort the request and dequeue", ->
User.refresh [
first: "<NAME>"
last: "<NAME>"
id: "IDD"
]
user = User.find("IDD")
spy = sinon.spy()
user.ajax().update().fail spy
Ryggrad.Ajax.queue().length.should.equal 1
jqXHR.abort()
Ryggrad.Ajax.queue().length.should.equal 0
stubbedAjax.should.have.been.called
it "should not replace AJAX results when dequeue", ->
User.refresh [],
clear: true
jqXHR.resolve [id: "IDD"]
User.fetch()
User.exists("IDD").should.be.truthy
it "should have success callbacks", ->
User.create
first: "Second"
success: spy
jqXHR.resolve()
stubbedAjax.should.have.been.called
it "should have error callbacks", ->
User.create
first: "Second"
,
error: spy
jqXHR.reject()
stubbedAjax.should.have.been.called
it "should cancel ajax on change", ->
User.create {first: "Second"}, ajax: false
jqXHR.resolve()
stubbedAjax.should.not.have.been.called
it "should expose the defaults object", ->
Ryggrad.Ajax.defaults.should.be.defined
it "can get a url property with optional host from a model and model instances", ->
User.url = "/people"
Ryggrad.Ajax.getURL(User).should.be "/people"
user = new User(id: 1)
user.url().should.be "/people/1"
user.url("custom").should.be "/people/1/custom"
Ryggrad.Model.host = "http://example.com"
user.url().should.be "http://example.com/people/1"
it "can override POST url with options on create", ->
User.create
first: "<NAME>"
id: "<NAME>23"
,
url: "/people"
stubbedAjax.should.have.been.calledWith
type: "POST"
headers:
"X-Requested-With": "XMLHttpRequest"
dataType: "json"
data: "{\"first\":\"<NAME>\",\"id\":\"123\"}"
contentType: "application/json"
url: "/people"
processData: false
it "can override GET url with options on fetch", ->
User.fetch url: "/people"
stubbedAjax.should.have.been.calledWith
type: "GET"
headers:
"X-Requested-With": "XMLHttpRequest"
dataType: "json"
url: "/people"
processData: false
data: undefined
it "can override PUT url with options on update", ->
user = User.create(
first: "<NAME>"
id: "<NAME>23"
,
ajax: false
)
user.updateAttributes
first: "<NAME>"
,
url: "/people"
stubbedAjax.should.have.been.calledWith
type: "PUT"
headers:
"X-Requested-With": "XMLHttpRequest"
dataType: "json"
data: "{\"first\":\"Odam\",\"id\":\"123\"}"
contentType: "application/json"
url: "/people"
processData: false
it "can override DELETE url with options on destroy", ->
user = User.create(
first: "<NAME>"
id: "<NAME>23"
,
ajax: false
)
user.destroy url: "/people"
stubbedAjax.should.have.been.calledWith
type: "DELETE"
headers:
"X-Requested-With": "XMLHttpRequest"
dataType: "json"
url: "/people"
processData: false
data: undefined
it "should have a url function", ->
Ryggrad.Model.host = ""
User.url().should.be "/users"
User.url("search").should.be "/users/search"
user = new User(id: 1)
user.url().should.be "/users/1"
user.url("custom").should.be "/users/1/custom"
Ryggrad.Model.host = "http://example.com"
User.url().should.be "http://example.com/users"
user.url().should.be "http://example.com/users/1"
it "can gather scope for the url from the model", ->
Ryggrad.Model.host = ""
User.scope = "admin"
User.url().should.be "/admin/users"
User.url("custom").should.be "/admin/users/custom"
user = new User(id: 1)
user.url().should.be "/admin/users/1"
User.scope = ->
"/roots/1"
User.url().should.be "/roots/1/users"
user.url().should.be "/roots/1/users/1"
user.url("custom").should.be "/roots/1/users/1/custom"
Ryggrad.Model.host = "http://example.com"
User.url().should.be "http://example.com/roots/1/users"
user.url().should.be "http://example.com/roots/1/users/1"
it "can gather scope for the url from a model instance", ->
Ryggrad.Model.host = ""
User.url().should.be "/users"
user = new User(id: 1)
user.scope = "admin"
user.url().should.be "/admin/users/1"
user.scope = ->
"/roots/1"
User.url().should.be "/users"
user.url().should.be "/roots/1/users/1"
user.url("custom").should.be "/roots/1/users/1/custom"
Ryggrad.Model.host = "http://example.com"
User.url().should.be "http://example.com/users"
user.url().should.be "http://example.com/roots/1/users/1"
it "should allow the scope for url on model to be superseeded by an instance", ->
Ryggrad.Model.host = ""
User.scope = "admin"
User.url().should.be "/admin/users"
user = new User(id: 1)
user.url().should.be "/admin/users/1"
user.scope = ->
"/roots/1"
User.url().should.be "/admin/users"
user.url().should.be "/roots/1/users/1"
Ryggrad.Model.host = "http://example.com"
User.url().should.be "http://example.com/admin/users"
user.url().should.be "http://example.com/roots/1/users/1"
it "should work with relative urls", ->
User.url = "../api/user"
Ryggrad.Ajax.getURL(User).should.be "../api/user"
user = new User(id: 1)
Ryggrad.Ajax.getURL(user).should.be "../api/user/1"
it "should get the collection url from the model instance", ->
Ryggrad.Model.host = ""
User.scope = "admin"
user = new User(id: 1)
Ryggrad.Ajax.getCollectionURL(user).should.be "/admin/users"
user.scope = "/root"
Ryggrad.Ajax.getCollectionURL(user).should.be "/root/users"
user.scope = ->
"/roots/" + @id
Ryggrad.Ajax.getCollectionURL(user).should.be "/roots/1/users"
| true | # This spec has to be run in a browser. Unfortunately phantomjs does not like it and I have yet to figure out why exactly.
describe "Ryggrad.Ajax", ->
User = undefined
jqXHR = undefined
spy = undefined
stubbedAjax = undefined
beforeEach ->
Ryggrad.Ajax.clearQueue()
class User extends Ryggrad.Model
@configure("User", "first", "last")
@extend Ryggrad.Model.Ajax
jqXHR = $.Deferred()
$.extend jqXHR,
readyState: 0
setRequestHeader: ->
this
getAllResponseHeaders: ->
getResponseHeader: ->
overrideMimeType: ->
this
abort: ->
@reject arguments
this
success: jqXHR.done
error: jqXHR.fail
complete: jqXHR.done
stubbedAjax = sinon.stub jQuery, 'ajax'
stubbedAjax.returns(jqXHR)
afterEach ->
stubbedAjax.restore()
it "can GET a collection on fetch", ->
User.fetch()
stubbedAjax.should.have.been.calledWith
data: undefined
dataType: "json"
headers: "X-Requested-With": "XMLHttpRequest"
processData: false
type: "GET"
url: "/users"
it "can GET a record on fetch", ->
User.refresh [
first: "PI:NAME:<NAME>END_PI"
last: "PI:NAME:<NAME>END_PI"
id: "IDD"
]
User.fetch id: "IDD"
stubbedAjax.should.have.been.calledWith
data: undefined
dataType: "json"
headers: "X-Requested-With": "XMLHttpRequest"
processData: false
type: "GET"
url: "/users/IDD"
it "allows undeclared attributes from server", ->
User.refresh [
id: "12345"
first: "PI:NAME:<NAME>END_PI"
last: "PI:NAME:<NAME>END_PI"
created_by: "spine_user"
created_at: "2013-07-14T14:00:00-04:00"
updated_at: "2013-07-14T14:00:00-04:00"
]
User.first().created_by.should.equal "spine_user"
it "should send POST on create", ->
User.create
first: "PI:NAME:<NAME>END_PI"
last: "PI:NAME:<NAME>END_PI"
id: "IDD"
stubbedAjax.should.have.been.calledWith
type: "POST"
headers:
"X-Requested-With": "XMLHttpRequest"
contentType: "application/json"
dataType: "json"
data: "{\"first\":\"PI:NAME:<NAME>END_PI\",\"last\":\"PI:NAME:<NAME>END_PI\",\"id\":\"IDD\"}"
url: "/users"
processData: false
it "should send PUT on update", ->
User.refresh [
first: "PI:NAME:<NAME>END_PI"
last: "PI:NAME:<NAME>END_PI"
id: "IDD"
]
User.first().updateAttributes
first: "PI:NAME:<NAME>END_PI"
last: "PI:NAME:<NAME>END_PI"
stubbedAjax.should.have.been.calledWith
type: "PUT"
headers:
"X-Requested-With": "XMLHttpRequest"
contentType: "application/json"
dataType: "json"
data: "{\"first\":\"PI:NAME:<NAME>END_PI\",\"last\":\"PI:NAME:<NAME>END_PI\",\"id\":\"IDD\"}"
url: "/users/IDD"
processData: false
it "should send DELETE on destroy", ->
User.refresh [
first: "PI:NAME:<NAME>END_PI"
last: "PI:NAME:<NAME>END_PI"
id: "IDD"
]
User.first().destroy()
stubbedAjax.should.have.been.calledWith
data: undefined
dataType: "json"
headers:
"X-Requested-With": "XMLHttpRequest"
processData: false
type: "DELETE",
url: "/users/IDD"
it "should update record after PUT/POST", ->
User.create
first: "PI:NAME:<NAME>END_PI"
last: "PI:NAME:<NAME>END_PI"
id: "IDD"
newAtts =
first: "PI:NAME:<NAME>END_PI"
last: "PI:NAME:<NAME>END_PI"
id: "IDD"
jqXHR.resolve newAtts
User.first().attributes().first.should.equal newAtts.first
it "should update record with undeclared attributes from server", ->
User.create
first: "PI:NAME:<NAME>END_PI"
last: "PI:NAME:<NAME>END_PI"
serverAttrs =
id: "12345"
first: "PI:NAME:<NAME>END_PI"
last: "PI:NAME:<NAME>END_PI"
created_by: "spine_user"
created_at: "2013-07-14T14:00:00-04:00"
updated_at: "2013-07-14T14:00:00-04:00"
jqXHR.resolve serverAttrs
User.first().created_by.should.equal "spine_user"
it "should change record ID after PUT/POST", ->
User.create id: "IDD"
newAtts = id: "IDD2"
jqXHR.resolve newAtts
User.first().id.should.equal "IDD2"
User.irecords["IDD2"].id.should.equal User.first().id
it "can update record IDs for already queued requests", ->
u = User.create()
u.first = "PI:NAME:<NAME>END_PI"
u.last = "PI:NAME:<NAME>END_PI"
u.save()
newAtts = id: "IDD"
jqXHR.resolve newAtts
stubbedAjax.should.have.been.calledWith
contentType: "application/json"
data: "{\"first\":\"PI:NAME:<NAME>END_PI\",\"last\":\"PI:NAME:<NAME>END_PI\",\"id\":\"IDD\"}"
dataType: "json"
headers:
"X-Requested-With": "XMLHttpRequest"
processData: false
type: "PUT"
url: "/users/IDD"
it "should not recreate records after DELETE", ->
User.refresh [
first: "PI:NAME:<NAME>END_PI"
last: "PI:NAME:<NAME>END_PI"
id: "MYID"
]
User.first().destroy()
User.count().should.equal 0
jqXHR.resolve
id: "MYID"
name: "PI:NAME:<NAME>END_PI"
last: "PI:NAME:<NAME>END_PI"
User.count().should.equal 0
it "should send requests synchronously", ->
User.create first: "First"
stubbedAjax.should.have.been.called
stubbedAjax.reset()
User.create first: "Second"
stubbedAjax.should.not.have.been.called
jqXHR.resolve()
stubbedAjax.should.have.been.called
it "should return promise objects", ->
User.refresh [
first: "PI:NAME:<NAME>END_PI"
last: "PI:NAME:<NAME>END_PI"
id: "IDD"
]
user = User.find("IDD")
user.ajax().update().done spy
jqXHR.resolve()
stubbedAjax.should.have.been.called
it "should allow promise objects to abort the request and dequeue", ->
User.refresh [
first: "PI:NAME:<NAME>END_PI"
last: "PI:NAME:<NAME>END_PI"
id: "IDD"
]
user = User.find("IDD")
spy = sinon.spy()
user.ajax().update().fail spy
Ryggrad.Ajax.queue().length.should.equal 1
jqXHR.abort()
Ryggrad.Ajax.queue().length.should.equal 0
stubbedAjax.should.have.been.called
it "should not replace AJAX results when dequeue", ->
User.refresh [],
clear: true
jqXHR.resolve [id: "IDD"]
User.fetch()
User.exists("IDD").should.be.truthy
it "should have success callbacks", ->
User.create
first: "Second"
success: spy
jqXHR.resolve()
stubbedAjax.should.have.been.called
it "should have error callbacks", ->
User.create
first: "Second"
,
error: spy
jqXHR.reject()
stubbedAjax.should.have.been.called
it "should cancel ajax on change", ->
User.create {first: "Second"}, ajax: false
jqXHR.resolve()
stubbedAjax.should.not.have.been.called
it "should expose the defaults object", ->
Ryggrad.Ajax.defaults.should.be.defined
it "can get a url property with optional host from a model and model instances", ->
User.url = "/people"
Ryggrad.Ajax.getURL(User).should.be "/people"
user = new User(id: 1)
user.url().should.be "/people/1"
user.url("custom").should.be "/people/1/custom"
Ryggrad.Model.host = "http://example.com"
user.url().should.be "http://example.com/people/1"
it "can override POST url with options on create", ->
User.create
first: "PI:NAME:<NAME>END_PI"
id: "PI:NAME:<NAME>END_PI23"
,
url: "/people"
stubbedAjax.should.have.been.calledWith
type: "POST"
headers:
"X-Requested-With": "XMLHttpRequest"
dataType: "json"
data: "{\"first\":\"PI:NAME:<NAME>END_PI\",\"id\":\"123\"}"
contentType: "application/json"
url: "/people"
processData: false
it "can override GET url with options on fetch", ->
User.fetch url: "/people"
stubbedAjax.should.have.been.calledWith
type: "GET"
headers:
"X-Requested-With": "XMLHttpRequest"
dataType: "json"
url: "/people"
processData: false
data: undefined
it "can override PUT url with options on update", ->
user = User.create(
first: "PI:NAME:<NAME>END_PI"
id: "PI:NAME:<NAME>END_PI23"
,
ajax: false
)
user.updateAttributes
first: "PI:NAME:<NAME>END_PI"
,
url: "/people"
stubbedAjax.should.have.been.calledWith
type: "PUT"
headers:
"X-Requested-With": "XMLHttpRequest"
dataType: "json"
data: "{\"first\":\"Odam\",\"id\":\"123\"}"
contentType: "application/json"
url: "/people"
processData: false
it "can override DELETE url with options on destroy", ->
user = User.create(
first: "PI:NAME:<NAME>END_PI"
id: "PI:NAME:<NAME>END_PI23"
,
ajax: false
)
user.destroy url: "/people"
stubbedAjax.should.have.been.calledWith
type: "DELETE"
headers:
"X-Requested-With": "XMLHttpRequest"
dataType: "json"
url: "/people"
processData: false
data: undefined
it "should have a url function", ->
Ryggrad.Model.host = ""
User.url().should.be "/users"
User.url("search").should.be "/users/search"
user = new User(id: 1)
user.url().should.be "/users/1"
user.url("custom").should.be "/users/1/custom"
Ryggrad.Model.host = "http://example.com"
User.url().should.be "http://example.com/users"
user.url().should.be "http://example.com/users/1"
it "can gather scope for the url from the model", ->
Ryggrad.Model.host = ""
User.scope = "admin"
User.url().should.be "/admin/users"
User.url("custom").should.be "/admin/users/custom"
user = new User(id: 1)
user.url().should.be "/admin/users/1"
User.scope = ->
"/roots/1"
User.url().should.be "/roots/1/users"
user.url().should.be "/roots/1/users/1"
user.url("custom").should.be "/roots/1/users/1/custom"
Ryggrad.Model.host = "http://example.com"
User.url().should.be "http://example.com/roots/1/users"
user.url().should.be "http://example.com/roots/1/users/1"
it "can gather scope for the url from a model instance", ->
Ryggrad.Model.host = ""
User.url().should.be "/users"
user = new User(id: 1)
user.scope = "admin"
user.url().should.be "/admin/users/1"
user.scope = ->
"/roots/1"
User.url().should.be "/users"
user.url().should.be "/roots/1/users/1"
user.url("custom").should.be "/roots/1/users/1/custom"
Ryggrad.Model.host = "http://example.com"
User.url().should.be "http://example.com/users"
user.url().should.be "http://example.com/roots/1/users/1"
it "should allow the scope for url on model to be superseeded by an instance", ->
Ryggrad.Model.host = ""
User.scope = "admin"
User.url().should.be "/admin/users"
user = new User(id: 1)
user.url().should.be "/admin/users/1"
user.scope = ->
"/roots/1"
User.url().should.be "/admin/users"
user.url().should.be "/roots/1/users/1"
Ryggrad.Model.host = "http://example.com"
User.url().should.be "http://example.com/admin/users"
user.url().should.be "http://example.com/roots/1/users/1"
it "should work with relative urls", ->
User.url = "../api/user"
Ryggrad.Ajax.getURL(User).should.be "../api/user"
user = new User(id: 1)
Ryggrad.Ajax.getURL(user).should.be "../api/user/1"
it "should get the collection url from the model instance", ->
Ryggrad.Model.host = ""
User.scope = "admin"
user = new User(id: 1)
Ryggrad.Ajax.getCollectionURL(user).should.be "/admin/users"
user.scope = "/root"
Ryggrad.Ajax.getCollectionURL(user).should.be "/root/users"
user.scope = ->
"/roots/" + @id
Ryggrad.Ajax.getCollectionURL(user).should.be "/roots/1/users"
|
[
{
"context": "nfirmation token from the email.'\n example: '4-32fad81jdaf$329'\n exits:\n success:\n description: 'Email ",
"end": 231,
"score": 0.9965340495109558,
"start": 214,
"tag": "PASSWORD",
"value": "4-32fad81jdaf$329"
}
] | api/controllers/auth/confirm-email.coffee | nkofl/sails-1.0-template | 0 | module.exports =
friendlyName: 'Confirm email'
description: 'Confirm an email address for new or edited users'
inputs:
token:
description: 'The confirmation token from the email.'
example: '4-32fad81jdaf$329'
exits:
success:
description: 'Email address confirmed'
redirect:
description: 'Email address confirmed'
responseType: 'redirect'
invalidOrExpiredToken:
responseType: 'expired'
description: 'The provided token is invalid or expired'
emailAddressNoLongerAvailable:
statusCode: 409
viewTemplatePath: '500'
description: 'The email address is no longer available.'
emailChangeAborted:
statusCode: 500
viewTemplatePath: '500'
description: 'The new candidate email address is missing or the change request was cancelled.'
fn: (inputs, exits) ->
if !inputs.token
sails.log.warn 'Attempting to confirm email, but no reset password token included in request! Displaying error page...'
return exits.invalidOrExpiredToken 'Bad Token'
user = await User.findOne emailToken: inputs.token
if !user || user.emailExpires <= (new Date())
return exits.invalidOrExpiredToken 'Bad Token'
if user.emailStatus == 'unconfirmed'
updatedUser = await User.update( id: user.id ).set
emailStatus: 'confirmed'
emailToken: ''
emailExpires: null
.fetch()
if updatedUser? && updatedUser.length > 0
user = updatedUser[0]
else if user.emailStatus == 'changeRequested' && user.emailChangeCandidate
if await User.count( emailAddress: user.emailChangeCandidate ) > 0
if this.req.wantsJSON || this.req.isSocket
return exits.emailAddressNoLongerAvailable()
else
await sails.helpers.flash this.req, 'Email address no longer available'
return exits.redirect '/'
updatedUser = await User.update({ id: user.id }).set
emailStatus: 'confirmed'
emailToken: ''
emailExpires: null
email: user.emailChangeCandidate
emailChangeCandidate: ''
.fetch()
else
updatedUser = null
if updatedUser? && updatedUser.length > 0
this.req.session.user = updatedUser[0]
if this.req.wantsJSON || this.req.isSocket
exits.success()
else
await sails.helpers.flash this.req, 'Email address confirmed'
exits.redirect '/'
| 116036 | module.exports =
friendlyName: 'Confirm email'
description: 'Confirm an email address for new or edited users'
inputs:
token:
description: 'The confirmation token from the email.'
example: '<PASSWORD>'
exits:
success:
description: 'Email address confirmed'
redirect:
description: 'Email address confirmed'
responseType: 'redirect'
invalidOrExpiredToken:
responseType: 'expired'
description: 'The provided token is invalid or expired'
emailAddressNoLongerAvailable:
statusCode: 409
viewTemplatePath: '500'
description: 'The email address is no longer available.'
emailChangeAborted:
statusCode: 500
viewTemplatePath: '500'
description: 'The new candidate email address is missing or the change request was cancelled.'
fn: (inputs, exits) ->
if !inputs.token
sails.log.warn 'Attempting to confirm email, but no reset password token included in request! Displaying error page...'
return exits.invalidOrExpiredToken 'Bad Token'
user = await User.findOne emailToken: inputs.token
if !user || user.emailExpires <= (new Date())
return exits.invalidOrExpiredToken 'Bad Token'
if user.emailStatus == 'unconfirmed'
updatedUser = await User.update( id: user.id ).set
emailStatus: 'confirmed'
emailToken: ''
emailExpires: null
.fetch()
if updatedUser? && updatedUser.length > 0
user = updatedUser[0]
else if user.emailStatus == 'changeRequested' && user.emailChangeCandidate
if await User.count( emailAddress: user.emailChangeCandidate ) > 0
if this.req.wantsJSON || this.req.isSocket
return exits.emailAddressNoLongerAvailable()
else
await sails.helpers.flash this.req, 'Email address no longer available'
return exits.redirect '/'
updatedUser = await User.update({ id: user.id }).set
emailStatus: 'confirmed'
emailToken: ''
emailExpires: null
email: user.emailChangeCandidate
emailChangeCandidate: ''
.fetch()
else
updatedUser = null
if updatedUser? && updatedUser.length > 0
this.req.session.user = updatedUser[0]
if this.req.wantsJSON || this.req.isSocket
exits.success()
else
await sails.helpers.flash this.req, 'Email address confirmed'
exits.redirect '/'
| true | module.exports =
friendlyName: 'Confirm email'
description: 'Confirm an email address for new or edited users'
inputs:
token:
description: 'The confirmation token from the email.'
example: 'PI:PASSWORD:<PASSWORD>END_PI'
exits:
success:
description: 'Email address confirmed'
redirect:
description: 'Email address confirmed'
responseType: 'redirect'
invalidOrExpiredToken:
responseType: 'expired'
description: 'The provided token is invalid or expired'
emailAddressNoLongerAvailable:
statusCode: 409
viewTemplatePath: '500'
description: 'The email address is no longer available.'
emailChangeAborted:
statusCode: 500
viewTemplatePath: '500'
description: 'The new candidate email address is missing or the change request was cancelled.'
fn: (inputs, exits) ->
if !inputs.token
sails.log.warn 'Attempting to confirm email, but no reset password token included in request! Displaying error page...'
return exits.invalidOrExpiredToken 'Bad Token'
user = await User.findOne emailToken: inputs.token
if !user || user.emailExpires <= (new Date())
return exits.invalidOrExpiredToken 'Bad Token'
if user.emailStatus == 'unconfirmed'
updatedUser = await User.update( id: user.id ).set
emailStatus: 'confirmed'
emailToken: ''
emailExpires: null
.fetch()
if updatedUser? && updatedUser.length > 0
user = updatedUser[0]
else if user.emailStatus == 'changeRequested' && user.emailChangeCandidate
if await User.count( emailAddress: user.emailChangeCandidate ) > 0
if this.req.wantsJSON || this.req.isSocket
return exits.emailAddressNoLongerAvailable()
else
await sails.helpers.flash this.req, 'Email address no longer available'
return exits.redirect '/'
updatedUser = await User.update({ id: user.id }).set
emailStatus: 'confirmed'
emailToken: ''
emailExpires: null
email: user.emailChangeCandidate
emailChangeCandidate: ''
.fetch()
else
updatedUser = null
if updatedUser? && updatedUser.length > 0
this.req.session.user = updatedUser[0]
if this.req.wantsJSON || this.req.isSocket
exits.success()
else
await sails.helpers.flash this.req, 'Email address confirmed'
exits.redirect '/'
|
[
{
"context": "uments\nargv = yargs\n .usage('Usage: $0 --token 377sdgsr32r3afpafsp ' +\n \t'--mongoDb \\\"mongodb://localhost:27017/g",
"end": 638,
"score": 0.9949950575828552,
"start": 619,
"tag": "PASSWORD",
"value": "377sdgsr32r3afpafsp"
}
] | muse-crawlers/github_crawler/src/githubSearch.coffee | esenator/muse | 0 | ##
## Copyright (c) 2014-2017 Leidos.
##
## License: 3-clause BSD, see https://opensource.org/licenses/BSD-3-Clause
##
##
## Developed under contract #FA8750-14-C-0241
##
chalk = require 'chalk'
https = require 'https'
url = require 'url'
sleep = require 'sleep'
uuid = require 'uuid'
yargs = require 'yargs'
fs = require 'fs'
util = require 'util'
octonode = require 'octonode'
async = require 'async'
GitCrawler = require './GitCrawler'
require 'shelljs/global'
mongodb = require 'mongodb'
mongo = mongodb.MongoClient
redisdb = require 'redis'
# Command line arguments
argv = yargs
.usage('Usage: $0 --token 377sdgsr32r3afpafsp ' +
'--mongoDb \"mongodb://localhost:27017/github\" ' +
'--mongoCollection github_1 ' +
'--redisHost \"localhost\" ' +
'--redisDb 8 ' +
'--out /datastore' +
'--query github_query')
.demand(['token','mongoDb', 'mongoCollection', 'out', 'query'])
.argv;
token = argv.token
db_url = argv.mongoDb
db_collection = argv.mongoCollection
download_path = argv.out
redis_database = argv.redisDb
redis_host = argv.redisHost
san_path1 = '/data/corpus_0to7'
san_path2 = '/data/corpus_8tof'
query = argv.query
github = octonode.client token
process.title = "github-search-crawler";
# Check for required software
required_sw = ["git"]
for app in required_sw
if not which app
console.log chalk.red 'Fatal error: requires ' + app
# Display download location
console.log ''
console.log 'Projects will be downloaded to:'
console.log ' ', chalk.yellow download_path
mongo.connect db_url, (err, db) =>
console.log ''
console.log 'Connecting to mongodb at ', chalk.yellow db_url
console.log " unable to access database: #{err}" if err
collection = db.collection db_collection
console.log ' using collection ', chalk.yellow db_collection
# Next step
doRedisConnect collection
getPath = (download_path, uuid) =>
result = uuid.split("", 8)
res_path = ''
for res in result
res_path += res + '/'
return download_path + '/' + res_path + uuid
# Open redis connection
doRedisConnect = (mongo_collection) =>
console.log ''
console.log 'Connecting to redis server at ', chalk.yellow redis_host
redis = redisdb.createClient 6379, redis_host, {}
redis.on 'connect', (err, res) =>
redis.select redis_database, () =>
console.log ' using database ' , chalk.yellow redis_database
start mongo_collection, redis
redis.on 'error', (err) =>
console.log chalk.red "error event - " + redis_host + ":6379 - " + err
start = (mongo_collection, redis ) =>
console.log ''
console.log 'Starting GitHub Search-Query Crawl...'
console.log ''
number = 1
pages = [1,2,3,4,5,6,7,8,9,10]
ghsearch = github.search()
async.eachSeries pages, (page, callback1) =>
console.log ''
ghsearch.repos {q: query, page: page, per_page: 100}, (err, results) =>
if err
console.log err
return callback1()
else
console.log 'Github Search returned: ' + results.total_count
console.log 'Page: ' + page
console.log 'Total items on page: ' + results.items.length
async.eachSeries results.items, (repo, callback) =>
console.log '---------------------------------------'
console.log 'Working on #' + number++ + ' of ' + results.total_count
console.log ' projectID: ' + repo.id + ' name: ' + repo.full_name
console.log ''
mongo_collection.findOne { id: {$gt: parseInt(repo.id)}}, (err, project) =>
if err
console.log chalk.red " Mongo: No project found"
return callback()
else
if project
console.log ' Mongo: already has projectID'
redisCheck redis, repo, callback
else
console.log ' Mongo: not found; inserting now'
mongo_collection.insert repo, {w: 1}, (err, docs) =>
if err
console.log err
return callback()
else
redisCheck redis, repo, callback
redisCheck = (redis, project, callback) =>
console.log ''
console.log ' Redis: checking github id: ' + chalk.blue(project.id)
redis.get 'id-to-uuid:github:' + project.id.toString(), (err, reply) =>
id = ''
if err
console.log chalk.red(err)
return callback()
else
if reply
console.log chalk.yellow(' already exists; overwriting...')
id = reply
else
console.log ' generating a new uuid'
id = uuid.v4()
redis.set 'id-to-uuid:github:' + project.id.toString(), id.toString(), (err, reply) =>
if err
console.log chalk.red err
return callback()
else
redis.set 'id-to-uuid:github:' + project.id.toString(), id.toString(), (err, reply) =>
if err
console.log chalk.red err
return callback()
console.log ' is uniquely identified as ', chalk.magenta(id)
console.log ''
project_path = getPath(san_path1,id)
fs.exists project_path, (exists) =>
if exists
console.log ' already exists in corpus at: ' + san_path1
return callback()
else
project_path = getPath(san_path2,id)
fs.exists project_path, (exists) =>
if exists
console.log ' already exists in corpus at ' + san_path2
return callback()
else
project_path = getPath(download_path,id)
fs.exists project_path, (exists) =>
if exists
console.log ' already downloaded at: ' + download_path
return callback()
else
gc = GitCrawler(github, download_path)
github.limit (err, left, max) =>
console.log " Rate limiting remaining: " + left + " of " + max
console.log ""
if left < 100
console.log 'sleeping 10 minutes'
setTimeout(900000) =>
gc.download project.full_name, id, () =>
return callback()
else
gc.download project.full_name, id, () =>
return callback()
| 114170 | ##
## Copyright (c) 2014-2017 Leidos.
##
## License: 3-clause BSD, see https://opensource.org/licenses/BSD-3-Clause
##
##
## Developed under contract #FA8750-14-C-0241
##
chalk = require 'chalk'
https = require 'https'
url = require 'url'
sleep = require 'sleep'
uuid = require 'uuid'
yargs = require 'yargs'
fs = require 'fs'
util = require 'util'
octonode = require 'octonode'
async = require 'async'
GitCrawler = require './GitCrawler'
require 'shelljs/global'
mongodb = require 'mongodb'
mongo = mongodb.MongoClient
redisdb = require 'redis'
# Command line arguments
argv = yargs
.usage('Usage: $0 --token <PASSWORD> ' +
'--mongoDb \"mongodb://localhost:27017/github\" ' +
'--mongoCollection github_1 ' +
'--redisHost \"localhost\" ' +
'--redisDb 8 ' +
'--out /datastore' +
'--query github_query')
.demand(['token','mongoDb', 'mongoCollection', 'out', 'query'])
.argv;
token = argv.token
db_url = argv.mongoDb
db_collection = argv.mongoCollection
download_path = argv.out
redis_database = argv.redisDb
redis_host = argv.redisHost
san_path1 = '/data/corpus_0to7'
san_path2 = '/data/corpus_8tof'
query = argv.query
github = octonode.client token
process.title = "github-search-crawler";
# Check for required software
required_sw = ["git"]
for app in required_sw
if not which app
console.log chalk.red 'Fatal error: requires ' + app
# Display download location
console.log ''
console.log 'Projects will be downloaded to:'
console.log ' ', chalk.yellow download_path
mongo.connect db_url, (err, db) =>
console.log ''
console.log 'Connecting to mongodb at ', chalk.yellow db_url
console.log " unable to access database: #{err}" if err
collection = db.collection db_collection
console.log ' using collection ', chalk.yellow db_collection
# Next step
doRedisConnect collection
getPath = (download_path, uuid) =>
result = uuid.split("", 8)
res_path = ''
for res in result
res_path += res + '/'
return download_path + '/' + res_path + uuid
# Open redis connection
doRedisConnect = (mongo_collection) =>
console.log ''
console.log 'Connecting to redis server at ', chalk.yellow redis_host
redis = redisdb.createClient 6379, redis_host, {}
redis.on 'connect', (err, res) =>
redis.select redis_database, () =>
console.log ' using database ' , chalk.yellow redis_database
start mongo_collection, redis
redis.on 'error', (err) =>
console.log chalk.red "error event - " + redis_host + ":6379 - " + err
start = (mongo_collection, redis ) =>
console.log ''
console.log 'Starting GitHub Search-Query Crawl...'
console.log ''
number = 1
pages = [1,2,3,4,5,6,7,8,9,10]
ghsearch = github.search()
async.eachSeries pages, (page, callback1) =>
console.log ''
ghsearch.repos {q: query, page: page, per_page: 100}, (err, results) =>
if err
console.log err
return callback1()
else
console.log 'Github Search returned: ' + results.total_count
console.log 'Page: ' + page
console.log 'Total items on page: ' + results.items.length
async.eachSeries results.items, (repo, callback) =>
console.log '---------------------------------------'
console.log 'Working on #' + number++ + ' of ' + results.total_count
console.log ' projectID: ' + repo.id + ' name: ' + repo.full_name
console.log ''
mongo_collection.findOne { id: {$gt: parseInt(repo.id)}}, (err, project) =>
if err
console.log chalk.red " Mongo: No project found"
return callback()
else
if project
console.log ' Mongo: already has projectID'
redisCheck redis, repo, callback
else
console.log ' Mongo: not found; inserting now'
mongo_collection.insert repo, {w: 1}, (err, docs) =>
if err
console.log err
return callback()
else
redisCheck redis, repo, callback
redisCheck = (redis, project, callback) =>
console.log ''
console.log ' Redis: checking github id: ' + chalk.blue(project.id)
redis.get 'id-to-uuid:github:' + project.id.toString(), (err, reply) =>
id = ''
if err
console.log chalk.red(err)
return callback()
else
if reply
console.log chalk.yellow(' already exists; overwriting...')
id = reply
else
console.log ' generating a new uuid'
id = uuid.v4()
redis.set 'id-to-uuid:github:' + project.id.toString(), id.toString(), (err, reply) =>
if err
console.log chalk.red err
return callback()
else
redis.set 'id-to-uuid:github:' + project.id.toString(), id.toString(), (err, reply) =>
if err
console.log chalk.red err
return callback()
console.log ' is uniquely identified as ', chalk.magenta(id)
console.log ''
project_path = getPath(san_path1,id)
fs.exists project_path, (exists) =>
if exists
console.log ' already exists in corpus at: ' + san_path1
return callback()
else
project_path = getPath(san_path2,id)
fs.exists project_path, (exists) =>
if exists
console.log ' already exists in corpus at ' + san_path2
return callback()
else
project_path = getPath(download_path,id)
fs.exists project_path, (exists) =>
if exists
console.log ' already downloaded at: ' + download_path
return callback()
else
gc = GitCrawler(github, download_path)
github.limit (err, left, max) =>
console.log " Rate limiting remaining: " + left + " of " + max
console.log ""
if left < 100
console.log 'sleeping 10 minutes'
setTimeout(900000) =>
gc.download project.full_name, id, () =>
return callback()
else
gc.download project.full_name, id, () =>
return callback()
| true | ##
## Copyright (c) 2014-2017 Leidos.
##
## License: 3-clause BSD, see https://opensource.org/licenses/BSD-3-Clause
##
##
## Developed under contract #FA8750-14-C-0241
##
chalk = require 'chalk'
https = require 'https'
url = require 'url'
sleep = require 'sleep'
uuid = require 'uuid'
yargs = require 'yargs'
fs = require 'fs'
util = require 'util'
octonode = require 'octonode'
async = require 'async'
GitCrawler = require './GitCrawler'
require 'shelljs/global'
mongodb = require 'mongodb'
mongo = mongodb.MongoClient
redisdb = require 'redis'
# Command line arguments
argv = yargs
.usage('Usage: $0 --token PI:PASSWORD:<PASSWORD>END_PI ' +
'--mongoDb \"mongodb://localhost:27017/github\" ' +
'--mongoCollection github_1 ' +
'--redisHost \"localhost\" ' +
'--redisDb 8 ' +
'--out /datastore' +
'--query github_query')
.demand(['token','mongoDb', 'mongoCollection', 'out', 'query'])
.argv;
token = argv.token
db_url = argv.mongoDb
db_collection = argv.mongoCollection
download_path = argv.out
redis_database = argv.redisDb
redis_host = argv.redisHost
san_path1 = '/data/corpus_0to7'
san_path2 = '/data/corpus_8tof'
query = argv.query
github = octonode.client token
process.title = "github-search-crawler";
# Check for required software
required_sw = ["git"]
for app in required_sw
if not which app
console.log chalk.red 'Fatal error: requires ' + app
# Display download location
console.log ''
console.log 'Projects will be downloaded to:'
console.log ' ', chalk.yellow download_path
mongo.connect db_url, (err, db) =>
console.log ''
console.log 'Connecting to mongodb at ', chalk.yellow db_url
console.log " unable to access database: #{err}" if err
collection = db.collection db_collection
console.log ' using collection ', chalk.yellow db_collection
# Next step
doRedisConnect collection
getPath = (download_path, uuid) =>
result = uuid.split("", 8)
res_path = ''
for res in result
res_path += res + '/'
return download_path + '/' + res_path + uuid
# Open redis connection
doRedisConnect = (mongo_collection) =>
console.log ''
console.log 'Connecting to redis server at ', chalk.yellow redis_host
redis = redisdb.createClient 6379, redis_host, {}
redis.on 'connect', (err, res) =>
redis.select redis_database, () =>
console.log ' using database ' , chalk.yellow redis_database
start mongo_collection, redis
redis.on 'error', (err) =>
console.log chalk.red "error event - " + redis_host + ":6379 - " + err
start = (mongo_collection, redis ) =>
console.log ''
console.log 'Starting GitHub Search-Query Crawl...'
console.log ''
number = 1
pages = [1,2,3,4,5,6,7,8,9,10]
ghsearch = github.search()
async.eachSeries pages, (page, callback1) =>
console.log ''
ghsearch.repos {q: query, page: page, per_page: 100}, (err, results) =>
if err
console.log err
return callback1()
else
console.log 'Github Search returned: ' + results.total_count
console.log 'Page: ' + page
console.log 'Total items on page: ' + results.items.length
async.eachSeries results.items, (repo, callback) =>
console.log '---------------------------------------'
console.log 'Working on #' + number++ + ' of ' + results.total_count
console.log ' projectID: ' + repo.id + ' name: ' + repo.full_name
console.log ''
mongo_collection.findOne { id: {$gt: parseInt(repo.id)}}, (err, project) =>
if err
console.log chalk.red " Mongo: No project found"
return callback()
else
if project
console.log ' Mongo: already has projectID'
redisCheck redis, repo, callback
else
console.log ' Mongo: not found; inserting now'
mongo_collection.insert repo, {w: 1}, (err, docs) =>
if err
console.log err
return callback()
else
redisCheck redis, repo, callback
redisCheck = (redis, project, callback) =>
console.log ''
console.log ' Redis: checking github id: ' + chalk.blue(project.id)
redis.get 'id-to-uuid:github:' + project.id.toString(), (err, reply) =>
id = ''
if err
console.log chalk.red(err)
return callback()
else
if reply
console.log chalk.yellow(' already exists; overwriting...')
id = reply
else
console.log ' generating a new uuid'
id = uuid.v4()
redis.set 'id-to-uuid:github:' + project.id.toString(), id.toString(), (err, reply) =>
if err
console.log chalk.red err
return callback()
else
redis.set 'id-to-uuid:github:' + project.id.toString(), id.toString(), (err, reply) =>
if err
console.log chalk.red err
return callback()
console.log ' is uniquely identified as ', chalk.magenta(id)
console.log ''
project_path = getPath(san_path1,id)
fs.exists project_path, (exists) =>
if exists
console.log ' already exists in corpus at: ' + san_path1
return callback()
else
project_path = getPath(san_path2,id)
fs.exists project_path, (exists) =>
if exists
console.log ' already exists in corpus at ' + san_path2
return callback()
else
project_path = getPath(download_path,id)
fs.exists project_path, (exists) =>
if exists
console.log ' already downloaded at: ' + download_path
return callback()
else
gc = GitCrawler(github, download_path)
github.limit (err, left, max) =>
console.log " Rate limiting remaining: " + left + " of " + max
console.log ""
if left < 100
console.log 'sleeping 10 minutes'
setTimeout(900000) =>
gc.download project.full_name, id, () =>
return callback()
else
gc.download project.full_name, id, () =>
return callback()
|
[
{
"context": "s = 0\ntotalHoursAllocated = (end, start) ->\n # As Professor Bettati would say, this is programming at th",
"end": 2599,
"score": 0.8860546946525574,
"start": 2595,
"tag": "NAME",
"value": "Prof"
},
{
"context": "\ntotalHoursAllocated = (end, start) ->\n # As Profess... | app/assets/javascripts/setup.coffee | dasanurag/Study-Tracker | 1 | errorList = []
copyschedule = ->
$div = $('div[id^="single-schedule"]:last')
num = parseInt($div.prop('id').match(/\d+/g), 10) + 1
$div_orig = $('div[id="single-schedule-0"]:first')
$newsched = $div_orig.clone().prop('id', 'single-schedule-' + num)
$div_current = this.closest('div[id^="single-subject"]')
parent_header = $div_current.id
$last_form = $("#" + parent_header).find('div[id^="single-schedule"]:last')
$last_form.after $newsched
return
deleteschedule = ->
$div_current = this.closest('div[id^="single-subject"]')
parent_header = $div_current.id
$div = $("#" + parent_header).find('div[id^="single-schedule"]:last')
if parseInt($div.prop('id').match(/\d+/g), 10) > 1
$div.remove()
return
copysubject = ->
$div = $('div[id^="single-subject"]:last')
num = parseInt($div.prop('id').match(/\d+/g), 10) + 1
$div_orig = $('div[id="single-subject-0"]')
$newsched = $div_orig.clone().prop('id', 'single-subject-' + num)
$newsched.find('.btn-copy').on 'click', copyschedule
$newsched.find('.btn-delete').on 'click', deleteschedule
$div.after $newsched
return
deletesubject = ->
div_current = $('div[id^="single-subject"]:last')
parent_header = div_current.prop("id")
if parseInt(parent_header.match(/\d+/g), 10) > 1
div_current.remove()
return
dateToday = ->
today = new Date
dd = today.getDate()
mm = today.getMonth() + 1
#January is 0!
yyyy = today.getFullYear()
if dd < 10
dd = '0' + dd
if mm < 10
mm = '0' + mm
today = yyyy + '-' + mm + '-' + dd
return today
validateStartDate = (startDate) ->
# validate that date entered is not in past
today = dateToday()
if startDate == ""
errorList.push "Start date is empty."
return false
if startDate < today
errorList.push "Start date is in the past!"
#$('#startdate').after '<p>You sure, you can time travel?.</p>'
return false
true
validateEndDate = (endDate, startDate) ->
if endDate == ""
errorList.push "End date can not be empty"
return false
if endDate < startDate
errorList.push "End date can not be less than start date"
#$('#enddate').after '<p>Wah Modiji Wah!</p>'
return false
true
validateSubjectName = (subject) ->
if subject == ""
errorList.push "Subject field can not be empty"
#$('#subject').after '<p>Empty, eh? </p>'
return false
true
validateHours = (hours) ->
if hours == "" || hours <= 0
errorList.push "hours field can not be empty"
return false
true
totalHours = 0
totalHoursAllocated = (end, start) ->
# As Professor Bettati would say, this is programming at the level of a baboon
# but the following hacky way gets us the time difference
timeStart = new Date('01/19/2038 ' + start).getHours()
timeEnd = new Date('01/19/2038 ' + end).getHours()
# the end is near
hourDiff = timeEnd - timeStart
# collect hours
totalHours += hourDiff
validateHoursAllocated = (hours) ->
if totalHours != parseInt(hours)
errorList.push "Total hours are not consistent."
totalHours = 0
return false
totalHours = 0
true
parseAndValidate = ->
formObj = parseForm()
###
formObj = {
subjects : [{
end_date: "2018-11-02",
hours: "1",
name: "Physics"
schedules: [{
day: "mon",
start: "11:11",
end: "12:35"
},{
day: "tue",
start: "23:12",
end: " 23:35"
}]
},{
end_date: "2018-11-03",
hours: "1",
name: "Chemsitry"
schedules: [{
day: "wed",
start: "1:11",
end: "13:35"
},{
day: "thur",
start: "4:12",
end: " 5:35"
},{
day: "fri",
start: "2:12",
end: " 3:35"
}]
}]
}
###
errorList = []
errorText = ''
$('#error1').remove()
if validate(formObj)
#send to controller
$.ajax
type: 'POST'
url: '../setup/create'
data: formObj
dataType: 'text'
success: (resultData) ->
window.location.replace("../dashboard/index");
return
else
error = 0
errorText = '<li id="error1">'
while error < errorList.length
errorText += '<span> '+ errorList[error] + '</span>'
error++
errorText+= '</li>'
$('#error').after(errorText)
#alert 'Totally unproductive error message'
validate = (formObj) ->
json_s = JSON.stringify(formObj)
json = JSON.parse(json_s)
i = 0 # to iterate subjects
while i < json.subjects.length
subject = json.subjects[i].name
if(!validateSubjectName(subject))
return false
hours = json.subjects[i].hours
if(!validateHours(hours))
return false
startDate = json.subjects[i].start_date
if(!validateStartDate(startDate))
return false
endDate = json.subjects[i].end_date
if(!validateEndDate(endDate, startDate))
return false
schedules = json.subjects[i].schedules
j = 0 # to iterate schedules
diff = 0 # will collect total hours
while j < schedules.length
# total time should be equal to 'hours' alloted
totalHoursAllocated(schedules[j].end, schedules[j].start)
j++
if(!validateHoursAllocated(hours))
return false
i++
return true
parseForm = ->
formObj = {}
formObj['subjects'] = []
subjects = $('div[id^="single-subject"]')
i = 1
while i < subjects.length
temp_subj = {}
subject = $(subjects[i])
temp_subj['name'] = subject.find('input[id="subject"]').val()
temp_subj['hours'] = subject.find('input[id="hours"]').val()
temp_subj['start_date'] = subject.find('input[id="startdate"]').val()
temp_subj['end_date'] = subject.find('input[id="enddate"]').val()
temp_subj['schedules'] = []
schedules = subject.find('div[id^="single-schedule"]')
j=1
while j < schedules.length
temp_sched = {}
schedule = $(schedules[j])
temp_sched['day'] = schedule.find('select[id="day"]').val()
temp_sched['start'] = schedule.find('input[id="starttime"]').val()
temp_sched['end'] = schedule.find('input[id="endtime"]').val()
temp_subj['schedules'].push(temp_sched)
j++
formObj['subjects'].push(temp_subj)
i++
return formObj
$(document).ready ->
$ ->
$('button[class*=btn-copy]').on 'click', copyschedule
return
$ ->
$('.btn-delete').on 'click', deleteschedule
return
$ ->
$('.btn-subject').on 'click', copysubject
$ ->
$('.btn-del-subject').on 'click', deletesubject
$ ->
$('.btn-submit').on 'click', parseAndValidate
return
return
return | 118471 | errorList = []
copyschedule = ->
$div = $('div[id^="single-schedule"]:last')
num = parseInt($div.prop('id').match(/\d+/g), 10) + 1
$div_orig = $('div[id="single-schedule-0"]:first')
$newsched = $div_orig.clone().prop('id', 'single-schedule-' + num)
$div_current = this.closest('div[id^="single-subject"]')
parent_header = $div_current.id
$last_form = $("#" + parent_header).find('div[id^="single-schedule"]:last')
$last_form.after $newsched
return
deleteschedule = ->
$div_current = this.closest('div[id^="single-subject"]')
parent_header = $div_current.id
$div = $("#" + parent_header).find('div[id^="single-schedule"]:last')
if parseInt($div.prop('id').match(/\d+/g), 10) > 1
$div.remove()
return
copysubject = ->
$div = $('div[id^="single-subject"]:last')
num = parseInt($div.prop('id').match(/\d+/g), 10) + 1
$div_orig = $('div[id="single-subject-0"]')
$newsched = $div_orig.clone().prop('id', 'single-subject-' + num)
$newsched.find('.btn-copy').on 'click', copyschedule
$newsched.find('.btn-delete').on 'click', deleteschedule
$div.after $newsched
return
deletesubject = ->
div_current = $('div[id^="single-subject"]:last')
parent_header = div_current.prop("id")
if parseInt(parent_header.match(/\d+/g), 10) > 1
div_current.remove()
return
dateToday = ->
today = new Date
dd = today.getDate()
mm = today.getMonth() + 1
#January is 0!
yyyy = today.getFullYear()
if dd < 10
dd = '0' + dd
if mm < 10
mm = '0' + mm
today = yyyy + '-' + mm + '-' + dd
return today
validateStartDate = (startDate) ->
# validate that date entered is not in past
today = dateToday()
if startDate == ""
errorList.push "Start date is empty."
return false
if startDate < today
errorList.push "Start date is in the past!"
#$('#startdate').after '<p>You sure, you can time travel?.</p>'
return false
true
validateEndDate = (endDate, startDate) ->
if endDate == ""
errorList.push "End date can not be empty"
return false
if endDate < startDate
errorList.push "End date can not be less than start date"
#$('#enddate').after '<p>Wah Modiji Wah!</p>'
return false
true
validateSubjectName = (subject) ->
if subject == ""
errorList.push "Subject field can not be empty"
#$('#subject').after '<p>Empty, eh? </p>'
return false
true
validateHours = (hours) ->
if hours == "" || hours <= 0
errorList.push "hours field can not be empty"
return false
true
totalHours = 0
totalHoursAllocated = (end, start) ->
# As <NAME> <NAME> <NAME> would say, this is programming at the level of a baboon
# but the following hacky way gets us the time difference
timeStart = new Date('01/19/2038 ' + start).getHours()
timeEnd = new Date('01/19/2038 ' + end).getHours()
# the end is near
hourDiff = timeEnd - timeStart
# collect hours
totalHours += hourDiff
validateHoursAllocated = (hours) ->
if totalHours != parseInt(hours)
errorList.push "Total hours are not consistent."
totalHours = 0
return false
totalHours = 0
true
parseAndValidate = ->
formObj = parseForm()
###
formObj = {
subjects : [{
end_date: "2018-11-02",
hours: "1",
name: "<NAME>"
schedules: [{
day: "mon",
start: "11:11",
end: "12:35"
},{
day: "tue",
start: "23:12",
end: " 23:35"
}]
},{
end_date: "2018-11-03",
hours: "1",
name: "<NAME>"
schedules: [{
day: "wed",
start: "1:11",
end: "13:35"
},{
day: "thur",
start: "4:12",
end: " 5:35"
},{
day: "fri",
start: "2:12",
end: " 3:35"
}]
}]
}
###
errorList = []
errorText = ''
$('#error1').remove()
if validate(formObj)
#send to controller
$.ajax
type: 'POST'
url: '../setup/create'
data: formObj
dataType: 'text'
success: (resultData) ->
window.location.replace("../dashboard/index");
return
else
error = 0
errorText = '<li id="error1">'
while error < errorList.length
errorText += '<span> '+ errorList[error] + '</span>'
error++
errorText+= '</li>'
$('#error').after(errorText)
#alert 'Totally unproductive error message'
validate = (formObj) ->
json_s = JSON.stringify(formObj)
json = JSON.parse(json_s)
i = 0 # to iterate subjects
while i < json.subjects.length
subject = json.subjects[i].name
if(!validateSubjectName(subject))
return false
hours = json.subjects[i].hours
if(!validateHours(hours))
return false
startDate = json.subjects[i].start_date
if(!validateStartDate(startDate))
return false
endDate = json.subjects[i].end_date
if(!validateEndDate(endDate, startDate))
return false
schedules = json.subjects[i].schedules
j = 0 # to iterate schedules
diff = 0 # will collect total hours
while j < schedules.length
# total time should be equal to 'hours' alloted
totalHoursAllocated(schedules[j].end, schedules[j].start)
j++
if(!validateHoursAllocated(hours))
return false
i++
return true
parseForm = ->
formObj = {}
formObj['subjects'] = []
subjects = $('div[id^="single-subject"]')
i = 1
while i < subjects.length
temp_subj = {}
subject = $(subjects[i])
temp_subj['name'] = subject.find('input[id="subject"]').val()
temp_subj['hours'] = subject.find('input[id="hours"]').val()
temp_subj['start_date'] = subject.find('input[id="startdate"]').val()
temp_subj['end_date'] = subject.find('input[id="enddate"]').val()
temp_subj['schedules'] = []
schedules = subject.find('div[id^="single-schedule"]')
j=1
while j < schedules.length
temp_sched = {}
schedule = $(schedules[j])
temp_sched['day'] = schedule.find('select[id="day"]').val()
temp_sched['start'] = schedule.find('input[id="starttime"]').val()
temp_sched['end'] = schedule.find('input[id="endtime"]').val()
temp_subj['schedules'].push(temp_sched)
j++
formObj['subjects'].push(temp_subj)
i++
return formObj
$(document).ready ->
$ ->
$('button[class*=btn-copy]').on 'click', copyschedule
return
$ ->
$('.btn-delete').on 'click', deleteschedule
return
$ ->
$('.btn-subject').on 'click', copysubject
$ ->
$('.btn-del-subject').on 'click', deletesubject
$ ->
$('.btn-submit').on 'click', parseAndValidate
return
return
return | true | errorList = []
copyschedule = ->
$div = $('div[id^="single-schedule"]:last')
num = parseInt($div.prop('id').match(/\d+/g), 10) + 1
$div_orig = $('div[id="single-schedule-0"]:first')
$newsched = $div_orig.clone().prop('id', 'single-schedule-' + num)
$div_current = this.closest('div[id^="single-subject"]')
parent_header = $div_current.id
$last_form = $("#" + parent_header).find('div[id^="single-schedule"]:last')
$last_form.after $newsched
return
deleteschedule = ->
$div_current = this.closest('div[id^="single-subject"]')
parent_header = $div_current.id
$div = $("#" + parent_header).find('div[id^="single-schedule"]:last')
if parseInt($div.prop('id').match(/\d+/g), 10) > 1
$div.remove()
return
copysubject = ->
$div = $('div[id^="single-subject"]:last')
num = parseInt($div.prop('id').match(/\d+/g), 10) + 1
$div_orig = $('div[id="single-subject-0"]')
$newsched = $div_orig.clone().prop('id', 'single-subject-' + num)
$newsched.find('.btn-copy').on 'click', copyschedule
$newsched.find('.btn-delete').on 'click', deleteschedule
$div.after $newsched
return
deletesubject = ->
div_current = $('div[id^="single-subject"]:last')
parent_header = div_current.prop("id")
if parseInt(parent_header.match(/\d+/g), 10) > 1
div_current.remove()
return
dateToday = ->
today = new Date
dd = today.getDate()
mm = today.getMonth() + 1
#January is 0!
yyyy = today.getFullYear()
if dd < 10
dd = '0' + dd
if mm < 10
mm = '0' + mm
today = yyyy + '-' + mm + '-' + dd
return today
validateStartDate = (startDate) ->
# validate that date entered is not in past
today = dateToday()
if startDate == ""
errorList.push "Start date is empty."
return false
if startDate < today
errorList.push "Start date is in the past!"
#$('#startdate').after '<p>You sure, you can time travel?.</p>'
return false
true
validateEndDate = (endDate, startDate) ->
if endDate == ""
errorList.push "End date can not be empty"
return false
if endDate < startDate
errorList.push "End date can not be less than start date"
#$('#enddate').after '<p>Wah Modiji Wah!</p>'
return false
true
validateSubjectName = (subject) ->
if subject == ""
errorList.push "Subject field can not be empty"
#$('#subject').after '<p>Empty, eh? </p>'
return false
true
validateHours = (hours) ->
if hours == "" || hours <= 0
errorList.push "hours field can not be empty"
return false
true
totalHours = 0
totalHoursAllocated = (end, start) ->
# As PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI would say, this is programming at the level of a baboon
# but the following hacky way gets us the time difference
timeStart = new Date('01/19/2038 ' + start).getHours()
timeEnd = new Date('01/19/2038 ' + end).getHours()
# the end is near
hourDiff = timeEnd - timeStart
# collect hours
totalHours += hourDiff
validateHoursAllocated = (hours) ->
if totalHours != parseInt(hours)
errorList.push "Total hours are not consistent."
totalHours = 0
return false
totalHours = 0
true
parseAndValidate = ->
formObj = parseForm()
###
formObj = {
subjects : [{
end_date: "2018-11-02",
hours: "1",
name: "PI:NAME:<NAME>END_PI"
schedules: [{
day: "mon",
start: "11:11",
end: "12:35"
},{
day: "tue",
start: "23:12",
end: " 23:35"
}]
},{
end_date: "2018-11-03",
hours: "1",
name: "PI:NAME:<NAME>END_PI"
schedules: [{
day: "wed",
start: "1:11",
end: "13:35"
},{
day: "thur",
start: "4:12",
end: " 5:35"
},{
day: "fri",
start: "2:12",
end: " 3:35"
}]
}]
}
###
errorList = []
errorText = ''
$('#error1').remove()
if validate(formObj)
#send to controller
$.ajax
type: 'POST'
url: '../setup/create'
data: formObj
dataType: 'text'
success: (resultData) ->
window.location.replace("../dashboard/index");
return
else
error = 0
errorText = '<li id="error1">'
while error < errorList.length
errorText += '<span> '+ errorList[error] + '</span>'
error++
errorText+= '</li>'
$('#error').after(errorText)
#alert 'Totally unproductive error message'
validate = (formObj) ->
json_s = JSON.stringify(formObj)
json = JSON.parse(json_s)
i = 0 # to iterate subjects
while i < json.subjects.length
subject = json.subjects[i].name
if(!validateSubjectName(subject))
return false
hours = json.subjects[i].hours
if(!validateHours(hours))
return false
startDate = json.subjects[i].start_date
if(!validateStartDate(startDate))
return false
endDate = json.subjects[i].end_date
if(!validateEndDate(endDate, startDate))
return false
schedules = json.subjects[i].schedules
j = 0 # to iterate schedules
diff = 0 # will collect total hours
while j < schedules.length
# total time should be equal to 'hours' alloted
totalHoursAllocated(schedules[j].end, schedules[j].start)
j++
if(!validateHoursAllocated(hours))
return false
i++
return true
parseForm = ->
formObj = {}
formObj['subjects'] = []
subjects = $('div[id^="single-subject"]')
i = 1
while i < subjects.length
temp_subj = {}
subject = $(subjects[i])
temp_subj['name'] = subject.find('input[id="subject"]').val()
temp_subj['hours'] = subject.find('input[id="hours"]').val()
temp_subj['start_date'] = subject.find('input[id="startdate"]').val()
temp_subj['end_date'] = subject.find('input[id="enddate"]').val()
temp_subj['schedules'] = []
schedules = subject.find('div[id^="single-schedule"]')
j=1
while j < schedules.length
temp_sched = {}
schedule = $(schedules[j])
temp_sched['day'] = schedule.find('select[id="day"]').val()
temp_sched['start'] = schedule.find('input[id="starttime"]').val()
temp_sched['end'] = schedule.find('input[id="endtime"]').val()
temp_subj['schedules'].push(temp_sched)
j++
formObj['subjects'].push(temp_subj)
i++
return formObj
$(document).ready ->
$ ->
$('button[class*=btn-copy]').on 'click', copyschedule
return
$ ->
$('.btn-delete').on 'click', deleteschedule
return
$ ->
$('.btn-subject').on 'click', copysubject
$ ->
$('.btn-del-subject').on 'click', deletesubject
$ ->
$('.btn-submit').on 'click', parseAndValidate
return
return
return |
[
{
"context": "cs/#info.info\n\nFramer.Info =\n\ttitle: \"\"\n\tauthor: \"Tony\"\n\ttwitter: \"\"\n\tdescription: \"\"\n\ninertiaCurve = \"s",
"end": 146,
"score": 0.9983677864074707,
"start": 142,
"tag": "NAME",
"value": "Tony"
}
] | 51momentum.framer/app.coffee | gremjua-forks/100daysofframer | 26 | # Project Info
# This info is presented in a widget when you share.
# http://framerjs.com/docs/#info.info
Framer.Info =
title: ""
author: "Tony"
twitter: ""
description: ""
inertiaCurve = "spring(150, 10, 0)"
Layer::inertia = () ->
speedConstant = 80
dragDirectionisUpwards = @.draggable.calculateVelocity().y < 0
currentVelocityY = Math.abs(@.draggable.calculateVelocity().y)
currentYPosition = @.y
dragDirectionisForwards = @.draggable.calculateVelocity().x < 0
currentVelocityX = Math.abs(@.draggable.calculateVelocity().x)
currentXPosition = @.x
if dragDirectionisUpwards
@.animate
properties: y: currentYPosition - (currentVelocityY * speedConstant)
curve: inertiaCurve
else
@.animate
properties: y: currentYPosition + (currentVelocityY * speedConstant)
curve: inertiaCurve
if dragDirectionisForwards
@.animate
properties: x: currentXPosition - (currentVelocityX * speedConstant)
curve: inertiaCurve
else
@.animate
properties: x: currentXPosition + (currentVelocityX * speedConstant)
curve: inertiaCurve
@.onAnimationEnd ->
if @.maxY > Screen.height
@.animate
properties:
maxY: Screen.height
curve: inertiaCurve
if @.y < 0
@.animate
properties:
y: 0
curve: inertiaCurve
if @.maxX > Screen.width
@.animate
properties:
maxX: Screen.width
curve: inertiaCurve
if @.x < 0
@.animate
properties:
x: 0
curve: inertiaCurve
inertiaLayer = new Layer size: 180, backgroundColor: "lightblue", html: "inertia"
inertiaLayer.draggable.enabled = true
inertiaLayer.center()
inertiaLayer.centerY(-100)
momentumLayer = new Layer size: 180, backgroundColor: "lightgreen", html: "momentum"
momentumLayer.draggable.enabled = true
momentumLayer.draggable.overdrag = false
momentumLayer.center()
momentumLayer.centerY(100)
momentumLayer.draggable.momentumOptions =
tension: 200
friction: 5
momentumLayer.draggable.constraints =
x: 0
y: 0
width: Screen.width
height: Screen.height
detectHit = ->
if inertiaLayer.maxX >= momentumLayer.x and
inertiaLayer.x <= momentumLayer.maxX and
inertiaLayer.maxY >= momentumLayer.y and
inertiaLayer.y <= momentumLayer.maxY
inertiaLayer.animate
properties:
backgroundColor: "orange"
opacity: 0.7
curve: inertiaCurve
momentumLayer.animate
properties:
backgroundColor: "red"
opacity: 0.7
curve: inertiaCurve
else
inertiaLayer.animate
properties:
backgroundColor: "lightblue"
opacity: 1
curve: inertiaCurve
momentumLayer.animate
properties:
backgroundColor: "lightgreen"
opacity: 1
curve: inertiaCurve
inertiaLayer.on Events.DragEnd, ->
@.inertia()
detectHit()
@.onAnimationEnd ->
detectHit()
inertiaLayer.onMove ->
detectHit()
momentumLayer.on Events.DragEnd, ->
@.inertia()
detectHit()
@.onAnimationEnd ->
detectHit()
momentumLayer.onMove ->
detectHit()
| 195000 | # Project Info
# This info is presented in a widget when you share.
# http://framerjs.com/docs/#info.info
Framer.Info =
title: ""
author: "<NAME>"
twitter: ""
description: ""
inertiaCurve = "spring(150, 10, 0)"
Layer::inertia = () ->
speedConstant = 80
dragDirectionisUpwards = @.draggable.calculateVelocity().y < 0
currentVelocityY = Math.abs(@.draggable.calculateVelocity().y)
currentYPosition = @.y
dragDirectionisForwards = @.draggable.calculateVelocity().x < 0
currentVelocityX = Math.abs(@.draggable.calculateVelocity().x)
currentXPosition = @.x
if dragDirectionisUpwards
@.animate
properties: y: currentYPosition - (currentVelocityY * speedConstant)
curve: inertiaCurve
else
@.animate
properties: y: currentYPosition + (currentVelocityY * speedConstant)
curve: inertiaCurve
if dragDirectionisForwards
@.animate
properties: x: currentXPosition - (currentVelocityX * speedConstant)
curve: inertiaCurve
else
@.animate
properties: x: currentXPosition + (currentVelocityX * speedConstant)
curve: inertiaCurve
@.onAnimationEnd ->
if @.maxY > Screen.height
@.animate
properties:
maxY: Screen.height
curve: inertiaCurve
if @.y < 0
@.animate
properties:
y: 0
curve: inertiaCurve
if @.maxX > Screen.width
@.animate
properties:
maxX: Screen.width
curve: inertiaCurve
if @.x < 0
@.animate
properties:
x: 0
curve: inertiaCurve
inertiaLayer = new Layer size: 180, backgroundColor: "lightblue", html: "inertia"
inertiaLayer.draggable.enabled = true
inertiaLayer.center()
inertiaLayer.centerY(-100)
momentumLayer = new Layer size: 180, backgroundColor: "lightgreen", html: "momentum"
momentumLayer.draggable.enabled = true
momentumLayer.draggable.overdrag = false
momentumLayer.center()
momentumLayer.centerY(100)
momentumLayer.draggable.momentumOptions =
tension: 200
friction: 5
momentumLayer.draggable.constraints =
x: 0
y: 0
width: Screen.width
height: Screen.height
detectHit = ->
if inertiaLayer.maxX >= momentumLayer.x and
inertiaLayer.x <= momentumLayer.maxX and
inertiaLayer.maxY >= momentumLayer.y and
inertiaLayer.y <= momentumLayer.maxY
inertiaLayer.animate
properties:
backgroundColor: "orange"
opacity: 0.7
curve: inertiaCurve
momentumLayer.animate
properties:
backgroundColor: "red"
opacity: 0.7
curve: inertiaCurve
else
inertiaLayer.animate
properties:
backgroundColor: "lightblue"
opacity: 1
curve: inertiaCurve
momentumLayer.animate
properties:
backgroundColor: "lightgreen"
opacity: 1
curve: inertiaCurve
inertiaLayer.on Events.DragEnd, ->
@.inertia()
detectHit()
@.onAnimationEnd ->
detectHit()
inertiaLayer.onMove ->
detectHit()
momentumLayer.on Events.DragEnd, ->
@.inertia()
detectHit()
@.onAnimationEnd ->
detectHit()
momentumLayer.onMove ->
detectHit()
| true | # Project Info
# This info is presented in a widget when you share.
# http://framerjs.com/docs/#info.info
Framer.Info =
title: ""
author: "PI:NAME:<NAME>END_PI"
twitter: ""
description: ""
inertiaCurve = "spring(150, 10, 0)"
Layer::inertia = () ->
speedConstant = 80
dragDirectionisUpwards = @.draggable.calculateVelocity().y < 0
currentVelocityY = Math.abs(@.draggable.calculateVelocity().y)
currentYPosition = @.y
dragDirectionisForwards = @.draggable.calculateVelocity().x < 0
currentVelocityX = Math.abs(@.draggable.calculateVelocity().x)
currentXPosition = @.x
if dragDirectionisUpwards
@.animate
properties: y: currentYPosition - (currentVelocityY * speedConstant)
curve: inertiaCurve
else
@.animate
properties: y: currentYPosition + (currentVelocityY * speedConstant)
curve: inertiaCurve
if dragDirectionisForwards
@.animate
properties: x: currentXPosition - (currentVelocityX * speedConstant)
curve: inertiaCurve
else
@.animate
properties: x: currentXPosition + (currentVelocityX * speedConstant)
curve: inertiaCurve
@.onAnimationEnd ->
if @.maxY > Screen.height
@.animate
properties:
maxY: Screen.height
curve: inertiaCurve
if @.y < 0
@.animate
properties:
y: 0
curve: inertiaCurve
if @.maxX > Screen.width
@.animate
properties:
maxX: Screen.width
curve: inertiaCurve
if @.x < 0
@.animate
properties:
x: 0
curve: inertiaCurve
inertiaLayer = new Layer size: 180, backgroundColor: "lightblue", html: "inertia"
inertiaLayer.draggable.enabled = true
inertiaLayer.center()
inertiaLayer.centerY(-100)
momentumLayer = new Layer size: 180, backgroundColor: "lightgreen", html: "momentum"
momentumLayer.draggable.enabled = true
momentumLayer.draggable.overdrag = false
momentumLayer.center()
momentumLayer.centerY(100)
momentumLayer.draggable.momentumOptions =
tension: 200
friction: 5
momentumLayer.draggable.constraints =
x: 0
y: 0
width: Screen.width
height: Screen.height
detectHit = ->
if inertiaLayer.maxX >= momentumLayer.x and
inertiaLayer.x <= momentumLayer.maxX and
inertiaLayer.maxY >= momentumLayer.y and
inertiaLayer.y <= momentumLayer.maxY
inertiaLayer.animate
properties:
backgroundColor: "orange"
opacity: 0.7
curve: inertiaCurve
momentumLayer.animate
properties:
backgroundColor: "red"
opacity: 0.7
curve: inertiaCurve
else
inertiaLayer.animate
properties:
backgroundColor: "lightblue"
opacity: 1
curve: inertiaCurve
momentumLayer.animate
properties:
backgroundColor: "lightgreen"
opacity: 1
curve: inertiaCurve
inertiaLayer.on Events.DragEnd, ->
@.inertia()
detectHit()
@.onAnimationEnd ->
detectHit()
inertiaLayer.onMove ->
detectHit()
momentumLayer.on Events.DragEnd, ->
@.inertia()
detectHit()
@.onAnimationEnd ->
detectHit()
momentumLayer.onMove ->
detectHit()
|
[
{
"context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public Li",
"end": 43,
"score": 0.9999149441719055,
"start": 29,
"tag": "EMAIL",
"value": "contact@ppy.sh"
}
] | resources/assets/coffee/_classes/forum-topic-post-jump.coffee | osu-katakuna/osu-katakuna-web | 5 | # Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
# See the LICENCE file in the repository root for full licence text.
class @ForumTopicPostJump
constructor: (@forum) ->
$(document).on 'click', '.js-forum-topic-post-jump--cover', @start
$(document).on 'blur', '.js-forum-topic-post-jump--input', @end
$(document).on 'keyup', '.js-forum-topic-post-jump--input', @keyup
$.subscribe 'forum:topic:jumpTo', @end
end: =>
$('.js-forum-topic-post-jump--container').removeClass('forum-topic-nav__item--focus')
$('.js-forum-topic-post-jump--cover').show()
$('.js-forum-topic-post-jump--counter').show()
$('.js-forum-topic-post-jump--input').hide()
keyup: (e) =>
if e.keyCode == 27
$(e.currentTarget).blur()
return
input = e.currentTarget
value = input.value
numericValue = value.replace(/\D/g, '')
return if value == numericValue
input.value = numericValue
start: =>
$('.js-forum-topic-post-jump--container').addClass('forum-topic-nav__item--focus')
$('.js-forum-topic-post-jump--cover').hide()
$('.js-forum-topic-post-jump--counter').hide()
$input = $('.js-forum-topic-post-jump--input')
.val(@forum.currentPostPosition)
.show()
.focus()
$input[0].selectionStart = 0
$input[0].selectionEnd = $input.val().length
| 73960 | # Copyright (c) ppy Pty Ltd <<EMAIL>>. Licensed under the GNU Affero General Public License v3.0.
# See the LICENCE file in the repository root for full licence text.
class @ForumTopicPostJump
constructor: (@forum) ->
$(document).on 'click', '.js-forum-topic-post-jump--cover', @start
$(document).on 'blur', '.js-forum-topic-post-jump--input', @end
$(document).on 'keyup', '.js-forum-topic-post-jump--input', @keyup
$.subscribe 'forum:topic:jumpTo', @end
end: =>
$('.js-forum-topic-post-jump--container').removeClass('forum-topic-nav__item--focus')
$('.js-forum-topic-post-jump--cover').show()
$('.js-forum-topic-post-jump--counter').show()
$('.js-forum-topic-post-jump--input').hide()
keyup: (e) =>
if e.keyCode == 27
$(e.currentTarget).blur()
return
input = e.currentTarget
value = input.value
numericValue = value.replace(/\D/g, '')
return if value == numericValue
input.value = numericValue
start: =>
$('.js-forum-topic-post-jump--container').addClass('forum-topic-nav__item--focus')
$('.js-forum-topic-post-jump--cover').hide()
$('.js-forum-topic-post-jump--counter').hide()
$input = $('.js-forum-topic-post-jump--input')
.val(@forum.currentPostPosition)
.show()
.focus()
$input[0].selectionStart = 0
$input[0].selectionEnd = $input.val().length
| true | # Copyright (c) ppy Pty Ltd <PI:EMAIL:<EMAIL>END_PI>. Licensed under the GNU Affero General Public License v3.0.
# See the LICENCE file in the repository root for full licence text.
class @ForumTopicPostJump
constructor: (@forum) ->
$(document).on 'click', '.js-forum-topic-post-jump--cover', @start
$(document).on 'blur', '.js-forum-topic-post-jump--input', @end
$(document).on 'keyup', '.js-forum-topic-post-jump--input', @keyup
$.subscribe 'forum:topic:jumpTo', @end
end: =>
$('.js-forum-topic-post-jump--container').removeClass('forum-topic-nav__item--focus')
$('.js-forum-topic-post-jump--cover').show()
$('.js-forum-topic-post-jump--counter').show()
$('.js-forum-topic-post-jump--input').hide()
keyup: (e) =>
if e.keyCode == 27
$(e.currentTarget).blur()
return
input = e.currentTarget
value = input.value
numericValue = value.replace(/\D/g, '')
return if value == numericValue
input.value = numericValue
start: =>
$('.js-forum-topic-post-jump--container').addClass('forum-topic-nav__item--focus')
$('.js-forum-topic-post-jump--cover').hide()
$('.js-forum-topic-post-jump--counter').hide()
$input = $('.js-forum-topic-post-jump--input')
.val(@forum.currentPostPosition)
.show()
.focus()
$input[0].selectionStart = 0
$input[0].selectionEnd = $input.val().length
|
[
{
"context": "p, i in @props.tutorial.steps\n step._key ?= Math.random()\n <MediaCard key={step._key} className=\"t",
"end": 3714,
"score": 0.9798312187194824,
"start": 3703,
"tag": "KEY",
"value": "Math.random"
}
] | app/classifier/tutorial.cjsx | snblickhan/Panoptes-Front-End | 0 | React = require 'react'
PropTypes = require 'prop-types'
createReactClass = require 'create-react-class'
Dialog = require 'modal-form/dialog'
Translate = require 'react-translate-component'
MediaCard = require('../components/media-card').default
{Markdown} = require 'markdownz'
apiClient = require 'panoptes-client/lib/api-client'
{ Provider } = require('react-redux')
StepThrough = require('../components/step-through').default
Translations = require('./translations').default
completedThisSession = {}
window?.tutorialsCompletedThisSession = completedThisSession
module.exports = createReactClass
displayName: 'Tutorial'
statics:
find: (workflow) ->
# Prefer fetching the tutorial for the workflow, if a workflow is given.
if workflow?
apiClient.type('tutorials').get workflow_id: workflow.id
.then (tutorials) ->
# Backwards compatibility for null kind values. We assume these are standard tutorials.
onlyStandardTutorials = tutorials.filter (tutorial) ->
tutorial.kind in ['tutorial', null]
onlyStandardTutorials[0]
else
Promise.resolve()
startIfNecessary: (tutorial, user, preferences, geordi, store) ->
if tutorial?
@checkIfCompleted(tutorial, user, preferences).then (completed) =>
unless completed
@start tutorial, user, preferences, geordi, store
checkIfCompleted: (tutorial, user, preferences) ->
if user?
window.prefs = preferences
Promise.resolve preferences?.preferences?.tutorials_completed_at?[tutorial.id]?
else
Promise.resolve completedThisSession[tutorial.id]?
start: (tutorial, user, preferences, geordi, store) ->
TutorialComponent = this
if tutorial.steps.length isnt 0
awaitTutorialMedia = tutorial.get 'attached_images'
.catch ->
# Checking for attached images throws if there are none.
[]
.then (mediaResources) ->
mediaByID = {}
for mediaResource in mediaResources
mediaByID[mediaResource.id] = mediaResource
mediaByID
awaitTutorialMedia.then (mediaByID) =>
tutorialContent =
<Provider store={store}>
<Translations original={tutorial} type="tutorial">
<TutorialComponent tutorial={tutorial} media={mediaByID} preferences={preferences} user={user} geordi={geordi} />
</Translations>
</Provider>
Dialog.alert(tutorialContent, {
className: 'tutorial-dialog',
required: true,
closeButton: true
})
.catch (e) =>
console.warn e
null # We don't really care if the user canceled or completed the tutorial.
propTypes:
geordi: PropTypes.object
preferences: PropTypes.shape
preferences: PropTypes.object
tutorial: PropTypes.shape
steps: PropTypes.arrayOf PropTypes.shape
media: PropTypes.string
content: PropTypes.string
translation: PropTypes.shape
steps: PropTypes.arrayOf PropTypes.shape
content: PropTypes.string
user: PropTypes.object
getDefaultProps: ->
geordi: {}
media: {}
preferences: null
tutorial: {}
user: null
componentWillMount: ->
@previousActiveElement = document.activeElement
componentWillUnmount: ->
@handleUnmount()
render: ->
isIE = 'ActiveXObject' of window
if isIE
tutorialStyle = height: '85vh'
<StepThrough ref="stepThrough" className="tutorial-steps" style={tutorialStyle}>
{for step, i in @props.tutorial.steps
step._key ?= Math.random()
<MediaCard key={step._key} className="tutorial-step" src={@props.media[step.media]?.src}>
<Markdown>{@props.translation.steps[i].content}</Markdown>
<hr />
<p style={textAlign: 'center'}>
{if i is @props.tutorial.steps.length - 1
<button type="submit" className="major-button"><Translate content="classifier.letsGo" /></button>
else
<button type="button" className="standard-button" onClick={@handleNextClick}><Translate content="classifier.continue" /></button>}
</p>
</MediaCard>}
</StepThrough>
handleNextClick: ->
@refs.stepThrough.goNext()
handleUnmount: ->
@previousActiveElement?.focus()
now = new Date().toISOString()
completedThisSession[@props.tutorial.id] = now
if @props.user?
projectPreferences = @props.preferences
# Build this manually. Having an index (even as a strings) keys creates an array.
projectPreferences.preferences ?= {}
projectPreferences.preferences.tutorials_completed_at ?= {}
projectPreferences.update "preferences.tutorials_completed_at.#{@props.tutorial.id}": now
projectPreferences.save()
@logToGeordi now
logToGeordi: (datetime) ->
@props.geordi.logEvent {
type: "tutorial-completion"
data: {
tutorial: @props.tutorial.id
tutorialCompleted: datetime
}
}
| 37490 | React = require 'react'
PropTypes = require 'prop-types'
createReactClass = require 'create-react-class'
Dialog = require 'modal-form/dialog'
Translate = require 'react-translate-component'
MediaCard = require('../components/media-card').default
{Markdown} = require 'markdownz'
apiClient = require 'panoptes-client/lib/api-client'
{ Provider } = require('react-redux')
StepThrough = require('../components/step-through').default
Translations = require('./translations').default
completedThisSession = {}
window?.tutorialsCompletedThisSession = completedThisSession
module.exports = createReactClass
displayName: 'Tutorial'
statics:
find: (workflow) ->
# Prefer fetching the tutorial for the workflow, if a workflow is given.
if workflow?
apiClient.type('tutorials').get workflow_id: workflow.id
.then (tutorials) ->
# Backwards compatibility for null kind values. We assume these are standard tutorials.
onlyStandardTutorials = tutorials.filter (tutorial) ->
tutorial.kind in ['tutorial', null]
onlyStandardTutorials[0]
else
Promise.resolve()
startIfNecessary: (tutorial, user, preferences, geordi, store) ->
if tutorial?
@checkIfCompleted(tutorial, user, preferences).then (completed) =>
unless completed
@start tutorial, user, preferences, geordi, store
checkIfCompleted: (tutorial, user, preferences) ->
if user?
window.prefs = preferences
Promise.resolve preferences?.preferences?.tutorials_completed_at?[tutorial.id]?
else
Promise.resolve completedThisSession[tutorial.id]?
start: (tutorial, user, preferences, geordi, store) ->
TutorialComponent = this
if tutorial.steps.length isnt 0
awaitTutorialMedia = tutorial.get 'attached_images'
.catch ->
# Checking for attached images throws if there are none.
[]
.then (mediaResources) ->
mediaByID = {}
for mediaResource in mediaResources
mediaByID[mediaResource.id] = mediaResource
mediaByID
awaitTutorialMedia.then (mediaByID) =>
tutorialContent =
<Provider store={store}>
<Translations original={tutorial} type="tutorial">
<TutorialComponent tutorial={tutorial} media={mediaByID} preferences={preferences} user={user} geordi={geordi} />
</Translations>
</Provider>
Dialog.alert(tutorialContent, {
className: 'tutorial-dialog',
required: true,
closeButton: true
})
.catch (e) =>
console.warn e
null # We don't really care if the user canceled or completed the tutorial.
propTypes:
geordi: PropTypes.object
preferences: PropTypes.shape
preferences: PropTypes.object
tutorial: PropTypes.shape
steps: PropTypes.arrayOf PropTypes.shape
media: PropTypes.string
content: PropTypes.string
translation: PropTypes.shape
steps: PropTypes.arrayOf PropTypes.shape
content: PropTypes.string
user: PropTypes.object
getDefaultProps: ->
geordi: {}
media: {}
preferences: null
tutorial: {}
user: null
componentWillMount: ->
@previousActiveElement = document.activeElement
componentWillUnmount: ->
@handleUnmount()
render: ->
isIE = 'ActiveXObject' of window
if isIE
tutorialStyle = height: '85vh'
<StepThrough ref="stepThrough" className="tutorial-steps" style={tutorialStyle}>
{for step, i in @props.tutorial.steps
step._key ?= <KEY>()
<MediaCard key={step._key} className="tutorial-step" src={@props.media[step.media]?.src}>
<Markdown>{@props.translation.steps[i].content}</Markdown>
<hr />
<p style={textAlign: 'center'}>
{if i is @props.tutorial.steps.length - 1
<button type="submit" className="major-button"><Translate content="classifier.letsGo" /></button>
else
<button type="button" className="standard-button" onClick={@handleNextClick}><Translate content="classifier.continue" /></button>}
</p>
</MediaCard>}
</StepThrough>
handleNextClick: ->
@refs.stepThrough.goNext()
handleUnmount: ->
@previousActiveElement?.focus()
now = new Date().toISOString()
completedThisSession[@props.tutorial.id] = now
if @props.user?
projectPreferences = @props.preferences
# Build this manually. Having an index (even as a strings) keys creates an array.
projectPreferences.preferences ?= {}
projectPreferences.preferences.tutorials_completed_at ?= {}
projectPreferences.update "preferences.tutorials_completed_at.#{@props.tutorial.id}": now
projectPreferences.save()
@logToGeordi now
logToGeordi: (datetime) ->
@props.geordi.logEvent {
type: "tutorial-completion"
data: {
tutorial: @props.tutorial.id
tutorialCompleted: datetime
}
}
| true | React = require 'react'
PropTypes = require 'prop-types'
createReactClass = require 'create-react-class'
Dialog = require 'modal-form/dialog'
Translate = require 'react-translate-component'
MediaCard = require('../components/media-card').default
{Markdown} = require 'markdownz'
apiClient = require 'panoptes-client/lib/api-client'
{ Provider } = require('react-redux')
StepThrough = require('../components/step-through').default
Translations = require('./translations').default
completedThisSession = {}
window?.tutorialsCompletedThisSession = completedThisSession
module.exports = createReactClass
displayName: 'Tutorial'
statics:
find: (workflow) ->
# Prefer fetching the tutorial for the workflow, if a workflow is given.
if workflow?
apiClient.type('tutorials').get workflow_id: workflow.id
.then (tutorials) ->
# Backwards compatibility for null kind values. We assume these are standard tutorials.
onlyStandardTutorials = tutorials.filter (tutorial) ->
tutorial.kind in ['tutorial', null]
onlyStandardTutorials[0]
else
Promise.resolve()
startIfNecessary: (tutorial, user, preferences, geordi, store) ->
if tutorial?
@checkIfCompleted(tutorial, user, preferences).then (completed) =>
unless completed
@start tutorial, user, preferences, geordi, store
checkIfCompleted: (tutorial, user, preferences) ->
if user?
window.prefs = preferences
Promise.resolve preferences?.preferences?.tutorials_completed_at?[tutorial.id]?
else
Promise.resolve completedThisSession[tutorial.id]?
start: (tutorial, user, preferences, geordi, store) ->
TutorialComponent = this
if tutorial.steps.length isnt 0
awaitTutorialMedia = tutorial.get 'attached_images'
.catch ->
# Checking for attached images throws if there are none.
[]
.then (mediaResources) ->
mediaByID = {}
for mediaResource in mediaResources
mediaByID[mediaResource.id] = mediaResource
mediaByID
awaitTutorialMedia.then (mediaByID) =>
tutorialContent =
<Provider store={store}>
<Translations original={tutorial} type="tutorial">
<TutorialComponent tutorial={tutorial} media={mediaByID} preferences={preferences} user={user} geordi={geordi} />
</Translations>
</Provider>
Dialog.alert(tutorialContent, {
className: 'tutorial-dialog',
required: true,
closeButton: true
})
.catch (e) =>
console.warn e
null # We don't really care if the user canceled or completed the tutorial.
propTypes:
geordi: PropTypes.object
preferences: PropTypes.shape
preferences: PropTypes.object
tutorial: PropTypes.shape
steps: PropTypes.arrayOf PropTypes.shape
media: PropTypes.string
content: PropTypes.string
translation: PropTypes.shape
steps: PropTypes.arrayOf PropTypes.shape
content: PropTypes.string
user: PropTypes.object
getDefaultProps: ->
geordi: {}
media: {}
preferences: null
tutorial: {}
user: null
componentWillMount: ->
@previousActiveElement = document.activeElement
componentWillUnmount: ->
@handleUnmount()
render: ->
isIE = 'ActiveXObject' of window
if isIE
tutorialStyle = height: '85vh'
<StepThrough ref="stepThrough" className="tutorial-steps" style={tutorialStyle}>
{for step, i in @props.tutorial.steps
step._key ?= PI:KEY:<KEY>END_PI()
<MediaCard key={step._key} className="tutorial-step" src={@props.media[step.media]?.src}>
<Markdown>{@props.translation.steps[i].content}</Markdown>
<hr />
<p style={textAlign: 'center'}>
{if i is @props.tutorial.steps.length - 1
<button type="submit" className="major-button"><Translate content="classifier.letsGo" /></button>
else
<button type="button" className="standard-button" onClick={@handleNextClick}><Translate content="classifier.continue" /></button>}
</p>
</MediaCard>}
</StepThrough>
handleNextClick: ->
@refs.stepThrough.goNext()
handleUnmount: ->
@previousActiveElement?.focus()
now = new Date().toISOString()
completedThisSession[@props.tutorial.id] = now
if @props.user?
projectPreferences = @props.preferences
# Build this manually. Having an index (even as a strings) keys creates an array.
projectPreferences.preferences ?= {}
projectPreferences.preferences.tutorials_completed_at ?= {}
projectPreferences.update "preferences.tutorials_completed_at.#{@props.tutorial.id}": now
projectPreferences.save()
@logToGeordi now
logToGeordi: (datetime) ->
@props.geordi.logEvent {
type: "tutorial-completion"
data: {
tutorial: @props.tutorial.id
tutorialCompleted: datetime
}
}
|
[
{
"context": " asking @#{user}!\\n\\nI'm created by a kid named **Piyush Raj** A.K.A. @0x48piraj *([Github](https://github.com",
"end": 235,
"score": 0.9997302889823914,
"start": 225,
"tag": "NAME",
"value": "Piyush Raj"
},
{
"context": "\\nI'm created by a kid named **Piyush Raj** A... | scripts/creators.coffee | 0x48piraj/fossbot | 8 |
module.exports = (robot) ->
robot.hear /(.*)(fossbot|who|creators)(.*)(behind|created)(.*)(you)(.*)/i, (msg) ->
user = msg.message.user.login
msg.send "Thanks for asking @#{user}!\n\nI'm created by a kid named **Piyush Raj** A.K.A. @0x48piraj *([Github](https://github.com/0x48piraj) | [LinkedIn](https://www.linkedin.com/in/0x48piraj/) | [Twitter](https://twitter.com/0x48piraj))*"
| 150249 |
module.exports = (robot) ->
robot.hear /(.*)(fossbot|who|creators)(.*)(behind|created)(.*)(you)(.*)/i, (msg) ->
user = msg.message.user.login
msg.send "Thanks for asking @#{user}!\n\nI'm created by a kid named **<NAME>** A.K.A. @0x48piraj *([Github](https://github.com/0x48piraj) | [LinkedIn](https://www.linkedin.com/in/0x48piraj/) | [Twitter](https://twitter.com/0x48piraj))*"
| true |
module.exports = (robot) ->
robot.hear /(.*)(fossbot|who|creators)(.*)(behind|created)(.*)(you)(.*)/i, (msg) ->
user = msg.message.user.login
msg.send "Thanks for asking @#{user}!\n\nI'm created by a kid named **PI:NAME:<NAME>END_PI** A.K.A. @0x48piraj *([Github](https://github.com/0x48piraj) | [LinkedIn](https://www.linkedin.com/in/0x48piraj/) | [Twitter](https://twitter.com/0x48piraj))*"
|
[
{
"context": "e\n })\n .metadata {\n meta_title: 'Peter DeMartini'\n meta_description: \"I am a husband, a fat",
"end": 728,
"score": 0.9989837408065796,
"start": 713,
"tag": "NAME",
"value": "Peter DeMartini"
},
{
"context": " not because it is my job.\"\n ... | build.coffee | peterdemartini/blog | 0 | MetalSmith = require 'metalsmith'
collections = require 'metalsmith-collections'
drafts = require 'metalsmith-drafts'
markdown = require 'metalsmith-markdown'
permalinks = require 'metalsmith-permalinks'
templates = require 'metalsmith-templates'
debug = require('debug')('peterdemartini:build')
require './handlebars-config'
class Builder
constructor: ->
run: (callback=->) =>
debug 'Building site...'
MetalSmith(__dirname)
.use drafts()
.use collections({
pages:
pattern: 'content/pages/*.md'
posts:
pattern: 'content/posts/*.md',
sortBy: 'date',
reverse: true
})
.metadata {
meta_title: 'Peter DeMartini'
meta_description: "I am a husband, a father, and a Software Craftsman. I build because I love it, not because it is my job."
meta_author: 'Peter DeMartini'
}
.use markdown()
.use permalinks(pattern: ':title')
.use templates(engine: 'handlebars')
.build callback
module.exports = Builder
| 165854 | MetalSmith = require 'metalsmith'
collections = require 'metalsmith-collections'
drafts = require 'metalsmith-drafts'
markdown = require 'metalsmith-markdown'
permalinks = require 'metalsmith-permalinks'
templates = require 'metalsmith-templates'
debug = require('debug')('peterdemartini:build')
require './handlebars-config'
class Builder
constructor: ->
run: (callback=->) =>
debug 'Building site...'
MetalSmith(__dirname)
.use drafts()
.use collections({
pages:
pattern: 'content/pages/*.md'
posts:
pattern: 'content/posts/*.md',
sortBy: 'date',
reverse: true
})
.metadata {
meta_title: '<NAME>'
meta_description: "I am a husband, a father, and a Software Craftsman. I build because I love it, not because it is my job."
meta_author: '<NAME>'
}
.use markdown()
.use permalinks(pattern: ':title')
.use templates(engine: 'handlebars')
.build callback
module.exports = Builder
| true | MetalSmith = require 'metalsmith'
collections = require 'metalsmith-collections'
drafts = require 'metalsmith-drafts'
markdown = require 'metalsmith-markdown'
permalinks = require 'metalsmith-permalinks'
templates = require 'metalsmith-templates'
debug = require('debug')('peterdemartini:build')
require './handlebars-config'
class Builder
constructor: ->
run: (callback=->) =>
debug 'Building site...'
MetalSmith(__dirname)
.use drafts()
.use collections({
pages:
pattern: 'content/pages/*.md'
posts:
pattern: 'content/posts/*.md',
sortBy: 'date',
reverse: true
})
.metadata {
meta_title: 'PI:NAME:<NAME>END_PI'
meta_description: "I am a husband, a father, and a Software Craftsman. I build because I love it, not because it is my job."
meta_author: 'PI:NAME:<NAME>END_PI'
}
.use markdown()
.use permalinks(pattern: ':title')
.use templates(engine: 'handlebars')
.build callback
module.exports = Builder
|
[
{
"context": "\t\tset_key\n\n\t\t\ttree\n\telse\n\t\treturn h 'div',\n\t\t\tkey: '__root'\n\t\t\tcn: 'navtree-root'\n\t\t\ttree\n\n\nfindNavKey = (tr",
"end": 808,
"score": 0.7058178186416626,
"start": 801,
"tag": "KEY",
"value": "'__root"
}
] | docs-site/NavBar.coffee | lerp-io/editor-gui | 2 | import {createContext,useContext,createElement,useState,useEffect,useRef,useReducer} from 'react'
h = createElement
import './NavBar.less'
NavBarContext = createContext
root: yes
renderNavTree = (set_key,props,offset,select,level,click)->
tree = []
tree_items = props.children
scroll_top = props.top || 0
for key,child_props of tree_items
tree.push renderNavTree(key,child_props,offset,select,level+1)
my_select = select.indexOf(set_key) >= 0
if set_key
return h 'div',
key: set_key
cn: 'navtree-section l'+level+' '+(my_select && 'select' || '')+' '+(props.className || '')
h 'div',
cn:'navtree-label l'+level+' '+(my_select && 'select' || '')
onClick: ()->
document.body.scrollTo(0,offset+scroll_top)
set_key
tree
else
return h 'div',
key: '__root'
cn: 'navtree-root'
tree
findNavKey = (tree,scrollY,select)->
for key,it of tree
if scrollY < it.bot && scrollY >= it.top
select.push key
findNavKey(it.children,scrollY,select)
return select
return select
NavBar = (props)->
[select,setSelect] = useState([])
[nav_tree,setNavTree] = useState({})
[hash,setHash] = useState(23)
root_ref = useRef()
state_ref = useRef
select:[]
nav_tree:{}
hash: hash
checkSelect = ->
nav_tree = state_ref.current.nav_tree
select = state_ref.current.select
# rect = root_ref.current.getBoundingClientRect()
# log window.scrollY,rect.top
new_select = findNavKey(nav_tree,document.body.scrollTop-root_ref.current.offsetTop,[])
# log new_select,select
if new_select.length != select.length
state_ref.current.select = new_select
return setSelect(new_select)
for i in [0...select.length]
if new_select[i] != select[i]
state_ref.current.select = new_select
return setSelect(new_select)
return
useEffect ()->
# log 'use effect',my_nav_tree
# log state_ref.current.hash
if state_ref.current.hash != hash
checkSelect()
setHash(state_ref.current.hash)
setNavTree(state_ref.current.nav_tree)
useEffect ()->
# console.log('SET NAV TREE',self_context.nav_tree)
window.addEventListener 'scroll',checkSelect
return ()->
window.removeEventListener 'scroll',checkSelect
,[]
rendered_nav_tree = renderNavTree(null,{children:nav_tree},root_ref.current?.offsetTop||0,state_ref.current.select,0)
h NavBarContext.Provider,
value:
setNav: (link_name,top,bot,link_children,hash)->
state_ref.current.nav_tree[link_name] = {top:top,bot:bot,children:link_children,bg_color:props.bg_color}
state_ref.current.hash *= hash
h 'div',
cn: 'nav-context'
ref: root_ref
rendered_nav_tree
h 'div',
cn: 'nav-content-root'
props.children
NavBarSection = (props)->
context = useContext(NavBarContext)
ref = useRef()
self_context =
setNav: (link_name,top,bot,nav_children,hash,className)->
self_context.hash *= hash
self_context.nav_children[link_name] = {top:top,bot:bot,children:nav_children,className:className}
return
nav_children: {}
hash: 23
useEffect ()->
# log 'set nav bar hash'
self_context.hash *= (ref.current.offsetTop+ref.current.clientHeight)*31
context.setNav(props.nav_key,ref.current.offsetTop,ref.current.offsetTop+ref.current.clientHeight,self_context.nav_children,self_context.hash,props.className)
return
h NavBarContext.Provider,
value: self_context
h 'div',
cn: 'nav-content'
ref: ref
props.children
export {NavBarSection}
export {NavBar} | 108987 | import {createContext,useContext,createElement,useState,useEffect,useRef,useReducer} from 'react'
h = createElement
import './NavBar.less'
NavBarContext = createContext
root: yes
renderNavTree = (set_key,props,offset,select,level,click)->
tree = []
tree_items = props.children
scroll_top = props.top || 0
for key,child_props of tree_items
tree.push renderNavTree(key,child_props,offset,select,level+1)
my_select = select.indexOf(set_key) >= 0
if set_key
return h 'div',
key: set_key
cn: 'navtree-section l'+level+' '+(my_select && 'select' || '')+' '+(props.className || '')
h 'div',
cn:'navtree-label l'+level+' '+(my_select && 'select' || '')
onClick: ()->
document.body.scrollTo(0,offset+scroll_top)
set_key
tree
else
return h 'div',
key: <KEY>'
cn: 'navtree-root'
tree
findNavKey = (tree,scrollY,select)->
for key,it of tree
if scrollY < it.bot && scrollY >= it.top
select.push key
findNavKey(it.children,scrollY,select)
return select
return select
NavBar = (props)->
[select,setSelect] = useState([])
[nav_tree,setNavTree] = useState({})
[hash,setHash] = useState(23)
root_ref = useRef()
state_ref = useRef
select:[]
nav_tree:{}
hash: hash
checkSelect = ->
nav_tree = state_ref.current.nav_tree
select = state_ref.current.select
# rect = root_ref.current.getBoundingClientRect()
# log window.scrollY,rect.top
new_select = findNavKey(nav_tree,document.body.scrollTop-root_ref.current.offsetTop,[])
# log new_select,select
if new_select.length != select.length
state_ref.current.select = new_select
return setSelect(new_select)
for i in [0...select.length]
if new_select[i] != select[i]
state_ref.current.select = new_select
return setSelect(new_select)
return
useEffect ()->
# log 'use effect',my_nav_tree
# log state_ref.current.hash
if state_ref.current.hash != hash
checkSelect()
setHash(state_ref.current.hash)
setNavTree(state_ref.current.nav_tree)
useEffect ()->
# console.log('SET NAV TREE',self_context.nav_tree)
window.addEventListener 'scroll',checkSelect
return ()->
window.removeEventListener 'scroll',checkSelect
,[]
rendered_nav_tree = renderNavTree(null,{children:nav_tree},root_ref.current?.offsetTop||0,state_ref.current.select,0)
h NavBarContext.Provider,
value:
setNav: (link_name,top,bot,link_children,hash)->
state_ref.current.nav_tree[link_name] = {top:top,bot:bot,children:link_children,bg_color:props.bg_color}
state_ref.current.hash *= hash
h 'div',
cn: 'nav-context'
ref: root_ref
rendered_nav_tree
h 'div',
cn: 'nav-content-root'
props.children
NavBarSection = (props)->
context = useContext(NavBarContext)
ref = useRef()
self_context =
setNav: (link_name,top,bot,nav_children,hash,className)->
self_context.hash *= hash
self_context.nav_children[link_name] = {top:top,bot:bot,children:nav_children,className:className}
return
nav_children: {}
hash: 23
useEffect ()->
# log 'set nav bar hash'
self_context.hash *= (ref.current.offsetTop+ref.current.clientHeight)*31
context.setNav(props.nav_key,ref.current.offsetTop,ref.current.offsetTop+ref.current.clientHeight,self_context.nav_children,self_context.hash,props.className)
return
h NavBarContext.Provider,
value: self_context
h 'div',
cn: 'nav-content'
ref: ref
props.children
export {NavBarSection}
export {NavBar} | true | import {createContext,useContext,createElement,useState,useEffect,useRef,useReducer} from 'react'
h = createElement
import './NavBar.less'
NavBarContext = createContext
root: yes
renderNavTree = (set_key,props,offset,select,level,click)->
tree = []
tree_items = props.children
scroll_top = props.top || 0
for key,child_props of tree_items
tree.push renderNavTree(key,child_props,offset,select,level+1)
my_select = select.indexOf(set_key) >= 0
if set_key
return h 'div',
key: set_key
cn: 'navtree-section l'+level+' '+(my_select && 'select' || '')+' '+(props.className || '')
h 'div',
cn:'navtree-label l'+level+' '+(my_select && 'select' || '')
onClick: ()->
document.body.scrollTo(0,offset+scroll_top)
set_key
tree
else
return h 'div',
key: PI:KEY:<KEY>END_PI'
cn: 'navtree-root'
tree
findNavKey = (tree,scrollY,select)->
for key,it of tree
if scrollY < it.bot && scrollY >= it.top
select.push key
findNavKey(it.children,scrollY,select)
return select
return select
NavBar = (props)->
[select,setSelect] = useState([])
[nav_tree,setNavTree] = useState({})
[hash,setHash] = useState(23)
root_ref = useRef()
state_ref = useRef
select:[]
nav_tree:{}
hash: hash
checkSelect = ->
nav_tree = state_ref.current.nav_tree
select = state_ref.current.select
# rect = root_ref.current.getBoundingClientRect()
# log window.scrollY,rect.top
new_select = findNavKey(nav_tree,document.body.scrollTop-root_ref.current.offsetTop,[])
# log new_select,select
if new_select.length != select.length
state_ref.current.select = new_select
return setSelect(new_select)
for i in [0...select.length]
if new_select[i] != select[i]
state_ref.current.select = new_select
return setSelect(new_select)
return
useEffect ()->
# log 'use effect',my_nav_tree
# log state_ref.current.hash
if state_ref.current.hash != hash
checkSelect()
setHash(state_ref.current.hash)
setNavTree(state_ref.current.nav_tree)
useEffect ()->
# console.log('SET NAV TREE',self_context.nav_tree)
window.addEventListener 'scroll',checkSelect
return ()->
window.removeEventListener 'scroll',checkSelect
,[]
rendered_nav_tree = renderNavTree(null,{children:nav_tree},root_ref.current?.offsetTop||0,state_ref.current.select,0)
h NavBarContext.Provider,
value:
setNav: (link_name,top,bot,link_children,hash)->
state_ref.current.nav_tree[link_name] = {top:top,bot:bot,children:link_children,bg_color:props.bg_color}
state_ref.current.hash *= hash
h 'div',
cn: 'nav-context'
ref: root_ref
rendered_nav_tree
h 'div',
cn: 'nav-content-root'
props.children
NavBarSection = (props)->
context = useContext(NavBarContext)
ref = useRef()
self_context =
setNav: (link_name,top,bot,nav_children,hash,className)->
self_context.hash *= hash
self_context.nav_children[link_name] = {top:top,bot:bot,children:nav_children,className:className}
return
nav_children: {}
hash: 23
useEffect ()->
# log 'set nav bar hash'
self_context.hash *= (ref.current.offsetTop+ref.current.clientHeight)*31
context.setNav(props.nav_key,ref.current.offsetTop,ref.current.offsetTop+ref.current.clientHeight,self_context.nav_children,self_context.hash,props.className)
return
h NavBarContext.Provider,
value: self_context
h 'div',
cn: 'nav-content'
ref: ref
props.children
export {NavBarSection}
export {NavBar} |
[
{
"context": "urn if contact.email.trim().length is 0\n\n key = Utils.toEquivalentEmailForm(contact.email)\n\n @_contactScores[key] ?=\n ",
"end": 3949,
"score": 0.9305750131607056,
"start": 3921,
"tag": "KEY",
"value": "Utils.toEquivalentEmailForm("
},
{
"context": " ke... | app/src/flux/stores/focused-contacts-store.coffee | immershy/nodemail | 0 | _ = require 'underscore'
Rx = require 'rx-lite'
Utils = require '../models/utils'
Actions = require '../actions'
NylasStore = require 'nylas-store'
Thread = require '../models/thread'
Contact = require '../models/contact'
MessageStore = require './message-store'
AccountStore = require './account-store'
DatabaseStore = require './database-store'
FocusedContentStore = require './focused-content-store'
# A store that handles the focuses collections of and individual contacts
class FocusedContactsStore extends NylasStore
constructor: ->
@listenTo MessageStore, @_onMessageStoreChanged
@listenTo Actions.focusContact, @_onFocusContact
@_clearCurrentParticipants()
sortedContacts: -> @_currentContacts
focusedContact: -> @_currentFocusedContact
focusedContactThreads: -> @_currentParticipantThreads ? []
# We need to wait now for the MessageStore to grab all of the
# appropriate messages for the given thread.
_onMessageStoreChanged: =>
threadId = if MessageStore.itemsLoading() then null else MessageStore.threadId()
# Always clear data immediately when we're showing the wrong thread
if @_currentThread and @_currentThread.id isnt threadId
@_clearCurrentParticipants()
@trigger()
# Wait to populate until the user has stopped moving through threads. This is
# important because the FocusedContactStore powers tons of third-party extensions,
# which could do /horrible/ things when we trigger.
@_onMessageStoreChangeThrottled ?= _.debounce =>
thread = if MessageStore.itemsLoading() then null else MessageStore.thread()
if thread and thread.id isnt @_currentThread?.id
@_currentThread = thread
@_popuateCurrentParticipants()
, 250
@_onMessageStoreChangeThrottled()
# For now we take the last message
_popuateCurrentParticipants: ->
@_scoreAllParticipants()
sorted = _.sortBy(_.values(@_contactScores), "score").reverse()
@_currentContacts = _.map(sorted, (obj) -> obj.contact)
@_onFocusContact(@_currentContacts[0])
_clearCurrentParticipants: ->
@_contactScores = {}
@_currentContacts = []
@_unsubFocusedContact?.dispose()
@_unsubFocusedContact = null
@_currentFocusedContact = null
@_currentThread = null
@_currentParticipantThreads = []
_onFocusContact: (contact) =>
@_unsubFocusedContact?.dispose()
@_unsubFocusedContact = null
@_currentParticipantThreads = []
if contact
query = DatabaseStore.findBy(Contact, {
email: contact.email,
accountId: @_currentThread.accountId
})
@_unsubFocusedContact = Rx.Observable.fromQuery(query).subscribe (match) =>
@_currentFocusedContact = match ? contact
@trigger()
@_loadCurrentParticipantThreads(contact.email)
else
@_currentFocusedContact = null
@trigger()
_loadCurrentParticipantThreads: (email) ->
DatabaseStore.findAll(Thread).where(Thread.attributes.participants.contains(email)).limit(100).then (threads = []) =>
@_currentParticipantThreads = threads
@trigger()
# We score everyone to determine who's the most relevant to display in
# the sidebar.
_scoreAllParticipants: ->
score = (message, msgNum, field, multiplier) =>
for contact, j in (message[field] ? [])
bonus = message[field].length - j
@_assignScore(contact, (msgNum+1) * multiplier + bonus)
for message, msgNum in MessageStore.items() by -1
if message.draft
score(message, msgNum, "to", 10000)
score(message, msgNum, "cc", 1000)
else
score(message, msgNum, "from", 100)
score(message, msgNum, "to", 10)
score(message, msgNum, "cc", 1)
return @_contactScores
# Self always gets a score of 0
_assignScore: (contact, score=0) ->
return unless contact and contact.email
return if contact.email.trim().length is 0
key = Utils.toEquivalentEmailForm(contact.email)
@_contactScores[key] ?=
contact: contact
score: score - @_calculatePenalties(contact, score)
_calculatePenalties: (contact, score) ->
penalties = 0
email = contact.email.toLowerCase().trim()
myEmail = AccountStore.accountForId(@currentThread?.accountId)?.emailAddress
if email is myEmail
# The whole thing which will penalize to zero
penalties += score
notCommonDomain = not Utils.emailHasCommonDomain(myEmail)
sameDomain = Utils.emailsHaveSameDomain(myEmail, email)
if notCommonDomain and sameDomain
penalties += score * 0.9
return Math.max(penalties, 0)
module.exports = new FocusedContactsStore
| 116818 | _ = require 'underscore'
Rx = require 'rx-lite'
Utils = require '../models/utils'
Actions = require '../actions'
NylasStore = require 'nylas-store'
Thread = require '../models/thread'
Contact = require '../models/contact'
MessageStore = require './message-store'
AccountStore = require './account-store'
DatabaseStore = require './database-store'
FocusedContentStore = require './focused-content-store'
# A store that handles the focuses collections of and individual contacts
class FocusedContactsStore extends NylasStore
constructor: ->
@listenTo MessageStore, @_onMessageStoreChanged
@listenTo Actions.focusContact, @_onFocusContact
@_clearCurrentParticipants()
sortedContacts: -> @_currentContacts
focusedContact: -> @_currentFocusedContact
focusedContactThreads: -> @_currentParticipantThreads ? []
# We need to wait now for the MessageStore to grab all of the
# appropriate messages for the given thread.
_onMessageStoreChanged: =>
threadId = if MessageStore.itemsLoading() then null else MessageStore.threadId()
# Always clear data immediately when we're showing the wrong thread
if @_currentThread and @_currentThread.id isnt threadId
@_clearCurrentParticipants()
@trigger()
# Wait to populate until the user has stopped moving through threads. This is
# important because the FocusedContactStore powers tons of third-party extensions,
# which could do /horrible/ things when we trigger.
@_onMessageStoreChangeThrottled ?= _.debounce =>
thread = if MessageStore.itemsLoading() then null else MessageStore.thread()
if thread and thread.id isnt @_currentThread?.id
@_currentThread = thread
@_popuateCurrentParticipants()
, 250
@_onMessageStoreChangeThrottled()
# For now we take the last message
_popuateCurrentParticipants: ->
@_scoreAllParticipants()
sorted = _.sortBy(_.values(@_contactScores), "score").reverse()
@_currentContacts = _.map(sorted, (obj) -> obj.contact)
@_onFocusContact(@_currentContacts[0])
_clearCurrentParticipants: ->
@_contactScores = {}
@_currentContacts = []
@_unsubFocusedContact?.dispose()
@_unsubFocusedContact = null
@_currentFocusedContact = null
@_currentThread = null
@_currentParticipantThreads = []
_onFocusContact: (contact) =>
@_unsubFocusedContact?.dispose()
@_unsubFocusedContact = null
@_currentParticipantThreads = []
if contact
query = DatabaseStore.findBy(Contact, {
email: contact.email,
accountId: @_currentThread.accountId
})
@_unsubFocusedContact = Rx.Observable.fromQuery(query).subscribe (match) =>
@_currentFocusedContact = match ? contact
@trigger()
@_loadCurrentParticipantThreads(contact.email)
else
@_currentFocusedContact = null
@trigger()
_loadCurrentParticipantThreads: (email) ->
DatabaseStore.findAll(Thread).where(Thread.attributes.participants.contains(email)).limit(100).then (threads = []) =>
@_currentParticipantThreads = threads
@trigger()
# We score everyone to determine who's the most relevant to display in
# the sidebar.
_scoreAllParticipants: ->
score = (message, msgNum, field, multiplier) =>
for contact, j in (message[field] ? [])
bonus = message[field].length - j
@_assignScore(contact, (msgNum+1) * multiplier + bonus)
for message, msgNum in MessageStore.items() by -1
if message.draft
score(message, msgNum, "to", 10000)
score(message, msgNum, "cc", 1000)
else
score(message, msgNum, "from", 100)
score(message, msgNum, "to", 10)
score(message, msgNum, "cc", 1)
return @_contactScores
# Self always gets a score of 0
_assignScore: (contact, score=0) ->
return unless contact and contact.email
return if contact.email.trim().length is 0
key = <KEY>contact.email<KEY>)
@_contactScores[key] ?=
contact: contact
score: score - @_calculatePenalties(contact, score)
_calculatePenalties: (contact, score) ->
penalties = 0
email = contact.email.toLowerCase().trim()
myEmail = AccountStore.accountForId(@currentThread?.accountId)?.emailAddress
if email is myEmail
# The whole thing which will penalize to zero
penalties += score
notCommonDomain = not Utils.emailHasCommonDomain(myEmail)
sameDomain = Utils.emailsHaveSameDomain(myEmail, email)
if notCommonDomain and sameDomain
penalties += score * 0.9
return Math.max(penalties, 0)
module.exports = new FocusedContactsStore
| true | _ = require 'underscore'
Rx = require 'rx-lite'
Utils = require '../models/utils'
Actions = require '../actions'
NylasStore = require 'nylas-store'
Thread = require '../models/thread'
Contact = require '../models/contact'
MessageStore = require './message-store'
AccountStore = require './account-store'
DatabaseStore = require './database-store'
FocusedContentStore = require './focused-content-store'
# A store that handles the focuses collections of and individual contacts
class FocusedContactsStore extends NylasStore
constructor: ->
@listenTo MessageStore, @_onMessageStoreChanged
@listenTo Actions.focusContact, @_onFocusContact
@_clearCurrentParticipants()
sortedContacts: -> @_currentContacts
focusedContact: -> @_currentFocusedContact
focusedContactThreads: -> @_currentParticipantThreads ? []
# We need to wait now for the MessageStore to grab all of the
# appropriate messages for the given thread.
_onMessageStoreChanged: =>
threadId = if MessageStore.itemsLoading() then null else MessageStore.threadId()
# Always clear data immediately when we're showing the wrong thread
if @_currentThread and @_currentThread.id isnt threadId
@_clearCurrentParticipants()
@trigger()
# Wait to populate until the user has stopped moving through threads. This is
# important because the FocusedContactStore powers tons of third-party extensions,
# which could do /horrible/ things when we trigger.
@_onMessageStoreChangeThrottled ?= _.debounce =>
thread = if MessageStore.itemsLoading() then null else MessageStore.thread()
if thread and thread.id isnt @_currentThread?.id
@_currentThread = thread
@_popuateCurrentParticipants()
, 250
@_onMessageStoreChangeThrottled()
# For now we take the last message
_popuateCurrentParticipants: ->
@_scoreAllParticipants()
sorted = _.sortBy(_.values(@_contactScores), "score").reverse()
@_currentContacts = _.map(sorted, (obj) -> obj.contact)
@_onFocusContact(@_currentContacts[0])
_clearCurrentParticipants: ->
@_contactScores = {}
@_currentContacts = []
@_unsubFocusedContact?.dispose()
@_unsubFocusedContact = null
@_currentFocusedContact = null
@_currentThread = null
@_currentParticipantThreads = []
_onFocusContact: (contact) =>
@_unsubFocusedContact?.dispose()
@_unsubFocusedContact = null
@_currentParticipantThreads = []
if contact
query = DatabaseStore.findBy(Contact, {
email: contact.email,
accountId: @_currentThread.accountId
})
@_unsubFocusedContact = Rx.Observable.fromQuery(query).subscribe (match) =>
@_currentFocusedContact = match ? contact
@trigger()
@_loadCurrentParticipantThreads(contact.email)
else
@_currentFocusedContact = null
@trigger()
_loadCurrentParticipantThreads: (email) ->
DatabaseStore.findAll(Thread).where(Thread.attributes.participants.contains(email)).limit(100).then (threads = []) =>
@_currentParticipantThreads = threads
@trigger()
# We score everyone to determine who's the most relevant to display in
# the sidebar.
_scoreAllParticipants: ->
score = (message, msgNum, field, multiplier) =>
for contact, j in (message[field] ? [])
bonus = message[field].length - j
@_assignScore(contact, (msgNum+1) * multiplier + bonus)
for message, msgNum in MessageStore.items() by -1
if message.draft
score(message, msgNum, "to", 10000)
score(message, msgNum, "cc", 1000)
else
score(message, msgNum, "from", 100)
score(message, msgNum, "to", 10)
score(message, msgNum, "cc", 1)
return @_contactScores
# Self always gets a score of 0
_assignScore: (contact, score=0) ->
return unless contact and contact.email
return if contact.email.trim().length is 0
key = PI:KEY:<KEY>END_PIcontact.emailPI:KEY:<KEY>END_PI)
@_contactScores[key] ?=
contact: contact
score: score - @_calculatePenalties(contact, score)
_calculatePenalties: (contact, score) ->
penalties = 0
email = contact.email.toLowerCase().trim()
myEmail = AccountStore.accountForId(@currentThread?.accountId)?.emailAddress
if email is myEmail
# The whole thing which will penalize to zero
penalties += score
notCommonDomain = not Utils.emailHasCommonDomain(myEmail)
sameDomain = Utils.emailsHaveSameDomain(myEmail, email)
if notCommonDomain and sameDomain
penalties += score * 0.9
return Math.max(penalties, 0)
module.exports = new FocusedContactsStore
|
[
{
"context": "ts.on 'join', (who, channel) =>\n if who.nick == @nick\n rand = Math.floor Math.random() * greetings",
"end": 96,
"score": 0.9953224658966064,
"start": 91,
"tag": "USERNAME",
"value": "@nick"
},
{
"context": "oining any channel'\n version: '0.1'\n authors: ['Á... | plugins/hi.coffee | alvaro-cuesta/nerdobot | 2 | module.exports = (greetings) ->
@events.on 'join', (who, channel) =>
if who.nick == @nick
rand = Math.floor Math.random() * greetings.length
greetings[rand].apply this, [channel]
name: 'Hi'
description: 'Greets randomly upon joining any channel'
version: '0.1'
authors: ['Álvaro Cuesta']
| 185567 | module.exports = (greetings) ->
@events.on 'join', (who, channel) =>
if who.nick == @nick
rand = Math.floor Math.random() * greetings.length
greetings[rand].apply this, [channel]
name: 'Hi'
description: 'Greets randomly upon joining any channel'
version: '0.1'
authors: ['<NAME>']
| true | module.exports = (greetings) ->
@events.on 'join', (who, channel) =>
if who.nick == @nick
rand = Math.floor Math.random() * greetings.length
greetings[rand].apply this, [channel]
name: 'Hi'
description: 'Greets randomly upon joining any channel'
version: '0.1'
authors: ['PI:NAME:<NAME>END_PI']
|
[
{
"context": "o\n\nFramer.Info =\n\ttitle: \"Dots Rebound\"\n\tauthor: \"Tony\"\n\ttwitter: \"TonyJing\"\n\tdescription: \"A rebound of",
"end": 158,
"score": 0.9722280502319336,
"start": 154,
"tag": "NAME",
"value": "Tony"
},
{
"context": "\ttitle: \"Dots Rebound\"\n\tauthor: \"Tony... | 71dots.framer/app.coffee | gremjua-forks/100daysofframer | 26 | # Project Info
# This info is presented in a widget when you share.
# http://framerjs.com/docs/#info.info
Framer.Info =
title: "Dots Rebound"
author: "Tony"
twitter: "TonyJing"
description: "A rebound of Jonas Treub's original prototype: http://share.framerjs.com/5kgx0udrhill/"
# Device Shake Module made by RayPS
# https://github.com/RayPS/Framer-Module-ShakeEvent
ShakeEvent = require "shake"
ShakeEvent.throttleInterval = 1
ShakeEvent.sensitivity = 30
ShakeEvent.onShake = () ->
createDots()
dotsCount = 1500
threshold = 80
pushFactor = 1.2
dots = []
document.body.style.cursor = "auto"
createDots = () ->
for dot in dots
dot.destroy
dots = []
dots = [0...dotsCount].map ->
d = new Layer
size: 8
borderRadius: 4
backgroundColor: "rgba(0,0,0,0.6)"
x: Math.random() * Screen.width
y: Math.random() * Screen.height
for i in [0...dots.length]
dots[i].oX = dots[i].x
dots[i].oY = dots[i].x
createDots()
drop = (dot, duration) ->
falling = new Animation
layer: dot
properties:
maxY: Screen.height
curve: "ease-in"
time: duration
falling.start()
pushDots = (event) ->
event = event.touches[0] if event.touches?
mouseX = event.clientX
mouseY = event.clientY
dots.forEach (dot) ->
dx = dot.midX - mouseX
dy = dot.midY - mouseY
return if Math.abs(dx) > threshold
return if Math.abs(dy) > threshold
distance = Math.sqrt(dx * dx + dy * dy)
if distance < threshold
dot.midX = mouseX + (dx / distance) * threshold
dot.midY = mouseY + (dy / distance) * threshold
if (dot.midX > dot.oX + threshold * pushFactor) or (dot.midX < dot.oX - threshold * pushFactor) or (dot.midY > dot.oY + threshold * pushFactor) or (dot.midY < dot.oY - threshold * pushFactor)
yDamp = 0.06/(dot.midY / Screen.height)
drop(dot, 0.25+yDamp )
bg = new BackgroundLayer
bg.onPan(pushDots)
bg.onMouseMove(pushDots) | 222630 | # Project Info
# This info is presented in a widget when you share.
# http://framerjs.com/docs/#info.info
Framer.Info =
title: "Dots Rebound"
author: "<NAME>"
twitter: "TonyJing"
description: "A rebound of <NAME>'s original prototype: http://share.framerjs.com/5kgx0udrhill/"
# Device Shake Module made by RayPS
# https://github.com/RayPS/Framer-Module-ShakeEvent
ShakeEvent = require "shake"
ShakeEvent.throttleInterval = 1
ShakeEvent.sensitivity = 30
ShakeEvent.onShake = () ->
createDots()
dotsCount = 1500
threshold = 80
pushFactor = 1.2
dots = []
document.body.style.cursor = "auto"
createDots = () ->
for dot in dots
dot.destroy
dots = []
dots = [0...dotsCount].map ->
d = new Layer
size: 8
borderRadius: 4
backgroundColor: "rgba(0,0,0,0.6)"
x: Math.random() * Screen.width
y: Math.random() * Screen.height
for i in [0...dots.length]
dots[i].oX = dots[i].x
dots[i].oY = dots[i].x
createDots()
drop = (dot, duration) ->
falling = new Animation
layer: dot
properties:
maxY: Screen.height
curve: "ease-in"
time: duration
falling.start()
pushDots = (event) ->
event = event.touches[0] if event.touches?
mouseX = event.clientX
mouseY = event.clientY
dots.forEach (dot) ->
dx = dot.midX - mouseX
dy = dot.midY - mouseY
return if Math.abs(dx) > threshold
return if Math.abs(dy) > threshold
distance = Math.sqrt(dx * dx + dy * dy)
if distance < threshold
dot.midX = mouseX + (dx / distance) * threshold
dot.midY = mouseY + (dy / distance) * threshold
if (dot.midX > dot.oX + threshold * pushFactor) or (dot.midX < dot.oX - threshold * pushFactor) or (dot.midY > dot.oY + threshold * pushFactor) or (dot.midY < dot.oY - threshold * pushFactor)
yDamp = 0.06/(dot.midY / Screen.height)
drop(dot, 0.25+yDamp )
bg = new BackgroundLayer
bg.onPan(pushDots)
bg.onMouseMove(pushDots) | true | # Project Info
# This info is presented in a widget when you share.
# http://framerjs.com/docs/#info.info
Framer.Info =
title: "Dots Rebound"
author: "PI:NAME:<NAME>END_PI"
twitter: "TonyJing"
description: "A rebound of PI:NAME:<NAME>END_PI's original prototype: http://share.framerjs.com/5kgx0udrhill/"
# Device Shake Module made by RayPS
# https://github.com/RayPS/Framer-Module-ShakeEvent
ShakeEvent = require "shake"
ShakeEvent.throttleInterval = 1
ShakeEvent.sensitivity = 30
ShakeEvent.onShake = () ->
createDots()
dotsCount = 1500
threshold = 80
pushFactor = 1.2
dots = []
document.body.style.cursor = "auto"
createDots = () ->
for dot in dots
dot.destroy
dots = []
dots = [0...dotsCount].map ->
d = new Layer
size: 8
borderRadius: 4
backgroundColor: "rgba(0,0,0,0.6)"
x: Math.random() * Screen.width
y: Math.random() * Screen.height
for i in [0...dots.length]
dots[i].oX = dots[i].x
dots[i].oY = dots[i].x
createDots()
drop = (dot, duration) ->
falling = new Animation
layer: dot
properties:
maxY: Screen.height
curve: "ease-in"
time: duration
falling.start()
pushDots = (event) ->
event = event.touches[0] if event.touches?
mouseX = event.clientX
mouseY = event.clientY
dots.forEach (dot) ->
dx = dot.midX - mouseX
dy = dot.midY - mouseY
return if Math.abs(dx) > threshold
return if Math.abs(dy) > threshold
distance = Math.sqrt(dx * dx + dy * dy)
if distance < threshold
dot.midX = mouseX + (dx / distance) * threshold
dot.midY = mouseY + (dy / distance) * threshold
if (dot.midX > dot.oX + threshold * pushFactor) or (dot.midX < dot.oX - threshold * pushFactor) or (dot.midY > dot.oY + threshold * pushFactor) or (dot.midY < dot.oY - threshold * pushFactor)
yDamp = 0.06/(dot.midY / Screen.height)
drop(dot, 0.25+yDamp )
bg = new BackgroundLayer
bg.onPan(pushDots)
bg.onMouseMove(pushDots) |
[
{
"context": "###\n# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>\n# Copyright (C) 2014 Jesús Espino ",
"end": 38,
"score": 0.9998884201049805,
"start": 25,
"tag": "NAME",
"value": "Andrey Antukh"
},
{
"context": "###\n# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>\n# Copyright... | public/taiga-front/app/coffee/modules/common/tags.coffee | mabotech/maboss | 0 | ###
# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>
# Copyright (C) 2014 Jesús Espino Garcia <jespinog@gmail.com>
# Copyright (C) 2014 David Barragán Merino <bameda@dbarragan.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# File: modules/common/tags.coffee
###
taiga = @.taiga
trim = @.taiga.trim
bindOnce = @.taiga.bindOnce
module = angular.module("taigaCommon")
# Directive that parses/format tags inputfield.
TagsDirective = ->
formatter = (v) ->
if _.isArray(v)
return v.join(", ")
return ""
parser = (v) ->
return [] if not v
result = _(v.split(",")).map((x) -> _.str.trim(x))
return result.value()
link = ($scope, $el, $attrs, $ctrl) ->
$ctrl.$formatters.push(formatter)
$ctrl.$parsers.push(parser)
$scope.$on "$destroy", ->
$el.off()
return {
require: "ngModel"
link: link
}
module.directive("tgTags", TagsDirective)
ColorizeTagsDirective = ->
templates = {
backlog: _.template("""
<% _.each(tags, function(tag) { %>
<span class="tag" style="border-left: 5px solid <%- tag.color %>"><%- tag.name %></span>
<% }) %>
""")
kanban: _.template("""
<% _.each(tags, function(tag) { %>
<a class="kanban-tag" href="" style="border-color: <%- tag.color %>" title="<%- tag.name %>" />
<% }) %>
""")
taskboard: _.template("""
<% _.each(tags, function(tag) { %>
<a class="taskboard-tag" href="" style="border-color: <%- tag.color %>" title="<%- tag.name %>" />
<% }) %>
""")
}
link = ($scope, $el, $attrs, $ctrl) ->
render = (srcTags) ->
template = templates[$attrs.tgColorizeTagsType]
srcTags.sort()
tags = _.map srcTags, (tag) ->
color = $scope.project.tags_colors[tag]
return {name: tag, color: color}
html = template({tags: tags})
$el.html(html)
$scope.$watch $attrs.tgColorizeTags, (tags) ->
render(tags) if tags?
$scope.$on "$destroy", ->
$el.off()
return {link: link}
module.directive("tgColorizeTags", ColorizeTagsDirective)
#############################################################################
## TagLine Directive (for Lightboxes)
#############################################################################
LbTagLineDirective = ($rs) ->
ENTER_KEY = 13
COMMA_KEY = 188
template = """
<div class="tags-container"></div>
<input type="text" placeholder="I'm it! Tag me..." class="tag-input" />
<a href="" title="Save" class="save icon icon-floppy hidden"></a>
""" # TODO: i18n
# Tags template (rendered manually using lodash)
templateTags = _.template("""
<% _.each(tags, function(tag) { %>
<span class="tag" <% if (tag.color) { %> style="border-left: 5px solid <%- tag.color %>;"<% } %>>
<span class="tag-name"><%- tag.name %></span>
<a href="" title="delete tag" class="icon icon-delete"></a>
</span>
<% }); %>
""") # TODO: i18n
link = ($scope, $el, $attrs, $model) ->
## Render
renderTags = (tags, tagsColors) ->
ctx = {
tags: _.map(tags, (t) -> {name: t, color: tagsColors[t]})
}
html = templateTags(ctx)
$el.find("div.tags-container").html(html)
showSaveButton = -> $el.find(".save").removeClass("hidden")
hideSaveButton = -> $el.find(".save").addClass("hidden")
resetInput = ->
$el.find("input").val("")
$el.find("input").autocomplete("close")
## Aux methods
addValue = (value) ->
value = trim(value.toLowerCase())
return if value.length == 0
tags = _.clone($model.$modelValue, false)
tags = [] if not tags?
tags.push(value) if value not in tags
$scope.$apply ->
$model.$setViewValue(tags)
deleteValue = (value) ->
value = trim(value.toLowerCase())
return if value.length == 0
tags = _.clone($model.$modelValue, false)
tags = _.pull(tags, value)
$scope.$apply ->
$model.$setViewValue(tags)
saveInputTag = () ->
value = $el.find("input").val()
addValue(value)
resetInput()
hideSaveButton()
removeInputLastCharacter = (input) =>
inputValue = input.val()
input.val inputValue.substring(0, inputValue.length - 1)
## Events
$el.on "keypress", "input", (event) ->
return if event.keyCode != ENTER_KEY
event.preventDefault()
$el.on "keyup", "input", (event) ->
target = angular.element(event.currentTarget)
if event.keyCode == ENTER_KEY
saveInputTag()
else if event.keyCode == COMMA_KEY
removeInputLastCharacter(target)
saveInputTag()
else
if target.val().length
showSaveButton()
else
hideSaveButton()
$el.on "click", ".save", (event) ->
event.preventDefault()
saveInputTag()
$el.on "click", ".icon-delete", (event) ->
event.preventDefault()
target = angular.element(event.currentTarget)
value = target.siblings(".tag-name").text()
deleteValue(value)
bindOnce $scope, "project", (project) ->
positioningFunction = (position, elements) ->
menu = elements.element.element
menu.css("width", elements.target.width)
menu.css("top", position.top)
menu.css("left", position.left)
$el.find("input").autocomplete({
source: _.keys(project.tags_colors)
position: {
my: "left top",
using: positioningFunction
}
select: (event, ui) ->
addValue(ui.item.value)
ui.item.value = ""
})
$scope.$watch $attrs.ngModel, (tags) ->
tagsColors = $scope.project?.tags_colors or []
renderTags(tags, tagsColors)
$scope.$on "$destroy", ->
$el.off()
return {
link:link,
require:"ngModel"
template: template
}
module.directive("tgLbTagLine", ["$tgResources", LbTagLineDirective])
#############################################################################
## TagLine Directive (for detail pages)
#############################################################################
TagLineDirective = ($rootScope, $repo, $rs, $confirm, $qqueue) ->
ENTER_KEY = 13
ESC_KEY = 27
COMMA_KEY = 188
template = """
<div class="tags-container"></div>
<a href="#" class="add-tag hidden" title="Add tag">
<span class="icon icon-plus"></span>
<span class="add-tag-text">Add tag</span>
</a>
<input type="text" placeholder="I'm it! Tag me..." class="tag-input hidden" />
<a href="" title="Save" class="save icon icon-floppy hidden"></a>
""" # TODO: i18n
# Tags template (rendered manually using lodash)
templateTags = _.template("""
<% _.each(tags, function(tag) { %>
<span class="tag" style="border-left: 5px solid <%- tag.color %>;">
<span class="tag-name"><%- tag.name %></span>
<% if (isEditable) { %>
<a href="" title="delete tag" class="icon icon-delete"></a>
<% } %>
</span>
<% }); %>
""") # TODO: i18n
link = ($scope, $el, $attrs, $model) ->
isEditable = ->
return $scope.project.my_permissions.indexOf($attrs.requiredPerm) != -1
## Render
renderTags = (tags, tagsColors) ->
ctx = {
tags: _.map(tags, (t) -> {name: t, color: tagsColors[t]})
isEditable: isEditable()
}
html = templateTags(ctx)
$el.find("div.tags-container").html(html)
renderInReadModeOnly = ->
$el.find(".add-tag").remove()
$el.find("input").remove()
$el.find(".save").remove()
showAddTagButton = -> $el.find(".add-tag").removeClass("hidden")
hideAddTagButton = -> $el.find(".add-tag").addClass("hidden")
showAddTagButtonText = -> $el.find(".add-tag-text").removeClass("hidden")
hideAddTagButtonText = -> $el.find(".add-tag-text").addClass("hidden")
showSaveButton = -> $el.find(".save").removeClass("hidden")
hideSaveButton = -> $el.find(".save").addClass("hidden")
showInput = -> $el.find("input").removeClass("hidden").focus()
hideInput = -> $el.find("input").addClass("hidden").blur()
resetInput = ->
$el.find("input").val("")
$el.find("input").autocomplete("close")
## Aux methods
addValue = $qqueue.bindAdd (value) ->
value = trim(value.toLowerCase())
return if value.length == 0
tags = _.clone($model.$modelValue.tags, false)
tags = [] if not tags?
tags.push(value) if value not in tags
model = $model.$modelValue.clone()
model.tags = tags
$model.$setViewValue(model)
onSuccess = ->
$rootScope.$broadcast("history:reload")
onError = ->
$confirm.notify("error")
model.revert()
$model.$setViewValue(model)
$repo.save(model).then(onSuccess, onError)
deleteValue = $qqueue.bindAdd (value) ->
value = trim(value.toLowerCase())
return if value.length == 0
tags = _.clone($model.$modelValue.tags, false)
tags = _.pull(tags, value)
model = $model.$modelValue.clone()
model.tags = tags
$model.$setViewValue(model)
onSuccess = ->
$rootScope.$broadcast("history:reload")
onError = ->
$confirm.notify("error")
model.revert()
$model.$setViewValue(model)
return $repo.save(model).then(onSuccess, onError)
saveInputTag = () ->
value = $el.find("input").val()
addValue(value)
resetInput()
hideSaveButton()
removeInputLastCharacter = (input) =>
inputValue = input.val()
input.val inputValue.substring(0, inputValue.length - 1)
## Events
$el.on "keypress", "input", (event) ->
return if event.keyCode not in [ENTER_KEY, ESC_KEY]
event.preventDefault()
$el.on "keyup", "input", (event) ->
target = angular.element(event.currentTarget)
if event.keyCode == ENTER_KEY
saveInputTag()
else if event.keyCode == COMMA_KEY
removeInputLastCharacter(target)
saveInputTag()
else if event.keyCode == ESC_KEY
resetInput()
hideInput()
hideSaveButton()
showAddTagButton()
else
if target.val().length
showSaveButton()
else
hideSaveButton()
$el.on "click", ".save", (event) ->
event.preventDefault()
saveInputTag()
$el.on "click", ".add-tag", (event) ->
event.preventDefault()
hideAddTagButton()
showInput()
$el.on "click", ".icon-delete", (event) ->
event.preventDefault()
target = angular.element(event.currentTarget)
value = target.siblings(".tag-name").text()
deleteValue(value)
bindOnce $scope, "project", (project) ->
if not isEditable()
renderInReadModeOnly()
return
showAddTagButton()
positioningFunction = (position, elements) ->
menu = elements.element.element
menu.css("width", elements.target.width)
menu.css("top", position.top)
menu.css("left", position.left)
$el.find("input").autocomplete({
source: _.keys(project.tags_colors)
position: {
my: "left top",
using: positioningFunction
}
select: (event, ui) ->
addValue(ui.item.value)
ui.item.value = ""
})
$scope.$watch $attrs.ngModel, (model) ->
return if not model
if model.tags?.length
hideAddTagButtonText()
else
showAddTagButtonText()
tagsColors = $scope.project?.tags_colors or []
renderTags(model.tags, tagsColors)
$scope.$on "$destroy", ->
$el.off()
return {
link:link,
require:"ngModel"
template: template
}
module.directive("tgTagLine", ["$rootScope", "$tgRepo", "$tgResources", "$tgConfirm", "$tgQqueue", TagLineDirective])
| 97119 | ###
# Copyright (C) 2014 <NAME> <<EMAIL>>
# Copyright (C) 2014 <NAME> <<EMAIL>>
# Copyright (C) 2014 <NAME> <<EMAIL>>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# File: modules/common/tags.coffee
###
taiga = @.taiga
trim = @.taiga.trim
bindOnce = @.taiga.bindOnce
module = angular.module("taigaCommon")
# Directive that parses/format tags inputfield.
TagsDirective = ->
formatter = (v) ->
if _.isArray(v)
return v.join(", ")
return ""
parser = (v) ->
return [] if not v
result = _(v.split(",")).map((x) -> _.str.trim(x))
return result.value()
link = ($scope, $el, $attrs, $ctrl) ->
$ctrl.$formatters.push(formatter)
$ctrl.$parsers.push(parser)
$scope.$on "$destroy", ->
$el.off()
return {
require: "ngModel"
link: link
}
module.directive("tgTags", TagsDirective)
ColorizeTagsDirective = ->
templates = {
backlog: _.template("""
<% _.each(tags, function(tag) { %>
<span class="tag" style="border-left: 5px solid <%- tag.color %>"><%- tag.name %></span>
<% }) %>
""")
kanban: _.template("""
<% _.each(tags, function(tag) { %>
<a class="kanban-tag" href="" style="border-color: <%- tag.color %>" title="<%- tag.name %>" />
<% }) %>
""")
taskboard: _.template("""
<% _.each(tags, function(tag) { %>
<a class="taskboard-tag" href="" style="border-color: <%- tag.color %>" title="<%- tag.name %>" />
<% }) %>
""")
}
link = ($scope, $el, $attrs, $ctrl) ->
render = (srcTags) ->
template = templates[$attrs.tgColorizeTagsType]
srcTags.sort()
tags = _.map srcTags, (tag) ->
color = $scope.project.tags_colors[tag]
return {name: tag, color: color}
html = template({tags: tags})
$el.html(html)
$scope.$watch $attrs.tgColorizeTags, (tags) ->
render(tags) if tags?
$scope.$on "$destroy", ->
$el.off()
return {link: link}
module.directive("tgColorizeTags", ColorizeTagsDirective)
#############################################################################
## TagLine Directive (for Lightboxes)
#############################################################################
LbTagLineDirective = ($rs) ->
ENTER_KEY = 13
COMMA_KEY = 188
template = """
<div class="tags-container"></div>
<input type="text" placeholder="I'm it! Tag me..." class="tag-input" />
<a href="" title="Save" class="save icon icon-floppy hidden"></a>
""" # TODO: i18n
# Tags template (rendered manually using lodash)
templateTags = _.template("""
<% _.each(tags, function(tag) { %>
<span class="tag" <% if (tag.color) { %> style="border-left: 5px solid <%- tag.color %>;"<% } %>>
<span class="tag-name"><%- tag.name %></span>
<a href="" title="delete tag" class="icon icon-delete"></a>
</span>
<% }); %>
""") # TODO: i18n
link = ($scope, $el, $attrs, $model) ->
## Render
renderTags = (tags, tagsColors) ->
ctx = {
tags: _.map(tags, (t) -> {name: t, color: tagsColors[t]})
}
html = templateTags(ctx)
$el.find("div.tags-container").html(html)
showSaveButton = -> $el.find(".save").removeClass("hidden")
hideSaveButton = -> $el.find(".save").addClass("hidden")
resetInput = ->
$el.find("input").val("")
$el.find("input").autocomplete("close")
## Aux methods
addValue = (value) ->
value = trim(value.toLowerCase())
return if value.length == 0
tags = _.clone($model.$modelValue, false)
tags = [] if not tags?
tags.push(value) if value not in tags
$scope.$apply ->
$model.$setViewValue(tags)
deleteValue = (value) ->
value = trim(value.toLowerCase())
return if value.length == 0
tags = _.clone($model.$modelValue, false)
tags = _.pull(tags, value)
$scope.$apply ->
$model.$setViewValue(tags)
saveInputTag = () ->
value = $el.find("input").val()
addValue(value)
resetInput()
hideSaveButton()
removeInputLastCharacter = (input) =>
inputValue = input.val()
input.val inputValue.substring(0, inputValue.length - 1)
## Events
$el.on "keypress", "input", (event) ->
return if event.keyCode != ENTER_KEY
event.preventDefault()
$el.on "keyup", "input", (event) ->
target = angular.element(event.currentTarget)
if event.keyCode == ENTER_KEY
saveInputTag()
else if event.keyCode == COMMA_KEY
removeInputLastCharacter(target)
saveInputTag()
else
if target.val().length
showSaveButton()
else
hideSaveButton()
$el.on "click", ".save", (event) ->
event.preventDefault()
saveInputTag()
$el.on "click", ".icon-delete", (event) ->
event.preventDefault()
target = angular.element(event.currentTarget)
value = target.siblings(".tag-name").text()
deleteValue(value)
bindOnce $scope, "project", (project) ->
positioningFunction = (position, elements) ->
menu = elements.element.element
menu.css("width", elements.target.width)
menu.css("top", position.top)
menu.css("left", position.left)
$el.find("input").autocomplete({
source: _.keys(project.tags_colors)
position: {
my: "left top",
using: positioningFunction
}
select: (event, ui) ->
addValue(ui.item.value)
ui.item.value = ""
})
$scope.$watch $attrs.ngModel, (tags) ->
tagsColors = $scope.project?.tags_colors or []
renderTags(tags, tagsColors)
$scope.$on "$destroy", ->
$el.off()
return {
link:link,
require:"ngModel"
template: template
}
module.directive("tgLbTagLine", ["$tgResources", LbTagLineDirective])
#############################################################################
## TagLine Directive (for detail pages)
#############################################################################
TagLineDirective = ($rootScope, $repo, $rs, $confirm, $qqueue) ->
ENTER_KEY = 13
ESC_KEY = 27
COMMA_KEY = 188
template = """
<div class="tags-container"></div>
<a href="#" class="add-tag hidden" title="Add tag">
<span class="icon icon-plus"></span>
<span class="add-tag-text">Add tag</span>
</a>
<input type="text" placeholder="I'm it! Tag me..." class="tag-input hidden" />
<a href="" title="Save" class="save icon icon-floppy hidden"></a>
""" # TODO: i18n
# Tags template (rendered manually using lodash)
templateTags = _.template("""
<% _.each(tags, function(tag) { %>
<span class="tag" style="border-left: 5px solid <%- tag.color %>;">
<span class="tag-name"><%- tag.name %></span>
<% if (isEditable) { %>
<a href="" title="delete tag" class="icon icon-delete"></a>
<% } %>
</span>
<% }); %>
""") # TODO: i18n
link = ($scope, $el, $attrs, $model) ->
isEditable = ->
return $scope.project.my_permissions.indexOf($attrs.requiredPerm) != -1
## Render
renderTags = (tags, tagsColors) ->
ctx = {
tags: _.map(tags, (t) -> {name: t, color: tagsColors[t]})
isEditable: isEditable()
}
html = templateTags(ctx)
$el.find("div.tags-container").html(html)
renderInReadModeOnly = ->
$el.find(".add-tag").remove()
$el.find("input").remove()
$el.find(".save").remove()
showAddTagButton = -> $el.find(".add-tag").removeClass("hidden")
hideAddTagButton = -> $el.find(".add-tag").addClass("hidden")
showAddTagButtonText = -> $el.find(".add-tag-text").removeClass("hidden")
hideAddTagButtonText = -> $el.find(".add-tag-text").addClass("hidden")
showSaveButton = -> $el.find(".save").removeClass("hidden")
hideSaveButton = -> $el.find(".save").addClass("hidden")
showInput = -> $el.find("input").removeClass("hidden").focus()
hideInput = -> $el.find("input").addClass("hidden").blur()
resetInput = ->
$el.find("input").val("")
$el.find("input").autocomplete("close")
## Aux methods
addValue = $qqueue.bindAdd (value) ->
value = trim(value.toLowerCase())
return if value.length == 0
tags = _.clone($model.$modelValue.tags, false)
tags = [] if not tags?
tags.push(value) if value not in tags
model = $model.$modelValue.clone()
model.tags = tags
$model.$setViewValue(model)
onSuccess = ->
$rootScope.$broadcast("history:reload")
onError = ->
$confirm.notify("error")
model.revert()
$model.$setViewValue(model)
$repo.save(model).then(onSuccess, onError)
deleteValue = $qqueue.bindAdd (value) ->
value = trim(value.toLowerCase())
return if value.length == 0
tags = _.clone($model.$modelValue.tags, false)
tags = _.pull(tags, value)
model = $model.$modelValue.clone()
model.tags = tags
$model.$setViewValue(model)
onSuccess = ->
$rootScope.$broadcast("history:reload")
onError = ->
$confirm.notify("error")
model.revert()
$model.$setViewValue(model)
return $repo.save(model).then(onSuccess, onError)
saveInputTag = () ->
value = $el.find("input").val()
addValue(value)
resetInput()
hideSaveButton()
removeInputLastCharacter = (input) =>
inputValue = input.val()
input.val inputValue.substring(0, inputValue.length - 1)
## Events
$el.on "keypress", "input", (event) ->
return if event.keyCode not in [ENTER_KEY, ESC_KEY]
event.preventDefault()
$el.on "keyup", "input", (event) ->
target = angular.element(event.currentTarget)
if event.keyCode == ENTER_KEY
saveInputTag()
else if event.keyCode == COMMA_KEY
removeInputLastCharacter(target)
saveInputTag()
else if event.keyCode == ESC_KEY
resetInput()
hideInput()
hideSaveButton()
showAddTagButton()
else
if target.val().length
showSaveButton()
else
hideSaveButton()
$el.on "click", ".save", (event) ->
event.preventDefault()
saveInputTag()
$el.on "click", ".add-tag", (event) ->
event.preventDefault()
hideAddTagButton()
showInput()
$el.on "click", ".icon-delete", (event) ->
event.preventDefault()
target = angular.element(event.currentTarget)
value = target.siblings(".tag-name").text()
deleteValue(value)
bindOnce $scope, "project", (project) ->
if not isEditable()
renderInReadModeOnly()
return
showAddTagButton()
positioningFunction = (position, elements) ->
menu = elements.element.element
menu.css("width", elements.target.width)
menu.css("top", position.top)
menu.css("left", position.left)
$el.find("input").autocomplete({
source: _.keys(project.tags_colors)
position: {
my: "left top",
using: positioningFunction
}
select: (event, ui) ->
addValue(ui.item.value)
ui.item.value = ""
})
$scope.$watch $attrs.ngModel, (model) ->
return if not model
if model.tags?.length
hideAddTagButtonText()
else
showAddTagButtonText()
tagsColors = $scope.project?.tags_colors or []
renderTags(model.tags, tagsColors)
$scope.$on "$destroy", ->
$el.off()
return {
link:link,
require:"ngModel"
template: template
}
module.directive("tgTagLine", ["$rootScope", "$tgRepo", "$tgResources", "$tgConfirm", "$tgQqueue", TagLineDirective])
| true | ###
# Copyright (C) 2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
# Copyright (C) 2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
# Copyright (C) 2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# File: modules/common/tags.coffee
###
taiga = @.taiga
trim = @.taiga.trim
bindOnce = @.taiga.bindOnce
module = angular.module("taigaCommon")
# Directive that parses/format tags inputfield.
TagsDirective = ->
formatter = (v) ->
if _.isArray(v)
return v.join(", ")
return ""
parser = (v) ->
return [] if not v
result = _(v.split(",")).map((x) -> _.str.trim(x))
return result.value()
link = ($scope, $el, $attrs, $ctrl) ->
$ctrl.$formatters.push(formatter)
$ctrl.$parsers.push(parser)
$scope.$on "$destroy", ->
$el.off()
return {
require: "ngModel"
link: link
}
module.directive("tgTags", TagsDirective)
ColorizeTagsDirective = ->
templates = {
backlog: _.template("""
<% _.each(tags, function(tag) { %>
<span class="tag" style="border-left: 5px solid <%- tag.color %>"><%- tag.name %></span>
<% }) %>
""")
kanban: _.template("""
<% _.each(tags, function(tag) { %>
<a class="kanban-tag" href="" style="border-color: <%- tag.color %>" title="<%- tag.name %>" />
<% }) %>
""")
taskboard: _.template("""
<% _.each(tags, function(tag) { %>
<a class="taskboard-tag" href="" style="border-color: <%- tag.color %>" title="<%- tag.name %>" />
<% }) %>
""")
}
link = ($scope, $el, $attrs, $ctrl) ->
render = (srcTags) ->
template = templates[$attrs.tgColorizeTagsType]
srcTags.sort()
tags = _.map srcTags, (tag) ->
color = $scope.project.tags_colors[tag]
return {name: tag, color: color}
html = template({tags: tags})
$el.html(html)
$scope.$watch $attrs.tgColorizeTags, (tags) ->
render(tags) if tags?
$scope.$on "$destroy", ->
$el.off()
return {link: link}
module.directive("tgColorizeTags", ColorizeTagsDirective)
#############################################################################
## TagLine Directive (for Lightboxes)
#############################################################################
LbTagLineDirective = ($rs) ->
ENTER_KEY = 13
COMMA_KEY = 188
template = """
<div class="tags-container"></div>
<input type="text" placeholder="I'm it! Tag me..." class="tag-input" />
<a href="" title="Save" class="save icon icon-floppy hidden"></a>
""" # TODO: i18n
# Tags template (rendered manually using lodash)
templateTags = _.template("""
<% _.each(tags, function(tag) { %>
<span class="tag" <% if (tag.color) { %> style="border-left: 5px solid <%- tag.color %>;"<% } %>>
<span class="tag-name"><%- tag.name %></span>
<a href="" title="delete tag" class="icon icon-delete"></a>
</span>
<% }); %>
""") # TODO: i18n
link = ($scope, $el, $attrs, $model) ->
## Render
renderTags = (tags, tagsColors) ->
ctx = {
tags: _.map(tags, (t) -> {name: t, color: tagsColors[t]})
}
html = templateTags(ctx)
$el.find("div.tags-container").html(html)
showSaveButton = -> $el.find(".save").removeClass("hidden")
hideSaveButton = -> $el.find(".save").addClass("hidden")
resetInput = ->
$el.find("input").val("")
$el.find("input").autocomplete("close")
## Aux methods
addValue = (value) ->
value = trim(value.toLowerCase())
return if value.length == 0
tags = _.clone($model.$modelValue, false)
tags = [] if not tags?
tags.push(value) if value not in tags
$scope.$apply ->
$model.$setViewValue(tags)
deleteValue = (value) ->
value = trim(value.toLowerCase())
return if value.length == 0
tags = _.clone($model.$modelValue, false)
tags = _.pull(tags, value)
$scope.$apply ->
$model.$setViewValue(tags)
saveInputTag = () ->
value = $el.find("input").val()
addValue(value)
resetInput()
hideSaveButton()
removeInputLastCharacter = (input) =>
inputValue = input.val()
input.val inputValue.substring(0, inputValue.length - 1)
## Events
$el.on "keypress", "input", (event) ->
return if event.keyCode != ENTER_KEY
event.preventDefault()
$el.on "keyup", "input", (event) ->
target = angular.element(event.currentTarget)
if event.keyCode == ENTER_KEY
saveInputTag()
else if event.keyCode == COMMA_KEY
removeInputLastCharacter(target)
saveInputTag()
else
if target.val().length
showSaveButton()
else
hideSaveButton()
$el.on "click", ".save", (event) ->
event.preventDefault()
saveInputTag()
$el.on "click", ".icon-delete", (event) ->
event.preventDefault()
target = angular.element(event.currentTarget)
value = target.siblings(".tag-name").text()
deleteValue(value)
bindOnce $scope, "project", (project) ->
positioningFunction = (position, elements) ->
menu = elements.element.element
menu.css("width", elements.target.width)
menu.css("top", position.top)
menu.css("left", position.left)
$el.find("input").autocomplete({
source: _.keys(project.tags_colors)
position: {
my: "left top",
using: positioningFunction
}
select: (event, ui) ->
addValue(ui.item.value)
ui.item.value = ""
})
$scope.$watch $attrs.ngModel, (tags) ->
tagsColors = $scope.project?.tags_colors or []
renderTags(tags, tagsColors)
$scope.$on "$destroy", ->
$el.off()
return {
link:link,
require:"ngModel"
template: template
}
module.directive("tgLbTagLine", ["$tgResources", LbTagLineDirective])
#############################################################################
## TagLine Directive (for detail pages)
#############################################################################
TagLineDirective = ($rootScope, $repo, $rs, $confirm, $qqueue) ->
ENTER_KEY = 13
ESC_KEY = 27
COMMA_KEY = 188
template = """
<div class="tags-container"></div>
<a href="#" class="add-tag hidden" title="Add tag">
<span class="icon icon-plus"></span>
<span class="add-tag-text">Add tag</span>
</a>
<input type="text" placeholder="I'm it! Tag me..." class="tag-input hidden" />
<a href="" title="Save" class="save icon icon-floppy hidden"></a>
""" # TODO: i18n
# Tags template (rendered manually using lodash)
templateTags = _.template("""
<% _.each(tags, function(tag) { %>
<span class="tag" style="border-left: 5px solid <%- tag.color %>;">
<span class="tag-name"><%- tag.name %></span>
<% if (isEditable) { %>
<a href="" title="delete tag" class="icon icon-delete"></a>
<% } %>
</span>
<% }); %>
""") # TODO: i18n
link = ($scope, $el, $attrs, $model) ->
isEditable = ->
return $scope.project.my_permissions.indexOf($attrs.requiredPerm) != -1
## Render
renderTags = (tags, tagsColors) ->
ctx = {
tags: _.map(tags, (t) -> {name: t, color: tagsColors[t]})
isEditable: isEditable()
}
html = templateTags(ctx)
$el.find("div.tags-container").html(html)
renderInReadModeOnly = ->
$el.find(".add-tag").remove()
$el.find("input").remove()
$el.find(".save").remove()
showAddTagButton = -> $el.find(".add-tag").removeClass("hidden")
hideAddTagButton = -> $el.find(".add-tag").addClass("hidden")
showAddTagButtonText = -> $el.find(".add-tag-text").removeClass("hidden")
hideAddTagButtonText = -> $el.find(".add-tag-text").addClass("hidden")
showSaveButton = -> $el.find(".save").removeClass("hidden")
hideSaveButton = -> $el.find(".save").addClass("hidden")
showInput = -> $el.find("input").removeClass("hidden").focus()
hideInput = -> $el.find("input").addClass("hidden").blur()
resetInput = ->
$el.find("input").val("")
$el.find("input").autocomplete("close")
## Aux methods
addValue = $qqueue.bindAdd (value) ->
value = trim(value.toLowerCase())
return if value.length == 0
tags = _.clone($model.$modelValue.tags, false)
tags = [] if not tags?
tags.push(value) if value not in tags
model = $model.$modelValue.clone()
model.tags = tags
$model.$setViewValue(model)
onSuccess = ->
$rootScope.$broadcast("history:reload")
onError = ->
$confirm.notify("error")
model.revert()
$model.$setViewValue(model)
$repo.save(model).then(onSuccess, onError)
deleteValue = $qqueue.bindAdd (value) ->
value = trim(value.toLowerCase())
return if value.length == 0
tags = _.clone($model.$modelValue.tags, false)
tags = _.pull(tags, value)
model = $model.$modelValue.clone()
model.tags = tags
$model.$setViewValue(model)
onSuccess = ->
$rootScope.$broadcast("history:reload")
onError = ->
$confirm.notify("error")
model.revert()
$model.$setViewValue(model)
return $repo.save(model).then(onSuccess, onError)
saveInputTag = () ->
value = $el.find("input").val()
addValue(value)
resetInput()
hideSaveButton()
removeInputLastCharacter = (input) =>
inputValue = input.val()
input.val inputValue.substring(0, inputValue.length - 1)
## Events
$el.on "keypress", "input", (event) ->
return if event.keyCode not in [ENTER_KEY, ESC_KEY]
event.preventDefault()
$el.on "keyup", "input", (event) ->
target = angular.element(event.currentTarget)
if event.keyCode == ENTER_KEY
saveInputTag()
else if event.keyCode == COMMA_KEY
removeInputLastCharacter(target)
saveInputTag()
else if event.keyCode == ESC_KEY
resetInput()
hideInput()
hideSaveButton()
showAddTagButton()
else
if target.val().length
showSaveButton()
else
hideSaveButton()
$el.on "click", ".save", (event) ->
event.preventDefault()
saveInputTag()
$el.on "click", ".add-tag", (event) ->
event.preventDefault()
hideAddTagButton()
showInput()
$el.on "click", ".icon-delete", (event) ->
event.preventDefault()
target = angular.element(event.currentTarget)
value = target.siblings(".tag-name").text()
deleteValue(value)
bindOnce $scope, "project", (project) ->
if not isEditable()
renderInReadModeOnly()
return
showAddTagButton()
positioningFunction = (position, elements) ->
menu = elements.element.element
menu.css("width", elements.target.width)
menu.css("top", position.top)
menu.css("left", position.left)
$el.find("input").autocomplete({
source: _.keys(project.tags_colors)
position: {
my: "left top",
using: positioningFunction
}
select: (event, ui) ->
addValue(ui.item.value)
ui.item.value = ""
})
$scope.$watch $attrs.ngModel, (model) ->
return if not model
if model.tags?.length
hideAddTagButtonText()
else
showAddTagButtonText()
tagsColors = $scope.project?.tags_colors or []
renderTags(model.tags, tagsColors)
$scope.$on "$destroy", ->
$el.off()
return {
link:link,
require:"ngModel"
template: template
}
module.directive("tgTagLine", ["$rootScope", "$tgRepo", "$tgResources", "$tgConfirm", "$tgQqueue", TagLineDirective])
|
[
{
"context": " cocktail', ->\n updated =\n name: 'Archer Marg'\n description: '5 ingredients...'\n\n ",
"end": 443,
"score": 0.9997413158416748,
"start": 432,
"tag": "NAME",
"value": "Archer Marg"
}
] | spec/javascripts/controllers/CocktailEditCtrl_spec.coffee | baberthal/cocktails | 0 | #= require spec_helper
describe 'CocktailEditCtrl', ->
beforeEach ->
@setupController('CocktailEditCtrl', false, 3)
@Cocktail = @model('Cocktail')
@loadFixtures()
@http.whenGET('/cocktails/3').respond(200, @oldCocktail)
@templateExpectations()
describe 'controller initialization', ->
describe 'editing a cocktail', ->
it 'can properly update the cocktail', ->
updated =
name: 'Archer Marg'
description: '5 ingredients...'
@scope.cocktail.name = updated.name
@scope.cocktail.description = updated.description
@scope.saveRecipe(@scope.cocktail)
@http.expectPUT('/cocktails/3').respond(204)
@http.flush()
it 'can close the dialog', ->
mdDialog = @injector.get('$mdDialog')
spyOn(mdDialog, 'cancel')
@scope.cancel()
expect(mdDialog.cancel).toHaveBeenCalled()
| 64280 | #= require spec_helper
describe 'CocktailEditCtrl', ->
beforeEach ->
@setupController('CocktailEditCtrl', false, 3)
@Cocktail = @model('Cocktail')
@loadFixtures()
@http.whenGET('/cocktails/3').respond(200, @oldCocktail)
@templateExpectations()
describe 'controller initialization', ->
describe 'editing a cocktail', ->
it 'can properly update the cocktail', ->
updated =
name: '<NAME>'
description: '5 ingredients...'
@scope.cocktail.name = updated.name
@scope.cocktail.description = updated.description
@scope.saveRecipe(@scope.cocktail)
@http.expectPUT('/cocktails/3').respond(204)
@http.flush()
it 'can close the dialog', ->
mdDialog = @injector.get('$mdDialog')
spyOn(mdDialog, 'cancel')
@scope.cancel()
expect(mdDialog.cancel).toHaveBeenCalled()
| true | #= require spec_helper
describe 'CocktailEditCtrl', ->
beforeEach ->
@setupController('CocktailEditCtrl', false, 3)
@Cocktail = @model('Cocktail')
@loadFixtures()
@http.whenGET('/cocktails/3').respond(200, @oldCocktail)
@templateExpectations()
describe 'controller initialization', ->
describe 'editing a cocktail', ->
it 'can properly update the cocktail', ->
updated =
name: 'PI:NAME:<NAME>END_PI'
description: '5 ingredients...'
@scope.cocktail.name = updated.name
@scope.cocktail.description = updated.description
@scope.saveRecipe(@scope.cocktail)
@http.expectPUT('/cocktails/3').respond(204)
@http.flush()
it 'can close the dialog', ->
mdDialog = @injector.get('$mdDialog')
spyOn(mdDialog, 'cancel')
@scope.cancel()
expect(mdDialog.cancel).toHaveBeenCalled()
|
[
{
"context": "1>\n \"\n imageCredit: \"Image credit and © Brian Koprowski\"\n content: '''\n To find out which animals",
"end": 459,
"score": 0.9996256828308105,
"start": 444,
"tag": "NAME",
"value": "Brian Koprowski"
},
{
"context": "! \n\n Chicago Wildlife W... | app/translations/en_us.coffee | zooniverse/Snapshot-Chicago | 2 | module.exports =
navigation:
home: 'Home'
about: 'About'
classify: 'Classify'
profile: 'Profile'
discuss: 'Talk'
education: 'Education'
press: 'Press'
blog: 'Blog'
home:
heading: 'Chicago Wildlife Watch'
rightBannerHeader: "What is Chicago Wildlife Watch?"
leftBannerHeader: "
<h2>Welcome to</h2>
<h1>Chicago <br/> Wildlife Watch</h1>
"
imageCredit: "Image credit and © Brian Koprowski"
content: '''
To find out which animals live in Chicago, we’ve collected more than 1 million photos of wildlife from the Loop to the burbs. To ID them, though, we need your help!
Chicago Wildlife Watch, developed by Lincoln Park Zoo and the Adler Planetarium, lets everyone help us understand how animals—from coyotes to chipmunks—share this great city.
'''
action: 'Get Started'
currentStatus: '<span class="classification-count">0</span> classifications by <span class="user-count">0</span> volunteers'
preFooterText: "Chicago Wildlife Watch is a collaboration between Lincoln Park Zoo, the Adler Planetarium and the Zooniverse."
stats:
header: "CHICAGO WILDLIFE WATCH Statistics"
activeUsers: "Active Users"
crittersIdentified: "Classifications"
totalImages: "Images Total"
complete: "Complete"
filterPage:
header: "Choose Your Data"
name: "Education Mode"
filtered: "Curated"
unfiltered: "Uncurated"
question: "Would you like to view Curated or Uncurated data?"
notification: "These images have been taken by cameras in public spaces"
description: """
If you are using Chicago Wildlife Watch for educational purposes or with young children, you might want to use our 'Curated' dataset option. The images in this data set are much more likely to contain an animal but still require additional attention to confirm the animal type. For a younger audience, or for a situation where time is limited, this may provide a more engaging experience.
"""
siteIntro:
s1:
title: "Welcome!"
content: "Welcome to Chicago Wildlife Watch! In this project, we are asking you to identify animals found in camera trap photos from around the city. Your help allows us to continue our research into urban biodiversity, making the city a better home for both humans and animals."
s2:
title: "Identifying animals"
content: "You are presented with a photo on the left and a list of potential animals on the right. When you spot an animal within a photo, simply click the corresponding animal on the right. You will be asked to supply some followup info, such as the number of animals found in the image."
s3:
title: "Filtering by characteristics"
content: "Occasionally it is difficult to determine which animal is in the photo. Just above the list of animals is a variety of methods to filter the animal list. Selecting different options reduces the number of choices, making your job easier."
s4:
title: "Made a mistake?"
content: "If you need to delete any of your existing marks while viewing an image, simply find your animal in the list below the image and click the 'X' icon. Don’t worry if you’re unsure about your choices, though—even a guess is more helpful than nothing!"
s5:
title: "That's it!"
content: "That's it! You may catch up on project updates either on the blog or through speaking with other volunteers. If you need additional help using the interface, click Tutorial within the list of links below the Finish button."
classify:
deleteAnnotation: 'Delete'
notSignedIn: 'You\'re not signed in!'
favorite: 'Favorite'
unfavorite: 'Unfavorite'
nothingLabel: 'Nothing here'
nextSubjectButton: 'Finish'
share: 'Share'
tweet: 'Tweet'
pin: 'Pin it'
discuss: 'Discuss'
next: 'Next capture'
search: 'Search'
annotationsMessage: "See something? Animals you identify will appear here..."
helpLink: "Need some spotting tips? Check out these blog posts!"
nothingToShow: 'There\'s nothing to show with these filters.'
clearFilters: 'Clear filters'
curatedError: "We can't find any subjects right now in our curated dataset', Click the 'Next Capture' button to try again or <a href='#/filter'>view our uncurated dataset</a>"
oftenConfused: 'Often confused with:'
count: 'How many'
behavior: 'Behavior'
behaviors:
headUp: 'Head Up'
headDown: 'Head Down'
neither: 'Neither'
notVisible: 'Not Visible'
notApplicable: 'N/A'
babies: 'Young present'
rain: 'Raining'
cancel: 'Cancel'
identify: 'Identify'
tutorial:
small: "Site Intro"
button: "Tutorial"
continueButton: 'Continue'
welcomeHeader: 'Welcome to Chicago Wildlife Watch!'
welcome: '''
This short tutorial will walk you through your first identification. Let's get started!
'''
trapsHeader: 'Check out the Images'
traps: '''
All over Chicago, scientists have set up motion-sensitive camera traps.
The camera snaps a few shots anytime something moves in front of it.
'''
taskHeader: 'Identify the Animals'
task: '''
Your task is to identify all the different animals that appear in the photos.
The species that will appear are listed here.
It's a big list, and some species may be unfamiliar,
but there are a few ways to narrow that list down using the characteristics you see.
'''
chooseRodentHeader: 'Looks like...'
chooseRodent: '''
The animal in the foreground of this photo looks like a rodent of some kind.
Let's choose <strong>"Rodent"</strong> from the <strong>"Looks like"</strong> menu.
'''
chooseTanYellowHeader: 'Characteristic: Coat'
chooseTanYellow: '''
Let's narrow the list down a bit by choosing the <strong>"Tan Yellow"</strong> swatch from the <strong>"Coat"</strong> menu.
'''
chooseBushyHeader: 'Characteristic: Tail'
chooseBushy: '''
We've narrowed the list down enough to see thumbnail previews of the remaining animals.
Choose the <strong>"Bushy"</strong> icon from the <strong>"Tail"</strong> menu to narrow the list down further.
'''
chooseGraySquirrelHeader: 'Make a choice'
chooseGraySquirrel: '''
Great, that leaves us with just one option!
Let's choose <strong>"Gray Squirrel"</strong> and make sure it's a match.
'''
confirmWildebeestHeader: 'Looks Good!'
confirmWildebeest: '''
By comparing the animal to the photos here and reading the description below, we can confirm that this is indeed a gray squirrel.
You can flip through the photos to see examples of the animal from multiple angles using the bullets on the right.
'''
identifyWildebeestHeader: 'Count & Behavior'
identifyWildebeest: '''
Once you're confident that this is a gray squirrel,
choose <strong>"1"</strong> from the count menu and <strong>"Head Up"</strong> from the behavior menu.
Then click "Identify."
'''
finishHeader: 'Nice Job!'
finish: '''
Now you're ready to identify some images on your own.
In each image, do your best to identify all the animals you can,
even if you can't see enough to be completely sure.
If there aren't any animals in an image, check "Nothing here" and then "Finish."
Your observations will be combined with those of multiple volunteers,
so even if you're not sure on something, your contribution is still very useful!
Don't forget: after identifying an image you can always <strong>discuss</strong> it with professional and citizen scientists or share it with friends.
Click <strong>"Finish"</strong> now to move on.
'''
animals:
beaver:
label: 'Beaver'
description: '''
This animal is usually brown with large sharp front teeth, clawed front feet webbed back feet, a round body and a large flat tail. As the second largest rodent in the world, beavers are semi-aquatic and primarily nocturnal.
'''
bird:
label: 'Bird'
description: '''
All manner of birds will be captured in the pictures, from cardinals to seagulls. They will frequently be found either nesting in trees or scavenging for food on the ground.
'''
chipmunk:
label: 'Chipmunk'
description: '''
A small member of the squirrel family that uses its cheek pouch to carry various nuts, berries and seeds into its burrow or nest to store its food. They have smaller, less bushy tails than a typical squirrel and sport signature white-and-brown stripes around their eye and going down their back. Typically brown or tan in color.
'''
coyote:
label: 'Coyote'
description: '''
Commonly brown and tan in color, this member of the dog family is smaller than a wolf. They have occasionally been called prairie wolves or brush wolves due to their wolf-like appearance, but they differ from wolves with their pointed snouts, slender body and tall, pointy ears. In the fall and winter, they form packs for more effective hunting.
'''
deer:
label: 'Deer'
description: '''
A fairly big, tan animal that is in the same family as moose and reindeer. They have large ears and short fluffy tails. The males are called bucks while females are called does, and the young are called fawns. Some males may have antlers depending on the time of the year.
'''
domCat:
label: 'Cat, Domestic'
description: '''
A common household pet with a small build, a long tail and small pointed ears. This animal comes in a variety of color, patterns (spotted or stripes), and breeds.
'''
domDog:
label: 'Dog, Domestic'
description: '''
A common household pet related to wolves, foxes and jackals. This animal comes in a variety of colors, sizes, patterns and breeds.
'''
flyingSquirrel:
label: 'Squirrel, Flying'
description: '''
A member of the squirrel family, this animal has large, dark eyes, loose skin between the front and back legs, clawed feet and a long, bushy tail with dark fur on top and light below. It travels from tree to tree by launching itself and spreading its limbs so it can glide while using its legs to steer and its tail to brake when it reaches its destination.
'''
foxSquirrel:
label: 'Squirrel, Fox'
description: '''
The largest species of tree squirrel in North America, they look like a larger typical squirrel with an orange tone to their fur. They can be around 2 feet in length and weight 1 - 2 lbs. It spends most of its time foraging for food and roaming around fields.
'''
grayFox:
label: 'Fox, Gray'
description: '''
A small to medium-sized animal with a gray coat on its back and head with light fur on its chest and belly. They have a signature black-tipped, bushy tail and a band of black fur from the inner corner of their eyes around the bottom of their snout. They are tree climbers, typically sleep during the day at very rocky locations and are active during the night.
'''
graySquirrel:
label: 'Squirrel, Gray'
description: '''
Small squirrels that are gray-brown all over their bodies except the white patch along their belly. This animal's diet consists of acorns, hickory nuts, maple and walnuts.
'''
horse:
label: 'Horse'
description: '''
A large, muscular animal with a mane of hair along the back of the head and neck. These animals have hooves and a long tail of hair.
'''
human:
label: 'Human'
description: '''
Identifying a human within a photo flags this image. We generally remove images of humans very quickly from the dataset.
'''
livestock:
label: 'Livestock'
description: '''
N/A. Identifying the frequency of livestock helps us understand the impact of human activity on the animal population in this urban habitat.
'''
mink:
label: 'Mink'
description: '''
Related to otters, weasels and ferrets, minks have pointed snouts with dark eyes. They also have clawed feet with webbing and bodies covered in thick brown fur that sheds water quickly. These animals live in semi-aquatic habitats.
'''
mouse:
label: 'Mouse'
description: '''
A very small animal with a long snout, big round ears and a long hairless tail. This animal can be found in and around grasslands and homes.
'''
mower:
label: 'Mower'
description: '''
N/A. Identifying the frequency of mowers helps us understand the impact of human activity on the animal population in this urban habitat.
'''
muskrat:
label: 'Muskrat'
description: '''
This animal normally has brown fur and a black tail with small dark eyes. The fur-less, scaly tail is half of its total length. When it walks, the tail creates a trail. Their front paws are clawed while the rear feet are semi-webbed and clawed.
'''
opossum:
label: 'Opossum'
description: '''
Adept tree climbers with their clawed feet and opposable big toe on rear paw. This animal is known for playing dead and has a white face with a pink nose, black eyes, black ears, long tail and long, gray fur on its body.
'''
rabbit:
label: 'Rabbit'
description: '''
Rabbits we see in urban settings have large, dark eyes, long ears pointed upwards and brown fur with a short, fluffy, white tail.
'''
raccoon:
label: 'Raccoon'
description: '''
This brown-gray furry animal looks like it is wearing a bandit mask with the black patches around its eyes on its white face. Another notable features are its finger-like clawed toes and its black-ringed tail with long fur. Raccoons are nocturnal and often seen foraging for food in trash bins.
'''
rat:
label: 'Rat'
description: '''
A large mouse-like critter with a pointy nose, round ears and a long, hairless, pinkish tail. Many people think they only roam the subway and sewers, but it is not uncommon to see then running across the street above ground.
'''
redFox:
label: 'Fox, Red'
description: '''
An animal with orange brownish fur along its head and back and white fur on its belly and typically at the tip of its bushy tail. Its tail helps it balance just like a cat’s. Some have black fur on the back of their ears and legs.
'''
skunk:
label: 'Skunk'
description: '''
An animal well known for its stinky spray towards predators and black coat with white stripe patterns. It has a single thin, white stripe down the middle of its face and two thicker white stripes originating at the top of its head running down either side of the back into its thick, bushy tail.
'''
woodChuck:
label: 'Woodchuck'
description: '''
This animal is also known as a groundhog. It has a brown furry coat, clawed feet, small eyes and ears, and a short, flat tail.
'''
melanisticGraySquirrel:
label: 'Squirrel, Melanistic Gray'
description: '''
Melanism is a genetic trait that produces extra melanin in the skin and fur, making an organism appear jet black if it has two sets of this recessive gene or brown/black if it only has one. Gray squirrels are known to carry this unusual genetic trait. This trait may be beneficial to gray squirrels living at northern latitudes as they would lose less heat during the cold winter months. The photo in this ID is of a brown/black melanistic gray squirrel.
'''
characteristics:
like: 'Looks like...'
coat: 'Coat'
tail: 'Tail'
build: 'Build'
characteristicValues:
likeCatDog: 'Cat Dog'
likeRodent: 'Rodent'
likeManMade: 'Vehicles'
likeOther: 'Other'
coatTanYellow: 'Tan Yellow'
coatRedBrown: 'Red Brown'
coatBrownBlack: 'Brown Black'
coatGrayBlack: 'Gray Black'
coatMottled: 'Mottled'
coatSolid: 'Solid'
coatOrTailStriped: 'Or Tail Striped'
tailBushy: 'Bushy'
tailSmooth: 'Smooth'
tailLong: 'Long'
buildStocky: 'Stocky'
buildLanky: 'Lanky'
buildSmall: 'Small'
buildLowSlung: 'Low Slung'
profile:
header: "Your Profile"
favorites: 'Favorites'
recents: 'Recents'
noFavorites: 'You have no favorites!'
noRecents: 'You have no recent identifications!'
showing: 'Showing'
loadMore: 'Load more'
about:
press:
nav:
"Press"
science:
nav: "Science"
header: "Science"
p: """
<p>
Cities can be hostile places for wildlife, with threats coming from habitat destruction, roads and traffic, humans, pets and large numbers of invasive species. However, with proper management, urban areas can house a number of important wildlife species, including carnivores and small mammals.
</p>
<p>
To assess the biodiversity of the greater Chicagoland area, Lincoln Park Zoo’s Urban Wildlife Institute has established monitoring stations within city parks, forest preserves, golf courses and cemeteries in parts of Cook, Lake, DuPage and Will Counties including downtown Chicago. Motion-triggered cameras are deployed four times per year at more than 100 sites to determine which species are present and to assess spatial and long-term patterns in wildlife communities.
</p>
<p>
Knowing where Chicago’s urban wildlife is located will help us to better conserve it. This knowledge will pave the way for future studies on the behavior and ecology of specific urban species, helping stakeholders to better manage wildlife conflict.
</p>
<p>
Keep an eye out for the black pouches that are often attached to trees in most of the photos. They contain a scented lure that increases the probability of photographing the wildlife community at a site.
</p>
<img src="./images/animals/fox-squirrel-1.jpg">
"""
questions: """
<h1>Our Scientific Questions</h1>
<h2>Where do they go?</h2>
<p>We don’t know as much as we’d like about species in urban systems. Even basic facts like what types of habitat attract which species are often unknown in areas like cities.
Finding out where certain species are most likely to occur allows us to target conservation and management efforts to ensure we can coexist with our wildlife neighbors.</p>
<h2>How are they doing?</h2>
<p>While we can’t directly measure populations with the data from our cameras, we can get a sense of which species are most common and which may be in decline.
This can help us make recommendations about how to improve conditions for the species that are in trouble.</p>
<h2>How do they compete?</h2>
<p>We know almost nothing about how species in urban areas might compete with one another, engage in predator-prey dynamics or avoid each other.
Preliminary results indicate that the normal community interactions we observe in natural systems don’t apply to urban areas, where entirely new dynamics seem to be in place.
By evaluating our camera images, we can begin to assemble the first complete picture of an urban ecosystem, including how all the species interact.</p>
<h2>How do they interact with us?</h2>
<p>By also collecting data on humans, and on pets like cats and dogs, we can get a sense of how animals in urban settings react to the people who make the city their home.
Some animals may be attracted to sites that are often visited by humans, while others may be looking for more secluded places. Humans are a critical part of the system,
and our camera data allows us to understand our impact, as well as the importance of food and habitat.</p>
"""
uwi:
nav: "Urban Wildlife Institute"
header: "Urban Wildlife Institute"
content: """
<p>Utilizing Lincoln Park Zoo’s diverse scientific specialties, the Urban Wildlife Institute studies the interaction between urban development and the natural ecosystem to develop scientific standards for minimizing conflict between these overlapping areas. Landscape ecology, population biology, epidemiology, endocrinology, veterinary medicine and other core disciplines contribute to an increased understanding of ecosystem health in an urban setting. The Urban Wildlife Institute aims to use Chicago as a model for urban areas struggling to deal with wildlife relocation, rehabilitation, disease and conflicts.</p>
<p>One issue receiving special emphasis is the transmission of disease from animals to humans—another byproduct of urban sprawl. By studying how people and animals interact in an urban setting, the Urban Wildlife Institute can help scientists to better understand—and curb—zoonotic disease threats such as West Nile virus, rabies and avian influenza.</p>
<p>Supported by a $1.5 million grant from the Davee Foundation, the Urban Wildlife Institute is forming partnerships with local nature and conservation organizations and conducting pilot studies into ecosystem health and human-wildlife interaction. By developing standards for managing urban wildlife issues, the institute is creating a conflict-management model that can be followed worldwide.</p>
<p>To learn more, you can visit <a href="http://www.lpzoo.org/conservation-science/science-centers/urban-wildlife-institute">their website</a>.</p>
"""
zooniverse:
nav: "Zooniverse"
header: "Zooniverse"
content: """
<p>The amount of data collected by modern research equipment is often too large for any one person or small team of people to effectively analyze. Over the past several decades, scientists have explored partnering with the public to help do real science when human eyes and thinking are still better at analysis than computers.</p>
<p>Known online as the Zooniverse, the Adler's Citizen Science department designs and develops web applications using data sets that would normally take a science team over 100 years to analyze and, with the help of a worldwide network of volunteers, complete the analysis with a high level of accuracy in weeks or months.</p>
<p>To participate in other citizen science efforts, visit <a href="https://www.zooniverse.org">Zooniverse.org</a>.</p>
"""
organizations:
nav: "Organizations"
header: "Organizations"
adler:
header: "Adler Planetarium"
p: """
<img src="./images/logos/adler-black.png" class="inline">
<a href="http://www.adlerplanetarium.org/">The Adler Planetarium</a> - America's First Planetarium - was founded in 1930 by Chicago business leader Max Adler.
The Adler is a recognized leader in science education, with a focus on inspiring young people to pursue careers in science, technology, engineering and math.
Throughout 80 years, the Adler has inspired the next generation of explorers by sharing the personal stories of space exploration and America’s space heroes.
"""
lincolnParkZoo:
header: "Lincoln Park Zoo"
p: """
<img src="./images/logos/lpz-black.png" class="inline">
<a href="http://www.lpzoo.org/">Lincoln Park Zoo</a> is a world of wildlife in the shadow of skyscrapers. Located within a verdant park just minutes north of Chicago, the zoo has been a natural, free oasis for generations of animal lovers, who visit the zoo to hear a lion’s roar echo off nearby apartment buildings, see gorillas climb trees as the Willis Tower looms in the distance or forget where they are as they immerse themselves in tropical rainforests, dry-thorn forests or spacious savannas.<br><br>
Lincoln Park Zoo is dedicated to connecting people with nature by providing a free, family-oriented wildlife experience in the heart of Chicago and by advancing the highest quality of animal care, education, science and conservation.
"""
team:
nav: "Team"
header: "Team"
science:
magle:
name: 'Dr. Seth Magle'
title: 'Director, Urban Wildlife Institute at Lincoln Park Zoo'
image: 'http://placehold.it/100'
description: '''
<p>Seth first became interested in conservation and ecology as a college student in 1997 while observing black-tailed prairie dogs living in sidewalk median strips near his home in Boulder, Colorado. Daily interactions with these resilient animals made him wonder what adaptations enabled these small mammals to persist in highly urban habitat and which factors contributed to their distribution and abundance. Eventually he completed an honors thesis on the behavior of this urban-adapted keystone species; he ultimately expanded on that research for both a master’s degree and a doctorate.</p>
<p>However, Seth’s interests go far beyond prairie dogs to encompass all wildlife species impacted by urbanization and human development. He has also engaged in research on movement behavior of white-tailed deer in a rural landscape characterized by high prevalence of disease outbreaks, assessments of the diversity of bird communities residing in agricultural habitat and the conservation of Canada lynx reintroduced to the southern edge of their historical range, where they are threatened by roads and traffic.</p>
<p>Seth strongly believes that if rare and imperiled species are to be conserved in our modern world, we must understand and mitigate all potential impacts of urban areas on wildlife. To that end, he engages in studies of urban wildlife that span a broad range of scientific disciplines, including behavioral ecology, conservation genetics, landscape ecology, environmental education and human dimensions of wildlife. His vision is to help create a world in which urban ecosystems represent an important component of the worldwide conservation of biodiversity.</p>
'''
lehrer:
name: "Liza Lehrer"
image: 'http://placehold.it/100'
description: '''
<p>Liza’s interest in wildlife began as a kid, while digging through her backyard and looking for bugs and worms to scare her sister. In college, she expanded her education with summer internships including wildlife rehabilitation, collecting behavioral data on Mexican wolves and a semester abroad studying marine life in the Great Barrier Reef.</p>
<p>After earning her degree in zoology, Liza was fortunate to work as a research intern at Lincoln Park Zoo and later as animal records keeper. It was her work at the zoo, and life in Chicago, that lead to her fascination with urban wildlife. Coyotes and foxes were becoming regular residents of the city, but how do they move about the urban landscape? What types of adjustments do they make to survive? To examine some of these questions, Liza returned to graduate school to study how urbanization affects survival, movements and behavior of an urban-adapter species, the woodchuck.</p>
<p>As urban wildlife ecologist for the Urban Wildlife Institute, Liza manages and collects data for the institute’s field research projects, including the Urban Wildlife Biodiversity Monitoring project. She coordinates collaborations and leads a project in partnership with the University of Illinois on the effects of relocation on nuisance woodchucks, which expands upon her master’s research. Liza’s research interests include urban wildlife, landscape ecology, behavioral ecology, wildlife disease and managing human-wildlife conflict.</p>
<p>Prior to joining the Urban Wildlife Institute, Liza served as an avian field assistant on a project examining urban disease ecology of West Nile virus and as a guest engagement leader at Lincoln Park Zoo.</p>
'''
fidino:
name: 'Mason Fidino'
description: '''
<p>Mason first began conservation and ecology work in 2006. Since then he has aided in numerous studies, from collecting clams and fish in the Columbia River to coring trees and identifying birds on the mountains of Washington. Mason completed his undergraduate education at Western Washington University in 2009. After a year-long stay in Dublin, Ireland, he moved to Chicago and began working at the Urban Wildlife Institute as Coordinator of Wildlife Management.</p>
'''
development:
raden:
name: 'Steve Raden'
image: 'http://placehold.it/100'
description: '''
<p>Steve is a software developer at Adler Planetarium and Zooniverse. As a Chicagoan, he enjoys walking the city's parks and streets and occasionally spotting animals. </p>
'''
vansingel:
name: 'Heath Van Singel'
image: 'http://placehold.it/100'
description: '''
<p>Heath is the UX/UI Designer for projects at the Zooniverse, where he works to craft thoughtful and engaging user experiences. Apart from design Heath also enjoys illustration, a good sci-fi or fantasy novel, and trips back to Michigan.</p>
'''
weiksnar:
name: 'Alex Weiksnar'
image: 'images/about/team/michael.jpg'
description: '''
<p>Alex currently works as a front-end developer for the Zooniverse out of the Adler Planetarium. He spends his time building rich and engaging user interfaces for the web.
Alex previously attended University of Miami, where he studied psychology, biology and English.
</p>
'''
wang:
name: 'Jun Wang'
description: '''
<p>Jun Wang is a research scientist at the Syracuse University School of Information Studies. He is interested in designing enjoyable web applications. He is currently a principal investigator of a project sponsored by National Academies: "Drawing-based social learning". He is also an investigator of a citizen science project (citizensort) at Syracuse University. Fascinated by the recent breakthrough in deep learning, he wonders how much computer and human can teach each other. He has enjoyed working with the Zooniverse n using Caffe, a fast deep learning framework, to accomplish pre-processing on the images displayed to volunteers on Chicago Wildlife Watch.</p>
'''
whyte:
name: 'Dr. Laura Whyte'
title: 'Director of Citizen Science at Adler Planetarium'
image: 'http://placehold.it/100'
description: '''
<p>The citizen science department at the Adler Planetarium is home to a development team who design and build Zooniverse websites - the worlds largest and most successful collection of citizen science projects. This team, who bring expertise in technology, education, science outreach and research, reach beyond the internet into the local community through school visits, youth programs and hack days events. As former astronomer, high school teacher, museum educator, and web developer, Laura leads these initiatives and the opportunity they bring to engage a wider Chicago audience in actively doing science.</p>
'''
connect:
header: "Connect"
action: "Get Started"
social: """
Follow the Adler Planetarium [<a href='http://www.adlerplanetarium.org/blogs'>Blog</a> / <a href= 'https://twitter.com/adlerskywatch'>Twitter</a>] and Lincoln Park Zoo Urban Wildlife Institute [<a href='https://www.lpzoo.org/rss-feeds?'>Blog</a> / <a href='https://twitter.com/lpz_uwi'>Twitter</a>] to keep current with the latest findings!
"""
education:
header: "Education"
overview:
nav: "Overview"
header: "Can I use Chicago Wildlife Watch in the classroom?"
p: """
Absolutely! Chicago Wildlife Watch, just like all the Zooniverse projects, offers a unique opportunity to explore real scientific data while making a contribution to cutting-edge research. We would like to stress that as each image is marked by the volunteers, it really does not matter if your students don't mark all the features. That being said, the task itself is simple enough that we believe most people can take part and make a worthwhile contribution regardless of age.
"""
resources:
nav: "Resources"
header: "What resources are there to support use in the classroom?"
content: """
<p>Over the summer of 2014, teen interns at Adler Planetarium developed a floor activity to bring awareness to the fact that nature is everywhere and we live in nature. A Lesson plan for this activity can be found on <a href='http://www.zooteach.org'>ZooTeach</a></p>
<p>Videos are also a great tool to introduce students to Chicago Wildlife Watch. Here are a couple of our favorites:</p>
<ul>
<li><a href='https://www.youtube.com/watch?v=iRhdDs91aas'> TropicMind.com: Ecosystem and Food Chain (aimed for younger children)</a> </li>
<li><a href='https://www.youtube.com/watch?v=iFeRFmqFChQ'>Bill Nye: The Science Guy - Biodiversity</a></li>
</ul>
<p>We also recommend checking out the Urban Wildlife Institute <a href="http://www.lpzoo.org/conservation-science/science-centers/urban-wildlife-institute">webpage</a> for more information on the organization.
</p>
"""
partner_resources:
nav: "Partner Resouces"
header: "Partner resources"
content: """
<p>Please visit Lincoln Park Zoo's Educator's Resources <a href="http://www.lpzoo.org/education/educators-resources"> webpage</a> to access curriculum guides, zoo field trip and self-tour information, accessibility kits and links to several multi-media apps.
</p>
<p>The Adler Planetarium is dedicated to helping the public experience science and discover the universe through field trips, school partnerships, child and teen programming. See the Teach and Learn <a href="http://www.adlerplanetarium.org/educator-resources/">section</a> of the Adler's website for details.
</p>
"""
aside:
content: """
<h1>Connect with Education</h1>
<p>The Chicago Wildlife Watch blog, as well as the partner Facebook pages, are great places to keep up to date with the latest science results, but there is also a Zooniverse Education Blog as well as a <a href='https://www.twitter.com/ZooTeach'>@ZooTeach</a> Twitter feed. The Urban Wildlife Institute also has a Twitter account, <a href='https://www.twitter.com/LPZ_UWI'>@LPZ_UWI</a>, that you can follow for more information on their work.</p>
"""
press:
header: "Press"
intro: "Chicago Wildlife Watch Recruits Chicagoans to Help with Urban Wildlife Science Research from Home or Classroom"
section_1: """
The Adler Planetarium and Lincoln Park Zoo have launched <b>Chicago Wildlife Watch</b>, a new web-based citizen science initiative that provides an opportunity for students, teachers and members of the public to actively participate in Chicagoland wildlife research through photo identification technology. The platform is available at <a href="http://www.chicagowildlifewatch.org">chicagowildlifewatch.org</a>.
"""
section_2: """
<b>Chicago Wildlife Watch</b> is a collaboration between the Adler Planetarium’s Zooniverse team and Lincoln Park Zoo’s Urban Wildlife Institute that began in early 2014. Faced with a year’s worth of back logged research, the Urban Wildlife Institute enlisted the help of the Adler Planetarium’s Zooniverse development team to create a citizen science platform that would empower the people of Chicago to assist researchers in classifying important data essential in assessing local wildlife and their habitats.
"""
downloads:
header: "Chicago Wildlife Watch Media Downloads:"
pressReleasePdf: "Press Release PDF"
bRollFootage: "B-roll Footage"
imagesDownloads: "Images Downloads"
imageCaptionSheet: "Image Caption Sheet"
slider:
header: "Images"
captions: """
<div id="caption-1" class="nivo-html-caption">
<p>The Adler Planetarium and Lincoln Park Zoo have launched Chicago Wildlife Watch, a new web-based citizen science initiative that provides an opportunity for students, teachers and members of the public to actively participate in Chicagoland wildlife research through photo identification technology available at chicagowildlifewatch.org. This data will help re- searchers apply findings that will positively influence urban wildlife policy.</p>
<p>© Adler Planetarium</p>
</div>
<div id="caption-2" class="nivo-html-caption">
<p>The camera traps used for Chicago Wildlife Watch data collection are set up in urban areas throughout Chicago including this South Loop location.</p>
<p>© Urban Wildlife Institute/Lincoln Park Zoo</p>
</div>
<div id="caption-3" class="nivo-html-caption">
<p>Seth Magle, PhD, Director of the Urban Wildlife Institute secures a camera trap that is used to capture data for Chicago Wildlife Watch. Urban Wildlife Institute scientists set up camera traps four times a year.</p>
<p>© Urban Wildlife Institute/Lincoln Park Zoo</p>
</div>
<div id="caption-4" class="nivo-html-caption">
<p>A resting coyote is captured by a Urban Wildlife Institute camera trap southwest of Chicago. Coyotes are among the most common carnivores in the Chicagoland area.</p>
<p>© Urban Wildlife Institute/Lincoln Park Zoo</p>
</div>
<div id="caption-5" class="nivo-html-caption">
<p>This image shows a raccoon and opossum in the city of Chicago. Exploring the relationship between urban species is one goal of Chicago Wildlife Watch.</p>
<p>© Urban Wildlife Institute/Lincoln Park Zoo</p>
</div>
<div id="caption-6" class="nivo-html-caption">
<p>Chicago Wildlife Watch will explore wildlife that utilize public spaces such as these coyotes foraging in a park on the Northwest side of Chicago.</p>
<p>© Urban Wildlife Institute/Lincoln Park Zoo</p>
</div>
<div id="caption-7" class="nivo-html-caption">
<p>This red fox sits facing an Urban Wildlife Institute camera trap west of the city. Red foxes are becoming uncommon in the Chicago area, with some speculat- ing that coyotes may be outcompeting them in urban spaces. Chicago Wildlife Watch may shed light on why this is occurring.</p>
<p>© Urban Wildlife Institute/Lincoln Park Zoo</p>
</div>
<div id="caption-8" class="nivo-html-caption">
<p>A Zooniverse team member from the Adler Planetarium demonstrates Chicago Wildlife Watch to participants of the Lincoln Park Zoo Conservation Camp. The Zooniverse is the world’s leading - and largest - citizen science platform.</p>
<p>© Adler Planetarium</p>
</div>
<div id="caption-9" class="nivo-html-caption">
<p>Participants of the Lincoln Park Zoo Conservation Camp classify animals on Chicago Wildlife Watch. This easy to use online platform, allows everyone from middle-school aged children to adults to contribute to real scientific research.</p>
<p>© Adler Planetarium</p>
</div>
"""
contacts:
header: "Media Contacts:"
sharon: """
Sharon Dewar<br>
Lincoln Park Zoo<br>
312-742-2246<br>
SDewar@lpzoo.org
"""
molly: """
Molly O’Connell<br>
Adler Planetarium<br>
312-322-0524<br>
moconnell@adlerplanetarium.org
"""
| 43430 | module.exports =
navigation:
home: 'Home'
about: 'About'
classify: 'Classify'
profile: 'Profile'
discuss: 'Talk'
education: 'Education'
press: 'Press'
blog: 'Blog'
home:
heading: 'Chicago Wildlife Watch'
rightBannerHeader: "What is Chicago Wildlife Watch?"
leftBannerHeader: "
<h2>Welcome to</h2>
<h1>Chicago <br/> Wildlife Watch</h1>
"
imageCredit: "Image credit and © <NAME>"
content: '''
To find out which animals live in Chicago, we’ve collected more than 1 million photos of wildlife from the Loop to the burbs. To ID them, though, we need your help!
Chicago Wildlife Watch, developed by Lin<NAME> Zoo and the Adler Planetarium, lets everyone help us understand how animals—from coyotes to chipmunks—share this great city.
'''
action: 'Get Started'
currentStatus: '<span class="classification-count">0</span> classifications by <span class="user-count">0</span> volunteers'
preFooterText: "Chicago Wildlife Watch is a collaboration between Lincoln Park Zoo, the Adler Planetarium and the Zooniverse."
stats:
header: "CHICAGO WILDLIFE WATCH Statistics"
activeUsers: "Active Users"
crittersIdentified: "Classifications"
totalImages: "Images Total"
complete: "Complete"
filterPage:
header: "Choose Your Data"
name: "Education Mode"
filtered: "Curated"
unfiltered: "Uncurated"
question: "Would you like to view Curated or Uncurated data?"
notification: "These images have been taken by cameras in public spaces"
description: """
If you are using Chicago Wildlife Watch for educational purposes or with young children, you might want to use our 'Curated' dataset option. The images in this data set are much more likely to contain an animal but still require additional attention to confirm the animal type. For a younger audience, or for a situation where time is limited, this may provide a more engaging experience.
"""
siteIntro:
s1:
title: "Welcome!"
content: "Welcome to Chicago Wildlife Watch! In this project, we are asking you to identify animals found in camera trap photos from around the city. Your help allows us to continue our research into urban biodiversity, making the city a better home for both humans and animals."
s2:
title: "Identifying animals"
content: "You are presented with a photo on the left and a list of potential animals on the right. When you spot an animal within a photo, simply click the corresponding animal on the right. You will be asked to supply some followup info, such as the number of animals found in the image."
s3:
title: "Filtering by characteristics"
content: "Occasionally it is difficult to determine which animal is in the photo. Just above the list of animals is a variety of methods to filter the animal list. Selecting different options reduces the number of choices, making your job easier."
s4:
title: "Made a mistake?"
content: "If you need to delete any of your existing marks while viewing an image, simply find your animal in the list below the image and click the 'X' icon. Don’t worry if you’re unsure about your choices, though—even a guess is more helpful than nothing!"
s5:
title: "That's it!"
content: "That's it! You may catch up on project updates either on the blog or through speaking with other volunteers. If you need additional help using the interface, click Tutorial within the list of links below the Finish button."
classify:
deleteAnnotation: 'Delete'
notSignedIn: 'You\'re not signed in!'
favorite: 'Favorite'
unfavorite: 'Unfavorite'
nothingLabel: 'Nothing here'
nextSubjectButton: 'Finish'
share: 'Share'
tweet: 'Tweet'
pin: 'Pin it'
discuss: 'Discuss'
next: 'Next capture'
search: 'Search'
annotationsMessage: "See something? Animals you identify will appear here..."
helpLink: "Need some spotting tips? Check out these blog posts!"
nothingToShow: 'There\'s nothing to show with these filters.'
clearFilters: 'Clear filters'
curatedError: "We can't find any subjects right now in our curated dataset', Click the 'Next Capture' button to try again or <a href='#/filter'>view our uncurated dataset</a>"
oftenConfused: 'Often confused with:'
count: 'How many'
behavior: 'Behavior'
behaviors:
headUp: 'Head Up'
headDown: 'Head Down'
neither: 'Neither'
notVisible: 'Not Visible'
notApplicable: 'N/A'
babies: 'Young present'
rain: 'Raining'
cancel: 'Cancel'
identify: 'Identify'
tutorial:
small: "Site Intro"
button: "Tutorial"
continueButton: 'Continue'
welcomeHeader: 'Welcome to Chicago Wildlife Watch!'
welcome: '''
This short tutorial will walk you through your first identification. Let's get started!
'''
trapsHeader: 'Check out the Images'
traps: '''
All over Chicago, scientists have set up motion-sensitive camera traps.
The camera snaps a few shots anytime something moves in front of it.
'''
taskHeader: 'Identify the Animals'
task: '''
Your task is to identify all the different animals that appear in the photos.
The species that will appear are listed here.
It's a big list, and some species may be unfamiliar,
but there are a few ways to narrow that list down using the characteristics you see.
'''
chooseRodentHeader: 'Looks like...'
chooseRodent: '''
The animal in the foreground of this photo looks like a rodent of some kind.
Let's choose <strong>"Rodent"</strong> from the <strong>"Looks like"</strong> menu.
'''
chooseTanYellowHeader: 'Characteristic: Coat'
chooseTanYellow: '''
Let's narrow the list down a bit by choosing the <strong>"Tan Yellow"</strong> swatch from the <strong>"Coat"</strong> menu.
'''
chooseBushyHeader: 'Characteristic: Tail'
chooseBushy: '''
We've narrowed the list down enough to see thumbnail previews of the remaining animals.
Choose the <strong>"Bushy"</strong> icon from the <strong>"Tail"</strong> menu to narrow the list down further.
'''
chooseGraySquirrelHeader: 'Make a choice'
chooseGraySquirrel: '''
Great, that leaves us with just one option!
Let's choose <strong>"Gray Squirrel"</strong> and make sure it's a match.
'''
confirmWildebeestHeader: 'Looks Good!'
confirmWildebeest: '''
By comparing the animal to the photos here and reading the description below, we can confirm that this is indeed a gray squirrel.
You can flip through the photos to see examples of the animal from multiple angles using the bullets on the right.
'''
identifyWildebeestHeader: 'Count & Behavior'
identifyWildebeest: '''
Once you're confident that this is a gray squirrel,
choose <strong>"1"</strong> from the count menu and <strong>"Head Up"</strong> from the behavior menu.
Then click "Identify."
'''
finishHeader: 'Nice Job!'
finish: '''
Now you're ready to identify some images on your own.
In each image, do your best to identify all the animals you can,
even if you can't see enough to be completely sure.
If there aren't any animals in an image, check "Nothing here" and then "Finish."
Your observations will be combined with those of multiple volunteers,
so even if you're not sure on something, your contribution is still very useful!
Don't forget: after identifying an image you can always <strong>discuss</strong> it with professional and citizen scientists or share it with friends.
Click <strong>"Finish"</strong> now to move on.
'''
animals:
beaver:
label: 'Beaver'
description: '''
This animal is usually brown with large sharp front teeth, clawed front feet webbed back feet, a round body and a large flat tail. As the second largest rodent in the world, beavers are semi-aquatic and primarily nocturnal.
'''
bird:
label: 'Bird'
description: '''
All manner of birds will be captured in the pictures, from cardinals to seagulls. They will frequently be found either nesting in trees or scavenging for food on the ground.
'''
chipmunk:
label: 'Chipmunk'
description: '''
A small member of the squirrel family that uses its cheek pouch to carry various nuts, berries and seeds into its burrow or nest to store its food. They have smaller, less bushy tails than a typical squirrel and sport signature white-and-brown stripes around their eye and going down their back. Typically brown or tan in color.
'''
coyote:
label: 'Coyote'
description: '''
Commonly brown and tan in color, this member of the dog family is smaller than a wolf. They have occasionally been called prairie wolves or brush wolves due to their wolf-like appearance, but they differ from wolves with their pointed snouts, slender body and tall, pointy ears. In the fall and winter, they form packs for more effective hunting.
'''
deer:
label: 'Deer'
description: '''
A fairly big, tan animal that is in the same family as moose and reindeer. They have large ears and short fluffy tails. The males are called bucks while females are called does, and the young are called fawns. Some males may have antlers depending on the time of the year.
'''
domCat:
label: 'Cat, Domestic'
description: '''
A common household pet with a small build, a long tail and small pointed ears. This animal comes in a variety of color, patterns (spotted or stripes), and breeds.
'''
domDog:
label: 'Dog, Domestic'
description: '''
A common household pet related to wolves, foxes and jackals. This animal comes in a variety of colors, sizes, patterns and breeds.
'''
flyingSquirrel:
label: 'Squirrel, Flying'
description: '''
A member of the squirrel family, this animal has large, dark eyes, loose skin between the front and back legs, clawed feet and a long, bushy tail with dark fur on top and light below. It travels from tree to tree by launching itself and spreading its limbs so it can glide while using its legs to steer and its tail to brake when it reaches its destination.
'''
foxSquirrel:
label: 'Squirrel, Fox'
description: '''
The largest species of tree squirrel in North America, they look like a larger typical squirrel with an orange tone to their fur. They can be around 2 feet in length and weight 1 - 2 lbs. It spends most of its time foraging for food and roaming around fields.
'''
grayFox:
label: 'Fox, Gray'
description: '''
A small to medium-sized animal with a gray coat on its back and head with light fur on its chest and belly. They have a signature black-tipped, bushy tail and a band of black fur from the inner corner of their eyes around the bottom of their snout. They are tree climbers, typically sleep during the day at very rocky locations and are active during the night.
'''
graySquirrel:
label: 'Squirrel, Gray'
description: '''
Small squirrels that are gray-brown all over their bodies except the white patch along their belly. This animal's diet consists of acorns, hickory nuts, maple and walnuts.
'''
horse:
label: 'Horse'
description: '''
A large, muscular animal with a mane of hair along the back of the head and neck. These animals have hooves and a long tail of hair.
'''
human:
label: 'Human'
description: '''
Identifying a human within a photo flags this image. We generally remove images of humans very quickly from the dataset.
'''
livestock:
label: 'Livestock'
description: '''
N/A. Identifying the frequency of livestock helps us understand the impact of human activity on the animal population in this urban habitat.
'''
mink:
label: 'Mink'
description: '''
Related to otters, weasels and ferrets, minks have pointed snouts with dark eyes. They also have clawed feet with webbing and bodies covered in thick brown fur that sheds water quickly. These animals live in semi-aquatic habitats.
'''
mouse:
label: 'Mouse'
description: '''
A very small animal with a long snout, big round ears and a long hairless tail. This animal can be found in and around grasslands and homes.
'''
mower:
label: 'Mower'
description: '''
N/A. Identifying the frequency of mowers helps us understand the impact of human activity on the animal population in this urban habitat.
'''
muskrat:
label: 'Muskrat'
description: '''
This animal normally has brown fur and a black tail with small dark eyes. The fur-less, scaly tail is half of its total length. When it walks, the tail creates a trail. Their front paws are clawed while the rear feet are semi-webbed and clawed.
'''
opossum:
label: 'Opossum'
description: '''
Adept tree climbers with their clawed feet and opposable big toe on rear paw. This animal is known for playing dead and has a white face with a pink nose, black eyes, black ears, long tail and long, gray fur on its body.
'''
rabbit:
label: 'Rabbit'
description: '''
Rabbits we see in urban settings have large, dark eyes, long ears pointed upwards and brown fur with a short, fluffy, white tail.
'''
raccoon:
label: 'Raccoon'
description: '''
This brown-gray furry animal looks like it is wearing a bandit mask with the black patches around its eyes on its white face. Another notable features are its finger-like clawed toes and its black-ringed tail with long fur. Raccoons are nocturnal and often seen foraging for food in trash bins.
'''
rat:
label: 'Rat'
description: '''
A large mouse-like critter with a pointy nose, round ears and a long, hairless, pinkish tail. Many people think they only roam the subway and sewers, but it is not uncommon to see then running across the street above ground.
'''
redFox:
label: 'Fox, Red'
description: '''
An animal with orange brownish fur along its head and back and white fur on its belly and typically at the tip of its bushy tail. Its tail helps it balance just like a cat’s. Some have black fur on the back of their ears and legs.
'''
skunk:
label: 'Skunk'
description: '''
An animal well known for its stinky spray towards predators and black coat with white stripe patterns. It has a single thin, white stripe down the middle of its face and two thicker white stripes originating at the top of its head running down either side of the back into its thick, bushy tail.
'''
woodChuck:
label: 'Woodchuck'
description: '''
This animal is also known as a groundhog. It has a brown furry coat, clawed feet, small eyes and ears, and a short, flat tail.
'''
melanisticGraySquirrel:
label: 'Squirrel, Melanistic Gray'
description: '''
Melanism is a genetic trait that produces extra melanin in the skin and fur, making an organism appear jet black if it has two sets of this recessive gene or brown/black if it only has one. Gray squirrels are known to carry this unusual genetic trait. This trait may be beneficial to gray squirrels living at northern latitudes as they would lose less heat during the cold winter months. The photo in this ID is of a brown/black melanistic gray squirrel.
'''
characteristics:
like: 'Looks like...'
coat: 'Coat'
tail: 'Tail'
build: 'Build'
characteristicValues:
likeCatDog: 'Cat Dog'
likeRodent: 'Rodent'
likeManMade: 'Vehicles'
likeOther: 'Other'
coatTanYellow: 'Tan Yellow'
coatRedBrown: 'Red Brown'
coatBrownBlack: 'Brown Black'
coatGrayBlack: 'Gray Black'
coatMottled: 'Mottled'
coatSolid: 'Solid'
coatOrTailStriped: 'Or Tail Striped'
tailBushy: 'Bushy'
tailSmooth: 'Smooth'
tailLong: 'Long'
buildStocky: 'Stocky'
buildLanky: 'Lanky'
buildSmall: 'Small'
buildLowSlung: 'Low Slung'
profile:
header: "Your Profile"
favorites: 'Favorites'
recents: 'Recents'
noFavorites: 'You have no favorites!'
noRecents: 'You have no recent identifications!'
showing: 'Showing'
loadMore: 'Load more'
about:
press:
nav:
"Press"
science:
nav: "Science"
header: "Science"
p: """
<p>
Cities can be hostile places for wildlife, with threats coming from habitat destruction, roads and traffic, humans, pets and large numbers of invasive species. However, with proper management, urban areas can house a number of important wildlife species, including carnivores and small mammals.
</p>
<p>
To assess the biodiversity of the greater Chicagoland area, Lincoln Park Zoo’s Urban Wildlife Institute has established monitoring stations within city parks, forest preserves, golf courses and cemeteries in parts of Cook, Lake, DuPage and Will Counties including downtown Chicago. Motion-triggered cameras are deployed four times per year at more than 100 sites to determine which species are present and to assess spatial and long-term patterns in wildlife communities.
</p>
<p>
Knowing where Chicago’s urban wildlife is located will help us to better conserve it. This knowledge will pave the way for future studies on the behavior and ecology of specific urban species, helping stakeholders to better manage wildlife conflict.
</p>
<p>
Keep an eye out for the black pouches that are often attached to trees in most of the photos. They contain a scented lure that increases the probability of photographing the wildlife community at a site.
</p>
<img src="./images/animals/fox-squirrel-1.jpg">
"""
questions: """
<h1>Our Scientific Questions</h1>
<h2>Where do they go?</h2>
<p>We don’t know as much as we’d like about species in urban systems. Even basic facts like what types of habitat attract which species are often unknown in areas like cities.
Finding out where certain species are most likely to occur allows us to target conservation and management efforts to ensure we can coexist with our wildlife neighbors.</p>
<h2>How are they doing?</h2>
<p>While we can’t directly measure populations with the data from our cameras, we can get a sense of which species are most common and which may be in decline.
This can help us make recommendations about how to improve conditions for the species that are in trouble.</p>
<h2>How do they compete?</h2>
<p>We know almost nothing about how species in urban areas might compete with one another, engage in predator-prey dynamics or avoid each other.
Preliminary results indicate that the normal community interactions we observe in natural systems don’t apply to urban areas, where entirely new dynamics seem to be in place.
By evaluating our camera images, we can begin to assemble the first complete picture of an urban ecosystem, including how all the species interact.</p>
<h2>How do they interact with us?</h2>
<p>By also collecting data on humans, and on pets like cats and dogs, we can get a sense of how animals in urban settings react to the people who make the city their home.
Some animals may be attracted to sites that are often visited by humans, while others may be looking for more secluded places. Humans are a critical part of the system,
and our camera data allows us to understand our impact, as well as the importance of food and habitat.</p>
"""
uwi:
nav: "Urban Wildlife Institute"
header: "Urban Wildlife Institute"
content: """
<p>Utilizing Lincoln Park Zoo’s diverse scientific specialties, the Urban Wildlife Institute studies the interaction between urban development and the natural ecosystem to develop scientific standards for minimizing conflict between these overlapping areas. Landscape ecology, population biology, epidemiology, endocrinology, veterinary medicine and other core disciplines contribute to an increased understanding of ecosystem health in an urban setting. The Urban Wildlife Institute aims to use Chicago as a model for urban areas struggling to deal with wildlife relocation, rehabilitation, disease and conflicts.</p>
<p>One issue receiving special emphasis is the transmission of disease from animals to humans—another byproduct of urban sprawl. By studying how people and animals interact in an urban setting, the Urban Wildlife Institute can help scientists to better understand—and curb—zoonotic disease threats such as West Nile virus, rabies and avian influenza.</p>
<p>Supported by a $1.5 million grant from the Davee Foundation, the Urban Wildlife Institute is forming partnerships with local nature and conservation organizations and conducting pilot studies into ecosystem health and human-wildlife interaction. By developing standards for managing urban wildlife issues, the institute is creating a conflict-management model that can be followed worldwide.</p>
<p>To learn more, you can visit <a href="http://www.lpzoo.org/conservation-science/science-centers/urban-wildlife-institute">their website</a>.</p>
"""
zooniverse:
nav: "Zooniverse"
header: "Zooniverse"
content: """
<p>The amount of data collected by modern research equipment is often too large for any one person or small team of people to effectively analyze. Over the past several decades, scientists have explored partnering with the public to help do real science when human eyes and thinking are still better at analysis than computers.</p>
<p>Known online as the Zooniverse, the Adler's Citizen Science department designs and develops web applications using data sets that would normally take a science team over 100 years to analyze and, with the help of a worldwide network of volunteers, complete the analysis with a high level of accuracy in weeks or months.</p>
<p>To participate in other citizen science efforts, visit <a href="https://www.zooniverse.org">Zooniverse.org</a>.</p>
"""
organizations:
nav: "Organizations"
header: "Organizations"
adler:
header: "Adler Planetarium"
p: """
<img src="./images/logos/adler-black.png" class="inline">
<a href="http://www.adlerplanetarium.org/">The Adler Planetarium</a> - America's First Planetarium - was founded in 1930 by Chicago business leader <NAME>.
The Adler is a recognized leader in science education, with a focus on inspiring young people to pursue careers in science, technology, engineering and math.
Throughout 80 years, the Adler has inspired the next generation of explorers by sharing the personal stories of space exploration and America’s space heroes.
"""
lincolnParkZoo:
header: "Lincoln Park Zoo"
p: """
<img src="./images/logos/lpz-black.png" class="inline">
<a href="http://www.lpzoo.org/">Lincoln Park Zoo</a> is a world of wildlife in the shadow of skyscrapers. Located within a verdant park just minutes north of Chicago, the zoo has been a natural, free oasis for generations of animal lovers, who visit the zoo to hear a lion’s roar echo off nearby apartment buildings, see gorillas climb trees as the Willis Tower looms in the distance or forget where they are as they immerse themselves in tropical rainforests, dry-thorn forests or spacious savannas.<br><br>
Lincoln Park Zoo is dedicated to connecting people with nature by providing a free, family-oriented wildlife experience in the heart of Chicago and by advancing the highest quality of animal care, education, science and conservation.
"""
team:
nav: "Team"
header: "Team"
science:
magle:
name: 'Dr. <NAME>'
title: 'Director, Urban Wildlife Institute at Lincoln Park Zoo'
image: 'http://placehold.it/100'
description: '''
<p><NAME> first became interested in conservation and ecology as a college student in 1997 while observing black-tailed prairie dogs living in sidewalk median strips near his home in Boulder, Colorado. Daily interactions with these resilient animals made him wonder what adaptations enabled these small mammals to persist in highly urban habitat and which factors contributed to their distribution and abundance. Eventually he completed an honors thesis on the behavior of this urban-adapted keystone species; he ultimately expanded on that research for both a master’s degree and a doctorate.</p>
<p>However, Seth’s interests go far beyond prairie dogs to encompass all wildlife species impacted by urbanization and human development. He has also engaged in research on movement behavior of white-tailed deer in a rural landscape characterized by high prevalence of disease outbreaks, assessments of the diversity of bird communities residing in agricultural habitat and the conservation of Canada lynx reintroduced to the southern edge of their historical range, where they are threatened by roads and traffic.</p>
<p>Seth strongly believes that if rare and imperiled species are to be conserved in our modern world, we must understand and mitigate all potential impacts of urban areas on wildlife. To that end, he engages in studies of urban wildlife that span a broad range of scientific disciplines, including behavioral ecology, conservation genetics, landscape ecology, environmental education and human dimensions of wildlife. His vision is to help create a world in which urban ecosystems represent an important component of the worldwide conservation of biodiversity.</p>
'''
lehrer:
name: "<NAME>"
image: 'http://placehold.it/100'
description: '''
<p><NAME>’s interest in wildlife began as a kid, while digging through her backyard and looking for bugs and worms to scare her sister. In college, she expanded her education with summer internships including wildlife rehabilitation, collecting behavioral data on Mexican wolves and a semester abroad studying marine life in the Great Barrier Reef.</p>
<p>After earning her degree in zoology, <NAME> was fortunate to work as a research intern at Lincoln Park Zoo and later as animal records keeper. It was her work at the zoo, and life in Chicago, that lead to her fascination with urban wildlife. Coyotes and foxes were becoming regular residents of the city, but how do they move about the urban landscape? What types of adjustments do they make to survive? To examine some of these questions, Liza returned to graduate school to study how urbanization affects survival, movements and behavior of an urban-adapter species, the woodchuck.</p>
<p>As urban wildlife ecologist for the Urban Wildlife Institute, Liza manages and collects data for the institute’s field research projects, including the Urban Wildlife Biodiversity Monitoring project. She coordinates collaborations and leads a project in partnership with the University of Illinois on the effects of relocation on nuisance woodchucks, which expands upon her master’s research. Liza’s research interests include urban wildlife, landscape ecology, behavioral ecology, wildlife disease and managing human-wildlife conflict.</p>
<p>Prior to joining the Urban Wildlife Institute, Liza served as an avian field assistant on a project examining urban disease ecology of West Nile virus and as a guest engagement leader at Lincoln Park Zoo.</p>
'''
fidino:
name: '<NAME>'
description: '''
<p>Mason first began conservation and ecology work in 2006. Since then he has aided in numerous studies, from collecting clams and fish in the Columbia River to coring trees and identifying birds on the mountains of Washington. Mason completed his undergraduate education at Western Washington University in 2009. After a year-long stay in Dublin, Ireland, he moved to Chicago and began working at the Urban Wildlife Institute as Coordinator of Wildlife Management.</p>
'''
development:
raden:
name: '<NAME>'
image: 'http://placehold.it/100'
description: '''
<p><NAME> is a software developer at Adler Planetarium and Zooniverse. As a Chicagoan, he enjoys walking the city's parks and streets and occasionally spotting animals. </p>
'''
vansingel:
name: '<NAME>'
image: 'http://placehold.it/100'
description: '''
<p>Heath is the UX/UI Designer for projects at the Zooniverse, where he works to craft thoughtful and engaging user experiences. Apart from design Heath also enjoys illustration, a good sci-fi or fantasy novel, and trips back to Michigan.</p>
'''
weiksnar:
name: '<NAME>'
image: 'images/about/team/michael.jpg'
description: '''
<p><NAME> currently works as a front-end developer for the Zooniverse out of the Adler Planetarium. He spends his time building rich and engaging user interfaces for the web.
<NAME> previously attended University of Miami, where he studied psychology, biology and English.
</p>
'''
wang:
name: '<NAME>'
description: '''
<p><NAME> is a research scientist at the Syracuse University School of Information Studies. He is interested in designing enjoyable web applications. He is currently a principal investigator of a project sponsored by National Academies: "Drawing-based social learning". He is also an investigator of a citizen science project (citizensort) at Syracuse University. Fascinated by the recent breakthrough in deep learning, he wonders how much computer and human can teach each other. He has enjoyed working with the Zooniverse n using Caffe, a fast deep learning framework, to accomplish pre-processing on the images displayed to volunteers on Chicago Wildlife Watch.</p>
'''
whyte:
name: 'Dr. <NAME>'
title: 'Director of Citizen Science at Adler Planetarium'
image: 'http://placehold.it/100'
description: '''
<p>The citizen science department at the Adler Planetarium is home to a development team who design and build Zooniverse websites - the worlds largest and most successful collection of citizen science projects. This team, who bring expertise in technology, education, science outreach and research, reach beyond the internet into the local community through school visits, youth programs and hack days events. As former astronomer, high school teacher, museum educator, and web developer, <NAME> leads these initiatives and the opportunity they bring to engage a wider Chicago audience in actively doing science.</p>
'''
connect:
header: "Connect"
action: "Get Started"
social: """
Follow the Adler Planetarium [<a href='http://www.adlerplanetarium.org/blogs'>Blog</a> / <a href= 'https://twitter.com/adlerskywatch'>Twitter</a>] and <NAME> Zoo Urban Wildlife Institute [<a href='https://www.lpzoo.org/rss-feeds?'>Blog</a> / <a href='https://twitter.com/lpz_uwi'>Twitter</a>] to keep current with the latest findings!
"""
education:
header: "Education"
overview:
nav: "Overview"
header: "Can I use Chicago Wildlife Watch in the classroom?"
p: """
Absolutely! Chicago Wildlife Watch, just like all the Zooniverse projects, offers a unique opportunity to explore real scientific data while making a contribution to cutting-edge research. We would like to stress that as each image is marked by the volunteers, it really does not matter if your students don't mark all the features. That being said, the task itself is simple enough that we believe most people can take part and make a worthwhile contribution regardless of age.
"""
resources:
nav: "Resources"
header: "What resources are there to support use in the classroom?"
content: """
<p>Over the summer of 2014, teen interns at Adler Planetarium developed a floor activity to bring awareness to the fact that nature is everywhere and we live in nature. A Lesson plan for this activity can be found on <a href='http://www.zooteach.org'>ZooTeach</a></p>
<p>Videos are also a great tool to introduce students to Chicago Wildlife Watch. Here are a couple of our favorites:</p>
<ul>
<li><a href='https://www.youtube.com/watch?v=iRhdDs91aas'> TropicMind.com: Ecosystem and Food Chain (aimed for younger children)</a> </li>
<li><a href='https://www.youtube.com/watch?v=iFeRFmqFChQ'><NAME>: The Science Guy - Biodiversity</a></li>
</ul>
<p>We also recommend checking out the Urban Wildlife Institute <a href="http://www.lpzoo.org/conservation-science/science-centers/urban-wildlife-institute">webpage</a> for more information on the organization.
</p>
"""
partner_resources:
nav: "Partner Resouces"
header: "Partner resources"
content: """
<p>Please visit <NAME> Zoo's Educator's Resources <a href="http://www.lpzoo.org/education/educators-resources"> webpage</a> to access curriculum guides, zoo field trip and self-tour information, accessibility kits and links to several multi-media apps.
</p>
<p>The Adler Planetarium is dedicated to helping the public experience science and discover the universe through field trips, school partnerships, child and teen programming. See the Teach and Learn <a href="http://www.adlerplanetarium.org/educator-resources/">section</a> of the Adler's website for details.
</p>
"""
aside:
content: """
<h1>Connect with Education</h1>
<p>The Chicago Wildlife Watch blog, as well as the partner Facebook pages, are great places to keep up to date with the latest science results, but there is also a Zooniverse Education Blog as well as a <a href='https://www.twitter.com/ZooTeach'>@ZooTeach</a> Twitter feed. The Urban Wildlife Institute also has a Twitter account, <a href='https://www.twitter.com/LPZ_UWI'>@LPZ_UWI</a>, that you can follow for more information on their work.</p>
"""
press:
header: "Press"
intro: "Chicago Wildlife Watch Recruits Chicagoans to Help with Urban Wildlife Science Research from Home or Classroom"
section_1: """
The Adler Planetarium and Lincoln Park Zoo have launched <b>Chicago Wildlife Watch</b>, a new web-based citizen science initiative that provides an opportunity for students, teachers and members of the public to actively participate in Chicagoland wildlife research through photo identification technology. The platform is available at <a href="http://www.chicagowildlifewatch.org">chicagowildlifewatch.org</a>.
"""
section_2: """
<b>Chicago Wildlife Watch</b> is a collaboration between the Adler Planetarium’s Zooniverse team and Lincoln Park Zoo’s Urban Wildlife Institute that began in early 2014. Faced with a year’s worth of back logged research, the Urban Wildlife Institute enlisted the help of the Adler Planetarium’s Zooniverse development team to create a citizen science platform that would empower the people of Chicago to assist researchers in classifying important data essential in assessing local wildlife and their habitats.
"""
downloads:
header: "Chicago Wildlife Watch Media Downloads:"
pressReleasePdf: "Press Release PDF"
bRollFootage: "B-roll Footage"
imagesDownloads: "Images Downloads"
imageCaptionSheet: "Image Caption Sheet"
slider:
header: "Images"
captions: """
<div id="caption-1" class="nivo-html-caption">
<p>The Adler Planetarium and Lincoln Park Zoo have launched Chicago Wildlife Watch, a new web-based citizen science initiative that provides an opportunity for students, teachers and members of the public to actively participate in Chicagoland wildlife research through photo identification technology available at chicagowildlifewatch.org. This data will help re- searchers apply findings that will positively influence urban wildlife policy.</p>
<p>© Adler Planetarium</p>
</div>
<div id="caption-2" class="nivo-html-caption">
<p>The camera traps used for Chicago Wildlife Watch data collection are set up in urban areas throughout Chicago including this South Loop location.</p>
<p>© Urban Wildlife Institute/Lincoln Park Zoo</p>
</div>
<div id="caption-3" class="nivo-html-caption">
<p><NAME>, PhD, Director of the Urban Wildlife Institute secures a camera trap that is used to capture data for Chicago Wildlife Watch. Urban Wildlife Institute scientists set up camera traps four times a year.</p>
<p>© Urban Wildlife Institute/Lincoln Park Zoo</p>
</div>
<div id="caption-4" class="nivo-html-caption">
<p>A resting coyote is captured by a Urban Wildlife Institute camera trap southwest of Chicago. Coyotes are among the most common carnivores in the Chicagoland area.</p>
<p>© Urban Wildlife Institute/Lincoln Park Zoo</p>
</div>
<div id="caption-5" class="nivo-html-caption">
<p>This image shows a raccoon and opossum in the city of Chicago. Exploring the relationship between urban species is one goal of Chicago Wildlife Watch.</p>
<p>© Urban Wildlife Institute/Lincoln Park Zoo</p>
</div>
<div id="caption-6" class="nivo-html-caption">
<p>Chicago Wildlife Watch will explore wildlife that utilize public spaces such as these coyotes foraging in a park on the Northwest side of Chicago.</p>
<p>© Urban Wildlife Institute/Lincoln Park Zoo</p>
</div>
<div id="caption-7" class="nivo-html-caption">
<p>This red fox sits facing an Urban Wildlife Institute camera trap west of the city. Red foxes are becoming uncommon in the Chicago area, with some speculat- ing that coyotes may be outcompeting them in urban spaces. Chicago Wildlife Watch may shed light on why this is occurring.</p>
<p>© Urban Wildlife Institute/Lincoln Park Zoo</p>
</div>
<div id="caption-8" class="nivo-html-caption">
<p>A Zooniverse team member from the Adler Planetarium demonstrates Chicago Wildlife Watch to participants of the Lincoln Park Zoo Conservation Camp. The Zooniverse is the world’s leading - and largest - citizen science platform.</p>
<p>© Adler Planetarium</p>
</div>
<div id="caption-9" class="nivo-html-caption">
<p>Participants of the Lincoln Park Zoo Conservation Camp classify animals on Chicago Wildlife Watch. This easy to use online platform, allows everyone from middle-school aged children to adults to contribute to real scientific research.</p>
<p>© Adler Planetarium</p>
</div>
"""
contacts:
header: "Media Contacts:"
sharon: """
<NAME><br>
Lincoln Park Zoo<br>
312-742-2246<br>
<EMAIL>
"""
molly: """
<NAME><br>
Adler Planetarium<br>
312-322-0524<br>
<EMAIL>
"""
| true | module.exports =
navigation:
home: 'Home'
about: 'About'
classify: 'Classify'
profile: 'Profile'
discuss: 'Talk'
education: 'Education'
press: 'Press'
blog: 'Blog'
home:
heading: 'Chicago Wildlife Watch'
rightBannerHeader: "What is Chicago Wildlife Watch?"
leftBannerHeader: "
<h2>Welcome to</h2>
<h1>Chicago <br/> Wildlife Watch</h1>
"
imageCredit: "Image credit and © PI:NAME:<NAME>END_PI"
content: '''
To find out which animals live in Chicago, we’ve collected more than 1 million photos of wildlife from the Loop to the burbs. To ID them, though, we need your help!
Chicago Wildlife Watch, developed by LinPI:NAME:<NAME>END_PI Zoo and the Adler Planetarium, lets everyone help us understand how animals—from coyotes to chipmunks—share this great city.
'''
action: 'Get Started'
currentStatus: '<span class="classification-count">0</span> classifications by <span class="user-count">0</span> volunteers'
preFooterText: "Chicago Wildlife Watch is a collaboration between Lincoln Park Zoo, the Adler Planetarium and the Zooniverse."
stats:
header: "CHICAGO WILDLIFE WATCH Statistics"
activeUsers: "Active Users"
crittersIdentified: "Classifications"
totalImages: "Images Total"
complete: "Complete"
filterPage:
header: "Choose Your Data"
name: "Education Mode"
filtered: "Curated"
unfiltered: "Uncurated"
question: "Would you like to view Curated or Uncurated data?"
notification: "These images have been taken by cameras in public spaces"
description: """
If you are using Chicago Wildlife Watch for educational purposes or with young children, you might want to use our 'Curated' dataset option. The images in this data set are much more likely to contain an animal but still require additional attention to confirm the animal type. For a younger audience, or for a situation where time is limited, this may provide a more engaging experience.
"""
siteIntro:
s1:
title: "Welcome!"
content: "Welcome to Chicago Wildlife Watch! In this project, we are asking you to identify animals found in camera trap photos from around the city. Your help allows us to continue our research into urban biodiversity, making the city a better home for both humans and animals."
s2:
title: "Identifying animals"
content: "You are presented with a photo on the left and a list of potential animals on the right. When you spot an animal within a photo, simply click the corresponding animal on the right. You will be asked to supply some followup info, such as the number of animals found in the image."
s3:
title: "Filtering by characteristics"
content: "Occasionally it is difficult to determine which animal is in the photo. Just above the list of animals is a variety of methods to filter the animal list. Selecting different options reduces the number of choices, making your job easier."
s4:
title: "Made a mistake?"
content: "If you need to delete any of your existing marks while viewing an image, simply find your animal in the list below the image and click the 'X' icon. Don’t worry if you’re unsure about your choices, though—even a guess is more helpful than nothing!"
s5:
title: "That's it!"
content: "That's it! You may catch up on project updates either on the blog or through speaking with other volunteers. If you need additional help using the interface, click Tutorial within the list of links below the Finish button."
classify:
deleteAnnotation: 'Delete'
notSignedIn: 'You\'re not signed in!'
favorite: 'Favorite'
unfavorite: 'Unfavorite'
nothingLabel: 'Nothing here'
nextSubjectButton: 'Finish'
share: 'Share'
tweet: 'Tweet'
pin: 'Pin it'
discuss: 'Discuss'
next: 'Next capture'
search: 'Search'
annotationsMessage: "See something? Animals you identify will appear here..."
helpLink: "Need some spotting tips? Check out these blog posts!"
nothingToShow: 'There\'s nothing to show with these filters.'
clearFilters: 'Clear filters'
curatedError: "We can't find any subjects right now in our curated dataset', Click the 'Next Capture' button to try again or <a href='#/filter'>view our uncurated dataset</a>"
oftenConfused: 'Often confused with:'
count: 'How many'
behavior: 'Behavior'
behaviors:
headUp: 'Head Up'
headDown: 'Head Down'
neither: 'Neither'
notVisible: 'Not Visible'
notApplicable: 'N/A'
babies: 'Young present'
rain: 'Raining'
cancel: 'Cancel'
identify: 'Identify'
tutorial:
small: "Site Intro"
button: "Tutorial"
continueButton: 'Continue'
welcomeHeader: 'Welcome to Chicago Wildlife Watch!'
welcome: '''
This short tutorial will walk you through your first identification. Let's get started!
'''
trapsHeader: 'Check out the Images'
traps: '''
All over Chicago, scientists have set up motion-sensitive camera traps.
The camera snaps a few shots anytime something moves in front of it.
'''
taskHeader: 'Identify the Animals'
task: '''
Your task is to identify all the different animals that appear in the photos.
The species that will appear are listed here.
It's a big list, and some species may be unfamiliar,
but there are a few ways to narrow that list down using the characteristics you see.
'''
chooseRodentHeader: 'Looks like...'
chooseRodent: '''
The animal in the foreground of this photo looks like a rodent of some kind.
Let's choose <strong>"Rodent"</strong> from the <strong>"Looks like"</strong> menu.
'''
chooseTanYellowHeader: 'Characteristic: Coat'
chooseTanYellow: '''
Let's narrow the list down a bit by choosing the <strong>"Tan Yellow"</strong> swatch from the <strong>"Coat"</strong> menu.
'''
chooseBushyHeader: 'Characteristic: Tail'
chooseBushy: '''
We've narrowed the list down enough to see thumbnail previews of the remaining animals.
Choose the <strong>"Bushy"</strong> icon from the <strong>"Tail"</strong> menu to narrow the list down further.
'''
chooseGraySquirrelHeader: 'Make a choice'
chooseGraySquirrel: '''
Great, that leaves us with just one option!
Let's choose <strong>"Gray Squirrel"</strong> and make sure it's a match.
'''
confirmWildebeestHeader: 'Looks Good!'
confirmWildebeest: '''
By comparing the animal to the photos here and reading the description below, we can confirm that this is indeed a gray squirrel.
You can flip through the photos to see examples of the animal from multiple angles using the bullets on the right.
'''
identifyWildebeestHeader: 'Count & Behavior'
identifyWildebeest: '''
Once you're confident that this is a gray squirrel,
choose <strong>"1"</strong> from the count menu and <strong>"Head Up"</strong> from the behavior menu.
Then click "Identify."
'''
finishHeader: 'Nice Job!'
finish: '''
Now you're ready to identify some images on your own.
In each image, do your best to identify all the animals you can,
even if you can't see enough to be completely sure.
If there aren't any animals in an image, check "Nothing here" and then "Finish."
Your observations will be combined with those of multiple volunteers,
so even if you're not sure on something, your contribution is still very useful!
Don't forget: after identifying an image you can always <strong>discuss</strong> it with professional and citizen scientists or share it with friends.
Click <strong>"Finish"</strong> now to move on.
'''
animals:
beaver:
label: 'Beaver'
description: '''
This animal is usually brown with large sharp front teeth, clawed front feet webbed back feet, a round body and a large flat tail. As the second largest rodent in the world, beavers are semi-aquatic and primarily nocturnal.
'''
bird:
label: 'Bird'
description: '''
All manner of birds will be captured in the pictures, from cardinals to seagulls. They will frequently be found either nesting in trees or scavenging for food on the ground.
'''
chipmunk:
label: 'Chipmunk'
description: '''
A small member of the squirrel family that uses its cheek pouch to carry various nuts, berries and seeds into its burrow or nest to store its food. They have smaller, less bushy tails than a typical squirrel and sport signature white-and-brown stripes around their eye and going down their back. Typically brown or tan in color.
'''
coyote:
label: 'Coyote'
description: '''
Commonly brown and tan in color, this member of the dog family is smaller than a wolf. They have occasionally been called prairie wolves or brush wolves due to their wolf-like appearance, but they differ from wolves with their pointed snouts, slender body and tall, pointy ears. In the fall and winter, they form packs for more effective hunting.
'''
deer:
label: 'Deer'
description: '''
A fairly big, tan animal that is in the same family as moose and reindeer. They have large ears and short fluffy tails. The males are called bucks while females are called does, and the young are called fawns. Some males may have antlers depending on the time of the year.
'''
domCat:
label: 'Cat, Domestic'
description: '''
A common household pet with a small build, a long tail and small pointed ears. This animal comes in a variety of color, patterns (spotted or stripes), and breeds.
'''
domDog:
label: 'Dog, Domestic'
description: '''
A common household pet related to wolves, foxes and jackals. This animal comes in a variety of colors, sizes, patterns and breeds.
'''
flyingSquirrel:
label: 'Squirrel, Flying'
description: '''
A member of the squirrel family, this animal has large, dark eyes, loose skin between the front and back legs, clawed feet and a long, bushy tail with dark fur on top and light below. It travels from tree to tree by launching itself and spreading its limbs so it can glide while using its legs to steer and its tail to brake when it reaches its destination.
'''
foxSquirrel:
label: 'Squirrel, Fox'
description: '''
The largest species of tree squirrel in North America, they look like a larger typical squirrel with an orange tone to their fur. They can be around 2 feet in length and weight 1 - 2 lbs. It spends most of its time foraging for food and roaming around fields.
'''
grayFox:
label: 'Fox, Gray'
description: '''
A small to medium-sized animal with a gray coat on its back and head with light fur on its chest and belly. They have a signature black-tipped, bushy tail and a band of black fur from the inner corner of their eyes around the bottom of their snout. They are tree climbers, typically sleep during the day at very rocky locations and are active during the night.
'''
graySquirrel:
label: 'Squirrel, Gray'
description: '''
Small squirrels that are gray-brown all over their bodies except the white patch along their belly. This animal's diet consists of acorns, hickory nuts, maple and walnuts.
'''
horse:
label: 'Horse'
description: '''
A large, muscular animal with a mane of hair along the back of the head and neck. These animals have hooves and a long tail of hair.
'''
human:
label: 'Human'
description: '''
Identifying a human within a photo flags this image. We generally remove images of humans very quickly from the dataset.
'''
livestock:
label: 'Livestock'
description: '''
N/A. Identifying the frequency of livestock helps us understand the impact of human activity on the animal population in this urban habitat.
'''
mink:
label: 'Mink'
description: '''
Related to otters, weasels and ferrets, minks have pointed snouts with dark eyes. They also have clawed feet with webbing and bodies covered in thick brown fur that sheds water quickly. These animals live in semi-aquatic habitats.
'''
mouse:
label: 'Mouse'
description: '''
A very small animal with a long snout, big round ears and a long hairless tail. This animal can be found in and around grasslands and homes.
'''
mower:
label: 'Mower'
description: '''
N/A. Identifying the frequency of mowers helps us understand the impact of human activity on the animal population in this urban habitat.
'''
muskrat:
label: 'Muskrat'
description: '''
This animal normally has brown fur and a black tail with small dark eyes. The fur-less, scaly tail is half of its total length. When it walks, the tail creates a trail. Their front paws are clawed while the rear feet are semi-webbed and clawed.
'''
opossum:
label: 'Opossum'
description: '''
Adept tree climbers with their clawed feet and opposable big toe on rear paw. This animal is known for playing dead and has a white face with a pink nose, black eyes, black ears, long tail and long, gray fur on its body.
'''
rabbit:
label: 'Rabbit'
description: '''
Rabbits we see in urban settings have large, dark eyes, long ears pointed upwards and brown fur with a short, fluffy, white tail.
'''
raccoon:
label: 'Raccoon'
description: '''
This brown-gray furry animal looks like it is wearing a bandit mask with the black patches around its eyes on its white face. Another notable features are its finger-like clawed toes and its black-ringed tail with long fur. Raccoons are nocturnal and often seen foraging for food in trash bins.
'''
rat:
label: 'Rat'
description: '''
A large mouse-like critter with a pointy nose, round ears and a long, hairless, pinkish tail. Many people think they only roam the subway and sewers, but it is not uncommon to see then running across the street above ground.
'''
redFox:
label: 'Fox, Red'
description: '''
An animal with orange brownish fur along its head and back and white fur on its belly and typically at the tip of its bushy tail. Its tail helps it balance just like a cat’s. Some have black fur on the back of their ears and legs.
'''
skunk:
label: 'Skunk'
description: '''
An animal well known for its stinky spray towards predators and black coat with white stripe patterns. It has a single thin, white stripe down the middle of its face and two thicker white stripes originating at the top of its head running down either side of the back into its thick, bushy tail.
'''
woodChuck:
label: 'Woodchuck'
description: '''
This animal is also known as a groundhog. It has a brown furry coat, clawed feet, small eyes and ears, and a short, flat tail.
'''
melanisticGraySquirrel:
label: 'Squirrel, Melanistic Gray'
description: '''
Melanism is a genetic trait that produces extra melanin in the skin and fur, making an organism appear jet black if it has two sets of this recessive gene or brown/black if it only has one. Gray squirrels are known to carry this unusual genetic trait. This trait may be beneficial to gray squirrels living at northern latitudes as they would lose less heat during the cold winter months. The photo in this ID is of a brown/black melanistic gray squirrel.
'''
characteristics:
like: 'Looks like...'
coat: 'Coat'
tail: 'Tail'
build: 'Build'
characteristicValues:
likeCatDog: 'Cat Dog'
likeRodent: 'Rodent'
likeManMade: 'Vehicles'
likeOther: 'Other'
coatTanYellow: 'Tan Yellow'
coatRedBrown: 'Red Brown'
coatBrownBlack: 'Brown Black'
coatGrayBlack: 'Gray Black'
coatMottled: 'Mottled'
coatSolid: 'Solid'
coatOrTailStriped: 'Or Tail Striped'
tailBushy: 'Bushy'
tailSmooth: 'Smooth'
tailLong: 'Long'
buildStocky: 'Stocky'
buildLanky: 'Lanky'
buildSmall: 'Small'
buildLowSlung: 'Low Slung'
profile:
header: "Your Profile"
favorites: 'Favorites'
recents: 'Recents'
noFavorites: 'You have no favorites!'
noRecents: 'You have no recent identifications!'
showing: 'Showing'
loadMore: 'Load more'
about:
press:
nav:
"Press"
science:
nav: "Science"
header: "Science"
p: """
<p>
Cities can be hostile places for wildlife, with threats coming from habitat destruction, roads and traffic, humans, pets and large numbers of invasive species. However, with proper management, urban areas can house a number of important wildlife species, including carnivores and small mammals.
</p>
<p>
To assess the biodiversity of the greater Chicagoland area, Lincoln Park Zoo’s Urban Wildlife Institute has established monitoring stations within city parks, forest preserves, golf courses and cemeteries in parts of Cook, Lake, DuPage and Will Counties including downtown Chicago. Motion-triggered cameras are deployed four times per year at more than 100 sites to determine which species are present and to assess spatial and long-term patterns in wildlife communities.
</p>
<p>
Knowing where Chicago’s urban wildlife is located will help us to better conserve it. This knowledge will pave the way for future studies on the behavior and ecology of specific urban species, helping stakeholders to better manage wildlife conflict.
</p>
<p>
Keep an eye out for the black pouches that are often attached to trees in most of the photos. They contain a scented lure that increases the probability of photographing the wildlife community at a site.
</p>
<img src="./images/animals/fox-squirrel-1.jpg">
"""
questions: """
<h1>Our Scientific Questions</h1>
<h2>Where do they go?</h2>
<p>We don’t know as much as we’d like about species in urban systems. Even basic facts like what types of habitat attract which species are often unknown in areas like cities.
Finding out where certain species are most likely to occur allows us to target conservation and management efforts to ensure we can coexist with our wildlife neighbors.</p>
<h2>How are they doing?</h2>
<p>While we can’t directly measure populations with the data from our cameras, we can get a sense of which species are most common and which may be in decline.
This can help us make recommendations about how to improve conditions for the species that are in trouble.</p>
<h2>How do they compete?</h2>
<p>We know almost nothing about how species in urban areas might compete with one another, engage in predator-prey dynamics or avoid each other.
Preliminary results indicate that the normal community interactions we observe in natural systems don’t apply to urban areas, where entirely new dynamics seem to be in place.
By evaluating our camera images, we can begin to assemble the first complete picture of an urban ecosystem, including how all the species interact.</p>
<h2>How do they interact with us?</h2>
<p>By also collecting data on humans, and on pets like cats and dogs, we can get a sense of how animals in urban settings react to the people who make the city their home.
Some animals may be attracted to sites that are often visited by humans, while others may be looking for more secluded places. Humans are a critical part of the system,
and our camera data allows us to understand our impact, as well as the importance of food and habitat.</p>
"""
uwi:
nav: "Urban Wildlife Institute"
header: "Urban Wildlife Institute"
content: """
<p>Utilizing Lincoln Park Zoo’s diverse scientific specialties, the Urban Wildlife Institute studies the interaction between urban development and the natural ecosystem to develop scientific standards for minimizing conflict between these overlapping areas. Landscape ecology, population biology, epidemiology, endocrinology, veterinary medicine and other core disciplines contribute to an increased understanding of ecosystem health in an urban setting. The Urban Wildlife Institute aims to use Chicago as a model for urban areas struggling to deal with wildlife relocation, rehabilitation, disease and conflicts.</p>
<p>One issue receiving special emphasis is the transmission of disease from animals to humans—another byproduct of urban sprawl. By studying how people and animals interact in an urban setting, the Urban Wildlife Institute can help scientists to better understand—and curb—zoonotic disease threats such as West Nile virus, rabies and avian influenza.</p>
<p>Supported by a $1.5 million grant from the Davee Foundation, the Urban Wildlife Institute is forming partnerships with local nature and conservation organizations and conducting pilot studies into ecosystem health and human-wildlife interaction. By developing standards for managing urban wildlife issues, the institute is creating a conflict-management model that can be followed worldwide.</p>
<p>To learn more, you can visit <a href="http://www.lpzoo.org/conservation-science/science-centers/urban-wildlife-institute">their website</a>.</p>
"""
zooniverse:
nav: "Zooniverse"
header: "Zooniverse"
content: """
<p>The amount of data collected by modern research equipment is often too large for any one person or small team of people to effectively analyze. Over the past several decades, scientists have explored partnering with the public to help do real science when human eyes and thinking are still better at analysis than computers.</p>
<p>Known online as the Zooniverse, the Adler's Citizen Science department designs and develops web applications using data sets that would normally take a science team over 100 years to analyze and, with the help of a worldwide network of volunteers, complete the analysis with a high level of accuracy in weeks or months.</p>
<p>To participate in other citizen science efforts, visit <a href="https://www.zooniverse.org">Zooniverse.org</a>.</p>
"""
organizations:
nav: "Organizations"
header: "Organizations"
adler:
header: "Adler Planetarium"
p: """
<img src="./images/logos/adler-black.png" class="inline">
<a href="http://www.adlerplanetarium.org/">The Adler Planetarium</a> - America's First Planetarium - was founded in 1930 by Chicago business leader PI:NAME:<NAME>END_PI.
The Adler is a recognized leader in science education, with a focus on inspiring young people to pursue careers in science, technology, engineering and math.
Throughout 80 years, the Adler has inspired the next generation of explorers by sharing the personal stories of space exploration and America’s space heroes.
"""
lincolnParkZoo:
header: "Lincoln Park Zoo"
p: """
<img src="./images/logos/lpz-black.png" class="inline">
<a href="http://www.lpzoo.org/">Lincoln Park Zoo</a> is a world of wildlife in the shadow of skyscrapers. Located within a verdant park just minutes north of Chicago, the zoo has been a natural, free oasis for generations of animal lovers, who visit the zoo to hear a lion’s roar echo off nearby apartment buildings, see gorillas climb trees as the Willis Tower looms in the distance or forget where they are as they immerse themselves in tropical rainforests, dry-thorn forests or spacious savannas.<br><br>
Lincoln Park Zoo is dedicated to connecting people with nature by providing a free, family-oriented wildlife experience in the heart of Chicago and by advancing the highest quality of animal care, education, science and conservation.
"""
team:
nav: "Team"
header: "Team"
science:
magle:
name: 'Dr. PI:NAME:<NAME>END_PI'
title: 'Director, Urban Wildlife Institute at Lincoln Park Zoo'
image: 'http://placehold.it/100'
description: '''
<p>PI:NAME:<NAME>END_PI first became interested in conservation and ecology as a college student in 1997 while observing black-tailed prairie dogs living in sidewalk median strips near his home in Boulder, Colorado. Daily interactions with these resilient animals made him wonder what adaptations enabled these small mammals to persist in highly urban habitat and which factors contributed to their distribution and abundance. Eventually he completed an honors thesis on the behavior of this urban-adapted keystone species; he ultimately expanded on that research for both a master’s degree and a doctorate.</p>
<p>However, Seth’s interests go far beyond prairie dogs to encompass all wildlife species impacted by urbanization and human development. He has also engaged in research on movement behavior of white-tailed deer in a rural landscape characterized by high prevalence of disease outbreaks, assessments of the diversity of bird communities residing in agricultural habitat and the conservation of Canada lynx reintroduced to the southern edge of their historical range, where they are threatened by roads and traffic.</p>
<p>Seth strongly believes that if rare and imperiled species are to be conserved in our modern world, we must understand and mitigate all potential impacts of urban areas on wildlife. To that end, he engages in studies of urban wildlife that span a broad range of scientific disciplines, including behavioral ecology, conservation genetics, landscape ecology, environmental education and human dimensions of wildlife. His vision is to help create a world in which urban ecosystems represent an important component of the worldwide conservation of biodiversity.</p>
'''
lehrer:
name: "PI:NAME:<NAME>END_PI"
image: 'http://placehold.it/100'
description: '''
<p>PI:NAME:<NAME>END_PI’s interest in wildlife began as a kid, while digging through her backyard and looking for bugs and worms to scare her sister. In college, she expanded her education with summer internships including wildlife rehabilitation, collecting behavioral data on Mexican wolves and a semester abroad studying marine life in the Great Barrier Reef.</p>
<p>After earning her degree in zoology, PI:NAME:<NAME>END_PI was fortunate to work as a research intern at Lincoln Park Zoo and later as animal records keeper. It was her work at the zoo, and life in Chicago, that lead to her fascination with urban wildlife. Coyotes and foxes were becoming regular residents of the city, but how do they move about the urban landscape? What types of adjustments do they make to survive? To examine some of these questions, Liza returned to graduate school to study how urbanization affects survival, movements and behavior of an urban-adapter species, the woodchuck.</p>
<p>As urban wildlife ecologist for the Urban Wildlife Institute, Liza manages and collects data for the institute’s field research projects, including the Urban Wildlife Biodiversity Monitoring project. She coordinates collaborations and leads a project in partnership with the University of Illinois on the effects of relocation on nuisance woodchucks, which expands upon her master’s research. Liza’s research interests include urban wildlife, landscape ecology, behavioral ecology, wildlife disease and managing human-wildlife conflict.</p>
<p>Prior to joining the Urban Wildlife Institute, Liza served as an avian field assistant on a project examining urban disease ecology of West Nile virus and as a guest engagement leader at Lincoln Park Zoo.</p>
'''
fidino:
name: 'PI:NAME:<NAME>END_PI'
description: '''
<p>Mason first began conservation and ecology work in 2006. Since then he has aided in numerous studies, from collecting clams and fish in the Columbia River to coring trees and identifying birds on the mountains of Washington. Mason completed his undergraduate education at Western Washington University in 2009. After a year-long stay in Dublin, Ireland, he moved to Chicago and began working at the Urban Wildlife Institute as Coordinator of Wildlife Management.</p>
'''
development:
raden:
name: 'PI:NAME:<NAME>END_PI'
image: 'http://placehold.it/100'
description: '''
<p>PI:NAME:<NAME>END_PI is a software developer at Adler Planetarium and Zooniverse. As a Chicagoan, he enjoys walking the city's parks and streets and occasionally spotting animals. </p>
'''
vansingel:
name: 'PI:NAME:<NAME>END_PI'
image: 'http://placehold.it/100'
description: '''
<p>Heath is the UX/UI Designer for projects at the Zooniverse, where he works to craft thoughtful and engaging user experiences. Apart from design Heath also enjoys illustration, a good sci-fi or fantasy novel, and trips back to Michigan.</p>
'''
weiksnar:
name: 'PI:NAME:<NAME>END_PI'
image: 'images/about/team/michael.jpg'
description: '''
<p>PI:NAME:<NAME>END_PI currently works as a front-end developer for the Zooniverse out of the Adler Planetarium. He spends his time building rich and engaging user interfaces for the web.
PI:NAME:<NAME>END_PI previously attended University of Miami, where he studied psychology, biology and English.
</p>
'''
wang:
name: 'PI:NAME:<NAME>END_PI'
description: '''
<p>PI:NAME:<NAME>END_PI is a research scientist at the Syracuse University School of Information Studies. He is interested in designing enjoyable web applications. He is currently a principal investigator of a project sponsored by National Academies: "Drawing-based social learning". He is also an investigator of a citizen science project (citizensort) at Syracuse University. Fascinated by the recent breakthrough in deep learning, he wonders how much computer and human can teach each other. He has enjoyed working with the Zooniverse n using Caffe, a fast deep learning framework, to accomplish pre-processing on the images displayed to volunteers on Chicago Wildlife Watch.</p>
'''
whyte:
name: 'Dr. PI:NAME:<NAME>END_PI'
title: 'Director of Citizen Science at Adler Planetarium'
image: 'http://placehold.it/100'
description: '''
<p>The citizen science department at the Adler Planetarium is home to a development team who design and build Zooniverse websites - the worlds largest and most successful collection of citizen science projects. This team, who bring expertise in technology, education, science outreach and research, reach beyond the internet into the local community through school visits, youth programs and hack days events. As former astronomer, high school teacher, museum educator, and web developer, PI:NAME:<NAME>END_PI leads these initiatives and the opportunity they bring to engage a wider Chicago audience in actively doing science.</p>
'''
connect:
header: "Connect"
action: "Get Started"
social: """
Follow the Adler Planetarium [<a href='http://www.adlerplanetarium.org/blogs'>Blog</a> / <a href= 'https://twitter.com/adlerskywatch'>Twitter</a>] and PI:NAME:<NAME>END_PI Zoo Urban Wildlife Institute [<a href='https://www.lpzoo.org/rss-feeds?'>Blog</a> / <a href='https://twitter.com/lpz_uwi'>Twitter</a>] to keep current with the latest findings!
"""
education:
header: "Education"
overview:
nav: "Overview"
header: "Can I use Chicago Wildlife Watch in the classroom?"
p: """
Absolutely! Chicago Wildlife Watch, just like all the Zooniverse projects, offers a unique opportunity to explore real scientific data while making a contribution to cutting-edge research. We would like to stress that as each image is marked by the volunteers, it really does not matter if your students don't mark all the features. That being said, the task itself is simple enough that we believe most people can take part and make a worthwhile contribution regardless of age.
"""
resources:
nav: "Resources"
header: "What resources are there to support use in the classroom?"
content: """
<p>Over the summer of 2014, teen interns at Adler Planetarium developed a floor activity to bring awareness to the fact that nature is everywhere and we live in nature. A Lesson plan for this activity can be found on <a href='http://www.zooteach.org'>ZooTeach</a></p>
<p>Videos are also a great tool to introduce students to Chicago Wildlife Watch. Here are a couple of our favorites:</p>
<ul>
<li><a href='https://www.youtube.com/watch?v=iRhdDs91aas'> TropicMind.com: Ecosystem and Food Chain (aimed for younger children)</a> </li>
<li><a href='https://www.youtube.com/watch?v=iFeRFmqFChQ'>PI:NAME:<NAME>END_PI: The Science Guy - Biodiversity</a></li>
</ul>
<p>We also recommend checking out the Urban Wildlife Institute <a href="http://www.lpzoo.org/conservation-science/science-centers/urban-wildlife-institute">webpage</a> for more information on the organization.
</p>
"""
partner_resources:
nav: "Partner Resouces"
header: "Partner resources"
content: """
<p>Please visit PI:NAME:<NAME>END_PI Zoo's Educator's Resources <a href="http://www.lpzoo.org/education/educators-resources"> webpage</a> to access curriculum guides, zoo field trip and self-tour information, accessibility kits and links to several multi-media apps.
</p>
<p>The Adler Planetarium is dedicated to helping the public experience science and discover the universe through field trips, school partnerships, child and teen programming. See the Teach and Learn <a href="http://www.adlerplanetarium.org/educator-resources/">section</a> of the Adler's website for details.
</p>
"""
aside:
content: """
<h1>Connect with Education</h1>
<p>The Chicago Wildlife Watch blog, as well as the partner Facebook pages, are great places to keep up to date with the latest science results, but there is also a Zooniverse Education Blog as well as a <a href='https://www.twitter.com/ZooTeach'>@ZooTeach</a> Twitter feed. The Urban Wildlife Institute also has a Twitter account, <a href='https://www.twitter.com/LPZ_UWI'>@LPZ_UWI</a>, that you can follow for more information on their work.</p>
"""
press:
header: "Press"
intro: "Chicago Wildlife Watch Recruits Chicagoans to Help with Urban Wildlife Science Research from Home or Classroom"
section_1: """
The Adler Planetarium and Lincoln Park Zoo have launched <b>Chicago Wildlife Watch</b>, a new web-based citizen science initiative that provides an opportunity for students, teachers and members of the public to actively participate in Chicagoland wildlife research through photo identification technology. The platform is available at <a href="http://www.chicagowildlifewatch.org">chicagowildlifewatch.org</a>.
"""
section_2: """
<b>Chicago Wildlife Watch</b> is a collaboration between the Adler Planetarium’s Zooniverse team and Lincoln Park Zoo’s Urban Wildlife Institute that began in early 2014. Faced with a year’s worth of back logged research, the Urban Wildlife Institute enlisted the help of the Adler Planetarium’s Zooniverse development team to create a citizen science platform that would empower the people of Chicago to assist researchers in classifying important data essential in assessing local wildlife and their habitats.
"""
downloads:
header: "Chicago Wildlife Watch Media Downloads:"
pressReleasePdf: "Press Release PDF"
bRollFootage: "B-roll Footage"
imagesDownloads: "Images Downloads"
imageCaptionSheet: "Image Caption Sheet"
slider:
header: "Images"
captions: """
<div id="caption-1" class="nivo-html-caption">
<p>The Adler Planetarium and Lincoln Park Zoo have launched Chicago Wildlife Watch, a new web-based citizen science initiative that provides an opportunity for students, teachers and members of the public to actively participate in Chicagoland wildlife research through photo identification technology available at chicagowildlifewatch.org. This data will help re- searchers apply findings that will positively influence urban wildlife policy.</p>
<p>© Adler Planetarium</p>
</div>
<div id="caption-2" class="nivo-html-caption">
<p>The camera traps used for Chicago Wildlife Watch data collection are set up in urban areas throughout Chicago including this South Loop location.</p>
<p>© Urban Wildlife Institute/Lincoln Park Zoo</p>
</div>
<div id="caption-3" class="nivo-html-caption">
<p>PI:NAME:<NAME>END_PI, PhD, Director of the Urban Wildlife Institute secures a camera trap that is used to capture data for Chicago Wildlife Watch. Urban Wildlife Institute scientists set up camera traps four times a year.</p>
<p>© Urban Wildlife Institute/Lincoln Park Zoo</p>
</div>
<div id="caption-4" class="nivo-html-caption">
<p>A resting coyote is captured by a Urban Wildlife Institute camera trap southwest of Chicago. Coyotes are among the most common carnivores in the Chicagoland area.</p>
<p>© Urban Wildlife Institute/Lincoln Park Zoo</p>
</div>
<div id="caption-5" class="nivo-html-caption">
<p>This image shows a raccoon and opossum in the city of Chicago. Exploring the relationship between urban species is one goal of Chicago Wildlife Watch.</p>
<p>© Urban Wildlife Institute/Lincoln Park Zoo</p>
</div>
<div id="caption-6" class="nivo-html-caption">
<p>Chicago Wildlife Watch will explore wildlife that utilize public spaces such as these coyotes foraging in a park on the Northwest side of Chicago.</p>
<p>© Urban Wildlife Institute/Lincoln Park Zoo</p>
</div>
<div id="caption-7" class="nivo-html-caption">
<p>This red fox sits facing an Urban Wildlife Institute camera trap west of the city. Red foxes are becoming uncommon in the Chicago area, with some speculat- ing that coyotes may be outcompeting them in urban spaces. Chicago Wildlife Watch may shed light on why this is occurring.</p>
<p>© Urban Wildlife Institute/Lincoln Park Zoo</p>
</div>
<div id="caption-8" class="nivo-html-caption">
<p>A Zooniverse team member from the Adler Planetarium demonstrates Chicago Wildlife Watch to participants of the Lincoln Park Zoo Conservation Camp. The Zooniverse is the world’s leading - and largest - citizen science platform.</p>
<p>© Adler Planetarium</p>
</div>
<div id="caption-9" class="nivo-html-caption">
<p>Participants of the Lincoln Park Zoo Conservation Camp classify animals on Chicago Wildlife Watch. This easy to use online platform, allows everyone from middle-school aged children to adults to contribute to real scientific research.</p>
<p>© Adler Planetarium</p>
</div>
"""
contacts:
header: "Media Contacts:"
sharon: """
PI:NAME:<NAME>END_PI<br>
Lincoln Park Zoo<br>
312-742-2246<br>
PI:EMAIL:<EMAIL>END_PI
"""
molly: """
PI:NAME:<NAME>END_PI<br>
Adler Planetarium<br>
312-322-0524<br>
PI:EMAIL:<EMAIL>END_PI
"""
|
[
{
"context": " senderId: opts.senderId\n senderUsername: opts.senderUsername\n receiverId: opts.receiverId\n receiverU",
"end": 2523,
"score": 0.7932201623916626,
"start": 2504,
"tag": "USERNAME",
"value": "opts.senderUsername"
},
{
"context": "erId: opts.receiverI... | lib/App.coffee | Elfoslav/codermania | 56 | #general functionality
class @App
@initTextEditor: (selector) ->
if Meteor.isClient
#editor docs: http://www.tinymce.com
#destroy the old one editor, in order to get new working
tinymce.get()?[0]?.destroy()
editor = tinymce.init
selector: selector
plugins: [
"advlist autolink lists link image charmap preview hr anchor pagebreak",
"visualblocks visualchars code fullscreen",
"nonbreaking save directionality",
"paste textpattern"
]
style_formats: [
{ title: 'small', inline: 'small' }
{ title: 'Inline code', inline: 'code' }
{ title: 'Block of code', block: 'pre' }
]
toolbar1: "styleselect | bold italic | bullist numlist outdent indent | link image | preview fullpage"
@getCurrentUserId: ->
Router.current().params.userId || Meteor.userId() || undefined
@getCurrentUsername: ->
user = Meteor.user()
Router.current().params.username || user?.username || undefined
@getCurrentUrl: ->
if Router.current().url.indexOf('http') is -1
url = Meteor.absoluteUrl()
return url += Router.current().url.replace('/', '')
return url = Router.current().url
@getAllNeedHelpUserCommentsCount: (needHelpId, userId) ->
NeedHelpComments.find
needHelpId: needHelpId
userId: { $ne: userId }
.count()
@getReadNeedHelpUserCommentsCount: (needHelpId, userId) ->
NeedHelpComments.find
needHelpId: needHelpId
userId: { $ne: userId }
readBy: { $in: [ userId ]}
.count()
@getUnreadNeedHelpUserCommentsCount: (needHelpId, userId) ->
NeedHelpComments.find
needHelpId: needHelpId
userId: { $ne: userId }
readBy: { $nin: [ userId ]}
.count()
###
#@params {
# studyGroupId: String
# homeworkId: String
# username: String
#}
###
@getStudyGroupHomeworkUrl: (params) ->
"#{Meteor.absoluteUrl()}study-groups/#{params.studyGroupId}/homework/#{params.homeworkId}/#{params.username}"
@insertMessage: (opts) ->
check opts,
senderId: String
senderUsername: String
receiverId: String
receiverUsername: String
text: String
needHelpId: Match.Optional String
if opts.senderUsername == opts.receiverUsername
throw new Meteor.Error('', 'Sender username is equal to receiver username. User cannot send message to himself.')
Messages.insert
senderId: opts.senderId
senderUsername: opts.senderUsername
receiverId: opts.receiverId
receiverUsername: opts.receiverUsername
text: opts.text
timestamp: Date.now()
isRead: false
needHelpId: opts.needHelpId
existingSendersList = SendersList.findOne({ senderId: opts.senderId, receiverId: opts.receiverId })
if existingSendersList
SendersList.update { senderId: opts.senderId, receiverId: opts.receiverId },
$set:
lastMsgTimestamp: Date.now()
senderUsername: opts.senderUsername #just in case
$inc: { unreadMsgsCount: 1 }
else
SendersList.insert
senderId: opts.senderId
senderUsername: opts.senderUsername
receiverId: opts.receiverId
lastMsgTimestamp: Date.now()
unreadMsgsCount: 1
@insertNotification: (data) ->
unless data.userIds?.length > 1
userIds = []
teachers = Meteor.users.find { 'roles.all': 'teacher' }
teachers.forEach (teacher) ->
if userIds.indexOf(teacher._id) == -1
userIds.push teacher._id
existing = AppNotifications.findOne
userId: data.userId
sourceId: data.sourceId
if existing
AppNotifications.update
userId: data.userId
sourceId: data.sourceId
,
$set:
userIds: data.userIds || userIds
type: data.type
isReadBy: data.isReadBy || []
timestamp: data.timestamp || Date.now()
text: data.text
else
AppNotifications.insert
userId: data.userId
userIds: data.userIds || userIds
sourceId: data.sourceId
type: data.type
isReadBy: data.isReadBy || []
timestamp: data.timestamp || Date.now()
text: data.text
@notifyTeachers: (data) ->
throw new Meteor.Error 500, 'notifyTeachers can only be called from the server' unless Meteor.isServer
teachers = Meteor.users.find
'roles.all': 'teacher'
teachers.forEach (teacher) =>
console.log 'submitting homework to teacher: ', teacher.username
#send a message only if user has student role. Student can have teacher role
if Roles.userIsInRole(data.userId, 'student', 'all') and teacher._id != @userId
if data.userId != teacher._id
App.insertNotification
userId: data.userId
sourceId: data.sourceId
type: data.type
text: data.text
@getWelcomeMessage: ->
return """
Hello, welcome to CoderMania! I would like to hear from you:\n
What is your experience with coding?\n
Why do you want to learn to code?\n
If you have any questions, you can write me here.
"""
@getEmailFooter: (opts) ->
msg = "
<p>
Watch CoderMania on social networks:
<a href=\"https://www.facebook.com/codermania\">Facebook</a>
,
<a href=\"https://twitter.com/codermania_com\">Twitter</a>
</p>
<p>
Support CoderMania on Patreon:
<a href=\"https://www.patreon.com/elfoslav\">https://www.patreon.com/elfoslav</a>
</p>
"
if opts.showUnsubscribe
msg += "
<p>
You can unsubscribe or modify your e-mail settings here:
<a href=\"http://www.codermania.com/user/settings\">http://www.codermania.com/user/settings</a>
</p>
"
return msg
@getClientErrorMessage: (err) ->
"""Something went wrong, please try again.
If you see this message again, please contact CoderMania admin: <b>tomas@codermania.com</b>
and tell him what does not work. Thanks.
<br><br>
Error: #{err.reason}"""
@sendEmailAboutMessage: (opts) ->
throw new Error('Cannot call from the client') unless Meteor.isServer
sender = opts.sender
receiver = opts.receiver
messagesUrl = Meteor.absoluteUrl() + 'messages/' + sender.username
msg = """
<p>
Hi #{receiver.username},<br><br>
#{sender.username} has sent you a message on CoderMania.
Go to <a href='#{messagesUrl}'>#{messagesUrl}</a> to see the message.
</p>
<br>
#{@getEmailFooter({ showUnsubscribe: false })}
"""
Email.send
from: sender?.emails?[0]?.address
to: receiver?.emails?[0]?.address
subject: "#{sender.username} has sent you a message on CoderMania"
html: msg
@sendEmailAboutHomeworkComment: (opts) ->
throw new Error('Cannot call from the client') unless Meteor.isServer
sender = opts.sender
receiver = opts.receiver
msg = """
<p>
Hi #{receiver.username},<br><br>
#{sender.username} commented your homework on CoderMania.
</p>
<p>
Go to <a href='#{opts.homeworkUrl}'>#{opts.homeworkUrl}</a> to see the message.
</p>
<br>
#{@getEmailFooter({ showUnsubscribe: false })}
"""
Email.send
from: sender?.emails?[0]?.address
to: receiver?.emails?[0]?.address
subject: "#{sender.username} commented your homework on CoderMania"
html: msg
@evaluateOperator: (val1, operator, val2) ->
if operator is '<'
return val1 < val2
if operator is '>'
return val1 > val2
if operator is '<='
return val1 <= val2
if operator is '>='
return val1 >= val2
if operator is '=='
return `val1 == val2`
if operator is '==='
return `val1 === val2`
if operator is '!='
return `val1 != val2`
if operator is '!=='
return `val1 !== val2`
@setPageTitle: (title) ->
document.title = title + ' | CoderMania'
| 28902 | #general functionality
class @App
@initTextEditor: (selector) ->
if Meteor.isClient
#editor docs: http://www.tinymce.com
#destroy the old one editor, in order to get new working
tinymce.get()?[0]?.destroy()
editor = tinymce.init
selector: selector
plugins: [
"advlist autolink lists link image charmap preview hr anchor pagebreak",
"visualblocks visualchars code fullscreen",
"nonbreaking save directionality",
"paste textpattern"
]
style_formats: [
{ title: 'small', inline: 'small' }
{ title: 'Inline code', inline: 'code' }
{ title: 'Block of code', block: 'pre' }
]
toolbar1: "styleselect | bold italic | bullist numlist outdent indent | link image | preview fullpage"
@getCurrentUserId: ->
Router.current().params.userId || Meteor.userId() || undefined
@getCurrentUsername: ->
user = Meteor.user()
Router.current().params.username || user?.username || undefined
@getCurrentUrl: ->
if Router.current().url.indexOf('http') is -1
url = Meteor.absoluteUrl()
return url += Router.current().url.replace('/', '')
return url = Router.current().url
@getAllNeedHelpUserCommentsCount: (needHelpId, userId) ->
NeedHelpComments.find
needHelpId: needHelpId
userId: { $ne: userId }
.count()
@getReadNeedHelpUserCommentsCount: (needHelpId, userId) ->
NeedHelpComments.find
needHelpId: needHelpId
userId: { $ne: userId }
readBy: { $in: [ userId ]}
.count()
@getUnreadNeedHelpUserCommentsCount: (needHelpId, userId) ->
NeedHelpComments.find
needHelpId: needHelpId
userId: { $ne: userId }
readBy: { $nin: [ userId ]}
.count()
###
#@params {
# studyGroupId: String
# homeworkId: String
# username: String
#}
###
@getStudyGroupHomeworkUrl: (params) ->
"#{Meteor.absoluteUrl()}study-groups/#{params.studyGroupId}/homework/#{params.homeworkId}/#{params.username}"
@insertMessage: (opts) ->
check opts,
senderId: String
senderUsername: String
receiverId: String
receiverUsername: String
text: String
needHelpId: Match.Optional String
if opts.senderUsername == opts.receiverUsername
throw new Meteor.Error('', 'Sender username is equal to receiver username. User cannot send message to himself.')
Messages.insert
senderId: opts.senderId
senderUsername: opts.senderUsername
receiverId: opts.receiverId
receiverUsername: opts.receiverUsername
text: opts.text
timestamp: Date.now()
isRead: false
needHelpId: opts.needHelpId
existingSendersList = SendersList.findOne({ senderId: opts.senderId, receiverId: opts.receiverId })
if existingSendersList
SendersList.update { senderId: opts.senderId, receiverId: opts.receiverId },
$set:
lastMsgTimestamp: Date.now()
senderUsername: opts.senderUsername #just in case
$inc: { unreadMsgsCount: 1 }
else
SendersList.insert
senderId: opts.senderId
senderUsername: opts.senderUsername
receiverId: opts.receiverId
lastMsgTimestamp: Date.now()
unreadMsgsCount: 1
@insertNotification: (data) ->
unless data.userIds?.length > 1
userIds = []
teachers = Meteor.users.find { 'roles.all': 'teacher' }
teachers.forEach (teacher) ->
if userIds.indexOf(teacher._id) == -1
userIds.push teacher._id
existing = AppNotifications.findOne
userId: data.userId
sourceId: data.sourceId
if existing
AppNotifications.update
userId: data.userId
sourceId: data.sourceId
,
$set:
userIds: data.userIds || userIds
type: data.type
isReadBy: data.isReadBy || []
timestamp: data.timestamp || Date.now()
text: data.text
else
AppNotifications.insert
userId: data.userId
userIds: data.userIds || userIds
sourceId: data.sourceId
type: data.type
isReadBy: data.isReadBy || []
timestamp: data.timestamp || Date.now()
text: data.text
@notifyTeachers: (data) ->
throw new Meteor.Error 500, 'notifyTeachers can only be called from the server' unless Meteor.isServer
teachers = Meteor.users.find
'roles.all': 'teacher'
teachers.forEach (teacher) =>
console.log 'submitting homework to teacher: ', teacher.username
#send a message only if user has student role. Student can have teacher role
if Roles.userIsInRole(data.userId, 'student', 'all') and teacher._id != @userId
if data.userId != teacher._id
App.insertNotification
userId: data.userId
sourceId: data.sourceId
type: data.type
text: data.text
@getWelcomeMessage: ->
return """
Hello, welcome to CoderMania! I would like to hear from you:\n
What is your experience with coding?\n
Why do you want to learn to code?\n
If you have any questions, you can write me here.
"""
@getEmailFooter: (opts) ->
msg = "
<p>
Watch CoderMania on social networks:
<a href=\"https://www.facebook.com/codermania\">Facebook</a>
,
<a href=\"https://twitter.com/codermania_com\">Twitter</a>
</p>
<p>
Support CoderMania on Patreon:
<a href=\"https://www.patreon.com/elfoslav\">https://www.patreon.com/elfoslav</a>
</p>
"
if opts.showUnsubscribe
msg += "
<p>
You can unsubscribe or modify your e-mail settings here:
<a href=\"http://www.codermania.com/user/settings\">http://www.codermania.com/user/settings</a>
</p>
"
return msg
@getClientErrorMessage: (err) ->
"""Something went wrong, please try again.
If you see this message again, please contact CoderMania admin: <b><EMAIL></b>
and tell him what does not work. Thanks.
<br><br>
Error: #{err.reason}"""
@sendEmailAboutMessage: (opts) ->
throw new Error('Cannot call from the client') unless Meteor.isServer
sender = opts.sender
receiver = opts.receiver
messagesUrl = Meteor.absoluteUrl() + 'messages/' + sender.username
msg = """
<p>
Hi #{receiver.username},<br><br>
#{sender.username} has sent you a message on CoderMania.
Go to <a href='#{messagesUrl}'>#{messagesUrl}</a> to see the message.
</p>
<br>
#{@getEmailFooter({ showUnsubscribe: false })}
"""
Email.send
from: sender?.emails?[0]?.address
to: receiver?.emails?[0]?.address
subject: "#{sender.username} has sent you a message on CoderMania"
html: msg
@sendEmailAboutHomeworkComment: (opts) ->
throw new Error('Cannot call from the client') unless Meteor.isServer
sender = opts.sender
receiver = opts.receiver
msg = """
<p>
Hi #{receiver.username},<br><br>
#{sender.username} commented your homework on CoderMania.
</p>
<p>
Go to <a href='#{opts.homeworkUrl}'>#{opts.homeworkUrl}</a> to see the message.
</p>
<br>
#{@getEmailFooter({ showUnsubscribe: false })}
"""
Email.send
from: sender?.emails?[0]?.address
to: receiver?.emails?[0]?.address
subject: "#{sender.username} commented your homework on CoderMania"
html: msg
@evaluateOperator: (val1, operator, val2) ->
if operator is '<'
return val1 < val2
if operator is '>'
return val1 > val2
if operator is '<='
return val1 <= val2
if operator is '>='
return val1 >= val2
if operator is '=='
return `val1 == val2`
if operator is '==='
return `val1 === val2`
if operator is '!='
return `val1 != val2`
if operator is '!=='
return `val1 !== val2`
@setPageTitle: (title) ->
document.title = title + ' | CoderMania'
| true | #general functionality
class @App
@initTextEditor: (selector) ->
if Meteor.isClient
#editor docs: http://www.tinymce.com
#destroy the old one editor, in order to get new working
tinymce.get()?[0]?.destroy()
editor = tinymce.init
selector: selector
plugins: [
"advlist autolink lists link image charmap preview hr anchor pagebreak",
"visualblocks visualchars code fullscreen",
"nonbreaking save directionality",
"paste textpattern"
]
style_formats: [
{ title: 'small', inline: 'small' }
{ title: 'Inline code', inline: 'code' }
{ title: 'Block of code', block: 'pre' }
]
toolbar1: "styleselect | bold italic | bullist numlist outdent indent | link image | preview fullpage"
@getCurrentUserId: ->
Router.current().params.userId || Meteor.userId() || undefined
@getCurrentUsername: ->
user = Meteor.user()
Router.current().params.username || user?.username || undefined
@getCurrentUrl: ->
if Router.current().url.indexOf('http') is -1
url = Meteor.absoluteUrl()
return url += Router.current().url.replace('/', '')
return url = Router.current().url
@getAllNeedHelpUserCommentsCount: (needHelpId, userId) ->
NeedHelpComments.find
needHelpId: needHelpId
userId: { $ne: userId }
.count()
@getReadNeedHelpUserCommentsCount: (needHelpId, userId) ->
NeedHelpComments.find
needHelpId: needHelpId
userId: { $ne: userId }
readBy: { $in: [ userId ]}
.count()
@getUnreadNeedHelpUserCommentsCount: (needHelpId, userId) ->
NeedHelpComments.find
needHelpId: needHelpId
userId: { $ne: userId }
readBy: { $nin: [ userId ]}
.count()
###
#@params {
# studyGroupId: String
# homeworkId: String
# username: String
#}
###
@getStudyGroupHomeworkUrl: (params) ->
"#{Meteor.absoluteUrl()}study-groups/#{params.studyGroupId}/homework/#{params.homeworkId}/#{params.username}"
@insertMessage: (opts) ->
check opts,
senderId: String
senderUsername: String
receiverId: String
receiverUsername: String
text: String
needHelpId: Match.Optional String
if opts.senderUsername == opts.receiverUsername
throw new Meteor.Error('', 'Sender username is equal to receiver username. User cannot send message to himself.')
Messages.insert
senderId: opts.senderId
senderUsername: opts.senderUsername
receiverId: opts.receiverId
receiverUsername: opts.receiverUsername
text: opts.text
timestamp: Date.now()
isRead: false
needHelpId: opts.needHelpId
existingSendersList = SendersList.findOne({ senderId: opts.senderId, receiverId: opts.receiverId })
if existingSendersList
SendersList.update { senderId: opts.senderId, receiverId: opts.receiverId },
$set:
lastMsgTimestamp: Date.now()
senderUsername: opts.senderUsername #just in case
$inc: { unreadMsgsCount: 1 }
else
SendersList.insert
senderId: opts.senderId
senderUsername: opts.senderUsername
receiverId: opts.receiverId
lastMsgTimestamp: Date.now()
unreadMsgsCount: 1
@insertNotification: (data) ->
unless data.userIds?.length > 1
userIds = []
teachers = Meteor.users.find { 'roles.all': 'teacher' }
teachers.forEach (teacher) ->
if userIds.indexOf(teacher._id) == -1
userIds.push teacher._id
existing = AppNotifications.findOne
userId: data.userId
sourceId: data.sourceId
if existing
AppNotifications.update
userId: data.userId
sourceId: data.sourceId
,
$set:
userIds: data.userIds || userIds
type: data.type
isReadBy: data.isReadBy || []
timestamp: data.timestamp || Date.now()
text: data.text
else
AppNotifications.insert
userId: data.userId
userIds: data.userIds || userIds
sourceId: data.sourceId
type: data.type
isReadBy: data.isReadBy || []
timestamp: data.timestamp || Date.now()
text: data.text
@notifyTeachers: (data) ->
throw new Meteor.Error 500, 'notifyTeachers can only be called from the server' unless Meteor.isServer
teachers = Meteor.users.find
'roles.all': 'teacher'
teachers.forEach (teacher) =>
console.log 'submitting homework to teacher: ', teacher.username
#send a message only if user has student role. Student can have teacher role
if Roles.userIsInRole(data.userId, 'student', 'all') and teacher._id != @userId
if data.userId != teacher._id
App.insertNotification
userId: data.userId
sourceId: data.sourceId
type: data.type
text: data.text
@getWelcomeMessage: ->
return """
Hello, welcome to CoderMania! I would like to hear from you:\n
What is your experience with coding?\n
Why do you want to learn to code?\n
If you have any questions, you can write me here.
"""
@getEmailFooter: (opts) ->
msg = "
<p>
Watch CoderMania on social networks:
<a href=\"https://www.facebook.com/codermania\">Facebook</a>
,
<a href=\"https://twitter.com/codermania_com\">Twitter</a>
</p>
<p>
Support CoderMania on Patreon:
<a href=\"https://www.patreon.com/elfoslav\">https://www.patreon.com/elfoslav</a>
</p>
"
if opts.showUnsubscribe
msg += "
<p>
You can unsubscribe or modify your e-mail settings here:
<a href=\"http://www.codermania.com/user/settings\">http://www.codermania.com/user/settings</a>
</p>
"
return msg
@getClientErrorMessage: (err) ->
"""Something went wrong, please try again.
If you see this message again, please contact CoderMania admin: <b>PI:EMAIL:<EMAIL>END_PI</b>
and tell him what does not work. Thanks.
<br><br>
Error: #{err.reason}"""
@sendEmailAboutMessage: (opts) ->
throw new Error('Cannot call from the client') unless Meteor.isServer
sender = opts.sender
receiver = opts.receiver
messagesUrl = Meteor.absoluteUrl() + 'messages/' + sender.username
msg = """
<p>
Hi #{receiver.username},<br><br>
#{sender.username} has sent you a message on CoderMania.
Go to <a href='#{messagesUrl}'>#{messagesUrl}</a> to see the message.
</p>
<br>
#{@getEmailFooter({ showUnsubscribe: false })}
"""
Email.send
from: sender?.emails?[0]?.address
to: receiver?.emails?[0]?.address
subject: "#{sender.username} has sent you a message on CoderMania"
html: msg
@sendEmailAboutHomeworkComment: (opts) ->
throw new Error('Cannot call from the client') unless Meteor.isServer
sender = opts.sender
receiver = opts.receiver
msg = """
<p>
Hi #{receiver.username},<br><br>
#{sender.username} commented your homework on CoderMania.
</p>
<p>
Go to <a href='#{opts.homeworkUrl}'>#{opts.homeworkUrl}</a> to see the message.
</p>
<br>
#{@getEmailFooter({ showUnsubscribe: false })}
"""
Email.send
from: sender?.emails?[0]?.address
to: receiver?.emails?[0]?.address
subject: "#{sender.username} commented your homework on CoderMania"
html: msg
@evaluateOperator: (val1, operator, val2) ->
if operator is '<'
return val1 < val2
if operator is '>'
return val1 > val2
if operator is '<='
return val1 <= val2
if operator is '>='
return val1 >= val2
if operator is '=='
return `val1 == val2`
if operator is '==='
return `val1 === val2`
if operator is '!='
return `val1 != val2`
if operator is '!=='
return `val1 !== val2`
@setPageTitle: (title) ->
document.title = title + ' | CoderMania'
|
[
{
"context": " #\n # Author: Karolin Varner\n # Date 6/20/2012\n #\n # This File is used to pars",
"end": 28,
"score": 0.9998971223831177,
"start": 14,
"tag": "NAME",
"value": "Karolin Varner"
},
{
"context": " The Simple Key-Value format\n # Written in 2012 by Karolin Varner karo@cu... | js/simplekv.coffee | koraa/SimpleKV | 0 | #
# Author: Karolin Varner
# Date 6/20/2012
#
# This File is used to parse and generate the simplekv format described in simplekv.spec.
#
################################
#
# SimpleKV - The Simple Key-Value format
# Written in 2012 by Karolin Varner karo@cupdev.net
#
# The Project SimpleKV includes this file and any related content and in particular the software libraries and the SimpleKV specification bundled with this project.
# This file is part of SimpleKV.
#
# To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to SimpleKV to the public domain worldwide. is distributed without any warranty.
# You should have received a copy of the CC0 Public Domain Dedication along with this software. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
#
#######################
# CONSTANTS
PARSE_ALLOWED_PRE = [' ', '\t', '\n']
PARSE_SPERATORS_PLAIN = [' ', '\t']
PARSE_SPERATOR_MARK = ':'
PARSE_KV_SPERATOR = '\n'
PARSE_COMMENT_CHAR = '#'
#######################
# Functions
split1 = (s, r) ->
m = s.match r
return [s] if m == null
[
s[...m["index"]],
s[(m["index"] + m[0].length)...]
]
# Generates an Object with two properties: num und string (n,s)
lnum = (n, s) ->
d = new Object()
d.n = n
d.s = s
return d
# Takes a list, returns a 2dimensional list where the left column is the index+1
lnumerize = (l) ->
(lnum i, l[i-1]) for i in [1..l.length]
# Extracts all the values from a numerized list
denumerize = (l) ->
e.s for e in l
#
# Filters a list
# This function is built for tables like from lnumerize
#
lnfilter = (l, f) ->
e for e in l when f(e.s, e.n)
#
# Filters a list and prints an error message if one line did not match
# This function is built for tables like from lnumerize
#
# Arguments:
# e - The Error message
# l - A table of lines and linenumbers, see =>lnum =>lnumerize
# f - The filter function
#
elnfilter = (l, f, e="No value given", type="Syntax Error") ->
lnfilter l, (x,n) ->
return true if f(x,n)
console.error type, "in line", n, ": ", e
#
# Maps the given function on all elements of the given list
# This function is built for tables like from lnumerize
#
lnmap = (l, f) ->
lnum e.n, f(e.s, e.n) for e in l
7 #######################
# PARSER
parse = (text) ->
# PIPELINE:
# - Split the text at each line
# - Strip the whitspace at the beginning of lines
# - Remove empty lines and lines with comments
# - Split each line into key and value
# - Filter all kvpairs without a value
#
# This piplene uses the ln* functions to always include the correct linenumbers
# The first and last statement contain the code to numerize/denumerize the list
lines = lnumerize text.split PARSE_KV_SPERATOR
stripped = lnmap lines, (l) -> l.replace /^\s+/, ""
nocomment = lnfilter stripped, (l) -> l[0] != PARSE_COMMENT_CHAR && l.length > 0
dsets = lnmap nocomment, (l) -> split1 l, /:\s*:?|:?\s*:|\s+/
kvpairs = elnfilter dsets, (p) -> p.length > 1
kvs = denumerize kvpairs
# Warn about empty values
elnfilter kvpairs, ((p) -> p[1].length > 0),
"Empty value", "Warning"
#
# Put all the key value pairs in a dict. Squash all multiply invoked keys into an array
r = {}
for [k,v] in kvs
curv = r[k]
if !curv?
r[k] = v
else if curv instanceof Array
curv.push v
else
r[k] = [curv, v]
r
parseheader = (text) ->
sf = split1 text, /(\n[^\S\n]*){5}/
header: parse sf[0]
body: sf[1]
#########################
# Export
#ifndef BROWSER
exports.PARSE_ALLOWED_PRE = PARSE_ALLOWED_PRE
exports.PARSE_SPERATORS_PLAIN = PARSE_SPERATORS_PLAIN
exports.PARSE_SPERATOR_MARK = PARSE_SPERATOR_MARK
exports.PARSE_KV_SPERATOR = PARSE_KV_SPERATOR
exports.parse = parse
exports.parseheader = parseheader
#endif | 62661 | #
# Author: <NAME>
# Date 6/20/2012
#
# This File is used to parse and generate the simplekv format described in simplekv.spec.
#
################################
#
# SimpleKV - The Simple Key-Value format
# Written in 2012 by <NAME> <EMAIL>
#
# The Project SimpleKV includes this file and any related content and in particular the software libraries and the SimpleKV specification bundled with this project.
# This file is part of SimpleKV.
#
# To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to SimpleKV to the public domain worldwide. is distributed without any warranty.
# You should have received a copy of the CC0 Public Domain Dedication along with this software. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
#
#######################
# CONSTANTS
PARSE_ALLOWED_PRE = [' ', '\t', '\n']
PARSE_SPERATORS_PLAIN = [' ', '\t']
PARSE_SPERATOR_MARK = ':'
PARSE_KV_SPERATOR = '\n'
PARSE_COMMENT_CHAR = '#'
#######################
# Functions
split1 = (s, r) ->
m = s.match r
return [s] if m == null
[
s[...m["index"]],
s[(m["index"] + m[0].length)...]
]
# Generates an Object with two properties: num und string (n,s)
lnum = (n, s) ->
d = new Object()
d.n = n
d.s = s
return d
# Takes a list, returns a 2dimensional list where the left column is the index+1
lnumerize = (l) ->
(lnum i, l[i-1]) for i in [1..l.length]
# Extracts all the values from a numerized list
denumerize = (l) ->
e.s for e in l
#
# Filters a list
# This function is built for tables like from lnumerize
#
lnfilter = (l, f) ->
e for e in l when f(e.s, e.n)
#
# Filters a list and prints an error message if one line did not match
# This function is built for tables like from lnumerize
#
# Arguments:
# e - The Error message
# l - A table of lines and linenumbers, see =>lnum =>lnumerize
# f - The filter function
#
elnfilter = (l, f, e="No value given", type="Syntax Error") ->
lnfilter l, (x,n) ->
return true if f(x,n)
console.error type, "in line", n, ": ", e
#
# Maps the given function on all elements of the given list
# This function is built for tables like from lnumerize
#
lnmap = (l, f) ->
lnum e.n, f(e.s, e.n) for e in l
7 #######################
# PARSER
parse = (text) ->
# PIPELINE:
# - Split the text at each line
# - Strip the whitspace at the beginning of lines
# - Remove empty lines and lines with comments
# - Split each line into key and value
# - Filter all kvpairs without a value
#
# This piplene uses the ln* functions to always include the correct linenumbers
# The first and last statement contain the code to numerize/denumerize the list
lines = lnumerize text.split PARSE_KV_SPERATOR
stripped = lnmap lines, (l) -> l.replace /^\s+/, ""
nocomment = lnfilter stripped, (l) -> l[0] != PARSE_COMMENT_CHAR && l.length > 0
dsets = lnmap nocomment, (l) -> split1 l, /:\s*:?|:?\s*:|\s+/
kvpairs = elnfilter dsets, (p) -> p.length > 1
kvs = denumerize kvpairs
# Warn about empty values
elnfilter kvpairs, ((p) -> p[1].length > 0),
"Empty value", "Warning"
#
# Put all the key value pairs in a dict. Squash all multiply invoked keys into an array
r = {}
for [k,v] in kvs
curv = r[k]
if !curv?
r[k] = v
else if curv instanceof Array
curv.push v
else
r[k] = [curv, v]
r
parseheader = (text) ->
sf = split1 text, /(\n[^\S\n]*){5}/
header: parse sf[0]
body: sf[1]
#########################
# Export
#ifndef BROWSER
exports.PARSE_ALLOWED_PRE = PARSE_ALLOWED_PRE
exports.PARSE_SPERATORS_PLAIN = PARSE_SPERATORS_PLAIN
exports.PARSE_SPERATOR_MARK = PARSE_SPERATOR_MARK
exports.PARSE_KV_SPERATOR = PARSE_KV_SPERATOR
exports.parse = parse
exports.parseheader = parseheader
#endif | true | #
# Author: PI:NAME:<NAME>END_PI
# Date 6/20/2012
#
# This File is used to parse and generate the simplekv format described in simplekv.spec.
#
################################
#
# SimpleKV - The Simple Key-Value format
# Written in 2012 by PI:NAME:<NAME>END_PI PI:EMAIL:<EMAIL>END_PI
#
# The Project SimpleKV includes this file and any related content and in particular the software libraries and the SimpleKV specification bundled with this project.
# This file is part of SimpleKV.
#
# To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to SimpleKV to the public domain worldwide. is distributed without any warranty.
# You should have received a copy of the CC0 Public Domain Dedication along with this software. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
#
#######################
# CONSTANTS
PARSE_ALLOWED_PRE = [' ', '\t', '\n']
PARSE_SPERATORS_PLAIN = [' ', '\t']
PARSE_SPERATOR_MARK = ':'
PARSE_KV_SPERATOR = '\n'
PARSE_COMMENT_CHAR = '#'
#######################
# Functions
split1 = (s, r) ->
m = s.match r
return [s] if m == null
[
s[...m["index"]],
s[(m["index"] + m[0].length)...]
]
# Generates an Object with two properties: num und string (n,s)
lnum = (n, s) ->
d = new Object()
d.n = n
d.s = s
return d
# Takes a list, returns a 2dimensional list where the left column is the index+1
lnumerize = (l) ->
(lnum i, l[i-1]) for i in [1..l.length]
# Extracts all the values from a numerized list
denumerize = (l) ->
e.s for e in l
#
# Filters a list
# This function is built for tables like from lnumerize
#
lnfilter = (l, f) ->
e for e in l when f(e.s, e.n)
#
# Filters a list and prints an error message if one line did not match
# This function is built for tables like from lnumerize
#
# Arguments:
# e - The Error message
# l - A table of lines and linenumbers, see =>lnum =>lnumerize
# f - The filter function
#
elnfilter = (l, f, e="No value given", type="Syntax Error") ->
lnfilter l, (x,n) ->
return true if f(x,n)
console.error type, "in line", n, ": ", e
#
# Maps the given function on all elements of the given list
# This function is built for tables like from lnumerize
#
lnmap = (l, f) ->
lnum e.n, f(e.s, e.n) for e in l
7 #######################
# PARSER
parse = (text) ->
# PIPELINE:
# - Split the text at each line
# - Strip the whitspace at the beginning of lines
# - Remove empty lines and lines with comments
# - Split each line into key and value
# - Filter all kvpairs without a value
#
# This piplene uses the ln* functions to always include the correct linenumbers
# The first and last statement contain the code to numerize/denumerize the list
lines = lnumerize text.split PARSE_KV_SPERATOR
stripped = lnmap lines, (l) -> l.replace /^\s+/, ""
nocomment = lnfilter stripped, (l) -> l[0] != PARSE_COMMENT_CHAR && l.length > 0
dsets = lnmap nocomment, (l) -> split1 l, /:\s*:?|:?\s*:|\s+/
kvpairs = elnfilter dsets, (p) -> p.length > 1
kvs = denumerize kvpairs
# Warn about empty values
elnfilter kvpairs, ((p) -> p[1].length > 0),
"Empty value", "Warning"
#
# Put all the key value pairs in a dict. Squash all multiply invoked keys into an array
r = {}
for [k,v] in kvs
curv = r[k]
if !curv?
r[k] = v
else if curv instanceof Array
curv.push v
else
r[k] = [curv, v]
r
parseheader = (text) ->
sf = split1 text, /(\n[^\S\n]*){5}/
header: parse sf[0]
body: sf[1]
#########################
# Export
#ifndef BROWSER
exports.PARSE_ALLOWED_PRE = PARSE_ALLOWED_PRE
exports.PARSE_SPERATORS_PLAIN = PARSE_SPERATORS_PLAIN
exports.PARSE_SPERATOR_MARK = PARSE_SPERATOR_MARK
exports.PARSE_KV_SPERATOR = PARSE_KV_SPERATOR
exports.parse = parse
exports.parseheader = parseheader
#endif |
[
{
"context": "to']\n choices:\n aa:\n label: 'Aardvark '.repeat 10\n description: 'Basically a l",
"end": 5579,
"score": 0.9804197549819946,
"start": 5571,
"tag": "NAME",
"value": "Aardvark"
}
] | app/pages/dev-classifier/mock-data.coffee | alexbfree/Panoptes-Front-End | 0 | apiClient = require 'panoptes-client/lib/api-client'
# This is just a blank image for testing drawing tools while offline.
BLANK_IMAGE = ['data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAoAAAAHgAQMAAAA',
'PH06nAAAABlBMVEXMzMyWlpYU2uzLAAAAPUlEQVR4nO3BAQ0AAADCoPdPbQ43oAAAAAAAAAAAAA',
'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgzwCX4AAB9Dl2RwAAAABJRU5ErkJggg=='].join ''
MISC_DRAWING_DETAILS = [{
type: 'single'
question: 'Cool?'
answers: [
{label: 'Yeah'}
{label: 'Nah'}
]
}, {
type: 'multiple'
question: 'Cool stuff?'
answers: [
{label: 'Ice'}
{label: 'Snow'}
]
}, {
type: 'text'
instruction: 'Any additional comments?'
}]
workflow = apiClient.type('workflows').create
id: 'MOCK_WORKFLOW_FOR_CLASSIFIER'
configuration:
enable_subject_flags: true
multi_image_mode: 'flipbook_and_separate'
multi_image_layout: 'grid3'
invert_subject: true
first_task: 'init'
tasks:
init:
type: 'single'
question: 'Where shall we start?'
help: 'You don’t need help with this.'
answers: [
{label: 'Everything all at once! :skull:', next: 'combo'}
{label: 'Crop the image', next: 'crop'}
{label: 'Enter some text', next: 'write'}
{label: 'Single-answer question', next: 'ask'}
{label: 'Multi-answer question', next: 'features'}
{label: 'Draw stuff', next: 'draw'}
{label: 'Survey the image', next: 'survey'}
{label: 'Maybe select something', next: 'dropdown'}
{label: 'We’re done here.', next: null}
]
combo:
type: 'combo'
loosen_requirements: true
tasks: [
'crop'
'write'
'ask'
'features'
'draw'
'survey'
]
next: 'init'
crop:
type: 'crop'
instruction: 'Drag out a box around the smaller rhino.'
help: 'That’s the adorable one.'
next: 'write'
write:
type: 'text'
required: true
instruction: 'What’s the name of this animal? Is it a rhino?'
help: '''
**Example**: If you see a bee, then type "Bee"
'''
next: 'ask'
ask:
type: 'single'
question: 'Rhino starts with...'
answers: [
{label: 'Are', next: 'features'}
{label: 'Aitch', next: 'features'}
{label: 'Eye', next: 'features'}
{label: 'En', next: 'features'}
{label: 'Oh', next: 'features'}
]
features:
type: 'multiple'
question: 'What **cool** features are present? The first two?'
answers: [
{label: 'Cold water'}
{label: 'Snow'}
{label: 'Ice'}
{label: 'Sunglasses'}
]
next: 'draw'
draw:
type: 'drawing'
required: true
instruction: 'Drop a point on the rhino eyeball.'
help: '''
Do this:
* Pick a tool
* Draw something
'''
tools: [
{type: 'point', label: 'Point', color: 'red', min: 1, max: 2}
{type: 'point', label: 'Small Point', color: 'coral', size: 'small'}
{type: 'line', label: 'Line', color: 'yellow', min: 0}
{type: 'rectangle', label: 'Rectangle', color: 'lime', max: 2}
{type: 'polygon', label: 'Polygon', color: 'cyan', details: MISC_DRAWING_DETAILS}
{type: 'circle', label: 'Circle', color: 'blue', details: MISC_DRAWING_DETAILS}
{type: 'ellipse', label: 'Ellipse '.repeat(25), color: 'magenta', details: MISC_DRAWING_DETAILS}
{type: 'bezier', label: 'Bezier', color: 'orange', details: MISC_DRAWING_DETAILS}
{type: 'column', label: 'Column Rectangle', color: 'darkgreen'}
{type: 'grid', label: 'Grid', color: 'purple'}
]
next: 'survey'
survey:
type: 'survey'
images:
aa1: '//placehold.it/64x32.png?text=AA1_WIDE'
aa2: '//placehold.it/64.png?text=AA2'
ar1: '//placehold.it/64x32.png?text=AR1_WIDE'
ar2: '//placehold.it/64.png?text=AR2'
to1: '//placehold.it/64x32.png?text=TO1_WIDE'
to2: '//placehold.it/64.png?text=TO2'
so: '//placehold.it/48.png?text=so'
sp: '//placehold.it/48.png?text=sp'
st: '//placehold.it/48.png?text=st'
ba: '//placehold.it/48.png?text=ba'
wh: '//placehold.it/48.png?text=wh'
ta: '//placehold.it/48.png?text=ta'
re: '//placehold.it/48.png?text=re'
br: '//placehold.it/48.png?text=br'
bl: '//placehold.it/48.png?text=bl'
gr: '//placehold.it/48.png?text=gr'
characteristicsOrder: ['pa', 'co']
characteristics:
pa:
label: 'Pattern'
valuesOrder: ['so', 'sp', 'st', 'ba']
values:
so:
label: 'Solid'
image: 'so'
sp:
label: 'Spots'
image: 'sp'
st:
label: 'Stripes'
image: 'st'
ba:
label: 'Bands'
image: 'ba'
co:
label: 'Color'
valuesOrder: ['wh', 'ta', 're', 'br', 'bl', 'gr']
values:
wh:
label: 'White'
image: 'wh'
ta:
label: 'Tan'
image: 'ta'
re:
label: 'Red'
image: 're'
br:
label: 'Brown'
image: 'br'
bl:
label: 'Black'
image: 'bl'
gr:
label: 'Green'
image: 'gr'
choicesOrder: ['aa', 'ar', 'to']
choices:
aa:
label: 'Aardvark '.repeat 10
description: 'Basically a long-nose rabbit'
images: [
'aa1'
'aa2'
]
characteristics:
pa: ['so']
co: ['ta', 'br']
confusionsOrder: ['ar']
confusions:
ar: 'They both start with “A”, so _some_ **dummies** get these two mixed up.'
ar:
label: 'Armadillo'
description: 'A little rolly dude'
images: [
'ar1'
'ar2'
]
characteristics:
pa: ['so', 'st']
co: ['ta', 'br']
confusionsOrder: []
confusions: {}
to:
label: 'Tortoise'
description: 'Little green house with legs'
images: [
'to1'
'to2'
]
characteristics:
pa: ['so']
co: ['gr']
confusionsOrder: []
confusions: {}
questionsMap:
ar: ['ho', 'be']
to: ['ho', 'be', 'in', 'bt']
questionsOrder: ['ho', 'be', 'in', 'hr']
questions:
ho:
required: true
multiple: false
label: 'How many?'
answersOrder: ['one', 'two', 'many']
answers:
one:
label: '1'
two:
label: '2'
many:
label: '3+'
be:
required: true
multiple: true
label: 'Any activity?'
answersOrder: ['mo', 'ea', 'in']
answers:
mo:
label: 'Moving'
ea:
label: 'Eating'
in:
label: 'Interacting'
in:
required: false
label: 'Any injuries?'
answersOrder: ['y', 'n']
answers:
y:
label: 'Yep'
n:
label: 'Nope'
hr:
required: false
multiple: true
label: 'Horns (toggle)'
answersOrder: ['y']
answers:
y:
label: 'Present'
bt:
required: true
multiple: false
label: 'Are tortoises awesome?'
answersOrder: ['y','Y']
answers:
y:
label: 'yes'
Y:
label: 'HECK YES'
next: 'init'
dropdown:
next: 'write'
type: 'dropdown'
instruction: "Select something, or if it's not an option - write it!"
selects: [
{
id: "cd1c7a8a13726"
title: "Country"
required: true
options: {
'*': [
{value: "USA", label: "United States of America"},
{value: "Canada", label: "Canada"},
{value: "Mypos", label: "Mypos"}
]
}
},
{
id: "26971f135cb4b"
title: "State/Province"
required: true
allowCreate: false
condition: "cd1c7a8a13726"
options: {
'USA': [
{value: "HI", label: "Hawaii"},
{value: "IL", label: "Illinois"},
{value: "WI", label: "Wisconsin"}
],
'Canada': [
{value: "AB", label: "Alberta"},
{value: "ON", label: "Ontario"},
{value: "QC", label: "Quebec"}
],
'Mypos': [
{value: "Gondor", label: "Gondor"},
{value: "Rohan", label: "Rohan"},
{value: "Shire", label: "Shire"}
]
}
},
{
id: "8f7afd193da42"
title: "County"
allowCreate: false
condition: "26971f135cb4b"
options: {
'USA;HI': [
{value: "Honolulu", label: "Honolulu"},
{value: "Maui", label: "Maui"}
],
'USA;IL': [
{value: "Cook", label: "Cook"},
{value: "Lake", label: "Lake"}
],
'Canada;AB': [
{value: "Rocky View", label: "Rocky View"},
{value: "Parkland", label: "Parkland"}
],
'Canada;QC': [
{value: "Montreal", label: "Montreal"},
{value: "Capitale-Nationale", label: "Capitale-Nationale"}
],
'Mypos;Rohan': [
{value: "Gotham County", label: "Gotham County"},
{value: "Metropolis County", label: "Metropolis County"}
],
'Mypos;Shire': [
{value: "Municipality of Bikini Bottom", label: "Municipality of Bikini Bottom"},
{value: "Elbonia", label: "Elbonia"}
]
}
},
{
id: "fdd12d9f1ad52"
title: "City"
allowCreate: false
condition: "8f7afd193da42"
options: {
'USA;HI;Honolulu': [
{value: "Honolulu", label: "Honolulu city"}
],
'USA;IL;Cook': [
{value: "Chicago", label: "Chicago"},
{value: "Evanston", label: "Evanston"}
],
'USA;IL;Lake': [
{value: "Waukegan", label: "Waukegan"},
{value: "Wheeling", label: "Wheeling"}
],
'Canada;AB;Rocky View': [
{value: "Airdrie", label: "Airdrie"},
{value: "Chestermere", label: "Chestermere"}
],
'Canada;QC;Capitale-Nationale': [
{value: "Quebec City", label: "Quebec City"},
{value: "Saint-Raymond", label: "Saint-Raymond"}
],
'Mypos;Rohan;Gotham County': [
{value: "Gotham", label: "Gotham"}
],
'Mypos;Rohan;Metropolis County': [
{value: "Metropolis", label: "Metropolis"}
],
'Mypos;Shire;Municipality of Bikini Bottom': [
{value: "Bikini Bottom", label: "Bikini Bottom"}
],
'Mypos;Shire;Elbonia': [
{value: "Townbert", label: "Townbert"}
]
}
},
{
id: "e45fdf113f07e"
title: "Best State Sports Team"
allowCreate: true
condition: "26971f135cb4b"
options: {
'USA;HI': [
{value: "59d8b49f6a0bc", label: "Sharks"},
{value: "1df102313d355", label: "Rainbow Warriors"}
],
'USA;IL': [
{value: "b085abfe3c4d9", label: "Bears"},
{value: "964419c0f3ade", label: "Bulls"},
{value: "e4430cd2c0be", label: "Blackhawks"}
],
'Canada;AB': [
{value: "6df716c19bf73", label: "Oilers"},
{value: "23843c7b8ca3a", label: "Flames"}
],
'Canada;QC': [
{value: "105ee8e45828c", label: "Canadiens"},
{value: "ade89b3bed25c", label: "Expos"}
],
'Mypos;Shire': [
{value: "084f28a8999be", label: "Mighty Ducks"},
{value: "b52ad46b3818e", label: "Little Giants"}
],
'Mypos;Rohan': [
{value: "df7cb03611f08", label: "Shelbyville Shelbyvillians"},
{value: "fac0841caac4e", label: "Springfield Isotopes"}
]
}
}
]
# Bulk up the survey task a bit:
'abcdefghijlkmnopqrstuvwxyz1234'.split('').forEach (x, i) ->
xi = x + i
workflow.tasks.survey.choicesOrder.push xi
workflow.tasks.survey.choices[xi] =
label: xi
description: xi
images: [Object.keys(workflow.tasks.survey.images)[Math.floor Math.random() * Object.keys(workflow.tasks.survey.images).length]]
characteristics: do ->
out = {}
workflow.tasks.survey.characteristicsOrder.forEach (charID) ->
out[charID] = workflow.tasks.survey.characteristics[charID].valuesOrder.filter ->
Math.random() < 0.5
out
confusionsOrder: []
confusions: {}
subject = apiClient.type('subjects').create
id: 'MOCK_SUBJECT_FOR_CLASSIFIER'
# Images originally from lorempixel.com shared under CC BY-SA,
# but the service is often slow and/or fails to load at all.
# Noted original source next to each.
locations: if navigator?.onLine
[
{'image/jpeg': "#{window.location.origin}/assets/dev-classifier/landscape.jpeg"} # //lorempixel.com/900/600/animals/1
{'image/jpeg': "#{window.location.origin}/assets/dev-classifier/portrait.jpeg"} # //lorempixel.com/600/900/animals/2
{'image/jpeg': "#{window.location.origin}/assets/dev-classifier/very-wide.jpeg"} # //lorempixel.com/1900/1000/animals/3
{'image/jpeg': "#{window.location.origin}/assets/dev-classifier/very-tall.jpeg"} # //lorempixel.com/1000/1900/animals/4
{'image/jpeg': "#{window.location.origin}/assets/dev-classifier/small.jpeg"} # //lorempixel.com/400/300/animals/4
]
else
[
{'image/png': BLANK_IMAGE}
]
metadata:
'Capture date': '5 Feb, 2015'
'Region': 'Chicago, IL'
expert_classification_data:
MOCK_WORKFLOW_FOR_CLASSIFIER: apiClient.type('classifications').create
annotations: [{
task: 'init'
value: 0
}, {
task: 'crop'
value: {
x: 20
y: 57
width: 224
height: 142
}
}, {
task: 'write'
value: 'Rhino'
}, {
task: 'ask'
value: 0
}, {
task: 'features'
value: [0, 1]
}, {
task: 'draw'
value: [{
tool: 0
frame: 0
x: 207
y: 134
details: [{
value: 0
}, {
value: []
}, {
value: ''
}]
}]
}, {
task: 'survey'
value: []
}, {
task: 'init'
value: 6
}]
project = apiClient.type('projects').create
id: 'MOCK_PROJECT_FOR_CLASSIFIER'
title: "The Dev Classifier"
experimental_tools: ['pan and zoom']
preferences = apiClient.type('project_preferences').create
preferences: {}
classification = apiClient.type('classifications').create
annotations: []
metadata: {}
links:
project: project.id
workflow: workflow.id
subjects: [subject.id]
_workflow: workflow # TEMP
_subjects: [subject] # TEMP
module.exports = {workflow, subject, classification, project, preferences}
window?.mockClassifierData = module.exports
| 101681 | apiClient = require 'panoptes-client/lib/api-client'
# This is just a blank image for testing drawing tools while offline.
BLANK_IMAGE = ['data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAoAAAAHgAQMAAAA',
'PH06nAAAABlBMVEXMzMyWlpYU2uzLAAAAPUlEQVR4nO3BAQ0AAADCoPdPbQ43oAAAAAAAAAAAAA',
'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgzwCX4AAB9Dl2RwAAAABJRU5ErkJggg=='].join ''
MISC_DRAWING_DETAILS = [{
type: 'single'
question: 'Cool?'
answers: [
{label: 'Yeah'}
{label: 'Nah'}
]
}, {
type: 'multiple'
question: 'Cool stuff?'
answers: [
{label: 'Ice'}
{label: 'Snow'}
]
}, {
type: 'text'
instruction: 'Any additional comments?'
}]
workflow = apiClient.type('workflows').create
id: 'MOCK_WORKFLOW_FOR_CLASSIFIER'
configuration:
enable_subject_flags: true
multi_image_mode: 'flipbook_and_separate'
multi_image_layout: 'grid3'
invert_subject: true
first_task: 'init'
tasks:
init:
type: 'single'
question: 'Where shall we start?'
help: 'You don’t need help with this.'
answers: [
{label: 'Everything all at once! :skull:', next: 'combo'}
{label: 'Crop the image', next: 'crop'}
{label: 'Enter some text', next: 'write'}
{label: 'Single-answer question', next: 'ask'}
{label: 'Multi-answer question', next: 'features'}
{label: 'Draw stuff', next: 'draw'}
{label: 'Survey the image', next: 'survey'}
{label: 'Maybe select something', next: 'dropdown'}
{label: 'We’re done here.', next: null}
]
combo:
type: 'combo'
loosen_requirements: true
tasks: [
'crop'
'write'
'ask'
'features'
'draw'
'survey'
]
next: 'init'
crop:
type: 'crop'
instruction: 'Drag out a box around the smaller rhino.'
help: 'That’s the adorable one.'
next: 'write'
write:
type: 'text'
required: true
instruction: 'What’s the name of this animal? Is it a rhino?'
help: '''
**Example**: If you see a bee, then type "Bee"
'''
next: 'ask'
ask:
type: 'single'
question: 'Rhino starts with...'
answers: [
{label: 'Are', next: 'features'}
{label: 'Aitch', next: 'features'}
{label: 'Eye', next: 'features'}
{label: 'En', next: 'features'}
{label: 'Oh', next: 'features'}
]
features:
type: 'multiple'
question: 'What **cool** features are present? The first two?'
answers: [
{label: 'Cold water'}
{label: 'Snow'}
{label: 'Ice'}
{label: 'Sunglasses'}
]
next: 'draw'
draw:
type: 'drawing'
required: true
instruction: 'Drop a point on the rhino eyeball.'
help: '''
Do this:
* Pick a tool
* Draw something
'''
tools: [
{type: 'point', label: 'Point', color: 'red', min: 1, max: 2}
{type: 'point', label: 'Small Point', color: 'coral', size: 'small'}
{type: 'line', label: 'Line', color: 'yellow', min: 0}
{type: 'rectangle', label: 'Rectangle', color: 'lime', max: 2}
{type: 'polygon', label: 'Polygon', color: 'cyan', details: MISC_DRAWING_DETAILS}
{type: 'circle', label: 'Circle', color: 'blue', details: MISC_DRAWING_DETAILS}
{type: 'ellipse', label: 'Ellipse '.repeat(25), color: 'magenta', details: MISC_DRAWING_DETAILS}
{type: 'bezier', label: 'Bezier', color: 'orange', details: MISC_DRAWING_DETAILS}
{type: 'column', label: 'Column Rectangle', color: 'darkgreen'}
{type: 'grid', label: 'Grid', color: 'purple'}
]
next: 'survey'
survey:
type: 'survey'
images:
aa1: '//placehold.it/64x32.png?text=AA1_WIDE'
aa2: '//placehold.it/64.png?text=AA2'
ar1: '//placehold.it/64x32.png?text=AR1_WIDE'
ar2: '//placehold.it/64.png?text=AR2'
to1: '//placehold.it/64x32.png?text=TO1_WIDE'
to2: '//placehold.it/64.png?text=TO2'
so: '//placehold.it/48.png?text=so'
sp: '//placehold.it/48.png?text=sp'
st: '//placehold.it/48.png?text=st'
ba: '//placehold.it/48.png?text=ba'
wh: '//placehold.it/48.png?text=wh'
ta: '//placehold.it/48.png?text=ta'
re: '//placehold.it/48.png?text=re'
br: '//placehold.it/48.png?text=br'
bl: '//placehold.it/48.png?text=bl'
gr: '//placehold.it/48.png?text=gr'
characteristicsOrder: ['pa', 'co']
characteristics:
pa:
label: 'Pattern'
valuesOrder: ['so', 'sp', 'st', 'ba']
values:
so:
label: 'Solid'
image: 'so'
sp:
label: 'Spots'
image: 'sp'
st:
label: 'Stripes'
image: 'st'
ba:
label: 'Bands'
image: 'ba'
co:
label: 'Color'
valuesOrder: ['wh', 'ta', 're', 'br', 'bl', 'gr']
values:
wh:
label: 'White'
image: 'wh'
ta:
label: 'Tan'
image: 'ta'
re:
label: 'Red'
image: 're'
br:
label: 'Brown'
image: 'br'
bl:
label: 'Black'
image: 'bl'
gr:
label: 'Green'
image: 'gr'
choicesOrder: ['aa', 'ar', 'to']
choices:
aa:
label: '<NAME> '.repeat 10
description: 'Basically a long-nose rabbit'
images: [
'aa1'
'aa2'
]
characteristics:
pa: ['so']
co: ['ta', 'br']
confusionsOrder: ['ar']
confusions:
ar: 'They both start with “A”, so _some_ **dummies** get these two mixed up.'
ar:
label: 'Armadillo'
description: 'A little rolly dude'
images: [
'ar1'
'ar2'
]
characteristics:
pa: ['so', 'st']
co: ['ta', 'br']
confusionsOrder: []
confusions: {}
to:
label: 'Tortoise'
description: 'Little green house with legs'
images: [
'to1'
'to2'
]
characteristics:
pa: ['so']
co: ['gr']
confusionsOrder: []
confusions: {}
questionsMap:
ar: ['ho', 'be']
to: ['ho', 'be', 'in', 'bt']
questionsOrder: ['ho', 'be', 'in', 'hr']
questions:
ho:
required: true
multiple: false
label: 'How many?'
answersOrder: ['one', 'two', 'many']
answers:
one:
label: '1'
two:
label: '2'
many:
label: '3+'
be:
required: true
multiple: true
label: 'Any activity?'
answersOrder: ['mo', 'ea', 'in']
answers:
mo:
label: 'Moving'
ea:
label: 'Eating'
in:
label: 'Interacting'
in:
required: false
label: 'Any injuries?'
answersOrder: ['y', 'n']
answers:
y:
label: 'Yep'
n:
label: 'Nope'
hr:
required: false
multiple: true
label: 'Horns (toggle)'
answersOrder: ['y']
answers:
y:
label: 'Present'
bt:
required: true
multiple: false
label: 'Are tortoises awesome?'
answersOrder: ['y','Y']
answers:
y:
label: 'yes'
Y:
label: 'HECK YES'
next: 'init'
dropdown:
next: 'write'
type: 'dropdown'
instruction: "Select something, or if it's not an option - write it!"
selects: [
{
id: "cd1c7a8a13726"
title: "Country"
required: true
options: {
'*': [
{value: "USA", label: "United States of America"},
{value: "Canada", label: "Canada"},
{value: "Mypos", label: "Mypos"}
]
}
},
{
id: "26971f135cb4b"
title: "State/Province"
required: true
allowCreate: false
condition: "cd1c7a8a13726"
options: {
'USA': [
{value: "HI", label: "Hawaii"},
{value: "IL", label: "Illinois"},
{value: "WI", label: "Wisconsin"}
],
'Canada': [
{value: "AB", label: "Alberta"},
{value: "ON", label: "Ontario"},
{value: "QC", label: "Quebec"}
],
'Mypos': [
{value: "Gondor", label: "Gondor"},
{value: "Rohan", label: "Rohan"},
{value: "Shire", label: "Shire"}
]
}
},
{
id: "8f7afd193da42"
title: "County"
allowCreate: false
condition: "26971f135cb4b"
options: {
'USA;HI': [
{value: "Honolulu", label: "Honolulu"},
{value: "Maui", label: "Maui"}
],
'USA;IL': [
{value: "Cook", label: "Cook"},
{value: "Lake", label: "Lake"}
],
'Canada;AB': [
{value: "Rocky View", label: "Rocky View"},
{value: "Parkland", label: "Parkland"}
],
'Canada;QC': [
{value: "Montreal", label: "Montreal"},
{value: "Capitale-Nationale", label: "Capitale-Nationale"}
],
'Mypos;Rohan': [
{value: "Gotham County", label: "Gotham County"},
{value: "Metropolis County", label: "Metropolis County"}
],
'Mypos;Shire': [
{value: "Municipality of Bikini Bottom", label: "Municipality of Bikini Bottom"},
{value: "Elbonia", label: "Elbonia"}
]
}
},
{
id: "fdd12d9f1ad52"
title: "City"
allowCreate: false
condition: "8f7afd193da42"
options: {
'USA;HI;Honolulu': [
{value: "Honolulu", label: "Honolulu city"}
],
'USA;IL;Cook': [
{value: "Chicago", label: "Chicago"},
{value: "Evanston", label: "Evanston"}
],
'USA;IL;Lake': [
{value: "Waukegan", label: "Waukegan"},
{value: "Wheeling", label: "Wheeling"}
],
'Canada;AB;Rocky View': [
{value: "Airdrie", label: "Airdrie"},
{value: "Chestermere", label: "Chestermere"}
],
'Canada;QC;Capitale-Nationale': [
{value: "Quebec City", label: "Quebec City"},
{value: "Saint-Raymond", label: "Saint-Raymond"}
],
'Mypos;Rohan;Gotham County': [
{value: "Gotham", label: "Gotham"}
],
'Mypos;Rohan;Metropolis County': [
{value: "Metropolis", label: "Metropolis"}
],
'Mypos;Shire;Municipality of Bikini Bottom': [
{value: "Bikini Bottom", label: "Bikini Bottom"}
],
'Mypos;Shire;Elbonia': [
{value: "Townbert", label: "Townbert"}
]
}
},
{
id: "e45fdf113f07e"
title: "Best State Sports Team"
allowCreate: true
condition: "26971f135cb4b"
options: {
'USA;HI': [
{value: "59d8b49f6a0bc", label: "Sharks"},
{value: "1df102313d355", label: "Rainbow Warriors"}
],
'USA;IL': [
{value: "b085abfe3c4d9", label: "Bears"},
{value: "964419c0f3ade", label: "Bulls"},
{value: "e4430cd2c0be", label: "Blackhawks"}
],
'Canada;AB': [
{value: "6df716c19bf73", label: "Oilers"},
{value: "23843c7b8ca3a", label: "Flames"}
],
'Canada;QC': [
{value: "105ee8e45828c", label: "Canadiens"},
{value: "ade89b3bed25c", label: "Expos"}
],
'Mypos;Shire': [
{value: "084f28a8999be", label: "Mighty Ducks"},
{value: "b52ad46b3818e", label: "Little Giants"}
],
'Mypos;Rohan': [
{value: "df7cb03611f08", label: "Shelbyville Shelbyvillians"},
{value: "fac0841caac4e", label: "Springfield Isotopes"}
]
}
}
]
# Bulk up the survey task a bit:
'abcdefghijlkmnopqrstuvwxyz1234'.split('').forEach (x, i) ->
xi = x + i
workflow.tasks.survey.choicesOrder.push xi
workflow.tasks.survey.choices[xi] =
label: xi
description: xi
images: [Object.keys(workflow.tasks.survey.images)[Math.floor Math.random() * Object.keys(workflow.tasks.survey.images).length]]
characteristics: do ->
out = {}
workflow.tasks.survey.characteristicsOrder.forEach (charID) ->
out[charID] = workflow.tasks.survey.characteristics[charID].valuesOrder.filter ->
Math.random() < 0.5
out
confusionsOrder: []
confusions: {}
subject = apiClient.type('subjects').create
id: 'MOCK_SUBJECT_FOR_CLASSIFIER'
# Images originally from lorempixel.com shared under CC BY-SA,
# but the service is often slow and/or fails to load at all.
# Noted original source next to each.
locations: if navigator?.onLine
[
{'image/jpeg': "#{window.location.origin}/assets/dev-classifier/landscape.jpeg"} # //lorempixel.com/900/600/animals/1
{'image/jpeg': "#{window.location.origin}/assets/dev-classifier/portrait.jpeg"} # //lorempixel.com/600/900/animals/2
{'image/jpeg': "#{window.location.origin}/assets/dev-classifier/very-wide.jpeg"} # //lorempixel.com/1900/1000/animals/3
{'image/jpeg': "#{window.location.origin}/assets/dev-classifier/very-tall.jpeg"} # //lorempixel.com/1000/1900/animals/4
{'image/jpeg': "#{window.location.origin}/assets/dev-classifier/small.jpeg"} # //lorempixel.com/400/300/animals/4
]
else
[
{'image/png': BLANK_IMAGE}
]
metadata:
'Capture date': '5 Feb, 2015'
'Region': 'Chicago, IL'
expert_classification_data:
MOCK_WORKFLOW_FOR_CLASSIFIER: apiClient.type('classifications').create
annotations: [{
task: 'init'
value: 0
}, {
task: 'crop'
value: {
x: 20
y: 57
width: 224
height: 142
}
}, {
task: 'write'
value: 'Rhino'
}, {
task: 'ask'
value: 0
}, {
task: 'features'
value: [0, 1]
}, {
task: 'draw'
value: [{
tool: 0
frame: 0
x: 207
y: 134
details: [{
value: 0
}, {
value: []
}, {
value: ''
}]
}]
}, {
task: 'survey'
value: []
}, {
task: 'init'
value: 6
}]
project = apiClient.type('projects').create
id: 'MOCK_PROJECT_FOR_CLASSIFIER'
title: "The Dev Classifier"
experimental_tools: ['pan and zoom']
preferences = apiClient.type('project_preferences').create
preferences: {}
classification = apiClient.type('classifications').create
annotations: []
metadata: {}
links:
project: project.id
workflow: workflow.id
subjects: [subject.id]
_workflow: workflow # TEMP
_subjects: [subject] # TEMP
module.exports = {workflow, subject, classification, project, preferences}
window?.mockClassifierData = module.exports
| true | apiClient = require 'panoptes-client/lib/api-client'
# This is just a blank image for testing drawing tools while offline.
BLANK_IMAGE = ['data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAoAAAAHgAQMAAAA',
'PH06nAAAABlBMVEXMzMyWlpYU2uzLAAAAPUlEQVR4nO3BAQ0AAADCoPdPbQ43oAAAAAAAAAAAAA',
'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgzwCX4AAB9Dl2RwAAAABJRU5ErkJggg=='].join ''
MISC_DRAWING_DETAILS = [{
type: 'single'
question: 'Cool?'
answers: [
{label: 'Yeah'}
{label: 'Nah'}
]
}, {
type: 'multiple'
question: 'Cool stuff?'
answers: [
{label: 'Ice'}
{label: 'Snow'}
]
}, {
type: 'text'
instruction: 'Any additional comments?'
}]
workflow = apiClient.type('workflows').create
id: 'MOCK_WORKFLOW_FOR_CLASSIFIER'
configuration:
enable_subject_flags: true
multi_image_mode: 'flipbook_and_separate'
multi_image_layout: 'grid3'
invert_subject: true
first_task: 'init'
tasks:
init:
type: 'single'
question: 'Where shall we start?'
help: 'You don’t need help with this.'
answers: [
{label: 'Everything all at once! :skull:', next: 'combo'}
{label: 'Crop the image', next: 'crop'}
{label: 'Enter some text', next: 'write'}
{label: 'Single-answer question', next: 'ask'}
{label: 'Multi-answer question', next: 'features'}
{label: 'Draw stuff', next: 'draw'}
{label: 'Survey the image', next: 'survey'}
{label: 'Maybe select something', next: 'dropdown'}
{label: 'We’re done here.', next: null}
]
combo:
type: 'combo'
loosen_requirements: true
tasks: [
'crop'
'write'
'ask'
'features'
'draw'
'survey'
]
next: 'init'
crop:
type: 'crop'
instruction: 'Drag out a box around the smaller rhino.'
help: 'That’s the adorable one.'
next: 'write'
write:
type: 'text'
required: true
instruction: 'What’s the name of this animal? Is it a rhino?'
help: '''
**Example**: If you see a bee, then type "Bee"
'''
next: 'ask'
ask:
type: 'single'
question: 'Rhino starts with...'
answers: [
{label: 'Are', next: 'features'}
{label: 'Aitch', next: 'features'}
{label: 'Eye', next: 'features'}
{label: 'En', next: 'features'}
{label: 'Oh', next: 'features'}
]
features:
type: 'multiple'
question: 'What **cool** features are present? The first two?'
answers: [
{label: 'Cold water'}
{label: 'Snow'}
{label: 'Ice'}
{label: 'Sunglasses'}
]
next: 'draw'
draw:
type: 'drawing'
required: true
instruction: 'Drop a point on the rhino eyeball.'
help: '''
Do this:
* Pick a tool
* Draw something
'''
tools: [
{type: 'point', label: 'Point', color: 'red', min: 1, max: 2}
{type: 'point', label: 'Small Point', color: 'coral', size: 'small'}
{type: 'line', label: 'Line', color: 'yellow', min: 0}
{type: 'rectangle', label: 'Rectangle', color: 'lime', max: 2}
{type: 'polygon', label: 'Polygon', color: 'cyan', details: MISC_DRAWING_DETAILS}
{type: 'circle', label: 'Circle', color: 'blue', details: MISC_DRAWING_DETAILS}
{type: 'ellipse', label: 'Ellipse '.repeat(25), color: 'magenta', details: MISC_DRAWING_DETAILS}
{type: 'bezier', label: 'Bezier', color: 'orange', details: MISC_DRAWING_DETAILS}
{type: 'column', label: 'Column Rectangle', color: 'darkgreen'}
{type: 'grid', label: 'Grid', color: 'purple'}
]
next: 'survey'
survey:
type: 'survey'
images:
aa1: '//placehold.it/64x32.png?text=AA1_WIDE'
aa2: '//placehold.it/64.png?text=AA2'
ar1: '//placehold.it/64x32.png?text=AR1_WIDE'
ar2: '//placehold.it/64.png?text=AR2'
to1: '//placehold.it/64x32.png?text=TO1_WIDE'
to2: '//placehold.it/64.png?text=TO2'
so: '//placehold.it/48.png?text=so'
sp: '//placehold.it/48.png?text=sp'
st: '//placehold.it/48.png?text=st'
ba: '//placehold.it/48.png?text=ba'
wh: '//placehold.it/48.png?text=wh'
ta: '//placehold.it/48.png?text=ta'
re: '//placehold.it/48.png?text=re'
br: '//placehold.it/48.png?text=br'
bl: '//placehold.it/48.png?text=bl'
gr: '//placehold.it/48.png?text=gr'
characteristicsOrder: ['pa', 'co']
characteristics:
pa:
label: 'Pattern'
valuesOrder: ['so', 'sp', 'st', 'ba']
values:
so:
label: 'Solid'
image: 'so'
sp:
label: 'Spots'
image: 'sp'
st:
label: 'Stripes'
image: 'st'
ba:
label: 'Bands'
image: 'ba'
co:
label: 'Color'
valuesOrder: ['wh', 'ta', 're', 'br', 'bl', 'gr']
values:
wh:
label: 'White'
image: 'wh'
ta:
label: 'Tan'
image: 'ta'
re:
label: 'Red'
image: 're'
br:
label: 'Brown'
image: 'br'
bl:
label: 'Black'
image: 'bl'
gr:
label: 'Green'
image: 'gr'
choicesOrder: ['aa', 'ar', 'to']
choices:
aa:
label: 'PI:NAME:<NAME>END_PI '.repeat 10
description: 'Basically a long-nose rabbit'
images: [
'aa1'
'aa2'
]
characteristics:
pa: ['so']
co: ['ta', 'br']
confusionsOrder: ['ar']
confusions:
ar: 'They both start with “A”, so _some_ **dummies** get these two mixed up.'
ar:
label: 'Armadillo'
description: 'A little rolly dude'
images: [
'ar1'
'ar2'
]
characteristics:
pa: ['so', 'st']
co: ['ta', 'br']
confusionsOrder: []
confusions: {}
to:
label: 'Tortoise'
description: 'Little green house with legs'
images: [
'to1'
'to2'
]
characteristics:
pa: ['so']
co: ['gr']
confusionsOrder: []
confusions: {}
questionsMap:
ar: ['ho', 'be']
to: ['ho', 'be', 'in', 'bt']
questionsOrder: ['ho', 'be', 'in', 'hr']
questions:
ho:
required: true
multiple: false
label: 'How many?'
answersOrder: ['one', 'two', 'many']
answers:
one:
label: '1'
two:
label: '2'
many:
label: '3+'
be:
required: true
multiple: true
label: 'Any activity?'
answersOrder: ['mo', 'ea', 'in']
answers:
mo:
label: 'Moving'
ea:
label: 'Eating'
in:
label: 'Interacting'
in:
required: false
label: 'Any injuries?'
answersOrder: ['y', 'n']
answers:
y:
label: 'Yep'
n:
label: 'Nope'
hr:
required: false
multiple: true
label: 'Horns (toggle)'
answersOrder: ['y']
answers:
y:
label: 'Present'
bt:
required: true
multiple: false
label: 'Are tortoises awesome?'
answersOrder: ['y','Y']
answers:
y:
label: 'yes'
Y:
label: 'HECK YES'
next: 'init'
dropdown:
next: 'write'
type: 'dropdown'
instruction: "Select something, or if it's not an option - write it!"
selects: [
{
id: "cd1c7a8a13726"
title: "Country"
required: true
options: {
'*': [
{value: "USA", label: "United States of America"},
{value: "Canada", label: "Canada"},
{value: "Mypos", label: "Mypos"}
]
}
},
{
id: "26971f135cb4b"
title: "State/Province"
required: true
allowCreate: false
condition: "cd1c7a8a13726"
options: {
'USA': [
{value: "HI", label: "Hawaii"},
{value: "IL", label: "Illinois"},
{value: "WI", label: "Wisconsin"}
],
'Canada': [
{value: "AB", label: "Alberta"},
{value: "ON", label: "Ontario"},
{value: "QC", label: "Quebec"}
],
'Mypos': [
{value: "Gondor", label: "Gondor"},
{value: "Rohan", label: "Rohan"},
{value: "Shire", label: "Shire"}
]
}
},
{
id: "8f7afd193da42"
title: "County"
allowCreate: false
condition: "26971f135cb4b"
options: {
'USA;HI': [
{value: "Honolulu", label: "Honolulu"},
{value: "Maui", label: "Maui"}
],
'USA;IL': [
{value: "Cook", label: "Cook"},
{value: "Lake", label: "Lake"}
],
'Canada;AB': [
{value: "Rocky View", label: "Rocky View"},
{value: "Parkland", label: "Parkland"}
],
'Canada;QC': [
{value: "Montreal", label: "Montreal"},
{value: "Capitale-Nationale", label: "Capitale-Nationale"}
],
'Mypos;Rohan': [
{value: "Gotham County", label: "Gotham County"},
{value: "Metropolis County", label: "Metropolis County"}
],
'Mypos;Shire': [
{value: "Municipality of Bikini Bottom", label: "Municipality of Bikini Bottom"},
{value: "Elbonia", label: "Elbonia"}
]
}
},
{
id: "fdd12d9f1ad52"
title: "City"
allowCreate: false
condition: "8f7afd193da42"
options: {
'USA;HI;Honolulu': [
{value: "Honolulu", label: "Honolulu city"}
],
'USA;IL;Cook': [
{value: "Chicago", label: "Chicago"},
{value: "Evanston", label: "Evanston"}
],
'USA;IL;Lake': [
{value: "Waukegan", label: "Waukegan"},
{value: "Wheeling", label: "Wheeling"}
],
'Canada;AB;Rocky View': [
{value: "Airdrie", label: "Airdrie"},
{value: "Chestermere", label: "Chestermere"}
],
'Canada;QC;Capitale-Nationale': [
{value: "Quebec City", label: "Quebec City"},
{value: "Saint-Raymond", label: "Saint-Raymond"}
],
'Mypos;Rohan;Gotham County': [
{value: "Gotham", label: "Gotham"}
],
'Mypos;Rohan;Metropolis County': [
{value: "Metropolis", label: "Metropolis"}
],
'Mypos;Shire;Municipality of Bikini Bottom': [
{value: "Bikini Bottom", label: "Bikini Bottom"}
],
'Mypos;Shire;Elbonia': [
{value: "Townbert", label: "Townbert"}
]
}
},
{
id: "e45fdf113f07e"
title: "Best State Sports Team"
allowCreate: true
condition: "26971f135cb4b"
options: {
'USA;HI': [
{value: "59d8b49f6a0bc", label: "Sharks"},
{value: "1df102313d355", label: "Rainbow Warriors"}
],
'USA;IL': [
{value: "b085abfe3c4d9", label: "Bears"},
{value: "964419c0f3ade", label: "Bulls"},
{value: "e4430cd2c0be", label: "Blackhawks"}
],
'Canada;AB': [
{value: "6df716c19bf73", label: "Oilers"},
{value: "23843c7b8ca3a", label: "Flames"}
],
'Canada;QC': [
{value: "105ee8e45828c", label: "Canadiens"},
{value: "ade89b3bed25c", label: "Expos"}
],
'Mypos;Shire': [
{value: "084f28a8999be", label: "Mighty Ducks"},
{value: "b52ad46b3818e", label: "Little Giants"}
],
'Mypos;Rohan': [
{value: "df7cb03611f08", label: "Shelbyville Shelbyvillians"},
{value: "fac0841caac4e", label: "Springfield Isotopes"}
]
}
}
]
# Bulk up the survey task a bit:
'abcdefghijlkmnopqrstuvwxyz1234'.split('').forEach (x, i) ->
xi = x + i
workflow.tasks.survey.choicesOrder.push xi
workflow.tasks.survey.choices[xi] =
label: xi
description: xi
images: [Object.keys(workflow.tasks.survey.images)[Math.floor Math.random() * Object.keys(workflow.tasks.survey.images).length]]
characteristics: do ->
out = {}
workflow.tasks.survey.characteristicsOrder.forEach (charID) ->
out[charID] = workflow.tasks.survey.characteristics[charID].valuesOrder.filter ->
Math.random() < 0.5
out
confusionsOrder: []
confusions: {}
subject = apiClient.type('subjects').create
id: 'MOCK_SUBJECT_FOR_CLASSIFIER'
# Images originally from lorempixel.com shared under CC BY-SA,
# but the service is often slow and/or fails to load at all.
# Noted original source next to each.
locations: if navigator?.onLine
[
{'image/jpeg': "#{window.location.origin}/assets/dev-classifier/landscape.jpeg"} # //lorempixel.com/900/600/animals/1
{'image/jpeg': "#{window.location.origin}/assets/dev-classifier/portrait.jpeg"} # //lorempixel.com/600/900/animals/2
{'image/jpeg': "#{window.location.origin}/assets/dev-classifier/very-wide.jpeg"} # //lorempixel.com/1900/1000/animals/3
{'image/jpeg': "#{window.location.origin}/assets/dev-classifier/very-tall.jpeg"} # //lorempixel.com/1000/1900/animals/4
{'image/jpeg': "#{window.location.origin}/assets/dev-classifier/small.jpeg"} # //lorempixel.com/400/300/animals/4
]
else
[
{'image/png': BLANK_IMAGE}
]
metadata:
'Capture date': '5 Feb, 2015'
'Region': 'Chicago, IL'
expert_classification_data:
MOCK_WORKFLOW_FOR_CLASSIFIER: apiClient.type('classifications').create
annotations: [{
task: 'init'
value: 0
}, {
task: 'crop'
value: {
x: 20
y: 57
width: 224
height: 142
}
}, {
task: 'write'
value: 'Rhino'
}, {
task: 'ask'
value: 0
}, {
task: 'features'
value: [0, 1]
}, {
task: 'draw'
value: [{
tool: 0
frame: 0
x: 207
y: 134
details: [{
value: 0
}, {
value: []
}, {
value: ''
}]
}]
}, {
task: 'survey'
value: []
}, {
task: 'init'
value: 6
}]
project = apiClient.type('projects').create
id: 'MOCK_PROJECT_FOR_CLASSIFIER'
title: "The Dev Classifier"
experimental_tools: ['pan and zoom']
preferences = apiClient.type('project_preferences').create
preferences: {}
classification = apiClient.type('classifications').create
annotations: []
metadata: {}
links:
project: project.id
workflow: workflow.id
subjects: [subject.id]
_workflow: workflow # TEMP
_subjects: [subject] # TEMP
module.exports = {workflow, subject, classification, project, preferences}
window?.mockClassifierData = module.exports
|
[
{
"context": "\n\ndnschain\nhttp://dnschain.net\n\nCopyright (c) 2013 Greg Slepak\nLicensed under the BSD 3-Clause license.\n\n###\n\n# ",
"end": 65,
"score": 0.9998716115951538,
"start": 54,
"tag": "NAME",
"value": "Greg Slepak"
},
{
"context": "t: if amRoot then 53 else 5333\n ... | src/lib/config.coffee | wartron/dnschain | 1 | ###
dnschain
http://dnschain.net
Copyright (c) 2013 Greg Slepak
Licensed under the BSD 3-Clause license.
###
# TODO: go through 'TODO's!
###
- DNSChain configuration:
- local in ~/.dnschain.conf (or ~/.dnschain/dnschain.conf)
- global in /etc/dnschain/dnschain.conf
- Namecoin
- Non-Windows: ~/.namecoin/namecoin.conf
- Windows: %APPDATA%\Namecoin\namecoin.conf
All parametrs can be overwritten using command line args and/or environment variables.
###
nconf = require 'nconf'
props = require 'properties'
fs = require 'fs'
tty = require 'tty'
module.exports = (dnschain) ->
# expose these into our namespace
for k of dnschain.globals
eval "var #{k} = dnschain.globals.#{k};"
# TODO: add path to our private key for signing answers
amRoot = process.getuid() is 0
dnscDefs =
log:
level: 'debug'
cli: tty.isatty process.stdout
pretty: tty.isatty process.stdout
timestamp: true
dns:
port: if amRoot then 53 else 5333
host: '0.0.0.0' # what we bind to
externalIP: externalIP() # Advertise this IP for "meta-TLDs" like dns.nmc
oldDNSMethod: consts.oldDNS.NATIVE_DNS # Use NATIVE_DNS until node gives TTLs!
oldDNS:
address: '8.8.8.8' # Google (we recommend running PowerDNS yourself and sending it there)
port: 53
type: 'udp'
http:
port: if amRoot then 80 else 8088
tlsPort: if amRoot then 443 else 4443
host: '0.0.0.0' # what we bind to
nmcDefs =
rpcport: 8336
rpcconnect: '127.0.0.1'
rpcuser: undefined
rpcpassword: undefined
fileFormatOpts =
comments: ['#', ';']
sections: true
props.parse = _.partialRight props.parse, fileFormatOpts
props.stringify = _.partialRight props.stringify, fileFormatOpts
# load our config
appname = "dnschain"
nconf.argv().env()
if process.env.HOME?
dnscConf = path.join process.env.HOME, ".#{appname}.conf"
unless fs.existsSync dnscConf
dnscConf = path.join process.env.HOME, ".#{appname}", "#{appname}.conf"
nconf.file 'user', {file: dnscConf, format: props}
nconf.file 'global', {file:"/etc/#{appname}/#{appname}.conf", format:props}
# namecoin
nmc = (new nconf.Provider()).argv().env()
nmcConf = if process.env.APPDATA?
path.join process.env.APPDATA, "Namecoin", "namecoin.conf"
else if process.env.HOME?
path.join process.env.HOME, ".namecoin", "namecoin.conf"
nmc.file('user', {file:nmcConf,format:props}) if nmcConf
stores =
dnschain: nconf.defaults dnscDefs
nmc: nmc.defaults nmcDefs
config =
get: (key, store="dnschain") -> stores[store].get key
set: (key, value, store="dnschain") -> stores[store].set key, value
# Namecoin's config is not ours, so we don't pretend it is
nmc:
get: (key)-> config.get key, 'nmc'
set: (key, value)-> config.set key, value, 'nmc' | 183790 | ###
dnschain
http://dnschain.net
Copyright (c) 2013 <NAME>
Licensed under the BSD 3-Clause license.
###
# TODO: go through 'TODO's!
###
- DNSChain configuration:
- local in ~/.dnschain.conf (or ~/.dnschain/dnschain.conf)
- global in /etc/dnschain/dnschain.conf
- Namecoin
- Non-Windows: ~/.namecoin/namecoin.conf
- Windows: %APPDATA%\Namecoin\namecoin.conf
All parametrs can be overwritten using command line args and/or environment variables.
###
nconf = require 'nconf'
props = require 'properties'
fs = require 'fs'
tty = require 'tty'
module.exports = (dnschain) ->
# expose these into our namespace
for k of dnschain.globals
eval "var #{k} = dnschain.globals.#{k};"
# TODO: add path to our private key for signing answers
amRoot = process.getuid() is 0
dnscDefs =
log:
level: 'debug'
cli: tty.isatty process.stdout
pretty: tty.isatty process.stdout
timestamp: true
dns:
port: if amRoot then 53 else 5333
host: '0.0.0.0' # what we bind to
externalIP: externalIP() # Advertise this IP for "meta-TLDs" like dns.nmc
oldDNSMethod: consts.oldDNS.NATIVE_DNS # Use NATIVE_DNS until node gives TTLs!
oldDNS:
address: '8.8.8.8' # Google (we recommend running PowerDNS yourself and sending it there)
port: 53
type: 'udp'
http:
port: if amRoot then 80 else 8088
tlsPort: if amRoot then 443 else 4443
host: '0.0.0.0' # what we bind to
nmcDefs =
rpcport: 8336
rpcconnect: '127.0.0.1'
rpcuser: undefined
rpcpassword: <PASSWORD>
fileFormatOpts =
comments: ['#', ';']
sections: true
props.parse = _.partialRight props.parse, fileFormatOpts
props.stringify = _.partialRight props.stringify, fileFormatOpts
# load our config
appname = "dnschain"
nconf.argv().env()
if process.env.HOME?
dnscConf = path.join process.env.HOME, ".#{appname}.conf"
unless fs.existsSync dnscConf
dnscConf = path.join process.env.HOME, ".#{appname}", "#{appname}.conf"
nconf.file 'user', {file: dnscConf, format: props}
nconf.file 'global', {file:"/etc/#{appname}/#{appname}.conf", format:props}
# namecoin
nmc = (new nconf.Provider()).argv().env()
nmcConf = if process.env.APPDATA?
path.join process.env.APPDATA, "Namecoin", "namecoin.conf"
else if process.env.HOME?
path.join process.env.HOME, ".namecoin", "namecoin.conf"
nmc.file('user', {file:nmcConf,format:props}) if nmcConf
stores =
dnschain: nconf.defaults dnscDefs
nmc: nmc.defaults nmcDefs
config =
get: (key, store="dnschain") -> stores[store].get key
set: (key, value, store="dnschain") -> stores[store].set key, value
# Namecoin's config is not ours, so we don't pretend it is
nmc:
get: (key)-> config.get key, 'nmc'
set: (key, value)-> config.set key, value, 'nmc' | true | ###
dnschain
http://dnschain.net
Copyright (c) 2013 PI:NAME:<NAME>END_PI
Licensed under the BSD 3-Clause license.
###
# TODO: go through 'TODO's!
###
- DNSChain configuration:
- local in ~/.dnschain.conf (or ~/.dnschain/dnschain.conf)
- global in /etc/dnschain/dnschain.conf
- Namecoin
- Non-Windows: ~/.namecoin/namecoin.conf
- Windows: %APPDATA%\Namecoin\namecoin.conf
All parametrs can be overwritten using command line args and/or environment variables.
###
nconf = require 'nconf'
props = require 'properties'
fs = require 'fs'
tty = require 'tty'
module.exports = (dnschain) ->
# expose these into our namespace
for k of dnschain.globals
eval "var #{k} = dnschain.globals.#{k};"
# TODO: add path to our private key for signing answers
amRoot = process.getuid() is 0
dnscDefs =
log:
level: 'debug'
cli: tty.isatty process.stdout
pretty: tty.isatty process.stdout
timestamp: true
dns:
port: if amRoot then 53 else 5333
host: '0.0.0.0' # what we bind to
externalIP: externalIP() # Advertise this IP for "meta-TLDs" like dns.nmc
oldDNSMethod: consts.oldDNS.NATIVE_DNS # Use NATIVE_DNS until node gives TTLs!
oldDNS:
address: '8.8.8.8' # Google (we recommend running PowerDNS yourself and sending it there)
port: 53
type: 'udp'
http:
port: if amRoot then 80 else 8088
tlsPort: if amRoot then 443 else 4443
host: '0.0.0.0' # what we bind to
nmcDefs =
rpcport: 8336
rpcconnect: '127.0.0.1'
rpcuser: undefined
rpcpassword: PI:PASSWORD:<PASSWORD>END_PI
fileFormatOpts =
comments: ['#', ';']
sections: true
props.parse = _.partialRight props.parse, fileFormatOpts
props.stringify = _.partialRight props.stringify, fileFormatOpts
# load our config
appname = "dnschain"
nconf.argv().env()
if process.env.HOME?
dnscConf = path.join process.env.HOME, ".#{appname}.conf"
unless fs.existsSync dnscConf
dnscConf = path.join process.env.HOME, ".#{appname}", "#{appname}.conf"
nconf.file 'user', {file: dnscConf, format: props}
nconf.file 'global', {file:"/etc/#{appname}/#{appname}.conf", format:props}
# namecoin
nmc = (new nconf.Provider()).argv().env()
nmcConf = if process.env.APPDATA?
path.join process.env.APPDATA, "Namecoin", "namecoin.conf"
else if process.env.HOME?
path.join process.env.HOME, ".namecoin", "namecoin.conf"
nmc.file('user', {file:nmcConf,format:props}) if nmcConf
stores =
dnschain: nconf.defaults dnscDefs
nmc: nmc.defaults nmcDefs
config =
get: (key, store="dnschain") -> stores[store].get key
set: (key, value, store="dnschain") -> stores[store].set key, value
# Namecoin's config is not ours, so we don't pretend it is
nmc:
get: (key)-> config.get key, 'nmc'
set: (key, value)-> config.set key, value, 'nmc' |
[
{
"context": "ect', ->\n beforeEach ->\n model = { name: 'Noah' }\n myMixin(model)\n\n it 'has instance met",
"end": 376,
"score": 0.9995779991149902,
"start": 372,
"tag": "NAME",
"value": "Noah"
},
{
"context": "eEach ->\n model = new MyBackboneModel name: 'Noah... | test/model_mixin.test.coffee | goodeggs/model-mixin | 2 | expect = require('chai').expect
Backbone = require 'backbone'
mongoose = require 'mongoose'
modelMixin = require '..'
myMixin = modelMixin
methods:
uppercaseName: ->
@get('name').toUpperCase()
statics:
version: ->
'1.0.0'
describe 'modelMixin', ->
model = null
describe 'mixing in into Object', ->
beforeEach ->
model = { name: 'Noah' }
myMixin(model)
it 'has instance methods', ->
expect(model.uppercaseName()).to.equal 'NOAH'
describe 'mixing in to Backbone model', ->
class MyBackboneModel extends Backbone.Model
myMixin(MyBackboneModel)
beforeEach ->
model = new MyBackboneModel name: 'Noah'
it 'has instance methods', ->
expect(model.uppercaseName()).to.equal 'NOAH'
it 'has static methods', ->
expect(MyBackboneModel.version()).to.equal '1.0.0'
it 'exposes static and instance methods on mixin', ->
expect(myMixin.statics.version).to.equal MyBackboneModel.version
expect(myMixin.methods.uppercaseName).to.equal model.uppercaseName
describe 'mixing in to Mongoose model', ->
schema = new mongoose.Schema
name: String
myMixin(schema)
MyMongooseModel = mongoose.model('MyMongooseModel', schema)
beforeEach ->
model = new MyMongooseModel name: 'Noah'
it 'has instance methods', ->
expect(model.uppercaseName()).to.equal 'NOAH'
it 'has static methods', ->
expect(MyMongooseModel.version()).to.equal '1.0.0'
it 'exposes static and instance methods on mixin', ->
expect(myMixin.statics.version).to.equal MyMongooseModel.version
expect(myMixin.methods.uppercaseName).to.equal model.uppercaseName | 129135 | expect = require('chai').expect
Backbone = require 'backbone'
mongoose = require 'mongoose'
modelMixin = require '..'
myMixin = modelMixin
methods:
uppercaseName: ->
@get('name').toUpperCase()
statics:
version: ->
'1.0.0'
describe 'modelMixin', ->
model = null
describe 'mixing in into Object', ->
beforeEach ->
model = { name: '<NAME>' }
myMixin(model)
it 'has instance methods', ->
expect(model.uppercaseName()).to.equal 'NOAH'
describe 'mixing in to Backbone model', ->
class MyBackboneModel extends Backbone.Model
myMixin(MyBackboneModel)
beforeEach ->
model = new MyBackboneModel name: '<NAME>'
it 'has instance methods', ->
expect(model.uppercaseName()).to.equal 'NOAH'
it 'has static methods', ->
expect(MyBackboneModel.version()).to.equal '1.0.0'
it 'exposes static and instance methods on mixin', ->
expect(myMixin.statics.version).to.equal MyBackboneModel.version
expect(myMixin.methods.uppercaseName).to.equal model.uppercaseName
describe 'mixing in to Mongoose model', ->
schema = new mongoose.Schema
name: String
myMixin(schema)
MyMongooseModel = mongoose.model('MyMongooseModel', schema)
beforeEach ->
model = new MyMongooseModel name: '<NAME>'
it 'has instance methods', ->
expect(model.uppercaseName()).to.equal 'NOAH'
it 'has static methods', ->
expect(MyMongooseModel.version()).to.equal '1.0.0'
it 'exposes static and instance methods on mixin', ->
expect(myMixin.statics.version).to.equal MyMongooseModel.version
expect(myMixin.methods.uppercaseName).to.equal model.uppercaseName | true | expect = require('chai').expect
Backbone = require 'backbone'
mongoose = require 'mongoose'
modelMixin = require '..'
myMixin = modelMixin
methods:
uppercaseName: ->
@get('name').toUpperCase()
statics:
version: ->
'1.0.0'
describe 'modelMixin', ->
model = null
describe 'mixing in into Object', ->
beforeEach ->
model = { name: 'PI:NAME:<NAME>END_PI' }
myMixin(model)
it 'has instance methods', ->
expect(model.uppercaseName()).to.equal 'NOAH'
describe 'mixing in to Backbone model', ->
class MyBackboneModel extends Backbone.Model
myMixin(MyBackboneModel)
beforeEach ->
model = new MyBackboneModel name: 'PI:NAME:<NAME>END_PI'
it 'has instance methods', ->
expect(model.uppercaseName()).to.equal 'NOAH'
it 'has static methods', ->
expect(MyBackboneModel.version()).to.equal '1.0.0'
it 'exposes static and instance methods on mixin', ->
expect(myMixin.statics.version).to.equal MyBackboneModel.version
expect(myMixin.methods.uppercaseName).to.equal model.uppercaseName
describe 'mixing in to Mongoose model', ->
schema = new mongoose.Schema
name: String
myMixin(schema)
MyMongooseModel = mongoose.model('MyMongooseModel', schema)
beforeEach ->
model = new MyMongooseModel name: 'PI:NAME:<NAME>END_PI'
it 'has instance methods', ->
expect(model.uppercaseName()).to.equal 'NOAH'
it 'has static methods', ->
expect(MyMongooseModel.version()).to.equal '1.0.0'
it 'exposes static and instance methods on mixin', ->
expect(myMixin.statics.version).to.equal MyMongooseModel.version
expect(myMixin.methods.uppercaseName).to.equal model.uppercaseName |
[
{
"context": "p.state'\n\n.constant 'app.state.index', {\n name: 'index',\n url: '',\n templateUrl: 'html/index.html',\n ",
"end": 73,
"score": 0.7321851253509521,
"start": 68,
"tag": "NAME",
"value": "index"
},
{
"context": "e) ->\n PubNub.init\n publish_key: 'pu... | src/coffee/state/index.coffee | KinveyApps/Gulper-AngularJS | 2 | angular.module 'app.state'
.constant 'app.state.index', {
name: 'index',
url: '',
templateUrl: 'html/index.html',
controller: 'app.control.index',
abstract: true
resolve:
me: ['$kinvey', '$state', '$q', 'PubNub', ($kinvey, $state, $q, PubNub) ->
deferred = $q.defer()
$kinvey.User.current().$promise.then ((response) ->
PubNub.init
publish_key: 'pub-c-54950570-ed66-4f98-8b3b-d101960f63ec'
subscribe_key: 'sub-c-ea5fd726-be91-11e3-b6e0-02ee2ddab7fe'
uuid: response._id
deferred.resolve response
), ((error)->
console.log error
$state.go 'login'
)
return deferred.promise
]
users: ['$kinvey', 'me', ($kinvey, me) ->
$kinvey.User.query
query:
_id:
$ne: me._id
]
rooms: ['$kinvey', ($kinvey) ->
($kinvey.Room.query
query:
_id:
$exists: true
resolve: 'participants'
retainReferences: false
).$promise
]
} | 70653 | angular.module 'app.state'
.constant 'app.state.index', {
name: '<NAME>',
url: '',
templateUrl: 'html/index.html',
controller: 'app.control.index',
abstract: true
resolve:
me: ['$kinvey', '$state', '$q', 'PubNub', ($kinvey, $state, $q, PubNub) ->
deferred = $q.defer()
$kinvey.User.current().$promise.then ((response) ->
PubNub.init
publish_key: '<KEY>'
subscribe_key: '<KEY>'
uuid: response._id
deferred.resolve response
), ((error)->
console.log error
$state.go 'login'
)
return deferred.promise
]
users: ['$kinvey', 'me', ($kinvey, me) ->
$kinvey.User.query
query:
_id:
$ne: me._id
]
rooms: ['$kinvey', ($kinvey) ->
($kinvey.Room.query
query:
_id:
$exists: true
resolve: 'participants'
retainReferences: false
).$promise
]
} | true | angular.module 'app.state'
.constant 'app.state.index', {
name: 'PI:NAME:<NAME>END_PI',
url: '',
templateUrl: 'html/index.html',
controller: 'app.control.index',
abstract: true
resolve:
me: ['$kinvey', '$state', '$q', 'PubNub', ($kinvey, $state, $q, PubNub) ->
deferred = $q.defer()
$kinvey.User.current().$promise.then ((response) ->
PubNub.init
publish_key: 'PI:KEY:<KEY>END_PI'
subscribe_key: 'PI:KEY:<KEY>END_PI'
uuid: response._id
deferred.resolve response
), ((error)->
console.log error
$state.go 'login'
)
return deferred.promise
]
users: ['$kinvey', 'me', ($kinvey, me) ->
$kinvey.User.query
query:
_id:
$ne: me._id
]
rooms: ['$kinvey', ($kinvey) ->
($kinvey.Room.query
query:
_id:
$exists: true
resolve: 'participants'
retainReferences: false
).$promise
]
} |
[
{
"context": "##############################################\n#\n# Markus 1/23/2017\n#\n#####################################",
"end": 75,
"score": 0.9988037347793579,
"start": 69,
"tag": "NAME",
"value": "Markus"
}
] | server/methods/review.coffee | MooqitaSFH/worklearn | 0 | ################################################################
#
# Markus 1/23/2017
#
################################################################
###############################################
Meteor.methods
assign_review: () ->
user = Meteor.user()
if not user._id
throw new Meteor.Error('Not permitted.')
res = assign_review null, user
return res
assign_review_with_challenge: (challenge_id) ->
user = Meteor.user()
if not user._id
throw new Meteor.Error('Not permitted.')
challenge = get_document_unprotected Challenges, challenge_id
res = assign_review challenge, user
return res
assign_review_to_tutor: (solution_id) ->
user = Meteor.user()
if not user._id
throw new Meteor.Error('Not permitted.')
solution = get_document_unprotected Solutions, solution_id
if not has_role Challenges, solution.challenge_id, user, TUTOR
throw new Meteor.Error('Not permitted.')
res = get_open_review_for_solution solution
return res
finish_review: (review_id) ->
user = Meteor.user()
if not user._id
throw new Meteor.Error('Not permitted.')
if not can_edit Reviews, review_id, user
throw new Meteor.Error('Not permitted.')
review = get_document_unprotected Reviews, review_id
review_id = finish_review review, user
res =
review_id: review._id
solution_id: review.solution_id
challenge_id: review.challenge_id
return res
| 149461 | ################################################################
#
# <NAME> 1/23/2017
#
################################################################
###############################################
Meteor.methods
assign_review: () ->
user = Meteor.user()
if not user._id
throw new Meteor.Error('Not permitted.')
res = assign_review null, user
return res
assign_review_with_challenge: (challenge_id) ->
user = Meteor.user()
if not user._id
throw new Meteor.Error('Not permitted.')
challenge = get_document_unprotected Challenges, challenge_id
res = assign_review challenge, user
return res
assign_review_to_tutor: (solution_id) ->
user = Meteor.user()
if not user._id
throw new Meteor.Error('Not permitted.')
solution = get_document_unprotected Solutions, solution_id
if not has_role Challenges, solution.challenge_id, user, TUTOR
throw new Meteor.Error('Not permitted.')
res = get_open_review_for_solution solution
return res
finish_review: (review_id) ->
user = Meteor.user()
if not user._id
throw new Meteor.Error('Not permitted.')
if not can_edit Reviews, review_id, user
throw new Meteor.Error('Not permitted.')
review = get_document_unprotected Reviews, review_id
review_id = finish_review review, user
res =
review_id: review._id
solution_id: review.solution_id
challenge_id: review.challenge_id
return res
| true | ################################################################
#
# PI:NAME:<NAME>END_PI 1/23/2017
#
################################################################
###############################################
Meteor.methods
assign_review: () ->
user = Meteor.user()
if not user._id
throw new Meteor.Error('Not permitted.')
res = assign_review null, user
return res
assign_review_with_challenge: (challenge_id) ->
user = Meteor.user()
if not user._id
throw new Meteor.Error('Not permitted.')
challenge = get_document_unprotected Challenges, challenge_id
res = assign_review challenge, user
return res
assign_review_to_tutor: (solution_id) ->
user = Meteor.user()
if not user._id
throw new Meteor.Error('Not permitted.')
solution = get_document_unprotected Solutions, solution_id
if not has_role Challenges, solution.challenge_id, user, TUTOR
throw new Meteor.Error('Not permitted.')
res = get_open_review_for_solution solution
return res
finish_review: (review_id) ->
user = Meteor.user()
if not user._id
throw new Meteor.Error('Not permitted.')
if not can_edit Reviews, review_id, user
throw new Meteor.Error('Not permitted.')
review = get_document_unprotected Reviews, review_id
review_id = finish_review review, user
res =
review_id: review._id
solution_id: review.solution_id
challenge_id: review.challenge_id
return res
|
[
{
"context": " \"positions\"\n }\n {\n name: \"Сотрудники\"\n sref: \"employees\"\n permission",
"end": 288,
"score": 0.91622394323349,
"start": 278,
"tag": "NAME",
"value": "Сотрудники"
}
] | static_source/app/services/menu.coffee | e154/angular-admin-menu | 0 | angular
.module('appServices')
.constant('mainMenuTree', [
{
name: "Сотрудники"
icon: "fa fa-users"
children: [
{
name: "Должности"
permission: "manage_positions"
sref: "positions"
}
{
name: "Сотрудники"
sref: "employees"
permission: "manage_employees"
children: [
{
name: "Сотрудник 1"
permission: "manage_positions"
}
{
name: "Сотрудник 2"
permission: "manage_employees"
children: [
{
name: "Сотрудник 2.1"
permission: "manage_positions"
}
{
name: "Сотрудник 2.2"
permission: "manage_employees"
children: [
{
name: "Сотрудник 2.2.1"
permission: "manage_positions"
}
{
name: "Сотрудник 2.2.2"
permission: "manage_employees"
}
]
}
]
}
]
}
]
}
{
name: "Интерфейс Конфигуратора"
icon: "fa fa-object-group"
children: [
{
name: "Скины"
sref : "skins"
permission: "manage_skins"
}
{
name: "Графика"
sref : "icons"
permission: "manage_icons"
children: []
}
{
name: "Языковые пакеты"
sref : "language_packs"
permission: "manage_language_packs"
}
]
}
{
name: "Валюта"
icon: "fa fa-btc"
children: [
{
name: "Список валют"
sref : "currencies"
permission: "manage_currencies"
}
{
name: "Курсы валют"
sref : "currency_books"
permission: "manage_currencies"
}
]
}
]
)
| 156383 | angular
.module('appServices')
.constant('mainMenuTree', [
{
name: "Сотрудники"
icon: "fa fa-users"
children: [
{
name: "Должности"
permission: "manage_positions"
sref: "positions"
}
{
name: "<NAME>"
sref: "employees"
permission: "manage_employees"
children: [
{
name: "Сотрудник 1"
permission: "manage_positions"
}
{
name: "Сотрудник 2"
permission: "manage_employees"
children: [
{
name: "Сотрудник 2.1"
permission: "manage_positions"
}
{
name: "Сотрудник 2.2"
permission: "manage_employees"
children: [
{
name: "Сотрудник 2.2.1"
permission: "manage_positions"
}
{
name: "Сотрудник 2.2.2"
permission: "manage_employees"
}
]
}
]
}
]
}
]
}
{
name: "Интерфейс Конфигуратора"
icon: "fa fa-object-group"
children: [
{
name: "Скины"
sref : "skins"
permission: "manage_skins"
}
{
name: "Графика"
sref : "icons"
permission: "manage_icons"
children: []
}
{
name: "Языковые пакеты"
sref : "language_packs"
permission: "manage_language_packs"
}
]
}
{
name: "Валюта"
icon: "fa fa-btc"
children: [
{
name: "Список валют"
sref : "currencies"
permission: "manage_currencies"
}
{
name: "Курсы валют"
sref : "currency_books"
permission: "manage_currencies"
}
]
}
]
)
| true | angular
.module('appServices')
.constant('mainMenuTree', [
{
name: "Сотрудники"
icon: "fa fa-users"
children: [
{
name: "Должности"
permission: "manage_positions"
sref: "positions"
}
{
name: "PI:NAME:<NAME>END_PI"
sref: "employees"
permission: "manage_employees"
children: [
{
name: "Сотрудник 1"
permission: "manage_positions"
}
{
name: "Сотрудник 2"
permission: "manage_employees"
children: [
{
name: "Сотрудник 2.1"
permission: "manage_positions"
}
{
name: "Сотрудник 2.2"
permission: "manage_employees"
children: [
{
name: "Сотрудник 2.2.1"
permission: "manage_positions"
}
{
name: "Сотрудник 2.2.2"
permission: "manage_employees"
}
]
}
]
}
]
}
]
}
{
name: "Интерфейс Конфигуратора"
icon: "fa fa-object-group"
children: [
{
name: "Скины"
sref : "skins"
permission: "manage_skins"
}
{
name: "Графика"
sref : "icons"
permission: "manage_icons"
children: []
}
{
name: "Языковые пакеты"
sref : "language_packs"
permission: "manage_language_packs"
}
]
}
{
name: "Валюта"
icon: "fa fa-btc"
children: [
{
name: "Список валют"
sref : "currencies"
permission: "manage_currencies"
}
{
name: "Курсы валют"
sref : "currency_books"
permission: "manage_currencies"
}
]
}
]
)
|
[
{
"context": "hash based implementation of the Map ADT\n @author Mads Hartmann Jensen (mads379@gmail.com)\n###\n\nmugs.provide(\"mugs.HashM",
"end": 103,
"score": 0.9998371005058289,
"start": 83,
"tag": "NAME",
"value": "Mads Hartmann Jensen"
},
{
"context": "on of the Map ADT\n @a... | src/HashMap.coffee | mads-hartmann/mugs | 1 | ###*
@fileoverview Contains a hash based implementation of the Map ADT
@author Mads Hartmann Jensen (mads379@gmail.com)
###
mugs.provide("mugs.HashMap")
mugs.require("mugs.Some")
mugs.require("mugs.None")
mugs.require("mugs.Collection")
mugs.require("mugs.List")
###*
HashMap
Implementation of an immutable Map based on a hash table. The bucket array approach is used and the underlying
data-structure is a Random Access List. Separate Chaining is used to deal with collisions where the chain is based
on a List.
A property named something like "mugs_uid_2kczq5" will be added to the key objects. This approach has been copied from
JS_Cols (http://jscols.com/).
<pre>
-----------------------------------------------------------
B is the number of items in the bucket array (101 by default)
b is the number of items in the current bucket
-----------------------------------------------------------
get(key) O(log B + b)
insert(key,item) O(log B + b)
remove(key) O(log B + b)
containsKey(key) O(log B + b)
forEach( f ) O(B * b * O(f))
values() O(B * b)
keys() O(B * b)
</pre>
@class HashMap
@augments mugs.Collection
@param {Array} keyValuePairs An array containing objects with the properties key & value.
@param {Bool} initialize This is only used internally. It's true if the bucket array should be initialize
###
mugs.HashMap = (keyValuePairs, initialize) ->
this.initializeBucketArray_() if initialize != false
mapUnderConstruction = this
if keyValuePairs instanceof Array and keyValuePairs.length > 0
for kv in keyValuePairs
mapUnderConstruction = mapUnderConstruction.insert(kv.key, kv.value)
mapUnderConstruction
mugs.HashMap.prototype = new mugs.Collection()
###*
If a (key,value) pair exists return mugs.Some(value), otherwise mugs.None()
@param key The key of the item to retrieve
@return Some(item) if an item was associated with the key. Otherwise None
###
mugs.HashMap.prototype.get = (key) ->
that = this
hash = this.getHash_(key)
bucket = this.getBucketFromKey_(key)
result = new None()
bucket.forEach( (item) -> if hash == that.getHash_(item.key) then result = new Some(item.value))
result
###*
Return a new mugs.HashMap containing the given (key,value) pair.
@param key The key to associate with the item
@param item The item to insert into the HashMap
@return A new HashMap with the with the new key/item inserted
###
mugs.HashMap.prototype.insert = (key, item) ->
index = this.compress_(this.getHash_(key))
bucket = this.getBucketFromKey_(key)
newBucketArr = this.bucketArray_.update(index, bucket.prepend({ key: key, value: item}))
newMap = new mugs.HashMap([], false)
newMap.bucketArray_ = newBucketArr
newMap
###*
Return a new HashMap without the given key.
@param key The key of the item to remove
@return A new HashMap without the given key.
###
mugs.HashMap.prototype.remove = (key) ->
that = this
index = that.compress_(that.getHash_(key))
bucket = that.getBucketFromKey_(key)
indexOfItem = bucket.findIndex( (item) -> that.getHash_(item.key) == that.getHash_(key) ).getOrElse(-1)
if indexOfItem >= 0
newBucketArr = that.bucketArray_.update(index, bucket.removeAt(indexOfItem))
newMap = new mugs.HashMap([],false)
newMap.bucketArray_ = newBucketArr
newMap
else
that
###*
True if the given key is contained in the TreeMap, otherwise false.
@param key The key to search for
@return True if the given key is contained in the HashMap, otherwise false.
###
mugs.HashMap.prototype.containsKey = (key) ->
that = this
hash = this.getHash_(key)
bucket = this.getBucketFromKey_(key)
isThere = false
bucket.forEach( (item) -> if hash == that.getHash_(item.key) then isThere = true )
isThere
###*
Returns a List with all of the values in the Map
@return {mugs.List} List with all of the values in the Map
###
mugs.HashMap.prototype.values = () ->
this.bucketArray_.flatMap( (bucket) -> bucket.map( (item) -> item.value ))
###*
Returns a List with all of the keys in the Map
@return {mugs.List} List with all of the keys in the Map
###
mugs.HashMap.prototype.keys = () ->
this.bucketArray_.flatMap( (bucket) -> bucket.map( (item) -> item.key ))
###*
@private
###
mugs.HashMap.prototype.N_ = 101
###*
@private
###
mugs.HashMap.prototype.bucketArray_ = new mugs.List() # TODO: Use Random Access List
###*
@private
###
mugs.HashMap.prototype.initializeBucketArray_ = () ->
i = 0
while i < this.N_
this.bucketArray_ = this.bucketArray_.prepend(new mugs.List())
i++
return
###*
@private
###
mugs.HashMap.prototype.getBucketFromKey_ = (key) ->
hash = this.getHash_(key)
index = this.compress_(hash)
this.bucketArray_.get(index).get()
###*
Generates a hash code for an object.
@private
###
mugs.HashMap.prototype.getHash_ = (key) ->
type = typeof key
if type == 'object' && key || type == 'function'
'o' + mugs.getUid(key)
else
type.substr(0,1) + key
###*
Converts the hash-code to an integer and then compresses the result hash-code
so it fits in the bucket array
@private
###
mugs.HashMap.prototype.compress_ = (key) ->
index = parseInt(key,36)
index % this.N_
###
---------------------------------------------------------------------------------------------
Methods related to Collection prototype
---------------------------------------------------------------------------------------------
###
###*
@private
###
mugs.HashMap.prototype.buildFromArray = (arr) ->
new mugs.HashMap(arr)
###*
Applies function 'f' on each value in the map. This return nothing and is only invoked
for the side-effects of f.
@see mugs.Collection
###
mugs.HashMap.prototype.forEach = ( f ) ->
this.bucketArray_.forEach( (bucket) -> bucket.forEach(f)) | 186195 | ###*
@fileoverview Contains a hash based implementation of the Map ADT
@author <NAME> (<EMAIL>)
###
mugs.provide("mugs.HashMap")
mugs.require("mugs.Some")
mugs.require("mugs.None")
mugs.require("mugs.Collection")
mugs.require("mugs.List")
###*
HashMap
Implementation of an immutable Map based on a hash table. The bucket array approach is used and the underlying
data-structure is a Random Access List. Separate Chaining is used to deal with collisions where the chain is based
on a List.
A property named something like "mugs_uid_2kczq5" will be added to the key objects. This approach has been copied from
JS_Cols (http://jscols.com/).
<pre>
-----------------------------------------------------------
B is the number of items in the bucket array (101 by default)
b is the number of items in the current bucket
-----------------------------------------------------------
get(key) O(log B + b)
insert(key,item) O(log B + b)
remove(key) O(log B + b)
containsKey(key) O(log B + b)
forEach( f ) O(B * b * O(f))
values() O(B * b)
keys() O(B * b)
</pre>
@class HashMap
@augments mugs.Collection
@param {Array} keyValuePairs An array containing objects with the properties key & value.
@param {Bool} initialize This is only used internally. It's true if the bucket array should be initialize
###
mugs.HashMap = (keyValuePairs, initialize) ->
this.initializeBucketArray_() if initialize != false
mapUnderConstruction = this
if keyValuePairs instanceof Array and keyValuePairs.length > 0
for kv in keyValuePairs
mapUnderConstruction = mapUnderConstruction.insert(kv.key, kv.value)
mapUnderConstruction
mugs.HashMap.prototype = new mugs.Collection()
###*
If a (key,value) pair exists return mugs.Some(value), otherwise mugs.None()
@param key The key of the item to retrieve
@return Some(item) if an item was associated with the key. Otherwise None
###
mugs.HashMap.prototype.get = (key) ->
that = this
hash = this.getHash_(key)
bucket = this.getBucketFromKey_(key)
result = new None()
bucket.forEach( (item) -> if hash == that.getHash_(item.key) then result = new Some(item.value))
result
###*
Return a new mugs.HashMap containing the given (key,value) pair.
@param key The key to associate with the item
@param item The item to insert into the HashMap
@return A new HashMap with the with the new key/item inserted
###
mugs.HashMap.prototype.insert = (key, item) ->
index = this.compress_(this.getHash_(key))
bucket = this.getBucketFromKey_(key)
newBucketArr = this.bucketArray_.update(index, bucket.prepend({ key: key, value: item}))
newMap = new mugs.HashMap([], false)
newMap.bucketArray_ = newBucketArr
newMap
###*
Return a new HashMap without the given key.
@param key The key of the item to remove
@return A new HashMap without the given key.
###
mugs.HashMap.prototype.remove = (key) ->
that = this
index = that.compress_(that.getHash_(key))
bucket = that.getBucketFromKey_(key)
indexOfItem = bucket.findIndex( (item) -> that.getHash_(item.key) == that.getHash_(key) ).getOrElse(-1)
if indexOfItem >= 0
newBucketArr = that.bucketArray_.update(index, bucket.removeAt(indexOfItem))
newMap = new mugs.HashMap([],false)
newMap.bucketArray_ = newBucketArr
newMap
else
that
###*
True if the given key is contained in the TreeMap, otherwise false.
@param key The key to search for
@return True if the given key is contained in the HashMap, otherwise false.
###
mugs.HashMap.prototype.containsKey = (key) ->
that = this
hash = this.getHash_(key)
bucket = this.getBucketFromKey_(key)
isThere = false
bucket.forEach( (item) -> if hash == that.getHash_(item.key) then isThere = true )
isThere
###*
Returns a List with all of the values in the Map
@return {mugs.List} List with all of the values in the Map
###
mugs.HashMap.prototype.values = () ->
this.bucketArray_.flatMap( (bucket) -> bucket.map( (item) -> item.value ))
###*
Returns a List with all of the keys in the Map
@return {mugs.List} List with all of the keys in the Map
###
mugs.HashMap.prototype.keys = () ->
this.bucketArray_.flatMap( (bucket) -> bucket.map( (item) -> item.key ))
###*
@private
###
mugs.HashMap.prototype.N_ = 101
###*
@private
###
mugs.HashMap.prototype.bucketArray_ = new mugs.List() # TODO: Use Random Access List
###*
@private
###
mugs.HashMap.prototype.initializeBucketArray_ = () ->
i = 0
while i < this.N_
this.bucketArray_ = this.bucketArray_.prepend(new mugs.List())
i++
return
###*
@private
###
mugs.HashMap.prototype.getBucketFromKey_ = (key) ->
hash = this.getHash_(key)
index = this.compress_(hash)
this.bucketArray_.get(index).get()
###*
Generates a hash code for an object.
@private
###
mugs.HashMap.prototype.getHash_ = (key) ->
type = typeof key
if type == 'object' && key || type == 'function'
'o' + mugs.getUid(key)
else
type.substr(0,1) + key
###*
Converts the hash-code to an integer and then compresses the result hash-code
so it fits in the bucket array
@private
###
mugs.HashMap.prototype.compress_ = (key) ->
index = parseInt(key,36)
index % this.N_
###
---------------------------------------------------------------------------------------------
Methods related to Collection prototype
---------------------------------------------------------------------------------------------
###
###*
@private
###
mugs.HashMap.prototype.buildFromArray = (arr) ->
new mugs.HashMap(arr)
###*
Applies function 'f' on each value in the map. This return nothing and is only invoked
for the side-effects of f.
@see mugs.Collection
###
mugs.HashMap.prototype.forEach = ( f ) ->
this.bucketArray_.forEach( (bucket) -> bucket.forEach(f)) | true | ###*
@fileoverview Contains a hash based implementation of the Map ADT
@author PI:NAME:<NAME>END_PI (PI:EMAIL:<EMAIL>END_PI)
###
mugs.provide("mugs.HashMap")
mugs.require("mugs.Some")
mugs.require("mugs.None")
mugs.require("mugs.Collection")
mugs.require("mugs.List")
###*
HashMap
Implementation of an immutable Map based on a hash table. The bucket array approach is used and the underlying
data-structure is a Random Access List. Separate Chaining is used to deal with collisions where the chain is based
on a List.
A property named something like "mugs_uid_2kczq5" will be added to the key objects. This approach has been copied from
JS_Cols (http://jscols.com/).
<pre>
-----------------------------------------------------------
B is the number of items in the bucket array (101 by default)
b is the number of items in the current bucket
-----------------------------------------------------------
get(key) O(log B + b)
insert(key,item) O(log B + b)
remove(key) O(log B + b)
containsKey(key) O(log B + b)
forEach( f ) O(B * b * O(f))
values() O(B * b)
keys() O(B * b)
</pre>
@class HashMap
@augments mugs.Collection
@param {Array} keyValuePairs An array containing objects with the properties key & value.
@param {Bool} initialize This is only used internally. It's true if the bucket array should be initialize
###
mugs.HashMap = (keyValuePairs, initialize) ->
this.initializeBucketArray_() if initialize != false
mapUnderConstruction = this
if keyValuePairs instanceof Array and keyValuePairs.length > 0
for kv in keyValuePairs
mapUnderConstruction = mapUnderConstruction.insert(kv.key, kv.value)
mapUnderConstruction
mugs.HashMap.prototype = new mugs.Collection()
###*
If a (key,value) pair exists return mugs.Some(value), otherwise mugs.None()
@param key The key of the item to retrieve
@return Some(item) if an item was associated with the key. Otherwise None
###
mugs.HashMap.prototype.get = (key) ->
that = this
hash = this.getHash_(key)
bucket = this.getBucketFromKey_(key)
result = new None()
bucket.forEach( (item) -> if hash == that.getHash_(item.key) then result = new Some(item.value))
result
###*
Return a new mugs.HashMap containing the given (key,value) pair.
@param key The key to associate with the item
@param item The item to insert into the HashMap
@return A new HashMap with the with the new key/item inserted
###
mugs.HashMap.prototype.insert = (key, item) ->
index = this.compress_(this.getHash_(key))
bucket = this.getBucketFromKey_(key)
newBucketArr = this.bucketArray_.update(index, bucket.prepend({ key: key, value: item}))
newMap = new mugs.HashMap([], false)
newMap.bucketArray_ = newBucketArr
newMap
###*
Return a new HashMap without the given key.
@param key The key of the item to remove
@return A new HashMap without the given key.
###
mugs.HashMap.prototype.remove = (key) ->
that = this
index = that.compress_(that.getHash_(key))
bucket = that.getBucketFromKey_(key)
indexOfItem = bucket.findIndex( (item) -> that.getHash_(item.key) == that.getHash_(key) ).getOrElse(-1)
if indexOfItem >= 0
newBucketArr = that.bucketArray_.update(index, bucket.removeAt(indexOfItem))
newMap = new mugs.HashMap([],false)
newMap.bucketArray_ = newBucketArr
newMap
else
that
###*
True if the given key is contained in the TreeMap, otherwise false.
@param key The key to search for
@return True if the given key is contained in the HashMap, otherwise false.
###
mugs.HashMap.prototype.containsKey = (key) ->
that = this
hash = this.getHash_(key)
bucket = this.getBucketFromKey_(key)
isThere = false
bucket.forEach( (item) -> if hash == that.getHash_(item.key) then isThere = true )
isThere
###*
Returns a List with all of the values in the Map
@return {mugs.List} List with all of the values in the Map
###
mugs.HashMap.prototype.values = () ->
this.bucketArray_.flatMap( (bucket) -> bucket.map( (item) -> item.value ))
###*
Returns a List with all of the keys in the Map
@return {mugs.List} List with all of the keys in the Map
###
mugs.HashMap.prototype.keys = () ->
this.bucketArray_.flatMap( (bucket) -> bucket.map( (item) -> item.key ))
###*
@private
###
mugs.HashMap.prototype.N_ = 101
###*
@private
###
mugs.HashMap.prototype.bucketArray_ = new mugs.List() # TODO: Use Random Access List
###*
@private
###
mugs.HashMap.prototype.initializeBucketArray_ = () ->
i = 0
while i < this.N_
this.bucketArray_ = this.bucketArray_.prepend(new mugs.List())
i++
return
###*
@private
###
mugs.HashMap.prototype.getBucketFromKey_ = (key) ->
hash = this.getHash_(key)
index = this.compress_(hash)
this.bucketArray_.get(index).get()
###*
Generates a hash code for an object.
@private
###
mugs.HashMap.prototype.getHash_ = (key) ->
type = typeof key
if type == 'object' && key || type == 'function'
'o' + mugs.getUid(key)
else
type.substr(0,1) + key
###*
Converts the hash-code to an integer and then compresses the result hash-code
so it fits in the bucket array
@private
###
mugs.HashMap.prototype.compress_ = (key) ->
index = parseInt(key,36)
index % this.N_
###
---------------------------------------------------------------------------------------------
Methods related to Collection prototype
---------------------------------------------------------------------------------------------
###
###*
@private
###
mugs.HashMap.prototype.buildFromArray = (arr) ->
new mugs.HashMap(arr)
###*
Applies function 'f' on each value in the map. This return nothing and is only invoked
for the side-effects of f.
@see mugs.Collection
###
mugs.HashMap.prototype.forEach = ( f ) ->
this.bucketArray_.forEach( (bucket) -> bucket.forEach(f)) |
[
{
"context": "rowser = undefined\n\n #\n # * Copyright 2011, John Resig\n # * Dual licensed under the MIT or GPL Versi",
"end": 185,
"score": 0.9997265934944153,
"start": 175,
"tag": "NAME",
"value": "John Resig"
}
] | src/utils/jquery_fix.coffee | arenoir/ember-table | 1 | ###
jQuery.browser shim that makes HT working with jQuery 1.8+
###
unless jQuery.browser
(->
matched = undefined
browser = undefined
#
# * Copyright 2011, John Resig
# * Dual licensed under the MIT or GPL Version 2 licenses.
# * http://jquery.org/license
#
jQuery.uaMatch = (ua) ->
ua = ua.toLowerCase()
match = /(chrome)[ \/]([\w.]+)/.exec(ua) or /(webkit)[ \/]([\w.]+)/.exec(ua) or /(opera)(?:.*version|)[ \/]([\w.]+)/.exec(ua) or /(msie) ([\w.]+)/.exec(ua) or ua.indexOf("compatible") < 0 and /(mozilla)(?:.*? rv:([\w.]+)|)/.exec(ua) or []
browser: match[1] or ""
version: match[2] or "0"
matched = jQuery.uaMatch(navigator.userAgent)
browser = {}
if matched.browser
browser[matched.browser] = true
browser.version = matched.version
# Chrome is Webkit, but Webkit is also Safari.
if browser.chrome
browser.webkit = true
else browser.safari = true if browser.webkit
res = jQuery.browser = browser
return res
)() | 84584 | ###
jQuery.browser shim that makes HT working with jQuery 1.8+
###
unless jQuery.browser
(->
matched = undefined
browser = undefined
#
# * Copyright 2011, <NAME>
# * Dual licensed under the MIT or GPL Version 2 licenses.
# * http://jquery.org/license
#
jQuery.uaMatch = (ua) ->
ua = ua.toLowerCase()
match = /(chrome)[ \/]([\w.]+)/.exec(ua) or /(webkit)[ \/]([\w.]+)/.exec(ua) or /(opera)(?:.*version|)[ \/]([\w.]+)/.exec(ua) or /(msie) ([\w.]+)/.exec(ua) or ua.indexOf("compatible") < 0 and /(mozilla)(?:.*? rv:([\w.]+)|)/.exec(ua) or []
browser: match[1] or ""
version: match[2] or "0"
matched = jQuery.uaMatch(navigator.userAgent)
browser = {}
if matched.browser
browser[matched.browser] = true
browser.version = matched.version
# Chrome is Webkit, but Webkit is also Safari.
if browser.chrome
browser.webkit = true
else browser.safari = true if browser.webkit
res = jQuery.browser = browser
return res
)() | true | ###
jQuery.browser shim that makes HT working with jQuery 1.8+
###
unless jQuery.browser
(->
matched = undefined
browser = undefined
#
# * Copyright 2011, PI:NAME:<NAME>END_PI
# * Dual licensed under the MIT or GPL Version 2 licenses.
# * http://jquery.org/license
#
jQuery.uaMatch = (ua) ->
ua = ua.toLowerCase()
match = /(chrome)[ \/]([\w.]+)/.exec(ua) or /(webkit)[ \/]([\w.]+)/.exec(ua) or /(opera)(?:.*version|)[ \/]([\w.]+)/.exec(ua) or /(msie) ([\w.]+)/.exec(ua) or ua.indexOf("compatible") < 0 and /(mozilla)(?:.*? rv:([\w.]+)|)/.exec(ua) or []
browser: match[1] or ""
version: match[2] or "0"
matched = jQuery.uaMatch(navigator.userAgent)
browser = {}
if matched.browser
browser[matched.browser] = true
browser.version = matched.version
# Chrome is Webkit, but Webkit is also Safari.
if browser.chrome
browser.webkit = true
else browser.safari = true if browser.webkit
res = jQuery.browser = browser
return res
)() |
[
{
"context": "ObjectId().toString()\n\t\t\t@user =\n\t\t\t\t_id: ObjectId(@user_id)\n\t\t\t@req.params = user_id: @user_id\n\n\t\tdescribe \"",
"end": 1770,
"score": 0.9362583160400391,
"start": 1762,
"tag": "USERNAME",
"value": "@user_id"
},
{
"context": "\t_id: ObjectId(@user_id)\n... | test/UnitTests/coffee/User/UserInfoControllerTests.coffee | watercrossing/web-sharelatex | 0 | sinon = require('sinon')
chai = require('chai')
assert = require("chai").assert
should = chai.should()
expect = chai.expect
modulePath = "../../../../app/js/Features/User/UserInfoController.js"
SandboxedModule = require('sandboxed-module')
events = require "events"
MockResponse = require "../helpers/MockResponse"
MockRequest = require "../helpers/MockRequest"
ObjectId = require("mongojs").ObjectId
describe "UserInfoController", ->
beforeEach ->
@UserDeleter =
deleteUser: sinon.stub().callsArgWith(1)
@UserUpdater =
updatePersonalInfo: sinon.stub()
@sanitizer = escape:(v)->v
sinon.spy @sanitizer, "escape"
@UserGetter = {}
@UserInfoController = SandboxedModule.require modulePath, requires:
"./UserGetter": @UserGetter
"./UserUpdater": @UserUpdater
"./UserDeleter": @UserDeleter
"logger-sharelatex": log:->
"sanitizer":@sanitizer
'../Authentication/AuthenticationController': @AuthenticationController = {getLoggedInUserId: sinon.stub()}
@req = new MockRequest()
@res = new MockResponse()
@next = sinon.stub()
describe "getLoggedInUsersPersonalInfo", ->
beforeEach ->
@user =
_id: ObjectId()
@req.user = @user
@req.session.user = @user
@UserInfoController.sendFormattedPersonalInfo = sinon.stub()
@UserGetter.getUser = sinon.stub().callsArgWith(2, null, @user)
@AuthenticationController.getLoggedInUserId = sinon.stub().returns(@user._id)
@UserInfoController.getLoggedInUsersPersonalInfo(@req, @res, @next)
it "should call sendFormattedPersonalInfo", ->
@UserInfoController.sendFormattedPersonalInfo
.calledWith(@user, @res, @next)
.should.equal true
describe "getPersonalInfo", ->
beforeEach ->
@user_id = ObjectId().toString()
@user =
_id: ObjectId(@user_id)
@req.params = user_id: @user_id
describe "when the user exists", ->
beforeEach ->
@UserGetter.getUser = sinon.stub().callsArgWith(2, null, @user)
@UserInfoController.sendFormattedPersonalInfo = sinon.stub()
@UserInfoController.getPersonalInfo(@req, @res, @next)
it "should look up the user in the database", ->
@UserGetter.getUser
.calledWith(@user_id, { _id: true, first_name: true, last_name: true, email: true })
.should.equal true
it "should send the formatted details back to the client", ->
@UserInfoController.sendFormattedPersonalInfo
.calledWith(@user, @res, @next)
.should.equal true
describe "when the user does not exist", ->
beforeEach ->
@UserGetter.getUser = sinon.stub().callsArgWith(2, null, null)
@UserInfoController.sendFormattedPersonalInfo = sinon.stub()
@UserInfoController.getPersonalInfo(@req, @res, @next)
it "should return 404 to the client", ->
@res.statusCode.should.equal 404
describe "sendFormattedPersonalInfo", ->
beforeEach ->
@user =
_id: ObjectId()
first_name: "Douglas"
last_name: "Adams"
email: "doug@sharelatex.com"
@formattedInfo =
id: @user._id.toString()
first_name: @user.first_name
last_name: @user.last_name
email: @user.email
@UserInfoController.formatPersonalInfo = sinon.stub().returns(@formattedInfo)
@UserInfoController.sendFormattedPersonalInfo @user, @res
it "should format the user details for the response", ->
@UserInfoController.formatPersonalInfo
.calledWith(@user)
.should.equal true
it "should send the formatted details back to the client", ->
@res.body.should.equal JSON.stringify(@formattedInfo)
describe "formatPersonalInfo", ->
it "should return the correctly formatted data", ->
@user =
_id: ObjectId()
first_name: "Douglas"
last_name: "Adams"
email: "doug@sharelatex.com"
password: "should-not-get-included"
signUpDate: new Date()
role:"student"
institution:"sheffield"
expect(@UserInfoController.formatPersonalInfo(@user)).to.deep.equal {
id: @user._id.toString()
first_name: @user.first_name
last_name: @user.last_name
email: @user.email
signUpDate: @user.signUpDate
role: @user.role
institution: @user.institution
}
| 2904 | sinon = require('sinon')
chai = require('chai')
assert = require("chai").assert
should = chai.should()
expect = chai.expect
modulePath = "../../../../app/js/Features/User/UserInfoController.js"
SandboxedModule = require('sandboxed-module')
events = require "events"
MockResponse = require "../helpers/MockResponse"
MockRequest = require "../helpers/MockRequest"
ObjectId = require("mongojs").ObjectId
describe "UserInfoController", ->
beforeEach ->
@UserDeleter =
deleteUser: sinon.stub().callsArgWith(1)
@UserUpdater =
updatePersonalInfo: sinon.stub()
@sanitizer = escape:(v)->v
sinon.spy @sanitizer, "escape"
@UserGetter = {}
@UserInfoController = SandboxedModule.require modulePath, requires:
"./UserGetter": @UserGetter
"./UserUpdater": @UserUpdater
"./UserDeleter": @UserDeleter
"logger-sharelatex": log:->
"sanitizer":@sanitizer
'../Authentication/AuthenticationController': @AuthenticationController = {getLoggedInUserId: sinon.stub()}
@req = new MockRequest()
@res = new MockResponse()
@next = sinon.stub()
describe "getLoggedInUsersPersonalInfo", ->
beforeEach ->
@user =
_id: ObjectId()
@req.user = @user
@req.session.user = @user
@UserInfoController.sendFormattedPersonalInfo = sinon.stub()
@UserGetter.getUser = sinon.stub().callsArgWith(2, null, @user)
@AuthenticationController.getLoggedInUserId = sinon.stub().returns(@user._id)
@UserInfoController.getLoggedInUsersPersonalInfo(@req, @res, @next)
it "should call sendFormattedPersonalInfo", ->
@UserInfoController.sendFormattedPersonalInfo
.calledWith(@user, @res, @next)
.should.equal true
describe "getPersonalInfo", ->
beforeEach ->
@user_id = ObjectId().toString()
@user =
_id: ObjectId(@user_id)
@req.params = user_id: @user_id
describe "when the user exists", ->
beforeEach ->
@UserGetter.getUser = sinon.stub().callsArgWith(2, null, @user)
@UserInfoController.sendFormattedPersonalInfo = sinon.stub()
@UserInfoController.getPersonalInfo(@req, @res, @next)
it "should look up the user in the database", ->
@UserGetter.getUser
.calledWith(@user_id, { _id: true, first_name: true, last_name: true, email: true })
.should.equal true
it "should send the formatted details back to the client", ->
@UserInfoController.sendFormattedPersonalInfo
.calledWith(@user, @res, @next)
.should.equal true
describe "when the user does not exist", ->
beforeEach ->
@UserGetter.getUser = sinon.stub().callsArgWith(2, null, null)
@UserInfoController.sendFormattedPersonalInfo = sinon.stub()
@UserInfoController.getPersonalInfo(@req, @res, @next)
it "should return 404 to the client", ->
@res.statusCode.should.equal 404
describe "sendFormattedPersonalInfo", ->
beforeEach ->
@user =
_id: ObjectId()
first_name: "<NAME>"
last_name: "<NAME>"
email: "<EMAIL>"
@formattedInfo =
id: @user._id.toString()
first_name: @user.first_name
last_name: @user.last_name
email: @user.email
@UserInfoController.formatPersonalInfo = sinon.stub().returns(@formattedInfo)
@UserInfoController.sendFormattedPersonalInfo @user, @res
it "should format the user details for the response", ->
@UserInfoController.formatPersonalInfo
.calledWith(@user)
.should.equal true
it "should send the formatted details back to the client", ->
@res.body.should.equal JSON.stringify(@formattedInfo)
describe "formatPersonalInfo", ->
it "should return the correctly formatted data", ->
@user =
_id: ObjectId()
first_name: "<NAME>"
last_name: "<NAME>"
email: "<EMAIL>"
password: "<PASSWORD>"
signUpDate: new Date()
role:"student"
institution:"sheffield"
expect(@UserInfoController.formatPersonalInfo(@user)).to.deep.equal {
id: @user._id.toString()
first_name: @user.first_name
last_name: @user.last_name
email: @user.email
signUpDate: @user.signUpDate
role: @user.role
institution: @user.institution
}
| true | sinon = require('sinon')
chai = require('chai')
assert = require("chai").assert
should = chai.should()
expect = chai.expect
modulePath = "../../../../app/js/Features/User/UserInfoController.js"
SandboxedModule = require('sandboxed-module')
events = require "events"
MockResponse = require "../helpers/MockResponse"
MockRequest = require "../helpers/MockRequest"
ObjectId = require("mongojs").ObjectId
describe "UserInfoController", ->
beforeEach ->
@UserDeleter =
deleteUser: sinon.stub().callsArgWith(1)
@UserUpdater =
updatePersonalInfo: sinon.stub()
@sanitizer = escape:(v)->v
sinon.spy @sanitizer, "escape"
@UserGetter = {}
@UserInfoController = SandboxedModule.require modulePath, requires:
"./UserGetter": @UserGetter
"./UserUpdater": @UserUpdater
"./UserDeleter": @UserDeleter
"logger-sharelatex": log:->
"sanitizer":@sanitizer
'../Authentication/AuthenticationController': @AuthenticationController = {getLoggedInUserId: sinon.stub()}
@req = new MockRequest()
@res = new MockResponse()
@next = sinon.stub()
describe "getLoggedInUsersPersonalInfo", ->
beforeEach ->
@user =
_id: ObjectId()
@req.user = @user
@req.session.user = @user
@UserInfoController.sendFormattedPersonalInfo = sinon.stub()
@UserGetter.getUser = sinon.stub().callsArgWith(2, null, @user)
@AuthenticationController.getLoggedInUserId = sinon.stub().returns(@user._id)
@UserInfoController.getLoggedInUsersPersonalInfo(@req, @res, @next)
it "should call sendFormattedPersonalInfo", ->
@UserInfoController.sendFormattedPersonalInfo
.calledWith(@user, @res, @next)
.should.equal true
describe "getPersonalInfo", ->
beforeEach ->
@user_id = ObjectId().toString()
@user =
_id: ObjectId(@user_id)
@req.params = user_id: @user_id
describe "when the user exists", ->
beforeEach ->
@UserGetter.getUser = sinon.stub().callsArgWith(2, null, @user)
@UserInfoController.sendFormattedPersonalInfo = sinon.stub()
@UserInfoController.getPersonalInfo(@req, @res, @next)
it "should look up the user in the database", ->
@UserGetter.getUser
.calledWith(@user_id, { _id: true, first_name: true, last_name: true, email: true })
.should.equal true
it "should send the formatted details back to the client", ->
@UserInfoController.sendFormattedPersonalInfo
.calledWith(@user, @res, @next)
.should.equal true
describe "when the user does not exist", ->
beforeEach ->
@UserGetter.getUser = sinon.stub().callsArgWith(2, null, null)
@UserInfoController.sendFormattedPersonalInfo = sinon.stub()
@UserInfoController.getPersonalInfo(@req, @res, @next)
it "should return 404 to the client", ->
@res.statusCode.should.equal 404
describe "sendFormattedPersonalInfo", ->
beforeEach ->
@user =
_id: ObjectId()
first_name: "PI:NAME:<NAME>END_PI"
last_name: "PI:NAME:<NAME>END_PI"
email: "PI:EMAIL:<EMAIL>END_PI"
@formattedInfo =
id: @user._id.toString()
first_name: @user.first_name
last_name: @user.last_name
email: @user.email
@UserInfoController.formatPersonalInfo = sinon.stub().returns(@formattedInfo)
@UserInfoController.sendFormattedPersonalInfo @user, @res
it "should format the user details for the response", ->
@UserInfoController.formatPersonalInfo
.calledWith(@user)
.should.equal true
it "should send the formatted details back to the client", ->
@res.body.should.equal JSON.stringify(@formattedInfo)
describe "formatPersonalInfo", ->
it "should return the correctly formatted data", ->
@user =
_id: ObjectId()
first_name: "PI:NAME:<NAME>END_PI"
last_name: "PI:NAME:<NAME>END_PI"
email: "PI:EMAIL:<EMAIL>END_PI"
password: "PI:PASSWORD:<PASSWORD>END_PI"
signUpDate: new Date()
role:"student"
institution:"sheffield"
expect(@UserInfoController.formatPersonalInfo(@user)).to.deep.equal {
id: @user._id.toString()
first_name: @user.first_name
last_name: @user.last_name
email: @user.email
signUpDate: @user.signUpDate
role: @user.role
institution: @user.institution
}
|
[
{
"context": "ngid', ->\n server.inject({method: 'GET', url: '192.168.0.203:4000/recordings?meetingid=fbdbde6fd7b6499723a101c",
"end": 399,
"score": 0.9996058344841003,
"start": 386,
"tag": "IP_ADDRESS",
"value": "192.168.0.203"
},
{
"context": "68.0.203:4000/recordings?meetingid=... | labs/api/recordings/test/routetests.coffee | thong-hoczita/bigbluebutton | 0 | assert = require('chai').assert
hapi = require('hapi')
routes = require('../lib/routes')
# integration tests for API endpoint
# setup server with firing up - use inject instead
server = new hapi.Server()
server.route(routes.routes)
# parseurls endpoint test
describe 'checking recordings', ->
it 'recordings for a given meetingid', ->
server.inject({method: 'GET', url: '192.168.0.203:4000/recordings?meetingid=fbdbde6fd7b6499723a101c4c962f03843b4879c'}, (res) ->
#console.log "json:" + res.payload
array = [
{
'format': 'presentation'
'timestamp':'1396619572523'
}, {
'format': 'capture'
'timestamp':'1396623833044'
}, {
'format': 'presentation'
'timestamp':'1396620788271'
}, {
'format': 'presentation'
'timestamp':'1396622260421'
}, {
'format': 'capture'
'timestamp':'1396623833035'
}, {
'format': 'capture'
'timestamp':'1396623830000'
}, {
'format': 'capture'
'timestamp':'1396619572523'
}, {
'format': 'capture'
'timestamp':'1396622260421'
}, {
'format': 'capture'
'timestamp':'1396620788271'
}, {
'format': 'presentation'
'timestamp':'1396623833035'
}, {
'format': 'capture'
'timestamp':'1396623831111'
}
]
parsedOnce = JSON.parse(res.payload)
index = 0
while index < parsedOnce.length
assert.deepEqual(JSON.stringify(array[index]), parsedOnce[index])
index++
#console.log index
)
###it 'add - should add two numbers together', ->
server.inject({method: 'PUT', url: '/sum/add/5/5'}, (res) ->
console.log "json:" +JSON.stringify(res.payload)
assert.deepEqual({'equals': 10}, JSON.parse(res.payload))
done()
)###
###it 'add - should error if a string is passed', (done) ->
server.inject({method: 'PUT', url: '/sum/add/100/1'}, (res) ->
console.log "json:" +JSON.stringify(res)
assert.deepEqual({
'statusCode': 400
'error': 'Bad Request'
'message': 'the value of b must be a number'
'validation': {
'source': 'path'
'keys': [
'b'
]
}
}, JSON.parse(res.payload))
done()
)### | 104350 | assert = require('chai').assert
hapi = require('hapi')
routes = require('../lib/routes')
# integration tests for API endpoint
# setup server with firing up - use inject instead
server = new hapi.Server()
server.route(routes.routes)
# parseurls endpoint test
describe 'checking recordings', ->
it 'recordings for a given meetingid', ->
server.inject({method: 'GET', url: '192.168.0.203:4000/recordings?meetingid=fbdbde6fd7b6499<KEY>b<KEY>c'}, (res) ->
#console.log "json:" + res.payload
array = [
{
'format': 'presentation'
'timestamp':'1396619572523'
}, {
'format': 'capture'
'timestamp':'1396623833044'
}, {
'format': 'presentation'
'timestamp':'1396620788271'
}, {
'format': 'presentation'
'timestamp':'1396622260421'
}, {
'format': 'capture'
'timestamp':'1396623833035'
}, {
'format': 'capture'
'timestamp':'1396623830000'
}, {
'format': 'capture'
'timestamp':'1396619572523'
}, {
'format': 'capture'
'timestamp':'1396622260421'
}, {
'format': 'capture'
'timestamp':'1396620788271'
}, {
'format': 'presentation'
'timestamp':'1396623833035'
}, {
'format': 'capture'
'timestamp':'1396623831111'
}
]
parsedOnce = JSON.parse(res.payload)
index = 0
while index < parsedOnce.length
assert.deepEqual(JSON.stringify(array[index]), parsedOnce[index])
index++
#console.log index
)
###it 'add - should add two numbers together', ->
server.inject({method: 'PUT', url: '/sum/add/5/5'}, (res) ->
console.log "json:" +JSON.stringify(res.payload)
assert.deepEqual({'equals': 10}, JSON.parse(res.payload))
done()
)###
###it 'add - should error if a string is passed', (done) ->
server.inject({method: 'PUT', url: '/sum/add/100/1'}, (res) ->
console.log "json:" +JSON.stringify(res)
assert.deepEqual({
'statusCode': 400
'error': 'Bad Request'
'message': 'the value of b must be a number'
'validation': {
'source': 'path'
'keys': [
'<KEY>'
]
}
}, JSON.parse(res.payload))
done()
)### | true | assert = require('chai').assert
hapi = require('hapi')
routes = require('../lib/routes')
# integration tests for API endpoint
# setup server with firing up - use inject instead
server = new hapi.Server()
server.route(routes.routes)
# parseurls endpoint test
describe 'checking recordings', ->
it 'recordings for a given meetingid', ->
server.inject({method: 'GET', url: '192.168.0.203:4000/recordings?meetingid=fbdbde6fd7b6499PI:KEY:<KEY>END_PIbPI:KEY:<KEY>END_PIc'}, (res) ->
#console.log "json:" + res.payload
array = [
{
'format': 'presentation'
'timestamp':'1396619572523'
}, {
'format': 'capture'
'timestamp':'1396623833044'
}, {
'format': 'presentation'
'timestamp':'1396620788271'
}, {
'format': 'presentation'
'timestamp':'1396622260421'
}, {
'format': 'capture'
'timestamp':'1396623833035'
}, {
'format': 'capture'
'timestamp':'1396623830000'
}, {
'format': 'capture'
'timestamp':'1396619572523'
}, {
'format': 'capture'
'timestamp':'1396622260421'
}, {
'format': 'capture'
'timestamp':'1396620788271'
}, {
'format': 'presentation'
'timestamp':'1396623833035'
}, {
'format': 'capture'
'timestamp':'1396623831111'
}
]
parsedOnce = JSON.parse(res.payload)
index = 0
while index < parsedOnce.length
assert.deepEqual(JSON.stringify(array[index]), parsedOnce[index])
index++
#console.log index
)
###it 'add - should add two numbers together', ->
server.inject({method: 'PUT', url: '/sum/add/5/5'}, (res) ->
console.log "json:" +JSON.stringify(res.payload)
assert.deepEqual({'equals': 10}, JSON.parse(res.payload))
done()
)###
###it 'add - should error if a string is passed', (done) ->
server.inject({method: 'PUT', url: '/sum/add/100/1'}, (res) ->
console.log "json:" +JSON.stringify(res)
assert.deepEqual({
'statusCode': 400
'error': 'Bad Request'
'message': 'the value of b must be a number'
'validation': {
'source': 'path'
'keys': [
'PI:KEY:<KEY>END_PI'
]
}
}, JSON.parse(res.payload))
done()
)### |
[
{
"context": "#\n# Notes:\n# For fun and whimsy!\n#\n# Author:\n# Justin Swift <jswift@opendns.com>\n\n# Shamelessly stolen snippe",
"end": 992,
"score": 0.9996704459190369,
"start": 980,
"tag": "NAME",
"value": "Justin Swift"
},
{
"context": "For fun and whimsy!\n#\n# Author:\n#... | node_modules/hubot-zmachine/src/zmachine.coffee | mikelovskij/sauron2 | 6 | # Description
# Play zmachine with Hubot
#
# Configuration:
# HUBOT_ZMACHINE_SERVER - A zmachine-api server.
# HUBOT_ZMACHINE_ROOMS - Optional. A comma-delimited list of rooms that don't require prefixes; all text will be zmachineed.
# HUBOT_ZMACHINE_OT_PREFIX - Optional. If you've got an on-topic room, use this text as prefix for off-topic talk.
#
# Commands:
# hubot z list - Lists all in-progress games on a server (also syncs hubot with server)
# hubot z start <game> - Starts a game (default is 'zmachine1')
# hubot z <action> - Performs the action
# hubot z save <name> - Saves a game with the given name via the zmachine-api (you can save via an action, but that will only save a local copy)
# hubot z restore <name> - Loads a game with the given name via the zmachine-api
# hubot z stop - Ends the game for this channel
# hubot z purge - Purges all in-progress games from memory (to be re-synced)
#
# Notes:
# For fun and whimsy!
#
# Author:
# Justin Swift <jswift@opendns.com>
# Shamelessly stolen snippets
String::startsWith ?= (s) -> @[...s.length] is s
module.exports = (robot) ->
unless process.env.HUBOT_ZMACHINE_SERVER
robot.logger.error "HUBOT_ZMACHINE_SERVER not defined, cannot play zmachine!"
return
server = process.env.HUBOT_ZMACHINE_SERVER
if process.env.HUBOT_ZMACHINE_ROOMS
zmachineRooms = process.env.HUBOT_ZMACHINE_ROOMS.split(',')
robot.logger.debug "Playing on-topic zmachine in #{zmachineRooms}"
else
robot.logger.debug "No on-topic zmachine rooms"
zmachineRooms = []
if process.env.HUBOT_ZMACHINE_OT_PREFIX
offtopicPrefix = process.env.HUBOT_ZMACHINE_OT_PREFIX
else
offtopicPrefix = "#"
zmachinePids = {}
initialized = false
get_key = (msg) ->
if msg.message.user.room?
return msg.message.user.room
else
return msg.message.user.name
list_games = (msg, callback, args) ->
msg.http("#{server}/games")
.get() (err, res, body) ->
if err
msg.send "Error: #{err}"
return
else
bodyJ = JSON.parse(body)
zmachinePids = {}
zmachinePids[bodyJI.label] = bodyJI.pid for bodyJI in bodyJ
initialized = true
if callback?
callback msg, args
robot.logger.debug "Initialized: #{body}"
else
msg.send "Initialized: #{body}"
purge_list = (msg) ->
zmachinePids = {}
start_game = (msg, game) ->
# Make sure we don't already have a room going
key = get_key msg
if zmachinePids[key]?
msg.send "There's already a game for #{key}!"
return
# Start the game
msg.send "Starting game"
game = game
label = key
data = "game=#{game}&label=#{label}"
msg.http("#{server}/games")
.header('Content-Type', 'application/x-www-form-urlencoded')
.post(data) (err, res, body) ->
if err
msg.send "Error: #{err}"
return
else
bodyJ = JSON.parse(body)
pid = bodyJ.pid
zmachinePids[key] = pid
msg.send "Started game #{pid}"
msg.send bodyJ.data
stop_game = (msg) ->
key = get_key msg
if zmachinePids[key]?
pid = zmachinePids[key]
msg.send "Killing game #{key}"
msg.http("#{server}/games/#{pid}")
.delete() (err, res, body) ->
if err
msg.send "Error: #{err}"
return
else
msg.send body
list_games msg
do_action = (msg, action) ->
# Make sure we have a room going
key = get_key msg
if not zmachinePids[key]
msg.send "There's no game for #{key}!"
return
# Do the action
robot.logger.debug "Doing action: #{action}"
data = "action=#{action}"
pid = zmachinePids[key]
msg.http("#{server}/games/#{pid}/action")
.header('Content-Type', 'application/x-www-form-urlencoded')
.post(data) (err, res, body) ->
if err
msg.send "Error: #{err}"
return
else
try
bodyJ = JSON.parse(body)
msg.send bodyJ.data
catch
msg.send "Received non-JSON response:"
msg.send body
save_game = (msg, name) ->
# Make sure we have a room going
key = get_key msg
if not zmachinePids[key]
msg.send "There's no game for #{key}!"
return
# Start the game
msg.send "Saving game"
name = name
pid = zmachinePids[key]
data = "file=#{name}"
msg.http("#{server}/games/#{pid}/save")
.header('Content-Type', 'application/x-www-form-urlencoded')
.post(data) (err, res, body) ->
if err
msg.send "Error: #{err}"
return
else
try
bodyJ = JSON.parse(body)
msg.send bodyJ.data
catch
msg.send "Received non-JSON response:"
msg.send body
restore_game = (msg, name) ->
# Make sure we have a room going
key = get_key msg
if not zmachinePids[key]
msg.send "There's no game for #{key}! Start the game you want to restore first!"
return
# Restore the game
msg.send "Restoring game"
name = name
pid = zmachinePids[key]
data = "file=#{name}"
msg.http("#{server}/games/#{pid}/restore")
.header('Content-Type', 'application/x-www-form-urlencoded')
.post(data) (err, res, body) ->
if err
msg.send "Error: #{err}"
return
else
try
bodyJ = JSON.parse(body)
msg.send bodyJ.data
catch
msg.send "Received non-JSON response:"
msg.send body
process_zmachine_msg = (msg) ->
action = msg.match[1]
robot.logger.debug "User #{msg.message.user.name} in room #{msg.message.user.room} doing: #{action}"
if action.startsWith("start")
# Default to zmachine1, a classic
game = "zmachine1"
actionList = action.split " "
if actionList.length > 1
# Try whatever game the user specified
game = actionList[1]
start_game msg, game
else if action == "stop"
# End the game
stop_game msg
else if action == "list"
# List all in-progress games on the server (and sync with them)
list_games msg
else if action == "purge"
# Forget all in-progress games; use when you need to re-sync with the server
purge_list msg
else if action.startsWith("save")
# Save to cloud
name = "save"
actionList = action.split " "
if actionList.length > 1
# Try whatever game the user specified
name = actionList[1]
save_game msg, name
else if action.startsWith("restore")
# Restore from cloud
name = "save"
actionList = action.split " "
if actionList.length > 1
# Try whatever game the user specified
name = actionList[1]
restore_game msg, name
else
# Not a special command, so Just zmachine It
do_action msg, action
# For in-character rooms, hear/respond to everything
robot.hear /(.*)/i, (msg) ->
if not msg.message.user.room?
# Private messages always require direct zmachine-ing
return
if msg.message.user.room not in zmachineRooms
# If we're not in a direct room, do nothing
return
action = msg.match[1]
if action.startsWith("/me") or action.startsWith(offtopicPrefix)
# ignore actions and the offtopicPrefix
return
if action.startsWith(robot.name)
# If we're in a direct room, and we hear the robot name, ignore and let respond handle it
return
robot.logger.debug "User #{msg.message.user.name} in room #{msg.message.user.room} doing: #{action}"
if not initialized
list_games msg, do_action, action
else
do_action msg, action
# For all rooms, respond directly to "z " commands
robot.respond /(?:z)(?: me)? (.*)/i, (msg) ->
if not initialized
# If we've just come up, we should sync our list of on-going games
list_games msg, process_zmachine_msg
else
process_zmachine_msg msg
| 210921 | # Description
# Play zmachine with Hubot
#
# Configuration:
# HUBOT_ZMACHINE_SERVER - A zmachine-api server.
# HUBOT_ZMACHINE_ROOMS - Optional. A comma-delimited list of rooms that don't require prefixes; all text will be zmachineed.
# HUBOT_ZMACHINE_OT_PREFIX - Optional. If you've got an on-topic room, use this text as prefix for off-topic talk.
#
# Commands:
# hubot z list - Lists all in-progress games on a server (also syncs hubot with server)
# hubot z start <game> - Starts a game (default is 'zmachine1')
# hubot z <action> - Performs the action
# hubot z save <name> - Saves a game with the given name via the zmachine-api (you can save via an action, but that will only save a local copy)
# hubot z restore <name> - Loads a game with the given name via the zmachine-api
# hubot z stop - Ends the game for this channel
# hubot z purge - Purges all in-progress games from memory (to be re-synced)
#
# Notes:
# For fun and whimsy!
#
# Author:
# <NAME> <<EMAIL>>
# Shamelessly stolen snippets
String::startsWith ?= (s) -> @[...s.length] is s
module.exports = (robot) ->
unless process.env.HUBOT_ZMACHINE_SERVER
robot.logger.error "HUBOT_ZMACHINE_SERVER not defined, cannot play zmachine!"
return
server = process.env.HUBOT_ZMACHINE_SERVER
if process.env.HUBOT_ZMACHINE_ROOMS
zmachineRooms = process.env.HUBOT_ZMACHINE_ROOMS.split(',')
robot.logger.debug "Playing on-topic zmachine in #{zmachineRooms}"
else
robot.logger.debug "No on-topic zmachine rooms"
zmachineRooms = []
if process.env.HUBOT_ZMACHINE_OT_PREFIX
offtopicPrefix = process.env.HUBOT_ZMACHINE_OT_PREFIX
else
offtopicPrefix = "#"
zmachinePids = {}
initialized = false
get_key = (msg) ->
if msg.message.user.room?
return msg.message.user.room
else
return msg.message.user.name
list_games = (msg, callback, args) ->
msg.http("#{server}/games")
.get() (err, res, body) ->
if err
msg.send "Error: #{err}"
return
else
bodyJ = JSON.parse(body)
zmachinePids = {}
zmachinePids[bodyJI.label] = bodyJI.pid for bodyJI in bodyJ
initialized = true
if callback?
callback msg, args
robot.logger.debug "Initialized: #{body}"
else
msg.send "Initialized: #{body}"
purge_list = (msg) ->
zmachinePids = {}
start_game = (msg, game) ->
# Make sure we don't already have a room going
key = get_key msg
if zmachinePids[key]?
msg.send "There's already a game for #{key}!"
return
# Start the game
msg.send "Starting game"
game = game
label = key
data = "game=#{game}&label=#{label}"
msg.http("#{server}/games")
.header('Content-Type', 'application/x-www-form-urlencoded')
.post(data) (err, res, body) ->
if err
msg.send "Error: #{err}"
return
else
bodyJ = JSON.parse(body)
pid = bodyJ.pid
zmachinePids[key] = pid
msg.send "Started game #{pid}"
msg.send bodyJ.data
stop_game = (msg) ->
key = get_key msg
if zmachinePids[key]?
pid = zmachinePids[key]
msg.send "Killing game #{key}"
msg.http("#{server}/games/#{pid}")
.delete() (err, res, body) ->
if err
msg.send "Error: #{err}"
return
else
msg.send body
list_games msg
do_action = (msg, action) ->
# Make sure we have a room going
key = get_key msg
if not zmachinePids[key]
msg.send "There's no game for #{key}!"
return
# Do the action
robot.logger.debug "Doing action: #{action}"
data = "action=#{action}"
pid = zmachinePids[key]
msg.http("#{server}/games/#{pid}/action")
.header('Content-Type', 'application/x-www-form-urlencoded')
.post(data) (err, res, body) ->
if err
msg.send "Error: #{err}"
return
else
try
bodyJ = JSON.parse(body)
msg.send bodyJ.data
catch
msg.send "Received non-JSON response:"
msg.send body
save_game = (msg, name) ->
# Make sure we have a room going
key = get_key msg
if not zmachinePids[key]
msg.send "There's no game for #{key}!"
return
# Start the game
msg.send "Saving game"
name = name
pid = zmachinePids[key]
data = "file=#{name}"
msg.http("#{server}/games/#{pid}/save")
.header('Content-Type', 'application/x-www-form-urlencoded')
.post(data) (err, res, body) ->
if err
msg.send "Error: #{err}"
return
else
try
bodyJ = JSON.parse(body)
msg.send bodyJ.data
catch
msg.send "Received non-JSON response:"
msg.send body
restore_game = (msg, name) ->
# Make sure we have a room going
key = get_key msg
if not zmachinePids[key]
msg.send "There's no game for #{key}! Start the game you want to restore first!"
return
# Restore the game
msg.send "Restoring game"
name = name
pid = zmachinePids[key]
data = "file=#{name}"
msg.http("#{server}/games/#{pid}/restore")
.header('Content-Type', 'application/x-www-form-urlencoded')
.post(data) (err, res, body) ->
if err
msg.send "Error: #{err}"
return
else
try
bodyJ = JSON.parse(body)
msg.send bodyJ.data
catch
msg.send "Received non-JSON response:"
msg.send body
process_zmachine_msg = (msg) ->
action = msg.match[1]
robot.logger.debug "User #{msg.message.user.name} in room #{msg.message.user.room} doing: #{action}"
if action.startsWith("start")
# Default to zmachine1, a classic
game = "zmachine1"
actionList = action.split " "
if actionList.length > 1
# Try whatever game the user specified
game = actionList[1]
start_game msg, game
else if action == "stop"
# End the game
stop_game msg
else if action == "list"
# List all in-progress games on the server (and sync with them)
list_games msg
else if action == "purge"
# Forget all in-progress games; use when you need to re-sync with the server
purge_list msg
else if action.startsWith("save")
# Save to cloud
name = "save"
actionList = action.split " "
if actionList.length > 1
# Try whatever game the user specified
name = actionList[1]
save_game msg, name
else if action.startsWith("restore")
# Restore from cloud
name = "save"
actionList = action.split " "
if actionList.length > 1
# Try whatever game the user specified
name = actionList[1]
restore_game msg, name
else
# Not a special command, so Just zmachine It
do_action msg, action
# For in-character rooms, hear/respond to everything
robot.hear /(.*)/i, (msg) ->
if not msg.message.user.room?
# Private messages always require direct zmachine-ing
return
if msg.message.user.room not in zmachineRooms
# If we're not in a direct room, do nothing
return
action = msg.match[1]
if action.startsWith("/me") or action.startsWith(offtopicPrefix)
# ignore actions and the offtopicPrefix
return
if action.startsWith(robot.name)
# If we're in a direct room, and we hear the robot name, ignore and let respond handle it
return
robot.logger.debug "User #{msg.message.user.name} in room #{msg.message.user.room} doing: #{action}"
if not initialized
list_games msg, do_action, action
else
do_action msg, action
# For all rooms, respond directly to "z " commands
robot.respond /(?:z)(?: me)? (.*)/i, (msg) ->
if not initialized
# If we've just come up, we should sync our list of on-going games
list_games msg, process_zmachine_msg
else
process_zmachine_msg msg
| true | # Description
# Play zmachine with Hubot
#
# Configuration:
# HUBOT_ZMACHINE_SERVER - A zmachine-api server.
# HUBOT_ZMACHINE_ROOMS - Optional. A comma-delimited list of rooms that don't require prefixes; all text will be zmachineed.
# HUBOT_ZMACHINE_OT_PREFIX - Optional. If you've got an on-topic room, use this text as prefix for off-topic talk.
#
# Commands:
# hubot z list - Lists all in-progress games on a server (also syncs hubot with server)
# hubot z start <game> - Starts a game (default is 'zmachine1')
# hubot z <action> - Performs the action
# hubot z save <name> - Saves a game with the given name via the zmachine-api (you can save via an action, but that will only save a local copy)
# hubot z restore <name> - Loads a game with the given name via the zmachine-api
# hubot z stop - Ends the game for this channel
# hubot z purge - Purges all in-progress games from memory (to be re-synced)
#
# Notes:
# For fun and whimsy!
#
# Author:
# PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
# Shamelessly stolen snippets
String::startsWith ?= (s) -> @[...s.length] is s
module.exports = (robot) ->
unless process.env.HUBOT_ZMACHINE_SERVER
robot.logger.error "HUBOT_ZMACHINE_SERVER not defined, cannot play zmachine!"
return
server = process.env.HUBOT_ZMACHINE_SERVER
if process.env.HUBOT_ZMACHINE_ROOMS
zmachineRooms = process.env.HUBOT_ZMACHINE_ROOMS.split(',')
robot.logger.debug "Playing on-topic zmachine in #{zmachineRooms}"
else
robot.logger.debug "No on-topic zmachine rooms"
zmachineRooms = []
if process.env.HUBOT_ZMACHINE_OT_PREFIX
offtopicPrefix = process.env.HUBOT_ZMACHINE_OT_PREFIX
else
offtopicPrefix = "#"
zmachinePids = {}
initialized = false
get_key = (msg) ->
if msg.message.user.room?
return msg.message.user.room
else
return msg.message.user.name
list_games = (msg, callback, args) ->
msg.http("#{server}/games")
.get() (err, res, body) ->
if err
msg.send "Error: #{err}"
return
else
bodyJ = JSON.parse(body)
zmachinePids = {}
zmachinePids[bodyJI.label] = bodyJI.pid for bodyJI in bodyJ
initialized = true
if callback?
callback msg, args
robot.logger.debug "Initialized: #{body}"
else
msg.send "Initialized: #{body}"
purge_list = (msg) ->
zmachinePids = {}
start_game = (msg, game) ->
# Make sure we don't already have a room going
key = get_key msg
if zmachinePids[key]?
msg.send "There's already a game for #{key}!"
return
# Start the game
msg.send "Starting game"
game = game
label = key
data = "game=#{game}&label=#{label}"
msg.http("#{server}/games")
.header('Content-Type', 'application/x-www-form-urlencoded')
.post(data) (err, res, body) ->
if err
msg.send "Error: #{err}"
return
else
bodyJ = JSON.parse(body)
pid = bodyJ.pid
zmachinePids[key] = pid
msg.send "Started game #{pid}"
msg.send bodyJ.data
stop_game = (msg) ->
key = get_key msg
if zmachinePids[key]?
pid = zmachinePids[key]
msg.send "Killing game #{key}"
msg.http("#{server}/games/#{pid}")
.delete() (err, res, body) ->
if err
msg.send "Error: #{err}"
return
else
msg.send body
list_games msg
do_action = (msg, action) ->
# Make sure we have a room going
key = get_key msg
if not zmachinePids[key]
msg.send "There's no game for #{key}!"
return
# Do the action
robot.logger.debug "Doing action: #{action}"
data = "action=#{action}"
pid = zmachinePids[key]
msg.http("#{server}/games/#{pid}/action")
.header('Content-Type', 'application/x-www-form-urlencoded')
.post(data) (err, res, body) ->
if err
msg.send "Error: #{err}"
return
else
try
bodyJ = JSON.parse(body)
msg.send bodyJ.data
catch
msg.send "Received non-JSON response:"
msg.send body
save_game = (msg, name) ->
# Make sure we have a room going
key = get_key msg
if not zmachinePids[key]
msg.send "There's no game for #{key}!"
return
# Start the game
msg.send "Saving game"
name = name
pid = zmachinePids[key]
data = "file=#{name}"
msg.http("#{server}/games/#{pid}/save")
.header('Content-Type', 'application/x-www-form-urlencoded')
.post(data) (err, res, body) ->
if err
msg.send "Error: #{err}"
return
else
try
bodyJ = JSON.parse(body)
msg.send bodyJ.data
catch
msg.send "Received non-JSON response:"
msg.send body
restore_game = (msg, name) ->
# Make sure we have a room going
key = get_key msg
if not zmachinePids[key]
msg.send "There's no game for #{key}! Start the game you want to restore first!"
return
# Restore the game
msg.send "Restoring game"
name = name
pid = zmachinePids[key]
data = "file=#{name}"
msg.http("#{server}/games/#{pid}/restore")
.header('Content-Type', 'application/x-www-form-urlencoded')
.post(data) (err, res, body) ->
if err
msg.send "Error: #{err}"
return
else
try
bodyJ = JSON.parse(body)
msg.send bodyJ.data
catch
msg.send "Received non-JSON response:"
msg.send body
process_zmachine_msg = (msg) ->
action = msg.match[1]
robot.logger.debug "User #{msg.message.user.name} in room #{msg.message.user.room} doing: #{action}"
if action.startsWith("start")
# Default to zmachine1, a classic
game = "zmachine1"
actionList = action.split " "
if actionList.length > 1
# Try whatever game the user specified
game = actionList[1]
start_game msg, game
else if action == "stop"
# End the game
stop_game msg
else if action == "list"
# List all in-progress games on the server (and sync with them)
list_games msg
else if action == "purge"
# Forget all in-progress games; use when you need to re-sync with the server
purge_list msg
else if action.startsWith("save")
# Save to cloud
name = "save"
actionList = action.split " "
if actionList.length > 1
# Try whatever game the user specified
name = actionList[1]
save_game msg, name
else if action.startsWith("restore")
# Restore from cloud
name = "save"
actionList = action.split " "
if actionList.length > 1
# Try whatever game the user specified
name = actionList[1]
restore_game msg, name
else
# Not a special command, so Just zmachine It
do_action msg, action
# For in-character rooms, hear/respond to everything
robot.hear /(.*)/i, (msg) ->
if not msg.message.user.room?
# Private messages always require direct zmachine-ing
return
if msg.message.user.room not in zmachineRooms
# If we're not in a direct room, do nothing
return
action = msg.match[1]
if action.startsWith("/me") or action.startsWith(offtopicPrefix)
# ignore actions and the offtopicPrefix
return
if action.startsWith(robot.name)
# If we're in a direct room, and we hear the robot name, ignore and let respond handle it
return
robot.logger.debug "User #{msg.message.user.name} in room #{msg.message.user.room} doing: #{action}"
if not initialized
list_games msg, do_action, action
else
do_action msg, action
# For all rooms, respond directly to "z " commands
robot.respond /(?:z)(?: me)? (.*)/i, (msg) ->
if not initialized
# If we've just come up, we should sync our list of on-going games
list_games msg, process_zmachine_msg
else
process_zmachine_msg msg
|
[
{
"context": "# Copyright (c) 2015 naymspace software (Dennis Nissen)\n#\n# Licensed under the Apache License, Version 2",
"end": 54,
"score": 0.9998677372932434,
"start": 41,
"tag": "NAME",
"value": "Dennis Nissen"
}
] | src/app/helper.spec.coffee | ogumi/client | 0 | # Copyright (c) 2015 naymspace software (Dennis Nissen)
#
# 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.
beforeEach module 'webClient', ($provide, $translateProvider, $stateProvider, $injector) ->
$provide.factory 'customLoader', ($q) ->
->
deferred = $q.defer()
deferred.resolve {}
deferred.promise
$translateProvider.useLoader 'customLoader'
return
beforeEach inject ($rootScope, $injector, Restangular, localStorageService) ->
$httpBackend = $injector.get('$httpBackend')
$httpBackend.when('GET', 'app/layout/header.html').respond(200)
return
| 113969 | # Copyright (c) 2015 naymspace software (<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.
beforeEach module 'webClient', ($provide, $translateProvider, $stateProvider, $injector) ->
$provide.factory 'customLoader', ($q) ->
->
deferred = $q.defer()
deferred.resolve {}
deferred.promise
$translateProvider.useLoader 'customLoader'
return
beforeEach inject ($rootScope, $injector, Restangular, localStorageService) ->
$httpBackend = $injector.get('$httpBackend')
$httpBackend.when('GET', 'app/layout/header.html').respond(200)
return
| true | # Copyright (c) 2015 naymspace software (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.
beforeEach module 'webClient', ($provide, $translateProvider, $stateProvider, $injector) ->
$provide.factory 'customLoader', ($q) ->
->
deferred = $q.defer()
deferred.resolve {}
deferred.promise
$translateProvider.useLoader 'customLoader'
return
beforeEach inject ($rootScope, $injector, Restangular, localStorageService) ->
$httpBackend = $injector.get('$httpBackend')
$httpBackend.when('GET', 'app/layout/header.html').respond(200)
return
|
[
{
"context": "###\nCopyright 2013 Simon Lydell\n\nThis file is part of throws.\n\nthrows is free sof",
"end": 31,
"score": 0.9998680353164673,
"start": 19,
"tag": "NAME",
"value": "Simon Lydell"
}
] | node_modules/parse-stack/test/common.coffee | KartikVashisth/Camper_Website | 7 | ###
Copyright 2013 Simon Lydell
This file is part of throws.
throws is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser
General Public License as published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
throws is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General
Public License for more details.
You should have received a copy of the GNU Lesser General Public License along with throws. If not,
see <http://www.gnu.org/licenses/>.
###
assert = require "yaba"
throws = require "throws"
equals = require "equals"
throws.messageHolder = assert
equal = (actual, expected)->
assert.actual = actual
assert.expected = expected
equals(actual, expected)
beforeEach ->
assert.runs = 0
module.exports = {assert, throws, equal}
| 16206 | ###
Copyright 2013 <NAME>
This file is part of throws.
throws is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser
General Public License as published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
throws is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General
Public License for more details.
You should have received a copy of the GNU Lesser General Public License along with throws. If not,
see <http://www.gnu.org/licenses/>.
###
assert = require "yaba"
throws = require "throws"
equals = require "equals"
throws.messageHolder = assert
equal = (actual, expected)->
assert.actual = actual
assert.expected = expected
equals(actual, expected)
beforeEach ->
assert.runs = 0
module.exports = {assert, throws, equal}
| true | ###
Copyright 2013 PI:NAME:<NAME>END_PI
This file is part of throws.
throws is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser
General Public License as published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
throws is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General
Public License for more details.
You should have received a copy of the GNU Lesser General Public License along with throws. If not,
see <http://www.gnu.org/licenses/>.
###
assert = require "yaba"
throws = require "throws"
equals = require "equals"
throws.messageHolder = assert
equal = (actual, expected)->
assert.actual = actual
assert.expected = expected
equals(actual, expected)
beforeEach ->
assert.runs = 0
module.exports = {assert, throws, equal}
|
[
{
"context": "###\n Fluidity\n Copyright (c) 2012 Kris Hedges <kris@inkspeck.com>, http://Inkspeck.com\n MIT Lic",
"end": 45,
"score": 0.999867856502533,
"start": 34,
"tag": "NAME",
"value": "Kris Hedges"
},
{
"context": "###\n Fluidity\n Copyright (c) 2012 Kris Hedges <kris@inkspeck... | lib/fluidity.coffee | InkSpeck/fluidity | 11 | ###
Fluidity
Copyright (c) 2012 Kris Hedges <kris@inkspeck.com>, http://Inkspeck.com
MIT Licensed
###
stylus = require 'stylus'
nodes = stylus.nodes
utils = stylus.utils
exports.version = '0.1.6'
exports.path = __dirname
plugin = ->
return (style) ->
style.include(__dirname)
exports = module.exports = plugin
| 200173 | ###
Fluidity
Copyright (c) 2012 <NAME> <<EMAIL>>, http://Inkspeck.com
MIT Licensed
###
stylus = require 'stylus'
nodes = stylus.nodes
utils = stylus.utils
exports.version = '0.1.6'
exports.path = __dirname
plugin = ->
return (style) ->
style.include(__dirname)
exports = module.exports = plugin
| true | ###
Fluidity
Copyright (c) 2012 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>, http://Inkspeck.com
MIT Licensed
###
stylus = require 'stylus'
nodes = stylus.nodes
utils = stylus.utils
exports.version = '0.1.6'
exports.path = __dirname
plugin = ->
return (style) ->
style.include(__dirname)
exports = module.exports = plugin
|
[
{
"context": "(Darwin)\nComment: GPGTools - https://gpgtools.org\n\nmQGiBFMFCfkRBACWAeNfoYui4Kmg/Z6x0wTiUyAc2qO4k0mn2nDRxg2ieKxoQYAu\nmv8VIdlUdokAblfoaBRjuN7tfB4D+wvGskgEPpIVBDTLylnzLSr/gZENKif0WQNm\nfIMsgUYjjx+HbEcdyF1aQZ8u6uvwjLkHYvuRc6hcf4jy1TTGMYxgbzJJewCg5wrQ\nUc4gfhwzqrWWCfkZDv0wuScD/0pVgq8gk0BtTfncKfYdNz... | test/files/dsa.iced | samkenxstream/kbpgp | 464 | {KeyManager} = require '../../'
{do_message,Processor} = require '../../lib/openpgp/processor'
{burn} = require '../../lib/openpgp/burner'
testing_unixtime = Math.floor(new Date(2014, 2, 20)/1000)
#=================================================================
dlg = {
key : """
-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: GnuPG/MacGPG2 v2.0.22 (Darwin)
Comment: GPGTools - https://gpgtools.org
mQGiBFMFCfkRBACWAeNfoYui4Kmg/Z6x0wTiUyAc2qO4k0mn2nDRxg2ieKxoQYAu
mv8VIdlUdokAblfoaBRjuN7tfB4D+wvGskgEPpIVBDTLylnzLSr/gZENKif0WQNm
fIMsgUYjjx+HbEcdyF1aQZ8u6uvwjLkHYvuRc6hcf4jy1TTGMYxgbzJJewCg5wrQ
Uc4gfhwzqrWWCfkZDv0wuScD/0pVgq8gk0BtTfncKfYdNzGe/sEEKC2YWUKDDXM6
U9g4o+V45KxX6CRTxPx6ZtnAyVY0jA+C2Ad0YAiTJloQSjTR5mOcff7Q4Y5TNdgi
wkIe/nJsfKMzbAcAp1rTOf8GRmyjGmH4y3agKD2dWAqZ5DVufN6zAe+Uo+6pGJmU
yyYsA/wMQYSodf8rVZOtgtH7Rt26VxHj3Mjl/BC+lDjVB+hHexYZf/uRxbcmUnVd
ZY+H2Z0gvCjgC/KFyJmWpsuomUs06ODzq2hq1yJRqeHqDvPp+8yJVsvOsdo6oKOz
fS295sIpo/2yYjloaIZu8d4Uz5wY8GaKSX8UZ4FL2mjhAqEhpbQfRGF2aWQgTGxv
eWQgR2VvcmdlIDxkbGdAZ292LnVrPohnBBMRCgAnBQJTBQn5AhsDBQkSzAMABQsJ
CAcDBRUKCQgLBRYCAwEAAh4BAheAAAoJEHGE0rkf9XmXw8MAmQGB2V8G75S5JTke
LWYec+iIb4cDAJ9p2To50haAhlBC024W91cmddudZg==
=VRBx
-----END PGP PUBLIC KEY BLOCK-----
""",
sigs : [ """
-----BEGIN PGP MESSAGE-----
Version: GnuPG/MacGPG2 v2.0.22 (Darwin)
Comment: GPGTools - https://gpgtools.org
owGbwMvMwCRY2HJpp/zXyumMp32TGIJZeab75ZcoJCWm5FTqKCTn5xVnpqQWZeal
K3gqlCcWKxSnJpakpigkpZaUp6bmKXilFpcWKzhnFGUWlygk5qUo+CUW5Oek5ufp
cXW4sTAIMjGwsTKBDGXg4hSA2RRxmGGuGAvn2sXdU95NC3x7Mfts0aLMJp7XDAv2
q85awd3aY9dgbP7Q0Pnnxdvqf/wA
=o8cb
-----END PGP MESSAGE-----"""
]
}
#=================================================================
exports.verify_sigs = (T,cb) ->
opts = now : testing_unixtime
await KeyManager.import_from_armored_pgp { raw : dlg.key, opts }, defer err, km
T.no_error err
fp = km.get_pgp_fingerprint().toString('hex').toUpperCase()
T.assert fp, "a fingerprint came back"
fp2 = "91D6582E37E81A9A7F19D2F57184D2B91FF57997"
T.equal fp, fp2, "the right fingerprint"
for sig in dlg.sigs
await do_message { armored : sig, keyfetch : km, now: testing_unixtime }, defer err, literals
T.no_error err
T.equal literals.length, 1, "only got 1 literal packet back"
lit = literals[0]
signer = lit.get_data_signer()
T.assert signer?, "we were signed"
fp3 = signer.get_key_manager().get_pgp_fingerprint().toString('hex').toUpperCase()
T.equal fp, fp3, "the literal data packet was signed with the right key"
cb()
#=================================================================
gbc = {
key : """
-----BEGIN PGP PRIVATE KEY BLOCK-----
Version: GnuPG v1.4.14 (GNU/Linux)
lQHhBFMFX/YRBACKwOOj7dkyHb8J3qDOvS0ZEcgiZnFCaLCh07GWV/S/HEelVaDF
BIVdn2Ho/j80HWkRMJAFqNBoEfqqz1n6MFxZNgUlWOOSdUIkOq2qcZhqQqcvwqJU
FxKKO7gKI037HBYlgmgD2/LGAWGZQDHDciDqcy+SEwvFB+y/x9bSSCornwCgnVzp
C77KgeXIS26JtbMeNd7x+xkD/3NjzK0jF3v7fASE2Eik+VlGiXkk8IuV32LYAtkd
Qyjw+Xqx6T3gtOEPOJWd0MlOdb75J/EMJYN+10yMCIFgMTUexL4uVRKMRBy3JBwW
kHApO+LG/2g5ZHupaqBixfcpya5N1T+sNNlPQ1pvCTANakp1ELR2BAb6g5PGuQab
scboA/9LsjYMdTqXQVCj9ck0+kSFxeBygobDqQIwd4BW2fMRzRg7kFZdICtzYSSi
2z9iHmzC+OiokPKHnVSYRKSZ5cHe/ke2SunptKzpFhWxKO5FYRODX3txvEMUUst+
FE1f/+dnLQyxY5BB1fRcpUlUtRZ453lObMm0aY652bgyW/6CSP4DAwJVX0fqCIms
8WC03phNbtqDYUIajoX+e+p8wBBUNRZo4JSV8s7OTI+MMTR0MO38+9B+cM9KKmbG
A0Clx7Q3R2VvcmdlcyBCZW5qYW1pbiBDbGVtZW5jZWF1IChwdyBpcyAnYWJjZCcp
IDxnYmNAZ292LmZyPohoBBMRAgAoBQJTBV/2AhsDBQkSzAMABgsJCAcDAgYVCAIJ
CgsEFgIDAQIeAQIXgAAKCRA350+UAcLjmJWYAKCYHsrgY+k3bQ7ov2XHf9SjX7qU
twCfebPu3y0/Ll7OdCw5fcXuzbCUbjY=
=s2F5
-----END PGP PRIVATE KEY BLOCK-----
""",
msg : """
We have just won the most terrible war in history, yet here is
a Frenchman who misses his target 6 out of 7 times at point-blank
range. Of course this fellow must be punished for the careless
use of a dangerous weapon and for poor marksmanship. I suggest
that he be locked up for eight years, with intensive training
in a shooting gallery."""
}
exports.dsa_round_trip = (T,cb) ->
opts = now : testing_unixtime
await KeyManager.import_from_armored_pgp { raw : gbc.key, opts }, defer err, km
T.no_error err
T.equal km.get_primary_keypair().nbits(), 1024, "the right number of bits"
await km.unlock_pgp { passphrase : 'abcd' }, defer err
T.no_error err
key = km.find_signing_pgp_key()
await burn { msg : gbc.msg, signing_key : key, opts }, defer err, asc
T.no_error err
await do_message { armored : asc, keyfetch : km, now : testing_unixtime }, defer esc
T.no_error err
cb()
#=================================================================
| 88318 | {KeyManager} = require '../../'
{do_message,Processor} = require '../../lib/openpgp/processor'
{burn} = require '../../lib/openpgp/burner'
testing_unixtime = Math.floor(new Date(2014, 2, 20)/1000)
#=================================================================
dlg = {
key : """
-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: GnuPG/MacGPG2 v2.0.22 (Darwin)
Comment: GPGTools - https://gpgtools.org
<KEY>
-----END PGP PUBLIC KEY BLOCK-----
""",
sigs : [ """
-----BEGIN PGP MESSAGE-----
Version: GnuPG/MacGPG2 v2.0.22 (Darwin)
Comment: GPGTools - https://gpgtools.org
<KEY>
-----END PGP MESSAGE-----"""
]
}
#=================================================================
exports.verify_sigs = (T,cb) ->
opts = now : testing_unixtime
await KeyManager.import_from_armored_pgp { raw : dlg.key, opts }, defer err, km
T.no_error err
fp = km.get_pgp_fingerprint().toString('hex').toUpperCase()
T.assert fp, "a fingerprint came back"
fp2 = "91D6582E37E81A9A7F19D2F57184D2B91FF57997"
T.equal fp, fp2, "the right fingerprint"
for sig in dlg.sigs
await do_message { armored : sig, keyfetch : km, now: testing_unixtime }, defer err, literals
T.no_error err
T.equal literals.length, 1, "only got 1 literal packet back"
lit = literals[0]
signer = lit.get_data_signer()
T.assert signer?, "we were signed"
fp3 = signer.get_key_manager().get_pgp_fingerprint().toString('hex').toUpperCase()
T.equal fp, fp3, "the literal data packet was signed with the right key"
cb()
#=================================================================
gbc = {
key : """
-----BEGIN PGP PRIVATE KEY BLOCK-----
Version: GnuPG v1.4.14 (GNU/Linux)
<KEY>
2z<KEY>
-----END PGP PRIVATE KEY BLOCK-----
""",
msg : """
We have just won the most terrible war in history, yet here is
a Frenchman who misses his target 6 out of 7 times at point-blank
range. Of course this fellow must be punished for the careless
use of a dangerous weapon and for poor marksmanship. I suggest
that he be locked up for eight years, with intensive training
in a shooting gallery."""
}
exports.dsa_round_trip = (T,cb) ->
opts = now : testing_unixtime
await KeyManager.import_from_armored_pgp { raw : gbc.key, opts }, defer err, km
T.no_error err
T.equal km.get_primary_keypair().nbits(), 1024, "the right number of bits"
await km.unlock_pgp { passphrase : '<PASSWORD>' }, defer err
T.no_error err
key = km.find_signing_pgp_key()
await burn { msg : gbc.msg, signing_key : key, opts }, defer err, asc
T.no_error err
await do_message { armored : asc, keyfetch : km, now : testing_unixtime }, defer esc
T.no_error err
cb()
#=================================================================
| true | {KeyManager} = require '../../'
{do_message,Processor} = require '../../lib/openpgp/processor'
{burn} = require '../../lib/openpgp/burner'
testing_unixtime = Math.floor(new Date(2014, 2, 20)/1000)
#=================================================================
dlg = {
key : """
-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: GnuPG/MacGPG2 v2.0.22 (Darwin)
Comment: GPGTools - https://gpgtools.org
PI:KEY:<KEY>END_PI
-----END PGP PUBLIC KEY BLOCK-----
""",
sigs : [ """
-----BEGIN PGP MESSAGE-----
Version: GnuPG/MacGPG2 v2.0.22 (Darwin)
Comment: GPGTools - https://gpgtools.org
PI:KEY:<KEY>END_PI
-----END PGP MESSAGE-----"""
]
}
#=================================================================
exports.verify_sigs = (T,cb) ->
opts = now : testing_unixtime
await KeyManager.import_from_armored_pgp { raw : dlg.key, opts }, defer err, km
T.no_error err
fp = km.get_pgp_fingerprint().toString('hex').toUpperCase()
T.assert fp, "a fingerprint came back"
fp2 = "91D6582E37E81A9A7F19D2F57184D2B91FF57997"
T.equal fp, fp2, "the right fingerprint"
for sig in dlg.sigs
await do_message { armored : sig, keyfetch : km, now: testing_unixtime }, defer err, literals
T.no_error err
T.equal literals.length, 1, "only got 1 literal packet back"
lit = literals[0]
signer = lit.get_data_signer()
T.assert signer?, "we were signed"
fp3 = signer.get_key_manager().get_pgp_fingerprint().toString('hex').toUpperCase()
T.equal fp, fp3, "the literal data packet was signed with the right key"
cb()
#=================================================================
gbc = {
key : """
-----BEGIN PGP PRIVATE KEY BLOCK-----
Version: GnuPG v1.4.14 (GNU/Linux)
PI:KEY:<KEY>END_PI
2zPI:KEY:<KEY>END_PI
-----END PGP PRIVATE KEY BLOCK-----
""",
msg : """
We have just won the most terrible war in history, yet here is
a Frenchman who misses his target 6 out of 7 times at point-blank
range. Of course this fellow must be punished for the careless
use of a dangerous weapon and for poor marksmanship. I suggest
that he be locked up for eight years, with intensive training
in a shooting gallery."""
}
exports.dsa_round_trip = (T,cb) ->
opts = now : testing_unixtime
await KeyManager.import_from_armored_pgp { raw : gbc.key, opts }, defer err, km
T.no_error err
T.equal km.get_primary_keypair().nbits(), 1024, "the right number of bits"
await km.unlock_pgp { passphrase : 'PI:PASSWORD:<PASSWORD>END_PI' }, defer err
T.no_error err
key = km.find_signing_pgp_key()
await burn { msg : gbc.msg, signing_key : key, opts }, defer err, asc
T.no_error err
await do_message { armored : asc, keyfetch : km, now : testing_unixtime }, defer esc
T.no_error err
cb()
#=================================================================
|
[
{
"context": "# Copyright (c) Konode. All rights reserved.\n# This source code is subje",
"end": 22,
"score": 0.9953069686889648,
"start": 16,
"tag": "NAME",
"value": "Konode"
}
] | src/programsDropdown.coffee | LogicalOutcomes/KoNote | 1 | # Copyright (c) Konode. All rights reserved.
# This source code is subject to the terms of the Mozilla Public License, v. 2.0
# that can be found in the LICENSE file or at: http://mozilla.org/MPL/2.0
# Dropdown component for program selection, minus selected program
Imm = require 'immutable'
Term = require './term'
load = (win) ->
React = win.React
R = React.DOM
B = require('./utils/reactBootstrap').load(win, 'DropdownButton', 'MenuItem')
ColorKeyBubble = require('./colorKeyBubble').load(win)
{FaIcon} = require('./utils').load(win)
ProgramsDropdown = React.createFactory React.createClass
displayName: 'ProgramsDropdown'
mixins: [React.addons.PureRenderMixin]
propTypes: {
selectedProgramId: React.PropTypes.string
programsById: React.PropTypes.instanceOf(Imm.Map).isRequired
placeholder: React.PropTypes.string
onSelect: React.PropTypes.func.isRequired
bsStyle: React.PropTypes.string
}
getDefaultProps: -> {
selectedProgramId: ''
placeholder: "No #{Term 'Program'}"
excludeNone: false
bsStyle: 'link'
}
getInitialState: -> {
isOpen: null
}
toggle: ->
@setState {isOpen: not @state.isOpen}
render: ->
# selectedProgram can be null, so bypasses getDefaultProps
selectedProgramId = @props.selectedProgramId or ''
selectedProgram = @props.programsById.get(selectedProgramId) or Imm.Map()
remainingPrograms = @props.programsById.delete(selectedProgramId).valueSeq().toList()
R.span({
className: 'programsDropdown'
onClick: @toggle
},
B.DropdownButton({
ref: 'dropdown'
id: 'programsDropdown'
open: @state.isOpen
onClose: @toggle
bsStyle: @props.bsStyle
pullRight: true
title: R.span({
className: 'currentProgram'
style: { borderBottomColor: selectedProgram.get('colorKeyHex')}
},
selectedProgram.get('name') or @props.placeholder
)
},
(remainingPrograms
.filter (program) =>
program.get('status') is 'default'
.map (program) =>
B.MenuItem({
key: program.get('id')
onClick: @props.onSelect.bind null, program.get('id')
},
program.get('name')
' '
ColorKeyBubble({colorKeyHex: program.get('colorKeyHex')})
)
)
(if not remainingPrograms.isEmpty() and selectedProgramId and not @props.excludeNone
B.MenuItem({divider: true})
)
(if selectedProgramId and not @props.excludeNone
B.MenuItem({
onClick: @props.onSelect.bind null, null
},
"None "
FaIcon('ban')
)
)
)
)
return ProgramsDropdown
module.exports = {load}
| 185280 | # Copyright (c) <NAME>. All rights reserved.
# This source code is subject to the terms of the Mozilla Public License, v. 2.0
# that can be found in the LICENSE file or at: http://mozilla.org/MPL/2.0
# Dropdown component for program selection, minus selected program
Imm = require 'immutable'
Term = require './term'
load = (win) ->
React = win.React
R = React.DOM
B = require('./utils/reactBootstrap').load(win, 'DropdownButton', 'MenuItem')
ColorKeyBubble = require('./colorKeyBubble').load(win)
{FaIcon} = require('./utils').load(win)
ProgramsDropdown = React.createFactory React.createClass
displayName: 'ProgramsDropdown'
mixins: [React.addons.PureRenderMixin]
propTypes: {
selectedProgramId: React.PropTypes.string
programsById: React.PropTypes.instanceOf(Imm.Map).isRequired
placeholder: React.PropTypes.string
onSelect: React.PropTypes.func.isRequired
bsStyle: React.PropTypes.string
}
getDefaultProps: -> {
selectedProgramId: ''
placeholder: "No #{Term 'Program'}"
excludeNone: false
bsStyle: 'link'
}
getInitialState: -> {
isOpen: null
}
toggle: ->
@setState {isOpen: not @state.isOpen}
render: ->
# selectedProgram can be null, so bypasses getDefaultProps
selectedProgramId = @props.selectedProgramId or ''
selectedProgram = @props.programsById.get(selectedProgramId) or Imm.Map()
remainingPrograms = @props.programsById.delete(selectedProgramId).valueSeq().toList()
R.span({
className: 'programsDropdown'
onClick: @toggle
},
B.DropdownButton({
ref: 'dropdown'
id: 'programsDropdown'
open: @state.isOpen
onClose: @toggle
bsStyle: @props.bsStyle
pullRight: true
title: R.span({
className: 'currentProgram'
style: { borderBottomColor: selectedProgram.get('colorKeyHex')}
},
selectedProgram.get('name') or @props.placeholder
)
},
(remainingPrograms
.filter (program) =>
program.get('status') is 'default'
.map (program) =>
B.MenuItem({
key: program.get('id')
onClick: @props.onSelect.bind null, program.get('id')
},
program.get('name')
' '
ColorKeyBubble({colorKeyHex: program.get('colorKeyHex')})
)
)
(if not remainingPrograms.isEmpty() and selectedProgramId and not @props.excludeNone
B.MenuItem({divider: true})
)
(if selectedProgramId and not @props.excludeNone
B.MenuItem({
onClick: @props.onSelect.bind null, null
},
"None "
FaIcon('ban')
)
)
)
)
return ProgramsDropdown
module.exports = {load}
| true | # Copyright (c) PI:NAME:<NAME>END_PI. All rights reserved.
# This source code is subject to the terms of the Mozilla Public License, v. 2.0
# that can be found in the LICENSE file or at: http://mozilla.org/MPL/2.0
# Dropdown component for program selection, minus selected program
Imm = require 'immutable'
Term = require './term'
load = (win) ->
React = win.React
R = React.DOM
B = require('./utils/reactBootstrap').load(win, 'DropdownButton', 'MenuItem')
ColorKeyBubble = require('./colorKeyBubble').load(win)
{FaIcon} = require('./utils').load(win)
ProgramsDropdown = React.createFactory React.createClass
displayName: 'ProgramsDropdown'
mixins: [React.addons.PureRenderMixin]
propTypes: {
selectedProgramId: React.PropTypes.string
programsById: React.PropTypes.instanceOf(Imm.Map).isRequired
placeholder: React.PropTypes.string
onSelect: React.PropTypes.func.isRequired
bsStyle: React.PropTypes.string
}
getDefaultProps: -> {
selectedProgramId: ''
placeholder: "No #{Term 'Program'}"
excludeNone: false
bsStyle: 'link'
}
getInitialState: -> {
isOpen: null
}
toggle: ->
@setState {isOpen: not @state.isOpen}
render: ->
# selectedProgram can be null, so bypasses getDefaultProps
selectedProgramId = @props.selectedProgramId or ''
selectedProgram = @props.programsById.get(selectedProgramId) or Imm.Map()
remainingPrograms = @props.programsById.delete(selectedProgramId).valueSeq().toList()
R.span({
className: 'programsDropdown'
onClick: @toggle
},
B.DropdownButton({
ref: 'dropdown'
id: 'programsDropdown'
open: @state.isOpen
onClose: @toggle
bsStyle: @props.bsStyle
pullRight: true
title: R.span({
className: 'currentProgram'
style: { borderBottomColor: selectedProgram.get('colorKeyHex')}
},
selectedProgram.get('name') or @props.placeholder
)
},
(remainingPrograms
.filter (program) =>
program.get('status') is 'default'
.map (program) =>
B.MenuItem({
key: program.get('id')
onClick: @props.onSelect.bind null, program.get('id')
},
program.get('name')
' '
ColorKeyBubble({colorKeyHex: program.get('colorKeyHex')})
)
)
(if not remainingPrograms.isEmpty() and selectedProgramId and not @props.excludeNone
B.MenuItem({divider: true})
)
(if selectedProgramId and not @props.excludeNone
B.MenuItem({
onClick: @props.onSelect.bind null, null
},
"None "
FaIcon('ban')
)
)
)
)
return ProgramsDropdown
module.exports = {load}
|
[
{
"context": "# Author: Josh Bass\n# Description: The React View for the Header bar ",
"end": 19,
"score": 0.9998677372932434,
"start": 10,
"tag": "NAME",
"value": "Josh Bass"
}
] | src/client/utilities/ObjectCache.coffee | jbass86/Aroma | 0 | # Author: Josh Bass
# Description: The React View for the Header bar at the top of the mast diagnostic display.
module.exports = class ObjectCache
constructor: (options) ->
options = if options then options else {};
@max_size = if options.max_size then options.max_size else 50;
@cull_time = if options.cull_time then options.cull_time else 5000;
@cache = {};
@cache_list = [];
@interval_task = window.setInterval(() =>
if (@cache_list.length > 50)
offset = @cache_list.length - 50;
for i in [0..offset]
delete @cache[@cache_list[i].attr];
@cache_list.splice(0, offset);
, 5000);
get: (attr) ->
if (@cache[attr])
@cache[attr].object;
else
undefined;
put: (attr, object) ->
if (!@cache[attr])
obj = {attr: attr, time: new Date(), object: object};
@cache[attr] = obj;
@cache_list.push(obj);
@cache_list.sort((a, b) =>
if (a.time.getTime() > b.time.getTime())
return 1;
else if (a.time.getTime() < b.time.getTime())
return -1;
return 0;
);
destroy: () ->
window.clearInterval(@interval_task);
| 150288 | # Author: <NAME>
# Description: The React View for the Header bar at the top of the mast diagnostic display.
module.exports = class ObjectCache
constructor: (options) ->
options = if options then options else {};
@max_size = if options.max_size then options.max_size else 50;
@cull_time = if options.cull_time then options.cull_time else 5000;
@cache = {};
@cache_list = [];
@interval_task = window.setInterval(() =>
if (@cache_list.length > 50)
offset = @cache_list.length - 50;
for i in [0..offset]
delete @cache[@cache_list[i].attr];
@cache_list.splice(0, offset);
, 5000);
get: (attr) ->
if (@cache[attr])
@cache[attr].object;
else
undefined;
put: (attr, object) ->
if (!@cache[attr])
obj = {attr: attr, time: new Date(), object: object};
@cache[attr] = obj;
@cache_list.push(obj);
@cache_list.sort((a, b) =>
if (a.time.getTime() > b.time.getTime())
return 1;
else if (a.time.getTime() < b.time.getTime())
return -1;
return 0;
);
destroy: () ->
window.clearInterval(@interval_task);
| true | # Author: PI:NAME:<NAME>END_PI
# Description: The React View for the Header bar at the top of the mast diagnostic display.
module.exports = class ObjectCache
constructor: (options) ->
options = if options then options else {};
@max_size = if options.max_size then options.max_size else 50;
@cull_time = if options.cull_time then options.cull_time else 5000;
@cache = {};
@cache_list = [];
@interval_task = window.setInterval(() =>
if (@cache_list.length > 50)
offset = @cache_list.length - 50;
for i in [0..offset]
delete @cache[@cache_list[i].attr];
@cache_list.splice(0, offset);
, 5000);
get: (attr) ->
if (@cache[attr])
@cache[attr].object;
else
undefined;
put: (attr, object) ->
if (!@cache[attr])
obj = {attr: attr, time: new Date(), object: object};
@cache[attr] = obj;
@cache_list.push(obj);
@cache_list.sort((a, b) =>
if (a.time.getTime() > b.time.getTime())
return 1;
else if (a.time.getTime() < b.time.getTime())
return -1;
return 0;
);
destroy: () ->
window.clearInterval(@interval_task);
|
[
{
"context": "min = Auth.isAdmin()\n\n $scope.user =\n email: 'admin@admin.com'\n password: 'admin'\n\n $scope.login = ->\n A",
"end": 269,
"score": 0.9999126195907593,
"start": 254,
"tag": "EMAIL",
"value": "admin@admin.com"
},
{
"context": "ser =\n email: 'admin@admin... | client/components/navbar/navbar.controller.coffee | scsijs/.jsbongular | 10 | 'use strict'
angular.module 'beepBoopWebsiteApp'
.controller 'NavbarCtrl', ($scope, $location, Auth) ->
$scope.isLoggedIn = Auth.isLoggedIn()
$scope.currentUser = Auth.getCurrentUser()
$scope.isAdmin = Auth.isAdmin()
$scope.user =
email: 'admin@admin.com'
password: 'admin'
$scope.login = ->
Auth.login $scope.user
.then ->
window.location.reload()
.catch (err) ->
alert err
$scope.logout = ->
Auth.logout()
window.location.reload()
$scope.isActive = (route) ->
$location.path().indexOf(route) > -1
| 51081 | 'use strict'
angular.module 'beepBoopWebsiteApp'
.controller 'NavbarCtrl', ($scope, $location, Auth) ->
$scope.isLoggedIn = Auth.isLoggedIn()
$scope.currentUser = Auth.getCurrentUser()
$scope.isAdmin = Auth.isAdmin()
$scope.user =
email: '<EMAIL>'
password: '<PASSWORD>'
$scope.login = ->
Auth.login $scope.user
.then ->
window.location.reload()
.catch (err) ->
alert err
$scope.logout = ->
Auth.logout()
window.location.reload()
$scope.isActive = (route) ->
$location.path().indexOf(route) > -1
| true | 'use strict'
angular.module 'beepBoopWebsiteApp'
.controller 'NavbarCtrl', ($scope, $location, Auth) ->
$scope.isLoggedIn = Auth.isLoggedIn()
$scope.currentUser = Auth.getCurrentUser()
$scope.isAdmin = Auth.isAdmin()
$scope.user =
email: 'PI:EMAIL:<EMAIL>END_PI'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
$scope.login = ->
Auth.login $scope.user
.then ->
window.location.reload()
.catch (err) ->
alert err
$scope.logout = ->
Auth.logout()
window.location.reload()
$scope.isActive = (route) ->
$location.path().indexOf(route) > -1
|
[
{
"context": "#\n# ngOnboarding\n# by Adam Albrecht\n# http://adamalbrecht.com\n#\n# Source Code: https:",
"end": 35,
"score": 0.9998996257781982,
"start": 22,
"tag": "NAME",
"value": "Adam Albrecht"
},
{
"context": "malbrecht.com\n#\n# Source Code: https://github.com/adamalbrecht/ng... | src/ng-onboarding.coffee | DanieleMancini/ngOnboarding | 127 | #
# ngOnboarding
# by Adam Albrecht
# http://adamalbrecht.com
#
# Source Code: https://github.com/adamalbrecht/ngOnboarding
#
# Compatible with Angular 1.2.x
#
app = angular.module("ngOnboarding", [])
app.provider "ngOnboardingDefaults", ->
options: {
overlay: true,
overlayOpacity: 0.6,
overlayClass: 'onboarding-overlay',
popoverClass: 'onboarding-popover',
titleClass: 'onboarding-popover-title',
contentClass: 'onboarding-popover-content',
arrowClass: 'onboarding-arrow',
buttonContainerClass: 'onboarding-button-container',
buttonClass: "onboarding-button",
showButtons: true,
nextButtonText: 'Next →',
previousButtonText: '← Previous',
showDoneButton: true,
doneButtonText: 'Done',
closeButtonClass: 'onboarding-close-button',
closeButtonText: 'X',
stepClass: 'onboarding-step-info',
showStepInfo: true
}
$get: ->
@options
set: (keyOrHash, value) ->
if typeof(keyOrHash) == 'object'
for k, v of keyOrHash
@options[k] = v
else
@options[keyOrHash] = value
app.directive 'onboardingPopover', ['ngOnboardingDefaults', '$sce', '$timeout', (ngOnboardingDefaults, $sce, $timeout) ->
restrict: 'E'
scope:
enabled: '='
steps: '='
onFinishCallback: '&onFinishCallback'
index: '=stepIndex'
replace: true
link: (scope, element, attrs) ->
# Important Variables
curStep = null
attributesToClear = ['title', 'top', 'right', 'bottom', 'left', 'width', 'height', 'position']
scope.stepCount = scope.steps.length
# Button Actions
scope.next = -> scope.index = scope.index + 1
scope.previous = -> scope.index = scope.index - 1
scope.close = ->
scope.enabled = false
setupOverlay(false)
if scope.onFinishCallback
scope.onFinishCallback()
# Watch for changes in the current step index
scope.$watch 'index', (newVal, oldVal) ->
if newVal == null
scope.enabled = false
setupOverlay(false)
return
curStep = scope.steps[scope.index]
scope.lastStep = (scope.index + 1 == scope.steps.length)
scope.showNextButton = (scope.index + 1 < scope.steps.length)
scope.showPreviousButton = (scope.index > 0)
for attr in attributesToClear
scope[attr] = null
for k, v of ngOnboardingDefaults
if curStep[k] == undefined
scope[k] = v
for k, v of curStep
scope[k] = v
# Allow some variables to include html
scope.description = $sce.trustAsHtml(scope.description)
scope.nextButtonText = $sce.trustAsHtml(scope.nextButtonText)
scope.previousButtonText = $sce.trustAsHtml(scope.previousButtonText)
scope.doneButtonText = $sce.trustAsHtml(scope.doneButtonText)
scope.closeButtonText = $sce.trustAsHtml(scope.closeButtonText)
setupOverlay()
setupPositioning()
setupOverlay = (showOverlay=true) ->
$('.onboarding-focus').removeClass('onboarding-focus')
if showOverlay
if curStep['attachTo'] && scope.overlay
$(curStep['attachTo']).addClass('onboarding-focus')
setupPositioning = ->
attachTo = curStep['attachTo']
scope.position = curStep['position']
xMargin = 15
yMargin = 15
if attachTo
# SET X POSITION
unless scope.left || scope.right
left = null
right = null
if scope.position == 'right'
left = $(attachTo).offset().left + $(attachTo).outerWidth() + xMargin
else if scope.position == 'left'
right = $(window).width() - $(attachTo).offset().left + xMargin
else if scope.position == 'top' || scope.position == 'bottom'
left = $(attachTo).offset().left
if curStep['xOffset']
left = left + curStep['xOffset'] if left != null
right = right - curStep['xOffset'] if right != null
scope.left = left
scope.right = right
# SET Y POSITION
unless scope.top || scope.bottom
top = null
bottom = null
if scope.position == 'left' || scope.position == 'right'
top = $(attachTo).offset().top
else if scope.position == 'bottom'
top = $(attachTo).offset().top + $(attachTo).outerHeight() + yMargin
else if scope.position == 'top'
bottom = $(window).height() - $(attachTo).offset().top + yMargin
if curStep['yOffset']
top = top + curStep['yOffset'] if top != null
bottom = bottom - curStep['yOffset'] if bottom != null
scope.top = top
scope.bottom = bottom
if scope.position && scope.position.length
scope.positionClass = "onboarding-#{scope.position}"
else
scope.positionClass = null
if scope.steps.length && !scope.index
scope.index = 0
template: """
<div class='onboarding-container' ng-show='enabled'>
<div class='{{overlayClass}}' ng-style='{opacity: overlayOpacity}', ng-show='overlay'></div>
<div class='{{popoverClass}} {{positionClass}}' ng-style="{width: width, height: height, left: left, top: top, right: right, bottom: bottom}">
<div class='{{arrowClass}}'></div>
<h3 class='{{titleClass}}' ng-show='title' ng-bind='title'></h3>
<a href='' ng-click='close()' class='{{closeButtonClass}}' ng-bind-html='closeButtonText'></a>
<div class='{{contentClass}}'>
<p ng-bind-html='description'></p>
</div>
<div class='{{buttonContainerClass}}' ng-show='showButtons'>
<span ng-show='showStepInfo' class='{{stepClass}}'>Step {{index + 1}} of {{stepCount}}</span>
<a href='' ng-click='previous()' ng-show='showPreviousButton' class='{{buttonClass}}' ng-bind-html='previousButtonText'></a>
<a href='' ng-click='next()' ng-show='showNextButton' class='{{buttonClass}}' ng-bind-html='nextButtonText'></a>
<a href='' ng-click='close()' ng-show='showDoneButton && lastStep' class='{{buttonClass}}' ng-bind-html='doneButtonText'></a>
</div>
</div>
</div>
"""
]
| 27454 | #
# ngOnboarding
# by <NAME>
# http://adamalbrecht.com
#
# Source Code: https://github.com/adamalbrecht/ngOnboarding
#
# Compatible with Angular 1.2.x
#
app = angular.module("ngOnboarding", [])
app.provider "ngOnboardingDefaults", ->
options: {
overlay: true,
overlayOpacity: 0.6,
overlayClass: 'onboarding-overlay',
popoverClass: 'onboarding-popover',
titleClass: 'onboarding-popover-title',
contentClass: 'onboarding-popover-content',
arrowClass: 'onboarding-arrow',
buttonContainerClass: 'onboarding-button-container',
buttonClass: "onboarding-button",
showButtons: true,
nextButtonText: 'Next →',
previousButtonText: '← Previous',
showDoneButton: true,
doneButtonText: 'Done',
closeButtonClass: 'onboarding-close-button',
closeButtonText: 'X',
stepClass: 'onboarding-step-info',
showStepInfo: true
}
$get: ->
@options
set: (keyOrHash, value) ->
if typeof(keyOrHash) == 'object'
for k, v of keyOrHash
@options[k] = v
else
@options[keyOrHash] = value
app.directive 'onboardingPopover', ['ngOnboardingDefaults', '$sce', '$timeout', (ngOnboardingDefaults, $sce, $timeout) ->
restrict: 'E'
scope:
enabled: '='
steps: '='
onFinishCallback: '&onFinishCallback'
index: '=stepIndex'
replace: true
link: (scope, element, attrs) ->
# Important Variables
curStep = null
attributesToClear = ['title', 'top', 'right', 'bottom', 'left', 'width', 'height', 'position']
scope.stepCount = scope.steps.length
# Button Actions
scope.next = -> scope.index = scope.index + 1
scope.previous = -> scope.index = scope.index - 1
scope.close = ->
scope.enabled = false
setupOverlay(false)
if scope.onFinishCallback
scope.onFinishCallback()
# Watch for changes in the current step index
scope.$watch 'index', (newVal, oldVal) ->
if newVal == null
scope.enabled = false
setupOverlay(false)
return
curStep = scope.steps[scope.index]
scope.lastStep = (scope.index + 1 == scope.steps.length)
scope.showNextButton = (scope.index + 1 < scope.steps.length)
scope.showPreviousButton = (scope.index > 0)
for attr in attributesToClear
scope[attr] = null
for k, v of ngOnboardingDefaults
if curStep[k] == undefined
scope[k] = v
for k, v of curStep
scope[k] = v
# Allow some variables to include html
scope.description = $sce.trustAsHtml(scope.description)
scope.nextButtonText = $sce.trustAsHtml(scope.nextButtonText)
scope.previousButtonText = $sce.trustAsHtml(scope.previousButtonText)
scope.doneButtonText = $sce.trustAsHtml(scope.doneButtonText)
scope.closeButtonText = $sce.trustAsHtml(scope.closeButtonText)
setupOverlay()
setupPositioning()
setupOverlay = (showOverlay=true) ->
$('.onboarding-focus').removeClass('onboarding-focus')
if showOverlay
if curStep['attachTo'] && scope.overlay
$(curStep['attachTo']).addClass('onboarding-focus')
setupPositioning = ->
attachTo = curStep['attachTo']
scope.position = curStep['position']
xMargin = 15
yMargin = 15
if attachTo
# SET X POSITION
unless scope.left || scope.right
left = null
right = null
if scope.position == 'right'
left = $(attachTo).offset().left + $(attachTo).outerWidth() + xMargin
else if scope.position == 'left'
right = $(window).width() - $(attachTo).offset().left + xMargin
else if scope.position == 'top' || scope.position == 'bottom'
left = $(attachTo).offset().left
if curStep['xOffset']
left = left + curStep['xOffset'] if left != null
right = right - curStep['xOffset'] if right != null
scope.left = left
scope.right = right
# SET Y POSITION
unless scope.top || scope.bottom
top = null
bottom = null
if scope.position == 'left' || scope.position == 'right'
top = $(attachTo).offset().top
else if scope.position == 'bottom'
top = $(attachTo).offset().top + $(attachTo).outerHeight() + yMargin
else if scope.position == 'top'
bottom = $(window).height() - $(attachTo).offset().top + yMargin
if curStep['yOffset']
top = top + curStep['yOffset'] if top != null
bottom = bottom - curStep['yOffset'] if bottom != null
scope.top = top
scope.bottom = bottom
if scope.position && scope.position.length
scope.positionClass = "onboarding-#{scope.position}"
else
scope.positionClass = null
if scope.steps.length && !scope.index
scope.index = 0
template: """
<div class='onboarding-container' ng-show='enabled'>
<div class='{{overlayClass}}' ng-style='{opacity: overlayOpacity}', ng-show='overlay'></div>
<div class='{{popoverClass}} {{positionClass}}' ng-style="{width: width, height: height, left: left, top: top, right: right, bottom: bottom}">
<div class='{{arrowClass}}'></div>
<h3 class='{{titleClass}}' ng-show='title' ng-bind='title'></h3>
<a href='' ng-click='close()' class='{{closeButtonClass}}' ng-bind-html='closeButtonText'></a>
<div class='{{contentClass}}'>
<p ng-bind-html='description'></p>
</div>
<div class='{{buttonContainerClass}}' ng-show='showButtons'>
<span ng-show='showStepInfo' class='{{stepClass}}'>Step {{index + 1}} of {{stepCount}}</span>
<a href='' ng-click='previous()' ng-show='showPreviousButton' class='{{buttonClass}}' ng-bind-html='previousButtonText'></a>
<a href='' ng-click='next()' ng-show='showNextButton' class='{{buttonClass}}' ng-bind-html='nextButtonText'></a>
<a href='' ng-click='close()' ng-show='showDoneButton && lastStep' class='{{buttonClass}}' ng-bind-html='doneButtonText'></a>
</div>
</div>
</div>
"""
]
| true | #
# ngOnboarding
# by PI:NAME:<NAME>END_PI
# http://adamalbrecht.com
#
# Source Code: https://github.com/adamalbrecht/ngOnboarding
#
# Compatible with Angular 1.2.x
#
app = angular.module("ngOnboarding", [])
app.provider "ngOnboardingDefaults", ->
options: {
overlay: true,
overlayOpacity: 0.6,
overlayClass: 'onboarding-overlay',
popoverClass: 'onboarding-popover',
titleClass: 'onboarding-popover-title',
contentClass: 'onboarding-popover-content',
arrowClass: 'onboarding-arrow',
buttonContainerClass: 'onboarding-button-container',
buttonClass: "onboarding-button",
showButtons: true,
nextButtonText: 'Next →',
previousButtonText: '← Previous',
showDoneButton: true,
doneButtonText: 'Done',
closeButtonClass: 'onboarding-close-button',
closeButtonText: 'X',
stepClass: 'onboarding-step-info',
showStepInfo: true
}
$get: ->
@options
set: (keyOrHash, value) ->
if typeof(keyOrHash) == 'object'
for k, v of keyOrHash
@options[k] = v
else
@options[keyOrHash] = value
app.directive 'onboardingPopover', ['ngOnboardingDefaults', '$sce', '$timeout', (ngOnboardingDefaults, $sce, $timeout) ->
restrict: 'E'
scope:
enabled: '='
steps: '='
onFinishCallback: '&onFinishCallback'
index: '=stepIndex'
replace: true
link: (scope, element, attrs) ->
# Important Variables
curStep = null
attributesToClear = ['title', 'top', 'right', 'bottom', 'left', 'width', 'height', 'position']
scope.stepCount = scope.steps.length
# Button Actions
scope.next = -> scope.index = scope.index + 1
scope.previous = -> scope.index = scope.index - 1
scope.close = ->
scope.enabled = false
setupOverlay(false)
if scope.onFinishCallback
scope.onFinishCallback()
# Watch for changes in the current step index
scope.$watch 'index', (newVal, oldVal) ->
if newVal == null
scope.enabled = false
setupOverlay(false)
return
curStep = scope.steps[scope.index]
scope.lastStep = (scope.index + 1 == scope.steps.length)
scope.showNextButton = (scope.index + 1 < scope.steps.length)
scope.showPreviousButton = (scope.index > 0)
for attr in attributesToClear
scope[attr] = null
for k, v of ngOnboardingDefaults
if curStep[k] == undefined
scope[k] = v
for k, v of curStep
scope[k] = v
# Allow some variables to include html
scope.description = $sce.trustAsHtml(scope.description)
scope.nextButtonText = $sce.trustAsHtml(scope.nextButtonText)
scope.previousButtonText = $sce.trustAsHtml(scope.previousButtonText)
scope.doneButtonText = $sce.trustAsHtml(scope.doneButtonText)
scope.closeButtonText = $sce.trustAsHtml(scope.closeButtonText)
setupOverlay()
setupPositioning()
setupOverlay = (showOverlay=true) ->
$('.onboarding-focus').removeClass('onboarding-focus')
if showOverlay
if curStep['attachTo'] && scope.overlay
$(curStep['attachTo']).addClass('onboarding-focus')
setupPositioning = ->
attachTo = curStep['attachTo']
scope.position = curStep['position']
xMargin = 15
yMargin = 15
if attachTo
# SET X POSITION
unless scope.left || scope.right
left = null
right = null
if scope.position == 'right'
left = $(attachTo).offset().left + $(attachTo).outerWidth() + xMargin
else if scope.position == 'left'
right = $(window).width() - $(attachTo).offset().left + xMargin
else if scope.position == 'top' || scope.position == 'bottom'
left = $(attachTo).offset().left
if curStep['xOffset']
left = left + curStep['xOffset'] if left != null
right = right - curStep['xOffset'] if right != null
scope.left = left
scope.right = right
# SET Y POSITION
unless scope.top || scope.bottom
top = null
bottom = null
if scope.position == 'left' || scope.position == 'right'
top = $(attachTo).offset().top
else if scope.position == 'bottom'
top = $(attachTo).offset().top + $(attachTo).outerHeight() + yMargin
else if scope.position == 'top'
bottom = $(window).height() - $(attachTo).offset().top + yMargin
if curStep['yOffset']
top = top + curStep['yOffset'] if top != null
bottom = bottom - curStep['yOffset'] if bottom != null
scope.top = top
scope.bottom = bottom
if scope.position && scope.position.length
scope.positionClass = "onboarding-#{scope.position}"
else
scope.positionClass = null
if scope.steps.length && !scope.index
scope.index = 0
template: """
<div class='onboarding-container' ng-show='enabled'>
<div class='{{overlayClass}}' ng-style='{opacity: overlayOpacity}', ng-show='overlay'></div>
<div class='{{popoverClass}} {{positionClass}}' ng-style="{width: width, height: height, left: left, top: top, right: right, bottom: bottom}">
<div class='{{arrowClass}}'></div>
<h3 class='{{titleClass}}' ng-show='title' ng-bind='title'></h3>
<a href='' ng-click='close()' class='{{closeButtonClass}}' ng-bind-html='closeButtonText'></a>
<div class='{{contentClass}}'>
<p ng-bind-html='description'></p>
</div>
<div class='{{buttonContainerClass}}' ng-show='showButtons'>
<span ng-show='showStepInfo' class='{{stepClass}}'>Step {{index + 1}} of {{stepCount}}</span>
<a href='' ng-click='previous()' ng-show='showPreviousButton' class='{{buttonClass}}' ng-bind-html='previousButtonText'></a>
<a href='' ng-click='next()' ng-show='showNextButton' class='{{buttonClass}}' ng-bind-html='nextButtonText'></a>
<a href='' ng-click='close()' ng-show='showDoneButton && lastStep' class='{{buttonClass}}' ng-bind-html='doneButtonText'></a>
</div>
</div>
</div>
"""
]
|
[
{
"context": " # BERT-JS\n # Copyright (c) 2009 Rusty Klophaus (@rklophaus)\n # Contributions by Ben Browning (@b",
"end": 47,
"score": 0.9998824000358582,
"start": 33,
"tag": "NAME",
"value": "Rusty Klophaus"
},
{
"context": " # BERT-JS\n # Copyright (c) 2009 Rusty Klophaus (@rkloph... | lib/util/cert.coffee | jcrom/emp-debugger | 2 | # BERT-JS
# Copyright (c) 2009 Rusty Klophaus (@rklophaus)
# Contributions by Ben Browning (@bbrowning)
# See MIT-LICENSE for licensing information.
#
#
# BERT-JS is a Javascript implementation of Binary Erlang Term Serialization.
# - http://github.com/rklophaus/BERT-JS
#
# References:
# - http://www.erlang-factory.com/upload/presentations/36/tom_preston_werner_erlectricity.pdf
# - http://www.erlang.org/doc/apps/erts/erl_ext_dist.html#8
#
#
# - CLASSES -
# Buffer = require 'Buffer'
module.exports =
class BertClass
BERT_START:String.fromCharCode(131)
SMALL_ATOM:String.fromCharCode(115)
ATOM:String.fromCharCode(100)
BINARY:String.fromCharCode(109)
SMALL_INTEGER:String.fromCharCode(97)
INTEGER:String.fromCharCode(98)
SMALL_BIG:String.fromCharCode(110)
LARGE_BIG:String.fromCharCode(111)
FLOAT:String.fromCharCode(99)
STRING:String.fromCharCode(107)
LIST:String.fromCharCode(108)
SMALL_TUPLE:String.fromCharCode(104)
LARGE_TUPLE:String.fromCharCode(105)
NIL:String.fromCharCode(106)
ZERO:String.fromCharCode(0)
BERT_START_C:131
SMALL_ATOM_C:115
ATOM_C:100
BINARY_C:109
SMALL_INTEGER_C:97
INTEGER_C:98
SMALL_BIG_C:110
LARGE_BIG_C:111
FLOAT_C:99
STRING_C:107
LIST_C:108
SMALL_TUPLE_C:104
LARGE_TUPLE_C:105
NIL_C:106
ZERO_C:0
constructor: ->
# console.log "initial "
this
encode: (obj) ->
re = @encode_inner(obj)
# console.log re
if Buffer.isBuffer re
re_buf = new Buffer(re.length+1)
re.copy re_buf,1
re_buf[0] = @BERT_START_C
# console.log re_buf
re_buf
else
@BERT_START+re
# decode: (obj) ->
# unless obj[0] is @BERT_START
# throw "invalid bert"
#
# new_obj = @decode_inner obj.substring(1)
#
# unless new_obj.rest is ""
# throw "invalid bert"
#
# new_obj.value
encode_inner: (obj) ->
if obj
func = 'encode_' + typeof(obj)
# console.log func
this[func](obj)
else
throw new Error("Cannot encode undefined values.")
encode_string: (obj) ->
buf = new Buffer(obj)
re_buf = new Buffer(buf.length+3)
len = @int_to_bytes(obj.length, 2)
buf.copy re_buf,3
for index in [0..len.length-1]
re_buf[index+1]=len[index].charCodeAt 0
re_buf[0]=@STRING_C
re_buf
encode_boolen: (obj) ->
if obj
@encode_inner @atom("true")
else
@encode_inner @atom("false")
encode_number: (obj) ->
s=isInteger= (obj%1 is 0)
unless isInteger
return @encode_float(obj)
unless !(isInteger && obj >= 0 && obj < 256)
re_buf = new Buffer(2)
re_buf[0]=@SMALL_INTEGER_C
re_buf[1]=@int_to_bytes(obj,1)[0].charCodeAt 0
re_buf
unless !(isInteger && obj >= -134217728 && obj <= 134217727)
re_buf = new Buffer(5)
re_buf[0]=@INTEGER_C
len=@int_to_bytes obj,4
for index in [0..len.length-1]
re_buf[index+1]=len[index].charCodeAt 0
re_buf
s = @bignum_to_bytes(obj)
buf = new Buffer(s)
len = 0
head = 0
if s.length < 256
# return @SMALL_BIG+@int_to_bytes(s.length - 1, 1) + s
len = @int_to_bytes(s.length-1, 1)
head=@SMALL_BIG_C
else
len = @int_to_bytes(s.length-1, 4)
head=@LARGE_BIG_C
start_index = 1+len.length
re_buf = new Buffer(buf.length+start_index)
buf.copy re_buf,start_index
re_buf[0]=head
for index in [0..len.length-1]
re_buf[index+1]=len[index].charCodeAt 0
re_buf
# return @LARGE_BIG +@int_to_bytes(s.length - 1, 4) + s
encode_float: (obj) ->
tmp_val=obj.toExponential();
while tmp_val.length <31
tmp_val+=@ZERO
# @FLOAT+s
buf = new Buffer(tmp_val)
re_buf = new Buffer(buf.length+1)
buf.copy re_buf,1
re_buf[0]=@FLOAT_C
re_buf
encode_object: (obj) ->
# console.log obj
unless obj
return @encode_inner @atom("null")
unless obj.type isnt "Atom"
return @encode_atom obj
unless obj.type isnt "Binary"
return @encode_binary obj
unless obj.type isnt "Tuple"
return @encode_tuple obj
unless obj.constructor.toString().indexOf("Array") is -1
return @encode_array obj
@encode_associative_array obj
encode_atom: (obj) ->
buf = new Buffer(obj.value)
re_buf = new Buffer(obj.value.length+3)
len = @int_to_bytes(obj.value.length, 2)
buf.copy re_buf,3
for index in [0..len.length-1]
re_buf[index+1]=len[index].charCodeAt 0
re_buf[0]=@ATOM_C
re_buf
encode_binary: (obj) ->
# console.log "encode_binary"
# console.log obj
re_buf = new Buffer(obj.value.length+5)
if Buffer.isBuffer obj.value
obj.value.copy re_buf,5
else
buf = new Buffer obj.value
buf.copy re_buf,5
re_buf[0] = @BINARY_C
len = @int_to_bytes(obj.value.length, 4)
for index in [0..3]
re_buf[index+1]=len[index].charCodeAt 0
# console.log re_buf
# @BINARY+@int_to_bytes(obj.value.length, 4)+obj.value
re_buf
encode_tuple: (obj) ->
# console.log "encode_tuple"
s=""
re_arr=[]
head=""
len=""
if obj.length < 256
head = @SMALL_TUPLE_C
len=@int_to_bytes obj.length, 1
# s+=@SMALL_TUPLE+@int_to_bytes obj.length, 1
else
head = @LARGE_TUPLE_C
len=@int_to_bytes obj.length, 4
# s+=@LARGE_TUPLE+@int_to_bytes obj.length, 4
for i in [0..obj.length-1]
tmp_re = @encode_inner obj[i]
# console.log tmp_re
# re_arr.push @encode_inner obj[i]
re_arr.push tmp_re
all_len = 0
for tmp_ele in re_arr
# console.log tmp_ele
all_len+=tmp_ele.length
start_index = 1+len.length
re_buf = new Buffer(all_len+start_index)
for tmp_ele in re_arr
all_len+=tmp_ele.length
tmp_ele.copy re_buf,start_index
start_index+=tmp_ele.length
for index in [0..len.length-1]
re_buf[index+1]=len[index].charCodeAt 0
re_buf[0]=head
# console.log "-----------"
# console.log re_buf
re_buf
# re_buf = new Buffer(obj.value.length+5)
encode_array: (obj) ->
# console.log "encode array"
unless obj.length isnt 0
return new Buffer(@NIL)
# s=@LIST+@int_to_bytes obj.length, 4
len = @int_to_bytes obj.length, 4
buf = new Buffer(5)
buf[0]=@LIST_C
for index in [0..len.length-1]
buf[index+1]=len[index].charCodeAt 0
re_arr = []
re_arr.push buf
for i in [0..obj.length-1]
re_arr.push @encode_inner obj[i]
# s+=@NIL
all_len = 0
for tmp_ele in re_arr
all_len+=tmp_ele.length
start_index = 0
end_index = all_len
re_buf = new Buffer(all_len+start_index+1) # all+nil
for tmp_ele in re_arr
all_len+=tmp_ele.length
tmp_ele.copy re_buf,start_index
start_index+=tmp_ele.length
re_buf[end_index]=@NIL_C
re_buf
encode_associative_array: (obj) ->
# console.log "encode_associative_array"
# console.log obj
arr = new Array()
for key,value of obj
unless !obj.hasOwnProperty key
arr.push @tuple(@atom(key), value)
@encode_array arr
int_to_bytes: (int, length) ->
isNegative=originalInt=i=rem=s=""
isNegative = int <0
int=-int-1 unless !isNegative
originalInt=int
for i in [0..length-1]
rem=int % 256
rem=255-rem unless !isNegative
# console.log rem
s=String.fromCharCode(rem) + s
int = Math.floor int/256
i+=1
throw("Argument out of range: "+originalInt) unless int <=0
s
# Encode an integer into an Erlang bignum,
# which is a byte of 1 or 0 representing
# whether the number is negative or positive,
# followed by little-endian bytes.
bignum_to_bytes: (int) ->
isNegative=rem=s= ""
isNegative = int < 0
if isNegative
int *= -1
s+=String.fromCharCode 1
else
s+=String.fromCharCode 0
while int isnt 0
rem = int % 256
s+=String.fromCharCode rem
int = Math.floor int/256
s
# @notic 基本类型
atom: (obj)->
{type:"Atom", value:obj, toString: -> obj}
binary: (obj) ->
{type:"Binary", value:obj, toString: ->
if Buffer.isBuffer obj
tmp_val = obj.toString()
"<<\"#{tmp_val}\">>"
else
"<<\"#{obj}\">>"}
tuple: (arr...) ->
tmp_obj = {type:"Tuple", length:arr.length, value:arr}
index = -1
tmp_obj[index+=1]=tmp_ele for tmp_ele in arr
tmp_obj.toString = ->
i = 0
s = ""
for i in [0..this.length-1]
unless s is ""
s+=", "
s+=this[i].toString();
"{#{s}}"
tmp_obj
binary_to_list: (str) ->
ret = new Array()
for i in [0..str.length-1]
ret.push str.fromCharCode i
ret
sign:(data) ->
shasum = crypto.createHash 'sha1'
shasum.update data
shasum.digest 'hex'
| 101032 | # BERT-JS
# Copyright (c) 2009 <NAME> (@rklophaus)
# Contributions by <NAME> (@bbrowning)
# See MIT-LICENSE for licensing information.
#
#
# BERT-JS is a Javascript implementation of Binary Erlang Term Serialization.
# - http://github.com/rklophaus/BERT-JS
#
# References:
# - http://www.erlang-factory.com/upload/presentations/36/tom_preston_werner_erlectricity.pdf
# - http://www.erlang.org/doc/apps/erts/erl_ext_dist.html#8
#
#
# - CLASSES -
# Buffer = require 'Buffer'
module.exports =
class BertClass
BERT_START:String.fromCharCode(131)
SMALL_ATOM:String.fromCharCode(115)
ATOM:String.fromCharCode(100)
BINARY:String.fromCharCode(109)
SMALL_INTEGER:String.fromCharCode(97)
INTEGER:String.fromCharCode(98)
SMALL_BIG:String.fromCharCode(110)
LARGE_BIG:String.fromCharCode(111)
FLOAT:String.fromCharCode(99)
STRING:String.fromCharCode(107)
LIST:String.fromCharCode(108)
SMALL_TUPLE:String.fromCharCode(104)
LARGE_TUPLE:String.fromCharCode(105)
NIL:String.fromCharCode(106)
ZERO:String.fromCharCode(0)
BERT_START_C:131
SMALL_ATOM_C:115
ATOM_C:100
BINARY_C:109
SMALL_INTEGER_C:97
INTEGER_C:98
SMALL_BIG_C:110
LARGE_BIG_C:111
FLOAT_C:99
STRING_C:107
LIST_C:108
SMALL_TUPLE_C:104
LARGE_TUPLE_C:105
NIL_C:106
ZERO_C:0
constructor: ->
# console.log "initial "
this
encode: (obj) ->
re = @encode_inner(obj)
# console.log re
if Buffer.isBuffer re
re_buf = new Buffer(re.length+1)
re.copy re_buf,1
re_buf[0] = @BERT_START_C
# console.log re_buf
re_buf
else
@BERT_START+re
# decode: (obj) ->
# unless obj[0] is @BERT_START
# throw "invalid bert"
#
# new_obj = @decode_inner obj.substring(1)
#
# unless new_obj.rest is ""
# throw "invalid bert"
#
# new_obj.value
encode_inner: (obj) ->
if obj
func = 'encode_' + typeof(obj)
# console.log func
this[func](obj)
else
throw new Error("Cannot encode undefined values.")
encode_string: (obj) ->
buf = new Buffer(obj)
re_buf = new Buffer(buf.length+3)
len = @int_to_bytes(obj.length, 2)
buf.copy re_buf,3
for index in [0..len.length-1]
re_buf[index+1]=len[index].charCodeAt 0
re_buf[0]=@STRING_C
re_buf
encode_boolen: (obj) ->
if obj
@encode_inner @atom("true")
else
@encode_inner @atom("false")
encode_number: (obj) ->
s=isInteger= (obj%1 is 0)
unless isInteger
return @encode_float(obj)
unless !(isInteger && obj >= 0 && obj < 256)
re_buf = new Buffer(2)
re_buf[0]=@SMALL_INTEGER_C
re_buf[1]=@int_to_bytes(obj,1)[0].charCodeAt 0
re_buf
unless !(isInteger && obj >= -134217728 && obj <= 134217727)
re_buf = new Buffer(5)
re_buf[0]=@INTEGER_C
len=@int_to_bytes obj,4
for index in [0..len.length-1]
re_buf[index+1]=len[index].charCodeAt 0
re_buf
s = @bignum_to_bytes(obj)
buf = new Buffer(s)
len = 0
head = 0
if s.length < 256
# return @SMALL_BIG+@int_to_bytes(s.length - 1, 1) + s
len = @int_to_bytes(s.length-1, 1)
head=@SMALL_BIG_C
else
len = @int_to_bytes(s.length-1, 4)
head=@LARGE_BIG_C
start_index = 1+len.length
re_buf = new Buffer(buf.length+start_index)
buf.copy re_buf,start_index
re_buf[0]=head
for index in [0..len.length-1]
re_buf[index+1]=len[index].charCodeAt 0
re_buf
# return @LARGE_BIG +@int_to_bytes(s.length - 1, 4) + s
encode_float: (obj) ->
tmp_val=obj.toExponential();
while tmp_val.length <31
tmp_val+=@ZERO
# @FLOAT+s
buf = new Buffer(tmp_val)
re_buf = new Buffer(buf.length+1)
buf.copy re_buf,1
re_buf[0]=@FLOAT_C
re_buf
encode_object: (obj) ->
# console.log obj
unless obj
return @encode_inner @atom("null")
unless obj.type isnt "Atom"
return @encode_atom obj
unless obj.type isnt "Binary"
return @encode_binary obj
unless obj.type isnt "Tuple"
return @encode_tuple obj
unless obj.constructor.toString().indexOf("Array") is -1
return @encode_array obj
@encode_associative_array obj
encode_atom: (obj) ->
buf = new Buffer(obj.value)
re_buf = new Buffer(obj.value.length+3)
len = @int_to_bytes(obj.value.length, 2)
buf.copy re_buf,3
for index in [0..len.length-1]
re_buf[index+1]=len[index].charCodeAt 0
re_buf[0]=@ATOM_C
re_buf
encode_binary: (obj) ->
# console.log "encode_binary"
# console.log obj
re_buf = new Buffer(obj.value.length+5)
if Buffer.isBuffer obj.value
obj.value.copy re_buf,5
else
buf = new Buffer obj.value
buf.copy re_buf,5
re_buf[0] = @BINARY_C
len = @int_to_bytes(obj.value.length, 4)
for index in [0..3]
re_buf[index+1]=len[index].charCodeAt 0
# console.log re_buf
# @BINARY+@int_to_bytes(obj.value.length, 4)+obj.value
re_buf
encode_tuple: (obj) ->
# console.log "encode_tuple"
s=""
re_arr=[]
head=""
len=""
if obj.length < 256
head = @SMALL_TUPLE_C
len=@int_to_bytes obj.length, 1
# s+=@SMALL_TUPLE+@int_to_bytes obj.length, 1
else
head = @LARGE_TUPLE_C
len=@int_to_bytes obj.length, 4
# s+=@LARGE_TUPLE+@int_to_bytes obj.length, 4
for i in [0..obj.length-1]
tmp_re = @encode_inner obj[i]
# console.log tmp_re
# re_arr.push @encode_inner obj[i]
re_arr.push tmp_re
all_len = 0
for tmp_ele in re_arr
# console.log tmp_ele
all_len+=tmp_ele.length
start_index = 1+len.length
re_buf = new Buffer(all_len+start_index)
for tmp_ele in re_arr
all_len+=tmp_ele.length
tmp_ele.copy re_buf,start_index
start_index+=tmp_ele.length
for index in [0..len.length-1]
re_buf[index+1]=len[index].charCodeAt 0
re_buf[0]=head
# console.log "-----------"
# console.log re_buf
re_buf
# re_buf = new Buffer(obj.value.length+5)
encode_array: (obj) ->
# console.log "encode array"
unless obj.length isnt 0
return new Buffer(@NIL)
# s=@LIST+@int_to_bytes obj.length, 4
len = @int_to_bytes obj.length, 4
buf = new Buffer(5)
buf[0]=@LIST_C
for index in [0..len.length-1]
buf[index+1]=len[index].charCodeAt 0
re_arr = []
re_arr.push buf
for i in [0..obj.length-1]
re_arr.push @encode_inner obj[i]
# s+=@NIL
all_len = 0
for tmp_ele in re_arr
all_len+=tmp_ele.length
start_index = 0
end_index = all_len
re_buf = new Buffer(all_len+start_index+1) # all+nil
for tmp_ele in re_arr
all_len+=tmp_ele.length
tmp_ele.copy re_buf,start_index
start_index+=tmp_ele.length
re_buf[end_index]=@NIL_C
re_buf
encode_associative_array: (obj) ->
# console.log "encode_associative_array"
# console.log obj
arr = new Array()
for key,value of obj
unless !obj.hasOwnProperty key
arr.push @tuple(@atom(key), value)
@encode_array arr
int_to_bytes: (int, length) ->
isNegative=originalInt=i=rem=s=""
isNegative = int <0
int=-int-1 unless !isNegative
originalInt=int
for i in [0..length-1]
rem=int % 256
rem=255-rem unless !isNegative
# console.log rem
s=String.fromCharCode(rem) + s
int = Math.floor int/256
i+=1
throw("Argument out of range: "+originalInt) unless int <=0
s
# Encode an integer into an Erlang bignum,
# which is a byte of 1 or 0 representing
# whether the number is negative or positive,
# followed by little-endian bytes.
bignum_to_bytes: (int) ->
isNegative=rem=s= ""
isNegative = int < 0
if isNegative
int *= -1
s+=String.fromCharCode 1
else
s+=String.fromCharCode 0
while int isnt 0
rem = int % 256
s+=String.fromCharCode rem
int = Math.floor int/256
s
# @notic 基本类型
atom: (obj)->
{type:"Atom", value:obj, toString: -> obj}
binary: (obj) ->
{type:"Binary", value:obj, toString: ->
if Buffer.isBuffer obj
tmp_val = obj.toString()
"<<\"#{tmp_val}\">>"
else
"<<\"#{obj}\">>"}
tuple: (arr...) ->
tmp_obj = {type:"Tuple", length:arr.length, value:arr}
index = -1
tmp_obj[index+=1]=tmp_ele for tmp_ele in arr
tmp_obj.toString = ->
i = 0
s = ""
for i in [0..this.length-1]
unless s is ""
s+=", "
s+=this[i].toString();
"{#{s}}"
tmp_obj
binary_to_list: (str) ->
ret = new Array()
for i in [0..str.length-1]
ret.push str.fromCharCode i
ret
sign:(data) ->
shasum = crypto.createHash 'sha1'
shasum.update data
shasum.digest 'hex'
| true | # BERT-JS
# Copyright (c) 2009 PI:NAME:<NAME>END_PI (@rklophaus)
# Contributions by PI:NAME:<NAME>END_PI (@bbrowning)
# See MIT-LICENSE for licensing information.
#
#
# BERT-JS is a Javascript implementation of Binary Erlang Term Serialization.
# - http://github.com/rklophaus/BERT-JS
#
# References:
# - http://www.erlang-factory.com/upload/presentations/36/tom_preston_werner_erlectricity.pdf
# - http://www.erlang.org/doc/apps/erts/erl_ext_dist.html#8
#
#
# - CLASSES -
# Buffer = require 'Buffer'
module.exports =
class BertClass
BERT_START:String.fromCharCode(131)
SMALL_ATOM:String.fromCharCode(115)
ATOM:String.fromCharCode(100)
BINARY:String.fromCharCode(109)
SMALL_INTEGER:String.fromCharCode(97)
INTEGER:String.fromCharCode(98)
SMALL_BIG:String.fromCharCode(110)
LARGE_BIG:String.fromCharCode(111)
FLOAT:String.fromCharCode(99)
STRING:String.fromCharCode(107)
LIST:String.fromCharCode(108)
SMALL_TUPLE:String.fromCharCode(104)
LARGE_TUPLE:String.fromCharCode(105)
NIL:String.fromCharCode(106)
ZERO:String.fromCharCode(0)
BERT_START_C:131
SMALL_ATOM_C:115
ATOM_C:100
BINARY_C:109
SMALL_INTEGER_C:97
INTEGER_C:98
SMALL_BIG_C:110
LARGE_BIG_C:111
FLOAT_C:99
STRING_C:107
LIST_C:108
SMALL_TUPLE_C:104
LARGE_TUPLE_C:105
NIL_C:106
ZERO_C:0
constructor: ->
# console.log "initial "
this
encode: (obj) ->
re = @encode_inner(obj)
# console.log re
if Buffer.isBuffer re
re_buf = new Buffer(re.length+1)
re.copy re_buf,1
re_buf[0] = @BERT_START_C
# console.log re_buf
re_buf
else
@BERT_START+re
# decode: (obj) ->
# unless obj[0] is @BERT_START
# throw "invalid bert"
#
# new_obj = @decode_inner obj.substring(1)
#
# unless new_obj.rest is ""
# throw "invalid bert"
#
# new_obj.value
encode_inner: (obj) ->
if obj
func = 'encode_' + typeof(obj)
# console.log func
this[func](obj)
else
throw new Error("Cannot encode undefined values.")
encode_string: (obj) ->
buf = new Buffer(obj)
re_buf = new Buffer(buf.length+3)
len = @int_to_bytes(obj.length, 2)
buf.copy re_buf,3
for index in [0..len.length-1]
re_buf[index+1]=len[index].charCodeAt 0
re_buf[0]=@STRING_C
re_buf
encode_boolen: (obj) ->
if obj
@encode_inner @atom("true")
else
@encode_inner @atom("false")
encode_number: (obj) ->
s=isInteger= (obj%1 is 0)
unless isInteger
return @encode_float(obj)
unless !(isInteger && obj >= 0 && obj < 256)
re_buf = new Buffer(2)
re_buf[0]=@SMALL_INTEGER_C
re_buf[1]=@int_to_bytes(obj,1)[0].charCodeAt 0
re_buf
unless !(isInteger && obj >= -134217728 && obj <= 134217727)
re_buf = new Buffer(5)
re_buf[0]=@INTEGER_C
len=@int_to_bytes obj,4
for index in [0..len.length-1]
re_buf[index+1]=len[index].charCodeAt 0
re_buf
s = @bignum_to_bytes(obj)
buf = new Buffer(s)
len = 0
head = 0
if s.length < 256
# return @SMALL_BIG+@int_to_bytes(s.length - 1, 1) + s
len = @int_to_bytes(s.length-1, 1)
head=@SMALL_BIG_C
else
len = @int_to_bytes(s.length-1, 4)
head=@LARGE_BIG_C
start_index = 1+len.length
re_buf = new Buffer(buf.length+start_index)
buf.copy re_buf,start_index
re_buf[0]=head
for index in [0..len.length-1]
re_buf[index+1]=len[index].charCodeAt 0
re_buf
# return @LARGE_BIG +@int_to_bytes(s.length - 1, 4) + s
encode_float: (obj) ->
tmp_val=obj.toExponential();
while tmp_val.length <31
tmp_val+=@ZERO
# @FLOAT+s
buf = new Buffer(tmp_val)
re_buf = new Buffer(buf.length+1)
buf.copy re_buf,1
re_buf[0]=@FLOAT_C
re_buf
encode_object: (obj) ->
# console.log obj
unless obj
return @encode_inner @atom("null")
unless obj.type isnt "Atom"
return @encode_atom obj
unless obj.type isnt "Binary"
return @encode_binary obj
unless obj.type isnt "Tuple"
return @encode_tuple obj
unless obj.constructor.toString().indexOf("Array") is -1
return @encode_array obj
@encode_associative_array obj
encode_atom: (obj) ->
buf = new Buffer(obj.value)
re_buf = new Buffer(obj.value.length+3)
len = @int_to_bytes(obj.value.length, 2)
buf.copy re_buf,3
for index in [0..len.length-1]
re_buf[index+1]=len[index].charCodeAt 0
re_buf[0]=@ATOM_C
re_buf
encode_binary: (obj) ->
# console.log "encode_binary"
# console.log obj
re_buf = new Buffer(obj.value.length+5)
if Buffer.isBuffer obj.value
obj.value.copy re_buf,5
else
buf = new Buffer obj.value
buf.copy re_buf,5
re_buf[0] = @BINARY_C
len = @int_to_bytes(obj.value.length, 4)
for index in [0..3]
re_buf[index+1]=len[index].charCodeAt 0
# console.log re_buf
# @BINARY+@int_to_bytes(obj.value.length, 4)+obj.value
re_buf
encode_tuple: (obj) ->
# console.log "encode_tuple"
s=""
re_arr=[]
head=""
len=""
if obj.length < 256
head = @SMALL_TUPLE_C
len=@int_to_bytes obj.length, 1
# s+=@SMALL_TUPLE+@int_to_bytes obj.length, 1
else
head = @LARGE_TUPLE_C
len=@int_to_bytes obj.length, 4
# s+=@LARGE_TUPLE+@int_to_bytes obj.length, 4
for i in [0..obj.length-1]
tmp_re = @encode_inner obj[i]
# console.log tmp_re
# re_arr.push @encode_inner obj[i]
re_arr.push tmp_re
all_len = 0
for tmp_ele in re_arr
# console.log tmp_ele
all_len+=tmp_ele.length
start_index = 1+len.length
re_buf = new Buffer(all_len+start_index)
for tmp_ele in re_arr
all_len+=tmp_ele.length
tmp_ele.copy re_buf,start_index
start_index+=tmp_ele.length
for index in [0..len.length-1]
re_buf[index+1]=len[index].charCodeAt 0
re_buf[0]=head
# console.log "-----------"
# console.log re_buf
re_buf
# re_buf = new Buffer(obj.value.length+5)
encode_array: (obj) ->
# console.log "encode array"
unless obj.length isnt 0
return new Buffer(@NIL)
# s=@LIST+@int_to_bytes obj.length, 4
len = @int_to_bytes obj.length, 4
buf = new Buffer(5)
buf[0]=@LIST_C
for index in [0..len.length-1]
buf[index+1]=len[index].charCodeAt 0
re_arr = []
re_arr.push buf
for i in [0..obj.length-1]
re_arr.push @encode_inner obj[i]
# s+=@NIL
all_len = 0
for tmp_ele in re_arr
all_len+=tmp_ele.length
start_index = 0
end_index = all_len
re_buf = new Buffer(all_len+start_index+1) # all+nil
for tmp_ele in re_arr
all_len+=tmp_ele.length
tmp_ele.copy re_buf,start_index
start_index+=tmp_ele.length
re_buf[end_index]=@NIL_C
re_buf
encode_associative_array: (obj) ->
# console.log "encode_associative_array"
# console.log obj
arr = new Array()
for key,value of obj
unless !obj.hasOwnProperty key
arr.push @tuple(@atom(key), value)
@encode_array arr
int_to_bytes: (int, length) ->
isNegative=originalInt=i=rem=s=""
isNegative = int <0
int=-int-1 unless !isNegative
originalInt=int
for i in [0..length-1]
rem=int % 256
rem=255-rem unless !isNegative
# console.log rem
s=String.fromCharCode(rem) + s
int = Math.floor int/256
i+=1
throw("Argument out of range: "+originalInt) unless int <=0
s
# Encode an integer into an Erlang bignum,
# which is a byte of 1 or 0 representing
# whether the number is negative or positive,
# followed by little-endian bytes.
bignum_to_bytes: (int) ->
isNegative=rem=s= ""
isNegative = int < 0
if isNegative
int *= -1
s+=String.fromCharCode 1
else
s+=String.fromCharCode 0
while int isnt 0
rem = int % 256
s+=String.fromCharCode rem
int = Math.floor int/256
s
# @notic 基本类型
atom: (obj)->
{type:"Atom", value:obj, toString: -> obj}
binary: (obj) ->
{type:"Binary", value:obj, toString: ->
if Buffer.isBuffer obj
tmp_val = obj.toString()
"<<\"#{tmp_val}\">>"
else
"<<\"#{obj}\">>"}
tuple: (arr...) ->
tmp_obj = {type:"Tuple", length:arr.length, value:arr}
index = -1
tmp_obj[index+=1]=tmp_ele for tmp_ele in arr
tmp_obj.toString = ->
i = 0
s = ""
for i in [0..this.length-1]
unless s is ""
s+=", "
s+=this[i].toString();
"{#{s}}"
tmp_obj
binary_to_list: (str) ->
ret = new Array()
for i in [0..str.length-1]
ret.push str.fromCharCode i
ret
sign:(data) ->
shasum = crypto.createHash 'sha1'
shasum.update data
shasum.digest 'hex'
|
[
{
"context": "###\nNicholas Clawson -2014\n\nPopup list view to select tasks to run.\nEx",
"end": 20,
"score": 0.9996826648712158,
"start": 4,
"tag": "NAME",
"value": "Nicholas Clawson"
}
] | .atom/packages/grunt-runner/lib/task-list-view.coffee | callistino/dotfiles | 0 | ###
Nicholas Clawson -2014
Popup list view to select tasks to run.
Extends Atoms SelectListView but adds the functionality
of being able to add custom tasks to the list
###
{SelectListView, $$} = require 'atom'
module.exports = class TaskListView extends SelectListView
callback: ->
items: []
# creates the view, handles previous state
# adds enter handler
initialize:(callback, state = {}) ->
super
@callback = callback
@setItems if Array.isArray state.items then state.items else []
@addClass 'overlay from-top'
@setMaxItems 5
_this = @
this.filterEditorView.on 'keydown', (evt) ->
if evt.which == 13
selected = _this.getSelectedItem()
text = _this.filterEditorView.getEditor().getBuffer().getText()
_this.confirmed if selected then selected else text
# adds a single item to top of the list
# or moves the item to the top if it was already there
addItem:(item) ->
@items = [item].concat @items.filter (value) ->
item != value
# helper function: addItem for multiple items
addItems:(items) ->
@addItem item for item in items
# called when an Item is selected
confirmed:(item) ->
@addItem item
@cancel()
@callback item
# called whenever the list is attached to the dom
# makes sure to fill list up and set focus on editor
attach: ->
@populateList()
atom.workspaceView.append @
@focusFilterEditor()
# returns JSON object representing state
serialize: ->
return items: @items.slice 0, 4
# uses jquery(?) to return an object
viewForItem:(task) ->
$$ ->
@li task
# my empty message
getEmptyMessage: ->
"Press Enter to run the task."
| 113984 | ###
<NAME> -2014
Popup list view to select tasks to run.
Extends Atoms SelectListView but adds the functionality
of being able to add custom tasks to the list
###
{SelectListView, $$} = require 'atom'
module.exports = class TaskListView extends SelectListView
callback: ->
items: []
# creates the view, handles previous state
# adds enter handler
initialize:(callback, state = {}) ->
super
@callback = callback
@setItems if Array.isArray state.items then state.items else []
@addClass 'overlay from-top'
@setMaxItems 5
_this = @
this.filterEditorView.on 'keydown', (evt) ->
if evt.which == 13
selected = _this.getSelectedItem()
text = _this.filterEditorView.getEditor().getBuffer().getText()
_this.confirmed if selected then selected else text
# adds a single item to top of the list
# or moves the item to the top if it was already there
addItem:(item) ->
@items = [item].concat @items.filter (value) ->
item != value
# helper function: addItem for multiple items
addItems:(items) ->
@addItem item for item in items
# called when an Item is selected
confirmed:(item) ->
@addItem item
@cancel()
@callback item
# called whenever the list is attached to the dom
# makes sure to fill list up and set focus on editor
attach: ->
@populateList()
atom.workspaceView.append @
@focusFilterEditor()
# returns JSON object representing state
serialize: ->
return items: @items.slice 0, 4
# uses jquery(?) to return an object
viewForItem:(task) ->
$$ ->
@li task
# my empty message
getEmptyMessage: ->
"Press Enter to run the task."
| true | ###
PI:NAME:<NAME>END_PI -2014
Popup list view to select tasks to run.
Extends Atoms SelectListView but adds the functionality
of being able to add custom tasks to the list
###
{SelectListView, $$} = require 'atom'
module.exports = class TaskListView extends SelectListView
callback: ->
items: []
# creates the view, handles previous state
# adds enter handler
initialize:(callback, state = {}) ->
super
@callback = callback
@setItems if Array.isArray state.items then state.items else []
@addClass 'overlay from-top'
@setMaxItems 5
_this = @
this.filterEditorView.on 'keydown', (evt) ->
if evt.which == 13
selected = _this.getSelectedItem()
text = _this.filterEditorView.getEditor().getBuffer().getText()
_this.confirmed if selected then selected else text
# adds a single item to top of the list
# or moves the item to the top if it was already there
addItem:(item) ->
@items = [item].concat @items.filter (value) ->
item != value
# helper function: addItem for multiple items
addItems:(items) ->
@addItem item for item in items
# called when an Item is selected
confirmed:(item) ->
@addItem item
@cancel()
@callback item
# called whenever the list is attached to the dom
# makes sure to fill list up and set focus on editor
attach: ->
@populateList()
atom.workspaceView.append @
@focusFilterEditor()
# returns JSON object representing state
serialize: ->
return items: @items.slice 0, 4
# uses jquery(?) to return an object
viewForItem:(task) ->
$$ ->
@li task
# my empty message
getEmptyMessage: ->
"Press Enter to run the task."
|
[
{
"context": " when there is no date or time', ->\n name = 'Just a name'\n result = parser.parseNameDateTime n",
"end": 266,
"score": 0.8252332806587219,
"start": 262,
"tag": "NAME",
"value": "Just"
},
{
"context": "n there is no date or time', ->\n name = 'Just a name... | src/tests/parser_test.coffee | dwetterau/hubot-delta | 0 | assert = require 'assert'
Parser = require('../parser')
parser = null
describe 'parser', ->
before ->
parser = new Parser()
describe 'name and description parsing', ->
it 'should just return a name when there is no date or time', ->
name = 'Just a name'
result = parser.parseNameDateTime name
assert.equal result.length, 3
assert.equal result[0], name
assert.equal result[1], null
assert.equal result[2], null
it 'should return the name and description when both are present', ->
name = 'Just a name'
date = 'the date'
result = parser.parseNameDateTime(name + ' on ' + date)
assert.equal result.length, 3
assert.equal result[0], name
assert.equal result[1], date
assert.equal result[2], null
| 71008 | assert = require 'assert'
Parser = require('../parser')
parser = null
describe 'parser', ->
before ->
parser = new Parser()
describe 'name and description parsing', ->
it 'should just return a name when there is no date or time', ->
name = '<NAME> a name'
result = parser.parseNameDateTime name
assert.equal result.length, 3
assert.equal result[0], name
assert.equal result[1], null
assert.equal result[2], null
it 'should return the name and description when both are present', ->
name = '<NAME> a name'
date = 'the date'
result = parser.parseNameDateTime(name + ' on ' + date)
assert.equal result.length, 3
assert.equal result[0], name
assert.equal result[1], date
assert.equal result[2], null
| true | assert = require 'assert'
Parser = require('../parser')
parser = null
describe 'parser', ->
before ->
parser = new Parser()
describe 'name and description parsing', ->
it 'should just return a name when there is no date or time', ->
name = 'PI:NAME:<NAME>END_PI a name'
result = parser.parseNameDateTime name
assert.equal result.length, 3
assert.equal result[0], name
assert.equal result[1], null
assert.equal result[2], null
it 'should return the name and description when both are present', ->
name = 'PI:NAME:<NAME>END_PI a name'
date = 'the date'
result = parser.parseNameDateTime(name + ' on ' + date)
assert.equal result.length, 3
assert.equal result[0], name
assert.equal result[1], date
assert.equal result[2], null
|
[
{
"context": "# xcolor\n# Copyright (c) 2013 Charles Moncrief <cmoncrief@gmail.com>\n# MIT Licensed\n\nfs = r",
"end": 46,
"score": 0.9998728036880493,
"start": 30,
"tag": "NAME",
"value": "Charles Moncrief"
},
{
"context": "# xcolor\n# Copyright (c) 2013 Charles Moncrief <cmonc... | src/xcolor.coffee | cmoncrief/xcolor | 1 | # xcolor
# Copyright (c) 2013 Charles Moncrief <cmoncrief@gmail.com>
# MIT Licensed
fs = require 'fs'
{reset} = require './codes'
convert = require './convert'
custom = {}
format = (str) ->
str = str.replace /\{\{([\s\S]*?)\}\}/g, (str, p1) -> convert p1, custom
str = str.replace /(\&=[\S][\S])/g, (str, p1) -> convert p1, custom
str = str.replace /(\&\[?[+nN]?[?\S]?)/g, (str, p1) -> convert p1, custom
unless str.match /\x1B\[0m$/ then str = "#{str}#{reset}"
str
addStyle = (style = {}) ->
custom[key] = value for key, value of style
clearStyles = ->
custom = {}
loadStyles = (fileName) ->
try
fileInput = JSON.parse(fs.readFileSync fileName)
custom[key] = value for key, value of fileInput
catch error
return error
log = (input, args...) ->
console.log format(input), args...
module.exports = format
module.exports.log = log
module.exports.addStyle = addStyle
module.exports.loadStyles = loadStyles
| 12707 | # xcolor
# Copyright (c) 2013 <NAME> <<EMAIL>>
# MIT Licensed
fs = require 'fs'
{reset} = require './codes'
convert = require './convert'
custom = {}
format = (str) ->
str = str.replace /\{\{([\s\S]*?)\}\}/g, (str, p1) -> convert p1, custom
str = str.replace /(\&=[\S][\S])/g, (str, p1) -> convert p1, custom
str = str.replace /(\&\[?[+nN]?[?\S]?)/g, (str, p1) -> convert p1, custom
unless str.match /\x1B\[0m$/ then str = "#{str}#{reset}"
str
addStyle = (style = {}) ->
custom[key] = value for key, value of style
clearStyles = ->
custom = {}
loadStyles = (fileName) ->
try
fileInput = JSON.parse(fs.readFileSync fileName)
custom[key] = value for key, value of fileInput
catch error
return error
log = (input, args...) ->
console.log format(input), args...
module.exports = format
module.exports.log = log
module.exports.addStyle = addStyle
module.exports.loadStyles = loadStyles
| true | # xcolor
# Copyright (c) 2013 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
# MIT Licensed
fs = require 'fs'
{reset} = require './codes'
convert = require './convert'
custom = {}
format = (str) ->
str = str.replace /\{\{([\s\S]*?)\}\}/g, (str, p1) -> convert p1, custom
str = str.replace /(\&=[\S][\S])/g, (str, p1) -> convert p1, custom
str = str.replace /(\&\[?[+nN]?[?\S]?)/g, (str, p1) -> convert p1, custom
unless str.match /\x1B\[0m$/ then str = "#{str}#{reset}"
str
addStyle = (style = {}) ->
custom[key] = value for key, value of style
clearStyles = ->
custom = {}
loadStyles = (fileName) ->
try
fileInput = JSON.parse(fs.readFileSync fileName)
custom[key] = value for key, value of fileInput
catch error
return error
log = (input, args...) ->
console.log format(input), args...
module.exports = format
module.exports.log = log
module.exports.addStyle = addStyle
module.exports.loadStyles = loadStyles
|
[
{
"context": "xtends LayerInfo\n @shouldParse: (key) -> key is 'lnsr'\n\n parse: ->\n @id = @file.readString(4)",
"end": 138,
"score": 0.9114049077033997,
"start": 134,
"tag": "KEY",
"value": "lnsr"
}
] | lib/psd/layer_info/layer_name_source.coffee | LoginovIlya/psd.js | 2,218 | LayerInfo = require '../layer_info.coffee'
module.exports = class LayerNameSource extends LayerInfo
@shouldParse: (key) -> key is 'lnsr'
parse: ->
@id = @file.readString(4) | 181600 | LayerInfo = require '../layer_info.coffee'
module.exports = class LayerNameSource extends LayerInfo
@shouldParse: (key) -> key is '<KEY>'
parse: ->
@id = @file.readString(4) | true | LayerInfo = require '../layer_info.coffee'
module.exports = class LayerNameSource extends LayerInfo
@shouldParse: (key) -> key is 'PI:KEY:<KEY>END_PI'
parse: ->
@id = @file.readString(4) |
[
{
"context": "# Copyright (C) 2012\tSaleem Abdul Hamid\n# \n# This file is part of Mundlejs.\n# \n# Mundlejs",
"end": 39,
"score": 0.9998797178268433,
"start": 21,
"tag": "NAME",
"value": "Saleem Abdul Hamid"
}
] | src/client.coffee | meelash/Mundlejs | 0 | # Copyright (C) 2012 Saleem Abdul Hamid
#
# This file is part of Mundlejs.
#
# Mundlejs is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# Some portions Copyright (C) 2012 Koding, Inc. under the MIT License
# http://www.opensource.org/licenses/mit-license.php
#
# base refers to js files that are referenced from the base dir path defined server-side- generally not packaged mundles
# mundle refers to js files that are in packaged mundles installed in the mundles directory by `mundle install`
basePrefix = '/b'
mundlePrefix = '/m'
# Each file that is loaded is evaluated in the context of a new Module instance
# Each instance has the variables module, exports, and require in scope
# module is a reference to the module instance for that file
# exports is the exports object which can be changed in the initial evaluation of the file to define the module api
# require will require a new file (with the option of a relative path, relative to the parent of this file)
class Module
constructor:(@path)->
@exports = {}
runInContext:(source)->
module = @
exports = module.exports
require = module.require.bind module
eval source
return module.exports
# If module has not been fetched, fetch it and all its dependencies asynchronously and execute just it immediately, then callback its exports
# If module has been fetched but not executed, execute it, then return and callback its exports
# If module has already been executed, just return and callback its exports
require:(path, callback)->
if /^(\.|\.\.)?\//.test path
path = resolveBasePath path, parent @path
requireBase path, callback
else
path = resolveMundlePath path
requireMundle path, callback
baseModule = (new Module "#{basePrefix}/")
# The var require here was added for testing in node.js to override node's require
window.require = require = baseModule.require.bind baseModule
requestHostname = window.location.hostname
requestPort = window.location.port
# xhr request to server
# looks like: http://<location.hostname>:<location.port>/mundlejs</file requested>?alreadyLoadedModule=1&anotherAlreadyLoaded=1&.....
serverRequire = (path, callback)->
request = new XMLHttpRequest()
request.open('GET', "//#{requestHostname}:#{requestPort}/mundlejs#{path}?#{cacheDiffString()}", true)
# request.setRequestHeader 'clientid', 'lakjsdflkjasld'
request.responseType = 'text'
request.onload = ->
response = JSON.parse request.response
callback response.err, response.results
request.send()
##
# Utils
##
requireBase = (path, callback)->
if (exported = cache.modules[path])?
callback? null, exported
return exported
else if (source = cache.fetched[path])?
do ->
module = new Module path
exported = cache.modules[path] = module.runInContext source
callback? null, exported
return exported
else
serverRequire path, (errors, sources)=>
# console.log path
# console.log Object.keys sources
if errors?
for err in errors when err?
console.warn err
for own subPath, source of sources
cache.fetched[subPath] = source
callback? null, requireBase path
requireMundle = (path, callback)->
if (exported = cache.modules[path])?
callback? null, exported
return exported
else if (source = cache.fetched[path])?
do ->
module = new Module path
exported = cache.modules[path] = module.runInContext source
callback? null, exported
return exported
else
serverRequire path, (errors, sources)=>
# console.log path
# console.log Object.keys sources
if errors?
for err in errors when err?
console.warn err
for own subPath, source of sources
cache.fetched[subPath] = source
cacheVersion subPath
path = updateMundleVersion path
callback? null, requireMundle path
# All paths get resolved to 'absolute' paths from the client-side 'root' with either a '/m/' or '/b/' prefix.
# /m is the path to installed mundles
# /b is the base path set on the server-side component
# relative path, e.g. '../foo.js' in a file at '/b/foo/bar/bar.js' resolves to '/b/foo/foo.js'
# "absolute" path, e.g. '/foo.js' resolves to '/b/foo.js'
# mundle name, e.g. 'foo' resolves to '/m/foo'
resolveBasePath = (path, parentPath)->
# absolute paths
if /^\//.test path
return path = "#{basePrefix}#{path}"
# relative paths
else
components = path.split '/'
path = parentPath
while components.length > 0
switch component = (components.splice 0, 1)[0]
when '..'
path = parent path
when '.'
else
path += "/#{component}"
return path
resolveMundlePath = (path)->
match = /^(.*?)((@)(.*?))?(\/.*)?$/.exec path
version = match[4] or cache.versions[match[1]] or '0.0.0'
path = "#{mundlePrefix}/#{match[1]}/#{version}"
if (subDir = match[5])?
path += subDir
path
updateMundleVersion = (path)->
match = /^(\/m\/(.*?)\/)(.*?)(\/.*)?$/.exec path
if (version = match[3]) is '0.0.0'
version = cache.versions[match[2]] or '0.0.0'
path = match[1]+version
if (subDir = match[4])?
path += subDir
path
parent = (path)->
ar = path.split '/'
console.error 'parent only accepts absolute paths' unless ar[0] is ''
if ar[1] is 'm'
if ar.length < 5 # []/[m]/[moduleName]/[version]/
return ar.join '/'
else if ar.length < 3 # []/[b]/
return ar.join '/'
ar.pop()
ar.join '/'
cacheDiffString = ->
((Object.keys cache.fetched).join '=1&') + '=1'
cacheVersion = (path)->
if (match = /\/m\/(.*?)\/(.*?)(\/.*)?$/.exec path)?
[match, mundle, version] = match
cache.versions[mundle] = version
# modules - {file:reference to exports from already executed files}
# fetched - {file:string of the text of an already fetched file}
cache =
modules : {}
fetched : {}
versions : {}
| 52138 | # Copyright (C) 2012 <NAME>
#
# This file is part of Mundlejs.
#
# Mundlejs is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# Some portions Copyright (C) 2012 Koding, Inc. under the MIT License
# http://www.opensource.org/licenses/mit-license.php
#
# base refers to js files that are referenced from the base dir path defined server-side- generally not packaged mundles
# mundle refers to js files that are in packaged mundles installed in the mundles directory by `mundle install`
basePrefix = '/b'
mundlePrefix = '/m'
# Each file that is loaded is evaluated in the context of a new Module instance
# Each instance has the variables module, exports, and require in scope
# module is a reference to the module instance for that file
# exports is the exports object which can be changed in the initial evaluation of the file to define the module api
# require will require a new file (with the option of a relative path, relative to the parent of this file)
class Module
constructor:(@path)->
@exports = {}
runInContext:(source)->
module = @
exports = module.exports
require = module.require.bind module
eval source
return module.exports
# If module has not been fetched, fetch it and all its dependencies asynchronously and execute just it immediately, then callback its exports
# If module has been fetched but not executed, execute it, then return and callback its exports
# If module has already been executed, just return and callback its exports
require:(path, callback)->
if /^(\.|\.\.)?\//.test path
path = resolveBasePath path, parent @path
requireBase path, callback
else
path = resolveMundlePath path
requireMundle path, callback
baseModule = (new Module "#{basePrefix}/")
# The var require here was added for testing in node.js to override node's require
window.require = require = baseModule.require.bind baseModule
requestHostname = window.location.hostname
requestPort = window.location.port
# xhr request to server
# looks like: http://<location.hostname>:<location.port>/mundlejs</file requested>?alreadyLoadedModule=1&anotherAlreadyLoaded=1&.....
serverRequire = (path, callback)->
request = new XMLHttpRequest()
request.open('GET', "//#{requestHostname}:#{requestPort}/mundlejs#{path}?#{cacheDiffString()}", true)
# request.setRequestHeader 'clientid', 'lakjsdflkjasld'
request.responseType = 'text'
request.onload = ->
response = JSON.parse request.response
callback response.err, response.results
request.send()
##
# Utils
##
requireBase = (path, callback)->
if (exported = cache.modules[path])?
callback? null, exported
return exported
else if (source = cache.fetched[path])?
do ->
module = new Module path
exported = cache.modules[path] = module.runInContext source
callback? null, exported
return exported
else
serverRequire path, (errors, sources)=>
# console.log path
# console.log Object.keys sources
if errors?
for err in errors when err?
console.warn err
for own subPath, source of sources
cache.fetched[subPath] = source
callback? null, requireBase path
requireMundle = (path, callback)->
if (exported = cache.modules[path])?
callback? null, exported
return exported
else if (source = cache.fetched[path])?
do ->
module = new Module path
exported = cache.modules[path] = module.runInContext source
callback? null, exported
return exported
else
serverRequire path, (errors, sources)=>
# console.log path
# console.log Object.keys sources
if errors?
for err in errors when err?
console.warn err
for own subPath, source of sources
cache.fetched[subPath] = source
cacheVersion subPath
path = updateMundleVersion path
callback? null, requireMundle path
# All paths get resolved to 'absolute' paths from the client-side 'root' with either a '/m/' or '/b/' prefix.
# /m is the path to installed mundles
# /b is the base path set on the server-side component
# relative path, e.g. '../foo.js' in a file at '/b/foo/bar/bar.js' resolves to '/b/foo/foo.js'
# "absolute" path, e.g. '/foo.js' resolves to '/b/foo.js'
# mundle name, e.g. 'foo' resolves to '/m/foo'
resolveBasePath = (path, parentPath)->
# absolute paths
if /^\//.test path
return path = "#{basePrefix}#{path}"
# relative paths
else
components = path.split '/'
path = parentPath
while components.length > 0
switch component = (components.splice 0, 1)[0]
when '..'
path = parent path
when '.'
else
path += "/#{component}"
return path
resolveMundlePath = (path)->
match = /^(.*?)((@)(.*?))?(\/.*)?$/.exec path
version = match[4] or cache.versions[match[1]] or '0.0.0'
path = "#{mundlePrefix}/#{match[1]}/#{version}"
if (subDir = match[5])?
path += subDir
path
updateMundleVersion = (path)->
match = /^(\/m\/(.*?)\/)(.*?)(\/.*)?$/.exec path
if (version = match[3]) is '0.0.0'
version = cache.versions[match[2]] or '0.0.0'
path = match[1]+version
if (subDir = match[4])?
path += subDir
path
parent = (path)->
ar = path.split '/'
console.error 'parent only accepts absolute paths' unless ar[0] is ''
if ar[1] is 'm'
if ar.length < 5 # []/[m]/[moduleName]/[version]/
return ar.join '/'
else if ar.length < 3 # []/[b]/
return ar.join '/'
ar.pop()
ar.join '/'
cacheDiffString = ->
((Object.keys cache.fetched).join '=1&') + '=1'
cacheVersion = (path)->
if (match = /\/m\/(.*?)\/(.*?)(\/.*)?$/.exec path)?
[match, mundle, version] = match
cache.versions[mundle] = version
# modules - {file:reference to exports from already executed files}
# fetched - {file:string of the text of an already fetched file}
cache =
modules : {}
fetched : {}
versions : {}
| true | # Copyright (C) 2012 PI:NAME:<NAME>END_PI
#
# This file is part of Mundlejs.
#
# Mundlejs is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# Some portions Copyright (C) 2012 Koding, Inc. under the MIT License
# http://www.opensource.org/licenses/mit-license.php
#
# base refers to js files that are referenced from the base dir path defined server-side- generally not packaged mundles
# mundle refers to js files that are in packaged mundles installed in the mundles directory by `mundle install`
basePrefix = '/b'
mundlePrefix = '/m'
# Each file that is loaded is evaluated in the context of a new Module instance
# Each instance has the variables module, exports, and require in scope
# module is a reference to the module instance for that file
# exports is the exports object which can be changed in the initial evaluation of the file to define the module api
# require will require a new file (with the option of a relative path, relative to the parent of this file)
class Module
constructor:(@path)->
@exports = {}
runInContext:(source)->
module = @
exports = module.exports
require = module.require.bind module
eval source
return module.exports
# If module has not been fetched, fetch it and all its dependencies asynchronously and execute just it immediately, then callback its exports
# If module has been fetched but not executed, execute it, then return and callback its exports
# If module has already been executed, just return and callback its exports
require:(path, callback)->
if /^(\.|\.\.)?\//.test path
path = resolveBasePath path, parent @path
requireBase path, callback
else
path = resolveMundlePath path
requireMundle path, callback
baseModule = (new Module "#{basePrefix}/")
# The var require here was added for testing in node.js to override node's require
window.require = require = baseModule.require.bind baseModule
requestHostname = window.location.hostname
requestPort = window.location.port
# xhr request to server
# looks like: http://<location.hostname>:<location.port>/mundlejs</file requested>?alreadyLoadedModule=1&anotherAlreadyLoaded=1&.....
serverRequire = (path, callback)->
request = new XMLHttpRequest()
request.open('GET', "//#{requestHostname}:#{requestPort}/mundlejs#{path}?#{cacheDiffString()}", true)
# request.setRequestHeader 'clientid', 'lakjsdflkjasld'
request.responseType = 'text'
request.onload = ->
response = JSON.parse request.response
callback response.err, response.results
request.send()
##
# Utils
##
requireBase = (path, callback)->
if (exported = cache.modules[path])?
callback? null, exported
return exported
else if (source = cache.fetched[path])?
do ->
module = new Module path
exported = cache.modules[path] = module.runInContext source
callback? null, exported
return exported
else
serverRequire path, (errors, sources)=>
# console.log path
# console.log Object.keys sources
if errors?
for err in errors when err?
console.warn err
for own subPath, source of sources
cache.fetched[subPath] = source
callback? null, requireBase path
requireMundle = (path, callback)->
if (exported = cache.modules[path])?
callback? null, exported
return exported
else if (source = cache.fetched[path])?
do ->
module = new Module path
exported = cache.modules[path] = module.runInContext source
callback? null, exported
return exported
else
serverRequire path, (errors, sources)=>
# console.log path
# console.log Object.keys sources
if errors?
for err in errors when err?
console.warn err
for own subPath, source of sources
cache.fetched[subPath] = source
cacheVersion subPath
path = updateMundleVersion path
callback? null, requireMundle path
# All paths get resolved to 'absolute' paths from the client-side 'root' with either a '/m/' or '/b/' prefix.
# /m is the path to installed mundles
# /b is the base path set on the server-side component
# relative path, e.g. '../foo.js' in a file at '/b/foo/bar/bar.js' resolves to '/b/foo/foo.js'
# "absolute" path, e.g. '/foo.js' resolves to '/b/foo.js'
# mundle name, e.g. 'foo' resolves to '/m/foo'
resolveBasePath = (path, parentPath)->
# absolute paths
if /^\//.test path
return path = "#{basePrefix}#{path}"
# relative paths
else
components = path.split '/'
path = parentPath
while components.length > 0
switch component = (components.splice 0, 1)[0]
when '..'
path = parent path
when '.'
else
path += "/#{component}"
return path
resolveMundlePath = (path)->
match = /^(.*?)((@)(.*?))?(\/.*)?$/.exec path
version = match[4] or cache.versions[match[1]] or '0.0.0'
path = "#{mundlePrefix}/#{match[1]}/#{version}"
if (subDir = match[5])?
path += subDir
path
updateMundleVersion = (path)->
match = /^(\/m\/(.*?)\/)(.*?)(\/.*)?$/.exec path
if (version = match[3]) is '0.0.0'
version = cache.versions[match[2]] or '0.0.0'
path = match[1]+version
if (subDir = match[4])?
path += subDir
path
parent = (path)->
ar = path.split '/'
console.error 'parent only accepts absolute paths' unless ar[0] is ''
if ar[1] is 'm'
if ar.length < 5 # []/[m]/[moduleName]/[version]/
return ar.join '/'
else if ar.length < 3 # []/[b]/
return ar.join '/'
ar.pop()
ar.join '/'
cacheDiffString = ->
((Object.keys cache.fetched).join '=1&') + '=1'
cacheVersion = (path)->
if (match = /\/m\/(.*?)\/(.*?)(\/.*)?$/.exec path)?
[match, mundle, version] = match
cache.versions[mundle] = version
# modules - {file:reference to exports from already executed files}
# fetched - {file:string of the text of an already fetched file}
cache =
modules : {}
fetched : {}
versions : {}
|
[
{
"context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public Li",
"end": 43,
"score": 0.9999109506607056,
"start": 29,
"tag": "EMAIL",
"value": "contact@ppy.sh"
}
] | resources/assets/lib/select-options.coffee | osu-katakuna/osu-katakuna-web | 5 | # Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
# See the LICENCE file in the repository root for full licence text.
import * as React from 'react'
import { a, i, div } from 'react-dom-factories'
import { createRef, PureComponent } from 'react'
export class SelectOptions extends PureComponent
constructor: (props) ->
super props
@bn = @props.bn ? 'select-options'
@hasBlackout = @props.blackout || @props.blackout == undefined
@ref = createRef()
@state =
showingSelector: false
componentDidMount: =>
document.addEventListener 'click', @hideSelector
componentDidUpdate: (_prevProps, prevState) =>
Blackout.toggle(@state.showingSelector, 0.5) if @hasBlackout && prevState.showingSelector != @state.showingSelector
componentWillUnmount: ->
document.removeEventListener 'click', @hideSelector
render: =>
classNames = "#{@bn}"
classNames += " #{@bn}--selecting" if @state.showingSelector
div
className: classNames
ref: @ref
div
className: "#{@bn}__select"
@renderItem
children: [
div
className: 'u-ellipsis-overflow'
key: 'current'
@props.selected?.text
div
key: 'decoration'
className: "#{@bn}__decoration",
i className: "fas fa-chevron-down"
]
item: @props.selected
onClick: @toggleSelector
div
className: "#{@bn}__selector"
for item in @props.options
@renderOption item
renderOption: (item) =>
@renderItem
children: [
div
className: 'u-ellipsis-overflow'
key: item.id
item.text
],
item: item
selected: @props.selected?.id == item.id
onClick: (event) => @itemSelected(event, item)
renderItem: ({ children, item, onClick, selected = false }) ->
cssClasses = "#{@bn}__item"
cssClasses += " #{@bn}__item--selected" if selected
return @props.renderItem({ children, item, onClick, cssClasses }) if @props.renderItem?
a
className: cssClasses
href: '#'
key: item.id
onClick: onClick
children
# dismiss the selector if clicking anywhere outside of it.
hideSelector: (e) =>
@setState showingSelector: false if e.button == 0 && !(@ref.current in e.composedPath())
itemSelected: (event, item) ->
return if event.button != 0
event.preventDefault()
@setState showingSelector: false
@props.onItemSelected?(item)
toggleSelector: (event) =>
return if event.button != 0
event.preventDefault()
@setState showingSelector: !@state.showingSelector
| 71857 | # Copyright (c) ppy Pty Ltd <<EMAIL>>. Licensed under the GNU Affero General Public License v3.0.
# See the LICENCE file in the repository root for full licence text.
import * as React from 'react'
import { a, i, div } from 'react-dom-factories'
import { createRef, PureComponent } from 'react'
export class SelectOptions extends PureComponent
constructor: (props) ->
super props
@bn = @props.bn ? 'select-options'
@hasBlackout = @props.blackout || @props.blackout == undefined
@ref = createRef()
@state =
showingSelector: false
componentDidMount: =>
document.addEventListener 'click', @hideSelector
componentDidUpdate: (_prevProps, prevState) =>
Blackout.toggle(@state.showingSelector, 0.5) if @hasBlackout && prevState.showingSelector != @state.showingSelector
componentWillUnmount: ->
document.removeEventListener 'click', @hideSelector
render: =>
classNames = "#{@bn}"
classNames += " #{@bn}--selecting" if @state.showingSelector
div
className: classNames
ref: @ref
div
className: "#{@bn}__select"
@renderItem
children: [
div
className: 'u-ellipsis-overflow'
key: 'current'
@props.selected?.text
div
key: 'decoration'
className: "#{@bn}__decoration",
i className: "fas fa-chevron-down"
]
item: @props.selected
onClick: @toggleSelector
div
className: "#{@bn}__selector"
for item in @props.options
@renderOption item
renderOption: (item) =>
@renderItem
children: [
div
className: 'u-ellipsis-overflow'
key: item.id
item.text
],
item: item
selected: @props.selected?.id == item.id
onClick: (event) => @itemSelected(event, item)
renderItem: ({ children, item, onClick, selected = false }) ->
cssClasses = "#{@bn}__item"
cssClasses += " #{@bn}__item--selected" if selected
return @props.renderItem({ children, item, onClick, cssClasses }) if @props.renderItem?
a
className: cssClasses
href: '#'
key: item.id
onClick: onClick
children
# dismiss the selector if clicking anywhere outside of it.
hideSelector: (e) =>
@setState showingSelector: false if e.button == 0 && !(@ref.current in e.composedPath())
itemSelected: (event, item) ->
return if event.button != 0
event.preventDefault()
@setState showingSelector: false
@props.onItemSelected?(item)
toggleSelector: (event) =>
return if event.button != 0
event.preventDefault()
@setState showingSelector: !@state.showingSelector
| true | # Copyright (c) ppy Pty Ltd <PI:EMAIL:<EMAIL>END_PI>. Licensed under the GNU Affero General Public License v3.0.
# See the LICENCE file in the repository root for full licence text.
import * as React from 'react'
import { a, i, div } from 'react-dom-factories'
import { createRef, PureComponent } from 'react'
export class SelectOptions extends PureComponent
constructor: (props) ->
super props
@bn = @props.bn ? 'select-options'
@hasBlackout = @props.blackout || @props.blackout == undefined
@ref = createRef()
@state =
showingSelector: false
componentDidMount: =>
document.addEventListener 'click', @hideSelector
componentDidUpdate: (_prevProps, prevState) =>
Blackout.toggle(@state.showingSelector, 0.5) if @hasBlackout && prevState.showingSelector != @state.showingSelector
componentWillUnmount: ->
document.removeEventListener 'click', @hideSelector
render: =>
classNames = "#{@bn}"
classNames += " #{@bn}--selecting" if @state.showingSelector
div
className: classNames
ref: @ref
div
className: "#{@bn}__select"
@renderItem
children: [
div
className: 'u-ellipsis-overflow'
key: 'current'
@props.selected?.text
div
key: 'decoration'
className: "#{@bn}__decoration",
i className: "fas fa-chevron-down"
]
item: @props.selected
onClick: @toggleSelector
div
className: "#{@bn}__selector"
for item in @props.options
@renderOption item
renderOption: (item) =>
@renderItem
children: [
div
className: 'u-ellipsis-overflow'
key: item.id
item.text
],
item: item
selected: @props.selected?.id == item.id
onClick: (event) => @itemSelected(event, item)
renderItem: ({ children, item, onClick, selected = false }) ->
cssClasses = "#{@bn}__item"
cssClasses += " #{@bn}__item--selected" if selected
return @props.renderItem({ children, item, onClick, cssClasses }) if @props.renderItem?
a
className: cssClasses
href: '#'
key: item.id
onClick: onClick
children
# dismiss the selector if clicking anywhere outside of it.
hideSelector: (e) =>
@setState showingSelector: false if e.button == 0 && !(@ref.current in e.composedPath())
itemSelected: (event, item) ->
return if event.button != 0
event.preventDefault()
@setState showingSelector: false
@props.onItemSelected?(item)
toggleSelector: (event) =>
return if event.button != 0
event.preventDefault()
@setState showingSelector: !@state.showingSelector
|
[
{
"context": "ta)-> \n data.user.name.assert_Is 'Joe'\n\n using new Api_File(), ->\n @.get(req, r",
"end": 841,
"score": 0.9996725916862488,
"start": 838,
"tag": "NAME",
"value": "Joe"
},
{
"context": "ty.json_Parse()\n data.user.name.assert_Is 'Joe'\n\... | test/controllers/Api-File.test.coffee | nhannan/BSIMM | 0 | Api_File = require '../../src/controllers/Api-File'
#Server = require '../../src/server/Server'
describe 'controllers | Api-File', ->
#app = null
api_File = null
before ->
using new Api_File(), ->
api_File = @
#app = new Server().setup_Server().app
it 'constructor', ->
using api_File, ->
@.constructor.name.assert_Is 'Api_File'
@.router.assert_Is_Function()
@.data_Files.constructor.name.assert_Is 'Data_Files'
it 'add_Routes', ->
using api_File, ->
@.add_Routes()
@.router.stack.assert_Size_Is 3
it 'get', ->
req =
params :
filename: 'json-data'
res =
setHeader: (name, value)->
name.assert_Is 'Content-Type'
value.assert_Is 'application/json'
send: (data)->
data.user.name.assert_Is 'Joe'
using new Api_File(), ->
@.get(req, res)
it 'get (pretty)', ->
req =
params :
filename: 'json-data'
query:
pretty : ''
res =
setHeader: (name, value)->
name.assert_Is 'Content-Type'
value.assert_Is 'application/json'
send: (data_pretty)->
assert_Is_Undefined data_pretty.user
data = data_pretty.json_Parse()
data.user.name.assert_Is 'Joe'
using new Api_File(), ->
@.get(req, res)
it 'get (bad data)', ->
req = params : null
res =
send: (data)->
data.assert_Is {error: 'not found' }
using new Api_File(), ->
@.get(req, res)
it 'list', ->
res =
send: (data)->
data.assert_Size_Is_Bigger_Than 3
data.assert_Contains [ 'coffee-data', 'health-care-results', 'json-data' ]
using new Api_File(), ->
@.data_Files.data_Path.assert_Folder_Exists()
@.list(null,res)
it 'save', ->
data_Path = api_File.data_Files
.data_Path.assert_Folder_Exists()
file_Name = "tmp-file"
file_Path = "#{data_Path}/#{file_Name}.json"
initial_Data = { initial: 'data' }
changed_Data = { other : 'data' }
file_Path.file_Write initial_Data.json_Str()
req =
params: filename: file_Name
body : changed_Data.json_Str()
res =
send: (data)->
file_Path.file_Contents().assert_Is changed_Data.json_Str()
data.assert_Is { status: 'file saved ok'}
file_Path.assert_File_Deleted()
using new Api_File(), ->
@.save req, res
it 'save (bad file)', ->
req =
params: filename: 'aaaa'
body : 'bbb'
res =
send: (data)->
data.assert_Is { error: 'save failed'}
using new Api_File(), ->
@.save req, res | 35310 | Api_File = require '../../src/controllers/Api-File'
#Server = require '../../src/server/Server'
describe 'controllers | Api-File', ->
#app = null
api_File = null
before ->
using new Api_File(), ->
api_File = @
#app = new Server().setup_Server().app
it 'constructor', ->
using api_File, ->
@.constructor.name.assert_Is 'Api_File'
@.router.assert_Is_Function()
@.data_Files.constructor.name.assert_Is 'Data_Files'
it 'add_Routes', ->
using api_File, ->
@.add_Routes()
@.router.stack.assert_Size_Is 3
it 'get', ->
req =
params :
filename: 'json-data'
res =
setHeader: (name, value)->
name.assert_Is 'Content-Type'
value.assert_Is 'application/json'
send: (data)->
data.user.name.assert_Is '<NAME>'
using new Api_File(), ->
@.get(req, res)
it 'get (pretty)', ->
req =
params :
filename: 'json-data'
query:
pretty : ''
res =
setHeader: (name, value)->
name.assert_Is 'Content-Type'
value.assert_Is 'application/json'
send: (data_pretty)->
assert_Is_Undefined data_pretty.user
data = data_pretty.json_Parse()
data.user.name.assert_Is '<NAME>'
using new Api_File(), ->
@.get(req, res)
it 'get (bad data)', ->
req = params : null
res =
send: (data)->
data.assert_Is {error: 'not found' }
using new Api_File(), ->
@.get(req, res)
it 'list', ->
res =
send: (data)->
data.assert_Size_Is_Bigger_Than 3
data.assert_Contains [ 'coffee-data', 'health-care-results', 'json-data' ]
using new Api_File(), ->
@.data_Files.data_Path.assert_Folder_Exists()
@.list(null,res)
it 'save', ->
data_Path = api_File.data_Files
.data_Path.assert_Folder_Exists()
file_Name = "tmp-file"
file_Path = "#{data_Path}/#{file_Name}.json"
initial_Data = { initial: 'data' }
changed_Data = { other : 'data' }
file_Path.file_Write initial_Data.json_Str()
req =
params: filename: file_Name
body : changed_Data.json_Str()
res =
send: (data)->
file_Path.file_Contents().assert_Is changed_Data.json_Str()
data.assert_Is { status: 'file saved ok'}
file_Path.assert_File_Deleted()
using new Api_File(), ->
@.save req, res
it 'save (bad file)', ->
req =
params: filename: 'aaaa'
body : 'bbb'
res =
send: (data)->
data.assert_Is { error: 'save failed'}
using new Api_File(), ->
@.save req, res | true | Api_File = require '../../src/controllers/Api-File'
#Server = require '../../src/server/Server'
describe 'controllers | Api-File', ->
#app = null
api_File = null
before ->
using new Api_File(), ->
api_File = @
#app = new Server().setup_Server().app
it 'constructor', ->
using api_File, ->
@.constructor.name.assert_Is 'Api_File'
@.router.assert_Is_Function()
@.data_Files.constructor.name.assert_Is 'Data_Files'
it 'add_Routes', ->
using api_File, ->
@.add_Routes()
@.router.stack.assert_Size_Is 3
it 'get', ->
req =
params :
filename: 'json-data'
res =
setHeader: (name, value)->
name.assert_Is 'Content-Type'
value.assert_Is 'application/json'
send: (data)->
data.user.name.assert_Is 'PI:NAME:<NAME>END_PI'
using new Api_File(), ->
@.get(req, res)
it 'get (pretty)', ->
req =
params :
filename: 'json-data'
query:
pretty : ''
res =
setHeader: (name, value)->
name.assert_Is 'Content-Type'
value.assert_Is 'application/json'
send: (data_pretty)->
assert_Is_Undefined data_pretty.user
data = data_pretty.json_Parse()
data.user.name.assert_Is 'PI:NAME:<NAME>END_PI'
using new Api_File(), ->
@.get(req, res)
it 'get (bad data)', ->
req = params : null
res =
send: (data)->
data.assert_Is {error: 'not found' }
using new Api_File(), ->
@.get(req, res)
it 'list', ->
res =
send: (data)->
data.assert_Size_Is_Bigger_Than 3
data.assert_Contains [ 'coffee-data', 'health-care-results', 'json-data' ]
using new Api_File(), ->
@.data_Files.data_Path.assert_Folder_Exists()
@.list(null,res)
it 'save', ->
data_Path = api_File.data_Files
.data_Path.assert_Folder_Exists()
file_Name = "tmp-file"
file_Path = "#{data_Path}/#{file_Name}.json"
initial_Data = { initial: 'data' }
changed_Data = { other : 'data' }
file_Path.file_Write initial_Data.json_Str()
req =
params: filename: file_Name
body : changed_Data.json_Str()
res =
send: (data)->
file_Path.file_Contents().assert_Is changed_Data.json_Str()
data.assert_Is { status: 'file saved ok'}
file_Path.assert_File_Deleted()
using new Api_File(), ->
@.save req, res
it 'save (bad file)', ->
req =
params: filename: 'aaaa'
body : 'bbb'
res =
send: (data)->
data.assert_Is { error: 'save failed'}
using new Api_File(), ->
@.save req, res |
[
{
"context": "# Галереи\njQuery ($) ->\n\t$ '*[data-toggle=\"lightbox\"]'\n\t.cl",
"end": 9,
"score": 0.8451868891716003,
"start": 2,
"tag": "NAME",
"value": "Галереи"
}
] | coffee/lightbox.coffee | ooo-rbin/simpla-theme-bootstrap | 1 | # Галереи
jQuery ($) ->
$ '*[data-toggle="lightbox"]'
.click (event) ->
event.preventDefault();
do $ this
.ekkoLightbox
| 121043 | # <NAME>
jQuery ($) ->
$ '*[data-toggle="lightbox"]'
.click (event) ->
event.preventDefault();
do $ this
.ekkoLightbox
| true | # PI:NAME:<NAME>END_PI
jQuery ($) ->
$ '*[data-toggle="lightbox"]'
.click (event) ->
event.preventDefault();
do $ this
.ekkoLightbox
|
[
{
"context": "er.unload()\n\t\t\tR.city =\n\t\t\t\towner: owner\n\t\t\t\tname: name\n\t\t\t\tsite: null\n\t\t\tR.drawingMode = if name in ['pi",
"end": 3113,
"score": 0.9728670120239258,
"start": 3109,
"tag": "NAME",
"value": "name"
}
] | coffee/City.coffee | arthursw/comme-un-dessein-client | 0 | define ['paper', 'R', 'Utils/Utils', 'UI/Modal', 'i18next' ], (P, R, Utils, Modal, i18next) ->
class CityManager
constructor: ()->
@cityPanelJ = $('#City')
@citiesListsJ = @cityPanelJ.find('.city-list')
@userCitiesJ = @cityPanelJ.find('.user-cities')
@publicCitiesJ = @cityPanelJ.find('.public-cities')
@createCityBtnJ = @cityPanelJ.find('.create-city')
@citiesListBtnJ = @cityPanelJ.find('.load-city')
@createCityBtnJ.click @createCityModal
@citiesListBtnJ.click @citiesModal
if R.offline then return
$.ajax( { method: "POST", url: "ajaxCall/", data: { data: JSON.stringify({ function: 'loadCities', args: {} }) } } ).done(@addCities)
return
createCity: (data)=>
# Dajaxice.draw.createCity(@createCityCallback, name: data.name, public: data.public)
$.ajax( method: "POST", url: "ajaxCall/", data: data: JSON.stringify { function: 'createCity', args: name: data.name, public: data.public } ).done(@createCityCallback)
return
createCityCallback: (result)=>
modal = Modal.getModalByTitle('Create city')
modal?.hide()
if not R.loader.checkError(result) then return
city = JSON.parse(result.city)
@addCity(city, true)
@loadCity(city.name, city.owner)
return
createCityModal: ()=>
modal = Modal.createModal( title: 'Create city', submit: @createCity, postSubmit: 'load' )
modal.addTextInput( label: "City name", name: 'name', required: true, submitShortcut: true, placeholder: 'Paris' )
modal.addCheckbox( label: "Public", name: 'public', helpMessage: "Public cities will be accessible by anyone.", defaultValue: true )
modal.show()
return
addCity: (city, userCity)->
cityJ = $("<li>")
cityJ.append($('<span>').addClass('name').attr('data-i18n', city.name).text(i18next.t(city.name)))
cityJ.attr('data-owner', city.owner).attr('data-pk', city._id.$oid).attr('data-public', city.public or 0).attr('data-name', city.name)
cityJ.click @onCityClicked
# popover
# cityJ.attr('data-placement', 'right')
# cityJ.attr('data-container', 'body')
# cityJ.attr('data-trigger', 'hover')
# cityJ.attr('data-delay', {show: 500, hide: 100})
# cityJ.attr('data-content', 'by ' + city.owner)
# # cityJ.attr('data-content', 'by '+city.owner)
# cityJ.popover()
if userCity
btnJ = $('<button type="button"><span class="glyphicon glyphicon-cog" aria-hidden="true"></span></button>')
btnJ.click @openCitySettings
cityJ.append(btnJ)
@userCitiesJ.append(cityJ)
else
@publicCitiesJ.append(cityJ)
return
addCities: (result)=>
if not R.loader.checkError(result) then return
userCities = JSON.parse(result.userCities)
publicCities = JSON.parse(result.publicCities)
for cities, i in [userCities, publicCities]
userCity = i==0
for city in cities
@addCity(city, userCity)
return
onCityClicked: (event)=>
parentJ = $(event.target).closest('li')
name = parentJ.attr('data-name')
owner = parentJ.attr('data-owner')
@loadCity(name, owner)
return
loadCity: (name, owner)->
R.loader.unload()
R.city =
owner: owner
name: name
site: null
R.drawingMode = if name in ['pixel', 'ortho', 'orthoDiag', 'image', 'line', 'lineOrthoDiag', 'dot', 'cross'] then name else null
R.loader.load()
R.view.updateHash()
R.view.createBackground()
if R.selectedTool instanceof R.Tools.Path
R.selectedTool.showDraftLimits()
return
openCitySettings: (event)=>
event.stopPropagation()
liJ = $(event.target).closest('li')
name = liJ.attr('data-name')
isPublic = parseInt(liJ.attr('data-public'))
pk = liJ.attr('data-pk')
modal = Modal.createModal(title: 'Modify city', submit: @updateCity, data: { pk: pk, name: name }, postSubmit: 'load' )
modal.addTextInput( name: 'name', label: 'Name', defaultValue: name, required: true, submitShortcut: true )
modal.addCheckbox( name: 'public', label: 'Public', helpMessage: "Public cities will be accessible by anyone.", defaultValue: isPublic )
modal.addButton( name: 'Delete', type: 'danger', submit: @deleteCity)
modal.show()
return
updateCity: (data)=>
if R.city.name == data.data.name
@modifyingCurrentCity = true
# Dajaxice.draw.updateCity(@updateCityCallback, pk: data.data.pk, name: data.name, public: data.public )
$.ajax( method: "POST", url: "ajaxCall/", data: data: JSON.stringify { function: 'updateCity', args: pk: data.data.pk, name: data.name, public: data.public } ).done(@updateCityCallback)
return
updateCityCallback: (result)=>
modal = Modal.getModalByTitle('Modify city')
modal.hide()
if not R.loader.checkError(result)
@modifyingCurrentCity = false
return
city = JSON.parse(result.city)
if @modifyingCurrentCity
R.city.name = city.name
R.city.owner = city.owner
R.view.updateHash()
@modifyingCurrentCity = false
cityJ = @citiesListsJ.find('li[data-pk="' + city._id.$oid + '"]')
cityJ.attr('data-name', city.name)
cityJ.attr('data-public', Number(city.public or 0))
cityJ.attr('data-content', 'by ' + city.owner)
cityJ.find('.name').text(city.name)
return
deleteCity: (data)=>
# Dajaxice.draw.deleteCity(@deleteCityCallback, {name: data.data.name})
$.ajax( method: "POST", url: "ajaxCall/", data: data: JSON.stringify { function: 'deleteCity', args: {name: data.data.name} } ).done(@deleteCityCallback)
return
deleteCityCallback: (result)=>
if not R.loader.checkError(result) then return
@citiesListsJ.find('li[data-pk="'+result.cityPk+'"]').remove()
return
# displayCities: ()->
# # Dajaxice.draw.loadPublicCities(@loadPublicCitiesCallback)
# $.ajax( method: "POST", url: "ajaxCall/", data: data: JSON.stringify { function: 'loadPublicCities', args: {} } ).done(@loadPublicCitiesCallback)
# return
#
# cityRowClicked: (field, value, row, $element)=>
# console.log row.pk
# @loadCity(row.name, row.author)
# return
# loadPublicCitiesCallback: (result)->
# if not R.loader.checkError(result) then return
#
# modal = Modal.createModal( title: 'Cities', submit: null )
#
# tableData =
# columns: [
# field: 'name'
# title: 'Name'
# ,
# field: 'author'
# title: 'Author'
# ,
# field: 'date'
# title: 'Date'
# ,
# field: 'public'
# title: 'Public'
# ]
# data: []
#
# for city in publicCities
# tableData.data.push( name: city.name, author: city.author, date: city.date, public: city.public, pk: city._id.$oid )
#
# tableJ = modal.addTable(tableData)
# tableJ.on 'click-cell.bs.table', @cityRowClicked
# modal.show()
# return
# R.initializeCities = ()->
# R.toolsJ.find("[data-name='Create']").click ()->
# submit = (data)->
# # Dajaxice.draw.createCity(R.loadCityFromServer, name: data.name, public: data.public)
# $.ajax( method: "POST", url: "ajaxCall/", data: data: JSON.stringify { function: 'createCity', args: name: data.name, public: data.public } ).done(R.loadCityFromServer))
# return
# modal = Modal.createModal( title: 'Create city', submit: submit, postSubmit: 'load' )
# modal.addTextInput( label: "City name", name: 'name', required: true, submitShortcut: true, placeholder: 'Paris' )
# modal.addCheckbox( label: "Public", name: 'public', helpMessage: "Public cities will be accessible by anyone.", defaultValue: true )
# modal.show()
# return
# R.toolsJ.find("[data-name='Open']").click ()->
# modal = Modal.createModal( title: 'Open city', name: 'open-city' )
# modal.modalBodyJ.find('.modal-footer').hide()
# modal.addProgressBar()
# modal.show()
# # Dajaxice.draw.loadCities(R.loadCities)
# $.ajax( method: "POST", url: "ajaxCall/", data: data: JSON.stringify { function: 'loadCities', args: {} } ).done(R.loadCities)
# return
# return
# R.modifyCity = (event)->
# event.stopPropagation()
# buttonJ = $(this)
# parentJ = buttonJ.parents('tr:first')
# name = parentJ.attr('data-name')
# isPublic = parseInt(parentJ.attr('data-public'))
# pk = parentJ.attr('data-pk')
# updateCity = (data)->
# callback = (result)->
# modal = Modal.getModalByTitle('Modify city')
# modal.hide()
# if not R.loader.checkError(result) then return
# city = JSON.parse(result.city)
# R.alertManager.alert "City successfully renamed to: " + city.name, "info"
# modalBodyJ = Modal.getModalByTitle('Open city').modalBodyJ
# rowJ = modalBodyJ.find('[data-pk="' + city._id.$oid + '"]')
# rowJ.attr('data-name', city.name)
# rowJ.attr('data-public', Number(city.public or 0))
# rowJ.find('.name').text(city.name)
# rowJ.find('.public').text(if city.public then 'Public' else 'Private')
# return
# # Dajaxice.draw.updateCity(callback, pk: data.data.pk, name: data.name, public: data.public )
# $.ajax( method: "POST", url: "ajaxCall/", data: data: JSON.stringify { function: 'updateCity', args: pk: data.data.pk, name: data.name, public: data.public } ).done(callback))
# return
# modal = Modal.createModal(title: 'Modify city', submit: updateCity, data: { pk: pk }, postSubmit: 'load' )
# modal.addTextInput( name: 'name', label: 'Name', defaultValue: name, required: true, submitShortcut: true )
# modal.addCheckbox( name: 'public', label: 'Public', helpMessage: "Public cities will be accessible by anyone.", defaultValue: isPublic )
# modal.show()
# # event.stopPropagation()
# # buttonJ = $(this)
# # parentJ = buttonJ.parents('tr:first')
# # parentJ.find('input.name').show()
# # parentJ.find('input.public').attr('disabled', false)
# # buttonJ.text('Ok')
# # buttonJ.off('click').click (event)->
# # event.stopPropagation()
# # buttonJ = $(this)
# # parentJ = buttonJ.parents('tr:first')
# # inputJ = parentJ.find('input.name')
# # publicJ = parentJ.find('input.public')
# # pk = parentJ.attr('data-pk')
# # newName = inputJ.val()
# # isPublic = publicJ.is(':checked')
# # callback = (result)->
# # if not R.loader.checkError(result) then return
# # city = JSON.parse(result.city)
# # R.alertManager.alert "City successfully renamed to: " + city.name, "info"
# # return
# # # Dajaxice.draw.updateCity(callback, pk: pk, name: newName, 'public': isPublic )
# # $.ajax( method: "POST", url: "ajaxCall/", data: data: JSON.stringify { function: 'updateCity', args: pk: pk, name: newName, 'public': isPublic } ).done(callback))
# # inputJ.hide()
# # publicJ.attr('disabled', true)
# # buttonJ.off('click').click(R.modifyCity)
# # return
# return
# R.loadCities = (result)->
# if not R.loader.checkError(result) then return
# userCities = JSON.parse(result.userCities)
# publicCities = JSON.parse(result.publicCities)
# modal = Modal.getModalByTitle('Open city')
# modal.removeProgressBar()
# modalBodyJ = modal.modalBodyJ
# for citiesList, i in [userCities, publicCities]
# if i==0 and userCities.length>0
# titleJ = $('<h3>').text('Your cities')
# modalBodyJ.append(titleJ)
# # tdJ.append(titleJ)
# else
# titleJ = $('<h3>').text('Public cities')
# modalBodyJ.append(titleJ)
# # tdJ.append(titleJ)
# tableJ = $('<table>').addClass("table table-hover").css( width: "100%" )
# tbodyJ = $('<tbody>')
# for city in citiesList
# rowJ = $("<tr>").attr('data-name', city.name).attr('data-owner', city.owner).attr('data-pk', city._id.$oid).attr('data-public', Number(city.public or 0))
# td1J = $('<td>')
# td2J = $('<td>')
# td3J = $('<td>')
# # rowJ.css( display: 'inline-block' )
# nameJ = $("<span class='name'>").text(city.name)
# # date = new Date(city.date)
# # dateJ = $("<div>").text(date.toLocaleString())
# td1J.append(nameJ)
# # rowJ.append(dateJ)
# if i==0
# publicJ = $("<span class='public'>").text(if city.public then 'Public' else 'Private')
# td2J.append(publicJ)
# modifyButtonJ = $('<button class="btn btn-default">').text('Modify')
# modifyButtonJ.click(R.modifyCity)
# deleteButtonJ = $('<button class="btn btn-default">').text('Delete')
# deleteButtonJ.click (event)->
# event.stopPropagation()
# name = $(this).parents('tr:first').attr('data-name')
# # Dajaxice.draw.deleteCity(R.loader.checkError, name: name)
# $.ajax( method: "POST", url: "ajaxCall/", data: data: JSON.stringify { function: 'deleteCity', args: name: name } ).done(R.loader.checkError))
# return
# td3J.append(modifyButtonJ)
# td3J.append(deleteButtonJ)
# loadButtonJ = $('<button class="btn btn-primary">').text('Load')
# loadButtonJ.click ()->
# name = $(this).parents('tr:first').attr('data-name')
# owner = $(this).parents('tr:first').attr('data-owner')
# R.loadCity(name, owner)
# return
# td3J.append(loadButtonJ)
# rowJ.append(td1J, td2J, td3J)
# tbodyJ.append(rowJ)
# tableJ.append(tbodyJ)
# modalBodyJ.append(tableJ)
# return
return CityManager
| 193090 | define ['paper', 'R', 'Utils/Utils', 'UI/Modal', 'i18next' ], (P, R, Utils, Modal, i18next) ->
class CityManager
constructor: ()->
@cityPanelJ = $('#City')
@citiesListsJ = @cityPanelJ.find('.city-list')
@userCitiesJ = @cityPanelJ.find('.user-cities')
@publicCitiesJ = @cityPanelJ.find('.public-cities')
@createCityBtnJ = @cityPanelJ.find('.create-city')
@citiesListBtnJ = @cityPanelJ.find('.load-city')
@createCityBtnJ.click @createCityModal
@citiesListBtnJ.click @citiesModal
if R.offline then return
$.ajax( { method: "POST", url: "ajaxCall/", data: { data: JSON.stringify({ function: 'loadCities', args: {} }) } } ).done(@addCities)
return
createCity: (data)=>
# Dajaxice.draw.createCity(@createCityCallback, name: data.name, public: data.public)
$.ajax( method: "POST", url: "ajaxCall/", data: data: JSON.stringify { function: 'createCity', args: name: data.name, public: data.public } ).done(@createCityCallback)
return
createCityCallback: (result)=>
modal = Modal.getModalByTitle('Create city')
modal?.hide()
if not R.loader.checkError(result) then return
city = JSON.parse(result.city)
@addCity(city, true)
@loadCity(city.name, city.owner)
return
createCityModal: ()=>
modal = Modal.createModal( title: 'Create city', submit: @createCity, postSubmit: 'load' )
modal.addTextInput( label: "City name", name: 'name', required: true, submitShortcut: true, placeholder: 'Paris' )
modal.addCheckbox( label: "Public", name: 'public', helpMessage: "Public cities will be accessible by anyone.", defaultValue: true )
modal.show()
return
addCity: (city, userCity)->
cityJ = $("<li>")
cityJ.append($('<span>').addClass('name').attr('data-i18n', city.name).text(i18next.t(city.name)))
cityJ.attr('data-owner', city.owner).attr('data-pk', city._id.$oid).attr('data-public', city.public or 0).attr('data-name', city.name)
cityJ.click @onCityClicked
# popover
# cityJ.attr('data-placement', 'right')
# cityJ.attr('data-container', 'body')
# cityJ.attr('data-trigger', 'hover')
# cityJ.attr('data-delay', {show: 500, hide: 100})
# cityJ.attr('data-content', 'by ' + city.owner)
# # cityJ.attr('data-content', 'by '+city.owner)
# cityJ.popover()
if userCity
btnJ = $('<button type="button"><span class="glyphicon glyphicon-cog" aria-hidden="true"></span></button>')
btnJ.click @openCitySettings
cityJ.append(btnJ)
@userCitiesJ.append(cityJ)
else
@publicCitiesJ.append(cityJ)
return
addCities: (result)=>
if not R.loader.checkError(result) then return
userCities = JSON.parse(result.userCities)
publicCities = JSON.parse(result.publicCities)
for cities, i in [userCities, publicCities]
userCity = i==0
for city in cities
@addCity(city, userCity)
return
onCityClicked: (event)=>
parentJ = $(event.target).closest('li')
name = parentJ.attr('data-name')
owner = parentJ.attr('data-owner')
@loadCity(name, owner)
return
loadCity: (name, owner)->
R.loader.unload()
R.city =
owner: owner
name: <NAME>
site: null
R.drawingMode = if name in ['pixel', 'ortho', 'orthoDiag', 'image', 'line', 'lineOrthoDiag', 'dot', 'cross'] then name else null
R.loader.load()
R.view.updateHash()
R.view.createBackground()
if R.selectedTool instanceof R.Tools.Path
R.selectedTool.showDraftLimits()
return
openCitySettings: (event)=>
event.stopPropagation()
liJ = $(event.target).closest('li')
name = liJ.attr('data-name')
isPublic = parseInt(liJ.attr('data-public'))
pk = liJ.attr('data-pk')
modal = Modal.createModal(title: 'Modify city', submit: @updateCity, data: { pk: pk, name: name }, postSubmit: 'load' )
modal.addTextInput( name: 'name', label: 'Name', defaultValue: name, required: true, submitShortcut: true )
modal.addCheckbox( name: 'public', label: 'Public', helpMessage: "Public cities will be accessible by anyone.", defaultValue: isPublic )
modal.addButton( name: 'Delete', type: 'danger', submit: @deleteCity)
modal.show()
return
updateCity: (data)=>
if R.city.name == data.data.name
@modifyingCurrentCity = true
# Dajaxice.draw.updateCity(@updateCityCallback, pk: data.data.pk, name: data.name, public: data.public )
$.ajax( method: "POST", url: "ajaxCall/", data: data: JSON.stringify { function: 'updateCity', args: pk: data.data.pk, name: data.name, public: data.public } ).done(@updateCityCallback)
return
updateCityCallback: (result)=>
modal = Modal.getModalByTitle('Modify city')
modal.hide()
if not R.loader.checkError(result)
@modifyingCurrentCity = false
return
city = JSON.parse(result.city)
if @modifyingCurrentCity
R.city.name = city.name
R.city.owner = city.owner
R.view.updateHash()
@modifyingCurrentCity = false
cityJ = @citiesListsJ.find('li[data-pk="' + city._id.$oid + '"]')
cityJ.attr('data-name', city.name)
cityJ.attr('data-public', Number(city.public or 0))
cityJ.attr('data-content', 'by ' + city.owner)
cityJ.find('.name').text(city.name)
return
deleteCity: (data)=>
# Dajaxice.draw.deleteCity(@deleteCityCallback, {name: data.data.name})
$.ajax( method: "POST", url: "ajaxCall/", data: data: JSON.stringify { function: 'deleteCity', args: {name: data.data.name} } ).done(@deleteCityCallback)
return
deleteCityCallback: (result)=>
if not R.loader.checkError(result) then return
@citiesListsJ.find('li[data-pk="'+result.cityPk+'"]').remove()
return
# displayCities: ()->
# # Dajaxice.draw.loadPublicCities(@loadPublicCitiesCallback)
# $.ajax( method: "POST", url: "ajaxCall/", data: data: JSON.stringify { function: 'loadPublicCities', args: {} } ).done(@loadPublicCitiesCallback)
# return
#
# cityRowClicked: (field, value, row, $element)=>
# console.log row.pk
# @loadCity(row.name, row.author)
# return
# loadPublicCitiesCallback: (result)->
# if not R.loader.checkError(result) then return
#
# modal = Modal.createModal( title: 'Cities', submit: null )
#
# tableData =
# columns: [
# field: 'name'
# title: 'Name'
# ,
# field: 'author'
# title: 'Author'
# ,
# field: 'date'
# title: 'Date'
# ,
# field: 'public'
# title: 'Public'
# ]
# data: []
#
# for city in publicCities
# tableData.data.push( name: city.name, author: city.author, date: city.date, public: city.public, pk: city._id.$oid )
#
# tableJ = modal.addTable(tableData)
# tableJ.on 'click-cell.bs.table', @cityRowClicked
# modal.show()
# return
# R.initializeCities = ()->
# R.toolsJ.find("[data-name='Create']").click ()->
# submit = (data)->
# # Dajaxice.draw.createCity(R.loadCityFromServer, name: data.name, public: data.public)
# $.ajax( method: "POST", url: "ajaxCall/", data: data: JSON.stringify { function: 'createCity', args: name: data.name, public: data.public } ).done(R.loadCityFromServer))
# return
# modal = Modal.createModal( title: 'Create city', submit: submit, postSubmit: 'load' )
# modal.addTextInput( label: "City name", name: 'name', required: true, submitShortcut: true, placeholder: 'Paris' )
# modal.addCheckbox( label: "Public", name: 'public', helpMessage: "Public cities will be accessible by anyone.", defaultValue: true )
# modal.show()
# return
# R.toolsJ.find("[data-name='Open']").click ()->
# modal = Modal.createModal( title: 'Open city', name: 'open-city' )
# modal.modalBodyJ.find('.modal-footer').hide()
# modal.addProgressBar()
# modal.show()
# # Dajaxice.draw.loadCities(R.loadCities)
# $.ajax( method: "POST", url: "ajaxCall/", data: data: JSON.stringify { function: 'loadCities', args: {} } ).done(R.loadCities)
# return
# return
# R.modifyCity = (event)->
# event.stopPropagation()
# buttonJ = $(this)
# parentJ = buttonJ.parents('tr:first')
# name = parentJ.attr('data-name')
# isPublic = parseInt(parentJ.attr('data-public'))
# pk = parentJ.attr('data-pk')
# updateCity = (data)->
# callback = (result)->
# modal = Modal.getModalByTitle('Modify city')
# modal.hide()
# if not R.loader.checkError(result) then return
# city = JSON.parse(result.city)
# R.alertManager.alert "City successfully renamed to: " + city.name, "info"
# modalBodyJ = Modal.getModalByTitle('Open city').modalBodyJ
# rowJ = modalBodyJ.find('[data-pk="' + city._id.$oid + '"]')
# rowJ.attr('data-name', city.name)
# rowJ.attr('data-public', Number(city.public or 0))
# rowJ.find('.name').text(city.name)
# rowJ.find('.public').text(if city.public then 'Public' else 'Private')
# return
# # Dajaxice.draw.updateCity(callback, pk: data.data.pk, name: data.name, public: data.public )
# $.ajax( method: "POST", url: "ajaxCall/", data: data: JSON.stringify { function: 'updateCity', args: pk: data.data.pk, name: data.name, public: data.public } ).done(callback))
# return
# modal = Modal.createModal(title: 'Modify city', submit: updateCity, data: { pk: pk }, postSubmit: 'load' )
# modal.addTextInput( name: 'name', label: 'Name', defaultValue: name, required: true, submitShortcut: true )
# modal.addCheckbox( name: 'public', label: 'Public', helpMessage: "Public cities will be accessible by anyone.", defaultValue: isPublic )
# modal.show()
# # event.stopPropagation()
# # buttonJ = $(this)
# # parentJ = buttonJ.parents('tr:first')
# # parentJ.find('input.name').show()
# # parentJ.find('input.public').attr('disabled', false)
# # buttonJ.text('Ok')
# # buttonJ.off('click').click (event)->
# # event.stopPropagation()
# # buttonJ = $(this)
# # parentJ = buttonJ.parents('tr:first')
# # inputJ = parentJ.find('input.name')
# # publicJ = parentJ.find('input.public')
# # pk = parentJ.attr('data-pk')
# # newName = inputJ.val()
# # isPublic = publicJ.is(':checked')
# # callback = (result)->
# # if not R.loader.checkError(result) then return
# # city = JSON.parse(result.city)
# # R.alertManager.alert "City successfully renamed to: " + city.name, "info"
# # return
# # # Dajaxice.draw.updateCity(callback, pk: pk, name: newName, 'public': isPublic )
# # $.ajax( method: "POST", url: "ajaxCall/", data: data: JSON.stringify { function: 'updateCity', args: pk: pk, name: newName, 'public': isPublic } ).done(callback))
# # inputJ.hide()
# # publicJ.attr('disabled', true)
# # buttonJ.off('click').click(R.modifyCity)
# # return
# return
# R.loadCities = (result)->
# if not R.loader.checkError(result) then return
# userCities = JSON.parse(result.userCities)
# publicCities = JSON.parse(result.publicCities)
# modal = Modal.getModalByTitle('Open city')
# modal.removeProgressBar()
# modalBodyJ = modal.modalBodyJ
# for citiesList, i in [userCities, publicCities]
# if i==0 and userCities.length>0
# titleJ = $('<h3>').text('Your cities')
# modalBodyJ.append(titleJ)
# # tdJ.append(titleJ)
# else
# titleJ = $('<h3>').text('Public cities')
# modalBodyJ.append(titleJ)
# # tdJ.append(titleJ)
# tableJ = $('<table>').addClass("table table-hover").css( width: "100%" )
# tbodyJ = $('<tbody>')
# for city in citiesList
# rowJ = $("<tr>").attr('data-name', city.name).attr('data-owner', city.owner).attr('data-pk', city._id.$oid).attr('data-public', Number(city.public or 0))
# td1J = $('<td>')
# td2J = $('<td>')
# td3J = $('<td>')
# # rowJ.css( display: 'inline-block' )
# nameJ = $("<span class='name'>").text(city.name)
# # date = new Date(city.date)
# # dateJ = $("<div>").text(date.toLocaleString())
# td1J.append(nameJ)
# # rowJ.append(dateJ)
# if i==0
# publicJ = $("<span class='public'>").text(if city.public then 'Public' else 'Private')
# td2J.append(publicJ)
# modifyButtonJ = $('<button class="btn btn-default">').text('Modify')
# modifyButtonJ.click(R.modifyCity)
# deleteButtonJ = $('<button class="btn btn-default">').text('Delete')
# deleteButtonJ.click (event)->
# event.stopPropagation()
# name = $(this).parents('tr:first').attr('data-name')
# # Dajaxice.draw.deleteCity(R.loader.checkError, name: name)
# $.ajax( method: "POST", url: "ajaxCall/", data: data: JSON.stringify { function: 'deleteCity', args: name: name } ).done(R.loader.checkError))
# return
# td3J.append(modifyButtonJ)
# td3J.append(deleteButtonJ)
# loadButtonJ = $('<button class="btn btn-primary">').text('Load')
# loadButtonJ.click ()->
# name = $(this).parents('tr:first').attr('data-name')
# owner = $(this).parents('tr:first').attr('data-owner')
# R.loadCity(name, owner)
# return
# td3J.append(loadButtonJ)
# rowJ.append(td1J, td2J, td3J)
# tbodyJ.append(rowJ)
# tableJ.append(tbodyJ)
# modalBodyJ.append(tableJ)
# return
return CityManager
| true | define ['paper', 'R', 'Utils/Utils', 'UI/Modal', 'i18next' ], (P, R, Utils, Modal, i18next) ->
class CityManager
constructor: ()->
@cityPanelJ = $('#City')
@citiesListsJ = @cityPanelJ.find('.city-list')
@userCitiesJ = @cityPanelJ.find('.user-cities')
@publicCitiesJ = @cityPanelJ.find('.public-cities')
@createCityBtnJ = @cityPanelJ.find('.create-city')
@citiesListBtnJ = @cityPanelJ.find('.load-city')
@createCityBtnJ.click @createCityModal
@citiesListBtnJ.click @citiesModal
if R.offline then return
$.ajax( { method: "POST", url: "ajaxCall/", data: { data: JSON.stringify({ function: 'loadCities', args: {} }) } } ).done(@addCities)
return
createCity: (data)=>
# Dajaxice.draw.createCity(@createCityCallback, name: data.name, public: data.public)
$.ajax( method: "POST", url: "ajaxCall/", data: data: JSON.stringify { function: 'createCity', args: name: data.name, public: data.public } ).done(@createCityCallback)
return
createCityCallback: (result)=>
modal = Modal.getModalByTitle('Create city')
modal?.hide()
if not R.loader.checkError(result) then return
city = JSON.parse(result.city)
@addCity(city, true)
@loadCity(city.name, city.owner)
return
createCityModal: ()=>
modal = Modal.createModal( title: 'Create city', submit: @createCity, postSubmit: 'load' )
modal.addTextInput( label: "City name", name: 'name', required: true, submitShortcut: true, placeholder: 'Paris' )
modal.addCheckbox( label: "Public", name: 'public', helpMessage: "Public cities will be accessible by anyone.", defaultValue: true )
modal.show()
return
addCity: (city, userCity)->
cityJ = $("<li>")
cityJ.append($('<span>').addClass('name').attr('data-i18n', city.name).text(i18next.t(city.name)))
cityJ.attr('data-owner', city.owner).attr('data-pk', city._id.$oid).attr('data-public', city.public or 0).attr('data-name', city.name)
cityJ.click @onCityClicked
# popover
# cityJ.attr('data-placement', 'right')
# cityJ.attr('data-container', 'body')
# cityJ.attr('data-trigger', 'hover')
# cityJ.attr('data-delay', {show: 500, hide: 100})
# cityJ.attr('data-content', 'by ' + city.owner)
# # cityJ.attr('data-content', 'by '+city.owner)
# cityJ.popover()
if userCity
btnJ = $('<button type="button"><span class="glyphicon glyphicon-cog" aria-hidden="true"></span></button>')
btnJ.click @openCitySettings
cityJ.append(btnJ)
@userCitiesJ.append(cityJ)
else
@publicCitiesJ.append(cityJ)
return
addCities: (result)=>
if not R.loader.checkError(result) then return
userCities = JSON.parse(result.userCities)
publicCities = JSON.parse(result.publicCities)
for cities, i in [userCities, publicCities]
userCity = i==0
for city in cities
@addCity(city, userCity)
return
onCityClicked: (event)=>
parentJ = $(event.target).closest('li')
name = parentJ.attr('data-name')
owner = parentJ.attr('data-owner')
@loadCity(name, owner)
return
loadCity: (name, owner)->
R.loader.unload()
R.city =
owner: owner
name: PI:NAME:<NAME>END_PI
site: null
R.drawingMode = if name in ['pixel', 'ortho', 'orthoDiag', 'image', 'line', 'lineOrthoDiag', 'dot', 'cross'] then name else null
R.loader.load()
R.view.updateHash()
R.view.createBackground()
if R.selectedTool instanceof R.Tools.Path
R.selectedTool.showDraftLimits()
return
openCitySettings: (event)=>
event.stopPropagation()
liJ = $(event.target).closest('li')
name = liJ.attr('data-name')
isPublic = parseInt(liJ.attr('data-public'))
pk = liJ.attr('data-pk')
modal = Modal.createModal(title: 'Modify city', submit: @updateCity, data: { pk: pk, name: name }, postSubmit: 'load' )
modal.addTextInput( name: 'name', label: 'Name', defaultValue: name, required: true, submitShortcut: true )
modal.addCheckbox( name: 'public', label: 'Public', helpMessage: "Public cities will be accessible by anyone.", defaultValue: isPublic )
modal.addButton( name: 'Delete', type: 'danger', submit: @deleteCity)
modal.show()
return
updateCity: (data)=>
if R.city.name == data.data.name
@modifyingCurrentCity = true
# Dajaxice.draw.updateCity(@updateCityCallback, pk: data.data.pk, name: data.name, public: data.public )
$.ajax( method: "POST", url: "ajaxCall/", data: data: JSON.stringify { function: 'updateCity', args: pk: data.data.pk, name: data.name, public: data.public } ).done(@updateCityCallback)
return
updateCityCallback: (result)=>
modal = Modal.getModalByTitle('Modify city')
modal.hide()
if not R.loader.checkError(result)
@modifyingCurrentCity = false
return
city = JSON.parse(result.city)
if @modifyingCurrentCity
R.city.name = city.name
R.city.owner = city.owner
R.view.updateHash()
@modifyingCurrentCity = false
cityJ = @citiesListsJ.find('li[data-pk="' + city._id.$oid + '"]')
cityJ.attr('data-name', city.name)
cityJ.attr('data-public', Number(city.public or 0))
cityJ.attr('data-content', 'by ' + city.owner)
cityJ.find('.name').text(city.name)
return
deleteCity: (data)=>
# Dajaxice.draw.deleteCity(@deleteCityCallback, {name: data.data.name})
$.ajax( method: "POST", url: "ajaxCall/", data: data: JSON.stringify { function: 'deleteCity', args: {name: data.data.name} } ).done(@deleteCityCallback)
return
deleteCityCallback: (result)=>
if not R.loader.checkError(result) then return
@citiesListsJ.find('li[data-pk="'+result.cityPk+'"]').remove()
return
# displayCities: ()->
# # Dajaxice.draw.loadPublicCities(@loadPublicCitiesCallback)
# $.ajax( method: "POST", url: "ajaxCall/", data: data: JSON.stringify { function: 'loadPublicCities', args: {} } ).done(@loadPublicCitiesCallback)
# return
#
# cityRowClicked: (field, value, row, $element)=>
# console.log row.pk
# @loadCity(row.name, row.author)
# return
# loadPublicCitiesCallback: (result)->
# if not R.loader.checkError(result) then return
#
# modal = Modal.createModal( title: 'Cities', submit: null )
#
# tableData =
# columns: [
# field: 'name'
# title: 'Name'
# ,
# field: 'author'
# title: 'Author'
# ,
# field: 'date'
# title: 'Date'
# ,
# field: 'public'
# title: 'Public'
# ]
# data: []
#
# for city in publicCities
# tableData.data.push( name: city.name, author: city.author, date: city.date, public: city.public, pk: city._id.$oid )
#
# tableJ = modal.addTable(tableData)
# tableJ.on 'click-cell.bs.table', @cityRowClicked
# modal.show()
# return
# R.initializeCities = ()->
# R.toolsJ.find("[data-name='Create']").click ()->
# submit = (data)->
# # Dajaxice.draw.createCity(R.loadCityFromServer, name: data.name, public: data.public)
# $.ajax( method: "POST", url: "ajaxCall/", data: data: JSON.stringify { function: 'createCity', args: name: data.name, public: data.public } ).done(R.loadCityFromServer))
# return
# modal = Modal.createModal( title: 'Create city', submit: submit, postSubmit: 'load' )
# modal.addTextInput( label: "City name", name: 'name', required: true, submitShortcut: true, placeholder: 'Paris' )
# modal.addCheckbox( label: "Public", name: 'public', helpMessage: "Public cities will be accessible by anyone.", defaultValue: true )
# modal.show()
# return
# R.toolsJ.find("[data-name='Open']").click ()->
# modal = Modal.createModal( title: 'Open city', name: 'open-city' )
# modal.modalBodyJ.find('.modal-footer').hide()
# modal.addProgressBar()
# modal.show()
# # Dajaxice.draw.loadCities(R.loadCities)
# $.ajax( method: "POST", url: "ajaxCall/", data: data: JSON.stringify { function: 'loadCities', args: {} } ).done(R.loadCities)
# return
# return
# R.modifyCity = (event)->
# event.stopPropagation()
# buttonJ = $(this)
# parentJ = buttonJ.parents('tr:first')
# name = parentJ.attr('data-name')
# isPublic = parseInt(parentJ.attr('data-public'))
# pk = parentJ.attr('data-pk')
# updateCity = (data)->
# callback = (result)->
# modal = Modal.getModalByTitle('Modify city')
# modal.hide()
# if not R.loader.checkError(result) then return
# city = JSON.parse(result.city)
# R.alertManager.alert "City successfully renamed to: " + city.name, "info"
# modalBodyJ = Modal.getModalByTitle('Open city').modalBodyJ
# rowJ = modalBodyJ.find('[data-pk="' + city._id.$oid + '"]')
# rowJ.attr('data-name', city.name)
# rowJ.attr('data-public', Number(city.public or 0))
# rowJ.find('.name').text(city.name)
# rowJ.find('.public').text(if city.public then 'Public' else 'Private')
# return
# # Dajaxice.draw.updateCity(callback, pk: data.data.pk, name: data.name, public: data.public )
# $.ajax( method: "POST", url: "ajaxCall/", data: data: JSON.stringify { function: 'updateCity', args: pk: data.data.pk, name: data.name, public: data.public } ).done(callback))
# return
# modal = Modal.createModal(title: 'Modify city', submit: updateCity, data: { pk: pk }, postSubmit: 'load' )
# modal.addTextInput( name: 'name', label: 'Name', defaultValue: name, required: true, submitShortcut: true )
# modal.addCheckbox( name: 'public', label: 'Public', helpMessage: "Public cities will be accessible by anyone.", defaultValue: isPublic )
# modal.show()
# # event.stopPropagation()
# # buttonJ = $(this)
# # parentJ = buttonJ.parents('tr:first')
# # parentJ.find('input.name').show()
# # parentJ.find('input.public').attr('disabled', false)
# # buttonJ.text('Ok')
# # buttonJ.off('click').click (event)->
# # event.stopPropagation()
# # buttonJ = $(this)
# # parentJ = buttonJ.parents('tr:first')
# # inputJ = parentJ.find('input.name')
# # publicJ = parentJ.find('input.public')
# # pk = parentJ.attr('data-pk')
# # newName = inputJ.val()
# # isPublic = publicJ.is(':checked')
# # callback = (result)->
# # if not R.loader.checkError(result) then return
# # city = JSON.parse(result.city)
# # R.alertManager.alert "City successfully renamed to: " + city.name, "info"
# # return
# # # Dajaxice.draw.updateCity(callback, pk: pk, name: newName, 'public': isPublic )
# # $.ajax( method: "POST", url: "ajaxCall/", data: data: JSON.stringify { function: 'updateCity', args: pk: pk, name: newName, 'public': isPublic } ).done(callback))
# # inputJ.hide()
# # publicJ.attr('disabled', true)
# # buttonJ.off('click').click(R.modifyCity)
# # return
# return
# R.loadCities = (result)->
# if not R.loader.checkError(result) then return
# userCities = JSON.parse(result.userCities)
# publicCities = JSON.parse(result.publicCities)
# modal = Modal.getModalByTitle('Open city')
# modal.removeProgressBar()
# modalBodyJ = modal.modalBodyJ
# for citiesList, i in [userCities, publicCities]
# if i==0 and userCities.length>0
# titleJ = $('<h3>').text('Your cities')
# modalBodyJ.append(titleJ)
# # tdJ.append(titleJ)
# else
# titleJ = $('<h3>').text('Public cities')
# modalBodyJ.append(titleJ)
# # tdJ.append(titleJ)
# tableJ = $('<table>').addClass("table table-hover").css( width: "100%" )
# tbodyJ = $('<tbody>')
# for city in citiesList
# rowJ = $("<tr>").attr('data-name', city.name).attr('data-owner', city.owner).attr('data-pk', city._id.$oid).attr('data-public', Number(city.public or 0))
# td1J = $('<td>')
# td2J = $('<td>')
# td3J = $('<td>')
# # rowJ.css( display: 'inline-block' )
# nameJ = $("<span class='name'>").text(city.name)
# # date = new Date(city.date)
# # dateJ = $("<div>").text(date.toLocaleString())
# td1J.append(nameJ)
# # rowJ.append(dateJ)
# if i==0
# publicJ = $("<span class='public'>").text(if city.public then 'Public' else 'Private')
# td2J.append(publicJ)
# modifyButtonJ = $('<button class="btn btn-default">').text('Modify')
# modifyButtonJ.click(R.modifyCity)
# deleteButtonJ = $('<button class="btn btn-default">').text('Delete')
# deleteButtonJ.click (event)->
# event.stopPropagation()
# name = $(this).parents('tr:first').attr('data-name')
# # Dajaxice.draw.deleteCity(R.loader.checkError, name: name)
# $.ajax( method: "POST", url: "ajaxCall/", data: data: JSON.stringify { function: 'deleteCity', args: name: name } ).done(R.loader.checkError))
# return
# td3J.append(modifyButtonJ)
# td3J.append(deleteButtonJ)
# loadButtonJ = $('<button class="btn btn-primary">').text('Load')
# loadButtonJ.click ()->
# name = $(this).parents('tr:first').attr('data-name')
# owner = $(this).parents('tr:first').attr('data-owner')
# R.loadCity(name, owner)
# return
# td3J.append(loadButtonJ)
# rowJ.append(td1J, td2J, td3J)
# tbodyJ.append(rowJ)
# tableJ.append(tbodyJ)
# modalBodyJ.append(tableJ)
# return
return CityManager
|
[
{
"context": "Ready = ->\n connection = \n url: 'http://153.120.17.226/xmlrpc.php'\n username: 'moongift'\n password",
"end": 134,
"score": 0.9147657752037048,
"start": 121,
"tag": "IP_ADDRESS",
"value": "53.120.17.226"
},
{
"context": "'http://153.120.17.226/xmlrpc.ph... | javascripts/app.coffee | moongift/xml-rpc | 0 | document.addEventListener("deviceready", onDeviceReady, false)
onDeviceReady = ->
connection =
url: 'http://153.120.17.226/xmlrpc.php'
username: 'moongift'
password: 'Lq2l2Eic14De'
wp = new WordPress(connection.url, connection.username, connection.password)
$("#file").on "change", (e) ->
file = e.target.files[0]
fr = new FileReader()
fr.onload = (e) ->
$("#photo").val(e.target.result)
fr.readAsDataURL(file)
$("form").on "submit", (e) ->
e.preventDefault()
form = $(e.target)
console.log(form.find("#photo").val())
console.log(atob(form.find("#photo").val().split(',')[1]))
console.log(new Base64(atob(form.find("#photo").val().split(',')[1])))
base64 = new Base64(atob(form.find("#photo").val().split(',')[1]));
file_name = $("#file")[0].value.replace(/.*\\/, "")
file_hash =
name: file_name
bits: base64
type: 'image/png'
file = wp.uploadFile(1, file_hash)
url = file.url.concat()
content = "<img src='#{url}' /><br />#{form.find('textarea').val()}"
post = wp.newPost 1,
post_title: form.find("input[name='title']").val()
post_content: content.replace(/&/g, "&").replace(/"/g, """).replace(/</g, "<").replace(/>/g, ">");
post_status: 'publish'
alert("投稿完了しました")
onDeviceReady() | 177596 | document.addEventListener("deviceready", onDeviceReady, false)
onDeviceReady = ->
connection =
url: 'http://1172.16.58.3/xmlrpc.php'
username: 'moongift'
password: '<PASSWORD>'
wp = new WordPress(connection.url, connection.username, connection.password)
$("#file").on "change", (e) ->
file = e.target.files[0]
fr = new FileReader()
fr.onload = (e) ->
$("#photo").val(e.target.result)
fr.readAsDataURL(file)
$("form").on "submit", (e) ->
e.preventDefault()
form = $(e.target)
console.log(form.find("#photo").val())
console.log(atob(form.find("#photo").val().split(',')[1]))
console.log(new Base64(atob(form.find("#photo").val().split(',')[1])))
base64 = new Base64(atob(form.find("#photo").val().split(',')[1]));
file_name = $("#file")[0].value.replace(/.*\\/, "")
file_hash =
name: file_name
bits: base64
type: 'image/png'
file = wp.uploadFile(1, file_hash)
url = file.url.concat()
content = "<img src='#{url}' /><br />#{form.find('textarea').val()}"
post = wp.newPost 1,
post_title: form.find("input[name='title']").val()
post_content: content.replace(/&/g, "&").replace(/"/g, """).replace(/</g, "<").replace(/>/g, ">");
post_status: 'publish'
alert("投稿完了しました")
onDeviceReady() | true | document.addEventListener("deviceready", onDeviceReady, false)
onDeviceReady = ->
connection =
url: 'http://1PI:IP_ADDRESS:172.16.58.3END_PI/xmlrpc.php'
username: 'moongift'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
wp = new WordPress(connection.url, connection.username, connection.password)
$("#file").on "change", (e) ->
file = e.target.files[0]
fr = new FileReader()
fr.onload = (e) ->
$("#photo").val(e.target.result)
fr.readAsDataURL(file)
$("form").on "submit", (e) ->
e.preventDefault()
form = $(e.target)
console.log(form.find("#photo").val())
console.log(atob(form.find("#photo").val().split(',')[1]))
console.log(new Base64(atob(form.find("#photo").val().split(',')[1])))
base64 = new Base64(atob(form.find("#photo").val().split(',')[1]));
file_name = $("#file")[0].value.replace(/.*\\/, "")
file_hash =
name: file_name
bits: base64
type: 'image/png'
file = wp.uploadFile(1, file_hash)
url = file.url.concat()
content = "<img src='#{url}' /><br />#{form.find('textarea').val()}"
post = wp.newPost 1,
post_title: form.find("input[name='title']").val()
post_content: content.replace(/&/g, "&").replace(/"/g, """).replace(/</g, "<").replace(/>/g, ">");
post_status: 'publish'
alert("投稿完了しました")
onDeviceReady() |
[
{
"context": "piSecret\n base = search + apiSecret\n token = CryptoJS.MD5(base)\n url = '/graph/' + apiKey + '/' + token ",
"end": 6232,
"score": 0.7025634050369263,
"start": 6220,
"tag": "KEY",
"value": "CryptoJS.MD5"
}
] | examples/demo.coffee | imgflo/imgflo-server | 29 | hasClassName = (el, name) ->
new RegExp('(?:^|\\s+)' + name + '(?:\\s+|$)').test el.className
addClassName = (el, name) ->
if !hasClassName(el, name)
el.className = if el.className then [
el.className
name
].join(' ') else name
return
removeClassName = (el, name) ->
if hasClassName(el, name)
c = @className
el.className = c.replace(new RegExp('(?:^|\\s+)' + name + '(?:\\s+|$)', 'g'), '')
return
### TODO:
# - make input picking a dialog "paste URL here"
# - move execute button down, change to spinner when processing (font-awesome?)
# - move graph details to below the graph selector
#
# - Don't show auth input fields all the time.
# If authed, checkmark OK. Not authed, allow to drop down to enter.
# - Allow to register new API keys "apps"
# - Allow to copy API keys/secret pair out.
# - Link out to API docs
#
# - add selected/deselected indicator to graph list
# - add invalidated/working/completed indicator on processed image
# - add API/authentication status element to header, shows when authed correctly
# -
# - make images use up available space vertically, centered
#
# Maybe
# - make HEAD request to check if image is cached,
# and then show without pressing execute?
#
# Later:
#
# - allow to upload image
# - allow to take picture with webcam
# - add progress bar for request processing.
# - add persisted history, with prev/next buttons in pictureSection
###
getDemoData = (callback) ->
req = new XMLHttpRequest
req.onreadystatechange = ->
if req.readyState == 4
if req.status == 200
d = JSON.parse(req.responseText)
return callback(null, d)
else
e = new Error(req.status)
return callback(e, null)
return
req.open 'GET', '/graphs', true
req.send()
return
getVersionInfo = (callback) ->
req = new XMLHttpRequest
req.onreadystatechange = ->
if req.readyState == 4
if req.status == 200
d = JSON.parse(req.responseText)
return callback(null, d)
else
e = new Error(req.status)
return callback(e, null)
return
req.open 'GET', '/version', true
req.send()
return
createGraphProperties = (container, name, graph, values) ->
if typeof graph.inports == 'undefined'
return null
inports = Object.keys(graph.inports)
inports.forEach (name) ->
port = graph.inports[name]
console.log 'p', name, port.metadata
value = values[name]
if name == 'input'
return
portInfo = document.createElement('li')
portInfo.className = 'line'
portName = document.createElement('label')
portName.className = 'portLabel'
portInput = document.createElement('input')
portName.innerHTML = '<span>' + name + '</span>'
# set an appropriate type
# TODO: set min and max, if exists. Maybe use range??
def = port.metadata?.default
type = port.metadata?.type
if type == 'int'
portInput.type = 'number'
if port.metadata.minimum? and port.metadata.maximum?
portInput.step = (port.metadata.maximum - port.metadata.minimum)/20
portInput.min = port.metadata.minimum
portInput.max = port.metadata.maximum
else
portInput.step = 1.0
else if type == 'number'
portInput.type = 'number'
if port.metadata.minimum? and port.metadata.maximum?
portInput.min = port.metadata.minimum
portInput.max = port.metadata.maximum
portInput.step = (port.metadata.maximum - port.metadata.minimum)/20
else
portInput.step = 0.25
else if type == 'enum' and port.metadata.values?
portInput = document.createElement('select')
for v in port.metadata.values
i = document.createElement('option')
i.value = v
i.innerHTML = v
if v == value
i.selected = true
else if v == def
i.selected = true
portInput.appendChild i
else if type == 'boolean'
portInput.type = 'checkbox'
portInput.value = if def then 'on' else 'off' if def?
else if type == 'color'
# TODO: also support opacity in colors. Needs to be a separate widget, 0-100% maybe.
portInput.type = 'color'
if def
def = def.substring(0, 7) if def.length == 9
portInput.value = def
else if type == 'buffer'
# Ignored
else if type
console.log 'Warking: Unknown port type', type
portInput.type = type
portInput.defaultValue = def if def?
portInput.placeholder = def.toString() if def?
portInput.name = name
portInput.className = 'portInput'
# show current value
if typeof value != 'undefined'
portInput.value = value
# show decription
description = port.metadata?.description or ""
portDescription = document.createElement('label')
portDescription.className = 'portDescription'
portDescription.innerHTML = '<span>' + description + '</span>'
portInfo.appendChild portName
portName.appendChild portInput
portInfo.appendChild portDescription
container.appendChild portInfo
return
container
createGraphList = (container, graphs, onClicked) ->
Object.keys(graphs).forEach (name) ->
if typeof graphs[name].inports != 'undefined'
graph = graphs[name]
e = document.createElement('li')
e.onclick = onClicked
displayName = name.replace('_', ' ')
e.className = 'graphEntry'
p = document.createElement('label')
p.innerHTML = displayName
e.appendChild p
img = document.createElement('img')
img.src = graph.thumbnailUrl
e.appendChild img
e.setAttribute 'data-graph-id', name
container.appendChild e
return
container
createRequestUrl = (graphname, parameters, apiKey, apiSecret, format=null) ->
formatExtension = if format then ".#{format}" else ''
hasQuery = Object.keys(parameters).length > 0
search = graphname + formatExtension + (if hasQuery then '?' else '')
for key of parameters
value = encodeURIComponent(parameters[key])
search += key + '=' + value + '&'
if hasQuery
search = search.substring(0, search.length - 1)
# strip trailing &
url = '/graph/' + search
if apiKey or apiSecret
base = search + apiSecret
token = CryptoJS.MD5(base)
url = '/graph/' + apiKey + '/' + token + '/' + search
url
getGraphProperties = (container, name, graphdef) ->
props = {}
inputs = Array.prototype.slice.call container.getElementsByTagName('input')
inputs = inputs.concat Array.prototype.slice.call container.getElementsByTagName('select')
for input in inputs
type = graphdef.inports[input.name]
if input.type == 'checkbox'
val = input.checked.toString()
props[input.name] = val if val != input.defaultValue
else if input.value?
props[input.name] = input.value if input.value != input.defaultValue
return props
parseQuery = (qstr) ->
query = {}
a = qstr.substr(1).split('&')
i = 0
while i < a.length
b = a[i].split('=')
query[decodeURIComponent(b[0])] = decodeURIComponent(b[1] or '')
i++
query
startsWith = (str, sub) ->
str.indexOf(sub) == 0
main = ->
id = (n) ->
document.getElementById n
activeGraphName = null
availableGraphs = null
processedUrl = ''
readApiInfo = ->
id('apiKey').value = localStorage['imgflo-server-api-key'] or ''
id('apiSecret').value = localStorage['imgflo-server-api-secret'] or ''
return
readApiInfo()
id('clearApiInfo').onclick = ->
localStorage['imgflo-server-api-key'] = ''
localStorage['imgflo-server-api-secret'] = ''
readApiInfo()
return
processCurrent = ->
graph = activeGraphName
props = getGraphProperties(id('graphProperties'), graph, availableGraphs[graph])
props.input = id('inputUrl').value
apiKey = id('apiKey').value
apiSecret = id('apiSecret').value
localStorage['imgflo-server-api-key'] = apiKey
localStorage['imgflo-server-api-secret'] = apiSecret
format = id('outputFormat').value
url = createRequestUrl(graph, props, apiKey, apiSecret, format)
bg = 'url("' + url + '")'
console.log 'processing:', url, bg
###
id('processedImage').onload = function() {
id('processedImage').className = "visible";
};
id('processedImage').src = u;
###
loc = window.location
processedUrl = loc.protocol + '//' + loc.host + url
id('processedImage').style.backgroundImage = bg
return
id('runButton').onclick = processCurrent
showUrl = () ->
prompt "Request URL:", processedUrl
id('processedUrl').onclick = showUrl
setInputUrl = (url) ->
console.log 'setting input', url
if !startsWith(url, 'http')
# Resolve to fully qualified URL
loc = window.location
url = loc.protocol + '//' + loc.host + '/' + url
if id('inputUrl').value != url
id('inputUrl').value = url
bg = 'url("' + url + '")'
id('originalImage').style.backgroundImage = bg
return
onInputChanged = (event) ->
url = id('inputUrl').value
setInputUrl url
return
id('inputUrl').onblur = onInputChanged
onInputChanged()
setActiveGraph = (name, properties) ->
if typeof availableGraphs[name] == 'undefined'
return false
activeGraphName = name
container = id('graphProperties')
len = container.children.length
#container.innerHTML = '';
i = 0
while i < len
container.removeChild container.children[0]
i++
createGraphProperties container, name, availableGraphs[name], properties
true
onGraphClicked = (event) ->
name = event.currentTarget.getAttribute('data-graph-id')
console.log 'onGraphClicked', name
setActiveGraph name, {}
return
getDemoData (err, demo) ->
if err
throw err
availableGraphs = demo.graphs
Object.keys(availableGraphs).forEach (name) ->
graph = availableGraphs[name]
props =
width: 150
input: id('inputUrl').value
apiKey = id('apiKey').value
apiSecret = id('apiSecret').value
localStorage['imgflo-server-api-key'] = apiKey
localStorage['imgflo-server-api-secret'] = apiSecret
graph.thumbnailUrl = createRequestUrl(name, props, apiKey, apiSecret)
return
if startsWith(window.location.pathname, '/debug')
# Set the UI widgets state based on what is in the URL
params = parseQuery(window.location.search)
parts = window.location.pathname.split('/')
graph = parts[3]
if parts.length >= 6
graph = parts[5]
setInputUrl params.input
setActiveGraph graph, params
else
setActiveGraph 'desaturate', {}
processCurrent()
createGraphList id('graphList'), demo.graphs, onGraphClicked
return
getVersionInfo (err, res) ->
version = 'Unknown'
if !err and res.server
version = res.server.toString()
id('version').innerHTML = 'imgflo-server: ' + version
return
return
main()
| 168055 | hasClassName = (el, name) ->
new RegExp('(?:^|\\s+)' + name + '(?:\\s+|$)').test el.className
addClassName = (el, name) ->
if !hasClassName(el, name)
el.className = if el.className then [
el.className
name
].join(' ') else name
return
removeClassName = (el, name) ->
if hasClassName(el, name)
c = @className
el.className = c.replace(new RegExp('(?:^|\\s+)' + name + '(?:\\s+|$)', 'g'), '')
return
### TODO:
# - make input picking a dialog "paste URL here"
# - move execute button down, change to spinner when processing (font-awesome?)
# - move graph details to below the graph selector
#
# - Don't show auth input fields all the time.
# If authed, checkmark OK. Not authed, allow to drop down to enter.
# - Allow to register new API keys "apps"
# - Allow to copy API keys/secret pair out.
# - Link out to API docs
#
# - add selected/deselected indicator to graph list
# - add invalidated/working/completed indicator on processed image
# - add API/authentication status element to header, shows when authed correctly
# -
# - make images use up available space vertically, centered
#
# Maybe
# - make HEAD request to check if image is cached,
# and then show without pressing execute?
#
# Later:
#
# - allow to upload image
# - allow to take picture with webcam
# - add progress bar for request processing.
# - add persisted history, with prev/next buttons in pictureSection
###
getDemoData = (callback) ->
req = new XMLHttpRequest
req.onreadystatechange = ->
if req.readyState == 4
if req.status == 200
d = JSON.parse(req.responseText)
return callback(null, d)
else
e = new Error(req.status)
return callback(e, null)
return
req.open 'GET', '/graphs', true
req.send()
return
getVersionInfo = (callback) ->
req = new XMLHttpRequest
req.onreadystatechange = ->
if req.readyState == 4
if req.status == 200
d = JSON.parse(req.responseText)
return callback(null, d)
else
e = new Error(req.status)
return callback(e, null)
return
req.open 'GET', '/version', true
req.send()
return
createGraphProperties = (container, name, graph, values) ->
if typeof graph.inports == 'undefined'
return null
inports = Object.keys(graph.inports)
inports.forEach (name) ->
port = graph.inports[name]
console.log 'p', name, port.metadata
value = values[name]
if name == 'input'
return
portInfo = document.createElement('li')
portInfo.className = 'line'
portName = document.createElement('label')
portName.className = 'portLabel'
portInput = document.createElement('input')
portName.innerHTML = '<span>' + name + '</span>'
# set an appropriate type
# TODO: set min and max, if exists. Maybe use range??
def = port.metadata?.default
type = port.metadata?.type
if type == 'int'
portInput.type = 'number'
if port.metadata.minimum? and port.metadata.maximum?
portInput.step = (port.metadata.maximum - port.metadata.minimum)/20
portInput.min = port.metadata.minimum
portInput.max = port.metadata.maximum
else
portInput.step = 1.0
else if type == 'number'
portInput.type = 'number'
if port.metadata.minimum? and port.metadata.maximum?
portInput.min = port.metadata.minimum
portInput.max = port.metadata.maximum
portInput.step = (port.metadata.maximum - port.metadata.minimum)/20
else
portInput.step = 0.25
else if type == 'enum' and port.metadata.values?
portInput = document.createElement('select')
for v in port.metadata.values
i = document.createElement('option')
i.value = v
i.innerHTML = v
if v == value
i.selected = true
else if v == def
i.selected = true
portInput.appendChild i
else if type == 'boolean'
portInput.type = 'checkbox'
portInput.value = if def then 'on' else 'off' if def?
else if type == 'color'
# TODO: also support opacity in colors. Needs to be a separate widget, 0-100% maybe.
portInput.type = 'color'
if def
def = def.substring(0, 7) if def.length == 9
portInput.value = def
else if type == 'buffer'
# Ignored
else if type
console.log 'Warking: Unknown port type', type
portInput.type = type
portInput.defaultValue = def if def?
portInput.placeholder = def.toString() if def?
portInput.name = name
portInput.className = 'portInput'
# show current value
if typeof value != 'undefined'
portInput.value = value
# show decription
description = port.metadata?.description or ""
portDescription = document.createElement('label')
portDescription.className = 'portDescription'
portDescription.innerHTML = '<span>' + description + '</span>'
portInfo.appendChild portName
portName.appendChild portInput
portInfo.appendChild portDescription
container.appendChild portInfo
return
container
createGraphList = (container, graphs, onClicked) ->
Object.keys(graphs).forEach (name) ->
if typeof graphs[name].inports != 'undefined'
graph = graphs[name]
e = document.createElement('li')
e.onclick = onClicked
displayName = name.replace('_', ' ')
e.className = 'graphEntry'
p = document.createElement('label')
p.innerHTML = displayName
e.appendChild p
img = document.createElement('img')
img.src = graph.thumbnailUrl
e.appendChild img
e.setAttribute 'data-graph-id', name
container.appendChild e
return
container
createRequestUrl = (graphname, parameters, apiKey, apiSecret, format=null) ->
formatExtension = if format then ".#{format}" else ''
hasQuery = Object.keys(parameters).length > 0
search = graphname + formatExtension + (if hasQuery then '?' else '')
for key of parameters
value = encodeURIComponent(parameters[key])
search += key + '=' + value + '&'
if hasQuery
search = search.substring(0, search.length - 1)
# strip trailing &
url = '/graph/' + search
if apiKey or apiSecret
base = search + apiSecret
token = <KEY>(base)
url = '/graph/' + apiKey + '/' + token + '/' + search
url
getGraphProperties = (container, name, graphdef) ->
props = {}
inputs = Array.prototype.slice.call container.getElementsByTagName('input')
inputs = inputs.concat Array.prototype.slice.call container.getElementsByTagName('select')
for input in inputs
type = graphdef.inports[input.name]
if input.type == 'checkbox'
val = input.checked.toString()
props[input.name] = val if val != input.defaultValue
else if input.value?
props[input.name] = input.value if input.value != input.defaultValue
return props
parseQuery = (qstr) ->
query = {}
a = qstr.substr(1).split('&')
i = 0
while i < a.length
b = a[i].split('=')
query[decodeURIComponent(b[0])] = decodeURIComponent(b[1] or '')
i++
query
startsWith = (str, sub) ->
str.indexOf(sub) == 0
main = ->
id = (n) ->
document.getElementById n
activeGraphName = null
availableGraphs = null
processedUrl = ''
readApiInfo = ->
id('apiKey').value = localStorage['imgflo-server-api-key'] or ''
id('apiSecret').value = localStorage['imgflo-server-api-secret'] or ''
return
readApiInfo()
id('clearApiInfo').onclick = ->
localStorage['imgflo-server-api-key'] = ''
localStorage['imgflo-server-api-secret'] = ''
readApiInfo()
return
processCurrent = ->
graph = activeGraphName
props = getGraphProperties(id('graphProperties'), graph, availableGraphs[graph])
props.input = id('inputUrl').value
apiKey = id('apiKey').value
apiSecret = id('apiSecret').value
localStorage['imgflo-server-api-key'] = apiKey
localStorage['imgflo-server-api-secret'] = apiSecret
format = id('outputFormat').value
url = createRequestUrl(graph, props, apiKey, apiSecret, format)
bg = 'url("' + url + '")'
console.log 'processing:', url, bg
###
id('processedImage').onload = function() {
id('processedImage').className = "visible";
};
id('processedImage').src = u;
###
loc = window.location
processedUrl = loc.protocol + '//' + loc.host + url
id('processedImage').style.backgroundImage = bg
return
id('runButton').onclick = processCurrent
showUrl = () ->
prompt "Request URL:", processedUrl
id('processedUrl').onclick = showUrl
setInputUrl = (url) ->
console.log 'setting input', url
if !startsWith(url, 'http')
# Resolve to fully qualified URL
loc = window.location
url = loc.protocol + '//' + loc.host + '/' + url
if id('inputUrl').value != url
id('inputUrl').value = url
bg = 'url("' + url + '")'
id('originalImage').style.backgroundImage = bg
return
onInputChanged = (event) ->
url = id('inputUrl').value
setInputUrl url
return
id('inputUrl').onblur = onInputChanged
onInputChanged()
setActiveGraph = (name, properties) ->
if typeof availableGraphs[name] == 'undefined'
return false
activeGraphName = name
container = id('graphProperties')
len = container.children.length
#container.innerHTML = '';
i = 0
while i < len
container.removeChild container.children[0]
i++
createGraphProperties container, name, availableGraphs[name], properties
true
onGraphClicked = (event) ->
name = event.currentTarget.getAttribute('data-graph-id')
console.log 'onGraphClicked', name
setActiveGraph name, {}
return
getDemoData (err, demo) ->
if err
throw err
availableGraphs = demo.graphs
Object.keys(availableGraphs).forEach (name) ->
graph = availableGraphs[name]
props =
width: 150
input: id('inputUrl').value
apiKey = id('apiKey').value
apiSecret = id('apiSecret').value
localStorage['imgflo-server-api-key'] = apiKey
localStorage['imgflo-server-api-secret'] = apiSecret
graph.thumbnailUrl = createRequestUrl(name, props, apiKey, apiSecret)
return
if startsWith(window.location.pathname, '/debug')
# Set the UI widgets state based on what is in the URL
params = parseQuery(window.location.search)
parts = window.location.pathname.split('/')
graph = parts[3]
if parts.length >= 6
graph = parts[5]
setInputUrl params.input
setActiveGraph graph, params
else
setActiveGraph 'desaturate', {}
processCurrent()
createGraphList id('graphList'), demo.graphs, onGraphClicked
return
getVersionInfo (err, res) ->
version = 'Unknown'
if !err and res.server
version = res.server.toString()
id('version').innerHTML = 'imgflo-server: ' + version
return
return
main()
| true | hasClassName = (el, name) ->
new RegExp('(?:^|\\s+)' + name + '(?:\\s+|$)').test el.className
addClassName = (el, name) ->
if !hasClassName(el, name)
el.className = if el.className then [
el.className
name
].join(' ') else name
return
removeClassName = (el, name) ->
if hasClassName(el, name)
c = @className
el.className = c.replace(new RegExp('(?:^|\\s+)' + name + '(?:\\s+|$)', 'g'), '')
return
### TODO:
# - make input picking a dialog "paste URL here"
# - move execute button down, change to spinner when processing (font-awesome?)
# - move graph details to below the graph selector
#
# - Don't show auth input fields all the time.
# If authed, checkmark OK. Not authed, allow to drop down to enter.
# - Allow to register new API keys "apps"
# - Allow to copy API keys/secret pair out.
# - Link out to API docs
#
# - add selected/deselected indicator to graph list
# - add invalidated/working/completed indicator on processed image
# - add API/authentication status element to header, shows when authed correctly
# -
# - make images use up available space vertically, centered
#
# Maybe
# - make HEAD request to check if image is cached,
# and then show without pressing execute?
#
# Later:
#
# - allow to upload image
# - allow to take picture with webcam
# - add progress bar for request processing.
# - add persisted history, with prev/next buttons in pictureSection
###
getDemoData = (callback) ->
req = new XMLHttpRequest
req.onreadystatechange = ->
if req.readyState == 4
if req.status == 200
d = JSON.parse(req.responseText)
return callback(null, d)
else
e = new Error(req.status)
return callback(e, null)
return
req.open 'GET', '/graphs', true
req.send()
return
getVersionInfo = (callback) ->
req = new XMLHttpRequest
req.onreadystatechange = ->
if req.readyState == 4
if req.status == 200
d = JSON.parse(req.responseText)
return callback(null, d)
else
e = new Error(req.status)
return callback(e, null)
return
req.open 'GET', '/version', true
req.send()
return
createGraphProperties = (container, name, graph, values) ->
if typeof graph.inports == 'undefined'
return null
inports = Object.keys(graph.inports)
inports.forEach (name) ->
port = graph.inports[name]
console.log 'p', name, port.metadata
value = values[name]
if name == 'input'
return
portInfo = document.createElement('li')
portInfo.className = 'line'
portName = document.createElement('label')
portName.className = 'portLabel'
portInput = document.createElement('input')
portName.innerHTML = '<span>' + name + '</span>'
# set an appropriate type
# TODO: set min and max, if exists. Maybe use range??
def = port.metadata?.default
type = port.metadata?.type
if type == 'int'
portInput.type = 'number'
if port.metadata.minimum? and port.metadata.maximum?
portInput.step = (port.metadata.maximum - port.metadata.minimum)/20
portInput.min = port.metadata.minimum
portInput.max = port.metadata.maximum
else
portInput.step = 1.0
else if type == 'number'
portInput.type = 'number'
if port.metadata.minimum? and port.metadata.maximum?
portInput.min = port.metadata.minimum
portInput.max = port.metadata.maximum
portInput.step = (port.metadata.maximum - port.metadata.minimum)/20
else
portInput.step = 0.25
else if type == 'enum' and port.metadata.values?
portInput = document.createElement('select')
for v in port.metadata.values
i = document.createElement('option')
i.value = v
i.innerHTML = v
if v == value
i.selected = true
else if v == def
i.selected = true
portInput.appendChild i
else if type == 'boolean'
portInput.type = 'checkbox'
portInput.value = if def then 'on' else 'off' if def?
else if type == 'color'
# TODO: also support opacity in colors. Needs to be a separate widget, 0-100% maybe.
portInput.type = 'color'
if def
def = def.substring(0, 7) if def.length == 9
portInput.value = def
else if type == 'buffer'
# Ignored
else if type
console.log 'Warking: Unknown port type', type
portInput.type = type
portInput.defaultValue = def if def?
portInput.placeholder = def.toString() if def?
portInput.name = name
portInput.className = 'portInput'
# show current value
if typeof value != 'undefined'
portInput.value = value
# show decription
description = port.metadata?.description or ""
portDescription = document.createElement('label')
portDescription.className = 'portDescription'
portDescription.innerHTML = '<span>' + description + '</span>'
portInfo.appendChild portName
portName.appendChild portInput
portInfo.appendChild portDescription
container.appendChild portInfo
return
container
createGraphList = (container, graphs, onClicked) ->
Object.keys(graphs).forEach (name) ->
if typeof graphs[name].inports != 'undefined'
graph = graphs[name]
e = document.createElement('li')
e.onclick = onClicked
displayName = name.replace('_', ' ')
e.className = 'graphEntry'
p = document.createElement('label')
p.innerHTML = displayName
e.appendChild p
img = document.createElement('img')
img.src = graph.thumbnailUrl
e.appendChild img
e.setAttribute 'data-graph-id', name
container.appendChild e
return
container
createRequestUrl = (graphname, parameters, apiKey, apiSecret, format=null) ->
formatExtension = if format then ".#{format}" else ''
hasQuery = Object.keys(parameters).length > 0
search = graphname + formatExtension + (if hasQuery then '?' else '')
for key of parameters
value = encodeURIComponent(parameters[key])
search += key + '=' + value + '&'
if hasQuery
search = search.substring(0, search.length - 1)
# strip trailing &
url = '/graph/' + search
if apiKey or apiSecret
base = search + apiSecret
token = PI:KEY:<KEY>END_PI(base)
url = '/graph/' + apiKey + '/' + token + '/' + search
url
getGraphProperties = (container, name, graphdef) ->
props = {}
inputs = Array.prototype.slice.call container.getElementsByTagName('input')
inputs = inputs.concat Array.prototype.slice.call container.getElementsByTagName('select')
for input in inputs
type = graphdef.inports[input.name]
if input.type == 'checkbox'
val = input.checked.toString()
props[input.name] = val if val != input.defaultValue
else if input.value?
props[input.name] = input.value if input.value != input.defaultValue
return props
parseQuery = (qstr) ->
query = {}
a = qstr.substr(1).split('&')
i = 0
while i < a.length
b = a[i].split('=')
query[decodeURIComponent(b[0])] = decodeURIComponent(b[1] or '')
i++
query
startsWith = (str, sub) ->
str.indexOf(sub) == 0
main = ->
id = (n) ->
document.getElementById n
activeGraphName = null
availableGraphs = null
processedUrl = ''
readApiInfo = ->
id('apiKey').value = localStorage['imgflo-server-api-key'] or ''
id('apiSecret').value = localStorage['imgflo-server-api-secret'] or ''
return
readApiInfo()
id('clearApiInfo').onclick = ->
localStorage['imgflo-server-api-key'] = ''
localStorage['imgflo-server-api-secret'] = ''
readApiInfo()
return
processCurrent = ->
graph = activeGraphName
props = getGraphProperties(id('graphProperties'), graph, availableGraphs[graph])
props.input = id('inputUrl').value
apiKey = id('apiKey').value
apiSecret = id('apiSecret').value
localStorage['imgflo-server-api-key'] = apiKey
localStorage['imgflo-server-api-secret'] = apiSecret
format = id('outputFormat').value
url = createRequestUrl(graph, props, apiKey, apiSecret, format)
bg = 'url("' + url + '")'
console.log 'processing:', url, bg
###
id('processedImage').onload = function() {
id('processedImage').className = "visible";
};
id('processedImage').src = u;
###
loc = window.location
processedUrl = loc.protocol + '//' + loc.host + url
id('processedImage').style.backgroundImage = bg
return
id('runButton').onclick = processCurrent
showUrl = () ->
prompt "Request URL:", processedUrl
id('processedUrl').onclick = showUrl
setInputUrl = (url) ->
console.log 'setting input', url
if !startsWith(url, 'http')
# Resolve to fully qualified URL
loc = window.location
url = loc.protocol + '//' + loc.host + '/' + url
if id('inputUrl').value != url
id('inputUrl').value = url
bg = 'url("' + url + '")'
id('originalImage').style.backgroundImage = bg
return
onInputChanged = (event) ->
url = id('inputUrl').value
setInputUrl url
return
id('inputUrl').onblur = onInputChanged
onInputChanged()
setActiveGraph = (name, properties) ->
if typeof availableGraphs[name] == 'undefined'
return false
activeGraphName = name
container = id('graphProperties')
len = container.children.length
#container.innerHTML = '';
i = 0
while i < len
container.removeChild container.children[0]
i++
createGraphProperties container, name, availableGraphs[name], properties
true
onGraphClicked = (event) ->
name = event.currentTarget.getAttribute('data-graph-id')
console.log 'onGraphClicked', name
setActiveGraph name, {}
return
getDemoData (err, demo) ->
if err
throw err
availableGraphs = demo.graphs
Object.keys(availableGraphs).forEach (name) ->
graph = availableGraphs[name]
props =
width: 150
input: id('inputUrl').value
apiKey = id('apiKey').value
apiSecret = id('apiSecret').value
localStorage['imgflo-server-api-key'] = apiKey
localStorage['imgflo-server-api-secret'] = apiSecret
graph.thumbnailUrl = createRequestUrl(name, props, apiKey, apiSecret)
return
if startsWith(window.location.pathname, '/debug')
# Set the UI widgets state based on what is in the URL
params = parseQuery(window.location.search)
parts = window.location.pathname.split('/')
graph = parts[3]
if parts.length >= 6
graph = parts[5]
setInputUrl params.input
setActiveGraph graph, params
else
setActiveGraph 'desaturate', {}
processCurrent()
createGraphList id('graphList'), demo.graphs, onGraphClicked
return
getVersionInfo (err, res) ->
version = 'Unknown'
if !err and res.server
version = res.server.toString()
id('version').innerHTML = 'imgflo-server: ' + version
return
return
main()
|
[
{
"context": " t.find('#mail').value\n password: t.find('#pw').value\n }, (err) -> if err then errCallback",
"end": 7347,
"score": 0.778483510017395,
"start": 7345,
"tag": "PASSWORD",
"value": "pw"
}
] | client/client.coffee | fazo96/markcloud | 0 | docs = new Meteor.Collection 'docs'
amIValid = ->
return no unless Meteor.user()
return yes if !Meteor.user().emails?
return yes for mail in Meteor.user().emails when mail.verified is yes; no
UI.registerHelper 'mail', ->
if Meteor.user().emails then Meteor.user().emails[0].address
UI.registerHelper 'amIValid', amIValid
Router.configure
layoutTemplate: 'layout'
loadingTemplate: 'loading'
docController = RouteController.extend
template: 'doc'
layoutTemplate: 'docLayout'
waitOn: -> Meteor.subscribe 'doc', @params._id
data: -> docs.findOne @params._id
action: ->
if @ready()
if @data()? then @render()
else @render '404'
else @render 'loading'
loggedOutController = RouteController.extend
onBeforeAction: ->
if Meteor.user() then Router.go 'profile', user: Meteor.user().username
@next()
action: ->
@render()
if Meteor.loggingIn() then @render 'spinner', to: 'outside'
loggedInController = RouteController.extend
action: -> if !Meteor.user() then @render '404' else @render()
Router.route '/',
name: 'home'
action: ->
if !@ready() then @render 'spinner', to: 'outside'
@render('home')
Router.route '/d/:_id',
name: 'doc'
controller: docController
Router.route '/@:user/:_id',
name: 'userDoc'
controller: docController
Router.route '/src/:_id',
name: 'src'
controller: docController
Router.route '/verify/:token?',
name: 'verify'
template: 'loading'
onBeforeAction: ->
Accounts.verifyEmail @params.token, (err) ->
if err then errCallback err
else Router.go 'profile', user: Meteor.user().username
@next()
Router.route '/edit/:_id',
name: 'edit'
template: 'editor'
controller: loggedInController
waitOn: -> Meteor.subscribe 'doc', @params._id
data: -> docs.findOne @params._id
Router.route '/@:user',
name: 'profile'
waitOn: ->
[Meteor.subscribe('docs', @params.user),
Meteor.subscribe('user', @params.user)]
data: -> Meteor.users.findOne username: @params.user
action: ->
if Meteor.loggingIn() then @render 'loading'
else if @ready()
if !@data() then @render '404' else @render()
else @render 'loading'
Router.route '/new',
name: 'new'
template: 'editor'
Router.route '/signup',
name: 'signup'
controller: loggedOutController
Router.route '/login',
name: 'signin'
template: 'signin'
controller: loggedOutController
Router.route '/(.*)', name: '404'
share.notify = notify = (opt) ->
if opt.type? then type = opt.type
else type = 'error'
if opt.title? then title = opt.title
else title = if type is 'error' then 'Error' else 'Ok'
swal title, opt.msg, type
errCallback = (err) ->
return unless err
if err.reason
notify title: err.code or 'Error', msg: err.reason, type: 'error'
else notify title: 'Error', msg: err, type: 'error'
Template.magicIcon.helpers
notHome: -> Router.current().route.getName() isnt 'home'
Template.layout.helpers
showSpinner: -> Meteor.status().connected is yes
Template.home.events
'click #twitter-login': ->
if Meteor.user() then return notify msg: "You're already Logged In!"
Meteor.loginWithTwitter {}, (e) ->
if e then errCallback e
else
Meteor.subscribe 'user'
notify type: 'success', msg: 'Logged in'
Template.editor.helpers
isPublic: -> return "checked" if @public is yes
showTitleChecked: -> return "checked" unless @showTitle is no
Template.editor.events
'click #upload': (e,t) ->
if Meteor.loggingIn()
return notify
msg: "Can't upload while Logging In.\nTry again in a few seconds."
if t.find('#title').value is ''
return notify msg: 'Please insert a title.'
if t.find('#editor').value is ''
return notify msg: "Empty documents are not valid."
if @_id then docs.update @_id, $set: {
title: t.find('#title').value
text: t.find('#editor').value
showTitle: $('#show-title').is(':checked')
public: $('#make-public').is(':checked')
}, (err) =>
if err then errCallback err
else
notify type:'success', msg:'Document updated.'
Router.go 'doc', _id: @_id
else docs.insert {
title: t.find('#title').value
text: t.find('#editor').value
showTitle: $('#show-title').is(':checked')
public: $('#make-public').is(':checked')
}, (err,id) ->
if err then errCallback err
else notify type:'success', msg:'Document created successfully!'
if id then Router.go 'doc', _id: id
Template.profile.helpers
isMe: -> Meteor.user() and Meteor.user()._id is @_id
noDocs: -> docs.find(owner: @_id).count() is 0
documents: -> docs.find {owner: @_id}, sort: dateCreated: -1
Template.profile.events
'click #resend': ->
Meteor.call 'sendVerificationEmail', (e,r) ->
if e then errCallback e
else notify msg: r, type:'success'
'click #logout': -> Meteor.logout(); Router.go 'home'
'click #deleteme': -> swal {
title: 'Are you sure?'
text: 'Do you want to permanently delete all your data?'
type: 'warning'
showCancelButton: yes
confirmButtonColor: "#DD6B55"
confirmButtonText: "Yes!"
}, -> Meteor.call 'deleteMe', (e,r) ->
if e then errCallback e
else notify type: 'success', msg: 'Account deleted'
Template.doc.helpers
valid: -> @text?
source: -> Router.current().route.getName() is 'src'
rows: -> ""+@text.split('\n').length
owned: -> Meteor.user() and Meteor.user()._id is @owner
ownerName: ->
if Router.current().route.getName() is 'userDoc'
return Router.current().params.user
expirationDays: ->
if @owner then return 'never'
else return moment.unix(@dateCreated).add(7,'days').fromNow()
Template.doc.events
'click #edit-doc': -> Router.go 'edit', _id: @_id
'click #del-doc': ->
if Meteor.user()._id is @owner
swal {
title: 'Are you sure?'
text: 'This document will be deleted permanently'
type: 'warning'
showCancelButton: yes
confirmButtonColor: "#DD6B55"
confirmButtonText: "Yes!"
}, => docs.remove @_id, (err) ->
if err then errCallback err
else notify type:'success', msg:'Document removed'
'click #src-doc': ->
if Router.current().route.getName() is 'src'
Router.go 'doc', _id: @_id
else Router.go 'src', _id: @_id
Template.signin.events
'click #signin': (e,t) ->
if not t.find('#mail').value
return notify msg: 'please enter your email or username'
else if not t.find('#pw').value
return notify msg: "Please enter a password"
else
Meteor.loginWithPassword t.find('#mail').value, t.find('#pw').value,(e)->
if e then errCallback e
else notify type:'success', msg:'Welcome back!'; Router.go 'home'
Template.signup.events
'click #signup': (e,t) ->
if not t.find('#mail').value
return notify msg: 'please enter your email'
if not t.find('#name').value
return notify msg: 'please enter your user name'
else if not t.find('#pw').value
return notify msg: "Please enter a password"
else if t.find('#pw').value isnt t.find('#rpw').value
return notify msg: "The passwords don't match"
else # Sending actual registration request
Accounts.createUser {
username: t.find('#name').value
email: t.find('#mail').value
password: t.find('#pw').value
}, (err) -> if err then errCallback err
else notify type: 'success', msg: 'check your email'
| 16427 | docs = new Meteor.Collection 'docs'
amIValid = ->
return no unless Meteor.user()
return yes if !Meteor.user().emails?
return yes for mail in Meteor.user().emails when mail.verified is yes; no
UI.registerHelper 'mail', ->
if Meteor.user().emails then Meteor.user().emails[0].address
UI.registerHelper 'amIValid', amIValid
Router.configure
layoutTemplate: 'layout'
loadingTemplate: 'loading'
docController = RouteController.extend
template: 'doc'
layoutTemplate: 'docLayout'
waitOn: -> Meteor.subscribe 'doc', @params._id
data: -> docs.findOne @params._id
action: ->
if @ready()
if @data()? then @render()
else @render '404'
else @render 'loading'
loggedOutController = RouteController.extend
onBeforeAction: ->
if Meteor.user() then Router.go 'profile', user: Meteor.user().username
@next()
action: ->
@render()
if Meteor.loggingIn() then @render 'spinner', to: 'outside'
loggedInController = RouteController.extend
action: -> if !Meteor.user() then @render '404' else @render()
Router.route '/',
name: 'home'
action: ->
if !@ready() then @render 'spinner', to: 'outside'
@render('home')
Router.route '/d/:_id',
name: 'doc'
controller: docController
Router.route '/@:user/:_id',
name: 'userDoc'
controller: docController
Router.route '/src/:_id',
name: 'src'
controller: docController
Router.route '/verify/:token?',
name: 'verify'
template: 'loading'
onBeforeAction: ->
Accounts.verifyEmail @params.token, (err) ->
if err then errCallback err
else Router.go 'profile', user: Meteor.user().username
@next()
Router.route '/edit/:_id',
name: 'edit'
template: 'editor'
controller: loggedInController
waitOn: -> Meteor.subscribe 'doc', @params._id
data: -> docs.findOne @params._id
Router.route '/@:user',
name: 'profile'
waitOn: ->
[Meteor.subscribe('docs', @params.user),
Meteor.subscribe('user', @params.user)]
data: -> Meteor.users.findOne username: @params.user
action: ->
if Meteor.loggingIn() then @render 'loading'
else if @ready()
if !@data() then @render '404' else @render()
else @render 'loading'
Router.route '/new',
name: 'new'
template: 'editor'
Router.route '/signup',
name: 'signup'
controller: loggedOutController
Router.route '/login',
name: 'signin'
template: 'signin'
controller: loggedOutController
Router.route '/(.*)', name: '404'
share.notify = notify = (opt) ->
if opt.type? then type = opt.type
else type = 'error'
if opt.title? then title = opt.title
else title = if type is 'error' then 'Error' else 'Ok'
swal title, opt.msg, type
errCallback = (err) ->
return unless err
if err.reason
notify title: err.code or 'Error', msg: err.reason, type: 'error'
else notify title: 'Error', msg: err, type: 'error'
Template.magicIcon.helpers
notHome: -> Router.current().route.getName() isnt 'home'
Template.layout.helpers
showSpinner: -> Meteor.status().connected is yes
Template.home.events
'click #twitter-login': ->
if Meteor.user() then return notify msg: "You're already Logged In!"
Meteor.loginWithTwitter {}, (e) ->
if e then errCallback e
else
Meteor.subscribe 'user'
notify type: 'success', msg: 'Logged in'
Template.editor.helpers
isPublic: -> return "checked" if @public is yes
showTitleChecked: -> return "checked" unless @showTitle is no
Template.editor.events
'click #upload': (e,t) ->
if Meteor.loggingIn()
return notify
msg: "Can't upload while Logging In.\nTry again in a few seconds."
if t.find('#title').value is ''
return notify msg: 'Please insert a title.'
if t.find('#editor').value is ''
return notify msg: "Empty documents are not valid."
if @_id then docs.update @_id, $set: {
title: t.find('#title').value
text: t.find('#editor').value
showTitle: $('#show-title').is(':checked')
public: $('#make-public').is(':checked')
}, (err) =>
if err then errCallback err
else
notify type:'success', msg:'Document updated.'
Router.go 'doc', _id: @_id
else docs.insert {
title: t.find('#title').value
text: t.find('#editor').value
showTitle: $('#show-title').is(':checked')
public: $('#make-public').is(':checked')
}, (err,id) ->
if err then errCallback err
else notify type:'success', msg:'Document created successfully!'
if id then Router.go 'doc', _id: id
Template.profile.helpers
isMe: -> Meteor.user() and Meteor.user()._id is @_id
noDocs: -> docs.find(owner: @_id).count() is 0
documents: -> docs.find {owner: @_id}, sort: dateCreated: -1
Template.profile.events
'click #resend': ->
Meteor.call 'sendVerificationEmail', (e,r) ->
if e then errCallback e
else notify msg: r, type:'success'
'click #logout': -> Meteor.logout(); Router.go 'home'
'click #deleteme': -> swal {
title: 'Are you sure?'
text: 'Do you want to permanently delete all your data?'
type: 'warning'
showCancelButton: yes
confirmButtonColor: "#DD6B55"
confirmButtonText: "Yes!"
}, -> Meteor.call 'deleteMe', (e,r) ->
if e then errCallback e
else notify type: 'success', msg: 'Account deleted'
Template.doc.helpers
valid: -> @text?
source: -> Router.current().route.getName() is 'src'
rows: -> ""+@text.split('\n').length
owned: -> Meteor.user() and Meteor.user()._id is @owner
ownerName: ->
if Router.current().route.getName() is 'userDoc'
return Router.current().params.user
expirationDays: ->
if @owner then return 'never'
else return moment.unix(@dateCreated).add(7,'days').fromNow()
Template.doc.events
'click #edit-doc': -> Router.go 'edit', _id: @_id
'click #del-doc': ->
if Meteor.user()._id is @owner
swal {
title: 'Are you sure?'
text: 'This document will be deleted permanently'
type: 'warning'
showCancelButton: yes
confirmButtonColor: "#DD6B55"
confirmButtonText: "Yes!"
}, => docs.remove @_id, (err) ->
if err then errCallback err
else notify type:'success', msg:'Document removed'
'click #src-doc': ->
if Router.current().route.getName() is 'src'
Router.go 'doc', _id: @_id
else Router.go 'src', _id: @_id
Template.signin.events
'click #signin': (e,t) ->
if not t.find('#mail').value
return notify msg: 'please enter your email or username'
else if not t.find('#pw').value
return notify msg: "Please enter a password"
else
Meteor.loginWithPassword t.find('#mail').value, t.find('#pw').value,(e)->
if e then errCallback e
else notify type:'success', msg:'Welcome back!'; Router.go 'home'
Template.signup.events
'click #signup': (e,t) ->
if not t.find('#mail').value
return notify msg: 'please enter your email'
if not t.find('#name').value
return notify msg: 'please enter your user name'
else if not t.find('#pw').value
return notify msg: "Please enter a password"
else if t.find('#pw').value isnt t.find('#rpw').value
return notify msg: "The passwords don't match"
else # Sending actual registration request
Accounts.createUser {
username: t.find('#name').value
email: t.find('#mail').value
password: t.find('#<PASSWORD>').value
}, (err) -> if err then errCallback err
else notify type: 'success', msg: 'check your email'
| true | docs = new Meteor.Collection 'docs'
amIValid = ->
return no unless Meteor.user()
return yes if !Meteor.user().emails?
return yes for mail in Meteor.user().emails when mail.verified is yes; no
UI.registerHelper 'mail', ->
if Meteor.user().emails then Meteor.user().emails[0].address
UI.registerHelper 'amIValid', amIValid
Router.configure
layoutTemplate: 'layout'
loadingTemplate: 'loading'
docController = RouteController.extend
template: 'doc'
layoutTemplate: 'docLayout'
waitOn: -> Meteor.subscribe 'doc', @params._id
data: -> docs.findOne @params._id
action: ->
if @ready()
if @data()? then @render()
else @render '404'
else @render 'loading'
loggedOutController = RouteController.extend
onBeforeAction: ->
if Meteor.user() then Router.go 'profile', user: Meteor.user().username
@next()
action: ->
@render()
if Meteor.loggingIn() then @render 'spinner', to: 'outside'
loggedInController = RouteController.extend
action: -> if !Meteor.user() then @render '404' else @render()
Router.route '/',
name: 'home'
action: ->
if !@ready() then @render 'spinner', to: 'outside'
@render('home')
Router.route '/d/:_id',
name: 'doc'
controller: docController
Router.route '/@:user/:_id',
name: 'userDoc'
controller: docController
Router.route '/src/:_id',
name: 'src'
controller: docController
Router.route '/verify/:token?',
name: 'verify'
template: 'loading'
onBeforeAction: ->
Accounts.verifyEmail @params.token, (err) ->
if err then errCallback err
else Router.go 'profile', user: Meteor.user().username
@next()
Router.route '/edit/:_id',
name: 'edit'
template: 'editor'
controller: loggedInController
waitOn: -> Meteor.subscribe 'doc', @params._id
data: -> docs.findOne @params._id
Router.route '/@:user',
name: 'profile'
waitOn: ->
[Meteor.subscribe('docs', @params.user),
Meteor.subscribe('user', @params.user)]
data: -> Meteor.users.findOne username: @params.user
action: ->
if Meteor.loggingIn() then @render 'loading'
else if @ready()
if !@data() then @render '404' else @render()
else @render 'loading'
Router.route '/new',
name: 'new'
template: 'editor'
Router.route '/signup',
name: 'signup'
controller: loggedOutController
Router.route '/login',
name: 'signin'
template: 'signin'
controller: loggedOutController
Router.route '/(.*)', name: '404'
share.notify = notify = (opt) ->
if opt.type? then type = opt.type
else type = 'error'
if opt.title? then title = opt.title
else title = if type is 'error' then 'Error' else 'Ok'
swal title, opt.msg, type
errCallback = (err) ->
return unless err
if err.reason
notify title: err.code or 'Error', msg: err.reason, type: 'error'
else notify title: 'Error', msg: err, type: 'error'
Template.magicIcon.helpers
notHome: -> Router.current().route.getName() isnt 'home'
Template.layout.helpers
showSpinner: -> Meteor.status().connected is yes
Template.home.events
'click #twitter-login': ->
if Meteor.user() then return notify msg: "You're already Logged In!"
Meteor.loginWithTwitter {}, (e) ->
if e then errCallback e
else
Meteor.subscribe 'user'
notify type: 'success', msg: 'Logged in'
Template.editor.helpers
isPublic: -> return "checked" if @public is yes
showTitleChecked: -> return "checked" unless @showTitle is no
Template.editor.events
'click #upload': (e,t) ->
if Meteor.loggingIn()
return notify
msg: "Can't upload while Logging In.\nTry again in a few seconds."
if t.find('#title').value is ''
return notify msg: 'Please insert a title.'
if t.find('#editor').value is ''
return notify msg: "Empty documents are not valid."
if @_id then docs.update @_id, $set: {
title: t.find('#title').value
text: t.find('#editor').value
showTitle: $('#show-title').is(':checked')
public: $('#make-public').is(':checked')
}, (err) =>
if err then errCallback err
else
notify type:'success', msg:'Document updated.'
Router.go 'doc', _id: @_id
else docs.insert {
title: t.find('#title').value
text: t.find('#editor').value
showTitle: $('#show-title').is(':checked')
public: $('#make-public').is(':checked')
}, (err,id) ->
if err then errCallback err
else notify type:'success', msg:'Document created successfully!'
if id then Router.go 'doc', _id: id
Template.profile.helpers
isMe: -> Meteor.user() and Meteor.user()._id is @_id
noDocs: -> docs.find(owner: @_id).count() is 0
documents: -> docs.find {owner: @_id}, sort: dateCreated: -1
Template.profile.events
'click #resend': ->
Meteor.call 'sendVerificationEmail', (e,r) ->
if e then errCallback e
else notify msg: r, type:'success'
'click #logout': -> Meteor.logout(); Router.go 'home'
'click #deleteme': -> swal {
title: 'Are you sure?'
text: 'Do you want to permanently delete all your data?'
type: 'warning'
showCancelButton: yes
confirmButtonColor: "#DD6B55"
confirmButtonText: "Yes!"
}, -> Meteor.call 'deleteMe', (e,r) ->
if e then errCallback e
else notify type: 'success', msg: 'Account deleted'
Template.doc.helpers
valid: -> @text?
source: -> Router.current().route.getName() is 'src'
rows: -> ""+@text.split('\n').length
owned: -> Meteor.user() and Meteor.user()._id is @owner
ownerName: ->
if Router.current().route.getName() is 'userDoc'
return Router.current().params.user
expirationDays: ->
if @owner then return 'never'
else return moment.unix(@dateCreated).add(7,'days').fromNow()
Template.doc.events
'click #edit-doc': -> Router.go 'edit', _id: @_id
'click #del-doc': ->
if Meteor.user()._id is @owner
swal {
title: 'Are you sure?'
text: 'This document will be deleted permanently'
type: 'warning'
showCancelButton: yes
confirmButtonColor: "#DD6B55"
confirmButtonText: "Yes!"
}, => docs.remove @_id, (err) ->
if err then errCallback err
else notify type:'success', msg:'Document removed'
'click #src-doc': ->
if Router.current().route.getName() is 'src'
Router.go 'doc', _id: @_id
else Router.go 'src', _id: @_id
Template.signin.events
'click #signin': (e,t) ->
if not t.find('#mail').value
return notify msg: 'please enter your email or username'
else if not t.find('#pw').value
return notify msg: "Please enter a password"
else
Meteor.loginWithPassword t.find('#mail').value, t.find('#pw').value,(e)->
if e then errCallback e
else notify type:'success', msg:'Welcome back!'; Router.go 'home'
Template.signup.events
'click #signup': (e,t) ->
if not t.find('#mail').value
return notify msg: 'please enter your email'
if not t.find('#name').value
return notify msg: 'please enter your user name'
else if not t.find('#pw').value
return notify msg: "Please enter a password"
else if t.find('#pw').value isnt t.find('#rpw').value
return notify msg: "The passwords don't match"
else # Sending actual registration request
Accounts.createUser {
username: t.find('#name').value
email: t.find('#mail').value
password: t.find('#PI:PASSWORD:<PASSWORD>END_PI').value
}, (err) -> if err then errCallback err
else notify type: 'success', msg: 'check your email'
|
[
{
"context": "line per method call when chaining calls\n# @author Rajendra Patil\n# @author Burak Yigit Kaya\n###\n\n'use strict'\n\nast",
"end": 104,
"score": 0.9998599886894226,
"start": 90,
"tag": "NAME",
"value": "Rajendra Patil"
},
{
"context": " chaining calls\n# @author Rajend... | src/rules/newline-per-chained-call.coffee | danielbayley/eslint-plugin-coffee | 21 | ###*
# @fileoverview Rule to ensure newline per method call when chaining calls
# @author Rajendra Patil
# @author Burak Yigit Kaya
###
'use strict'
astUtils = require '../eslint-ast-utils'
#------------------------------------------------------------------------------
# Rule Definition
#------------------------------------------------------------------------------
module.exports =
meta:
docs:
description: 'require a newline after each call in a method chain'
category: 'Stylistic Issues'
recommended: no
url: 'https://eslint.org/docs/rules/newline-per-chained-call'
# fixable: 'whitespace'
schema: [
type: 'object'
properties:
ignoreChainWithDepth:
type: 'integer'
minimum: 1
maximum: 10
additionalProperties: no
]
create: (context) ->
options = context.options[0] or {}
ignoreChainWithDepth = options.ignoreChainWithDepth or 2
sourceCode = context.getSourceCode()
###*
# Get the prefix of a given MemberExpression node.
# If the MemberExpression node is a computed value it returns a
# left bracket. If not it returns a period.
#
# @param {ASTNode} node - A MemberExpression node to get
# @returns {string} The prefix of the node.
###
getPrefix = (node) -> if node.computed then '[' else '.'
###*
# Gets the property text of a given MemberExpression node.
# If the text is multiline, this returns only the first line.
#
# @param {ASTNode} node - A MemberExpression node to get.
# @returns {string} The property text of the node.
###
getPropertyText = (node) ->
prefix = getPrefix node
lines = sourceCode.getText(node.property).split astUtils.LINEBREAK_MATCHER
suffix = if node.computed and lines.length is 1 then ']' else ''
prefix + lines[0] + suffix
'CallExpression:exit': (node) ->
return unless (
node.callee?.type is 'MemberExpression' and not node.callee.computed
)
{callee} = node
parent = callee.object
depth = 1
while parent?.callee and not parent.callee.computed
depth += 1
parent = parent.callee.object
if (
depth > ignoreChainWithDepth and
astUtils.isTokenOnSameLine callee.object, callee.property
)
context.report
node: callee.property
loc: callee.property.loc.start
message: 'Expected line break before `{{callee}}`.'
data:
callee: getPropertyText callee
# fix: (fixer) ->
# firstTokenAfterObject = sourceCode.getTokenAfter(
# callee.object
# astUtils.isNotClosingParenToken
# )
# fixer.insertTextBefore firstTokenAfterObject, '\n'
| 18914 | ###*
# @fileoverview Rule to ensure newline per method call when chaining calls
# @author <NAME>
# @author <NAME>
###
'use strict'
astUtils = require '../eslint-ast-utils'
#------------------------------------------------------------------------------
# Rule Definition
#------------------------------------------------------------------------------
module.exports =
meta:
docs:
description: 'require a newline after each call in a method chain'
category: 'Stylistic Issues'
recommended: no
url: 'https://eslint.org/docs/rules/newline-per-chained-call'
# fixable: 'whitespace'
schema: [
type: 'object'
properties:
ignoreChainWithDepth:
type: 'integer'
minimum: 1
maximum: 10
additionalProperties: no
]
create: (context) ->
options = context.options[0] or {}
ignoreChainWithDepth = options.ignoreChainWithDepth or 2
sourceCode = context.getSourceCode()
###*
# Get the prefix of a given MemberExpression node.
# If the MemberExpression node is a computed value it returns a
# left bracket. If not it returns a period.
#
# @param {ASTNode} node - A MemberExpression node to get
# @returns {string} The prefix of the node.
###
getPrefix = (node) -> if node.computed then '[' else '.'
###*
# Gets the property text of a given MemberExpression node.
# If the text is multiline, this returns only the first line.
#
# @param {ASTNode} node - A MemberExpression node to get.
# @returns {string} The property text of the node.
###
getPropertyText = (node) ->
prefix = getPrefix node
lines = sourceCode.getText(node.property).split astUtils.LINEBREAK_MATCHER
suffix = if node.computed and lines.length is 1 then ']' else ''
prefix + lines[0] + suffix
'CallExpression:exit': (node) ->
return unless (
node.callee?.type is 'MemberExpression' and not node.callee.computed
)
{callee} = node
parent = callee.object
depth = 1
while parent?.callee and not parent.callee.computed
depth += 1
parent = parent.callee.object
if (
depth > ignoreChainWithDepth and
astUtils.isTokenOnSameLine callee.object, callee.property
)
context.report
node: callee.property
loc: callee.property.loc.start
message: 'Expected line break before `{{callee}}`.'
data:
callee: getPropertyText callee
# fix: (fixer) ->
# firstTokenAfterObject = sourceCode.getTokenAfter(
# callee.object
# astUtils.isNotClosingParenToken
# )
# fixer.insertTextBefore firstTokenAfterObject, '\n'
| true | ###*
# @fileoverview Rule to ensure newline per method call when chaining calls
# @author PI:NAME:<NAME>END_PI
# @author PI:NAME:<NAME>END_PI
###
'use strict'
astUtils = require '../eslint-ast-utils'
#------------------------------------------------------------------------------
# Rule Definition
#------------------------------------------------------------------------------
module.exports =
meta:
docs:
description: 'require a newline after each call in a method chain'
category: 'Stylistic Issues'
recommended: no
url: 'https://eslint.org/docs/rules/newline-per-chained-call'
# fixable: 'whitespace'
schema: [
type: 'object'
properties:
ignoreChainWithDepth:
type: 'integer'
minimum: 1
maximum: 10
additionalProperties: no
]
create: (context) ->
options = context.options[0] or {}
ignoreChainWithDepth = options.ignoreChainWithDepth or 2
sourceCode = context.getSourceCode()
###*
# Get the prefix of a given MemberExpression node.
# If the MemberExpression node is a computed value it returns a
# left bracket. If not it returns a period.
#
# @param {ASTNode} node - A MemberExpression node to get
# @returns {string} The prefix of the node.
###
getPrefix = (node) -> if node.computed then '[' else '.'
###*
# Gets the property text of a given MemberExpression node.
# If the text is multiline, this returns only the first line.
#
# @param {ASTNode} node - A MemberExpression node to get.
# @returns {string} The property text of the node.
###
getPropertyText = (node) ->
prefix = getPrefix node
lines = sourceCode.getText(node.property).split astUtils.LINEBREAK_MATCHER
suffix = if node.computed and lines.length is 1 then ']' else ''
prefix + lines[0] + suffix
'CallExpression:exit': (node) ->
return unless (
node.callee?.type is 'MemberExpression' and not node.callee.computed
)
{callee} = node
parent = callee.object
depth = 1
while parent?.callee and not parent.callee.computed
depth += 1
parent = parent.callee.object
if (
depth > ignoreChainWithDepth and
astUtils.isTokenOnSameLine callee.object, callee.property
)
context.report
node: callee.property
loc: callee.property.loc.start
message: 'Expected line break before `{{callee}}`.'
data:
callee: getPropertyText callee
# fix: (fixer) ->
# firstTokenAfterObject = sourceCode.getTokenAfter(
# callee.object
# astUtils.isNotClosingParenToken
# )
# fixer.insertTextBefore firstTokenAfterObject, '\n'
|
[
{
"context": "tpBackend.expectPOST('/mock/42', id: 42, player: 'Jackie Robinson').respond 200\n CachedResource.save {id: 42}, {",
"end": 1385,
"score": 0.99988853931427,
"start": 1370,
"tag": "NAME",
"value": "Jackie Robinson"
},
{
"context": " CachedResource.save {id: 42}, {id: ... | test/full_local_storage_cache.test.coffee | goodeggs/angular-cached-resource | 152 | # can we mock localStorage? if not (ie Firefox), this test is not gonna work...
localStorageIsMockable = do ->
temp = window.localStorage.setItem
window.localStorage.setItem = -> 'test'
conditional = try
window.localStorage.setItem() is 'test'
catch
false
window.localStorage.setItem = temp
conditional
conditionallyDescribe = if localStorageIsMockable then describe else xdescribe
conditionallyDescribe 'a full localStorage cache', ->
{CachedResource, $httpBackend, $log} = {}
beforeEach ->
sinon.stub(window.localStorage, 'setItem').throws new Error('QuotaExceededError')
inject ($injector) ->
$log = $injector.get '$log'
$cachedResource = $injector.get '$cachedResource'
$httpBackend = $injector.get '$httpBackend'
CachedResource = $cachedResource 'full-local-storage-cache', '/mock/:id', id: '@id'
afterEach ->
window.localStorage.setItem.restore()
it 'still succeeds at GET requests', ->
$httpBackend.expectGET('/mock/42').respond question: 'The ultimate question of life, the universe, and everything'
resourceInstance = CachedResource.get id: 42
$httpBackend.flush()
expect(resourceInstance.question).to.equal 'The ultimate question of life, the universe, and everything'
it 'still succeeds at POST requests', ->
$httpBackend.expectPOST('/mock/42', id: 42, player: 'Jackie Robinson').respond 200
CachedResource.save {id: 42}, {id: 42, player: 'Jackie Robinson'}
$httpBackend.flush()
it 'logs an error on a failed write to localStorage', ->
CachedResource.save {id: 42}, {id: 42, player: 'Jackie Robinson'}
expect($log.error.logs[0][0]).to.contain "ngCachedResource"
expect($log.error.logs[0][1]).to.contain "Failed to write to localStorage"
expect($log.error.logs[0][2].error).to.have.property 'message', 'QuotaExceededError'
expect($log.error.logs[0][2]).to.have.property 'key', 'cachedResource://full-local-storage-cache?id=42'
expect($log.error.logs[0][2]).to.have.property 'value', '{"value":{"id":42,"player":"Jackie Robinson"},"dirty":true}'
| 45757 | # can we mock localStorage? if not (ie Firefox), this test is not gonna work...
localStorageIsMockable = do ->
temp = window.localStorage.setItem
window.localStorage.setItem = -> 'test'
conditional = try
window.localStorage.setItem() is 'test'
catch
false
window.localStorage.setItem = temp
conditional
conditionallyDescribe = if localStorageIsMockable then describe else xdescribe
conditionallyDescribe 'a full localStorage cache', ->
{CachedResource, $httpBackend, $log} = {}
beforeEach ->
sinon.stub(window.localStorage, 'setItem').throws new Error('QuotaExceededError')
inject ($injector) ->
$log = $injector.get '$log'
$cachedResource = $injector.get '$cachedResource'
$httpBackend = $injector.get '$httpBackend'
CachedResource = $cachedResource 'full-local-storage-cache', '/mock/:id', id: '@id'
afterEach ->
window.localStorage.setItem.restore()
it 'still succeeds at GET requests', ->
$httpBackend.expectGET('/mock/42').respond question: 'The ultimate question of life, the universe, and everything'
resourceInstance = CachedResource.get id: 42
$httpBackend.flush()
expect(resourceInstance.question).to.equal 'The ultimate question of life, the universe, and everything'
it 'still succeeds at POST requests', ->
$httpBackend.expectPOST('/mock/42', id: 42, player: '<NAME>').respond 200
CachedResource.save {id: 42}, {id: 42, player: '<NAME>'}
$httpBackend.flush()
it 'logs an error on a failed write to localStorage', ->
CachedResource.save {id: 42}, {id: 42, player: '<NAME>'}
expect($log.error.logs[0][0]).to.contain "ngCachedResource"
expect($log.error.logs[0][1]).to.contain "Failed to write to localStorage"
expect($log.error.logs[0][2].error).to.have.property 'message', 'QuotaExceededError'
expect($log.error.logs[0][2]).to.have.property 'key', 'cachedResource://full-local-storage-cache?id=42'
expect($log.error.logs[0][2]).to.have.property 'value', '{"value":{"id":42,"player":"<NAME>"},"dirty":true}'
| true | # can we mock localStorage? if not (ie Firefox), this test is not gonna work...
localStorageIsMockable = do ->
temp = window.localStorage.setItem
window.localStorage.setItem = -> 'test'
conditional = try
window.localStorage.setItem() is 'test'
catch
false
window.localStorage.setItem = temp
conditional
conditionallyDescribe = if localStorageIsMockable then describe else xdescribe
conditionallyDescribe 'a full localStorage cache', ->
{CachedResource, $httpBackend, $log} = {}
beforeEach ->
sinon.stub(window.localStorage, 'setItem').throws new Error('QuotaExceededError')
inject ($injector) ->
$log = $injector.get '$log'
$cachedResource = $injector.get '$cachedResource'
$httpBackend = $injector.get '$httpBackend'
CachedResource = $cachedResource 'full-local-storage-cache', '/mock/:id', id: '@id'
afterEach ->
window.localStorage.setItem.restore()
it 'still succeeds at GET requests', ->
$httpBackend.expectGET('/mock/42').respond question: 'The ultimate question of life, the universe, and everything'
resourceInstance = CachedResource.get id: 42
$httpBackend.flush()
expect(resourceInstance.question).to.equal 'The ultimate question of life, the universe, and everything'
it 'still succeeds at POST requests', ->
$httpBackend.expectPOST('/mock/42', id: 42, player: 'PI:NAME:<NAME>END_PI').respond 200
CachedResource.save {id: 42}, {id: 42, player: 'PI:NAME:<NAME>END_PI'}
$httpBackend.flush()
it 'logs an error on a failed write to localStorage', ->
CachedResource.save {id: 42}, {id: 42, player: 'PI:NAME:<NAME>END_PI'}
expect($log.error.logs[0][0]).to.contain "ngCachedResource"
expect($log.error.logs[0][1]).to.contain "Failed to write to localStorage"
expect($log.error.logs[0][2].error).to.have.property 'message', 'QuotaExceededError'
expect($log.error.logs[0][2]).to.have.property 'key', 'cachedResource://full-local-storage-cache?id=42'
expect($log.error.logs[0][2]).to.have.property 'value', '{"value":{"id":42,"player":"PI:NAME:<NAME>END_PI"},"dirty":true}'
|
[
{
"context": "* @package\t\tHome\n * @category\tmodules\n * @author\t\tNazar Mokrynskyi <nazar@mokrynskyi.com>\n * @copyright\tCopyright (c",
"end": 71,
"score": 0.9998899102210999,
"start": 55,
"tag": "NAME",
"value": "Nazar Mokrynskyi"
},
{
"context": "* @category\tmodules\n * @aut... | components/modules/Home/includes/js/guest.coffee | nazar-pc/cherrytea.org-old | 1 | ###
* @package Home
* @category modules
* @author Nazar Mokrynskyi <nazar@mokrynskyi.com>
* @copyright Copyright (c) 2013-2014, Nazar Mokrynskyi
* @license MIT License, see license.txt
###
$ ->
if !$('#map').length
return
$('.home-page-sign-in a:not(.gp)').click ->
location.href = 'HybridAuth/' + (if $(@).hasClass('fb') then 'Facebook' else 'Vkontakte')
| 184852 | ###
* @package Home
* @category modules
* @author <NAME> <<EMAIL>>
* @copyright Copyright (c) 2013-2014, <NAME>
* @license MIT License, see license.txt
###
$ ->
if !$('#map').length
return
$('.home-page-sign-in a:not(.gp)').click ->
location.href = 'HybridAuth/' + (if $(@).hasClass('fb') then 'Facebook' else 'Vkontakte')
| true | ###
* @package Home
* @category modules
* @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
* @copyright Copyright (c) 2013-2014, PI:NAME:<NAME>END_PI
* @license MIT License, see license.txt
###
$ ->
if !$('#map').length
return
$('.home-page-sign-in a:not(.gp)').click ->
location.href = 'HybridAuth/' + (if $(@).hasClass('fb') then 'Facebook' else 'Vkontakte')
|
[
{
"context": "= value.size\n\n setItem: (key, value) ->\n key = key.toString()\n filename = path.join(@location, encodeURIComp",
"end": 1412,
"score": 0.9864777326583862,
"start": 1398,
"tag": "KEY",
"value": "key.toString()"
},
{
"context": "lueStringLength\n\n getItem: (key... | node_modules/node-localstorage/LocalStorage.coffee | NileFrater/machinepack-nodestore | 0 | path = require('path')
fs = require('fs')
_emptyDirectory = (target) ->
_rm(path.join(target, p)) for p in fs.readdirSync(target)
_rm = (target) ->
if fs.statSync(target).isDirectory()
_emptyDirectory(target)
fs.rmdirSync(target)
else
fs.unlinkSync(target)
class QUOTA_EXCEEDED_ERR extends Error
constructor: (@message = 'Unknown error.') ->
if Error.captureStackTrace?
Error.captureStackTrace(this, @constructor)
@name = @constructor.name
toString: () ->
return "#{@name}: #{@message}"
class LocalStorage
constructor: (@location, @quota = 5 * 1024 * 1024) ->
unless this instanceof LocalStorage
return new LocalStorage(@location, @quota)
@length = 0 # !TODO: Maybe change this to a property with __defineProperty__
@bytesInUse = 0
@keys = []
@_init()
@QUOTA_EXCEEDED_ERR = QUOTA_EXCEEDED_ERR
_init: () ->
if fs.existsSync(@location)
unless fs.statSync(@location).isDirectory()
throw new Error("A file exists at the location '#{@location}' when trying to create/open localStorage")
unless fs.existsSync(@location)
fs.mkdirSync(@location)
@keys = fs.readdirSync(@location).map(decodeURIComponent)
@length = @keys.length
@bytesInUse = 0
for k in @keys
value = @getStat(k)
if value?.size?
@bytesInUse += value.size
setItem: (key, value) ->
key = key.toString()
filename = path.join(@location, encodeURIComponent(key))
existsBeforeSet = fs.existsSync(filename)
valueString = value.toString()
valueStringLength = valueString.length
if existsBeforeSet
oldLength = @getStat(key).size
else
oldLength = 0
if @bytesInUse - oldLength + valueStringLength > @quota
throw new QUOTA_EXCEEDED_ERR()
fs.writeFileSync(filename, valueString, 'utf8')
unless existsBeforeSet
@keys.push(key)
@length = @keys.length
@bytesInUse += valueStringLength
getItem: (key) ->
key = key.toString()
filename = path.join(@location, encodeURIComponent(key))
if fs.existsSync(filename)
return fs.readFileSync(filename, 'utf8')
else
return null
getStat: (key) ->
key = key.toString()
filename = path.join(@location, encodeURIComponent(key))
if fs.existsSync(filename)
return fs.statSync(filename,'utf8')
else
return null
removeItem: (key) ->
key = key.toString()
filename = path.join(@location, encodeURIComponent(key))
if fs.existsSync(filename)
_rm(filename)
@_init() # !TODO: Find a faster way to set @keys, length, and bytesInUse
key: (n) ->
return @keys[n]
clear: () ->
_emptyDirectory(@location)
@keys = []
@length = 0
@bytesInUse = 0
getBytesInUse: () ->
return @bytesInUse
_deleteLocation: () ->
_rm(@location)
@keys = []
@length = 0
@bytesInUse = 0
class JSONStorage extends LocalStorage
setItem: (key, value) ->
newValue = JSON.stringify(value)
super(key, newValue)
getItem: (key) ->
return JSON.parse(super(key))
exports.LocalStorage = LocalStorage
exports.JSONStorage = JSONStorage
exports.QUOTA_EXCEEDED_ERR = QUOTA_EXCEEDED_ERR
| 166457 | path = require('path')
fs = require('fs')
_emptyDirectory = (target) ->
_rm(path.join(target, p)) for p in fs.readdirSync(target)
_rm = (target) ->
if fs.statSync(target).isDirectory()
_emptyDirectory(target)
fs.rmdirSync(target)
else
fs.unlinkSync(target)
class QUOTA_EXCEEDED_ERR extends Error
constructor: (@message = 'Unknown error.') ->
if Error.captureStackTrace?
Error.captureStackTrace(this, @constructor)
@name = @constructor.name
toString: () ->
return "#{@name}: #{@message}"
class LocalStorage
constructor: (@location, @quota = 5 * 1024 * 1024) ->
unless this instanceof LocalStorage
return new LocalStorage(@location, @quota)
@length = 0 # !TODO: Maybe change this to a property with __defineProperty__
@bytesInUse = 0
@keys = []
@_init()
@QUOTA_EXCEEDED_ERR = QUOTA_EXCEEDED_ERR
_init: () ->
if fs.existsSync(@location)
unless fs.statSync(@location).isDirectory()
throw new Error("A file exists at the location '#{@location}' when trying to create/open localStorage")
unless fs.existsSync(@location)
fs.mkdirSync(@location)
@keys = fs.readdirSync(@location).map(decodeURIComponent)
@length = @keys.length
@bytesInUse = 0
for k in @keys
value = @getStat(k)
if value?.size?
@bytesInUse += value.size
setItem: (key, value) ->
key = <KEY>
filename = path.join(@location, encodeURIComponent(key))
existsBeforeSet = fs.existsSync(filename)
valueString = value.toString()
valueStringLength = valueString.length
if existsBeforeSet
oldLength = @getStat(key).size
else
oldLength = 0
if @bytesInUse - oldLength + valueStringLength > @quota
throw new QUOTA_EXCEEDED_ERR()
fs.writeFileSync(filename, valueString, 'utf8')
unless existsBeforeSet
@keys.push(key)
@length = @keys.length
@bytesInUse += valueStringLength
getItem: (key) ->
key = key.<KEY>()
filename = path.join(@location, encodeURIComponent(key))
if fs.existsSync(filename)
return fs.readFileSync(filename, 'utf8')
else
return null
getStat: (key) ->
key = key.<KEY>()
filename = path.join(@location, encodeURIComponent(key))
if fs.existsSync(filename)
return fs.statSync(filename,'utf8')
else
return null
removeItem: (key) ->
key = <KEY>
filename = path.join(@location, encodeURIComponent(key))
if fs.existsSync(filename)
_rm(filename)
@_init() # !TODO: Find a faster way to set @keys, length, and bytesInUse
key: (n) ->
return @keys[n]
clear: () ->
_emptyDirectory(@location)
@keys = []
@length = 0
@bytesInUse = 0
getBytesInUse: () ->
return @bytesInUse
_deleteLocation: () ->
_rm(@location)
@keys = []
@length = 0
@bytesInUse = 0
class JSONStorage extends LocalStorage
setItem: (key, value) ->
newValue = JSON.stringify(value)
super(key, newValue)
getItem: (key) ->
return JSON.parse(super(key))
exports.LocalStorage = LocalStorage
exports.JSONStorage = JSONStorage
exports.QUOTA_EXCEEDED_ERR = QUOTA_EXCEEDED_ERR
| true | path = require('path')
fs = require('fs')
_emptyDirectory = (target) ->
_rm(path.join(target, p)) for p in fs.readdirSync(target)
_rm = (target) ->
if fs.statSync(target).isDirectory()
_emptyDirectory(target)
fs.rmdirSync(target)
else
fs.unlinkSync(target)
class QUOTA_EXCEEDED_ERR extends Error
constructor: (@message = 'Unknown error.') ->
if Error.captureStackTrace?
Error.captureStackTrace(this, @constructor)
@name = @constructor.name
toString: () ->
return "#{@name}: #{@message}"
class LocalStorage
constructor: (@location, @quota = 5 * 1024 * 1024) ->
unless this instanceof LocalStorage
return new LocalStorage(@location, @quota)
@length = 0 # !TODO: Maybe change this to a property with __defineProperty__
@bytesInUse = 0
@keys = []
@_init()
@QUOTA_EXCEEDED_ERR = QUOTA_EXCEEDED_ERR
_init: () ->
if fs.existsSync(@location)
unless fs.statSync(@location).isDirectory()
throw new Error("A file exists at the location '#{@location}' when trying to create/open localStorage")
unless fs.existsSync(@location)
fs.mkdirSync(@location)
@keys = fs.readdirSync(@location).map(decodeURIComponent)
@length = @keys.length
@bytesInUse = 0
for k in @keys
value = @getStat(k)
if value?.size?
@bytesInUse += value.size
setItem: (key, value) ->
key = PI:KEY:<KEY>END_PI
filename = path.join(@location, encodeURIComponent(key))
existsBeforeSet = fs.existsSync(filename)
valueString = value.toString()
valueStringLength = valueString.length
if existsBeforeSet
oldLength = @getStat(key).size
else
oldLength = 0
if @bytesInUse - oldLength + valueStringLength > @quota
throw new QUOTA_EXCEEDED_ERR()
fs.writeFileSync(filename, valueString, 'utf8')
unless existsBeforeSet
@keys.push(key)
@length = @keys.length
@bytesInUse += valueStringLength
getItem: (key) ->
key = key.PI:KEY:<KEY>END_PI()
filename = path.join(@location, encodeURIComponent(key))
if fs.existsSync(filename)
return fs.readFileSync(filename, 'utf8')
else
return null
getStat: (key) ->
key = key.PI:KEY:<KEY>END_PI()
filename = path.join(@location, encodeURIComponent(key))
if fs.existsSync(filename)
return fs.statSync(filename,'utf8')
else
return null
removeItem: (key) ->
key = PI:KEY:<KEY>END_PI
filename = path.join(@location, encodeURIComponent(key))
if fs.existsSync(filename)
_rm(filename)
@_init() # !TODO: Find a faster way to set @keys, length, and bytesInUse
key: (n) ->
return @keys[n]
clear: () ->
_emptyDirectory(@location)
@keys = []
@length = 0
@bytesInUse = 0
getBytesInUse: () ->
return @bytesInUse
_deleteLocation: () ->
_rm(@location)
@keys = []
@length = 0
@bytesInUse = 0
class JSONStorage extends LocalStorage
setItem: (key, value) ->
newValue = JSON.stringify(value)
super(key, newValue)
getItem: (key) ->
return JSON.parse(super(key))
exports.LocalStorage = LocalStorage
exports.JSONStorage = JSONStorage
exports.QUOTA_EXCEEDED_ERR = QUOTA_EXCEEDED_ERR
|
[
{
"context": "{\n\t\t\tcache: true\n\t\t\traw: false\n\t\t\tauth: {username: admin.user, password: admin.pass}\n\t\t}\n\t\t@db = @connect.datab",
"end": 284,
"score": 0.9989209771156311,
"start": 274,
"tag": "USERNAME",
"value": "admin.user"
},
{
"context": "w: false\n\t\t\tauth: {us... | controllers/users.coffee | koostudios/couchpress | 7 | cradle = require 'cradle'
crypto = require 'crypto'
config = require('../config').config
admin = require('../config').admin
class User
constructor: () ->
@connect = new cradle.Connection config.db.host, config.db.port, {
cache: true
raw: false
auth: {username: admin.user, password: admin.pass}
}
@db = @connect.database '_users'
find: (user, pass, done) ->
@db.get 'org.couchdb.user:'+user, (err, user) ->
# Error
if !user || err
done null, null, {message: '<b>Error:</b> User not found.'}
else
hash = crypto.createHash('sha1').update(pass+user.salt).digest('hex')
if (hash != user.password_sha)
done null, null, {message: '<b>Error:</b> Password incorrect.'}
else
done null, user
findId: (id, done) ->
@db.get id, done
register: (data, done) ->
@db.save data, (err, user) ->
done err, user
check: (req, res, next) ->
if req.isAuthenticated()
next()
else
res.redirect '/login'
exports.users = new User() | 30427 | cradle = require 'cradle'
crypto = require 'crypto'
config = require('../config').config
admin = require('../config').admin
class User
constructor: () ->
@connect = new cradle.Connection config.db.host, config.db.port, {
cache: true
raw: false
auth: {username: admin.user, password: <PASSWORD>}
}
@db = @connect.database '_users'
find: (user, pass, done) ->
@db.get 'org.couchdb.user:'+user, (err, user) ->
# Error
if !user || err
done null, null, {message: '<b>Error:</b> User not found.'}
else
hash = crypto.createHash('sha1').update(pass+user.salt).digest('hex')
if (hash != user.password_sha)
done null, null, {message: '<b>Error:</b> Password incorrect.'}
else
done null, user
findId: (id, done) ->
@db.get id, done
register: (data, done) ->
@db.save data, (err, user) ->
done err, user
check: (req, res, next) ->
if req.isAuthenticated()
next()
else
res.redirect '/login'
exports.users = new User() | true | cradle = require 'cradle'
crypto = require 'crypto'
config = require('../config').config
admin = require('../config').admin
class User
constructor: () ->
@connect = new cradle.Connection config.db.host, config.db.port, {
cache: true
raw: false
auth: {username: admin.user, password: PI:PASSWORD:<PASSWORD>END_PI}
}
@db = @connect.database '_users'
find: (user, pass, done) ->
@db.get 'org.couchdb.user:'+user, (err, user) ->
# Error
if !user || err
done null, null, {message: '<b>Error:</b> User not found.'}
else
hash = crypto.createHash('sha1').update(pass+user.salt).digest('hex')
if (hash != user.password_sha)
done null, null, {message: '<b>Error:</b> Password incorrect.'}
else
done null, user
findId: (id, done) ->
@db.get id, done
register: (data, done) ->
@db.save data, (err, user) ->
done err, user
check: (req, res, next) ->
if req.isAuthenticated()
next()
else
res.redirect '/login'
exports.users = new User() |
[
{
"context": " properties', ->\n model = get: ->\n name: 'Abraham'\n\n attributes = SequelizeAdapter.get model\n ",
"end": 244,
"score": 0.8561139702796936,
"start": 237,
"tag": "NAME",
"value": "Abraham"
},
{
"context": "ter.get model\n expect(attributes.name).to.eq ... | test/yayson/adapters/sequelize.coffee | nie7321/yayson | 193 |
expect = require('chai').expect
SequelizeAdapter = require('../../../src/yayson/adapters/sequelize.coffee')
describe 'SequelizeAdapter', ->
beforeEach ->
it 'should get all object properties', ->
model = get: ->
name: 'Abraham'
attributes = SequelizeAdapter.get model
expect(attributes.name).to.eq 'Abraham'
it 'should get object property', ->
args = null
model = get: ->
args = arguments
'Abraham'
name = SequelizeAdapter.get model, 'name'
expect(name).to.eq 'Abraham'
expect(args[0]).to.eq 'name'
it 'should get the id', ->
model =
get: (attr) ->
expect(attr).to.eq 'id'
5
id = SequelizeAdapter.id model
expect(id).to.eq '5'
| 171733 |
expect = require('chai').expect
SequelizeAdapter = require('../../../src/yayson/adapters/sequelize.coffee')
describe 'SequelizeAdapter', ->
beforeEach ->
it 'should get all object properties', ->
model = get: ->
name: '<NAME>'
attributes = SequelizeAdapter.get model
expect(attributes.name).to.eq 'A<NAME>'
it 'should get object property', ->
args = null
model = get: ->
args = arguments
'Abraham'
name = SequelizeAdapter.get model, 'name'
expect(name).to.eq 'Abraham'
expect(args[0]).to.eq 'name'
it 'should get the id', ->
model =
get: (attr) ->
expect(attr).to.eq 'id'
5
id = SequelizeAdapter.id model
expect(id).to.eq '5'
| true |
expect = require('chai').expect
SequelizeAdapter = require('../../../src/yayson/adapters/sequelize.coffee')
describe 'SequelizeAdapter', ->
beforeEach ->
it 'should get all object properties', ->
model = get: ->
name: 'PI:NAME:<NAME>END_PI'
attributes = SequelizeAdapter.get model
expect(attributes.name).to.eq 'API:NAME:<NAME>END_PI'
it 'should get object property', ->
args = null
model = get: ->
args = arguments
'Abraham'
name = SequelizeAdapter.get model, 'name'
expect(name).to.eq 'Abraham'
expect(args[0]).to.eq 'name'
it 'should get the id', ->
model =
get: (attr) ->
expect(attr).to.eq 'id'
5
id = SequelizeAdapter.id model
expect(id).to.eq '5'
|
[
{
"context": "# Commands:\n# hubot whos the man\n#\n# Author:\n# Mateusz Kopij <sagasu>\n\nmodule.exports = (robot) ->\n\n robot.re",
"end": 157,
"score": 0.9998611807823181,
"start": 144,
"tag": "NAME",
"value": "Mateusz Kopij"
},
{
"context": "hubot whos the man\n#\n# Author:\... | scripts/whos-the-man.coffee | sagasu/doc | 1 | # Description:
# Prem, Prem, Prem
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# hubot whos the man
#
# Author:
# Mateusz Kopij <sagasu>
module.exports = (robot) ->
robot.respond /whos the man/i, (msg)->
msg.send "Prem, Prem, Prem!"
| 70940 | # Description:
# Prem, Prem, Prem
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# hubot whos the man
#
# Author:
# <NAME> <sagasu>
module.exports = (robot) ->
robot.respond /whos the man/i, (msg)->
msg.send "Prem, Prem, Prem!"
| true | # Description:
# Prem, Prem, Prem
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# hubot whos the man
#
# Author:
# PI:NAME:<NAME>END_PI <sagasu>
module.exports = (robot) ->
robot.respond /whos the man/i, (msg)->
msg.send "Prem, Prem, Prem!"
|
[
{
"context": "ler\"\nPAGES: \"Sayfalar\"\nPOSTS: \"Yazılar\"\nAUTHORS: \"Yazarlar\"\nSEARCH: \"Ara\"\nSOCIAL_NETWORKS: \"Sosyal Medya\"\nCA",
"end": 392,
"score": 0.996127188205719,
"start": 384,
"tag": "NAME",
"value": "Yazarlar"
},
{
"context": ": \"Ana sayfa\"\n\"search\":\n \"... | src/i18n/tr.cson | Intraktio/hybrid | 2 | PULL_TO_REFRESH: "Yenilemek için çekin!"
RETRY: "Tekrar Dene"
CANCEL: "Cancel"
SUBMIT: "Submit"
BACK: "Geri"
ERROR: "Bir şeyler ters gitti, lütfen tekrar deneyin."
ATTEMPT_TO_CONNECT: "Tekrar Bağlanılıyor"
OK: "Ok"
YES: "Evet"
NO: "Hayır"
EMPTY_LIST: "Burada bir şey yok!"
ENABLED: "Aktif"
MENU: "Menü"
HOME: "Ana Sayfa"
TAGS: "Etiketler"
PAGES: "Sayfalar"
POSTS: "Yazılar"
AUTHORS: "Yazarlar"
SEARCH: "Ara"
SOCIAL_NETWORKS: "Sosyal Medya"
CATEGORIES: "Kategoriler"
SETTINGS: "Ayarlar"
CUSTOM_POSTS: "Özel Gönderiler"
CUSTOM_TAXO: "Özel Taksonomi"
CUSTOM_TAXO_TITLE: "{{term}}: {{name}}"
PUSH_NOTIFS: "Push Bildirimleri"
PUSH_NOTIF_TITLE: "Yeni Yazı Yayımlandı!"
PUSH_NOTIF_TEXT: "Yeni Yazı/Sayfa: '{{postTitle}}' yayımlandı, açmak ister misiniz?"
BOOKMARKS: "Favoriler"
BOOKMARKS_EMPTY: "Henüz favori yazı yok!"
BOOKMARK_ADDED: "Favorilere eklendi!"
BOOKMARK_REMOVED: "Favorilerden kaldırıldı!"
ZOOM: "Zoom"
CACHE_CLEAR: "Clear cache"
CACHE_CLEARED: "Cache cleared"
"tags":
"title": "Etiketler"
"tag":
"title": "Etiket: {{name}}"
"categories":
"title": "Kategoriler"
"category":
"title": "Kategori: {{name}}"
"home":
"title": "Ana sayfa"
"search":
"inputPlaceholder": "Ara"
"title": "Ara"
"titleQuery": "Ara: {{query}}"
"sharing":
"shared": "Paylaşıldı!"
AUTHORS: "Yazarlar"
AUTHOR: "Yazar"
AUTHOR_TITLE: "Yazar: {{name}}"
"pages":
"title": "Sayfalar"
"posts":
"title": "Yazılar"
"featured": "Öne çıkan"
"post":
"comments": "Yorumlar"
"openInBrowser": "Tarayıcıda aç"
"about":
"title": "Hakkımızda"
"languages":
"en": "İngilizce"
"tr": "Türkçe"
"fr": "Fransızca"
"zh": "Çince"
"es": "İspanyolca"
"pl": "Lehçe (Polonezce)"
"de": "Almanca"
"pt": "Portekizce"
"it": "İtalyanca"
"nl": "Felemenkçe"
"ru": "Rusça" | 49207 | PULL_TO_REFRESH: "Yenilemek için çekin!"
RETRY: "Tekrar Dene"
CANCEL: "Cancel"
SUBMIT: "Submit"
BACK: "Geri"
ERROR: "Bir şeyler ters gitti, lütfen tekrar deneyin."
ATTEMPT_TO_CONNECT: "Tekrar Bağlanılıyor"
OK: "Ok"
YES: "Evet"
NO: "Hayır"
EMPTY_LIST: "Burada bir şey yok!"
ENABLED: "Aktif"
MENU: "Menü"
HOME: "Ana Sayfa"
TAGS: "Etiketler"
PAGES: "Sayfalar"
POSTS: "Yazılar"
AUTHORS: "<NAME>"
SEARCH: "Ara"
SOCIAL_NETWORKS: "Sosyal Medya"
CATEGORIES: "Kategoriler"
SETTINGS: "Ayarlar"
CUSTOM_POSTS: "Özel Gönderiler"
CUSTOM_TAXO: "Özel Taksonomi"
CUSTOM_TAXO_TITLE: "{{term}}: {{name}}"
PUSH_NOTIFS: "Push Bildirimleri"
PUSH_NOTIF_TITLE: "Yeni Yazı Yayımlandı!"
PUSH_NOTIF_TEXT: "Yeni Yazı/Sayfa: '{{postTitle}}' yayımlandı, açmak ister misiniz?"
BOOKMARKS: "Favoriler"
BOOKMARKS_EMPTY: "Henüz favori yazı yok!"
BOOKMARK_ADDED: "Favorilere eklendi!"
BOOKMARK_REMOVED: "Favorilerden kaldırıldı!"
ZOOM: "Zoom"
CACHE_CLEAR: "Clear cache"
CACHE_CLEARED: "Cache cleared"
"tags":
"title": "Etiketler"
"tag":
"title": "Etiket: {{name}}"
"categories":
"title": "Kategoriler"
"category":
"title": "Kategori: {{name}}"
"home":
"title": "Ana sayfa"
"search":
"inputPlaceholder": "A<NAME>"
"title": "Ara"
"titleQuery": "Ara: {{query}}"
"sharing":
"shared": "Paylaşıldı!"
AUTHORS: "<NAME>"
AUTHOR: "<NAME>"
AUTHOR_TITLE: "Yazar: {{name}}"
"pages":
"title": "Sayfalar"
"posts":
"title": "Yazılar"
"featured": "Öne çıkan"
"post":
"comments": "Yorumlar"
"openInBrowser": "Tarayıcıda aç"
"about":
"title": "Hakkımızda"
"languages":
"en": "İngilizce"
"tr": "Türkçe"
"fr": "Fransızca"
"zh": "Çince"
"es": "İspanyolca"
"pl": "Lehçe (Polonezce)"
"de": "Almanca"
"pt": "Portekizce"
"it": "İtalyanca"
"nl": "Felemenkçe"
"ru": "Rusça" | true | PULL_TO_REFRESH: "Yenilemek için çekin!"
RETRY: "Tekrar Dene"
CANCEL: "Cancel"
SUBMIT: "Submit"
BACK: "Geri"
ERROR: "Bir şeyler ters gitti, lütfen tekrar deneyin."
ATTEMPT_TO_CONNECT: "Tekrar Bağlanılıyor"
OK: "Ok"
YES: "Evet"
NO: "Hayır"
EMPTY_LIST: "Burada bir şey yok!"
ENABLED: "Aktif"
MENU: "Menü"
HOME: "Ana Sayfa"
TAGS: "Etiketler"
PAGES: "Sayfalar"
POSTS: "Yazılar"
AUTHORS: "PI:NAME:<NAME>END_PI"
SEARCH: "Ara"
SOCIAL_NETWORKS: "Sosyal Medya"
CATEGORIES: "Kategoriler"
SETTINGS: "Ayarlar"
CUSTOM_POSTS: "Özel Gönderiler"
CUSTOM_TAXO: "Özel Taksonomi"
CUSTOM_TAXO_TITLE: "{{term}}: {{name}}"
PUSH_NOTIFS: "Push Bildirimleri"
PUSH_NOTIF_TITLE: "Yeni Yazı Yayımlandı!"
PUSH_NOTIF_TEXT: "Yeni Yazı/Sayfa: '{{postTitle}}' yayımlandı, açmak ister misiniz?"
BOOKMARKS: "Favoriler"
BOOKMARKS_EMPTY: "Henüz favori yazı yok!"
BOOKMARK_ADDED: "Favorilere eklendi!"
BOOKMARK_REMOVED: "Favorilerden kaldırıldı!"
ZOOM: "Zoom"
CACHE_CLEAR: "Clear cache"
CACHE_CLEARED: "Cache cleared"
"tags":
"title": "Etiketler"
"tag":
"title": "Etiket: {{name}}"
"categories":
"title": "Kategoriler"
"category":
"title": "Kategori: {{name}}"
"home":
"title": "Ana sayfa"
"search":
"inputPlaceholder": "API:NAME:<NAME>END_PI"
"title": "Ara"
"titleQuery": "Ara: {{query}}"
"sharing":
"shared": "Paylaşıldı!"
AUTHORS: "PI:NAME:<NAME>END_PI"
AUTHOR: "PI:NAME:<NAME>END_PI"
AUTHOR_TITLE: "Yazar: {{name}}"
"pages":
"title": "Sayfalar"
"posts":
"title": "Yazılar"
"featured": "Öne çıkan"
"post":
"comments": "Yorumlar"
"openInBrowser": "Tarayıcıda aç"
"about":
"title": "Hakkımızda"
"languages":
"en": "İngilizce"
"tr": "Türkçe"
"fr": "Fransızca"
"zh": "Çince"
"es": "İspanyolca"
"pl": "Lehçe (Polonezce)"
"de": "Almanca"
"pt": "Portekizce"
"it": "İtalyanca"
"nl": "Felemenkçe"
"ru": "Rusça" |
[
{
"context": "e you supporting your team tonight\n#\n# Author:\n# sagasu\n\n\nmodule.exports = (robot) ->\n robot.hear /Who w",
"end": 380,
"score": 0.9986496567726135,
"start": 374,
"tag": "USERNAME",
"value": "sagasu"
},
{
"context": "msg.send \"I'll be watching from my virtual ... | src/euro2016.coffee | sagasu/hubot-euro2016 | 0 | # Description:
# Funny answers to football euro 2016 questions. Based on various memes and videos that are available on internet.
#
# Commands:
# hubot who will be in euro final?
# hubot why Argentina is in Euro?
# hubot why Argentina will win
# hubot how do you know that Ronaldo plays for Argentina
# hubot are you supporting your team tonight
#
# Author:
# sagasu
module.exports = (robot) ->
robot.hear /Who will be in euro final/i, (msg) ->
msg.send "Argentina vs South Africa"
robot.hear /why Argentina is in Euro/i, (msg) ->
msg.send "Because it is located next to Poland, mate! :flag-pl: :flag-pl:"
robot.hear /why Argentina will win/i, (msg) ->
msg.send "Because Ronaldo plays for them. You didn't know?"
robot.hear /how do you know that Ronaldo plays for Argentina/i, (msg) ->
msg.send "Because he has tan, mate!"
robot.hear /are you supporting your team tonight/i, (msg) ->
msg.send "I'll be watching from my virtual home dr Matt gave me. But my birds told me that there is a cool team going tonight to watch the game. Talk to Matts x2, don't be Andy come and join us! :flag-pl: :flag-pl:" | 106420 | # Description:
# Funny answers to football euro 2016 questions. Based on various memes and videos that are available on internet.
#
# Commands:
# hubot who will be in euro final?
# hubot why Argentina is in Euro?
# hubot why Argentina will win
# hubot how do you know that Ronaldo plays for Argentina
# hubot are you supporting your team tonight
#
# Author:
# sagasu
module.exports = (robot) ->
robot.hear /Who will be in euro final/i, (msg) ->
msg.send "Argentina vs South Africa"
robot.hear /why Argentina is in Euro/i, (msg) ->
msg.send "Because it is located next to Poland, mate! :flag-pl: :flag-pl:"
robot.hear /why Argentina will win/i, (msg) ->
msg.send "Because Ronaldo plays for them. You didn't know?"
robot.hear /how do you know that Ronaldo plays for Argentina/i, (msg) ->
msg.send "Because he has tan, mate!"
robot.hear /are you supporting your team tonight/i, (msg) ->
msg.send "I'll be watching from my virtual home dr <NAME>att gave me. But my birds told me that there is a cool team going tonight to watch the game. Talk to Matts x2, don't be Andy come and join us! :flag-pl: :flag-pl:" | true | # Description:
# Funny answers to football euro 2016 questions. Based on various memes and videos that are available on internet.
#
# Commands:
# hubot who will be in euro final?
# hubot why Argentina is in Euro?
# hubot why Argentina will win
# hubot how do you know that Ronaldo plays for Argentina
# hubot are you supporting your team tonight
#
# Author:
# sagasu
module.exports = (robot) ->
robot.hear /Who will be in euro final/i, (msg) ->
msg.send "Argentina vs South Africa"
robot.hear /why Argentina is in Euro/i, (msg) ->
msg.send "Because it is located next to Poland, mate! :flag-pl: :flag-pl:"
robot.hear /why Argentina will win/i, (msg) ->
msg.send "Because Ronaldo plays for them. You didn't know?"
robot.hear /how do you know that Ronaldo plays for Argentina/i, (msg) ->
msg.send "Because he has tan, mate!"
robot.hear /are you supporting your team tonight/i, (msg) ->
msg.send "I'll be watching from my virtual home dr PI:NAME:<NAME>END_PIatt gave me. But my birds told me that there is a cool team going tonight to watch the game. Talk to Matts x2, don't be Andy come and join us! :flag-pl: :flag-pl:" |
[
{
"context": "pcConfig = {\n iceServers: [\n url: 'turn:hackathon@s3-lon.mnsbone.net',\n# url: 'turn:s3-lon.mnsbone.net'\n ",
"end": 169,
"score": 0.9983639121055603,
"start": 141,
"tag": "EMAIL",
"value": "hackathon@s3-lon.mnsbone.net"
},
{
"context": "l: 'tur... | src/client/modules/rtc.coffee | LaPingvino/rizzoma | 88 | Request = require('../../share/communication').Request
DomUtils = require('../utils/dom')
pcConfig = {
iceServers: [
url: 'turn:hackathon@s3-lon.mnsbone.net',
# url: 'turn:s3-lon.mnsbone.net'
credential: 'Turn4Hack'
# username: 'hackathon'
]
}
sdpConstraints =
mandatory:
OfferToReceiveAudio: yes
OfferToReceiveVideo: yes
pcConstraints = {"optional": [{"DtlsSrtpKeyAgreement": true}]};
offerConstraints = {"optional": [], "mandatory": {}};
tmpl = ->
div {id: 'videoContainer', ondblclick: 'enterFullScreen()'}, ->
style '''
#videoContainer {
background-color: #000000;
position: absolute;
bottom: 200px;
margin: 0px auto;
-webkit-perspective: 1000;
width: 100%;
min-height: 200px;
z-index: 200;
}
.tips-hidden #videoContainer {
bottom: 81px;
}
#card {
-webkit-transition-property: rotation;
-webkit-transition-duration: 2s;
-webkit-transform-style: preserve-3d;
}
#local {
position: absolute;
width: 100%;
-webkit-transform: scale(-1, 1);
-webkit-backface-visibility: hidden;
}
#remote {
position: absolute;
width: 100%;
}
#mini {
position: absolute;
height: 30%;
width: 30%;
bottom: 32px;
right: 4px;
-webkit-transform: scale(-1, 1);
opacity: 1.0;
}
#localVideo {
width: 100%;
height: 100%;
opacity: 0;
-webkit-transition-property: opacity;
-webkit-transition-duration: 2s;
}
#remoteVideo {
width: 100%;
height: 100%;
opacity: 0;
-webkit-transition-property: opacity;
-webkit-transition-duration: 2s;
}
#miniVideo {
width: 100%;
height: 100%;
opacity: 0;
-webkit-transition-property: opacity;
-webkit-transition-duration: 2s;
}
#hangup {
font-size: 13px; font-weight: bold;
color: #FFFFFF;
width: 128px;
height: 24px;
background-color: #808080;
border-style: solid;
border-color: #FFFFFF;
margin: 2px;
}
'''
div id:"card", ->
div id:"local", ->
video {id: "localVideo", autoplay: "autoplay", muted: "true"}, ->
div id:"remote", ->
video {id: "remoteVideo", autoplay: "autoplay"}, ->
div id: "mini", ->
video {id: "miniVideo", autoplay: "autoplay", muted: "true"}, ->
renderTmpl = window.CoffeeKup.compile(tmpl)
mergeConstraints = (cons1, cons2) ->
merged = cons1;
for name of cons2.mandatory
merged.mandatory[name] = cons2.mandatory[name];
merged.optional.concat(cons2.optional);
return merged;
extractSdp = (sdpLine, pattern) ->
result = sdpLine.match(pattern)
if (result && result.length == 2) then result[1] else null
setDefaultCodec = (mLine, payload) ->
elements = mLine.split(' ')
newLine = new Array();
index = 0;
for element in elements
if (index is 3) # Format of media starts from the fourth.
newLine[index++] = payload; # Put target payload to the first.
if (element isnt payload)
newLine[index++] = element;
newLine.join(' ')
removeCN = (sdpLines, mLineIndex) ->
mLineElements = sdpLines[mLineIndex].split(' ')
# Scan from end for the convenience of removing an item.
for i in [sdpLines.length- 1..0]
payload = extractSdp(sdpLines[i], /a=rtpmap:(\d+) CN\/\d+/i)
if (payload)
cnPos = mLineElements.indexOf(payload)
if (cnPos isnt -1)
# Remove CN payload from m line.
mLineElements.splice(cnPos, 1)
# Remove CN line in sdp
sdpLines.splice(i, 1)
sdpLines[mLineIndex] = mLineElements.join(' ')
sdpLines
preferOpus = (sdp) ->
sdpLines = sdp.split('\r\n');
# Search for m line.
for sdpLine, i in sdpLines
if (sdpLine.search('m=audio') isnt -1)
mLineIndex = i;
break;
if (mLineIndex is null)
return sdp;
# If Opus is available, set it as the default in m line.
for sdpLine in sdpLines
if (sdpLine.search('opus/48000') isnt -1)
opusPayload = extractSdp(sdpLine, /:(\d+) opus\/48000/i);
if (opusPayload)
sdpLines[mLineIndex] = setDefaultCodec(sdpLines[mLineIndex], opusPayload);
break
# Remove CN in m line and sdp.
sdpLines = removeCN(sdpLines, mLineIndex);
sdp = sdpLines.join('\r\n');
sdp
class WebRtc
constructor: (@_rootRouter) ->
@_localStream = null
@_remoteStream = null
@_pc = null
@_container = null
@_initiator = null
setTimeout =>
@_subscribeToMessages()
, 100
_resize: =>
console.log 'resize'
if (@_remoteVideo.style.opacity is '1')
aspectRatio = @_remoteVideo.videoWidth/@_remoteVideo.videoHeight;
else if (@_localVideo.style.opacity is '1')
aspectRatio = @_localVideo.videoWidth/@_localVideo.videoHeight;
else
console.error('return')
return
navPanel = document.getElementById('navigation-panel')
innerHeight = navPanel.offsetHeight;
innerWidth = navPanel.offsetWidth;
videoWidth = if innerWidth < aspectRatio * innerHeight then innerWidth else aspectRatio * innerHeight;
videoHeight = if innerHeight < innerWidth / aspectRatio then innerHeight else innerWidth / aspectRatio;
containerDiv = @_container
containerDiv.style.width = videoWidth + 'px';
containerDiv.style.height = videoHeight + 'px';
# containerDiv.style.left = (innerWidth - videoWidth) / 2 + 'px';
# containerDiv.style.top = (innerHeight - videoHeight) / 2 + 'px';
_showVideo: ->
if @_container
document.getElementById('navigation-panel').appendChild(@_container)
$(window).on('resize', @_resize)
span = document.createElement('span')
span.appendChild(DomUtils.parseFromString(renderTmpl()))
@_container = span.firstChild
document.getElementById('navigation-panel').appendChild(@_container)
# document.body.appendChild(@_container)
@_localVideo = document.getElementById('localVideo')
@_localVideo.addEventListener 'loadedmetadata', =>
@_resize()
@_miniVideo = document.getElementById('miniVideo')
@_remoteVideo = document.getElementById('remoteVideo')
@_card = document.getElementById('card')
_hideVideo: ->
@_container.parentNode.removeChild(@_container)
_attachLocalStream: (@_localStream) ->
@_showVideo()
attachMediaStream(@_localVideo, @_localStream);
@_localVideo.style.opacity = 1;
_sendMessage: (msg) ->
msg.waveId = @_waveId
msg.userId = @_userId
params =
waveId: @_waveId
toUserId: @_initiator || @_userId
message: JSON.stringify(msg)
callback = (err) ->
return console.error(err) if err
# console.log 'sending message', params
console.log 'sending message to', params.toUserId
request = new Request(params, callback)
request.setProperty('recallOnDisconnect', true)
@_rootRouter.handle('network.messaging.sendToUser', request)
_startCallingFlow: (waveId, userId) ->
@_waveId = waveId
@_userId = userId
requestUserMedia (err, stream) =>
if err
alert(err)
return
@_attachLocalStream(stream)
@_sendMessage({type: 'takeCall', fromUserId: window.userInfo.id})
_waitForRemoteVideo: =>
#Call the getVideoTracks method via adapter.js.
videoTracks = @_remoteStream.getVideoTracks()
if (videoTracks.length is 0 || @_remoteVideo.currentTime > 0)
@_transitionToActive();
else
setTimeout(@_waitForRemoteVideo, 100)
_transitionToActive: ->
console.warn 'transition to active'
console.log @_remoteVideo
@_remoteVideo.style.opacity = 1;
@_card.style.webkitTransform = 'rotateY(180deg)';
setTimeout =>
@_localVideo.src = ''
, 500
setTimeout =>
@_miniVideo.style.opacity = 1;
, 1000
# Reset window display according to the asperio of remote video.
@_resize()
# setStatus('<input type=\'button\' id=\'hangup\' value=\'Hang up\' \
# onclick=\'onHangup()\' />');
_onRemoteStreamAdded: (event) =>
console.warn('Remote stream added.');
reattachMediaStream(@_miniVideo, @_localVideo)
attachMediaStream(@_remoteVideo, event.stream)
@_remoteStream = event.stream;
@_waitForRemoteVideo()
_onRemoteStreamRemoved: ->
console.log('Remote stream removed.');
_onIceCandidate: (event) =>
console.log 'onIceCandidate', event
if event.candidate
@_sendMessage(
type: 'candidate',
label: event.candidate.sdpMLineIndex,
id: event.candidate.sdpMid,
candidate: event.candidate.candidate
)
else
console.log('End of candidates.');
_createPeerConnection: ->
try
# Create an RTCPeerConnection via the polyfill (adapter.js).
pc = new RTCPeerConnection(pcConfig, pcConstraints);
pc.onicecandidate = @_onIceCandidate
console.log('Created RTCPeerConnnection with:\n' +
' config: \'' + JSON.stringify(pcConfig) + '\';\n' +
' constraints: \'' + JSON.stringify(pcConstraints) + '\'.');
catch e
console.log('Failed to create PeerConnection, exception: ' + e.message);
alert('Cannot create RTCPeerConnection object; WebRTC is not supported by this browser.');
return;
pc.onaddstream = @_onRemoteStreamAdded
pc.onremovestream = @_onRemoteStreamRemoved
@_pc = pc
_setLocalAndSendMessage: (sessionDescription) =>
# Set Opus as the preferred codec in SDP if Opus is present.
# sessionDescription.sdp = preferOpus(sessionDescription.sdp) # TODO: preferOpus
@_pc.setLocalDescription(sessionDescription);
@_sendMessage(sessionDescription);
_respondToCall: ->
constraints = mergeConstraints(offerConstraints, sdpConstraints); # TODO: merge constraints
# constraints = sdpConstraints
console.log('Sending offer to peer, with constraints: \n' +
' \'' + JSON.stringify(constraints) + '\'.')
@_pc.createOffer(@_setLocalAndSendMessage, null, constraints);
_takeCall: (msg) ->
console.warn "taking a call from #{msg.waveId} and #{msg.userId}"
requestUserMedia (err, stream) =>
if err
alert(err)
return
@_attachLocalStream(stream)
@_createPeerConnection();
console.log('Adding local stream.')
@_pc.addStream(@_localStream)
@_initiator = msg.fromUserId
@_respondToCall()
_takeOffer: (msg) ->
console.warn "taking an offer from #{msg.waveId} and #{msg.userId}"
@_createPeerConnection()
# if (stereo)
# msg.sdp = addStereo(message.sdp); # TODO: addStereo
@_pc.setRemoteDescription(new RTCSessionDescription(msg));
console.log('Sending answer to peer, with constraints: \n' +
' \'' + JSON.stringify(sdpConstraints) + '\'.')
@_pc.createAnswer(@_setLocalAndSendMessage, null, sdpConstraints);
_takeAnswer: (msg) ->
console.log "taking an answer from #{msg.waveId} and #{msg.userId}", msg
# if (stereo)
# message.sdp = addStereo(message.sdp); # TODO: addStereo
@_pc.setRemoteDescription(new RTCSessionDescription(msg));
_takeCandidate: (msg) ->
console.log "taking a candidate from #{msg.waveId} and #{msg.userId}"
candidate = new RTCIceCandidate({sdpMLineIndex: msg.label, candidate: msg.candidate});
@_pc.addIceCandidate(candidate);
_handleMessage: (msg) ->
try
msg = JSON.parse(msg.message)
@_waveId = msg.waveId
@_userId = msg.userId
catch e
return console.error('Could not parse message', msg)
return unless msg
switch msg.type
when 'takeCall'
@_takeCall(msg)
when 'offer'
@_takeOffer(msg)
when 'answer'
@_takeAnswer(msg)
when 'candidate'
@_takeCandidate(msg)
else
console.error('Unknown message received', msg)
_subscribeToMessages: ->
processMsg = (err, msg) =>
return err if err
@_handleMessage(msg)
request = new Request({resource: @_resource = Math.random()}, processMsg)
request.setProperty('recallOnDisconnect', true)
request.setProperty('wait', true)
@_rootRouter.handle('network.messaging.subscribeUser', request)
callUser: (waveId, userId) -> @_startCallingFlow(waveId, userId)
module.exports =
WebRtc: WebRtc
instance: null | 196436 | Request = require('../../share/communication').Request
DomUtils = require('../utils/dom')
pcConfig = {
iceServers: [
url: 'turn:<EMAIL>',
# url: 'turn:s3-lon.mnsbone.net'
credential: 'Turn4Hack'
# username: 'hackathon'
]
}
sdpConstraints =
mandatory:
OfferToReceiveAudio: yes
OfferToReceiveVideo: yes
pcConstraints = {"optional": [{"DtlsSrtpKeyAgreement": true}]};
offerConstraints = {"optional": [], "mandatory": {}};
tmpl = ->
div {id: 'videoContainer', ondblclick: 'enterFullScreen()'}, ->
style '''
#videoContainer {
background-color: #000000;
position: absolute;
bottom: 200px;
margin: 0px auto;
-webkit-perspective: 1000;
width: 100%;
min-height: 200px;
z-index: 200;
}
.tips-hidden #videoContainer {
bottom: 81px;
}
#card {
-webkit-transition-property: rotation;
-webkit-transition-duration: 2s;
-webkit-transform-style: preserve-3d;
}
#local {
position: absolute;
width: 100%;
-webkit-transform: scale(-1, 1);
-webkit-backface-visibility: hidden;
}
#remote {
position: absolute;
width: 100%;
}
#mini {
position: absolute;
height: 30%;
width: 30%;
bottom: 32px;
right: 4px;
-webkit-transform: scale(-1, 1);
opacity: 1.0;
}
#localVideo {
width: 100%;
height: 100%;
opacity: 0;
-webkit-transition-property: opacity;
-webkit-transition-duration: 2s;
}
#remoteVideo {
width: 100%;
height: 100%;
opacity: 0;
-webkit-transition-property: opacity;
-webkit-transition-duration: 2s;
}
#miniVideo {
width: 100%;
height: 100%;
opacity: 0;
-webkit-transition-property: opacity;
-webkit-transition-duration: 2s;
}
#hangup {
font-size: 13px; font-weight: bold;
color: #FFFFFF;
width: 128px;
height: 24px;
background-color: #808080;
border-style: solid;
border-color: #FFFFFF;
margin: 2px;
}
'''
div id:"card", ->
div id:"local", ->
video {id: "localVideo", autoplay: "autoplay", muted: "true"}, ->
div id:"remote", ->
video {id: "remoteVideo", autoplay: "autoplay"}, ->
div id: "mini", ->
video {id: "miniVideo", autoplay: "autoplay", muted: "true"}, ->
renderTmpl = window.CoffeeKup.compile(tmpl)
mergeConstraints = (cons1, cons2) ->
merged = cons1;
for name of cons2.mandatory
merged.mandatory[name] = cons2.mandatory[name];
merged.optional.concat(cons2.optional);
return merged;
extractSdp = (sdpLine, pattern) ->
result = sdpLine.match(pattern)
if (result && result.length == 2) then result[1] else null
setDefaultCodec = (mLine, payload) ->
elements = mLine.split(' ')
newLine = new Array();
index = 0;
for element in elements
if (index is 3) # Format of media starts from the fourth.
newLine[index++] = payload; # Put target payload to the first.
if (element isnt payload)
newLine[index++] = element;
newLine.join(' ')
removeCN = (sdpLines, mLineIndex) ->
mLineElements = sdpLines[mLineIndex].split(' ')
# Scan from end for the convenience of removing an item.
for i in [sdpLines.length- 1..0]
payload = extractSdp(sdpLines[i], /a=rtpmap:(\d+) CN\/\d+/i)
if (payload)
cnPos = mLineElements.indexOf(payload)
if (cnPos isnt -1)
# Remove CN payload from m line.
mLineElements.splice(cnPos, 1)
# Remove CN line in sdp
sdpLines.splice(i, 1)
sdpLines[mLineIndex] = mLineElements.join(' ')
sdpLines
preferOpus = (sdp) ->
sdpLines = sdp.split('\r\n');
# Search for m line.
for sdpLine, i in sdpLines
if (sdpLine.search('m=audio') isnt -1)
mLineIndex = i;
break;
if (mLineIndex is null)
return sdp;
# If Opus is available, set it as the default in m line.
for sdpLine in sdpLines
if (sdpLine.search('opus/48000') isnt -1)
opusPayload = extractSdp(sdpLine, /:(\d+) opus\/48000/i);
if (opusPayload)
sdpLines[mLineIndex] = setDefaultCodec(sdpLines[mLineIndex], opusPayload);
break
# Remove CN in m line and sdp.
sdpLines = removeCN(sdpLines, mLineIndex);
sdp = sdpLines.join('\r\n');
sdp
class WebRtc
constructor: (@_rootRouter) ->
@_localStream = null
@_remoteStream = null
@_pc = null
@_container = null
@_initiator = null
setTimeout =>
@_subscribeToMessages()
, 100
_resize: =>
console.log 'resize'
if (@_remoteVideo.style.opacity is '1')
aspectRatio = @_remoteVideo.videoWidth/@_remoteVideo.videoHeight;
else if (@_localVideo.style.opacity is '1')
aspectRatio = @_localVideo.videoWidth/@_localVideo.videoHeight;
else
console.error('return')
return
navPanel = document.getElementById('navigation-panel')
innerHeight = navPanel.offsetHeight;
innerWidth = navPanel.offsetWidth;
videoWidth = if innerWidth < aspectRatio * innerHeight then innerWidth else aspectRatio * innerHeight;
videoHeight = if innerHeight < innerWidth / aspectRatio then innerHeight else innerWidth / aspectRatio;
containerDiv = @_container
containerDiv.style.width = videoWidth + 'px';
containerDiv.style.height = videoHeight + 'px';
# containerDiv.style.left = (innerWidth - videoWidth) / 2 + 'px';
# containerDiv.style.top = (innerHeight - videoHeight) / 2 + 'px';
_showVideo: ->
if @_container
document.getElementById('navigation-panel').appendChild(@_container)
$(window).on('resize', @_resize)
span = document.createElement('span')
span.appendChild(DomUtils.parseFromString(renderTmpl()))
@_container = span.firstChild
document.getElementById('navigation-panel').appendChild(@_container)
# document.body.appendChild(@_container)
@_localVideo = document.getElementById('localVideo')
@_localVideo.addEventListener 'loadedmetadata', =>
@_resize()
@_miniVideo = document.getElementById('miniVideo')
@_remoteVideo = document.getElementById('remoteVideo')
@_card = document.getElementById('card')
_hideVideo: ->
@_container.parentNode.removeChild(@_container)
_attachLocalStream: (@_localStream) ->
@_showVideo()
attachMediaStream(@_localVideo, @_localStream);
@_localVideo.style.opacity = 1;
_sendMessage: (msg) ->
msg.waveId = @_waveId
msg.userId = @_userId
params =
waveId: @_waveId
toUserId: @_initiator || @_userId
message: JSON.stringify(msg)
callback = (err) ->
return console.error(err) if err
# console.log 'sending message', params
console.log 'sending message to', params.toUserId
request = new Request(params, callback)
request.setProperty('recallOnDisconnect', true)
@_rootRouter.handle('network.messaging.sendToUser', request)
_startCallingFlow: (waveId, userId) ->
@_waveId = waveId
@_userId = userId
requestUserMedia (err, stream) =>
if err
alert(err)
return
@_attachLocalStream(stream)
@_sendMessage({type: 'takeCall', fromUserId: window.userInfo.id})
_waitForRemoteVideo: =>
#Call the getVideoTracks method via adapter.js.
videoTracks = @_remoteStream.getVideoTracks()
if (videoTracks.length is 0 || @_remoteVideo.currentTime > 0)
@_transitionToActive();
else
setTimeout(@_waitForRemoteVideo, 100)
_transitionToActive: ->
console.warn 'transition to active'
console.log @_remoteVideo
@_remoteVideo.style.opacity = 1;
@_card.style.webkitTransform = 'rotateY(180deg)';
setTimeout =>
@_localVideo.src = ''
, 500
setTimeout =>
@_miniVideo.style.opacity = 1;
, 1000
# Reset window display according to the asperio of remote video.
@_resize()
# setStatus('<input type=\'button\' id=\'hangup\' value=\'Hang up\' \
# onclick=\'onHangup()\' />');
_onRemoteStreamAdded: (event) =>
console.warn('Remote stream added.');
reattachMediaStream(@_miniVideo, @_localVideo)
attachMediaStream(@_remoteVideo, event.stream)
@_remoteStream = event.stream;
@_waitForRemoteVideo()
_onRemoteStreamRemoved: ->
console.log('Remote stream removed.');
_onIceCandidate: (event) =>
console.log 'onIceCandidate', event
if event.candidate
@_sendMessage(
type: 'candidate',
label: event.candidate.sdpMLineIndex,
id: event.candidate.sdpMid,
candidate: event.candidate.candidate
)
else
console.log('End of candidates.');
_createPeerConnection: ->
try
# Create an RTCPeerConnection via the polyfill (adapter.js).
pc = new RTCPeerConnection(pcConfig, pcConstraints);
pc.onicecandidate = @_onIceCandidate
console.log('Created RTCPeerConnnection with:\n' +
' config: \'' + JSON.stringify(pcConfig) + '\';\n' +
' constraints: \'' + JSON.stringify(pcConstraints) + '\'.');
catch e
console.log('Failed to create PeerConnection, exception: ' + e.message);
alert('Cannot create RTCPeerConnection object; WebRTC is not supported by this browser.');
return;
pc.onaddstream = @_onRemoteStreamAdded
pc.onremovestream = @_onRemoteStreamRemoved
@_pc = pc
_setLocalAndSendMessage: (sessionDescription) =>
# Set Opus as the preferred codec in SDP if Opus is present.
# sessionDescription.sdp = preferOpus(sessionDescription.sdp) # TODO: preferOpus
@_pc.setLocalDescription(sessionDescription);
@_sendMessage(sessionDescription);
_respondToCall: ->
constraints = mergeConstraints(offerConstraints, sdpConstraints); # TODO: merge constraints
# constraints = sdpConstraints
console.log('Sending offer to peer, with constraints: \n' +
' \'' + JSON.stringify(constraints) + '\'.')
@_pc.createOffer(@_setLocalAndSendMessage, null, constraints);
_takeCall: (msg) ->
console.warn "taking a call from #{msg.waveId} and #{msg.userId}"
requestUserMedia (err, stream) =>
if err
alert(err)
return
@_attachLocalStream(stream)
@_createPeerConnection();
console.log('Adding local stream.')
@_pc.addStream(@_localStream)
@_initiator = msg.fromUserId
@_respondToCall()
_takeOffer: (msg) ->
console.warn "taking an offer from #{msg.waveId} and #{msg.userId}"
@_createPeerConnection()
# if (stereo)
# msg.sdp = addStereo(message.sdp); # TODO: addStereo
@_pc.setRemoteDescription(new RTCSessionDescription(msg));
console.log('Sending answer to peer, with constraints: \n' +
' \'' + JSON.stringify(sdpConstraints) + '\'.')
@_pc.createAnswer(@_setLocalAndSendMessage, null, sdpConstraints);
_takeAnswer: (msg) ->
console.log "taking an answer from #{msg.waveId} and #{msg.userId}", msg
# if (stereo)
# message.sdp = addStereo(message.sdp); # TODO: addStereo
@_pc.setRemoteDescription(new RTCSessionDescription(msg));
_takeCandidate: (msg) ->
console.log "taking a candidate from #{msg.waveId} and #{msg.userId}"
candidate = new RTCIceCandidate({sdpMLineIndex: msg.label, candidate: msg.candidate});
@_pc.addIceCandidate(candidate);
_handleMessage: (msg) ->
try
msg = JSON.parse(msg.message)
@_waveId = msg.waveId
@_userId = msg.userId
catch e
return console.error('Could not parse message', msg)
return unless msg
switch msg.type
when 'takeCall'
@_takeCall(msg)
when 'offer'
@_takeOffer(msg)
when 'answer'
@_takeAnswer(msg)
when 'candidate'
@_takeCandidate(msg)
else
console.error('Unknown message received', msg)
_subscribeToMessages: ->
processMsg = (err, msg) =>
return err if err
@_handleMessage(msg)
request = new Request({resource: @_resource = Math.random()}, processMsg)
request.setProperty('recallOnDisconnect', true)
request.setProperty('wait', true)
@_rootRouter.handle('network.messaging.subscribeUser', request)
callUser: (waveId, userId) -> @_startCallingFlow(waveId, userId)
module.exports =
WebRtc: WebRtc
instance: null | true | Request = require('../../share/communication').Request
DomUtils = require('../utils/dom')
pcConfig = {
iceServers: [
url: 'turn:PI:EMAIL:<EMAIL>END_PI',
# url: 'turn:s3-lon.mnsbone.net'
credential: 'Turn4Hack'
# username: 'hackathon'
]
}
sdpConstraints =
mandatory:
OfferToReceiveAudio: yes
OfferToReceiveVideo: yes
pcConstraints = {"optional": [{"DtlsSrtpKeyAgreement": true}]};
offerConstraints = {"optional": [], "mandatory": {}};
tmpl = ->
div {id: 'videoContainer', ondblclick: 'enterFullScreen()'}, ->
style '''
#videoContainer {
background-color: #000000;
position: absolute;
bottom: 200px;
margin: 0px auto;
-webkit-perspective: 1000;
width: 100%;
min-height: 200px;
z-index: 200;
}
.tips-hidden #videoContainer {
bottom: 81px;
}
#card {
-webkit-transition-property: rotation;
-webkit-transition-duration: 2s;
-webkit-transform-style: preserve-3d;
}
#local {
position: absolute;
width: 100%;
-webkit-transform: scale(-1, 1);
-webkit-backface-visibility: hidden;
}
#remote {
position: absolute;
width: 100%;
}
#mini {
position: absolute;
height: 30%;
width: 30%;
bottom: 32px;
right: 4px;
-webkit-transform: scale(-1, 1);
opacity: 1.0;
}
#localVideo {
width: 100%;
height: 100%;
opacity: 0;
-webkit-transition-property: opacity;
-webkit-transition-duration: 2s;
}
#remoteVideo {
width: 100%;
height: 100%;
opacity: 0;
-webkit-transition-property: opacity;
-webkit-transition-duration: 2s;
}
#miniVideo {
width: 100%;
height: 100%;
opacity: 0;
-webkit-transition-property: opacity;
-webkit-transition-duration: 2s;
}
#hangup {
font-size: 13px; font-weight: bold;
color: #FFFFFF;
width: 128px;
height: 24px;
background-color: #808080;
border-style: solid;
border-color: #FFFFFF;
margin: 2px;
}
'''
div id:"card", ->
div id:"local", ->
video {id: "localVideo", autoplay: "autoplay", muted: "true"}, ->
div id:"remote", ->
video {id: "remoteVideo", autoplay: "autoplay"}, ->
div id: "mini", ->
video {id: "miniVideo", autoplay: "autoplay", muted: "true"}, ->
renderTmpl = window.CoffeeKup.compile(tmpl)
mergeConstraints = (cons1, cons2) ->
merged = cons1;
for name of cons2.mandatory
merged.mandatory[name] = cons2.mandatory[name];
merged.optional.concat(cons2.optional);
return merged;
extractSdp = (sdpLine, pattern) ->
result = sdpLine.match(pattern)
if (result && result.length == 2) then result[1] else null
setDefaultCodec = (mLine, payload) ->
elements = mLine.split(' ')
newLine = new Array();
index = 0;
for element in elements
if (index is 3) # Format of media starts from the fourth.
newLine[index++] = payload; # Put target payload to the first.
if (element isnt payload)
newLine[index++] = element;
newLine.join(' ')
removeCN = (sdpLines, mLineIndex) ->
mLineElements = sdpLines[mLineIndex].split(' ')
# Scan from end for the convenience of removing an item.
for i in [sdpLines.length- 1..0]
payload = extractSdp(sdpLines[i], /a=rtpmap:(\d+) CN\/\d+/i)
if (payload)
cnPos = mLineElements.indexOf(payload)
if (cnPos isnt -1)
# Remove CN payload from m line.
mLineElements.splice(cnPos, 1)
# Remove CN line in sdp
sdpLines.splice(i, 1)
sdpLines[mLineIndex] = mLineElements.join(' ')
sdpLines
preferOpus = (sdp) ->
sdpLines = sdp.split('\r\n');
# Search for m line.
for sdpLine, i in sdpLines
if (sdpLine.search('m=audio') isnt -1)
mLineIndex = i;
break;
if (mLineIndex is null)
return sdp;
# If Opus is available, set it as the default in m line.
for sdpLine in sdpLines
if (sdpLine.search('opus/48000') isnt -1)
opusPayload = extractSdp(sdpLine, /:(\d+) opus\/48000/i);
if (opusPayload)
sdpLines[mLineIndex] = setDefaultCodec(sdpLines[mLineIndex], opusPayload);
break
# Remove CN in m line and sdp.
sdpLines = removeCN(sdpLines, mLineIndex);
sdp = sdpLines.join('\r\n');
sdp
class WebRtc
constructor: (@_rootRouter) ->
@_localStream = null
@_remoteStream = null
@_pc = null
@_container = null
@_initiator = null
setTimeout =>
@_subscribeToMessages()
, 100
_resize: =>
console.log 'resize'
if (@_remoteVideo.style.opacity is '1')
aspectRatio = @_remoteVideo.videoWidth/@_remoteVideo.videoHeight;
else if (@_localVideo.style.opacity is '1')
aspectRatio = @_localVideo.videoWidth/@_localVideo.videoHeight;
else
console.error('return')
return
navPanel = document.getElementById('navigation-panel')
innerHeight = navPanel.offsetHeight;
innerWidth = navPanel.offsetWidth;
videoWidth = if innerWidth < aspectRatio * innerHeight then innerWidth else aspectRatio * innerHeight;
videoHeight = if innerHeight < innerWidth / aspectRatio then innerHeight else innerWidth / aspectRatio;
containerDiv = @_container
containerDiv.style.width = videoWidth + 'px';
containerDiv.style.height = videoHeight + 'px';
# containerDiv.style.left = (innerWidth - videoWidth) / 2 + 'px';
# containerDiv.style.top = (innerHeight - videoHeight) / 2 + 'px';
_showVideo: ->
if @_container
document.getElementById('navigation-panel').appendChild(@_container)
$(window).on('resize', @_resize)
span = document.createElement('span')
span.appendChild(DomUtils.parseFromString(renderTmpl()))
@_container = span.firstChild
document.getElementById('navigation-panel').appendChild(@_container)
# document.body.appendChild(@_container)
@_localVideo = document.getElementById('localVideo')
@_localVideo.addEventListener 'loadedmetadata', =>
@_resize()
@_miniVideo = document.getElementById('miniVideo')
@_remoteVideo = document.getElementById('remoteVideo')
@_card = document.getElementById('card')
_hideVideo: ->
@_container.parentNode.removeChild(@_container)
_attachLocalStream: (@_localStream) ->
@_showVideo()
attachMediaStream(@_localVideo, @_localStream);
@_localVideo.style.opacity = 1;
_sendMessage: (msg) ->
msg.waveId = @_waveId
msg.userId = @_userId
params =
waveId: @_waveId
toUserId: @_initiator || @_userId
message: JSON.stringify(msg)
callback = (err) ->
return console.error(err) if err
# console.log 'sending message', params
console.log 'sending message to', params.toUserId
request = new Request(params, callback)
request.setProperty('recallOnDisconnect', true)
@_rootRouter.handle('network.messaging.sendToUser', request)
_startCallingFlow: (waveId, userId) ->
@_waveId = waveId
@_userId = userId
requestUserMedia (err, stream) =>
if err
alert(err)
return
@_attachLocalStream(stream)
@_sendMessage({type: 'takeCall', fromUserId: window.userInfo.id})
_waitForRemoteVideo: =>
#Call the getVideoTracks method via adapter.js.
videoTracks = @_remoteStream.getVideoTracks()
if (videoTracks.length is 0 || @_remoteVideo.currentTime > 0)
@_transitionToActive();
else
setTimeout(@_waitForRemoteVideo, 100)
_transitionToActive: ->
console.warn 'transition to active'
console.log @_remoteVideo
@_remoteVideo.style.opacity = 1;
@_card.style.webkitTransform = 'rotateY(180deg)';
setTimeout =>
@_localVideo.src = ''
, 500
setTimeout =>
@_miniVideo.style.opacity = 1;
, 1000
# Reset window display according to the asperio of remote video.
@_resize()
# setStatus('<input type=\'button\' id=\'hangup\' value=\'Hang up\' \
# onclick=\'onHangup()\' />');
_onRemoteStreamAdded: (event) =>
console.warn('Remote stream added.');
reattachMediaStream(@_miniVideo, @_localVideo)
attachMediaStream(@_remoteVideo, event.stream)
@_remoteStream = event.stream;
@_waitForRemoteVideo()
_onRemoteStreamRemoved: ->
console.log('Remote stream removed.');
_onIceCandidate: (event) =>
console.log 'onIceCandidate', event
if event.candidate
@_sendMessage(
type: 'candidate',
label: event.candidate.sdpMLineIndex,
id: event.candidate.sdpMid,
candidate: event.candidate.candidate
)
else
console.log('End of candidates.');
_createPeerConnection: ->
try
# Create an RTCPeerConnection via the polyfill (adapter.js).
pc = new RTCPeerConnection(pcConfig, pcConstraints);
pc.onicecandidate = @_onIceCandidate
console.log('Created RTCPeerConnnection with:\n' +
' config: \'' + JSON.stringify(pcConfig) + '\';\n' +
' constraints: \'' + JSON.stringify(pcConstraints) + '\'.');
catch e
console.log('Failed to create PeerConnection, exception: ' + e.message);
alert('Cannot create RTCPeerConnection object; WebRTC is not supported by this browser.');
return;
pc.onaddstream = @_onRemoteStreamAdded
pc.onremovestream = @_onRemoteStreamRemoved
@_pc = pc
_setLocalAndSendMessage: (sessionDescription) =>
# Set Opus as the preferred codec in SDP if Opus is present.
# sessionDescription.sdp = preferOpus(sessionDescription.sdp) # TODO: preferOpus
@_pc.setLocalDescription(sessionDescription);
@_sendMessage(sessionDescription);
_respondToCall: ->
constraints = mergeConstraints(offerConstraints, sdpConstraints); # TODO: merge constraints
# constraints = sdpConstraints
console.log('Sending offer to peer, with constraints: \n' +
' \'' + JSON.stringify(constraints) + '\'.')
@_pc.createOffer(@_setLocalAndSendMessage, null, constraints);
_takeCall: (msg) ->
console.warn "taking a call from #{msg.waveId} and #{msg.userId}"
requestUserMedia (err, stream) =>
if err
alert(err)
return
@_attachLocalStream(stream)
@_createPeerConnection();
console.log('Adding local stream.')
@_pc.addStream(@_localStream)
@_initiator = msg.fromUserId
@_respondToCall()
_takeOffer: (msg) ->
console.warn "taking an offer from #{msg.waveId} and #{msg.userId}"
@_createPeerConnection()
# if (stereo)
# msg.sdp = addStereo(message.sdp); # TODO: addStereo
@_pc.setRemoteDescription(new RTCSessionDescription(msg));
console.log('Sending answer to peer, with constraints: \n' +
' \'' + JSON.stringify(sdpConstraints) + '\'.')
@_pc.createAnswer(@_setLocalAndSendMessage, null, sdpConstraints);
_takeAnswer: (msg) ->
console.log "taking an answer from #{msg.waveId} and #{msg.userId}", msg
# if (stereo)
# message.sdp = addStereo(message.sdp); # TODO: addStereo
@_pc.setRemoteDescription(new RTCSessionDescription(msg));
_takeCandidate: (msg) ->
console.log "taking a candidate from #{msg.waveId} and #{msg.userId}"
candidate = new RTCIceCandidate({sdpMLineIndex: msg.label, candidate: msg.candidate});
@_pc.addIceCandidate(candidate);
_handleMessage: (msg) ->
try
msg = JSON.parse(msg.message)
@_waveId = msg.waveId
@_userId = msg.userId
catch e
return console.error('Could not parse message', msg)
return unless msg
switch msg.type
when 'takeCall'
@_takeCall(msg)
when 'offer'
@_takeOffer(msg)
when 'answer'
@_takeAnswer(msg)
when 'candidate'
@_takeCandidate(msg)
else
console.error('Unknown message received', msg)
_subscribeToMessages: ->
processMsg = (err, msg) =>
return err if err
@_handleMessage(msg)
request = new Request({resource: @_resource = Math.random()}, processMsg)
request.setProperty('recallOnDisconnect', true)
request.setProperty('wait', true)
@_rootRouter.handle('network.messaging.subscribeUser', request)
callUser: (waveId, userId) -> @_startCallingFlow(waveId, userId)
module.exports =
WebRtc: WebRtc
instance: null |
[
{
"context": "# Copyright (c) Konode. All rights reserved.\n# This source code is subje",
"end": 22,
"score": 0.9935299754142761,
"start": 16,
"tag": "NAME",
"value": "Konode"
}
] | src/clientFilePage/entryDateNavigator.coffee | LogicalOutcomes/KoNote | 1 | # Copyright (c) Konode. All rights reserved.
# This source code is subject to the terms of the Mozilla Public License, v. 2.0
# that can be found in the LICENSE file or at: http://mozilla.org/MPL/2.0
# Button that pops up a calendar, allowing the user to select a specific date
# The enabled/selectable dates are populated by @props.historyEntries
# Scrolling functionality is handled internally by EntriesListView
# TODO: Actively follow entriesList scroll with calendar view representation
Imm = require 'immutable'
Async = require 'async'
load = (win) ->
$ = win.jQuery
React = win.React
{PropTypes} = React
R = React.DOM
{FaIcon, makeMoment} = require('../utils').load(win)
EntryDateNavigator = React.createFactory React.createClass
displayName: 'EntryDateNavigator'
propTypes: {
historyEntries: PropTypes.instanceOf(Imm.List)
onSelect: PropTypes.func.isRequired
}
getDefaultProps: -> {
historyEntries: Imm.List()
onSelect: ->
}
getInitialState: -> {
isScrolling: false
}
componentWillUnmount: ->
@datetimepicker.destroy() if @datetimepicker?
componentDidUpdate: (oldProps, oldState) ->
# Re-init enabledDates when historyEntries has changed
# TODO: Use enabledDates API funct (currently doesn't work)
unless Imm.is oldProps.historyEntries, @props.historyEntries
console.log "Refreshing entryDateNavigator"
@_initDateTimePicker()
_generateEnabledDates: (historyEntries) ->
# TODO: Disable selection of any month within min->max whose days are all disabled
return historyEntries.map (e) -> makeMoment(e.get 'timestamp').startOf 'day'
_initDateTimePicker: (props) ->
# Destroy any pre-existing instance
@datetimepicker.destroy() if @datetimepicker?
if @props.historyEntries.isEmpty()
console.warn "Cancelled datetimepicker init, historyEntries is empty"
return
enabledDates = @props.historyEntries.map (e) -> makeMoment(e.get 'timestamp').startOf 'day'
# historyEntries are in reverse-order
minDate = enabledDates.last()
maxDate = enabledDates.first()
# Show the largest viewMode required to start selecting
viewMode = if minDate.isSame(maxDate, 'month')
'days'
else if minDate.isSame(maxDate, 'year')
'months'
else
'years'
# Block phantom 'onChange' from firing during init
@_tempDisableChangeEvent()
$input = $(@refs.hiddenInput)
$input.datetimepicker({
keepOpen: true
debug: true
format: 'YYYY-MM-DD'
enabledDates: enabledDates.toJS()
useCurrent: false
minDate
maxDate
widgetPositioning: {
horizontal: 'left'
vertical: 'top'
}
widgetParent: '#navigatorWrapper'
viewMode: 'years'
})
.on 'dp.change', ({date}) =>
# Prevent invalid/duplicate calls of @_skipToEntryDate
return if not date or @disableChange
# TODO: Detect month (< >) changes to follow with scroll
@_skipToEntryDate(date)
@datetimepicker = $input.data('DateTimePicker')
_skipToEntryDate: (date) ->
# Update the icon with an animated spinner while isScrolling
# Give spinner a chance to start spinning first
Async.series [
(cb) => @setState {isScrolling: true}, -> setTimeout(cb, 50)
(cb) => @props.onSelect(date, cb)
(cb) => @setState {isScrolling: false}, cb
], (err) =>
if err
throw new Error(err)
return
_tempDisableChangeEvent: ->
# Temporarily disable datetimepicker's 'change' event from firing
# This overrides default behaviour causing more events than needed
@disableChange = true
setTimeout (=> @disableChange = false), 500
_handleClick: ->
# Save on window.load perf by only mounting datetimepicker when used
@_initDateTimePicker() unless @datetimepicker?
@_tempDisableChangeEvent()
@datetimepicker.toggle()
_handleBlur: ->
@datetimepicker.hide() if @datetimepicker?
render: ->
{isScrolling} = @state
icon = if isScrolling then 'refresh fa-spin fa-fw' else 'sort'
R.div({id: 'entryDateNavigator'},
R.div({id: 'navigatorWrapper'},
R.input({ref: 'hiddenInput'})
R.button({
ref: 'button'
onClick: @_handleClick unless isScrolling
onBlur: @_handleBlur
className: [
'btn btn-default btn-xs'
'isScrolling' if isScrolling
].join ' '
},
FaIcon(icon)
)
)
)
return EntryDateNavigator
module.exports = {load}
| 185330 | # Copyright (c) <NAME>. All rights reserved.
# This source code is subject to the terms of the Mozilla Public License, v. 2.0
# that can be found in the LICENSE file or at: http://mozilla.org/MPL/2.0
# Button that pops up a calendar, allowing the user to select a specific date
# The enabled/selectable dates are populated by @props.historyEntries
# Scrolling functionality is handled internally by EntriesListView
# TODO: Actively follow entriesList scroll with calendar view representation
Imm = require 'immutable'
Async = require 'async'
load = (win) ->
$ = win.jQuery
React = win.React
{PropTypes} = React
R = React.DOM
{FaIcon, makeMoment} = require('../utils').load(win)
EntryDateNavigator = React.createFactory React.createClass
displayName: 'EntryDateNavigator'
propTypes: {
historyEntries: PropTypes.instanceOf(Imm.List)
onSelect: PropTypes.func.isRequired
}
getDefaultProps: -> {
historyEntries: Imm.List()
onSelect: ->
}
getInitialState: -> {
isScrolling: false
}
componentWillUnmount: ->
@datetimepicker.destroy() if @datetimepicker?
componentDidUpdate: (oldProps, oldState) ->
# Re-init enabledDates when historyEntries has changed
# TODO: Use enabledDates API funct (currently doesn't work)
unless Imm.is oldProps.historyEntries, @props.historyEntries
console.log "Refreshing entryDateNavigator"
@_initDateTimePicker()
_generateEnabledDates: (historyEntries) ->
# TODO: Disable selection of any month within min->max whose days are all disabled
return historyEntries.map (e) -> makeMoment(e.get 'timestamp').startOf 'day'
_initDateTimePicker: (props) ->
# Destroy any pre-existing instance
@datetimepicker.destroy() if @datetimepicker?
if @props.historyEntries.isEmpty()
console.warn "Cancelled datetimepicker init, historyEntries is empty"
return
enabledDates = @props.historyEntries.map (e) -> makeMoment(e.get 'timestamp').startOf 'day'
# historyEntries are in reverse-order
minDate = enabledDates.last()
maxDate = enabledDates.first()
# Show the largest viewMode required to start selecting
viewMode = if minDate.isSame(maxDate, 'month')
'days'
else if minDate.isSame(maxDate, 'year')
'months'
else
'years'
# Block phantom 'onChange' from firing during init
@_tempDisableChangeEvent()
$input = $(@refs.hiddenInput)
$input.datetimepicker({
keepOpen: true
debug: true
format: 'YYYY-MM-DD'
enabledDates: enabledDates.toJS()
useCurrent: false
minDate
maxDate
widgetPositioning: {
horizontal: 'left'
vertical: 'top'
}
widgetParent: '#navigatorWrapper'
viewMode: 'years'
})
.on 'dp.change', ({date}) =>
# Prevent invalid/duplicate calls of @_skipToEntryDate
return if not date or @disableChange
# TODO: Detect month (< >) changes to follow with scroll
@_skipToEntryDate(date)
@datetimepicker = $input.data('DateTimePicker')
_skipToEntryDate: (date) ->
# Update the icon with an animated spinner while isScrolling
# Give spinner a chance to start spinning first
Async.series [
(cb) => @setState {isScrolling: true}, -> setTimeout(cb, 50)
(cb) => @props.onSelect(date, cb)
(cb) => @setState {isScrolling: false}, cb
], (err) =>
if err
throw new Error(err)
return
_tempDisableChangeEvent: ->
# Temporarily disable datetimepicker's 'change' event from firing
# This overrides default behaviour causing more events than needed
@disableChange = true
setTimeout (=> @disableChange = false), 500
_handleClick: ->
# Save on window.load perf by only mounting datetimepicker when used
@_initDateTimePicker() unless @datetimepicker?
@_tempDisableChangeEvent()
@datetimepicker.toggle()
_handleBlur: ->
@datetimepicker.hide() if @datetimepicker?
render: ->
{isScrolling} = @state
icon = if isScrolling then 'refresh fa-spin fa-fw' else 'sort'
R.div({id: 'entryDateNavigator'},
R.div({id: 'navigatorWrapper'},
R.input({ref: 'hiddenInput'})
R.button({
ref: 'button'
onClick: @_handleClick unless isScrolling
onBlur: @_handleBlur
className: [
'btn btn-default btn-xs'
'isScrolling' if isScrolling
].join ' '
},
FaIcon(icon)
)
)
)
return EntryDateNavigator
module.exports = {load}
| true | # Copyright (c) PI:NAME:<NAME>END_PI. All rights reserved.
# This source code is subject to the terms of the Mozilla Public License, v. 2.0
# that can be found in the LICENSE file or at: http://mozilla.org/MPL/2.0
# Button that pops up a calendar, allowing the user to select a specific date
# The enabled/selectable dates are populated by @props.historyEntries
# Scrolling functionality is handled internally by EntriesListView
# TODO: Actively follow entriesList scroll with calendar view representation
Imm = require 'immutable'
Async = require 'async'
load = (win) ->
$ = win.jQuery
React = win.React
{PropTypes} = React
R = React.DOM
{FaIcon, makeMoment} = require('../utils').load(win)
EntryDateNavigator = React.createFactory React.createClass
displayName: 'EntryDateNavigator'
propTypes: {
historyEntries: PropTypes.instanceOf(Imm.List)
onSelect: PropTypes.func.isRequired
}
getDefaultProps: -> {
historyEntries: Imm.List()
onSelect: ->
}
getInitialState: -> {
isScrolling: false
}
componentWillUnmount: ->
@datetimepicker.destroy() if @datetimepicker?
componentDidUpdate: (oldProps, oldState) ->
# Re-init enabledDates when historyEntries has changed
# TODO: Use enabledDates API funct (currently doesn't work)
unless Imm.is oldProps.historyEntries, @props.historyEntries
console.log "Refreshing entryDateNavigator"
@_initDateTimePicker()
_generateEnabledDates: (historyEntries) ->
# TODO: Disable selection of any month within min->max whose days are all disabled
return historyEntries.map (e) -> makeMoment(e.get 'timestamp').startOf 'day'
_initDateTimePicker: (props) ->
# Destroy any pre-existing instance
@datetimepicker.destroy() if @datetimepicker?
if @props.historyEntries.isEmpty()
console.warn "Cancelled datetimepicker init, historyEntries is empty"
return
enabledDates = @props.historyEntries.map (e) -> makeMoment(e.get 'timestamp').startOf 'day'
# historyEntries are in reverse-order
minDate = enabledDates.last()
maxDate = enabledDates.first()
# Show the largest viewMode required to start selecting
viewMode = if minDate.isSame(maxDate, 'month')
'days'
else if minDate.isSame(maxDate, 'year')
'months'
else
'years'
# Block phantom 'onChange' from firing during init
@_tempDisableChangeEvent()
$input = $(@refs.hiddenInput)
$input.datetimepicker({
keepOpen: true
debug: true
format: 'YYYY-MM-DD'
enabledDates: enabledDates.toJS()
useCurrent: false
minDate
maxDate
widgetPositioning: {
horizontal: 'left'
vertical: 'top'
}
widgetParent: '#navigatorWrapper'
viewMode: 'years'
})
.on 'dp.change', ({date}) =>
# Prevent invalid/duplicate calls of @_skipToEntryDate
return if not date or @disableChange
# TODO: Detect month (< >) changes to follow with scroll
@_skipToEntryDate(date)
@datetimepicker = $input.data('DateTimePicker')
_skipToEntryDate: (date) ->
# Update the icon with an animated spinner while isScrolling
# Give spinner a chance to start spinning first
Async.series [
(cb) => @setState {isScrolling: true}, -> setTimeout(cb, 50)
(cb) => @props.onSelect(date, cb)
(cb) => @setState {isScrolling: false}, cb
], (err) =>
if err
throw new Error(err)
return
_tempDisableChangeEvent: ->
# Temporarily disable datetimepicker's 'change' event from firing
# This overrides default behaviour causing more events than needed
@disableChange = true
setTimeout (=> @disableChange = false), 500
_handleClick: ->
# Save on window.load perf by only mounting datetimepicker when used
@_initDateTimePicker() unless @datetimepicker?
@_tempDisableChangeEvent()
@datetimepicker.toggle()
_handleBlur: ->
@datetimepicker.hide() if @datetimepicker?
render: ->
{isScrolling} = @state
icon = if isScrolling then 'refresh fa-spin fa-fw' else 'sort'
R.div({id: 'entryDateNavigator'},
R.div({id: 'navigatorWrapper'},
R.input({ref: 'hiddenInput'})
R.button({
ref: 'button'
onClick: @_handleClick unless isScrolling
onBlur: @_handleBlur
className: [
'btn btn-default btn-xs'
'isScrolling' if isScrolling
].join ' '
},
FaIcon(icon)
)
)
)
return EntryDateNavigator
module.exports = {load}
|
[
{
"context": " zoom meeting and return the meeting link\n# zoom @username - get the zoom room for a specific user\n#\n# Autho",
"end": 237,
"score": 0.7363207936286926,
"start": 228,
"tag": "USERNAME",
"value": "@username"
},
{
"context": " the zoom room for a specific user\n#\n# A... | scripts/zoom.coffee | AdeTheux/hubot-slack | 0 | # Description:
# hubot zoom integration!
#
# Dependencies:
# None
#
# Configuration:
# HUBOT_ZOOM_API_KEY
# HUBOT_ZOOM_API_SECRET
#
# Commands:
# nestor zoom - start a zoom meeting and return the meeting link
# zoom @username - get the zoom room for a specific user
#
# Author:
# Gad Berger
sys = require 'sys'
zoom_meeting_create = "https://api.zoom.us/v1/meeting/create"
module.exports = (robot) ->
# copied from remember.coffee
memories = () -> robot.brain.data.remember ?= {}
# @hubot remember @username zoomroom is https://zoom.us/...
robot.hear /^zoom\s@([a-zA-Z0-9]+)\s?$/i, (msg) ->
if msg.message.user.id is robot.name
return
name = msg.match[1].toLowerCase()
key = '@' + name + ' zoomroom'
value = memories()[key]
if value
msg.send value
else
msg.send "I don't remember any zoomroom for @" + name
robot.respond /zoom$/i, (msg) ->
username = msg.message.user.name
zoom_host_id = zoomHostId(username)
# according to zoom support, only scheduled and recurring
# meetings can have the join before host option set to true
params = {}
params.api_key = process.env.HUBOT_ZOOM_API_KEY
params.api_secret = process.env.HUBOT_ZOOM_API_SECRET
params.data_type = "JSON"
params.host_id = zoom_host_id
params.start_time = Date().toString('yyyy-MM-ddTHH:mm:ssZ')
params.duration = 60
params.timezone = "GMT-5:00"
params.topic = "scheduled meeting"
params.type = 2
params.option_start_type = "video"
params.option_jbh = true
try
msg.http(zoom_meeting_create)
.header("content-type", "application/x-www-form-urlencoded")
.query(params)
.post() (error, response, body) ->
switch response.statusCode
when 200
json_body = JSON.parse(body)
if json_body.error?
msg.send "zoom error: #{json_body.error.message}"
else
msg.send "#{username} started a zoom session: #{json_body.join_url}"
else
msg.send "zoom? more like doom! there was a problem sending the request :("
catch e then msg.send e | 184396 | # Description:
# hubot zoom integration!
#
# Dependencies:
# None
#
# Configuration:
# HUBOT_ZOOM_API_KEY
# HUBOT_ZOOM_API_SECRET
#
# Commands:
# nestor zoom - start a zoom meeting and return the meeting link
# zoom @username - get the zoom room for a specific user
#
# Author:
# <NAME>
sys = require 'sys'
zoom_meeting_create = "https://api.zoom.us/v1/meeting/create"
module.exports = (robot) ->
# copied from remember.coffee
memories = () -> robot.brain.data.remember ?= {}
# @hubot remember @username zoomroom is https://zoom.us/...
robot.hear /^zoom\s@([a-zA-Z0-9]+)\s?$/i, (msg) ->
if msg.message.user.id is robot.name
return
name = msg.match[1].toLowerCase()
key = <KEY> ' <KEY>'
value = memories()[key]
if value
msg.send value
else
msg.send "I don't remember any zoomroom for @" + name
robot.respond /zoom$/i, (msg) ->
username = msg.message.user.name
zoom_host_id = zoomHostId(username)
# according to zoom support, only scheduled and recurring
# meetings can have the join before host option set to true
params = {}
params.api_key = process.env.HUBOT_ZOOM_API_KEY
params.api_secret = process.env.HUBOT_ZOOM_API_SECRET
params.data_type = "JSON"
params.host_id = zoom_host_id
params.start_time = Date().toString('yyyy-MM-ddTHH:mm:ssZ')
params.duration = 60
params.timezone = "GMT-5:00"
params.topic = "scheduled meeting"
params.type = 2
params.option_start_type = "video"
params.option_jbh = true
try
msg.http(zoom_meeting_create)
.header("content-type", "application/x-www-form-urlencoded")
.query(params)
.post() (error, response, body) ->
switch response.statusCode
when 200
json_body = JSON.parse(body)
if json_body.error?
msg.send "zoom error: #{json_body.error.message}"
else
msg.send "#{username} started a zoom session: #{json_body.join_url}"
else
msg.send "zoom? more like doom! there was a problem sending the request :("
catch e then msg.send e | true | # Description:
# hubot zoom integration!
#
# Dependencies:
# None
#
# Configuration:
# HUBOT_ZOOM_API_KEY
# HUBOT_ZOOM_API_SECRET
#
# Commands:
# nestor zoom - start a zoom meeting and return the meeting link
# zoom @username - get the zoom room for a specific user
#
# Author:
# PI:NAME:<NAME>END_PI
sys = require 'sys'
zoom_meeting_create = "https://api.zoom.us/v1/meeting/create"
module.exports = (robot) ->
# copied from remember.coffee
memories = () -> robot.brain.data.remember ?= {}
# @hubot remember @username zoomroom is https://zoom.us/...
robot.hear /^zoom\s@([a-zA-Z0-9]+)\s?$/i, (msg) ->
if msg.message.user.id is robot.name
return
name = msg.match[1].toLowerCase()
key = PI:KEY:<KEY>END_PI ' PI:KEY:<KEY>END_PI'
value = memories()[key]
if value
msg.send value
else
msg.send "I don't remember any zoomroom for @" + name
robot.respond /zoom$/i, (msg) ->
username = msg.message.user.name
zoom_host_id = zoomHostId(username)
# according to zoom support, only scheduled and recurring
# meetings can have the join before host option set to true
params = {}
params.api_key = process.env.HUBOT_ZOOM_API_KEY
params.api_secret = process.env.HUBOT_ZOOM_API_SECRET
params.data_type = "JSON"
params.host_id = zoom_host_id
params.start_time = Date().toString('yyyy-MM-ddTHH:mm:ssZ')
params.duration = 60
params.timezone = "GMT-5:00"
params.topic = "scheduled meeting"
params.type = 2
params.option_start_type = "video"
params.option_jbh = true
try
msg.http(zoom_meeting_create)
.header("content-type", "application/x-www-form-urlencoded")
.query(params)
.post() (error, response, body) ->
switch response.statusCode
when 200
json_body = JSON.parse(body)
if json_body.error?
msg.send "zoom error: #{json_body.error.message}"
else
msg.send "#{username} started a zoom session: #{json_body.join_url}"
else
msg.send "zoom? more like doom! there was a problem sending the request :("
catch e then msg.send e |
[
{
"context": ": (new Date).getTime()\n\n testResque =\n name: \"test\"\n failed: 12\n running: 10\n runningTooLon",
"end": 757,
"score": 0.7851300239562988,
"start": 753,
"tag": "NAME",
"value": "test"
}
] | spec/javascripts/controllers/FailedControllerSpec.coffee | stitchfix/resque-brain | 43 | describe "FailedController", ->
scope = null
ctrl = null
resques = null
failedJobs = null
location = null
modal = null
jobsFailed = _.map([1,2,3,4,5,6,7,8,9,10,11,12,13], (i)->
id: i
queue: "mail",
payload: {
class: "UserWelcomeMailer",
args: [ 12345 ]
}
worker: "worker#{i}"
exception: "Resque::TermException"
backtrace: [ "foo.rb", "blah.rb" ]
error: "SIGTERM"
)
updatedJob =
id: 2
queue: "mail",
payload: {
class: "UserWelcomeMailer",
args: [ 12345 ]
}
worker: "worker1"
exception: "Resque::TermException"
backtrace: [ "foo.rb", "blah.rb" ]
error: "SIGTERM"
retriedAt: (new Date).getTime()
testResque =
name: "test"
failed: 12
running: 10
runningTooLong: 3
waiting: 123
resqueName = 'test'
setupController = (page,pageSize,andAlso)->
inject((Resques, FailedJobs, $rootScope, $routeParams, $location, $controller, $modal)->
scope = $rootScope.$new()
location = $location
resques = Resques
failedJobs = FailedJobs
modal = $modal
spyOn(resques,"jobsFailed").andCallFake( (resque,start,count,success,failure)->
success(jobsFailed.slice(start,start + count))
)
spyOn(resques,"get").andCallFake( (resque,success,failure)-> success(testResque))
modalInstance =
result:
then: (f)-> f()
spyOn(modal,"open").andCallFake( () -> modalInstance)
$routeParams.resque = resqueName
$routeParams.page = page if page
$routeParams.pageSize = pageSize if pageSize
if andAlso
andAlso()
ctrl = $controller('FailedController', $scope: scope)
)
beforeEach(module("resqueBrain"))
describe 'loading the controller', ->
describe "without a page specified", ->
describe "without a page size", ->
beforeEach(setupController())
it 'exposes the list of jobs running', ->
expect(scope.jobsFailed).toEqualData(jobsFailed.slice(0,10))
expect(scope.numJobsFailed).toBe(12)
expect(scope.pages).toEqualData( [ 1, 2 ] )
expect(resques.jobsFailed.mostRecentCall.args[0]).toEqualData({ name: resqueName })
expect(resques.jobsFailed.mostRecentCall.args[1]).toBe(0)
expect(resques.jobsFailed.mostRecentCall.args[2]).toBe(10)
expect(scope.currentPage).toBe(1)
describe "with a page size", ->
beforeEach(setupController(null,5))
it 'exposes the list of jobs running', ->
expect(scope.jobsFailed).toEqualData(jobsFailed.slice(0,5))
expect(scope.numJobsFailed).toBe(12)
expect(scope.pages).toEqualData( [ 1, 2, 3 ] )
expect(resques.jobsFailed.mostRecentCall.args[0]).toEqualData({ name: resqueName })
expect(resques.jobsFailed.mostRecentCall.args[1]).toBe(0)
expect(resques.jobsFailed.mostRecentCall.args[2]).toBe(5)
expect(scope.currentPage).toBe(1)
describe "with a page specified", ->
describe "without a page size", ->
beforeEach(setupController(2))
it 'exposes the list of jobs running', ->
expect(scope.jobsFailed).toEqualData(jobsFailed.slice(10,13))
expect(scope.numJobsFailed).toBe(12)
expect(scope.pages).toEqualData( [ 1, 2 ] )
expect(resques.jobsFailed.mostRecentCall.args[0]).toEqualData({ name: resqueName })
expect(resques.jobsFailed.mostRecentCall.args[1]).toBe(10)
expect(resques.jobsFailed.mostRecentCall.args[2]).toBe(10)
expect(scope.currentPage).toBe(2)
describe "with a page size", ->
beforeEach(setupController(2,5))
it 'exposes the list of jobs running', ->
expect(scope.jobsFailed).toEqualData(jobsFailed.slice(5,10))
expect(scope.numJobsFailed).toBe(12)
expect(scope.pages).toEqualData( [ 1, 2, 3 ] )
expect(resques.jobsFailed.mostRecentCall.args[0]).toEqualData({ name: resqueName })
expect(resques.jobsFailed.mostRecentCall.args[1]).toBe(5)
expect(resques.jobsFailed.mostRecentCall.args[2]).toBe(5)
expect(scope.currentPage).toBe(2)
describe "goToPage", ->
beforeEach(setupController())
it 'fetches the next page of data', ->
scope.goToPage(2)
expect(location.search()["page"]).toBe(2)
describe "retry", ->
beforeEach ->
setupController(null, null, ->
spyOn(failedJobs,"retry").andCallFake( (resqueName, jobId, success,failure)-> success() )
spyOn(failedJobs,"get").andCallFake( (resqueName, jobId, success,failure)-> success(updatedJob) )
)
it 'calls retry then get on FailedJobs', ->
scope.retry(scope.jobsFailed[1])
expect(scope.jobsFailed[1]).toEqualData(updatedJob)
expect(failedJobs.retry.mostRecentCall.args[0]).toEqualData(resqueName)
expect(failedJobs.retry.mostRecentCall.args[1]).toEqualData(jobsFailed[1].id)
expect(failedJobs.get.mostRecentCall.args[0]).toEqualData(resqueName)
expect(failedJobs.get.mostRecentCall.args[1]).toEqualData(jobsFailed[1].id)
expect(modal.open.mostRecentCall.args[0].templateUrl).toBe("confirmRetryFailed.html")
expect(modal.open.mostRecentCall.args[0].controller).toBe("ConfirmDestructiveFailedQueueActionController")
expect(modal.open.mostRecentCall.args[0].backdrop).toBe(true)
describe "clear", ->
beforeEach ->
setupController(null, null, ->
spyOn(failedJobs,"clear").andCallFake( (resqueName, jobId, success,failure)-> success() )
)
describe "default call", ->
it 'calls clear then re-fetches all jobs', ->
scope.clear(scope.jobsFailed[1])
expect(failedJobs.clear.mostRecentCall.args[0]).toEqualData(resqueName)
expect(failedJobs.clear.mostRecentCall.args[1]).toEqualData(jobsFailed[1].id)
expect(modal.open.mostRecentCall.args[0].templateUrl).toBe("confirmClearFailed.html")
expect(modal.open.mostRecentCall.args[0].controller).toBe("ConfirmDestructiveFailedQueueActionController")
expect(modal.open.mostRecentCall.args[0].backdrop).toBe(true)
describe "called with param to skip modal nag", ->
it 'calls clear then re-fetches all jobs', ->
scope.clear(scope.jobsFailed[1],true)
expect(failedJobs.clear.mostRecentCall.args[0]).toEqualData(resqueName)
expect(failedJobs.clear.mostRecentCall.args[1]).toEqualData(jobsFailed[1].id)
expect(modal.open).not.toHaveBeenCalled()
describe "retryAndClear", ->
beforeEach ->
setupController(null, null, ->
spyOn(failedJobs,"retry").andCallFake( (resqueName, jobId, success,failure)-> success() )
spyOn(failedJobs,"clear").andCallFake( (resqueName, jobId, success,failure)-> success() )
)
it 'calls clear then re-fetches all jobs', ->
scope.retryAndClear(scope.jobsFailed[1])
expect(failedJobs.clear.mostRecentCall.args[0]).toEqualData(resqueName)
expect(failedJobs.clear.mostRecentCall.args[1]).toEqualData(jobsFailed[1].id)
expect(failedJobs.retry.mostRecentCall.args[0]).toEqualData(resqueName)
expect(failedJobs.retry.mostRecentCall.args[1]).toEqualData(jobsFailed[1].id)
describe "retryAll", ->
beforeEach ->
setupController(null, null, ->
spyOn(failedJobs,"retryAll").andCallFake( (resqueName, success,failure)-> success() )
)
it 'calls retry then get on FailedJobs', ->
scope.retryAll()
expect(failedJobs.retryAll.mostRecentCall.args[0]).toEqualData(resqueName)
expect(modal.open.mostRecentCall.args[0].templateUrl).toBe("confirmRetryFailed.html")
expect(modal.open.mostRecentCall.args[0].controller).toBe("ConfirmDestructiveFailedQueueActionController")
expect(modal.open.mostRecentCall.args[0].backdrop).toBe(true)
describe "clearAll", ->
beforeEach ->
setupController(null, null, ->
spyOn(failedJobs,"clearAll").andCallFake( (resqueName, success,failure)-> success() )
)
it 'calls clear then re-fetches all jobs', ->
scope.clearAll()
expect(failedJobs.clearAll.mostRecentCall.args[0]).toEqualData(resqueName)
expect(modal.open.mostRecentCall.args[0].templateUrl).toBe("confirmClearFailed.html")
expect(modal.open.mostRecentCall.args[0].controller).toBe("ConfirmDestructiveFailedQueueActionController")
expect(modal.open.mostRecentCall.args[0].backdrop).toBe(true)
describe "retryAndClearAll", ->
beforeEach ->
setupController(null, null, ->
spyOn(failedJobs,"retryAndClearAll").andCallFake( (resqueName, success,failure)-> success() )
)
it 'calls clear then re-fetches all jobs', ->
scope.retryAndClearAll()
expect(failedJobs.retryAndClearAll.mostRecentCall.args[0]).toEqualData(resqueName)
| 222301 | describe "FailedController", ->
scope = null
ctrl = null
resques = null
failedJobs = null
location = null
modal = null
jobsFailed = _.map([1,2,3,4,5,6,7,8,9,10,11,12,13], (i)->
id: i
queue: "mail",
payload: {
class: "UserWelcomeMailer",
args: [ 12345 ]
}
worker: "worker#{i}"
exception: "Resque::TermException"
backtrace: [ "foo.rb", "blah.rb" ]
error: "SIGTERM"
)
updatedJob =
id: 2
queue: "mail",
payload: {
class: "UserWelcomeMailer",
args: [ 12345 ]
}
worker: "worker1"
exception: "Resque::TermException"
backtrace: [ "foo.rb", "blah.rb" ]
error: "SIGTERM"
retriedAt: (new Date).getTime()
testResque =
name: "<NAME>"
failed: 12
running: 10
runningTooLong: 3
waiting: 123
resqueName = 'test'
setupController = (page,pageSize,andAlso)->
inject((Resques, FailedJobs, $rootScope, $routeParams, $location, $controller, $modal)->
scope = $rootScope.$new()
location = $location
resques = Resques
failedJobs = FailedJobs
modal = $modal
spyOn(resques,"jobsFailed").andCallFake( (resque,start,count,success,failure)->
success(jobsFailed.slice(start,start + count))
)
spyOn(resques,"get").andCallFake( (resque,success,failure)-> success(testResque))
modalInstance =
result:
then: (f)-> f()
spyOn(modal,"open").andCallFake( () -> modalInstance)
$routeParams.resque = resqueName
$routeParams.page = page if page
$routeParams.pageSize = pageSize if pageSize
if andAlso
andAlso()
ctrl = $controller('FailedController', $scope: scope)
)
beforeEach(module("resqueBrain"))
describe 'loading the controller', ->
describe "without a page specified", ->
describe "without a page size", ->
beforeEach(setupController())
it 'exposes the list of jobs running', ->
expect(scope.jobsFailed).toEqualData(jobsFailed.slice(0,10))
expect(scope.numJobsFailed).toBe(12)
expect(scope.pages).toEqualData( [ 1, 2 ] )
expect(resques.jobsFailed.mostRecentCall.args[0]).toEqualData({ name: resqueName })
expect(resques.jobsFailed.mostRecentCall.args[1]).toBe(0)
expect(resques.jobsFailed.mostRecentCall.args[2]).toBe(10)
expect(scope.currentPage).toBe(1)
describe "with a page size", ->
beforeEach(setupController(null,5))
it 'exposes the list of jobs running', ->
expect(scope.jobsFailed).toEqualData(jobsFailed.slice(0,5))
expect(scope.numJobsFailed).toBe(12)
expect(scope.pages).toEqualData( [ 1, 2, 3 ] )
expect(resques.jobsFailed.mostRecentCall.args[0]).toEqualData({ name: resqueName })
expect(resques.jobsFailed.mostRecentCall.args[1]).toBe(0)
expect(resques.jobsFailed.mostRecentCall.args[2]).toBe(5)
expect(scope.currentPage).toBe(1)
describe "with a page specified", ->
describe "without a page size", ->
beforeEach(setupController(2))
it 'exposes the list of jobs running', ->
expect(scope.jobsFailed).toEqualData(jobsFailed.slice(10,13))
expect(scope.numJobsFailed).toBe(12)
expect(scope.pages).toEqualData( [ 1, 2 ] )
expect(resques.jobsFailed.mostRecentCall.args[0]).toEqualData({ name: resqueName })
expect(resques.jobsFailed.mostRecentCall.args[1]).toBe(10)
expect(resques.jobsFailed.mostRecentCall.args[2]).toBe(10)
expect(scope.currentPage).toBe(2)
describe "with a page size", ->
beforeEach(setupController(2,5))
it 'exposes the list of jobs running', ->
expect(scope.jobsFailed).toEqualData(jobsFailed.slice(5,10))
expect(scope.numJobsFailed).toBe(12)
expect(scope.pages).toEqualData( [ 1, 2, 3 ] )
expect(resques.jobsFailed.mostRecentCall.args[0]).toEqualData({ name: resqueName })
expect(resques.jobsFailed.mostRecentCall.args[1]).toBe(5)
expect(resques.jobsFailed.mostRecentCall.args[2]).toBe(5)
expect(scope.currentPage).toBe(2)
describe "goToPage", ->
beforeEach(setupController())
it 'fetches the next page of data', ->
scope.goToPage(2)
expect(location.search()["page"]).toBe(2)
describe "retry", ->
beforeEach ->
setupController(null, null, ->
spyOn(failedJobs,"retry").andCallFake( (resqueName, jobId, success,failure)-> success() )
spyOn(failedJobs,"get").andCallFake( (resqueName, jobId, success,failure)-> success(updatedJob) )
)
it 'calls retry then get on FailedJobs', ->
scope.retry(scope.jobsFailed[1])
expect(scope.jobsFailed[1]).toEqualData(updatedJob)
expect(failedJobs.retry.mostRecentCall.args[0]).toEqualData(resqueName)
expect(failedJobs.retry.mostRecentCall.args[1]).toEqualData(jobsFailed[1].id)
expect(failedJobs.get.mostRecentCall.args[0]).toEqualData(resqueName)
expect(failedJobs.get.mostRecentCall.args[1]).toEqualData(jobsFailed[1].id)
expect(modal.open.mostRecentCall.args[0].templateUrl).toBe("confirmRetryFailed.html")
expect(modal.open.mostRecentCall.args[0].controller).toBe("ConfirmDestructiveFailedQueueActionController")
expect(modal.open.mostRecentCall.args[0].backdrop).toBe(true)
describe "clear", ->
beforeEach ->
setupController(null, null, ->
spyOn(failedJobs,"clear").andCallFake( (resqueName, jobId, success,failure)-> success() )
)
describe "default call", ->
it 'calls clear then re-fetches all jobs', ->
scope.clear(scope.jobsFailed[1])
expect(failedJobs.clear.mostRecentCall.args[0]).toEqualData(resqueName)
expect(failedJobs.clear.mostRecentCall.args[1]).toEqualData(jobsFailed[1].id)
expect(modal.open.mostRecentCall.args[0].templateUrl).toBe("confirmClearFailed.html")
expect(modal.open.mostRecentCall.args[0].controller).toBe("ConfirmDestructiveFailedQueueActionController")
expect(modal.open.mostRecentCall.args[0].backdrop).toBe(true)
describe "called with param to skip modal nag", ->
it 'calls clear then re-fetches all jobs', ->
scope.clear(scope.jobsFailed[1],true)
expect(failedJobs.clear.mostRecentCall.args[0]).toEqualData(resqueName)
expect(failedJobs.clear.mostRecentCall.args[1]).toEqualData(jobsFailed[1].id)
expect(modal.open).not.toHaveBeenCalled()
describe "retryAndClear", ->
beforeEach ->
setupController(null, null, ->
spyOn(failedJobs,"retry").andCallFake( (resqueName, jobId, success,failure)-> success() )
spyOn(failedJobs,"clear").andCallFake( (resqueName, jobId, success,failure)-> success() )
)
it 'calls clear then re-fetches all jobs', ->
scope.retryAndClear(scope.jobsFailed[1])
expect(failedJobs.clear.mostRecentCall.args[0]).toEqualData(resqueName)
expect(failedJobs.clear.mostRecentCall.args[1]).toEqualData(jobsFailed[1].id)
expect(failedJobs.retry.mostRecentCall.args[0]).toEqualData(resqueName)
expect(failedJobs.retry.mostRecentCall.args[1]).toEqualData(jobsFailed[1].id)
describe "retryAll", ->
beforeEach ->
setupController(null, null, ->
spyOn(failedJobs,"retryAll").andCallFake( (resqueName, success,failure)-> success() )
)
it 'calls retry then get on FailedJobs', ->
scope.retryAll()
expect(failedJobs.retryAll.mostRecentCall.args[0]).toEqualData(resqueName)
expect(modal.open.mostRecentCall.args[0].templateUrl).toBe("confirmRetryFailed.html")
expect(modal.open.mostRecentCall.args[0].controller).toBe("ConfirmDestructiveFailedQueueActionController")
expect(modal.open.mostRecentCall.args[0].backdrop).toBe(true)
describe "clearAll", ->
beforeEach ->
setupController(null, null, ->
spyOn(failedJobs,"clearAll").andCallFake( (resqueName, success,failure)-> success() )
)
it 'calls clear then re-fetches all jobs', ->
scope.clearAll()
expect(failedJobs.clearAll.mostRecentCall.args[0]).toEqualData(resqueName)
expect(modal.open.mostRecentCall.args[0].templateUrl).toBe("confirmClearFailed.html")
expect(modal.open.mostRecentCall.args[0].controller).toBe("ConfirmDestructiveFailedQueueActionController")
expect(modal.open.mostRecentCall.args[0].backdrop).toBe(true)
describe "retryAndClearAll", ->
beforeEach ->
setupController(null, null, ->
spyOn(failedJobs,"retryAndClearAll").andCallFake( (resqueName, success,failure)-> success() )
)
it 'calls clear then re-fetches all jobs', ->
scope.retryAndClearAll()
expect(failedJobs.retryAndClearAll.mostRecentCall.args[0]).toEqualData(resqueName)
| true | describe "FailedController", ->
scope = null
ctrl = null
resques = null
failedJobs = null
location = null
modal = null
jobsFailed = _.map([1,2,3,4,5,6,7,8,9,10,11,12,13], (i)->
id: i
queue: "mail",
payload: {
class: "UserWelcomeMailer",
args: [ 12345 ]
}
worker: "worker#{i}"
exception: "Resque::TermException"
backtrace: [ "foo.rb", "blah.rb" ]
error: "SIGTERM"
)
updatedJob =
id: 2
queue: "mail",
payload: {
class: "UserWelcomeMailer",
args: [ 12345 ]
}
worker: "worker1"
exception: "Resque::TermException"
backtrace: [ "foo.rb", "blah.rb" ]
error: "SIGTERM"
retriedAt: (new Date).getTime()
testResque =
name: "PI:NAME:<NAME>END_PI"
failed: 12
running: 10
runningTooLong: 3
waiting: 123
resqueName = 'test'
setupController = (page,pageSize,andAlso)->
inject((Resques, FailedJobs, $rootScope, $routeParams, $location, $controller, $modal)->
scope = $rootScope.$new()
location = $location
resques = Resques
failedJobs = FailedJobs
modal = $modal
spyOn(resques,"jobsFailed").andCallFake( (resque,start,count,success,failure)->
success(jobsFailed.slice(start,start + count))
)
spyOn(resques,"get").andCallFake( (resque,success,failure)-> success(testResque))
modalInstance =
result:
then: (f)-> f()
spyOn(modal,"open").andCallFake( () -> modalInstance)
$routeParams.resque = resqueName
$routeParams.page = page if page
$routeParams.pageSize = pageSize if pageSize
if andAlso
andAlso()
ctrl = $controller('FailedController', $scope: scope)
)
beforeEach(module("resqueBrain"))
describe 'loading the controller', ->
describe "without a page specified", ->
describe "without a page size", ->
beforeEach(setupController())
it 'exposes the list of jobs running', ->
expect(scope.jobsFailed).toEqualData(jobsFailed.slice(0,10))
expect(scope.numJobsFailed).toBe(12)
expect(scope.pages).toEqualData( [ 1, 2 ] )
expect(resques.jobsFailed.mostRecentCall.args[0]).toEqualData({ name: resqueName })
expect(resques.jobsFailed.mostRecentCall.args[1]).toBe(0)
expect(resques.jobsFailed.mostRecentCall.args[2]).toBe(10)
expect(scope.currentPage).toBe(1)
describe "with a page size", ->
beforeEach(setupController(null,5))
it 'exposes the list of jobs running', ->
expect(scope.jobsFailed).toEqualData(jobsFailed.slice(0,5))
expect(scope.numJobsFailed).toBe(12)
expect(scope.pages).toEqualData( [ 1, 2, 3 ] )
expect(resques.jobsFailed.mostRecentCall.args[0]).toEqualData({ name: resqueName })
expect(resques.jobsFailed.mostRecentCall.args[1]).toBe(0)
expect(resques.jobsFailed.mostRecentCall.args[2]).toBe(5)
expect(scope.currentPage).toBe(1)
describe "with a page specified", ->
describe "without a page size", ->
beforeEach(setupController(2))
it 'exposes the list of jobs running', ->
expect(scope.jobsFailed).toEqualData(jobsFailed.slice(10,13))
expect(scope.numJobsFailed).toBe(12)
expect(scope.pages).toEqualData( [ 1, 2 ] )
expect(resques.jobsFailed.mostRecentCall.args[0]).toEqualData({ name: resqueName })
expect(resques.jobsFailed.mostRecentCall.args[1]).toBe(10)
expect(resques.jobsFailed.mostRecentCall.args[2]).toBe(10)
expect(scope.currentPage).toBe(2)
describe "with a page size", ->
beforeEach(setupController(2,5))
it 'exposes the list of jobs running', ->
expect(scope.jobsFailed).toEqualData(jobsFailed.slice(5,10))
expect(scope.numJobsFailed).toBe(12)
expect(scope.pages).toEqualData( [ 1, 2, 3 ] )
expect(resques.jobsFailed.mostRecentCall.args[0]).toEqualData({ name: resqueName })
expect(resques.jobsFailed.mostRecentCall.args[1]).toBe(5)
expect(resques.jobsFailed.mostRecentCall.args[2]).toBe(5)
expect(scope.currentPage).toBe(2)
describe "goToPage", ->
beforeEach(setupController())
it 'fetches the next page of data', ->
scope.goToPage(2)
expect(location.search()["page"]).toBe(2)
describe "retry", ->
beforeEach ->
setupController(null, null, ->
spyOn(failedJobs,"retry").andCallFake( (resqueName, jobId, success,failure)-> success() )
spyOn(failedJobs,"get").andCallFake( (resqueName, jobId, success,failure)-> success(updatedJob) )
)
it 'calls retry then get on FailedJobs', ->
scope.retry(scope.jobsFailed[1])
expect(scope.jobsFailed[1]).toEqualData(updatedJob)
expect(failedJobs.retry.mostRecentCall.args[0]).toEqualData(resqueName)
expect(failedJobs.retry.mostRecentCall.args[1]).toEqualData(jobsFailed[1].id)
expect(failedJobs.get.mostRecentCall.args[0]).toEqualData(resqueName)
expect(failedJobs.get.mostRecentCall.args[1]).toEqualData(jobsFailed[1].id)
expect(modal.open.mostRecentCall.args[0].templateUrl).toBe("confirmRetryFailed.html")
expect(modal.open.mostRecentCall.args[0].controller).toBe("ConfirmDestructiveFailedQueueActionController")
expect(modal.open.mostRecentCall.args[0].backdrop).toBe(true)
describe "clear", ->
beforeEach ->
setupController(null, null, ->
spyOn(failedJobs,"clear").andCallFake( (resqueName, jobId, success,failure)-> success() )
)
describe "default call", ->
it 'calls clear then re-fetches all jobs', ->
scope.clear(scope.jobsFailed[1])
expect(failedJobs.clear.mostRecentCall.args[0]).toEqualData(resqueName)
expect(failedJobs.clear.mostRecentCall.args[1]).toEqualData(jobsFailed[1].id)
expect(modal.open.mostRecentCall.args[0].templateUrl).toBe("confirmClearFailed.html")
expect(modal.open.mostRecentCall.args[0].controller).toBe("ConfirmDestructiveFailedQueueActionController")
expect(modal.open.mostRecentCall.args[0].backdrop).toBe(true)
describe "called with param to skip modal nag", ->
it 'calls clear then re-fetches all jobs', ->
scope.clear(scope.jobsFailed[1],true)
expect(failedJobs.clear.mostRecentCall.args[0]).toEqualData(resqueName)
expect(failedJobs.clear.mostRecentCall.args[1]).toEqualData(jobsFailed[1].id)
expect(modal.open).not.toHaveBeenCalled()
describe "retryAndClear", ->
beforeEach ->
setupController(null, null, ->
spyOn(failedJobs,"retry").andCallFake( (resqueName, jobId, success,failure)-> success() )
spyOn(failedJobs,"clear").andCallFake( (resqueName, jobId, success,failure)-> success() )
)
it 'calls clear then re-fetches all jobs', ->
scope.retryAndClear(scope.jobsFailed[1])
expect(failedJobs.clear.mostRecentCall.args[0]).toEqualData(resqueName)
expect(failedJobs.clear.mostRecentCall.args[1]).toEqualData(jobsFailed[1].id)
expect(failedJobs.retry.mostRecentCall.args[0]).toEqualData(resqueName)
expect(failedJobs.retry.mostRecentCall.args[1]).toEqualData(jobsFailed[1].id)
describe "retryAll", ->
beforeEach ->
setupController(null, null, ->
spyOn(failedJobs,"retryAll").andCallFake( (resqueName, success,failure)-> success() )
)
it 'calls retry then get on FailedJobs', ->
scope.retryAll()
expect(failedJobs.retryAll.mostRecentCall.args[0]).toEqualData(resqueName)
expect(modal.open.mostRecentCall.args[0].templateUrl).toBe("confirmRetryFailed.html")
expect(modal.open.mostRecentCall.args[0].controller).toBe("ConfirmDestructiveFailedQueueActionController")
expect(modal.open.mostRecentCall.args[0].backdrop).toBe(true)
describe "clearAll", ->
beforeEach ->
setupController(null, null, ->
spyOn(failedJobs,"clearAll").andCallFake( (resqueName, success,failure)-> success() )
)
it 'calls clear then re-fetches all jobs', ->
scope.clearAll()
expect(failedJobs.clearAll.mostRecentCall.args[0]).toEqualData(resqueName)
expect(modal.open.mostRecentCall.args[0].templateUrl).toBe("confirmClearFailed.html")
expect(modal.open.mostRecentCall.args[0].controller).toBe("ConfirmDestructiveFailedQueueActionController")
expect(modal.open.mostRecentCall.args[0].backdrop).toBe(true)
describe "retryAndClearAll", ->
beforeEach ->
setupController(null, null, ->
spyOn(failedJobs,"retryAndClearAll").andCallFake( (resqueName, success,failure)-> success() )
)
it 'calls clear then re-fetches all jobs', ->
scope.retryAndClearAll()
expect(failedJobs.retryAndClearAll.mostRecentCall.args[0]).toEqualData(resqueName)
|
[
{
"context": "q9su7y?svg=true)](https://ci.appveyor.com/project/iikira/baidupcs-go)\n [\n [](https://ci.appveyor.com/project/iikira/baidupcs-go)
[](https://godoc.org/github.com/iikira/BaiduPCS-Go)
仿 Linux shell 文件处理命令的百度网盘命令行客户端.
This project was largely inspired by [GangZhuo/BaiduPCS](https://github.com/GangZhuo/BaiduPCS)
<!-- toc -->
- [特色](#特色)
- [编译/交叉编译 说明](#编译交叉编译-说明)
- [下载/运行 说明](#下载运行-说明)
* [Windows](#windows)
* [Linux / macOS](#linux--macos)
* [Android / iOS](#android--ios)
- [命令列表及说明](#命令列表及说明)
* [注意 ! ! !](#注意---)
* [检测程序更新](#检测程序更新)
* [登录百度帐号](#登录百度帐号)
* [列出帐号列表](#列出帐号列表)
* [切换百度帐号](#切换百度帐号)
* [退出百度帐号](#退出百度帐号)
* [获取网盘配额](#获取网盘配额)
* [切换工作目录](#切换工作目录)
* [输出工作目录](#输出工作目录)
* [列出目录](#列出目录)
* [列出目录树形图](#列出目录树形图)
* [获取单个文件/目录的元信息](#获取单个文件目录的元信息)
* [下载文件/目录](#下载文件目录)
* [上传文件/目录](#上传文件目录)
* [手动秒传文件](#手动秒传文件)
* [获取本地文件的秒传信息](#获取本地文件的秒传信息)
* [导出文件/目录](#导出文件目录)
* [创建目录](#创建目录)
* [删除文件/目录](#删除文件目录)
* [拷贝文件/目录](#拷贝文件目录)
* [移动/重命名文件/目录](#移动重命名文件目录)
* [离线下载](#离线下载)
+ [添加离线下载任务](#添加离线下载任务)
+ [精确查询离线下载任务](#精确查询离线下载任务)
+ [查询离线下载任务列表](#查询离线下载任务列表)
+ [取消离线下载任务](#取消离线下载任务)
+ [删除离线下载任务](#删除离线下载任务)
* [显示和修改程序配置项](#显示和修改程序配置项)
* [工具箱](#工具箱)
- [初级使用教程](#初级使用教程)
* [1. 查看程序使用说明](#1-查看程序使用说明)
* [2. 登录百度帐号 (必做)](#2-登录百度帐号-必做)
* [3. 切换网盘工作目录](#3-切换网盘工作目录)
* [4. 网盘内列出文件和目录](#4-网盘内列出文件和目录)
* [5. 下载文件](#5-下载文件)
* [6. 设置下载最大并发量](#6-设置下载最大并发量)
* [7. 退出程序](#7-退出程序)
- [常见问题](#常见问题)
- [TODO](#todo)
- [交流反馈](#交流反馈)
- [捐助](#捐助)
<!-- tocstop -->
# 特色
多平台支持, 支持 Windows, macOS, linux, 移动设备等.
百度帐号多用户支持;
通配符匹配网盘路径和 Tab 自动补齐命令和路径, [通配符_百度百科](https://baike.baidu.com/item/通配符);
[下载](#下载文件或目录)网盘内文件, 支持多个文件或目录下载, 支持断点续传和单文件并行下载;
[上传](#上传文件或目录)2GB以内的文件, 支持多个文件或目录上传;
[离线下载](#离线下载), 支持http/https/ftp/电驴/磁力链协议.
# 编译/交叉编译 说明
参见 [编译/交叉编译帮助](https://github.com/iikira/BaiduPCS-Go/wiki/编译-交叉编译帮助)
# 下载/运行 说明
Go语言程序, 可直接在[发布页](https://github.com/iikira/BaiduPCS-Go/releases)下载使用.
如果程序运行时输出乱码, 请检查下终端的编码方式是否为 `UTF-8`.
使用本程序之前, 建议学习一些 linux 基础知识 和 基础命令.
如果未带任何参数运行程序, 程序将会进入仿Linux shell系统用户界面的cli交互模式, 可直接运行相关命令.
cli交互模式下, 光标所在行的前缀应为 `BaiduPCS-Go >`, 如果登录了百度帐号则格式为 `BaiduPCS-Go:<工作目录> <百度ID>$ `
程序会提供相关命令的使用说明.
## Windows
程序应在 命令提示符 (Command Prompt) 或 PowerShell 中运行, 在 mintty (例如: GitBash) 可能会有显示问题.
也可直接双击程序运行, 具体使用方法请参见 [命令列表及说明](#命令列表及说明) 和 [初级使用教程](#初级使用教程).
## Linux / macOS
程序应在 终端 (Terminal) 运行.
具体使用方法请参见 [命令列表及说明](#命令列表及说明) 和 [初级使用教程](#初级使用教程).
## Android / iOS
> Android / iOS 移动设备操作比较麻烦, 不建议在移动设备上使用本程序.
安卓, 建议使用 [Termux](https://termux.com) 或 [NeoTerm](https://github.com/NeoTerm/NeoTerm) 或 终端模拟器, 以提供终端环境.
示例: [Android 运行本项目程序参考示例](https://github.com/iikira/BaiduPCS-Go/wiki/Android-运行本项目程序参考示例), 有兴趣的可以参考一下.
苹果iOS, 需要越狱, 在 Cydia 搜索下载并安装 MobileTerminal, 或者其他提供终端环境的软件.
示例: [iOS 运行本项目程序参考示例](https://github.com/iikira/BaiduPCS-Go/wiki/iOS-运行本项目程序参考示例), 有兴趣的可以参考一下.
具体使用方法请参见 [命令列表及说明](#命令列表及说明) 和 [初级使用教程](#初级使用教程).
# 命令列表及说明
## 注意 ! ! !
命令的前缀 `BaiduPCS-Go` 为指向程序运行的全路径名 (ARGv 的第一个参数)
直接运行程序时, 未带任何其他参数, 则程序进入cli交互模式, 运行以下命令时, 要把命令的前缀 `BaiduPCS-Go` 去掉!
cli交互模式已支持按tab键自动补全命令和路径.
## 检测程序更新
```
BaiduPCS-Go update
```
## 登录百度帐号
### 常规登录百度帐号
支持在线验证绑定的手机号或邮箱,
```
BaiduPCS-Go login
```
### 使用百度 BDUSS 来登录百度帐号
[关于 获取百度 BDUSS](https://github.com/iikira/BaiduPCS-Go/wiki/关于-获取百度-BDUSS)
```
BaiduPCS-Go login -bduss=<BDUSS>
```
#### 例子
```
BaiduPCS-Go login -bduss=1234567
```
```
BaiduPCS-Go login
请输入百度用户名(手机号/邮箱/用户名), 回车键提交 > 1234567
```
## 列出帐号列表
```
BaiduPCS-Go loglist
```
获取当前帐号, 和所有已登录的百度帐号
## 切换百度帐号
切换已登录的百度帐号
```
BaiduPCS-Go su <uid>
```
```
BaiduPCS-Go su
请输入要切换帐号的 # 值 >
```
## 退出百度帐号
退出当前登录的百度帐号
```
BaiduPCS-Go logout
```
程序会进一步确认退出帐号, 防止误操作.
## 获取网盘配额
```
BaiduPCS-Go quota
```
获取网盘的总储存空间, 和已使用的储存空间
## 切换工作目录
```
BaiduPCS-Go cd <目录>
```
### 切换工作目录后自动列出工作目录下的文件和目录
```
BaiduPCS-Go cd -l <目录>
```
#### 例子
```
# 切换 /我的资源 工作目录
BaiduPCS-Go cd /我的资源
# 切换 上级目录
BaiduPCS-Go cd ..
# 切换 根目录
BaiduPCS-Go cd /
# 切换 /我的资源 工作目录, 并自动列出 /我的资源 下的文件和目录
BaiduPCS-Go cd -l 我的资源
# 使用通配符
BaiduPCS-Go cd /我的*
```
## 输出工作目录
```
BaiduPCS-Go pwd
```
## 列出目录
列出当前工作目录的文件和目录或指定目录
```
BaiduPCS-Go ls
```
```
BaiduPCS-Go ls <目录>
```
### 可选参数
```
-asc: 升序排序
-desc: 降序排序
-time: 根据时间排序
-name: 根据文件名排序
-size: 根据大小排序
```
#### 例子
```
# 列出 我的资源 内的文件和目录
BaiduPCS-Go ls 我的资源
# 绝对路径
BaiduPCS-Go ls /我的资源
# 降序排序
BaiduPCS-Go ls -desc 我的资源
# 按文件大小降序排序
BaiduPCS-Go ls -size -desc 我的资源
# 使用通配符
BaiduPCS-Go ls /我的*
```
## 列出目录树形图
列出当前工作目录的文件和目录或指定目录的树形图
```
BaiduPCS-Go tree <目录>
# 默认获取工作目录元信息
BaiduPCS-Go tree
```
## 获取单个文件/目录的元信息
获取单个文件/目录的元信息
```
BaiduPCS-Go meta <文件/目录>
```
```
# 默认获取工作目录元信息
BaiduPCS-Go meta
```
#### 例子
```
BaiduPCS-Go meta 我的资源
BaiduPCS-Go meta /
```
## 下载文件/目录
```
BaiduPCS-Go download <网盘文件或目录的路径1> <文件或目录2> <文件或目录3> ...
BaiduPCS-Go d <网盘文件或目录的路径1> <文件或目录2> <文件或目录3> ...
```
### 可选参数
```
-test: 测试下载, 此操作不会保存文件到本地
-status: 输出所有线程的工作状态
--save: 将下载的文件直接保存到当前工作目录
--saveto: 将下载的文件直接保存到指定的目录
-x: 为文件加上执行权限, (windows系统无效)
-p <num>: 指定下载的最大并发量
```
支持多个文件或目录的下载.
下载的文件默认保存到 **程序所在目录** 的 download/ 目录, 支持设置指定目录, 重名的文件会自动跳过!
[关于下载的简单说明](https://github.com/iikira/BaiduPCS-Go/wiki/%E5%85%B3%E4%BA%8E%E4%B8%8B%E8%BD%BD%E7%9A%84%E7%AE%80%E5%8D%95%E8%AF%B4%E6%98%8E)
#### 例子
```
# 设置保存目录, 保存到 D:\\Downloads
# 注意区别反斜杠 "\\" 和 斜杠 "/" !!!
BaiduPCS-Go config set -savedir D:/Downloads
# 下载 /我的资源/1.mp4
BaiduPCS-Go d /我的资源/1.mp4
# 下载 /我的资源 整个目录!!
BaiduPCS-Go d /我的资源
# 下载网盘内的全部文件!!
BaiduPCS-Go d /
BaiduPCS-Go d *
```
## 上传文件/目录
```
BaiduPCS-Go upload <本地文件/目录的路径1> <文件/目录2> <文件/目录3> ... <目标目录>
BaiduPCS-Go u <本地文件/目录的路径1> <文件/目录2> <文件/目录3> ... <目标目录>
```
* 上传的文件将会保存到, <目标目录>.
* 遇到同名文件将会自动覆盖!!
* 当上传的文件名和网盘的目录名称相同时, 不会覆盖目录, 防止丢失数据.
#### 例子:
```
# 将本地的 C:\\Users\\Administrator\\Desktop\\1.mp4 上传到网盘 /视频 目录
# 注意区别反斜杠 "\\" 和 斜杠 "/" !!!
BaiduPCS-Go upload C:/Users/Administrator/Desktop/1.mp4 /视频
# 将本地的 C:\\Users\\Administrator\\Desktop\\1.mp4 和 C:\\Users\\Administrator\\Desktop\\2.mp4 上传到网盘 /视频 目录
BaiduPCS-Go upload C:/Users/Administrator/Desktop/1.mp4 C:/Users/Administrator/Desktop/2.mp4 /视频
# 将本地的 C:\\Users\\Administrator\\Desktop 整个目录上传到网盘 /视频 目录
BaiduPCS-Go upload C:/Users/Administrator/Desktop /视频
```
## 手动秒传文件
```
BaiduPCS-Go rapidupload -length=<文件的大小> -md5=<文件的md5值> -slicemd5=<文件前256KB切片的md5值(可选)> -crc32=<文件的crc32值(可选)> <保存的网盘路径, 需包含文件名>
BaiduPCS-Go ru -length=<文件的大小> -md5=<文件的md5值> -slicemd5=<文件前256KB切片的md5值(可选)> -crc32=<文件的crc32值(可选)> <保存的网盘路径, 需包含文件名>
```
注意: 使用此功能秒传文件, 前提是知道文件的大小, md5, 前256KB切片的 md5 (可选), crc32 (可选), 且百度网盘中存在一模一样的文件.
上传的文件将会保存到网盘的目标目录.
遇到同名文件将会自动覆盖!
#### 例子:
```
# 如果秒传成功, 则保存到网盘路径 /test
BaiduPCS-Go rapidupload -length=56276137 -md5=fbe082d80e90f90f0fb1f94adbbcfa7f -slicemd5=38c6a75b0ec4499271d4ea38a667ab61 -crc32=314332359 /test
# 精简一下, 如果秒传成功, 则保存到网盘路径 /test
BaiduPCS-Go rapidupload -length=56276137 -md5=fbe082d80e90f90f0fb1f94adbbcfa7f /test
```
## 获取本地文件的秒传信息
```
BaiduPCS-Go sumfile <本地文件的路径>
BaiduPCS-Go sf <本地文件的路径>
```
获取本地文件的大小, md5, 前256KB切片的 md5, crc32, 可用于秒传文件.
#### 例子:
```
# 获取 C:\\Users\\Administrator\\Desktop\\1.mp4 的秒传信息
BaiduPCS-Go sumfile C:/Users/Administrator/Desktop/1.mp4
```
## 导出文件/目录
```
BaiduPCS-Go export <文件/目录1> <文件/目录2> ...
BaiduPCS-Go ep <文件/目录1> <文件/目录2> ...
```
导出网盘内的文件或目录, 原理为秒传文件, 此操作会生成导出文件或目录的命令.
#### 例子:
```
# 导出当前工作目录:
BaiduPCS-Go export
# 导出所有文件和目录, 并设置新的根目录为 `/root`
BaiduPCS-Go export -root=/root /
# 导出 `/我的资源`
BaiduPCS-Go export /我的资源
```
## 创建目录
```
BaiduPCS-Go mkdir <目录>
```
#### 例子
```
BaiduPCS-Go mkdir 123
```
## 删除文件/目录
```
BaiduPCS-Go rm <网盘文件或目录的路径1> <文件或目录2> <文件或目录3> ...
```
注意: 删除多个文件和目录时, 请确保每一个文件和目录都存在, 否则删除操作会失败.
被删除的文件或目录可在网盘文件回收站找回.
#### 例子
```
# 删除 /我的资源/1.mp4
BaiduPCS-Go rm /我的资源/1.mp4
# 删除 /我的资源/1.mp4 和 /我的资源/2.mp4
BaiduPCS-Go rm /我的资源/1.mp4 /我的资源/2.mp4
# 删除 /我的资源 内的所有文件和目录, 但不删除该目录
BaiduPCS-Go rm /我的资源/*
# 删除 /我的资源 整个目录 !!
BaiduPCS-Go rm /我的资源
```
## 拷贝文件/目录
```
BaiduPCS-Go cp <文件/目录> <目标 文件/目录>
BaiduPCS-Go cp <文件/目录1> <文件/目录2> <文件/目录3> ... <目标目录>
```
注意: 拷贝多个文件和目录时, 请确保每一个文件和目录都存在, 否则拷贝操作会失败.
#### 例子
```
# 将 /我的资源/1.mp4 复制到 根目录 /
BaiduPCS-Go cp /我的资源/1.mp4 /
# 将 /我的资源/1.mp4 和 /我的资源/2.mp4 复制到 根目录 /
BaiduPCS-Go cp /我的资源/1.mp4 /我的资源/2.mp4 /
```
## 移动/重命名文件/目录
```
# 移动:
BaiduPCS-Go mv <文件/目录1> <文件/目录2> <文件/目录3> ... <目标目录>
# 重命名:
BaiduPCS-Go mv <文件/目录> <重命名的文件/目录>
```
注意: 移动多个文件和目录时, 请确保每一个文件和目录都存在, 否则移动操作会失败.
#### 例子
```
# 将 /我的资源/1.mp4 移动到 根目录 /
BaiduPCS-Go mv /我的资源/1.mp4 /
# 将 /我的资源/1.mp4 重命名为 /我的资源/3.mp4
BaiduPCS-Go mv /我的资源/1.mp4 /我的资源/3.mp4
```
## 离线下载
```
BaiduPCS-Go offlinedl
BaiduPCS-Go clouddl
BaiduPCS-Go od
```
离线下载支持http/https/ftp/电驴/磁力链协议
### 添加离线下载任务
```
BaiduPCS-Go offlinedl add -path=<离线下载文件保存的路径> 资源地址1 地址2 ...
```
添加任务成功之后, 返回离线下载的任务ID.
### 精确查询离线下载任务
```
BaiduPCS-Go offlinedl query 任务ID1 任务ID2 ...
```
### 查询离线下载任务列表
```
BaiduPCS-Go offlinedl list
```
### 取消离线下载任务
```
BaiduPCS-Go offlinedl cancel 任务ID1 任务ID2 ...
```
### 删除离线下载任务
```
BaiduPCS-Go offlinedl delete 任务ID1 任务ID2 ...
```
#### 例子
```
# 将百度和腾讯主页, 离线下载到根目录 /
BaiduPCS-Go offlinedl add -path=/ http://baidu.com http://qq.com
# 添加磁力链接任务
BaiduPCS-Go offlinedl add magnet:?xt=urn:btih:xxx
# 查询任务ID为 12345 的离线下载任务状态
BaiduPCS-Go offlinedl query 12345
# 取消任务ID为 12345 的离线下载任务
BaiduPCS-Go offlinedl cancel 12345
```
## 显示程序环境变量
```
BaiduPCS-Go env
```
BAIDUPCS_GO_CONFIG_DIR: 为具体的存储目录,
BAIDUPCS_GO_VERBOSE: 是否启用调试.
## 显示和修改程序配置项
```
# 显示配置
BaiduPCS-Go config
# 设置配置
BaiduPCS-Go config set
```
注意: v3.5 以后, 程序对配置文件储存路径的寻找做了调整, 配置文件所在的目录可以是程序本身所在目录, 也可以是家目录.
配置文件所在的目录为家目录的情况:
Windows: `%APPDATA%\\BaiduPCS-Go`
其他操作系统: `$HOME/.config/BaiduPCS-Go`
可通过设置环境变量 `BAIDUPCS_GO_CONFIG_DIR`, 指定配置文件存放的目录.
#### 例子
```
# 显示所有可以设置的值
BaiduPCS-Go config -h
BaiduPCS-Go config set -h
# 设置下载文件的储存目录
BaiduPCS-Go config set -savedir D:/Downloads
# 设置下载最大并发量为 150
BaiduPCS-Go config set -max_parallel 150
# 组合设置
BaiduPCS-Go config set -max_parallel 150 -savedir D:/Downloads
```
## 工具箱
```
BaiduPCS-Go tool
```
目前工具箱支持加解密文件等.
# 初级使用教程
新手建议: **双击运行程序**, 进入仿 Linux shell 的 cli 交互模式;
cli交互模式下, 光标所在行的前缀应为 `BaiduPCS-Go >`, 如果登录了百度帐号则格式为 `BaiduPCS-Go:<工作目录> <百度ID>$ `
以下例子的命令, 均为 cli交互模式下的命令
运行命令的正确操作: **输入命令, 按一下回车键 (键盘上的 Enter 键)**, 程序会接收到命令并输出结果
## 1. 查看程序使用说明
cli交互模式下, 运行命令 `help`
## 2. 登录百度帐号 (必做)
cli交互模式下, 运行命令 `login -h` (注意空格) 查看帮助
cli交互模式下, 运行命令 `login` 程序将会提示你输入百度用户名(手机号/邮箱/用户名)和密码, 必要时还可以在线验证绑定的手机号或邮箱
## 3. 切换网盘工作目录
cli交互模式下, 运行命令 `cd /我的资源` 将工作目录切换为 `/我的资源` (前提: 该目录存在于网盘)
目录支持通配符匹配, 所以你也可以这样: 运行命令 `cd /我的*` 或 `cd /我的??` 将工作目录切换为 `/我的资源`, 简化输入.
将工作目录切换为 `/我的资源` 成功后, 运行命令 `cd ..` 切换上级目录, 即将工作目录切换为 `/`
为什么要这样设计呢, 举个例子,
假设 你要下载 `/我的资源` 内名为 `1.mp4` 和 `2.mp4` 两个文件, 而未切换工作目录, 你需要依次运行以下命令:
```
d /我的资源/1.mp4
d /我的资源/2.mp4
```
而切换网盘工作目录之后, 依次运行以下命令:
```
cd /我的资源
d 1.mp4
d 2.mp4
```
这样就达到了简化输入的目的
## 4. 网盘内列出文件和目录
cli交互模式下, 运行命令 `ls -h` (注意空格) 查看帮助
cli交互模式下, 运行命令 `ls` 来列出当前所在目录的文件和目录
cli交互模式下, 运行命令 `ls /我的资源` 来列出 `/我的资源` 内的文件和目录
cli交互模式下, 运行命令 `ls ..` 来列出当前所在目录的上级目录的文件和目录
## 5. 下载文件
说明: 下载的文件默认保存到 download/ 目录 (文件夹)
cli交互模式下, 运行命令 `d -h` (注意空格) 查看帮助
cli交互模式下, 运行命令 `d /我的资源/1.mp4` 来下载位于 `/我的资源/1.mp4` 的文件 `1.mp4` , 该操作等效于运行以下命令:
```
cd /我的资源
d 1.mp4
```
现在已经支持目录 (文件夹) 下载, 所以, 运行以下命令, 会下载 `/我的资源` 内的所有文件 (违规文件除外):
```
d /我的资源
```
参见 例6 设置下载最大并发量
## 6. 设置下载最大并发量
cli交互模式下, 运行命令 `config set -h` (注意空格) 查看设置帮助以及可供设置的值
cli交互模式下, 运行命令 `config set -max_parallel 250` 将下载最大并发量设置为 250
下载最大并发量建议值: 50~500, 太低下载速度提升不明显甚至速度会变为0, 太高可能会导致程序出错被操作系统结束掉.
## 7. 退出程序
运行命令 `quit` 或 `exit` 或 组合键 `Ctrl+C` 或 组合键 `Ctrl+D`
# 常见问题
参见 [常见问题](https://github.com/iikira/BaiduPCS-Go/wiki/%E5%B8%B8%E8%A7%81%E9%97%AE%E9%A2%98)
# TODO
1. 上传大文件;
2. 回收站操作, 例如查询回收站文件, 还原文件或目录等.
# 交流反馈
提交Issue: [Issues](https://github.com/iikira/BaiduPCS-Go/issues)
邮箱: i@mail.iikira.com
QQ群: 178324706
# 捐助
如果你愿意.
| 支付宝 |
| :-----------------------------------: |
|  |
'''
tags: []
isStarred: false
isTrashed: false
| 174473 | createdAt: "2018-05-17T05:40:35.726Z"
updatedAt: "2018-05-17T05:42:09.604Z"
type: "MARKDOWN_NOTE"
folder: "86d729dde83c4a092177"
title: "BaiduPCS-Go 百度网盘客户端"
content: '''
# BaiduPCS-Go 百度网盘客户端
[](https://ci.appveyor.com/project/iikira/baidupcs-go)
[](https://godoc.org/github.com/iikira/BaiduPCS-Go)
仿 Linux shell 文件处理命令的百度网盘命令行客户端.
This project was largely inspired by [GangZhuo/BaiduPCS](https://github.com/GangZhuo/BaiduPCS)
<!-- toc -->
- [特色](#特色)
- [编译/交叉编译 说明](#编译交叉编译-说明)
- [下载/运行 说明](#下载运行-说明)
* [Windows](#windows)
* [Linux / macOS](#linux--macos)
* [Android / iOS](#android--ios)
- [命令列表及说明](#命令列表及说明)
* [注意 ! ! !](#注意---)
* [检测程序更新](#检测程序更新)
* [登录百度帐号](#登录百度帐号)
* [列出帐号列表](#列出帐号列表)
* [切换百度帐号](#切换百度帐号)
* [退出百度帐号](#退出百度帐号)
* [获取网盘配额](#获取网盘配额)
* [切换工作目录](#切换工作目录)
* [输出工作目录](#输出工作目录)
* [列出目录](#列出目录)
* [列出目录树形图](#列出目录树形图)
* [获取单个文件/目录的元信息](#获取单个文件目录的元信息)
* [下载文件/目录](#下载文件目录)
* [上传文件/目录](#上传文件目录)
* [手动秒传文件](#手动秒传文件)
* [获取本地文件的秒传信息](#获取本地文件的秒传信息)
* [导出文件/目录](#导出文件目录)
* [创建目录](#创建目录)
* [删除文件/目录](#删除文件目录)
* [拷贝文件/目录](#拷贝文件目录)
* [移动/重命名文件/目录](#移动重命名文件目录)
* [离线下载](#离线下载)
+ [添加离线下载任务](#添加离线下载任务)
+ [精确查询离线下载任务](#精确查询离线下载任务)
+ [查询离线下载任务列表](#查询离线下载任务列表)
+ [取消离线下载任务](#取消离线下载任务)
+ [删除离线下载任务](#删除离线下载任务)
* [显示和修改程序配置项](#显示和修改程序配置项)
* [工具箱](#工具箱)
- [初级使用教程](#初级使用教程)
* [1. 查看程序使用说明](#1-查看程序使用说明)
* [2. 登录百度帐号 (必做)](#2-登录百度帐号-必做)
* [3. 切换网盘工作目录](#3-切换网盘工作目录)
* [4. 网盘内列出文件和目录](#4-网盘内列出文件和目录)
* [5. 下载文件](#5-下载文件)
* [6. 设置下载最大并发量](#6-设置下载最大并发量)
* [7. 退出程序](#7-退出程序)
- [常见问题](#常见问题)
- [TODO](#todo)
- [交流反馈](#交流反馈)
- [捐助](#捐助)
<!-- tocstop -->
# 特色
多平台支持, 支持 Windows, macOS, linux, 移动设备等.
百度帐号多用户支持;
通配符匹配网盘路径和 Tab 自动补齐命令和路径, [通配符_百度百科](https://baike.baidu.com/item/通配符);
[下载](#下载文件或目录)网盘内文件, 支持多个文件或目录下载, 支持断点续传和单文件并行下载;
[上传](#上传文件或目录)2GB以内的文件, 支持多个文件或目录上传;
[离线下载](#离线下载), 支持http/https/ftp/电驴/磁力链协议.
# 编译/交叉编译 说明
参见 [编译/交叉编译帮助](https://github.com/iikira/BaiduPCS-Go/wiki/编译-交叉编译帮助)
# 下载/运行 说明
Go语言程序, 可直接在[发布页](https://github.com/iikira/BaiduPCS-Go/releases)下载使用.
如果程序运行时输出乱码, 请检查下终端的编码方式是否为 `UTF-8`.
使用本程序之前, 建议学习一些 linux 基础知识 和 基础命令.
如果未带任何参数运行程序, 程序将会进入仿Linux shell系统用户界面的cli交互模式, 可直接运行相关命令.
cli交互模式下, 光标所在行的前缀应为 `BaiduPCS-Go >`, 如果登录了百度帐号则格式为 `BaiduPCS-Go:<工作目录> <百度ID>$ `
程序会提供相关命令的使用说明.
## Windows
程序应在 命令提示符 (Command Prompt) 或 PowerShell 中运行, 在 mintty (例如: GitBash) 可能会有显示问题.
也可直接双击程序运行, 具体使用方法请参见 [命令列表及说明](#命令列表及说明) 和 [初级使用教程](#初级使用教程).
## Linux / macOS
程序应在 终端 (Terminal) 运行.
具体使用方法请参见 [命令列表及说明](#命令列表及说明) 和 [初级使用教程](#初级使用教程).
## Android / iOS
> Android / iOS 移动设备操作比较麻烦, 不建议在移动设备上使用本程序.
安卓, 建议使用 [Termux](https://termux.com) 或 [NeoTerm](https://github.com/NeoTerm/NeoTerm) 或 终端模拟器, 以提供终端环境.
示例: [Android 运行本项目程序参考示例](https://github.com/iikira/BaiduPCS-Go/wiki/Android-运行本项目程序参考示例), 有兴趣的可以参考一下.
苹果iOS, 需要越狱, 在 Cydia 搜索下载并安装 MobileTerminal, 或者其他提供终端环境的软件.
示例: [iOS 运行本项目程序参考示例](https://github.com/iikira/BaiduPCS-Go/wiki/iOS-运行本项目程序参考示例), 有兴趣的可以参考一下.
具体使用方法请参见 [命令列表及说明](#命令列表及说明) 和 [初级使用教程](#初级使用教程).
# 命令列表及说明
## 注意 ! ! !
命令的前缀 `BaiduPCS-Go` 为指向程序运行的全路径名 (ARGv 的第一个参数)
直接运行程序时, 未带任何其他参数, 则程序进入cli交互模式, 运行以下命令时, 要把命令的前缀 `BaiduPCS-Go` 去掉!
cli交互模式已支持按tab键自动补全命令和路径.
## 检测程序更新
```
BaiduPCS-Go update
```
## 登录百度帐号
### 常规登录百度帐号
支持在线验证绑定的手机号或邮箱,
```
BaiduPCS-Go login
```
### 使用百度 BDUSS 来登录百度帐号
[关于 获取百度 BDUSS](https://github.com/iikira/BaiduPCS-Go/wiki/关于-获取百度-BDUSS)
```
BaiduPCS-Go login -bduss=<BDUSS>
```
#### 例子
```
BaiduPCS-Go login -bduss=1234567
```
```
BaiduPCS-Go login
请输入百度用户名(手机号/邮箱/用户名), 回车键提交 > 1234567
```
## 列出帐号列表
```
BaiduPCS-Go loglist
```
获取当前帐号, 和所有已登录的百度帐号
## 切换百度帐号
切换已登录的百度帐号
```
BaiduPCS-Go su <uid>
```
```
BaiduPCS-Go su
请输入要切换帐号的 # 值 >
```
## 退出百度帐号
退出当前登录的百度帐号
```
BaiduPCS-Go logout
```
程序会进一步确认退出帐号, 防止误操作.
## 获取网盘配额
```
BaiduPCS-Go quota
```
获取网盘的总储存空间, 和已使用的储存空间
## 切换工作目录
```
BaiduPCS-Go cd <目录>
```
### 切换工作目录后自动列出工作目录下的文件和目录
```
BaiduPCS-Go cd -l <目录>
```
#### 例子
```
# 切换 /我的资源 工作目录
BaiduPCS-Go cd /我的资源
# 切换 上级目录
BaiduPCS-Go cd ..
# 切换 根目录
BaiduPCS-Go cd /
# 切换 /我的资源 工作目录, 并自动列出 /我的资源 下的文件和目录
BaiduPCS-Go cd -l 我的资源
# 使用通配符
BaiduPCS-Go cd /我的*
```
## 输出工作目录
```
BaiduPCS-Go pwd
```
## 列出目录
列出当前工作目录的文件和目录或指定目录
```
BaiduPCS-Go ls
```
```
BaiduPCS-Go ls <目录>
```
### 可选参数
```
-asc: 升序排序
-desc: 降序排序
-time: 根据时间排序
-name: 根据文件名排序
-size: 根据大小排序
```
#### 例子
```
# 列出 我的资源 内的文件和目录
BaiduPCS-Go ls 我的资源
# 绝对路径
BaiduPCS-Go ls /我的资源
# 降序排序
BaiduPCS-Go ls -desc 我的资源
# 按文件大小降序排序
BaiduPCS-Go ls -size -desc 我的资源
# 使用通配符
BaiduPCS-Go ls /我的*
```
## 列出目录树形图
列出当前工作目录的文件和目录或指定目录的树形图
```
BaiduPCS-Go tree <目录>
# 默认获取工作目录元信息
BaiduPCS-Go tree
```
## 获取单个文件/目录的元信息
获取单个文件/目录的元信息
```
BaiduPCS-Go meta <文件/目录>
```
```
# 默认获取工作目录元信息
BaiduPCS-Go meta
```
#### 例子
```
BaiduPCS-Go meta 我的资源
BaiduPCS-Go meta /
```
## 下载文件/目录
```
BaiduPCS-Go download <网盘文件或目录的路径1> <文件或目录2> <文件或目录3> ...
BaiduPCS-Go d <网盘文件或目录的路径1> <文件或目录2> <文件或目录3> ...
```
### 可选参数
```
-test: 测试下载, 此操作不会保存文件到本地
-status: 输出所有线程的工作状态
--save: 将下载的文件直接保存到当前工作目录
--saveto: 将下载的文件直接保存到指定的目录
-x: 为文件加上执行权限, (windows系统无效)
-p <num>: 指定下载的最大并发量
```
支持多个文件或目录的下载.
下载的文件默认保存到 **程序所在目录** 的 download/ 目录, 支持设置指定目录, 重名的文件会自动跳过!
[关于下载的简单说明](https://github.com/iikira/BaiduPCS-Go/wiki/%E5%85%B3%E4%BA%8E%E4%B8%8B%E8%BD%BD%E7%9A%84%E7%AE%80%E5%8D%95%E8%AF%B4%E6%98%8E)
#### 例子
```
# 设置保存目录, 保存到 D:\\Downloads
# 注意区别反斜杠 "\\" 和 斜杠 "/" !!!
BaiduPCS-Go config set -savedir D:/Downloads
# 下载 /我的资源/1.mp4
BaiduPCS-Go d /我的资源/1.mp4
# 下载 /我的资源 整个目录!!
BaiduPCS-Go d /我的资源
# 下载网盘内的全部文件!!
BaiduPCS-Go d /
BaiduPCS-Go d *
```
## 上传文件/目录
```
BaiduPCS-Go upload <本地文件/目录的路径1> <文件/目录2> <文件/目录3> ... <目标目录>
BaiduPCS-Go u <本地文件/目录的路径1> <文件/目录2> <文件/目录3> ... <目标目录>
```
* 上传的文件将会保存到, <目标目录>.
* 遇到同名文件将会自动覆盖!!
* 当上传的文件名和网盘的目录名称相同时, 不会覆盖目录, 防止丢失数据.
#### 例子:
```
# 将本地的 C:\\Users\\Administrator\\Desktop\\1.mp4 上传到网盘 /视频 目录
# 注意区别反斜杠 "\\" 和 斜杠 "/" !!!
BaiduPCS-Go upload C:/Users/Administrator/Desktop/1.mp4 /视频
# 将本地的 C:\\Users\\Administrator\\Desktop\\1.mp4 和 C:\\Users\\Administrator\\Desktop\\2.mp4 上传到网盘 /视频 目录
BaiduPCS-Go upload C:/Users/Administrator/Desktop/1.mp4 C:/Users/Administrator/Desktop/2.mp4 /视频
# 将本地的 C:\\Users\\Administrator\\Desktop 整个目录上传到网盘 /视频 目录
BaiduPCS-Go upload C:/Users/Administrator/Desktop /视频
```
## 手动秒传文件
```
BaiduPCS-Go rapidupload -length=<文件的大小> -md5=<文件的md5值> -slicemd5=<文件前256KB切片的md5值(可选)> -crc32=<文件的crc32值(可选)> <保存的网盘路径, 需包含文件名>
BaiduPCS-Go ru -length=<文件的大小> -md5=<文件的md5值> -slicemd5=<文件前256KB切片的md5值(可选)> -crc32=<文件的crc32值(可选)> <保存的网盘路径, 需包含文件名>
```
注意: 使用此功能秒传文件, 前提是知道文件的大小, md5, 前256KB切片的 md5 (可选), crc32 (可选), 且百度网盘中存在一模一样的文件.
上传的文件将会保存到网盘的目标目录.
遇到同名文件将会自动覆盖!
#### 例子:
```
# 如果秒传成功, 则保存到网盘路径 /test
BaiduPCS-Go rapidupload -length=56276137 -md5=fbe082d80e90f90f0fb1f94adbbcfa7f -slicemd5=38c6a75b0ec4499271d4ea38a667ab61 -crc32=314332359 /test
# 精简一下, 如果秒传成功, 则保存到网盘路径 /test
BaiduPCS-Go rapidupload -length=56276137 -md5=fbe082d80e90f90f0fb1f94adbbcfa7f /test
```
## 获取本地文件的秒传信息
```
BaiduPCS-Go sumfile <本地文件的路径>
BaiduPCS-Go sf <本地文件的路径>
```
获取本地文件的大小, md5, 前256KB切片的 md5, crc32, 可用于秒传文件.
#### 例子:
```
# 获取 C:\\Users\\Administrator\\Desktop\\1.mp4 的秒传信息
BaiduPCS-Go sumfile C:/Users/Administrator/Desktop/1.mp4
```
## 导出文件/目录
```
BaiduPCS-Go export <文件/目录1> <文件/目录2> ...
BaiduPCS-Go ep <文件/目录1> <文件/目录2> ...
```
导出网盘内的文件或目录, 原理为秒传文件, 此操作会生成导出文件或目录的命令.
#### 例子:
```
# 导出当前工作目录:
BaiduPCS-Go export
# 导出所有文件和目录, 并设置新的根目录为 `/root`
BaiduPCS-Go export -root=/root /
# 导出 `/我的资源`
BaiduPCS-Go export /我的资源
```
## 创建目录
```
BaiduPCS-Go mkdir <目录>
```
#### 例子
```
BaiduPCS-Go mkdir 123
```
## 删除文件/目录
```
BaiduPCS-Go rm <网盘文件或目录的路径1> <文件或目录2> <文件或目录3> ...
```
注意: 删除多个文件和目录时, 请确保每一个文件和目录都存在, 否则删除操作会失败.
被删除的文件或目录可在网盘文件回收站找回.
#### 例子
```
# 删除 /我的资源/1.mp4
BaiduPCS-Go rm /我的资源/1.mp4
# 删除 /我的资源/1.mp4 和 /我的资源/2.mp4
BaiduPCS-Go rm /我的资源/1.mp4 /我的资源/2.mp4
# 删除 /我的资源 内的所有文件和目录, 但不删除该目录
BaiduPCS-Go rm /我的资源/*
# 删除 /我的资源 整个目录 !!
BaiduPCS-Go rm /我的资源
```
## 拷贝文件/目录
```
BaiduPCS-Go cp <文件/目录> <目标 文件/目录>
BaiduPCS-Go cp <文件/目录1> <文件/目录2> <文件/目录3> ... <目标目录>
```
注意: 拷贝多个文件和目录时, 请确保每一个文件和目录都存在, 否则拷贝操作会失败.
#### 例子
```
# 将 /我的资源/1.mp4 复制到 根目录 /
BaiduPCS-Go cp /我的资源/1.mp4 /
# 将 /我的资源/1.mp4 和 /我的资源/2.mp4 复制到 根目录 /
BaiduPCS-Go cp /我的资源/1.mp4 /我的资源/2.mp4 /
```
## 移动/重命名文件/目录
```
# 移动:
BaiduPCS-Go mv <文件/目录1> <文件/目录2> <文件/目录3> ... <目标目录>
# 重命名:
BaiduPCS-Go mv <文件/目录> <重命名的文件/目录>
```
注意: 移动多个文件和目录时, 请确保每一个文件和目录都存在, 否则移动操作会失败.
#### 例子
```
# 将 /我的资源/1.mp4 移动到 根目录 /
BaiduPCS-Go mv /我的资源/1.mp4 /
# 将 /我的资源/1.mp4 重命名为 /我的资源/3.mp4
BaiduPCS-Go mv /我的资源/1.mp4 /我的资源/3.mp4
```
## 离线下载
```
BaiduPCS-Go offlinedl
BaiduPCS-Go clouddl
BaiduPCS-Go od
```
离线下载支持http/https/ftp/电驴/磁力链协议
### 添加离线下载任务
```
BaiduPCS-Go offlinedl add -path=<离线下载文件保存的路径> 资源地址1 地址2 ...
```
添加任务成功之后, 返回离线下载的任务ID.
### 精确查询离线下载任务
```
BaiduPCS-Go offlinedl query 任务ID1 任务ID2 ...
```
### 查询离线下载任务列表
```
BaiduPCS-Go offlinedl list
```
### 取消离线下载任务
```
BaiduPCS-Go offlinedl cancel 任务ID1 任务ID2 ...
```
### 删除离线下载任务
```
BaiduPCS-Go offlinedl delete 任务ID1 任务ID2 ...
```
#### 例子
```
# 将百度和腾讯主页, 离线下载到根目录 /
BaiduPCS-Go offlinedl add -path=/ http://baidu.com http://qq.com
# 添加磁力链接任务
BaiduPCS-Go offlinedl add magnet:?xt=urn:btih:xxx
# 查询任务ID为 12345 的离线下载任务状态
BaiduPCS-Go offlinedl query 12345
# 取消任务ID为 12345 的离线下载任务
BaiduPCS-Go offlinedl cancel 12345
```
## 显示程序环境变量
```
BaiduPCS-Go env
```
BAIDUPCS_GO_CONFIG_DIR: 为具体的存储目录,
BAIDUPCS_GO_VERBOSE: 是否启用调试.
## 显示和修改程序配置项
```
# 显示配置
BaiduPCS-Go config
# 设置配置
BaiduPCS-Go config set
```
注意: v3.5 以后, 程序对配置文件储存路径的寻找做了调整, 配置文件所在的目录可以是程序本身所在目录, 也可以是家目录.
配置文件所在的目录为家目录的情况:
Windows: `%APPDATA%\\BaiduPCS-Go`
其他操作系统: `$HOME/.config/BaiduPCS-Go`
可通过设置环境变量 `BAIDUPCS_GO_CONFIG_DIR`, 指定配置文件存放的目录.
#### 例子
```
# 显示所有可以设置的值
BaiduPCS-Go config -h
BaiduPCS-Go config set -h
# 设置下载文件的储存目录
BaiduPCS-Go config set -savedir D:/Downloads
# 设置下载最大并发量为 150
BaiduPCS-Go config set -max_parallel 150
# 组合设置
BaiduPCS-Go config set -max_parallel 150 -savedir D:/Downloads
```
## 工具箱
```
BaiduPCS-Go tool
```
目前工具箱支持加解密文件等.
# 初级使用教程
新手建议: **双击运行程序**, 进入仿 Linux shell 的 cli 交互模式;
cli交互模式下, 光标所在行的前缀应为 `BaiduPCS-Go >`, 如果登录了百度帐号则格式为 `BaiduPCS-Go:<工作目录> <百度ID>$ `
以下例子的命令, 均为 cli交互模式下的命令
运行命令的正确操作: **输入命令, 按一下回车键 (键盘上的 Enter 键)**, 程序会接收到命令并输出结果
## 1. 查看程序使用说明
cli交互模式下, 运行命令 `help`
## 2. 登录百度帐号 (必做)
cli交互模式下, 运行命令 `login -h` (注意空格) 查看帮助
cli交互模式下, 运行命令 `login` 程序将会提示你输入百度用户名(手机号/邮箱/用户名)和密码, 必要时还可以在线验证绑定的手机号或邮箱
## 3. 切换网盘工作目录
cli交互模式下, 运行命令 `cd /我的资源` 将工作目录切换为 `/我的资源` (前提: 该目录存在于网盘)
目录支持通配符匹配, 所以你也可以这样: 运行命令 `cd /我的*` 或 `cd /我的??` 将工作目录切换为 `/我的资源`, 简化输入.
将工作目录切换为 `/我的资源` 成功后, 运行命令 `cd ..` 切换上级目录, 即将工作目录切换为 `/`
为什么要这样设计呢, 举个例子,
假设 你要下载 `/我的资源` 内名为 `1.mp4` 和 `2.mp4` 两个文件, 而未切换工作目录, 你需要依次运行以下命令:
```
d /我的资源/1.mp4
d /我的资源/2.mp4
```
而切换网盘工作目录之后, 依次运行以下命令:
```
cd /我的资源
d 1.mp4
d 2.mp4
```
这样就达到了简化输入的目的
## 4. 网盘内列出文件和目录
cli交互模式下, 运行命令 `ls -h` (注意空格) 查看帮助
cli交互模式下, 运行命令 `ls` 来列出当前所在目录的文件和目录
cli交互模式下, 运行命令 `ls /我的资源` 来列出 `/我的资源` 内的文件和目录
cli交互模式下, 运行命令 `ls ..` 来列出当前所在目录的上级目录的文件和目录
## 5. 下载文件
说明: 下载的文件默认保存到 download/ 目录 (文件夹)
cli交互模式下, 运行命令 `d -h` (注意空格) 查看帮助
cli交互模式下, 运行命令 `d /我的资源/1.mp4` 来下载位于 `/我的资源/1.mp4` 的文件 `1.mp4` , 该操作等效于运行以下命令:
```
cd /我的资源
d 1.mp4
```
现在已经支持目录 (文件夹) 下载, 所以, 运行以下命令, 会下载 `/我的资源` 内的所有文件 (违规文件除外):
```
d /我的资源
```
参见 例6 设置下载最大并发量
## 6. 设置下载最大并发量
cli交互模式下, 运行命令 `config set -h` (注意空格) 查看设置帮助以及可供设置的值
cli交互模式下, 运行命令 `config set -max_parallel 250` 将下载最大并发量设置为 250
下载最大并发量建议值: 50~500, 太低下载速度提升不明显甚至速度会变为0, 太高可能会导致程序出错被操作系统结束掉.
## 7. 退出程序
运行命令 `quit` 或 `exit` 或 组合键 `Ctrl+C` 或 组合键 `Ctrl+D`
# 常见问题
参见 [常见问题](https://github.com/iikira/BaiduPCS-Go/wiki/%E5%B8%B8%E8%A7%81%E9%97%AE%E9%A2%98)
# TODO
1. 上传大文件;
2. 回收站操作, 例如查询回收站文件, 还原文件或目录等.
# 交流反馈
提交Issue: [Issues](https://github.com/iikira/BaiduPCS-Go/issues)
邮箱: <EMAIL>
QQ群: 178324706
# 捐助
如果你愿意.
| 支付宝 |
| :-----------------------------------: |
|  |
'''
tags: []
isStarred: false
isTrashed: false
| true | createdAt: "2018-05-17T05:40:35.726Z"
updatedAt: "2018-05-17T05:42:09.604Z"
type: "MARKDOWN_NOTE"
folder: "86d729dde83c4a092177"
title: "BaiduPCS-Go 百度网盘客户端"
content: '''
# BaiduPCS-Go 百度网盘客户端
[](https://ci.appveyor.com/project/iikira/baidupcs-go)
[](https://godoc.org/github.com/iikira/BaiduPCS-Go)
仿 Linux shell 文件处理命令的百度网盘命令行客户端.
This project was largely inspired by [GangZhuo/BaiduPCS](https://github.com/GangZhuo/BaiduPCS)
<!-- toc -->
- [特色](#特色)
- [编译/交叉编译 说明](#编译交叉编译-说明)
- [下载/运行 说明](#下载运行-说明)
* [Windows](#windows)
* [Linux / macOS](#linux--macos)
* [Android / iOS](#android--ios)
- [命令列表及说明](#命令列表及说明)
* [注意 ! ! !](#注意---)
* [检测程序更新](#检测程序更新)
* [登录百度帐号](#登录百度帐号)
* [列出帐号列表](#列出帐号列表)
* [切换百度帐号](#切换百度帐号)
* [退出百度帐号](#退出百度帐号)
* [获取网盘配额](#获取网盘配额)
* [切换工作目录](#切换工作目录)
* [输出工作目录](#输出工作目录)
* [列出目录](#列出目录)
* [列出目录树形图](#列出目录树形图)
* [获取单个文件/目录的元信息](#获取单个文件目录的元信息)
* [下载文件/目录](#下载文件目录)
* [上传文件/目录](#上传文件目录)
* [手动秒传文件](#手动秒传文件)
* [获取本地文件的秒传信息](#获取本地文件的秒传信息)
* [导出文件/目录](#导出文件目录)
* [创建目录](#创建目录)
* [删除文件/目录](#删除文件目录)
* [拷贝文件/目录](#拷贝文件目录)
* [移动/重命名文件/目录](#移动重命名文件目录)
* [离线下载](#离线下载)
+ [添加离线下载任务](#添加离线下载任务)
+ [精确查询离线下载任务](#精确查询离线下载任务)
+ [查询离线下载任务列表](#查询离线下载任务列表)
+ [取消离线下载任务](#取消离线下载任务)
+ [删除离线下载任务](#删除离线下载任务)
* [显示和修改程序配置项](#显示和修改程序配置项)
* [工具箱](#工具箱)
- [初级使用教程](#初级使用教程)
* [1. 查看程序使用说明](#1-查看程序使用说明)
* [2. 登录百度帐号 (必做)](#2-登录百度帐号-必做)
* [3. 切换网盘工作目录](#3-切换网盘工作目录)
* [4. 网盘内列出文件和目录](#4-网盘内列出文件和目录)
* [5. 下载文件](#5-下载文件)
* [6. 设置下载最大并发量](#6-设置下载最大并发量)
* [7. 退出程序](#7-退出程序)
- [常见问题](#常见问题)
- [TODO](#todo)
- [交流反馈](#交流反馈)
- [捐助](#捐助)
<!-- tocstop -->
# 特色
多平台支持, 支持 Windows, macOS, linux, 移动设备等.
百度帐号多用户支持;
通配符匹配网盘路径和 Tab 自动补齐命令和路径, [通配符_百度百科](https://baike.baidu.com/item/通配符);
[下载](#下载文件或目录)网盘内文件, 支持多个文件或目录下载, 支持断点续传和单文件并行下载;
[上传](#上传文件或目录)2GB以内的文件, 支持多个文件或目录上传;
[离线下载](#离线下载), 支持http/https/ftp/电驴/磁力链协议.
# 编译/交叉编译 说明
参见 [编译/交叉编译帮助](https://github.com/iikira/BaiduPCS-Go/wiki/编译-交叉编译帮助)
# 下载/运行 说明
Go语言程序, 可直接在[发布页](https://github.com/iikira/BaiduPCS-Go/releases)下载使用.
如果程序运行时输出乱码, 请检查下终端的编码方式是否为 `UTF-8`.
使用本程序之前, 建议学习一些 linux 基础知识 和 基础命令.
如果未带任何参数运行程序, 程序将会进入仿Linux shell系统用户界面的cli交互模式, 可直接运行相关命令.
cli交互模式下, 光标所在行的前缀应为 `BaiduPCS-Go >`, 如果登录了百度帐号则格式为 `BaiduPCS-Go:<工作目录> <百度ID>$ `
程序会提供相关命令的使用说明.
## Windows
程序应在 命令提示符 (Command Prompt) 或 PowerShell 中运行, 在 mintty (例如: GitBash) 可能会有显示问题.
也可直接双击程序运行, 具体使用方法请参见 [命令列表及说明](#命令列表及说明) 和 [初级使用教程](#初级使用教程).
## Linux / macOS
程序应在 终端 (Terminal) 运行.
具体使用方法请参见 [命令列表及说明](#命令列表及说明) 和 [初级使用教程](#初级使用教程).
## Android / iOS
> Android / iOS 移动设备操作比较麻烦, 不建议在移动设备上使用本程序.
安卓, 建议使用 [Termux](https://termux.com) 或 [NeoTerm](https://github.com/NeoTerm/NeoTerm) 或 终端模拟器, 以提供终端环境.
示例: [Android 运行本项目程序参考示例](https://github.com/iikira/BaiduPCS-Go/wiki/Android-运行本项目程序参考示例), 有兴趣的可以参考一下.
苹果iOS, 需要越狱, 在 Cydia 搜索下载并安装 MobileTerminal, 或者其他提供终端环境的软件.
示例: [iOS 运行本项目程序参考示例](https://github.com/iikira/BaiduPCS-Go/wiki/iOS-运行本项目程序参考示例), 有兴趣的可以参考一下.
具体使用方法请参见 [命令列表及说明](#命令列表及说明) 和 [初级使用教程](#初级使用教程).
# 命令列表及说明
## 注意 ! ! !
命令的前缀 `BaiduPCS-Go` 为指向程序运行的全路径名 (ARGv 的第一个参数)
直接运行程序时, 未带任何其他参数, 则程序进入cli交互模式, 运行以下命令时, 要把命令的前缀 `BaiduPCS-Go` 去掉!
cli交互模式已支持按tab键自动补全命令和路径.
## 检测程序更新
```
BaiduPCS-Go update
```
## 登录百度帐号
### 常规登录百度帐号
支持在线验证绑定的手机号或邮箱,
```
BaiduPCS-Go login
```
### 使用百度 BDUSS 来登录百度帐号
[关于 获取百度 BDUSS](https://github.com/iikira/BaiduPCS-Go/wiki/关于-获取百度-BDUSS)
```
BaiduPCS-Go login -bduss=<BDUSS>
```
#### 例子
```
BaiduPCS-Go login -bduss=1234567
```
```
BaiduPCS-Go login
请输入百度用户名(手机号/邮箱/用户名), 回车键提交 > 1234567
```
## 列出帐号列表
```
BaiduPCS-Go loglist
```
获取当前帐号, 和所有已登录的百度帐号
## 切换百度帐号
切换已登录的百度帐号
```
BaiduPCS-Go su <uid>
```
```
BaiduPCS-Go su
请输入要切换帐号的 # 值 >
```
## 退出百度帐号
退出当前登录的百度帐号
```
BaiduPCS-Go logout
```
程序会进一步确认退出帐号, 防止误操作.
## 获取网盘配额
```
BaiduPCS-Go quota
```
获取网盘的总储存空间, 和已使用的储存空间
## 切换工作目录
```
BaiduPCS-Go cd <目录>
```
### 切换工作目录后自动列出工作目录下的文件和目录
```
BaiduPCS-Go cd -l <目录>
```
#### 例子
```
# 切换 /我的资源 工作目录
BaiduPCS-Go cd /我的资源
# 切换 上级目录
BaiduPCS-Go cd ..
# 切换 根目录
BaiduPCS-Go cd /
# 切换 /我的资源 工作目录, 并自动列出 /我的资源 下的文件和目录
BaiduPCS-Go cd -l 我的资源
# 使用通配符
BaiduPCS-Go cd /我的*
```
## 输出工作目录
```
BaiduPCS-Go pwd
```
## 列出目录
列出当前工作目录的文件和目录或指定目录
```
BaiduPCS-Go ls
```
```
BaiduPCS-Go ls <目录>
```
### 可选参数
```
-asc: 升序排序
-desc: 降序排序
-time: 根据时间排序
-name: 根据文件名排序
-size: 根据大小排序
```
#### 例子
```
# 列出 我的资源 内的文件和目录
BaiduPCS-Go ls 我的资源
# 绝对路径
BaiduPCS-Go ls /我的资源
# 降序排序
BaiduPCS-Go ls -desc 我的资源
# 按文件大小降序排序
BaiduPCS-Go ls -size -desc 我的资源
# 使用通配符
BaiduPCS-Go ls /我的*
```
## 列出目录树形图
列出当前工作目录的文件和目录或指定目录的树形图
```
BaiduPCS-Go tree <目录>
# 默认获取工作目录元信息
BaiduPCS-Go tree
```
## 获取单个文件/目录的元信息
获取单个文件/目录的元信息
```
BaiduPCS-Go meta <文件/目录>
```
```
# 默认获取工作目录元信息
BaiduPCS-Go meta
```
#### 例子
```
BaiduPCS-Go meta 我的资源
BaiduPCS-Go meta /
```
## 下载文件/目录
```
BaiduPCS-Go download <网盘文件或目录的路径1> <文件或目录2> <文件或目录3> ...
BaiduPCS-Go d <网盘文件或目录的路径1> <文件或目录2> <文件或目录3> ...
```
### 可选参数
```
-test: 测试下载, 此操作不会保存文件到本地
-status: 输出所有线程的工作状态
--save: 将下载的文件直接保存到当前工作目录
--saveto: 将下载的文件直接保存到指定的目录
-x: 为文件加上执行权限, (windows系统无效)
-p <num>: 指定下载的最大并发量
```
支持多个文件或目录的下载.
下载的文件默认保存到 **程序所在目录** 的 download/ 目录, 支持设置指定目录, 重名的文件会自动跳过!
[关于下载的简单说明](https://github.com/iikira/BaiduPCS-Go/wiki/%E5%85%B3%E4%BA%8E%E4%B8%8B%E8%BD%BD%E7%9A%84%E7%AE%80%E5%8D%95%E8%AF%B4%E6%98%8E)
#### 例子
```
# 设置保存目录, 保存到 D:\\Downloads
# 注意区别反斜杠 "\\" 和 斜杠 "/" !!!
BaiduPCS-Go config set -savedir D:/Downloads
# 下载 /我的资源/1.mp4
BaiduPCS-Go d /我的资源/1.mp4
# 下载 /我的资源 整个目录!!
BaiduPCS-Go d /我的资源
# 下载网盘内的全部文件!!
BaiduPCS-Go d /
BaiduPCS-Go d *
```
## 上传文件/目录
```
BaiduPCS-Go upload <本地文件/目录的路径1> <文件/目录2> <文件/目录3> ... <目标目录>
BaiduPCS-Go u <本地文件/目录的路径1> <文件/目录2> <文件/目录3> ... <目标目录>
```
* 上传的文件将会保存到, <目标目录>.
* 遇到同名文件将会自动覆盖!!
* 当上传的文件名和网盘的目录名称相同时, 不会覆盖目录, 防止丢失数据.
#### 例子:
```
# 将本地的 C:\\Users\\Administrator\\Desktop\\1.mp4 上传到网盘 /视频 目录
# 注意区别反斜杠 "\\" 和 斜杠 "/" !!!
BaiduPCS-Go upload C:/Users/Administrator/Desktop/1.mp4 /视频
# 将本地的 C:\\Users\\Administrator\\Desktop\\1.mp4 和 C:\\Users\\Administrator\\Desktop\\2.mp4 上传到网盘 /视频 目录
BaiduPCS-Go upload C:/Users/Administrator/Desktop/1.mp4 C:/Users/Administrator/Desktop/2.mp4 /视频
# 将本地的 C:\\Users\\Administrator\\Desktop 整个目录上传到网盘 /视频 目录
BaiduPCS-Go upload C:/Users/Administrator/Desktop /视频
```
## 手动秒传文件
```
BaiduPCS-Go rapidupload -length=<文件的大小> -md5=<文件的md5值> -slicemd5=<文件前256KB切片的md5值(可选)> -crc32=<文件的crc32值(可选)> <保存的网盘路径, 需包含文件名>
BaiduPCS-Go ru -length=<文件的大小> -md5=<文件的md5值> -slicemd5=<文件前256KB切片的md5值(可选)> -crc32=<文件的crc32值(可选)> <保存的网盘路径, 需包含文件名>
```
注意: 使用此功能秒传文件, 前提是知道文件的大小, md5, 前256KB切片的 md5 (可选), crc32 (可选), 且百度网盘中存在一模一样的文件.
上传的文件将会保存到网盘的目标目录.
遇到同名文件将会自动覆盖!
#### 例子:
```
# 如果秒传成功, 则保存到网盘路径 /test
BaiduPCS-Go rapidupload -length=56276137 -md5=fbe082d80e90f90f0fb1f94adbbcfa7f -slicemd5=38c6a75b0ec4499271d4ea38a667ab61 -crc32=314332359 /test
# 精简一下, 如果秒传成功, 则保存到网盘路径 /test
BaiduPCS-Go rapidupload -length=56276137 -md5=fbe082d80e90f90f0fb1f94adbbcfa7f /test
```
## 获取本地文件的秒传信息
```
BaiduPCS-Go sumfile <本地文件的路径>
BaiduPCS-Go sf <本地文件的路径>
```
获取本地文件的大小, md5, 前256KB切片的 md5, crc32, 可用于秒传文件.
#### 例子:
```
# 获取 C:\\Users\\Administrator\\Desktop\\1.mp4 的秒传信息
BaiduPCS-Go sumfile C:/Users/Administrator/Desktop/1.mp4
```
## 导出文件/目录
```
BaiduPCS-Go export <文件/目录1> <文件/目录2> ...
BaiduPCS-Go ep <文件/目录1> <文件/目录2> ...
```
导出网盘内的文件或目录, 原理为秒传文件, 此操作会生成导出文件或目录的命令.
#### 例子:
```
# 导出当前工作目录:
BaiduPCS-Go export
# 导出所有文件和目录, 并设置新的根目录为 `/root`
BaiduPCS-Go export -root=/root /
# 导出 `/我的资源`
BaiduPCS-Go export /我的资源
```
## 创建目录
```
BaiduPCS-Go mkdir <目录>
```
#### 例子
```
BaiduPCS-Go mkdir 123
```
## 删除文件/目录
```
BaiduPCS-Go rm <网盘文件或目录的路径1> <文件或目录2> <文件或目录3> ...
```
注意: 删除多个文件和目录时, 请确保每一个文件和目录都存在, 否则删除操作会失败.
被删除的文件或目录可在网盘文件回收站找回.
#### 例子
```
# 删除 /我的资源/1.mp4
BaiduPCS-Go rm /我的资源/1.mp4
# 删除 /我的资源/1.mp4 和 /我的资源/2.mp4
BaiduPCS-Go rm /我的资源/1.mp4 /我的资源/2.mp4
# 删除 /我的资源 内的所有文件和目录, 但不删除该目录
BaiduPCS-Go rm /我的资源/*
# 删除 /我的资源 整个目录 !!
BaiduPCS-Go rm /我的资源
```
## 拷贝文件/目录
```
BaiduPCS-Go cp <文件/目录> <目标 文件/目录>
BaiduPCS-Go cp <文件/目录1> <文件/目录2> <文件/目录3> ... <目标目录>
```
注意: 拷贝多个文件和目录时, 请确保每一个文件和目录都存在, 否则拷贝操作会失败.
#### 例子
```
# 将 /我的资源/1.mp4 复制到 根目录 /
BaiduPCS-Go cp /我的资源/1.mp4 /
# 将 /我的资源/1.mp4 和 /我的资源/2.mp4 复制到 根目录 /
BaiduPCS-Go cp /我的资源/1.mp4 /我的资源/2.mp4 /
```
## 移动/重命名文件/目录
```
# 移动:
BaiduPCS-Go mv <文件/目录1> <文件/目录2> <文件/目录3> ... <目标目录>
# 重命名:
BaiduPCS-Go mv <文件/目录> <重命名的文件/目录>
```
注意: 移动多个文件和目录时, 请确保每一个文件和目录都存在, 否则移动操作会失败.
#### 例子
```
# 将 /我的资源/1.mp4 移动到 根目录 /
BaiduPCS-Go mv /我的资源/1.mp4 /
# 将 /我的资源/1.mp4 重命名为 /我的资源/3.mp4
BaiduPCS-Go mv /我的资源/1.mp4 /我的资源/3.mp4
```
## 离线下载
```
BaiduPCS-Go offlinedl
BaiduPCS-Go clouddl
BaiduPCS-Go od
```
离线下载支持http/https/ftp/电驴/磁力链协议
### 添加离线下载任务
```
BaiduPCS-Go offlinedl add -path=<离线下载文件保存的路径> 资源地址1 地址2 ...
```
添加任务成功之后, 返回离线下载的任务ID.
### 精确查询离线下载任务
```
BaiduPCS-Go offlinedl query 任务ID1 任务ID2 ...
```
### 查询离线下载任务列表
```
BaiduPCS-Go offlinedl list
```
### 取消离线下载任务
```
BaiduPCS-Go offlinedl cancel 任务ID1 任务ID2 ...
```
### 删除离线下载任务
```
BaiduPCS-Go offlinedl delete 任务ID1 任务ID2 ...
```
#### 例子
```
# 将百度和腾讯主页, 离线下载到根目录 /
BaiduPCS-Go offlinedl add -path=/ http://baidu.com http://qq.com
# 添加磁力链接任务
BaiduPCS-Go offlinedl add magnet:?xt=urn:btih:xxx
# 查询任务ID为 12345 的离线下载任务状态
BaiduPCS-Go offlinedl query 12345
# 取消任务ID为 12345 的离线下载任务
BaiduPCS-Go offlinedl cancel 12345
```
## 显示程序环境变量
```
BaiduPCS-Go env
```
BAIDUPCS_GO_CONFIG_DIR: 为具体的存储目录,
BAIDUPCS_GO_VERBOSE: 是否启用调试.
## 显示和修改程序配置项
```
# 显示配置
BaiduPCS-Go config
# 设置配置
BaiduPCS-Go config set
```
注意: v3.5 以后, 程序对配置文件储存路径的寻找做了调整, 配置文件所在的目录可以是程序本身所在目录, 也可以是家目录.
配置文件所在的目录为家目录的情况:
Windows: `%APPDATA%\\BaiduPCS-Go`
其他操作系统: `$HOME/.config/BaiduPCS-Go`
可通过设置环境变量 `BAIDUPCS_GO_CONFIG_DIR`, 指定配置文件存放的目录.
#### 例子
```
# 显示所有可以设置的值
BaiduPCS-Go config -h
BaiduPCS-Go config set -h
# 设置下载文件的储存目录
BaiduPCS-Go config set -savedir D:/Downloads
# 设置下载最大并发量为 150
BaiduPCS-Go config set -max_parallel 150
# 组合设置
BaiduPCS-Go config set -max_parallel 150 -savedir D:/Downloads
```
## 工具箱
```
BaiduPCS-Go tool
```
目前工具箱支持加解密文件等.
# 初级使用教程
新手建议: **双击运行程序**, 进入仿 Linux shell 的 cli 交互模式;
cli交互模式下, 光标所在行的前缀应为 `BaiduPCS-Go >`, 如果登录了百度帐号则格式为 `BaiduPCS-Go:<工作目录> <百度ID>$ `
以下例子的命令, 均为 cli交互模式下的命令
运行命令的正确操作: **输入命令, 按一下回车键 (键盘上的 Enter 键)**, 程序会接收到命令并输出结果
## 1. 查看程序使用说明
cli交互模式下, 运行命令 `help`
## 2. 登录百度帐号 (必做)
cli交互模式下, 运行命令 `login -h` (注意空格) 查看帮助
cli交互模式下, 运行命令 `login` 程序将会提示你输入百度用户名(手机号/邮箱/用户名)和密码, 必要时还可以在线验证绑定的手机号或邮箱
## 3. 切换网盘工作目录
cli交互模式下, 运行命令 `cd /我的资源` 将工作目录切换为 `/我的资源` (前提: 该目录存在于网盘)
目录支持通配符匹配, 所以你也可以这样: 运行命令 `cd /我的*` 或 `cd /我的??` 将工作目录切换为 `/我的资源`, 简化输入.
将工作目录切换为 `/我的资源` 成功后, 运行命令 `cd ..` 切换上级目录, 即将工作目录切换为 `/`
为什么要这样设计呢, 举个例子,
假设 你要下载 `/我的资源` 内名为 `1.mp4` 和 `2.mp4` 两个文件, 而未切换工作目录, 你需要依次运行以下命令:
```
d /我的资源/1.mp4
d /我的资源/2.mp4
```
而切换网盘工作目录之后, 依次运行以下命令:
```
cd /我的资源
d 1.mp4
d 2.mp4
```
这样就达到了简化输入的目的
## 4. 网盘内列出文件和目录
cli交互模式下, 运行命令 `ls -h` (注意空格) 查看帮助
cli交互模式下, 运行命令 `ls` 来列出当前所在目录的文件和目录
cli交互模式下, 运行命令 `ls /我的资源` 来列出 `/我的资源` 内的文件和目录
cli交互模式下, 运行命令 `ls ..` 来列出当前所在目录的上级目录的文件和目录
## 5. 下载文件
说明: 下载的文件默认保存到 download/ 目录 (文件夹)
cli交互模式下, 运行命令 `d -h` (注意空格) 查看帮助
cli交互模式下, 运行命令 `d /我的资源/1.mp4` 来下载位于 `/我的资源/1.mp4` 的文件 `1.mp4` , 该操作等效于运行以下命令:
```
cd /我的资源
d 1.mp4
```
现在已经支持目录 (文件夹) 下载, 所以, 运行以下命令, 会下载 `/我的资源` 内的所有文件 (违规文件除外):
```
d /我的资源
```
参见 例6 设置下载最大并发量
## 6. 设置下载最大并发量
cli交互模式下, 运行命令 `config set -h` (注意空格) 查看设置帮助以及可供设置的值
cli交互模式下, 运行命令 `config set -max_parallel 250` 将下载最大并发量设置为 250
下载最大并发量建议值: 50~500, 太低下载速度提升不明显甚至速度会变为0, 太高可能会导致程序出错被操作系统结束掉.
## 7. 退出程序
运行命令 `quit` 或 `exit` 或 组合键 `Ctrl+C` 或 组合键 `Ctrl+D`
# 常见问题
参见 [常见问题](https://github.com/iikira/BaiduPCS-Go/wiki/%E5%B8%B8%E8%A7%81%E9%97%AE%E9%A2%98)
# TODO
1. 上传大文件;
2. 回收站操作, 例如查询回收站文件, 还原文件或目录等.
# 交流反馈
提交Issue: [Issues](https://github.com/iikira/BaiduPCS-Go/issues)
邮箱: PI:EMAIL:<EMAIL>END_PI
QQ群: 178324706
# 捐助
如果你愿意.
| 支付宝 |
| :-----------------------------------: |
|  |
'''
tags: []
isStarred: false
isTrashed: false
|
[
{
"context": "te CollectionName { id: \"users/tony\", firstName: \"Tony\" })'\n action: (args) ->\n try\n matc",
"end": 2382,
"score": 0.9995777010917664,
"start": 2378,
"tag": "NAME",
"value": "Tony"
},
{
"context": "ject> [start [count]]\" (e.g., .find { firstName: \... | src/shell.coffee | tchype/raven-shell | 1 | #!/usr/bin/env coffee
repl = require('repl')
ravendb = require('ravendb')
ArgumentParser = require('argparse').ArgumentParser
version = '0.0.10' # Keep in sync with package.json
createDatastore = (r, url, databaseName) ->
r.context.db = ravendb(url, databaseName)
r.context.store = r.context.db.datastore
useDatabase = (r, databaseName) ->
throw new Error('The datastore must first be set') unless r?.context?.store?
r.context.db = ravendb(r.context.store.url, databaseName)
currentDatabaseString = (r) ->
'Using database "' + r.context.db.name + '" in datastore at: "' + r.context.store.url + '"'
defineCommands = (r) ->
r.defineCommand 'store',
help: 'Use the RavenDB datastore at a url ".store <url>"'
action: (url) ->
if url?
createDatastore(r, url, r.context.db.name) # TODO: IS THIS A GOOD IDEA, TO USE THE SAME DB NAME?
else
url = r.context.store.url
console.log currentDatabaseString(r)
r.displayPrompt()
r.defineCommand 'use',
help: 'Use the database with the given name ".use <database-name>"'
action: (name) ->
if name?
useDatabase(r, name)
else
name = r.context.db.name
console.log currentDatabaseString(r)
r.displayPrompt()
r.defineCommand 'stats',
help: 'Show statistics for the current database'
action: ->
try
r.context.db.getStats (error, stats) ->
if error?
console.error error
r.displayPrompt()
return
console.log stats
r.context._ = stats
r.displayPrompt()
catch e
console.error e
r.displayPrompt()
r.defineCommand 'collections',
help: 'Show all collections in the current database'
action: ->
try
r.context.db.getCollections (error, collections) ->
if error?
console.error error
r.displayPrompt()
return
if collections?.length?
console.log collection for collection in collections
else
console.log "No collections found."
r.context._ = collections
r.displayPrompt()
catch e
console.error e
r.displayPrompt()
r.defineCommand 'create',
help: 'Save a document to a collection (e.g., .create CollectionName { id: "users/tony", firstName: "Tony" })'
action: (args) ->
try
match = /(\w+)\s+(.*)/.exec(args)
throw Error('Wrong number of arguments; see .help for .savedoc usage') if match.length != 3
collection = match[1]
eval('doc = ' + match[2])
r.context.db.saveDocument collection, doc, (error, result) ->
console.error error if error?
console.log result if result?
r.context._ = result
r.displayPrompt()
catch e
console.error e
r.displayPrompt()
r.defineCommand 'read',
help: 'Get a document given its id (e.g., .read users/tony)',
action: (args) ->
try
throw Error('Wrong number of arguments; see .help for more information') unless args?
id = args
r.context.db.getDocument id, (error, result) ->
console.error error if error?
console.log result if result?
r.context._ = result
r.displayPrompt()
catch e
console.error e
r.displayPrompt()
r.defineCommand 'delete',
help: 'Delete a document given its id (e.g., .delete users/tony)'
action: (args) ->
try
throw Error('Wrong number of arguments; see .help for more information') unless args?
id = args
r.context.db.deleteDocument id, (error, result) ->
console.error error if error?
console.log result if result?
r.context._ = result
r.displayPrompt()
catch e
console.error e
r.displayPrompt()
r.defineCommand 'find',
help: 'Find documents ".find <JSON object> [start [count]]" (e.g., .find { firstName: "Tony" } 20 100)'
action: (args) ->
try
throw Error('Wrong number of arguments; see .help for .find usage') unless args?
# Parse args: { attr: value } [start [count]]
# .find { some: 'thing'} 20 100
# ^-------1------^^--2--^
# 3 5
# ^4-^
# match[0] = "{ some: 'thing'} 20 100"
# match[1] = "{ some: 'thing'}"
# match[2] = " 20 100"
# match[3] = "20"
# match[4] = " 100"
# match[5] = "100"
match = /(\{.*\})(\s+(\d+)(\s+(\d+))?)?/.exec(args)
eval('doc = ' + match[1])
start = if match[3]? then parseInt(match[3]) else null
count = if match[5]? then parseInt(match[5]) else null
r.context.db.find doc, start, count, (error, result) ->
console.error error if error?
console.log result if result?
r.context._ = result
r.displayPrompt()
catch e
console.error e
r.displayPrompt()
r.defineCommand 'docs',
help: 'Retrieve documents in a collection (e.g., .doc Users)'
action: (args) ->
try
# Parse args: [collection [start [count]]]
# .count Users 50 100
# ^-1-^^--2--^
# 3 5
# ^4-^
# match[0] = "Users 50 100"
# match[1] = "Users"
# match[2] = " 50 100"
# match[3] = "50"
# match[4] = " 100"
# match[5] = "100"
match = /(\w+)(\s+(\d+)(\s+(\d+))?)?/.exec(args)
collection = start = count = null
if match?
collection = match[1]
start = if match[3]? then parseInt(match[3]) else null
count = if match[5]? then parseInt(match[5]) else null
r.context.db.getDocsInCollection collection, start, count, (error, result) ->
console.error error if error?
console.log result if result?
r.context._ = result
r.displayPrompt()
catch e
console.error e
r.displayPrompt()
r.defineCommand 'count',
help: 'Show the count of documents in a collection or in the database if left blank (e.g., .count Users)'
action: (args) ->
try
collection = args || null
r.context.db.getDocumentCount collection, (error, result) ->
console.error error if error?
console.log result if result?
r.context._ = result
r.displayPrompt()
catch e
console.error e
r.displayPrompt()
r.defineCommand 'createIndex',
help: "Create an index with a name, map, and optional reduce: .create-index foobar { map: 'from doc in docs.Albums\rwhere doc.Genre != null\rselect new { Genre = doc.Genre.Id }'}"
action: (args) ->
try
name = index = null
match = /^(\w+)\s+(.*)$/.exec(args)
if match.length != 3
console.error 'Unable to craete index: wrong number of arguments. Type ".help" to see usage'
return
name = match[1]
index = match[2]
eval ('createIndexIndex = ' + index )
r.context.db.createIndex name, createIndexIndex['map'], createIndexIndex['reduce'], (error, result) ->
console.error error if error?
console.log result if result?
r.context._ = result
r.displayPrompt()
catch e
console.error e
r.displayPrompt()
r.defineCommand 'deleteIndex',
help: 'Delete an given its name (e.g., .delete AlbumsByGenre)'
action: (args) ->
try
throw Error('Wrong number of arguments; see .help for more information') unless args?
name = args
r.context.db.deleteIndex name, (error, result) ->
console.error error if error?
console.log result if result?
r.context._ = result
r.displayPrompt()
catch e
console.error e
r.displayPrompt()
r.defineCommand 'createDatabase',
help: 'Create a database tenant (e.g., .createDatabase Foobar)'
action: (args) ->
try
throw Error('Wrong number of arguments; see .help for more information') unless args?
name = args
r.context.store.createDatabase name, (error, result) ->
console.error error if error?
console.log result if result?
r.context._ = result
r.displayPrompt()
catch e
console.error e
r.displayPrompt()
r.defineCommand 'deleteDatabase',
help: 'Delete a database given its name (e.g., .deleteDatabase Foobar)'
action: (args) ->
try
throw Error('Wrong number of arguments; see .help for more information') unless args?
name = args
r.context.store.deleteDatabase name, (error, result) ->
console.error error if error?
console.log result if result?
r.context._ = result
r.displayPrompt()
catch e
console.error e
r.displayPrompt()
startREPL = (store, databaseName) ->
console.log "RavenDB shell version #{version}"
r = repl.start "> "
createDatastore(r, store, databaseName)
defineCommands(r)
console.log currentDatabaseString(r)
r.displayPrompt()
r
startInteractiveREPL = (store, databaseName) ->
startREPL(store, databaseName)
startEvalREPL = (string, store, databaseName) ->
r = startREPL(store, databaseName)
lines = string.split('\n')
lines.forEach (line) ->
if line?
r.rli.write(line + '\n')
r
startFileREPL = (filename, store, databaseName) ->
r = startREPL(store, databaseName)
r.rli.write ".load #{filename}\n"
r
parser = new ArgumentParser(
'version': version
addHelp: true
description: 'RavenDB command line shell'
)
parser.addArgument(
[ '-f', '--file' ],
{
help: 'load and execute a file of shell commands',
dest: 'file'
}
)
parser.addArgument(
[ '-e', '--eval' ],
{
help: 'evaluate a single string of shell commands',
dest: 'eval'
}
)
parser.addArgument(
[ '-s', '--store' ],
{
help: 'specify which data store to use (defaults to http://localhost:8080 if not specfied)',
defaultValue: 'http://localhost:8080',
dest: 'store'
}
)
parser.addArgument(
[ '-db', '--database'],
{
help: 'specify which database to use (defaults to "Default" if not specified)',
defaultValue: 'Default',
dest: 'database'
}
)
parser.addArgument(
[ '-ko', '--keep-open' ],
{
help: 'keep the shell open when the passed in file or eval is done executing',
action: 'storeTrue',
defaultValue: false,
dest: 'keepOpen'
}
)
args = parser.parseArgs()
shell = null
keepOpen = args.keepOpen
evalString = args.eval
file = args.file
store = args.store
database = args.database
if evalString?
shell = startEvalREPL(evalString, store, database)
else if file?
shell = startFileREPL(file, store, database)
unless shell?
shell = startInteractiveREPL(store, database)
else
unless keepOpen?
shell.rli.close()
| 180561 | #!/usr/bin/env coffee
repl = require('repl')
ravendb = require('ravendb')
ArgumentParser = require('argparse').ArgumentParser
version = '0.0.10' # Keep in sync with package.json
createDatastore = (r, url, databaseName) ->
r.context.db = ravendb(url, databaseName)
r.context.store = r.context.db.datastore
useDatabase = (r, databaseName) ->
throw new Error('The datastore must first be set') unless r?.context?.store?
r.context.db = ravendb(r.context.store.url, databaseName)
currentDatabaseString = (r) ->
'Using database "' + r.context.db.name + '" in datastore at: "' + r.context.store.url + '"'
defineCommands = (r) ->
r.defineCommand 'store',
help: 'Use the RavenDB datastore at a url ".store <url>"'
action: (url) ->
if url?
createDatastore(r, url, r.context.db.name) # TODO: IS THIS A GOOD IDEA, TO USE THE SAME DB NAME?
else
url = r.context.store.url
console.log currentDatabaseString(r)
r.displayPrompt()
r.defineCommand 'use',
help: 'Use the database with the given name ".use <database-name>"'
action: (name) ->
if name?
useDatabase(r, name)
else
name = r.context.db.name
console.log currentDatabaseString(r)
r.displayPrompt()
r.defineCommand 'stats',
help: 'Show statistics for the current database'
action: ->
try
r.context.db.getStats (error, stats) ->
if error?
console.error error
r.displayPrompt()
return
console.log stats
r.context._ = stats
r.displayPrompt()
catch e
console.error e
r.displayPrompt()
r.defineCommand 'collections',
help: 'Show all collections in the current database'
action: ->
try
r.context.db.getCollections (error, collections) ->
if error?
console.error error
r.displayPrompt()
return
if collections?.length?
console.log collection for collection in collections
else
console.log "No collections found."
r.context._ = collections
r.displayPrompt()
catch e
console.error e
r.displayPrompt()
r.defineCommand 'create',
help: 'Save a document to a collection (e.g., .create CollectionName { id: "users/tony", firstName: "<NAME>" })'
action: (args) ->
try
match = /(\w+)\s+(.*)/.exec(args)
throw Error('Wrong number of arguments; see .help for .savedoc usage') if match.length != 3
collection = match[1]
eval('doc = ' + match[2])
r.context.db.saveDocument collection, doc, (error, result) ->
console.error error if error?
console.log result if result?
r.context._ = result
r.displayPrompt()
catch e
console.error e
r.displayPrompt()
r.defineCommand 'read',
help: 'Get a document given its id (e.g., .read users/tony)',
action: (args) ->
try
throw Error('Wrong number of arguments; see .help for more information') unless args?
id = args
r.context.db.getDocument id, (error, result) ->
console.error error if error?
console.log result if result?
r.context._ = result
r.displayPrompt()
catch e
console.error e
r.displayPrompt()
r.defineCommand 'delete',
help: 'Delete a document given its id (e.g., .delete users/tony)'
action: (args) ->
try
throw Error('Wrong number of arguments; see .help for more information') unless args?
id = args
r.context.db.deleteDocument id, (error, result) ->
console.error error if error?
console.log result if result?
r.context._ = result
r.displayPrompt()
catch e
console.error e
r.displayPrompt()
r.defineCommand 'find',
help: 'Find documents ".find <JSON object> [start [count]]" (e.g., .find { firstName: "<NAME>" } 20 100)'
action: (args) ->
try
throw Error('Wrong number of arguments; see .help for .find usage') unless args?
# Parse args: { attr: value } [start [count]]
# .find { some: 'thing'} 20 100
# ^-------1------^^--2--^
# 3 5
# ^4-^
# match[0] = "{ some: 'thing'} 20 100"
# match[1] = "{ some: 'thing'}"
# match[2] = " 20 100"
# match[3] = "20"
# match[4] = " 100"
# match[5] = "100"
match = /(\{.*\})(\s+(\d+)(\s+(\d+))?)?/.exec(args)
eval('doc = ' + match[1])
start = if match[3]? then parseInt(match[3]) else null
count = if match[5]? then parseInt(match[5]) else null
r.context.db.find doc, start, count, (error, result) ->
console.error error if error?
console.log result if result?
r.context._ = result
r.displayPrompt()
catch e
console.error e
r.displayPrompt()
r.defineCommand 'docs',
help: 'Retrieve documents in a collection (e.g., .doc Users)'
action: (args) ->
try
# Parse args: [collection [start [count]]]
# .count Users 50 100
# ^-1-^^--2--^
# 3 5
# ^4-^
# match[0] = "Users 50 100"
# match[1] = "Users"
# match[2] = " 50 100"
# match[3] = "50"
# match[4] = " 100"
# match[5] = "100"
match = /(\w+)(\s+(\d+)(\s+(\d+))?)?/.exec(args)
collection = start = count = null
if match?
collection = match[1]
start = if match[3]? then parseInt(match[3]) else null
count = if match[5]? then parseInt(match[5]) else null
r.context.db.getDocsInCollection collection, start, count, (error, result) ->
console.error error if error?
console.log result if result?
r.context._ = result
r.displayPrompt()
catch e
console.error e
r.displayPrompt()
r.defineCommand 'count',
help: 'Show the count of documents in a collection or in the database if left blank (e.g., .count Users)'
action: (args) ->
try
collection = args || null
r.context.db.getDocumentCount collection, (error, result) ->
console.error error if error?
console.log result if result?
r.context._ = result
r.displayPrompt()
catch e
console.error e
r.displayPrompt()
r.defineCommand 'createIndex',
help: "Create an index with a name, map, and optional reduce: .create-index foobar { map: 'from doc in docs.Albums\rwhere doc.Genre != null\rselect new { Genre = doc.Genre.Id }'}"
action: (args) ->
try
name = index = null
match = /^(\w+)\s+(.*)$/.exec(args)
if match.length != 3
console.error 'Unable to craete index: wrong number of arguments. Type ".help" to see usage'
return
name = match[1]
index = match[2]
eval ('createIndexIndex = ' + index )
r.context.db.createIndex name, createIndexIndex['map'], createIndexIndex['reduce'], (error, result) ->
console.error error if error?
console.log result if result?
r.context._ = result
r.displayPrompt()
catch e
console.error e
r.displayPrompt()
r.defineCommand 'deleteIndex',
help: 'Delete an given its name (e.g., .delete AlbumsByGenre)'
action: (args) ->
try
throw Error('Wrong number of arguments; see .help for more information') unless args?
name = args
r.context.db.deleteIndex name, (error, result) ->
console.error error if error?
console.log result if result?
r.context._ = result
r.displayPrompt()
catch e
console.error e
r.displayPrompt()
r.defineCommand 'createDatabase',
help: 'Create a database tenant (e.g., .createDatabase Foobar)'
action: (args) ->
try
throw Error('Wrong number of arguments; see .help for more information') unless args?
name = args
r.context.store.createDatabase name, (error, result) ->
console.error error if error?
console.log result if result?
r.context._ = result
r.displayPrompt()
catch e
console.error e
r.displayPrompt()
r.defineCommand 'deleteDatabase',
help: 'Delete a database given its name (e.g., .deleteDatabase Foobar)'
action: (args) ->
try
throw Error('Wrong number of arguments; see .help for more information') unless args?
name = args
r.context.store.deleteDatabase name, (error, result) ->
console.error error if error?
console.log result if result?
r.context._ = result
r.displayPrompt()
catch e
console.error e
r.displayPrompt()
startREPL = (store, databaseName) ->
console.log "RavenDB shell version #{version}"
r = repl.start "> "
createDatastore(r, store, databaseName)
defineCommands(r)
console.log currentDatabaseString(r)
r.displayPrompt()
r
startInteractiveREPL = (store, databaseName) ->
startREPL(store, databaseName)
startEvalREPL = (string, store, databaseName) ->
r = startREPL(store, databaseName)
lines = string.split('\n')
lines.forEach (line) ->
if line?
r.rli.write(line + '\n')
r
startFileREPL = (filename, store, databaseName) ->
r = startREPL(store, databaseName)
r.rli.write ".load #{filename}\n"
r
parser = new ArgumentParser(
'version': version
addHelp: true
description: 'RavenDB command line shell'
)
parser.addArgument(
[ '-f', '--file' ],
{
help: 'load and execute a file of shell commands',
dest: 'file'
}
)
parser.addArgument(
[ '-e', '--eval' ],
{
help: 'evaluate a single string of shell commands',
dest: 'eval'
}
)
parser.addArgument(
[ '-s', '--store' ],
{
help: 'specify which data store to use (defaults to http://localhost:8080 if not specfied)',
defaultValue: 'http://localhost:8080',
dest: 'store'
}
)
parser.addArgument(
[ '-db', '--database'],
{
help: 'specify which database to use (defaults to "Default" if not specified)',
defaultValue: 'Default',
dest: 'database'
}
)
parser.addArgument(
[ '-ko', '--keep-open' ],
{
help: 'keep the shell open when the passed in file or eval is done executing',
action: 'storeTrue',
defaultValue: false,
dest: 'keepOpen'
}
)
args = parser.parseArgs()
shell = null
keepOpen = args.keepOpen
evalString = args.eval
file = args.file
store = args.store
database = args.database
if evalString?
shell = startEvalREPL(evalString, store, database)
else if file?
shell = startFileREPL(file, store, database)
unless shell?
shell = startInteractiveREPL(store, database)
else
unless keepOpen?
shell.rli.close()
| true | #!/usr/bin/env coffee
repl = require('repl')
ravendb = require('ravendb')
ArgumentParser = require('argparse').ArgumentParser
version = '0.0.10' # Keep in sync with package.json
createDatastore = (r, url, databaseName) ->
r.context.db = ravendb(url, databaseName)
r.context.store = r.context.db.datastore
useDatabase = (r, databaseName) ->
throw new Error('The datastore must first be set') unless r?.context?.store?
r.context.db = ravendb(r.context.store.url, databaseName)
currentDatabaseString = (r) ->
'Using database "' + r.context.db.name + '" in datastore at: "' + r.context.store.url + '"'
defineCommands = (r) ->
r.defineCommand 'store',
help: 'Use the RavenDB datastore at a url ".store <url>"'
action: (url) ->
if url?
createDatastore(r, url, r.context.db.name) # TODO: IS THIS A GOOD IDEA, TO USE THE SAME DB NAME?
else
url = r.context.store.url
console.log currentDatabaseString(r)
r.displayPrompt()
r.defineCommand 'use',
help: 'Use the database with the given name ".use <database-name>"'
action: (name) ->
if name?
useDatabase(r, name)
else
name = r.context.db.name
console.log currentDatabaseString(r)
r.displayPrompt()
r.defineCommand 'stats',
help: 'Show statistics for the current database'
action: ->
try
r.context.db.getStats (error, stats) ->
if error?
console.error error
r.displayPrompt()
return
console.log stats
r.context._ = stats
r.displayPrompt()
catch e
console.error e
r.displayPrompt()
r.defineCommand 'collections',
help: 'Show all collections in the current database'
action: ->
try
r.context.db.getCollections (error, collections) ->
if error?
console.error error
r.displayPrompt()
return
if collections?.length?
console.log collection for collection in collections
else
console.log "No collections found."
r.context._ = collections
r.displayPrompt()
catch e
console.error e
r.displayPrompt()
r.defineCommand 'create',
help: 'Save a document to a collection (e.g., .create CollectionName { id: "users/tony", firstName: "PI:NAME:<NAME>END_PI" })'
action: (args) ->
try
match = /(\w+)\s+(.*)/.exec(args)
throw Error('Wrong number of arguments; see .help for .savedoc usage') if match.length != 3
collection = match[1]
eval('doc = ' + match[2])
r.context.db.saveDocument collection, doc, (error, result) ->
console.error error if error?
console.log result if result?
r.context._ = result
r.displayPrompt()
catch e
console.error e
r.displayPrompt()
r.defineCommand 'read',
help: 'Get a document given its id (e.g., .read users/tony)',
action: (args) ->
try
throw Error('Wrong number of arguments; see .help for more information') unless args?
id = args
r.context.db.getDocument id, (error, result) ->
console.error error if error?
console.log result if result?
r.context._ = result
r.displayPrompt()
catch e
console.error e
r.displayPrompt()
r.defineCommand 'delete',
help: 'Delete a document given its id (e.g., .delete users/tony)'
action: (args) ->
try
throw Error('Wrong number of arguments; see .help for more information') unless args?
id = args
r.context.db.deleteDocument id, (error, result) ->
console.error error if error?
console.log result if result?
r.context._ = result
r.displayPrompt()
catch e
console.error e
r.displayPrompt()
r.defineCommand 'find',
help: 'Find documents ".find <JSON object> [start [count]]" (e.g., .find { firstName: "PI:NAME:<NAME>END_PI" } 20 100)'
action: (args) ->
try
throw Error('Wrong number of arguments; see .help for .find usage') unless args?
# Parse args: { attr: value } [start [count]]
# .find { some: 'thing'} 20 100
# ^-------1------^^--2--^
# 3 5
# ^4-^
# match[0] = "{ some: 'thing'} 20 100"
# match[1] = "{ some: 'thing'}"
# match[2] = " 20 100"
# match[3] = "20"
# match[4] = " 100"
# match[5] = "100"
match = /(\{.*\})(\s+(\d+)(\s+(\d+))?)?/.exec(args)
eval('doc = ' + match[1])
start = if match[3]? then parseInt(match[3]) else null
count = if match[5]? then parseInt(match[5]) else null
r.context.db.find doc, start, count, (error, result) ->
console.error error if error?
console.log result if result?
r.context._ = result
r.displayPrompt()
catch e
console.error e
r.displayPrompt()
r.defineCommand 'docs',
help: 'Retrieve documents in a collection (e.g., .doc Users)'
action: (args) ->
try
# Parse args: [collection [start [count]]]
# .count Users 50 100
# ^-1-^^--2--^
# 3 5
# ^4-^
# match[0] = "Users 50 100"
# match[1] = "Users"
# match[2] = " 50 100"
# match[3] = "50"
# match[4] = " 100"
# match[5] = "100"
match = /(\w+)(\s+(\d+)(\s+(\d+))?)?/.exec(args)
collection = start = count = null
if match?
collection = match[1]
start = if match[3]? then parseInt(match[3]) else null
count = if match[5]? then parseInt(match[5]) else null
r.context.db.getDocsInCollection collection, start, count, (error, result) ->
console.error error if error?
console.log result if result?
r.context._ = result
r.displayPrompt()
catch e
console.error e
r.displayPrompt()
r.defineCommand 'count',
help: 'Show the count of documents in a collection or in the database if left blank (e.g., .count Users)'
action: (args) ->
try
collection = args || null
r.context.db.getDocumentCount collection, (error, result) ->
console.error error if error?
console.log result if result?
r.context._ = result
r.displayPrompt()
catch e
console.error e
r.displayPrompt()
r.defineCommand 'createIndex',
help: "Create an index with a name, map, and optional reduce: .create-index foobar { map: 'from doc in docs.Albums\rwhere doc.Genre != null\rselect new { Genre = doc.Genre.Id }'}"
action: (args) ->
try
name = index = null
match = /^(\w+)\s+(.*)$/.exec(args)
if match.length != 3
console.error 'Unable to craete index: wrong number of arguments. Type ".help" to see usage'
return
name = match[1]
index = match[2]
eval ('createIndexIndex = ' + index )
r.context.db.createIndex name, createIndexIndex['map'], createIndexIndex['reduce'], (error, result) ->
console.error error if error?
console.log result if result?
r.context._ = result
r.displayPrompt()
catch e
console.error e
r.displayPrompt()
r.defineCommand 'deleteIndex',
help: 'Delete an given its name (e.g., .delete AlbumsByGenre)'
action: (args) ->
try
throw Error('Wrong number of arguments; see .help for more information') unless args?
name = args
r.context.db.deleteIndex name, (error, result) ->
console.error error if error?
console.log result if result?
r.context._ = result
r.displayPrompt()
catch e
console.error e
r.displayPrompt()
r.defineCommand 'createDatabase',
help: 'Create a database tenant (e.g., .createDatabase Foobar)'
action: (args) ->
try
throw Error('Wrong number of arguments; see .help for more information') unless args?
name = args
r.context.store.createDatabase name, (error, result) ->
console.error error if error?
console.log result if result?
r.context._ = result
r.displayPrompt()
catch e
console.error e
r.displayPrompt()
r.defineCommand 'deleteDatabase',
help: 'Delete a database given its name (e.g., .deleteDatabase Foobar)'
action: (args) ->
try
throw Error('Wrong number of arguments; see .help for more information') unless args?
name = args
r.context.store.deleteDatabase name, (error, result) ->
console.error error if error?
console.log result if result?
r.context._ = result
r.displayPrompt()
catch e
console.error e
r.displayPrompt()
startREPL = (store, databaseName) ->
console.log "RavenDB shell version #{version}"
r = repl.start "> "
createDatastore(r, store, databaseName)
defineCommands(r)
console.log currentDatabaseString(r)
r.displayPrompt()
r
startInteractiveREPL = (store, databaseName) ->
startREPL(store, databaseName)
startEvalREPL = (string, store, databaseName) ->
r = startREPL(store, databaseName)
lines = string.split('\n')
lines.forEach (line) ->
if line?
r.rli.write(line + '\n')
r
startFileREPL = (filename, store, databaseName) ->
r = startREPL(store, databaseName)
r.rli.write ".load #{filename}\n"
r
parser = new ArgumentParser(
'version': version
addHelp: true
description: 'RavenDB command line shell'
)
parser.addArgument(
[ '-f', '--file' ],
{
help: 'load and execute a file of shell commands',
dest: 'file'
}
)
parser.addArgument(
[ '-e', '--eval' ],
{
help: 'evaluate a single string of shell commands',
dest: 'eval'
}
)
parser.addArgument(
[ '-s', '--store' ],
{
help: 'specify which data store to use (defaults to http://localhost:8080 if not specfied)',
defaultValue: 'http://localhost:8080',
dest: 'store'
}
)
parser.addArgument(
[ '-db', '--database'],
{
help: 'specify which database to use (defaults to "Default" if not specified)',
defaultValue: 'Default',
dest: 'database'
}
)
parser.addArgument(
[ '-ko', '--keep-open' ],
{
help: 'keep the shell open when the passed in file or eval is done executing',
action: 'storeTrue',
defaultValue: false,
dest: 'keepOpen'
}
)
args = parser.parseArgs()
shell = null
keepOpen = args.keepOpen
evalString = args.eval
file = args.file
store = args.store
database = args.database
if evalString?
shell = startEvalREPL(evalString, store, database)
else if file?
shell = startFileREPL(file, store, database)
unless shell?
shell = startInteractiveREPL(store, database)
else
unless keepOpen?
shell.rli.close()
|
[
{
"context": "LaTeX and the Terminal.\n#\n# Copyright (C) 2014, William Stein\n#\n# This program is free software: you can red",
"end": 217,
"score": 0.9998791813850403,
"start": 204,
"tag": "NAME",
"value": "William Stein"
},
{
"context": " without blocking.\n This uses https... | .sagemathcloud/misc_node.coffee | febman/elastic-3D-model | 0 | ###############################################################################
#
# SageMathCloud: A collaborative web-based interface to Sage, IPython, LaTeX and the Terminal.
#
# Copyright (C) 2014, William Stein
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
###############################################################################
####################################################################
#
# misc JS functionality that only makes sense on the node side (not on
# the client)
#
####################################################################
assert = require('assert')
winston = require('winston')
net = require('net')
fs = require('fs')
misc = require 'misc'
async = require('async')
{walltime, defaults, required, to_json} = misc
###
Asynchronous JSON functionality: these are slower but block the main thread *less*.
- to_json_async - convert object to JSON string without blocking.
This uses https://github.com/ckknight/async-json
- from_json_async - convert JSON string to object/etc., without blocking,
though 2x times as slow as JSON.parse. This uses https://github.com/bjouhier/i-json
TESTS:
m=require('misc_node');s=JSON.stringify({x:new Buffer(10000000).toString('hex')}); d=new Date(); m.from_json_async(string: s, chunk_size:10000, cb: (e, r) -> console.log(e, new Date() - d)); new Date() - d
###
###
exports.to_json_async = (opts) ->
opts = defaults opts,
obj : required # Javascript object to convert to a JSON string
cb : required # cb(err, JSON string)
ijson = require('i-json')
exports.from_json_async = (opts) ->
opts = defaults opts,
string : required # string in JSON format
chunk_size : 50000 # size of chunks to parse -- affects how long this blocks the main thread
cb : required
p = ijson.createParser()
s = opts.string
f = (i, cb) ->
#t = misc.mswalltime()
p.update(s.slice(i*opts.chunk_size, (i+1)*opts.chunk_size))
#console.log("update: #{misc.mswalltime(t)}")
setTimeout(cb, 0)
async.mapSeries [0...s.length/opts.chunk_size], f, (err) ->
opts.cb(err, p.result())
###
######################################################################
# Our TCP messaging system. We send a message by first
# sending the length, then the bytes of the actual message. The code
# in this section is used by:
# * hub -- to communicate with sage_server and console_server
######################################################################
# Extend the socket object so that listens to all data coming in on this socket
# and fires a 'mesg' event, along with the JSON object or blob in the message
# So, one listens with:
# socket.on('mesg', (type, value) -> ...)
# where type is one if 'json' or 'blob'.
#
# Calling this function also adds a function .write_mesg to the socket, so that
# socket.write_mesg(type, data)
# will send the message of the given type on the socket. When type='json',
# data is just a JSON-able object. When type='blob', data={uuid:..., blob:...};
# since every blob is tagged with a uuid.
message = require 'message'
exports.enable_mesg = enable_mesg = (socket, desc) ->
socket.setMaxListeners(500) # we use a lot of listeners for listening for messages
socket._buf = null
socket._buf_target_length = -1
socket._listen_for_mesg = (data) ->
socket._buf = if socket._buf == null then data else Buffer.concat([socket._buf, data])
loop
if socket._buf_target_length == -1
# starting to read a new message
if socket._buf.length >= 4
socket._buf_target_length = socket._buf.readUInt32BE(0) + 4
else
return # have to wait for more data to find out message length
if socket._buf_target_length <= socket._buf.length
# read a new message from our buffer
type = socket._buf.slice(4, 5).toString()
mesg = socket._buf.slice(5, socket._buf_target_length)
switch type
when 'j' # JSON
s = mesg.toString()
try
obj = JSON.parse(s)
catch e
winston.debug("Error parsing JSON message='#{misc.trunc(s,512)}' on socket #{desc}")
# TODO -- this throw can seriously mess up the server; handle this
# in a better way in production. This could happen if there is
# corruption of the connection.
#throw(e)
return
socket.emit('mesg', 'json', obj)
when 'b' # BLOB (tagged by a uuid)
socket.emit('mesg', 'blob', {uuid:mesg.slice(0,36).toString(), blob:mesg.slice(36)})
else
throw("unknown message type '#{type}'")
socket._buf = socket._buf.slice(socket._buf_target_length)
socket._buf_target_length = -1
if socket._buf.length == 0
return
else # nothing to do but wait for more data
return
socket.on('data', socket._listen_for_mesg)
socket.write_mesg = (type, data, cb) -> # cb(err)
send = (s) ->
buf = new Buffer(4)
# This line was 4 hours of work. It is absolutely
# *critical* to change the (possibly a string) s into a
# buffer before computing its length and sending it!!
# Otherwise unicode characters will cause trouble.
if typeof(s) == "string"
s = Buffer(s)
buf.writeInt32BE(s.length, 0)
if not socket.writable
cb?("socket not writable")
return
else
socket.write(buf)
if not socket.writable
cb?("socket not writable")
return
else
socket.write(s, cb)
switch type
when 'json'
send('j' + JSON.stringify(data))
when 'blob'
assert(data.uuid?, "data object *must* have a uuid attribute")
assert(data.blob?, "data object *must* have a blob attribute")
send(Buffer.concat([new Buffer('b'), new Buffer(data.uuid), new Buffer(data.blob)]))
else
cb("unknown message type '#{type}'")
# Wait until we receive exactly *one* message of the given type
# with the given id, then call the callback with that message.
# (If the type is 'blob', with the given uuid.)
socket.recv_mesg = (opts) ->
opts = defaults opts,
type : required
id : required # or uuid
cb : required # called with cb(mesg)
timeout : undefined
f = (type, mesg) ->
if type == opts.type and ((type == 'json' and mesg.id == opts.id) or (type=='blob' and mesg.uuid=opts.id))
socket.removeListener('mesg', f)
opts.cb(mesg)
socket.on 'mesg', f
if opts.timeout?
timeout = () ->
if socket? and f in socket.listeners('mesg')
socket.removeListener('mesg', f)
opts.cb(message.error(error:"Timed out after #{opts.timeout} seconds."))
setTimeout(timeout, opts.timeout*1000)
# Stop watching data stream for messages and delete the write_mesg function.
exports.disable_mesg = (socket) ->
if socket._listen_for_mesg?
socket.removeListener('data', socket._listen_for_mesg)
delete socket._listen_for_mesg
# Wait to receive token over the socket; when it is received, call
# cb(false), then send back "y". If any mistake is made (or the
# socket times out after 10 seconds), send back "n" and close the
# connection.
exports.unlock_socket = (socket, token, cb) -> # cb(err)
timeout = setTimeout((() -> socket.destroy(); cb("Unlock socket -- timed out waiting for secret token")), 10000)
user_token = ''
listener = (data) ->
user_token += data.toString()
if user_token == token
socket.removeListener('data', listener)
# got it!
socket.write('y')
clearTimeout(timeout)
cb(false)
else if user_token.length > token.length or token.slice(0, user_token.length) != user_token
socket.removeListener('data', listener)
socket.write('n')
socket.write("Invalid secret token.")
socket.destroy()
clearTimeout(timeout)
cb("Invalid secret token.")
socket.on('data', listener)
# Connect to a locked socket on host, unlock it, and do
# cb(err, unlocked_socket).
# WARNING: Use only on an encrypted VPN, since this is not
# an *encryption* protocol.
exports.connect_to_locked_socket = (opts) ->
{port, host, token, timeout, cb} = defaults opts,
host : 'localhost'
port : required
token : required
timeout : 5
cb : required
if not (port > 0 and port < 65536)
cb("connect_to_locked_socket -- RangeError: port should be > 0 and < 65536: #{port}")
return
winston.debug("misc_node: connecting to a locked socket on port #{port}...")
timer = undefined
timed_out = () ->
m = "misc_node: timed out trying to connect to locked socket on port #{port}"
winston.debug(m)
cb?(m)
cb = undefined # NOTE: here and everywhere below we set cb to undefined after calling it, and only call it if defined, since the event and timer callback stuff is very hard to do right here without calling cb more than once (which is VERY bad to do).
socket?.end()
timer = undefined
timer = setTimeout(timed_out, timeout*1000)
socket = net.connect {host:host, port:port}, () =>
listener = (data) ->
winston.debug("misc_node: got back response: #{data}")
socket.removeListener('data', listener)
if data.toString() == 'y'
if timer?
clearTimeout(timer)
cb?(undefined, socket)
cb = undefined
else
socket.destroy()
if timer?
clearTimeout(timer)
cb?("Permission denied (invalid secret token) when connecting to the local hub.")
cb = undefined
socket.on 'data', listener
winston.debug("misc_node: connected, now sending secret token")
socket.write(token)
# This is called in case there is an error trying to make the connection, e.g., "connection refused".
socket.on "error", (err) =>
if timer?
clearTimeout(timer)
cb?(err)
cb = undefined
crypto = require('crypto')
# compute sha1 hash of data in hex
exports.sha1 = (data) ->
sha1sum = crypto.createHash('sha1')
sha1sum.update(data)
return sha1sum.digest('hex')
# Compute a uuid v4 from the Sha-1 hash of data.
exports.uuidsha1 = (data) ->
s = exports.sha1(data)
i = -1
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) ->
i += 1
switch c
when 'x'
return s[i]
when 'y'
# take 8 + low order 3 bits of hex number.
return ((parseInt('0x'+s[i],16)&0x3)|0x8).toString(16)
)
###################################################################
# Execute code
###################################################################
#
temp = require('temp')
async = require('async')
fs = require('fs')
child_process = require 'child_process'
exports.execute_code = execute_code = (opts) ->
opts = defaults opts,
command : required
args : []
path : undefined # defaults to home directory; where code is executed from
timeout : 10 # timeout in *seconds*
ulimit_timeout : true # if set, use ulimit to ensure a cpu timeout -- don't use when launching a daemon!
err_on_exit: true # if true, then a nonzero exit code will result in cb(error_message)
max_output : undefined # bound on size of stdout and stderr; further output ignored
bash : false # if true, ignore args and evaluate command as a bash command
home : undefined
uid : undefined
gid : undefined
env : undefined # if given, added to exec environment
verbose : true
cb : undefined
start_time = walltime()
if opts.verbose
winston.debug("execute_code: \"#{opts.command} #{opts.args.join(' ')}\"")
s = opts.command.split(/\s+/g) # split on whitespace
if opts.args.length == 0 and s.length > 1
opts.bash = true
if not opts.home?
opts.home = process.env.HOME
if not opts.path?
opts.path = opts.home
else if opts.path[0] != '/'
opts.path = opts.home + '/' + opts.path
stdout = ''
stderr = ''
exit_code = undefined
env = misc.copy(process.env)
if opts.env?
for k, v of opts.env
env[k] = v
if opts.uid?
env.HOME = opts.home
tmpfilename = undefined
ran_code = false
async.series([
(c) ->
if not opts.bash
c()
return
if opts.timeout? and opts.ulimit_timeout
# This ensures that everything involved with this
# command really does die no matter what; it's
# better than killing from outside, since it gets
# all subprocesses since they inherit the limits.
cmd = "ulimit -t #{opts.timeout}\n#{opts.command}"
else
cmd = opts.command
if opts.verbose
winston.debug("execute_code: writing temporary file that contains bash program.")
temp.open '', (err, info) ->
if err
c(err)
else
opts.command = 'bash'
opts.args = [info.path]
tmpfilename = info.path
fs.write(info.fd, cmd)
fs.close(info.fd, c)
(c) ->
if tmpfilename?
fs.chmod(tmpfilename, 0o777, c)
else
c()
(c) ->
if opts.verbose
winston.debug("Spawning the command #{opts.command} with given args #{opts.args} and timeout of #{opts.timeout}s...")
o = {cwd:opts.path}
if env?
o.env = env
if opts.uid
o.uid = opts.uid
if opts.gid
o.gid = opts.gid
try
r = child_process.spawn(opts.command, opts.args, o)
catch e
# Yes, spawn can cause this error if there is no memory, and there's no event! -- Error: spawn ENOMEM
c("error #{misc.to_json(e)}")
return
ran_code = true
if opts.verbose
winston.debug("Listen for stdout, stderr and exit events.")
stdout = ''
r.stdout.on 'data', (data) ->
data = data.toString()
if opts.max_output?
if stdout.length < opts.max_output
stdout += data.slice(0,opts.max_output - stdout.length)
else
stdout += data
r.stderr.on 'data', (data) ->
data = data.toString()
if opts.max_output?
if stderr.length < opts.max_output
stderr += data.slice(0,opts.max_output - stderr.length)
else
stderr += data
stderr_is_done = stdout_is_done = false
r.stderr.on 'end', () ->
stderr_is_done = true
finish()
r.stdout.on 'end', () ->
stdout_is_done = true
finish()
r.on 'exit', (code) ->
exit_code = code
finish()
# This can happen, e.g., "Error: spawn ENOMEM" if there is no memory. Without this handler,
# an unhandled exception gets raised, which is nasty.
# From docs: "Note that the exit-event may or may not fire after an error has occured. "
r.on 'error', (err) ->
if not exit_code?
exit_code = 1
stderr += to_json(err)
finish()
callback_done = false
finish = () ->
if stdout_is_done and stderr_is_done and exit_code?
if opts.err_on_exit and exit_code != 0
if not callback_done
callback_done = true
c("command '#{opts.command}' (args=#{opts.args.join(' ')}) exited with nonzero code #{exit_code} -- stderr='#{stderr}'")
else
if opts.max_output?
if stdout.length >= opts.max_output
stdout += " (truncated at #{opts.max_output} characters)"
if stderr.length >= opts.max_output
stderr += " (truncated at #{opts.max_output} characters)"
if not callback_done
callback_done = true
c()
if opts.timeout?
f = () ->
if r.exitCode == null
if opts.verbose
winston.debug("execute_code: subprocess did not exit after #{opts.timeout} seconds, so killing with SIGKILL")
try
r.kill("SIGKILL") # this does not kill the process group :-(
catch e
# Exceptions can happen, which left uncaught messes up calling code bigtime.
if opts.verbose
winston.debug("execute_code: r.kill raised an exception.")
if not callback_done
callback_done = true
c("killed command '#{opts.command} #{opts.args.join(' ')}'")
setTimeout(f, opts.timeout*1000)
], (err) ->
if not exit_code?
exit_code = 1 # don't have one due to SIGKILL
# TODO: This is dangerous, e.g., it could print out a secret_token to a log file.
# winston.debug("(time: #{walltime() - start_time}): Done running '#{opts.command} #{opts.args.join(' ')}'; resulted in stdout='#{misc.trunc(stdout,512)}', stderr='#{misc.trunc(stderr,512)}', exit_code=#{exit_code}, err=#{err}")
# Do not litter:
if tmpfilename?
try
fs.unlink(tmpfilename)
catch e
winston.debug("failed to unlink #{tmpfilename}")
if opts.verbose
winston.debug("finished exec of #{opts.command} (took #{walltime(start_time)}s)")
winston.debug("stdout='#{misc.trunc(stdout,512)}', stderr='#{misc.trunc(stderr,512)}', exit_code=#{exit_code}")
if not opts.err_on_exit and ran_code
# as long as we made it to running some code, we consider this a success (that is what err_on_exit means).
opts.cb?(false, {stdout:stdout, stderr:stderr, exit_code:exit_code})
else
opts.cb?(err, {stdout:stdout, stderr:stderr, exit_code:exit_code})
)
####
## Applications of execute_code
exports.disk_usage = (path, cb) -> # cb(err, usage in K (1024 bytes) of path)
exports.execute_code
command : "du"
args : ['-s', path]
cb : (err, output) ->
if err
cb(err)
else
cb(false, parseInt(output.stdout.split(' ')[0]))
###################################
# project_id --> username mapping
# The username associated to a given project id is just the string of
# the uuid, but with -'s replaced by _'s so we obtain a valid unix
# account name, and shortened to fit Linux and sanity requirements.
exports.username = (project_id) ->
if '..' in project_id or project_id.length != 36
# a sanity check -- this should never ever be allowed to happen, ever.
throw Error("invalid project id #{project_id}")
# Return a for-sure safe username
return project_id.slice(0,8).replace(/[^a-z0-9]/g,'')
address_to_local_port = {}
local_port_to_child_process = {}
exports.keep_portforward_alive = (port) ->
r = local_port_to_child_process[port]
if r?
r.activity = true
exports.unforward_port = (opts) ->
opts = defaults opts,
port : required
cb : required
winston.debug("Unforwarding port #{opts.port}")
r = local_port_to_child_process[local_port]
if r?
r.kill("SIGKILL")
exports.unforward_all_ports = () ->
for port, r of local_port_to_child_process
r.kill("SIGKILL")
free_port = exports.free_port = (cb) -> # cb(err, available port as assigned by the operating system)
server = require("net").createServer()
port = 0
server.on "listening", () ->
port = server.address().port
server.close()
server.on "close", ->
f = () ->
cb(null, port)
# give the OS a chance to really make the port available again.
setTimeout(f, 500)
server.listen(0)
exports.forward_remote_port_to_localhost = (opts) ->
opts = defaults opts,
username : required
host : required
ssh_port : 22
remote_port : required
activity_time : 2000 # kill connection if the HUB doesn't
# actively *receive* something on this
# port for this many seconds.
keep_alive_time:2000 # network activity every this many
# seconds.; lower to more quickly detect
# a broken connection; raise to reduce resources
cb : required # cb(err, local_port)
opts.ssh_port = parseInt(opts.ssh_port)
if not (opts.ssh_port >= 1 and opts.ssh_port <= 66000)
opts.cb("Invalid ssh_port option")
return
opts.remote_port = parseInt(opts.remote_port)
if not (opts.remote_port >= 1 and opts.remote_port <= 66000)
opts.cb("Invalid remote_port option")
return
winston.debug("Forward a remote port #{opts.remote_port} on #{opts.host} to localhost.")
remote_address = "#{opts.username}@#{opts.host}:#{opts.remote_port} -p#{opts.ssh_port}"
###
local_port = address_to_local_port[remote_address]
if local_port?
# We already have a valid forward
opts.cb(false, local_port)
return
###
# We have to make a new port forward
free_port (err, local_port) ->
if err
opts.cb(err)
return
winston.debug("forward_remote_port_to_local_host: local port #{local_port} available")
command = "ssh"
args = ['-o', 'StrictHostKeyChecking=no', "-p", opts.ssh_port,
'-L', "#{local_port}:localhost:#{opts.remote_port}",
"#{opts.username}@#{opts.host}",
"TERM=vt100 /usr/bin/watch -t -n #{opts.keep_alive_time} date"]
r = child_process.spawn(command, args)
cb_happened = false
new_output = false
r.stdout.on 'data', (data) ->
# Got a local_port -- let's use it.
address_to_local_port[remote_address] = local_port
local_port_to_child_process[local_port] = r
new_output = true
# as soon as something is output, it's working (I hope).
if not cb_happened
opts.cb(false, local_port)
cb_happened = true
stderr = ''
r.stderr.on 'data', (data) ->
stderr += data.toString()
kill_if_no_new_output = () ->
if not new_output
winston.debug("Killing ssh port forward #{remote_address} --> localhost:#{local_port} due to it not working")
r.kill("SIGKILL")
new_output = false
# check every few seconds
kill_no_output_timer = setInterval(kill_if_no_new_output, 1000*opts.keep_alive_time)
kill_if_no_new_activity = () ->
if not r.activity?
winston.debug("Killing ssh port forward #{remote_address} --> localhost:#{local_port} due to not receiving any data for at least #{opts.activity_time} seconds.")
r.kill("SIGKILL")
else
# delete it -- the only way connection won't be killed is if this gets set again by an active call to keep_portforward_alive above.
delete r.activity
kill_no_activity_timer = setInterval(kill_if_no_new_activity, 1000*opts.activity_time)
r.on 'exit', (code) ->
if not cb_happened
opts.cb("Problem setting up ssh port forward -- #{stderr}")
delete address_to_local_port[remote_address]
clearInterval(kill_no_output_timer)
clearInterval(kill_no_activity_timer)
# Any non-absolute path is assumed to be relative to the user's home directory.
# This function converts such a path to an absolute path.
exports.abspath = abspath = (path) ->
if path.length == 0
return process.env.HOME
if path[0] == '/'
return path # already an absolute path
p = process.env.HOME + '/' + path
p = p.replace(/\/\.\//g,'/') # get rid of /./, which is the same as /...
return p
# Other path related functions...
# Make sure that that the directory containing the file indicated by
# the path exists and has restrictive permissions.
ensure_containing_directory_exists = (path, cb) -> # cb(err)
path = abspath(path)
dir = misc.path_split(path).head # containing path
fs.exists dir, (exists) ->
if exists
cb?()
else
async.series([
(cb) ->
if dir != ''
# recursively make sure the entire chain of directories exists.
ensure_containing_directory_exists(dir, cb)
else
cb()
(cb) ->
fs.mkdir(dir, 0o700, cb)
], (err) ->
if err.code == 'EEXIST'
cb?()
else
cb?(err)
)
exports.ensure_containing_directory_exists = ensure_containing_directory_exists
# Determine if path (file or directory) is writable -- this works even if permissions are right but
# filesystem is read only, e.g., ~/.zfs/snapshot/...
# It's an error if the path doesn't exist.
exports.is_file_readonly = (opts) ->
opts = defaults opts,
path : required
cb : required # cb(err, true if read only (false otherwise))
readonly = undefined
# determine if file is writable
execute_code
command : 'find'
args : [opts.path, '-maxdepth', '0', '-writable']
err_on_exit : false
cb : (err, output) =>
if err
opts.cb(err)
else if output.stderr or output.exit_code
opts.cb("no such path '#{opts.path}'")
else
readonly = output.stdout.length == 0
opts.cb(undefined, readonly)
# like in sage, a quick way to save/load JSON-able objects to disk; blocking and not compressed.
exports.saveSync = (obj, filename) ->
fs.writeFileSync(filename, JSON.stringify(obj))
exports.loadSync = (filename) ->
JSON.parse(fs.readFileSync(filename).toString())
| 155665 | ###############################################################################
#
# SageMathCloud: A collaborative web-based interface to Sage, IPython, LaTeX and the Terminal.
#
# Copyright (C) 2014, <NAME>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
###############################################################################
####################################################################
#
# misc JS functionality that only makes sense on the node side (not on
# the client)
#
####################################################################
assert = require('assert')
winston = require('winston')
net = require('net')
fs = require('fs')
misc = require 'misc'
async = require('async')
{walltime, defaults, required, to_json} = misc
###
Asynchronous JSON functionality: these are slower but block the main thread *less*.
- to_json_async - convert object to JSON string without blocking.
This uses https://github.com/ckknight/async-json
- from_json_async - convert JSON string to object/etc., without blocking,
though 2x times as slow as JSON.parse. This uses https://github.com/bjouhier/i-json
TESTS:
m=require('misc_node');s=JSON.stringify({x:new Buffer(10000000).toString('hex')}); d=new Date(); m.from_json_async(string: s, chunk_size:10000, cb: (e, r) -> console.log(e, new Date() - d)); new Date() - d
###
###
exports.to_json_async = (opts) ->
opts = defaults opts,
obj : required # Javascript object to convert to a JSON string
cb : required # cb(err, JSON string)
ijson = require('i-json')
exports.from_json_async = (opts) ->
opts = defaults opts,
string : required # string in JSON format
chunk_size : 50000 # size of chunks to parse -- affects how long this blocks the main thread
cb : required
p = ijson.createParser()
s = opts.string
f = (i, cb) ->
#t = misc.mswalltime()
p.update(s.slice(i*opts.chunk_size, (i+1)*opts.chunk_size))
#console.log("update: #{misc.mswalltime(t)}")
setTimeout(cb, 0)
async.mapSeries [0...s.length/opts.chunk_size], f, (err) ->
opts.cb(err, p.result())
###
######################################################################
# Our TCP messaging system. We send a message by first
# sending the length, then the bytes of the actual message. The code
# in this section is used by:
# * hub -- to communicate with sage_server and console_server
######################################################################
# Extend the socket object so that listens to all data coming in on this socket
# and fires a 'mesg' event, along with the JSON object or blob in the message
# So, one listens with:
# socket.on('mesg', (type, value) -> ...)
# where type is one if 'json' or 'blob'.
#
# Calling this function also adds a function .write_mesg to the socket, so that
# socket.write_mesg(type, data)
# will send the message of the given type on the socket. When type='json',
# data is just a JSON-able object. When type='blob', data={uuid:..., blob:...};
# since every blob is tagged with a uuid.
message = require 'message'
exports.enable_mesg = enable_mesg = (socket, desc) ->
socket.setMaxListeners(500) # we use a lot of listeners for listening for messages
socket._buf = null
socket._buf_target_length = -1
socket._listen_for_mesg = (data) ->
socket._buf = if socket._buf == null then data else Buffer.concat([socket._buf, data])
loop
if socket._buf_target_length == -1
# starting to read a new message
if socket._buf.length >= 4
socket._buf_target_length = socket._buf.readUInt32BE(0) + 4
else
return # have to wait for more data to find out message length
if socket._buf_target_length <= socket._buf.length
# read a new message from our buffer
type = socket._buf.slice(4, 5).toString()
mesg = socket._buf.slice(5, socket._buf_target_length)
switch type
when 'j' # JSON
s = mesg.toString()
try
obj = JSON.parse(s)
catch e
winston.debug("Error parsing JSON message='#{misc.trunc(s,512)}' on socket #{desc}")
# TODO -- this throw can seriously mess up the server; handle this
# in a better way in production. This could happen if there is
# corruption of the connection.
#throw(e)
return
socket.emit('mesg', 'json', obj)
when 'b' # BLOB (tagged by a uuid)
socket.emit('mesg', 'blob', {uuid:mesg.slice(0,36).toString(), blob:mesg.slice(36)})
else
throw("unknown message type '#{type}'")
socket._buf = socket._buf.slice(socket._buf_target_length)
socket._buf_target_length = -1
if socket._buf.length == 0
return
else # nothing to do but wait for more data
return
socket.on('data', socket._listen_for_mesg)
socket.write_mesg = (type, data, cb) -> # cb(err)
send = (s) ->
buf = new Buffer(4)
# This line was 4 hours of work. It is absolutely
# *critical* to change the (possibly a string) s into a
# buffer before computing its length and sending it!!
# Otherwise unicode characters will cause trouble.
if typeof(s) == "string"
s = Buffer(s)
buf.writeInt32BE(s.length, 0)
if not socket.writable
cb?("socket not writable")
return
else
socket.write(buf)
if not socket.writable
cb?("socket not writable")
return
else
socket.write(s, cb)
switch type
when 'json'
send('j' + JSON.stringify(data))
when 'blob'
assert(data.uuid?, "data object *must* have a uuid attribute")
assert(data.blob?, "data object *must* have a blob attribute")
send(Buffer.concat([new Buffer('b'), new Buffer(data.uuid), new Buffer(data.blob)]))
else
cb("unknown message type '#{type}'")
# Wait until we receive exactly *one* message of the given type
# with the given id, then call the callback with that message.
# (If the type is 'blob', with the given uuid.)
socket.recv_mesg = (opts) ->
opts = defaults opts,
type : required
id : required # or uuid
cb : required # called with cb(mesg)
timeout : undefined
f = (type, mesg) ->
if type == opts.type and ((type == 'json' and mesg.id == opts.id) or (type=='blob' and mesg.uuid=opts.id))
socket.removeListener('mesg', f)
opts.cb(mesg)
socket.on 'mesg', f
if opts.timeout?
timeout = () ->
if socket? and f in socket.listeners('mesg')
socket.removeListener('mesg', f)
opts.cb(message.error(error:"Timed out after #{opts.timeout} seconds."))
setTimeout(timeout, opts.timeout*1000)
# Stop watching data stream for messages and delete the write_mesg function.
exports.disable_mesg = (socket) ->
if socket._listen_for_mesg?
socket.removeListener('data', socket._listen_for_mesg)
delete socket._listen_for_mesg
# Wait to receive token over the socket; when it is received, call
# cb(false), then send back "y". If any mistake is made (or the
# socket times out after 10 seconds), send back "n" and close the
# connection.
exports.unlock_socket = (socket, token, cb) -> # cb(err)
timeout = setTimeout((() -> socket.destroy(); cb("Unlock socket -- timed out waiting for secret token")), 10000)
user_token = ''
listener = (data) ->
user_token += data.<KEY>()
if user_token == token
socket.removeListener('data', listener)
# got it!
socket.write('y')
clearTimeout(timeout)
cb(false)
else if user_token.length > token.length or token.slice(0, user_token.length) != user_token
socket.removeListener('data', listener)
socket.write('n')
socket.write("Invalid secret token.")
socket.destroy()
clearTimeout(timeout)
cb("Invalid secret token.")
socket.on('data', listener)
# Connect to a locked socket on host, unlock it, and do
# cb(err, unlocked_socket).
# WARNING: Use only on an encrypted VPN, since this is not
# an *encryption* protocol.
exports.connect_to_locked_socket = (opts) ->
{port, host, token, timeout, cb} = defaults opts,
host : 'localhost'
port : required
token : required
timeout : 5
cb : required
if not (port > 0 and port < 65536)
cb("connect_to_locked_socket -- RangeError: port should be > 0 and < 65536: #{port}")
return
winston.debug("misc_node: connecting to a locked socket on port #{port}...")
timer = undefined
timed_out = () ->
m = "misc_node: timed out trying to connect to locked socket on port #{port}"
winston.debug(m)
cb?(m)
cb = undefined # NOTE: here and everywhere below we set cb to undefined after calling it, and only call it if defined, since the event and timer callback stuff is very hard to do right here without calling cb more than once (which is VERY bad to do).
socket?.end()
timer = undefined
timer = setTimeout(timed_out, timeout*1000)
socket = net.connect {host:host, port:port}, () =>
listener = (data) ->
winston.debug("misc_node: got back response: #{data}")
socket.removeListener('data', listener)
if data.toString() == 'y'
if timer?
clearTimeout(timer)
cb?(undefined, socket)
cb = undefined
else
socket.destroy()
if timer?
clearTimeout(timer)
cb?("Permission denied (invalid secret token) when connecting to the local hub.")
cb = undefined
socket.on 'data', listener
winston.debug("misc_node: connected, now sending secret token")
socket.write(token)
# This is called in case there is an error trying to make the connection, e.g., "connection refused".
socket.on "error", (err) =>
if timer?
clearTimeout(timer)
cb?(err)
cb = undefined
crypto = require('crypto')
# compute sha1 hash of data in hex
exports.sha1 = (data) ->
sha1sum = crypto.createHash('sha1')
sha1sum.update(data)
return sha1sum.digest('hex')
# Compute a uuid v4 from the Sha-1 hash of data.
exports.uuidsha1 = (data) ->
s = exports.sha1(data)
i = -1
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) ->
i += 1
switch c
when 'x'
return s[i]
when 'y'
# take 8 + low order 3 bits of hex number.
return ((parseInt('0x'+s[i],16)&0x3)|0x8).toString(16)
)
###################################################################
# Execute code
###################################################################
#
temp = require('temp')
async = require('async')
fs = require('fs')
child_process = require 'child_process'
exports.execute_code = execute_code = (opts) ->
opts = defaults opts,
command : required
args : []
path : undefined # defaults to home directory; where code is executed from
timeout : 10 # timeout in *seconds*
ulimit_timeout : true # if set, use ulimit to ensure a cpu timeout -- don't use when launching a daemon!
err_on_exit: true # if true, then a nonzero exit code will result in cb(error_message)
max_output : undefined # bound on size of stdout and stderr; further output ignored
bash : false # if true, ignore args and evaluate command as a bash command
home : undefined
uid : undefined
gid : undefined
env : undefined # if given, added to exec environment
verbose : true
cb : undefined
start_time = walltime()
if opts.verbose
winston.debug("execute_code: \"#{opts.command} #{opts.args.join(' ')}\"")
s = opts.command.split(/\s+/g) # split on whitespace
if opts.args.length == 0 and s.length > 1
opts.bash = true
if not opts.home?
opts.home = process.env.HOME
if not opts.path?
opts.path = opts.home
else if opts.path[0] != '/'
opts.path = opts.home + '/' + opts.path
stdout = ''
stderr = ''
exit_code = undefined
env = misc.copy(process.env)
if opts.env?
for k, v of opts.env
env[k] = v
if opts.uid?
env.HOME = opts.home
tmpfilename = undefined
ran_code = false
async.series([
(c) ->
if not opts.bash
c()
return
if opts.timeout? and opts.ulimit_timeout
# This ensures that everything involved with this
# command really does die no matter what; it's
# better than killing from outside, since it gets
# all subprocesses since they inherit the limits.
cmd = "ulimit -t #{opts.timeout}\n#{opts.command}"
else
cmd = opts.command
if opts.verbose
winston.debug("execute_code: writing temporary file that contains bash program.")
temp.open '', (err, info) ->
if err
c(err)
else
opts.command = 'bash'
opts.args = [info.path]
tmpfilename = info.path
fs.write(info.fd, cmd)
fs.close(info.fd, c)
(c) ->
if tmpfilename?
fs.chmod(tmpfilename, 0o777, c)
else
c()
(c) ->
if opts.verbose
winston.debug("Spawning the command #{opts.command} with given args #{opts.args} and timeout of #{opts.timeout}s...")
o = {cwd:opts.path}
if env?
o.env = env
if opts.uid
o.uid = opts.uid
if opts.gid
o.gid = opts.gid
try
r = child_process.spawn(opts.command, opts.args, o)
catch e
# Yes, spawn can cause this error if there is no memory, and there's no event! -- Error: spawn ENOMEM
c("error #{misc.to_json(e)}")
return
ran_code = true
if opts.verbose
winston.debug("Listen for stdout, stderr and exit events.")
stdout = ''
r.stdout.on 'data', (data) ->
data = data.toString()
if opts.max_output?
if stdout.length < opts.max_output
stdout += data.slice(0,opts.max_output - stdout.length)
else
stdout += data
r.stderr.on 'data', (data) ->
data = data.toString()
if opts.max_output?
if stderr.length < opts.max_output
stderr += data.slice(0,opts.max_output - stderr.length)
else
stderr += data
stderr_is_done = stdout_is_done = false
r.stderr.on 'end', () ->
stderr_is_done = true
finish()
r.stdout.on 'end', () ->
stdout_is_done = true
finish()
r.on 'exit', (code) ->
exit_code = code
finish()
# This can happen, e.g., "Error: spawn ENOMEM" if there is no memory. Without this handler,
# an unhandled exception gets raised, which is nasty.
# From docs: "Note that the exit-event may or may not fire after an error has occured. "
r.on 'error', (err) ->
if not exit_code?
exit_code = 1
stderr += to_json(err)
finish()
callback_done = false
finish = () ->
if stdout_is_done and stderr_is_done and exit_code?
if opts.err_on_exit and exit_code != 0
if not callback_done
callback_done = true
c("command '#{opts.command}' (args=#{opts.args.join(' ')}) exited with nonzero code #{exit_code} -- stderr='#{stderr}'")
else
if opts.max_output?
if stdout.length >= opts.max_output
stdout += " (truncated at #{opts.max_output} characters)"
if stderr.length >= opts.max_output
stderr += " (truncated at #{opts.max_output} characters)"
if not callback_done
callback_done = true
c()
if opts.timeout?
f = () ->
if r.exitCode == null
if opts.verbose
winston.debug("execute_code: subprocess did not exit after #{opts.timeout} seconds, so killing with SIGKILL")
try
r.kill("SIGKILL") # this does not kill the process group :-(
catch e
# Exceptions can happen, which left uncaught messes up calling code bigtime.
if opts.verbose
winston.debug("execute_code: r.kill raised an exception.")
if not callback_done
callback_done = true
c("killed command '#{opts.command} #{opts.args.join(' ')}'")
setTimeout(f, opts.timeout*1000)
], (err) ->
if not exit_code?
exit_code = 1 # don't have one due to SIGKILL
# TODO: This is dangerous, e.g., it could print out a secret_token to a log file.
# winston.debug("(time: #{walltime() - start_time}): Done running '#{opts.command} #{opts.args.join(' ')}'; resulted in stdout='#{misc.trunc(stdout,512)}', stderr='#{misc.trunc(stderr,512)}', exit_code=#{exit_code}, err=#{err}")
# Do not litter:
if tmpfilename?
try
fs.unlink(tmpfilename)
catch e
winston.debug("failed to unlink #{tmpfilename}")
if opts.verbose
winston.debug("finished exec of #{opts.command} (took #{walltime(start_time)}s)")
winston.debug("stdout='#{misc.trunc(stdout,512)}', stderr='#{misc.trunc(stderr,512)}', exit_code=#{exit_code}")
if not opts.err_on_exit and ran_code
# as long as we made it to running some code, we consider this a success (that is what err_on_exit means).
opts.cb?(false, {stdout:stdout, stderr:stderr, exit_code:exit_code})
else
opts.cb?(err, {stdout:stdout, stderr:stderr, exit_code:exit_code})
)
####
## Applications of execute_code
exports.disk_usage = (path, cb) -> # cb(err, usage in K (1024 bytes) of path)
exports.execute_code
command : "du"
args : ['-s', path]
cb : (err, output) ->
if err
cb(err)
else
cb(false, parseInt(output.stdout.split(' ')[0]))
###################################
# project_id --> username mapping
# The username associated to a given project id is just the string of
# the uuid, but with -'s replaced by _'s so we obtain a valid unix
# account name, and shortened to fit Linux and sanity requirements.
exports.username = (project_id) ->
if '..' in project_id or project_id.length != 36
# a sanity check -- this should never ever be allowed to happen, ever.
throw Error("invalid project id #{project_id}")
# Return a for-sure safe username
return project_id.slice(0,8).replace(/[^a-z0-9]/g,'')
address_to_local_port = {}
local_port_to_child_process = {}
exports.keep_portforward_alive = (port) ->
r = local_port_to_child_process[port]
if r?
r.activity = true
exports.unforward_port = (opts) ->
opts = defaults opts,
port : required
cb : required
winston.debug("Unforwarding port #{opts.port}")
r = local_port_to_child_process[local_port]
if r?
r.kill("SIGKILL")
exports.unforward_all_ports = () ->
for port, r of local_port_to_child_process
r.kill("SIGKILL")
free_port = exports.free_port = (cb) -> # cb(err, available port as assigned by the operating system)
server = require("net").createServer()
port = 0
server.on "listening", () ->
port = server.address().port
server.close()
server.on "close", ->
f = () ->
cb(null, port)
# give the OS a chance to really make the port available again.
setTimeout(f, 500)
server.listen(0)
exports.forward_remote_port_to_localhost = (opts) ->
opts = defaults opts,
username : required
host : required
ssh_port : 22
remote_port : required
activity_time : 2000 # kill connection if the HUB doesn't
# actively *receive* something on this
# port for this many seconds.
keep_alive_time:2000 # network activity every this many
# seconds.; lower to more quickly detect
# a broken connection; raise to reduce resources
cb : required # cb(err, local_port)
opts.ssh_port = parseInt(opts.ssh_port)
if not (opts.ssh_port >= 1 and opts.ssh_port <= 66000)
opts.cb("Invalid ssh_port option")
return
opts.remote_port = parseInt(opts.remote_port)
if not (opts.remote_port >= 1 and opts.remote_port <= 66000)
opts.cb("Invalid remote_port option")
return
winston.debug("Forward a remote port #{opts.remote_port} on #{opts.host} to localhost.")
remote_address = "#{opts.username}@#{opts.host}:#{opts.remote_port} -p#{opts.ssh_port}"
###
local_port = address_to_local_port[remote_address]
if local_port?
# We already have a valid forward
opts.cb(false, local_port)
return
###
# We have to make a new port forward
free_port (err, local_port) ->
if err
opts.cb(err)
return
winston.debug("forward_remote_port_to_local_host: local port #{local_port} available")
command = "ssh"
args = ['-o', 'StrictHostKeyChecking=no', "-p", opts.ssh_port,
'-L', "#{local_port}:localhost:#{opts.remote_port}",
"#{opts.username}@#{opts.host}",
"TERM=vt100 /usr/bin/watch -t -n #{opts.keep_alive_time} date"]
r = child_process.spawn(command, args)
cb_happened = false
new_output = false
r.stdout.on 'data', (data) ->
# Got a local_port -- let's use it.
address_to_local_port[remote_address] = local_port
local_port_to_child_process[local_port] = r
new_output = true
# as soon as something is output, it's working (I hope).
if not cb_happened
opts.cb(false, local_port)
cb_happened = true
stderr = ''
r.stderr.on 'data', (data) ->
stderr += data.toString()
kill_if_no_new_output = () ->
if not new_output
winston.debug("Killing ssh port forward #{remote_address} --> localhost:#{local_port} due to it not working")
r.kill("SIGKILL")
new_output = false
# check every few seconds
kill_no_output_timer = setInterval(kill_if_no_new_output, 1000*opts.keep_alive_time)
kill_if_no_new_activity = () ->
if not r.activity?
winston.debug("Killing ssh port forward #{remote_address} --> localhost:#{local_port} due to not receiving any data for at least #{opts.activity_time} seconds.")
r.kill("SIGKILL")
else
# delete it -- the only way connection won't be killed is if this gets set again by an active call to keep_portforward_alive above.
delete r.activity
kill_no_activity_timer = setInterval(kill_if_no_new_activity, 1000*opts.activity_time)
r.on 'exit', (code) ->
if not cb_happened
opts.cb("Problem setting up ssh port forward -- #{stderr}")
delete address_to_local_port[remote_address]
clearInterval(kill_no_output_timer)
clearInterval(kill_no_activity_timer)
# Any non-absolute path is assumed to be relative to the user's home directory.
# This function converts such a path to an absolute path.
exports.abspath = abspath = (path) ->
if path.length == 0
return process.env.HOME
if path[0] == '/'
return path # already an absolute path
p = process.env.HOME + '/' + path
p = p.replace(/\/\.\//g,'/') # get rid of /./, which is the same as /...
return p
# Other path related functions...
# Make sure that that the directory containing the file indicated by
# the path exists and has restrictive permissions.
ensure_containing_directory_exists = (path, cb) -> # cb(err)
path = abspath(path)
dir = misc.path_split(path).head # containing path
fs.exists dir, (exists) ->
if exists
cb?()
else
async.series([
(cb) ->
if dir != ''
# recursively make sure the entire chain of directories exists.
ensure_containing_directory_exists(dir, cb)
else
cb()
(cb) ->
fs.mkdir(dir, 0o700, cb)
], (err) ->
if err.code == 'EEXIST'
cb?()
else
cb?(err)
)
exports.ensure_containing_directory_exists = ensure_containing_directory_exists
# Determine if path (file or directory) is writable -- this works even if permissions are right but
# filesystem is read only, e.g., ~/.zfs/snapshot/...
# It's an error if the path doesn't exist.
exports.is_file_readonly = (opts) ->
opts = defaults opts,
path : required
cb : required # cb(err, true if read only (false otherwise))
readonly = undefined
# determine if file is writable
execute_code
command : 'find'
args : [opts.path, '-maxdepth', '0', '-writable']
err_on_exit : false
cb : (err, output) =>
if err
opts.cb(err)
else if output.stderr or output.exit_code
opts.cb("no such path '#{opts.path}'")
else
readonly = output.stdout.length == 0
opts.cb(undefined, readonly)
# like in sage, a quick way to save/load JSON-able objects to disk; blocking and not compressed.
exports.saveSync = (obj, filename) ->
fs.writeFileSync(filename, JSON.stringify(obj))
exports.loadSync = (filename) ->
JSON.parse(fs.readFileSync(filename).toString())
| true | ###############################################################################
#
# SageMathCloud: A collaborative web-based interface to Sage, IPython, LaTeX and the Terminal.
#
# Copyright (C) 2014, PI:NAME:<NAME>END_PI
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
###############################################################################
####################################################################
#
# misc JS functionality that only makes sense on the node side (not on
# the client)
#
####################################################################
assert = require('assert')
winston = require('winston')
net = require('net')
fs = require('fs')
misc = require 'misc'
async = require('async')
{walltime, defaults, required, to_json} = misc
###
Asynchronous JSON functionality: these are slower but block the main thread *less*.
- to_json_async - convert object to JSON string without blocking.
This uses https://github.com/ckknight/async-json
- from_json_async - convert JSON string to object/etc., without blocking,
though 2x times as slow as JSON.parse. This uses https://github.com/bjouhier/i-json
TESTS:
m=require('misc_node');s=JSON.stringify({x:new Buffer(10000000).toString('hex')}); d=new Date(); m.from_json_async(string: s, chunk_size:10000, cb: (e, r) -> console.log(e, new Date() - d)); new Date() - d
###
###
exports.to_json_async = (opts) ->
opts = defaults opts,
obj : required # Javascript object to convert to a JSON string
cb : required # cb(err, JSON string)
ijson = require('i-json')
exports.from_json_async = (opts) ->
opts = defaults opts,
string : required # string in JSON format
chunk_size : 50000 # size of chunks to parse -- affects how long this blocks the main thread
cb : required
p = ijson.createParser()
s = opts.string
f = (i, cb) ->
#t = misc.mswalltime()
p.update(s.slice(i*opts.chunk_size, (i+1)*opts.chunk_size))
#console.log("update: #{misc.mswalltime(t)}")
setTimeout(cb, 0)
async.mapSeries [0...s.length/opts.chunk_size], f, (err) ->
opts.cb(err, p.result())
###
######################################################################
# Our TCP messaging system. We send a message by first
# sending the length, then the bytes of the actual message. The code
# in this section is used by:
# * hub -- to communicate with sage_server and console_server
######################################################################
# Extend the socket object so that listens to all data coming in on this socket
# and fires a 'mesg' event, along with the JSON object or blob in the message
# So, one listens with:
# socket.on('mesg', (type, value) -> ...)
# where type is one if 'json' or 'blob'.
#
# Calling this function also adds a function .write_mesg to the socket, so that
# socket.write_mesg(type, data)
# will send the message of the given type on the socket. When type='json',
# data is just a JSON-able object. When type='blob', data={uuid:..., blob:...};
# since every blob is tagged with a uuid.
message = require 'message'
exports.enable_mesg = enable_mesg = (socket, desc) ->
socket.setMaxListeners(500) # we use a lot of listeners for listening for messages
socket._buf = null
socket._buf_target_length = -1
socket._listen_for_mesg = (data) ->
socket._buf = if socket._buf == null then data else Buffer.concat([socket._buf, data])
loop
if socket._buf_target_length == -1
# starting to read a new message
if socket._buf.length >= 4
socket._buf_target_length = socket._buf.readUInt32BE(0) + 4
else
return # have to wait for more data to find out message length
if socket._buf_target_length <= socket._buf.length
# read a new message from our buffer
type = socket._buf.slice(4, 5).toString()
mesg = socket._buf.slice(5, socket._buf_target_length)
switch type
when 'j' # JSON
s = mesg.toString()
try
obj = JSON.parse(s)
catch e
winston.debug("Error parsing JSON message='#{misc.trunc(s,512)}' on socket #{desc}")
# TODO -- this throw can seriously mess up the server; handle this
# in a better way in production. This could happen if there is
# corruption of the connection.
#throw(e)
return
socket.emit('mesg', 'json', obj)
when 'b' # BLOB (tagged by a uuid)
socket.emit('mesg', 'blob', {uuid:mesg.slice(0,36).toString(), blob:mesg.slice(36)})
else
throw("unknown message type '#{type}'")
socket._buf = socket._buf.slice(socket._buf_target_length)
socket._buf_target_length = -1
if socket._buf.length == 0
return
else # nothing to do but wait for more data
return
socket.on('data', socket._listen_for_mesg)
socket.write_mesg = (type, data, cb) -> # cb(err)
send = (s) ->
buf = new Buffer(4)
# This line was 4 hours of work. It is absolutely
# *critical* to change the (possibly a string) s into a
# buffer before computing its length and sending it!!
# Otherwise unicode characters will cause trouble.
if typeof(s) == "string"
s = Buffer(s)
buf.writeInt32BE(s.length, 0)
if not socket.writable
cb?("socket not writable")
return
else
socket.write(buf)
if not socket.writable
cb?("socket not writable")
return
else
socket.write(s, cb)
switch type
when 'json'
send('j' + JSON.stringify(data))
when 'blob'
assert(data.uuid?, "data object *must* have a uuid attribute")
assert(data.blob?, "data object *must* have a blob attribute")
send(Buffer.concat([new Buffer('b'), new Buffer(data.uuid), new Buffer(data.blob)]))
else
cb("unknown message type '#{type}'")
# Wait until we receive exactly *one* message of the given type
# with the given id, then call the callback with that message.
# (If the type is 'blob', with the given uuid.)
socket.recv_mesg = (opts) ->
opts = defaults opts,
type : required
id : required # or uuid
cb : required # called with cb(mesg)
timeout : undefined
f = (type, mesg) ->
if type == opts.type and ((type == 'json' and mesg.id == opts.id) or (type=='blob' and mesg.uuid=opts.id))
socket.removeListener('mesg', f)
opts.cb(mesg)
socket.on 'mesg', f
if opts.timeout?
timeout = () ->
if socket? and f in socket.listeners('mesg')
socket.removeListener('mesg', f)
opts.cb(message.error(error:"Timed out after #{opts.timeout} seconds."))
setTimeout(timeout, opts.timeout*1000)
# Stop watching data stream for messages and delete the write_mesg function.
exports.disable_mesg = (socket) ->
if socket._listen_for_mesg?
socket.removeListener('data', socket._listen_for_mesg)
delete socket._listen_for_mesg
# Wait to receive token over the socket; when it is received, call
# cb(false), then send back "y". If any mistake is made (or the
# socket times out after 10 seconds), send back "n" and close the
# connection.
exports.unlock_socket = (socket, token, cb) -> # cb(err)
timeout = setTimeout((() -> socket.destroy(); cb("Unlock socket -- timed out waiting for secret token")), 10000)
user_token = ''
listener = (data) ->
user_token += data.PI:KEY:<KEY>END_PI()
if user_token == token
socket.removeListener('data', listener)
# got it!
socket.write('y')
clearTimeout(timeout)
cb(false)
else if user_token.length > token.length or token.slice(0, user_token.length) != user_token
socket.removeListener('data', listener)
socket.write('n')
socket.write("Invalid secret token.")
socket.destroy()
clearTimeout(timeout)
cb("Invalid secret token.")
socket.on('data', listener)
# Connect to a locked socket on host, unlock it, and do
# cb(err, unlocked_socket).
# WARNING: Use only on an encrypted VPN, since this is not
# an *encryption* protocol.
exports.connect_to_locked_socket = (opts) ->
{port, host, token, timeout, cb} = defaults opts,
host : 'localhost'
port : required
token : required
timeout : 5
cb : required
if not (port > 0 and port < 65536)
cb("connect_to_locked_socket -- RangeError: port should be > 0 and < 65536: #{port}")
return
winston.debug("misc_node: connecting to a locked socket on port #{port}...")
timer = undefined
timed_out = () ->
m = "misc_node: timed out trying to connect to locked socket on port #{port}"
winston.debug(m)
cb?(m)
cb = undefined # NOTE: here and everywhere below we set cb to undefined after calling it, and only call it if defined, since the event and timer callback stuff is very hard to do right here without calling cb more than once (which is VERY bad to do).
socket?.end()
timer = undefined
timer = setTimeout(timed_out, timeout*1000)
socket = net.connect {host:host, port:port}, () =>
listener = (data) ->
winston.debug("misc_node: got back response: #{data}")
socket.removeListener('data', listener)
if data.toString() == 'y'
if timer?
clearTimeout(timer)
cb?(undefined, socket)
cb = undefined
else
socket.destroy()
if timer?
clearTimeout(timer)
cb?("Permission denied (invalid secret token) when connecting to the local hub.")
cb = undefined
socket.on 'data', listener
winston.debug("misc_node: connected, now sending secret token")
socket.write(token)
# This is called in case there is an error trying to make the connection, e.g., "connection refused".
socket.on "error", (err) =>
if timer?
clearTimeout(timer)
cb?(err)
cb = undefined
crypto = require('crypto')
# compute sha1 hash of data in hex
exports.sha1 = (data) ->
sha1sum = crypto.createHash('sha1')
sha1sum.update(data)
return sha1sum.digest('hex')
# Compute a uuid v4 from the Sha-1 hash of data.
exports.uuidsha1 = (data) ->
s = exports.sha1(data)
i = -1
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) ->
i += 1
switch c
when 'x'
return s[i]
when 'y'
# take 8 + low order 3 bits of hex number.
return ((parseInt('0x'+s[i],16)&0x3)|0x8).toString(16)
)
###################################################################
# Execute code
###################################################################
#
temp = require('temp')
async = require('async')
fs = require('fs')
child_process = require 'child_process'
exports.execute_code = execute_code = (opts) ->
opts = defaults opts,
command : required
args : []
path : undefined # defaults to home directory; where code is executed from
timeout : 10 # timeout in *seconds*
ulimit_timeout : true # if set, use ulimit to ensure a cpu timeout -- don't use when launching a daemon!
err_on_exit: true # if true, then a nonzero exit code will result in cb(error_message)
max_output : undefined # bound on size of stdout and stderr; further output ignored
bash : false # if true, ignore args and evaluate command as a bash command
home : undefined
uid : undefined
gid : undefined
env : undefined # if given, added to exec environment
verbose : true
cb : undefined
start_time = walltime()
if opts.verbose
winston.debug("execute_code: \"#{opts.command} #{opts.args.join(' ')}\"")
s = opts.command.split(/\s+/g) # split on whitespace
if opts.args.length == 0 and s.length > 1
opts.bash = true
if not opts.home?
opts.home = process.env.HOME
if not opts.path?
opts.path = opts.home
else if opts.path[0] != '/'
opts.path = opts.home + '/' + opts.path
stdout = ''
stderr = ''
exit_code = undefined
env = misc.copy(process.env)
if opts.env?
for k, v of opts.env
env[k] = v
if opts.uid?
env.HOME = opts.home
tmpfilename = undefined
ran_code = false
async.series([
(c) ->
if not opts.bash
c()
return
if opts.timeout? and opts.ulimit_timeout
# This ensures that everything involved with this
# command really does die no matter what; it's
# better than killing from outside, since it gets
# all subprocesses since they inherit the limits.
cmd = "ulimit -t #{opts.timeout}\n#{opts.command}"
else
cmd = opts.command
if opts.verbose
winston.debug("execute_code: writing temporary file that contains bash program.")
temp.open '', (err, info) ->
if err
c(err)
else
opts.command = 'bash'
opts.args = [info.path]
tmpfilename = info.path
fs.write(info.fd, cmd)
fs.close(info.fd, c)
(c) ->
if tmpfilename?
fs.chmod(tmpfilename, 0o777, c)
else
c()
(c) ->
if opts.verbose
winston.debug("Spawning the command #{opts.command} with given args #{opts.args} and timeout of #{opts.timeout}s...")
o = {cwd:opts.path}
if env?
o.env = env
if opts.uid
o.uid = opts.uid
if opts.gid
o.gid = opts.gid
try
r = child_process.spawn(opts.command, opts.args, o)
catch e
# Yes, spawn can cause this error if there is no memory, and there's no event! -- Error: spawn ENOMEM
c("error #{misc.to_json(e)}")
return
ran_code = true
if opts.verbose
winston.debug("Listen for stdout, stderr and exit events.")
stdout = ''
r.stdout.on 'data', (data) ->
data = data.toString()
if opts.max_output?
if stdout.length < opts.max_output
stdout += data.slice(0,opts.max_output - stdout.length)
else
stdout += data
r.stderr.on 'data', (data) ->
data = data.toString()
if opts.max_output?
if stderr.length < opts.max_output
stderr += data.slice(0,opts.max_output - stderr.length)
else
stderr += data
stderr_is_done = stdout_is_done = false
r.stderr.on 'end', () ->
stderr_is_done = true
finish()
r.stdout.on 'end', () ->
stdout_is_done = true
finish()
r.on 'exit', (code) ->
exit_code = code
finish()
# This can happen, e.g., "Error: spawn ENOMEM" if there is no memory. Without this handler,
# an unhandled exception gets raised, which is nasty.
# From docs: "Note that the exit-event may or may not fire after an error has occured. "
r.on 'error', (err) ->
if not exit_code?
exit_code = 1
stderr += to_json(err)
finish()
callback_done = false
finish = () ->
if stdout_is_done and stderr_is_done and exit_code?
if opts.err_on_exit and exit_code != 0
if not callback_done
callback_done = true
c("command '#{opts.command}' (args=#{opts.args.join(' ')}) exited with nonzero code #{exit_code} -- stderr='#{stderr}'")
else
if opts.max_output?
if stdout.length >= opts.max_output
stdout += " (truncated at #{opts.max_output} characters)"
if stderr.length >= opts.max_output
stderr += " (truncated at #{opts.max_output} characters)"
if not callback_done
callback_done = true
c()
if opts.timeout?
f = () ->
if r.exitCode == null
if opts.verbose
winston.debug("execute_code: subprocess did not exit after #{opts.timeout} seconds, so killing with SIGKILL")
try
r.kill("SIGKILL") # this does not kill the process group :-(
catch e
# Exceptions can happen, which left uncaught messes up calling code bigtime.
if opts.verbose
winston.debug("execute_code: r.kill raised an exception.")
if not callback_done
callback_done = true
c("killed command '#{opts.command} #{opts.args.join(' ')}'")
setTimeout(f, opts.timeout*1000)
], (err) ->
if not exit_code?
exit_code = 1 # don't have one due to SIGKILL
# TODO: This is dangerous, e.g., it could print out a secret_token to a log file.
# winston.debug("(time: #{walltime() - start_time}): Done running '#{opts.command} #{opts.args.join(' ')}'; resulted in stdout='#{misc.trunc(stdout,512)}', stderr='#{misc.trunc(stderr,512)}', exit_code=#{exit_code}, err=#{err}")
# Do not litter:
if tmpfilename?
try
fs.unlink(tmpfilename)
catch e
winston.debug("failed to unlink #{tmpfilename}")
if opts.verbose
winston.debug("finished exec of #{opts.command} (took #{walltime(start_time)}s)")
winston.debug("stdout='#{misc.trunc(stdout,512)}', stderr='#{misc.trunc(stderr,512)}', exit_code=#{exit_code}")
if not opts.err_on_exit and ran_code
# as long as we made it to running some code, we consider this a success (that is what err_on_exit means).
opts.cb?(false, {stdout:stdout, stderr:stderr, exit_code:exit_code})
else
opts.cb?(err, {stdout:stdout, stderr:stderr, exit_code:exit_code})
)
####
## Applications of execute_code
exports.disk_usage = (path, cb) -> # cb(err, usage in K (1024 bytes) of path)
exports.execute_code
command : "du"
args : ['-s', path]
cb : (err, output) ->
if err
cb(err)
else
cb(false, parseInt(output.stdout.split(' ')[0]))
###################################
# project_id --> username mapping
# The username associated to a given project id is just the string of
# the uuid, but with -'s replaced by _'s so we obtain a valid unix
# account name, and shortened to fit Linux and sanity requirements.
exports.username = (project_id) ->
if '..' in project_id or project_id.length != 36
# a sanity check -- this should never ever be allowed to happen, ever.
throw Error("invalid project id #{project_id}")
# Return a for-sure safe username
return project_id.slice(0,8).replace(/[^a-z0-9]/g,'')
address_to_local_port = {}
local_port_to_child_process = {}
exports.keep_portforward_alive = (port) ->
r = local_port_to_child_process[port]
if r?
r.activity = true
exports.unforward_port = (opts) ->
opts = defaults opts,
port : required
cb : required
winston.debug("Unforwarding port #{opts.port}")
r = local_port_to_child_process[local_port]
if r?
r.kill("SIGKILL")
exports.unforward_all_ports = () ->
for port, r of local_port_to_child_process
r.kill("SIGKILL")
free_port = exports.free_port = (cb) -> # cb(err, available port as assigned by the operating system)
server = require("net").createServer()
port = 0
server.on "listening", () ->
port = server.address().port
server.close()
server.on "close", ->
f = () ->
cb(null, port)
# give the OS a chance to really make the port available again.
setTimeout(f, 500)
server.listen(0)
exports.forward_remote_port_to_localhost = (opts) ->
opts = defaults opts,
username : required
host : required
ssh_port : 22
remote_port : required
activity_time : 2000 # kill connection if the HUB doesn't
# actively *receive* something on this
# port for this many seconds.
keep_alive_time:2000 # network activity every this many
# seconds.; lower to more quickly detect
# a broken connection; raise to reduce resources
cb : required # cb(err, local_port)
opts.ssh_port = parseInt(opts.ssh_port)
if not (opts.ssh_port >= 1 and opts.ssh_port <= 66000)
opts.cb("Invalid ssh_port option")
return
opts.remote_port = parseInt(opts.remote_port)
if not (opts.remote_port >= 1 and opts.remote_port <= 66000)
opts.cb("Invalid remote_port option")
return
winston.debug("Forward a remote port #{opts.remote_port} on #{opts.host} to localhost.")
remote_address = "#{opts.username}@#{opts.host}:#{opts.remote_port} -p#{opts.ssh_port}"
###
local_port = address_to_local_port[remote_address]
if local_port?
# We already have a valid forward
opts.cb(false, local_port)
return
###
# We have to make a new port forward
free_port (err, local_port) ->
if err
opts.cb(err)
return
winston.debug("forward_remote_port_to_local_host: local port #{local_port} available")
command = "ssh"
args = ['-o', 'StrictHostKeyChecking=no', "-p", opts.ssh_port,
'-L', "#{local_port}:localhost:#{opts.remote_port}",
"#{opts.username}@#{opts.host}",
"TERM=vt100 /usr/bin/watch -t -n #{opts.keep_alive_time} date"]
r = child_process.spawn(command, args)
cb_happened = false
new_output = false
r.stdout.on 'data', (data) ->
# Got a local_port -- let's use it.
address_to_local_port[remote_address] = local_port
local_port_to_child_process[local_port] = r
new_output = true
# as soon as something is output, it's working (I hope).
if not cb_happened
opts.cb(false, local_port)
cb_happened = true
stderr = ''
r.stderr.on 'data', (data) ->
stderr += data.toString()
kill_if_no_new_output = () ->
if not new_output
winston.debug("Killing ssh port forward #{remote_address} --> localhost:#{local_port} due to it not working")
r.kill("SIGKILL")
new_output = false
# check every few seconds
kill_no_output_timer = setInterval(kill_if_no_new_output, 1000*opts.keep_alive_time)
kill_if_no_new_activity = () ->
if not r.activity?
winston.debug("Killing ssh port forward #{remote_address} --> localhost:#{local_port} due to not receiving any data for at least #{opts.activity_time} seconds.")
r.kill("SIGKILL")
else
# delete it -- the only way connection won't be killed is if this gets set again by an active call to keep_portforward_alive above.
delete r.activity
kill_no_activity_timer = setInterval(kill_if_no_new_activity, 1000*opts.activity_time)
r.on 'exit', (code) ->
if not cb_happened
opts.cb("Problem setting up ssh port forward -- #{stderr}")
delete address_to_local_port[remote_address]
clearInterval(kill_no_output_timer)
clearInterval(kill_no_activity_timer)
# Any non-absolute path is assumed to be relative to the user's home directory.
# This function converts such a path to an absolute path.
exports.abspath = abspath = (path) ->
if path.length == 0
return process.env.HOME
if path[0] == '/'
return path # already an absolute path
p = process.env.HOME + '/' + path
p = p.replace(/\/\.\//g,'/') # get rid of /./, which is the same as /...
return p
# Other path related functions...
# Make sure that that the directory containing the file indicated by
# the path exists and has restrictive permissions.
ensure_containing_directory_exists = (path, cb) -> # cb(err)
path = abspath(path)
dir = misc.path_split(path).head # containing path
fs.exists dir, (exists) ->
if exists
cb?()
else
async.series([
(cb) ->
if dir != ''
# recursively make sure the entire chain of directories exists.
ensure_containing_directory_exists(dir, cb)
else
cb()
(cb) ->
fs.mkdir(dir, 0o700, cb)
], (err) ->
if err.code == 'EEXIST'
cb?()
else
cb?(err)
)
exports.ensure_containing_directory_exists = ensure_containing_directory_exists
# Determine if path (file or directory) is writable -- this works even if permissions are right but
# filesystem is read only, e.g., ~/.zfs/snapshot/...
# It's an error if the path doesn't exist.
exports.is_file_readonly = (opts) ->
opts = defaults opts,
path : required
cb : required # cb(err, true if read only (false otherwise))
readonly = undefined
# determine if file is writable
execute_code
command : 'find'
args : [opts.path, '-maxdepth', '0', '-writable']
err_on_exit : false
cb : (err, output) =>
if err
opts.cb(err)
else if output.stderr or output.exit_code
opts.cb("no such path '#{opts.path}'")
else
readonly = output.stdout.length == 0
opts.cb(undefined, readonly)
# like in sage, a quick way to save/load JSON-able objects to disk; blocking and not compressed.
exports.saveSync = (obj, filename) ->
fs.writeFileSync(filename, JSON.stringify(obj))
exports.loadSync = (filename) ->
JSON.parse(fs.readFileSync(filename).toString())
|
[
{
"context": " origin = { constructorName: 'JAccount', id: '5asf222141saf' }\n * loadAccount origin, (err, account) -> c",
"end": 344,
"score": 0.550065279006958,
"start": 332,
"tag": "PASSWORD",
"value": "asf222141saf"
},
{
"context": " remote.api.JAccount.one { 'profile.ni... | client/app/lib/util/fetchAccount.coffee | lionheart1022/koding | 0 | remote = require 'app/remote'
###*
* Wrapper function around `JAccount#cacheable`
* It adds a little bit of intelligence around first
* argument so that, it will fetch the account depending
* on some other situations.
*
* Example:
*
* # it accepts an origin object.
* origin = { constructorName: 'JAccount', id: '5asf222141saf' }
* loadAccount origin, (err, account) -> console.log account
*
* # or it accepts a username string.
* loadAccount 'foo', (err, account) -> console.log account
*
*
* @param {object|string} origin
* @param {function(err: object, account: JAccount)}
###
module.exports = fetchAccount = (origin, callback) ->
if origin.constructorName
origin.id or= origin._id
remote.cacheable origin.constructorName, origin.id, callback
else if 'bot' is origin
remote.api.JAccount.one { 'profile.nickname': 'bot' }, callback
else if 'string' is typeof origin
remote.cacheable origin, (err, [account]) -> callback err, account
else if origin?.bongo_?.constructorName is 'JAccount'
callback null, origin
else if origin?.isIntegration
callback null, origin
else
callback { message: 'utils.fetchAccount: wrong type of argument - origin' }
| 10236 | remote = require 'app/remote'
###*
* Wrapper function around `JAccount#cacheable`
* It adds a little bit of intelligence around first
* argument so that, it will fetch the account depending
* on some other situations.
*
* Example:
*
* # it accepts an origin object.
* origin = { constructorName: 'JAccount', id: '5<PASSWORD>' }
* loadAccount origin, (err, account) -> console.log account
*
* # or it accepts a username string.
* loadAccount 'foo', (err, account) -> console.log account
*
*
* @param {object|string} origin
* @param {function(err: object, account: JAccount)}
###
module.exports = fetchAccount = (origin, callback) ->
if origin.constructorName
origin.id or= origin._id
remote.cacheable origin.constructorName, origin.id, callback
else if 'bot' is origin
remote.api.JAccount.one { 'profile.nickname': 'bot' }, callback
else if 'string' is typeof origin
remote.cacheable origin, (err, [account]) -> callback err, account
else if origin?.bongo_?.constructorName is 'JAccount'
callback null, origin
else if origin?.isIntegration
callback null, origin
else
callback { message: 'utils.fetchAccount: wrong type of argument - origin' }
| true | remote = require 'app/remote'
###*
* Wrapper function around `JAccount#cacheable`
* It adds a little bit of intelligence around first
* argument so that, it will fetch the account depending
* on some other situations.
*
* Example:
*
* # it accepts an origin object.
* origin = { constructorName: 'JAccount', id: '5PI:PASSWORD:<PASSWORD>END_PI' }
* loadAccount origin, (err, account) -> console.log account
*
* # or it accepts a username string.
* loadAccount 'foo', (err, account) -> console.log account
*
*
* @param {object|string} origin
* @param {function(err: object, account: JAccount)}
###
module.exports = fetchAccount = (origin, callback) ->
if origin.constructorName
origin.id or= origin._id
remote.cacheable origin.constructorName, origin.id, callback
else if 'bot' is origin
remote.api.JAccount.one { 'profile.nickname': 'bot' }, callback
else if 'string' is typeof origin
remote.cacheable origin, (err, [account]) -> callback err, account
else if origin?.bongo_?.constructorName is 'JAccount'
callback null, origin
else if origin?.isIntegration
callback null, origin
else
callback { message: 'utils.fetchAccount: wrong type of argument - origin' }
|
[
{
"context": "ll Name: Coffeescript Javascript File\n# Developer: Jeremy Ashkenas\n# File Type: Executable Programming File\n# Wiki: ",
"end": 289,
"score": 0.9998900890350342,
"start": 274,
"tag": "NAME",
"value": "Jeremy Ashkenas"
}
] | hello_world/coffeescript.coffee | AaryanKhClasses/Programming-Languages | 1 | # JavaScript file written in CoffeeScript, a programming language that compiles and transcompiles to JavaScript; saved in a text format and contains code that is similar to JavaScript, but modified to be more readable.
# Full Name: Coffeescript Javascript File
# Developer: Jeremy Ashkenas
# File Type: Executable Programming File
# Wiki: https://en.wikipedia.org/wiki/CoffeeScript
console.log("Hello World!") # Prints the "Hello World" | 30903 | # JavaScript file written in CoffeeScript, a programming language that compiles and transcompiles to JavaScript; saved in a text format and contains code that is similar to JavaScript, but modified to be more readable.
# Full Name: Coffeescript Javascript File
# Developer: <NAME>
# File Type: Executable Programming File
# Wiki: https://en.wikipedia.org/wiki/CoffeeScript
console.log("Hello World!") # Prints the "Hello World" | true | # JavaScript file written in CoffeeScript, a programming language that compiles and transcompiles to JavaScript; saved in a text format and contains code that is similar to JavaScript, but modified to be more readable.
# Full Name: Coffeescript Javascript File
# Developer: PI:NAME:<NAME>END_PI
# File Type: Executable Programming File
# Wiki: https://en.wikipedia.org/wiki/CoffeeScript
console.log("Hello World!") # Prints the "Hello World" |
[
{
"context": "nto battle.\"\n }\n {\n name: 'Mobile Artillery'\n difficulty: 1\n id: 'mobile-artill",
"end": 3146,
"score": 0.5322274565696716,
"start": 3137,
"tag": "NAME",
"value": "Artillery"
},
{
"context": " ]\n\n experienced = [\n {\n ... | app/views/play_view.coffee | oaugereau/codecombat | 0 | View = require 'views/kinds/RootView'
template = require 'templates/play'
LevelSession = require 'models/LevelSession'
CocoCollection = require 'collections/CocoCollection'
class LevelSessionsCollection extends CocoCollection
url: ''
model: LevelSession
constructor: (model) ->
super()
@url = "/db/user/#{me.id}/level.sessions?project=state.complete,levelID"
module.exports = class PlayView extends View
id: "play-view"
template: template
constructor: (options) ->
super options
@levelStatusMap = {}
@sessions = new LevelSessionsCollection()
@sessions.fetch()
@listenToOnce @sessions, 'sync', @onSessionsLoaded
onSessionsLoaded: (e) ->
for session in @sessions.models
@levelStatusMap[session.get('levelID')] = if session.get('state')?.complete then 'complete' else 'started'
@render()
getRenderData: (context={}) ->
context = super(context)
context.home = true
context.notFound = @getQueryVariable 'not_found'
tutorials = [
{
name: 'Rescue Mission'
difficulty: 1
id: 'rescue-mission'
image: '/file/db/level/52740644904ac0411700067c/rescue_mission_icon.png'
description: "Tharin has been captured!"
}
{
name: 'Grab the Mushroom'
difficulty: 1
id: 'grab-the-mushroom'
image: '/file/db/level/529662dfe0df8f0000000007/grab_the_mushroom_icon.png'
description: "Grab a powerup and smash a big ogre."
}
{
name: 'Drink Me'
difficulty: 1
id: 'drink-me'
image: '/file/db/level/525dc5589a0765e496000006/drink_me_icon.png'
description: "Drink up and slay two munchkins."
}
{
name: 'Taunt the Guards'
difficulty: 1
id: 'taunt-the-guards'
image: '/file/db/level/5276c9bdcf83207a2801ff8f/taunt_icon.png'
description: "Tharin, if clever, can escape with Phoebe."
}
{
name: "It's a Trap"
difficulty: 1
id: 'its-a-trap'
image: '/file/db/level/528aea2d7f37fc4e0700016b/its_a_trap_icon.png'
description: "Organize a dungeon ambush with archers."
}
{
name: 'Break the Prison'
difficulty: 1
id: 'break-the-prison'
image: '/file/db/level/5275272c69abdcb12401216e/break_the_prison_icon.png'
description: "More comrades are imprisoned!"
}
{
name: 'Taunt'
difficulty: 1
id: 'taunt'
image: '/file/db/level/525f150306e1ab0962000018/taunt_icon.png'
description: "Taunt the ogre to claim victory."
}
{
name: 'Cowardly Taunt'
difficulty: 1
id: 'cowardly-taunt'
image: '/file/db/level/525abfd9b12777d78e000009/cowardly_taunt_icon.png'
description: "Lure infuriated ogres to their doom."
}
{
name: 'Commanding Followers'
difficulty: 1
id: 'commanding-followers'
image: '/file/db/level/525ef8ef06e1ab0962000003/commanding_followers_icon.png'
description: "Lead allied soldiers into battle."
}
{
name: 'Mobile Artillery'
difficulty: 1
id: 'mobile-artillery'
image: '/file/db/level/525085419851b83f4b000001/mobile_artillery_icon.png'
description: "Blow ogres up!"
}
]
experienced = [
{
name: 'Hunter Triplets'
difficulty: 2
id: 'hunter-triplets'
image: '/file/db/level/526711d9add4f8965f000002/hunter_triplets_icon.png'
description: "Three soldiers go ogre hunting."
}
{
name: 'Emphasis on Aim'
difficulty: 2
id: 'emphasis-on-aim'
image: '/file/db/level/525f384d96cd77000000000f/munchkin_masher_icon.png'
description: "Chose your targets carefully."
}
{
name: 'Zone of Danger'
difficulty: 3
id: 'zone-of-danger'
image: '/file/db/level/526ae95c1e5cd30000000008/zone_of_danger_icon.png'
description: "Target the ogres swarming into arrow range."
}
{
name: 'Molotov Medic'
difficulty: 2
id: 'molotov-medic'
image: '/file/db/level/52602ecb026e8481e7000001/generic_1.png'
description: "Tharin must play support in this dungeon battle."
}
{
name: 'Gridmancer'
difficulty: 5
id: 'gridmancer'
image: '/file/db/level/52ae2460ef42c52f13000008/gridmancer_icon.png'
description: "Super algorithm challenge level!"
}
]
arenas = [
{
name: 'Greed'
difficulty: 4
id: 'greed'
image: '/file/db/level/526fd3043c637ece50001bb2/the_herd_icon.png'
description: "Liked Dungeon Arena and Gold Rush? Put them together in this economic arena!"
levelPath: 'ladder'
}
{
name: 'Dungeon Arena'
difficulty: 3
id: 'dungeon-arena'
image: '/file/db/level/526ae95c1e5cd30000000008/zone_of_danger_icon.png'
description: "Play head-to-head against fellow Wizards in a dungeon melee!"
levelPath: 'ladder'
}
{
name: 'Gold Rush'
difficulty: 3
id: 'gold-rush'
image: '/file/db/level/52602ecb026e8481e7000001/generic_1.png'
description: "Prove you are better at collecting gold than your opponent!"
levelPath: 'ladder'
}
{
name: 'Brawlwood'
difficulty: 4
id: 'brawlwood'
image: '/file/db/level/525ef8ef06e1ab0962000003/commanding_followers_icon.png'
description: "Combat the armies of other Wizards in a strategic forest arena! (Fast computer required.)"
levelPath: 'ladder'
}
]
playerCreated = [
{
name: 'Extra Extrapolation'
difficulty: 2
id: 'extra-extrapolation'
image: '/file/db/level/526bda3fe79aefde2a003e36/mobile_artillery_icon.png'
description: "Predict your target's position for deadly aim. - by Sootn"
}
{
name: 'The Right Route'
difficulty: 1
id: 'the-right-route'
image: '/file/db/level/526fd3043c637ece50001bb2/the_herd_icon.png'
description: "Strike at the weak point in an array of enemies. - by Aftermath"
}
{
name: 'Sword Loop'
difficulty: 2
id: 'sword-loop'
image: '/file/db/level/525dc5589a0765e496000006/drink_me_icon.png'
description: 'Kill the ogres and save the peasants with for-loops. - by Prabh Simran Singh Baweja'
}
{
name: 'Coin Mania'
difficulty: 2
id: 'coin-mania'
image: '/file/db/level/529662dfe0df8f0000000007/grab_the_mushroom_icon.png'
description: 'Learn while-loops to grab coins and potions. - by Prabh Simran Singh Baweja'
}
{
name: 'Bubble Sort Bootcamp Battle'
difficulty: 3
id: 'bubble-sort-bootcamp-battle'
image: '/file/db/level/525ef8ef06e1ab0962000003/commanding_followers_icon.png'
description: "Write a bubble sort to organize your soldiers. - by Alexandru Caciulescu"
}
{
name: 'Ogres of Hanoi'
difficulty: 3
id: 'ogres-of-hanoi'
image: '/file/db/level/526fd3043c637ece50001bb2/the_herd_icon.png'
description: "Transfer a stack of ogres while preserving their honor. - by Alexandru Caciulescu"
}
{
name: 'Danger! Minefield'
difficulty: 3
id: 'danger-minefield'
image: '/file/db/level/526bda3fe79aefde2a003e36/mobile_artillery_icon.png'
description: "Learn how to find prime numbers while defusing mines! - by Alexandru Caciulescu"
}
{
name: 'Find the Spy'
difficulty: 2
id: 'find-the-spy'
image: '/file/db/level/526ae95c1e5cd30000000008/zone_of_danger_icon.png'
description: "Identify the spies hidden among your soldiers - by Nathan Gossett"
}
{
name: 'Harvest Time'
difficulty: 2
id: 'harvest-time'
image: '/file/db/level/529662dfe0df8f0000000007/grab_the_mushroom_icon.png'
description: "Collect a hundred mushrooms in just five lines of code - by Nathan Gossett"
}
]
context.campaigns = [
{id: "beginner", name: "Beginner Campaign", description: "... in which you learn the wizardry of programming.", levels: tutorials}
{id: "multiplayer", name: "Multiplayer Arenas", description: "... in which you code head-to-head against other players.", levels: arenas}
{id: "dev", name: "Random Harder Levels", description: "... in which you learn the interface while doing something a little harder.", levels: experienced}
{id: "player_created", name: "Player-Created", description: "... in which you battle against the creativity of your fellow <a href=\"/contribute#artisan\">Artisan Wizards</a>.", levels: playerCreated}
]
context.levelStatusMap = @levelStatusMap
context
afterRender: ->
super()
@$el.find('.modal').on 'shown.bs.modal', ->
$('input:visible:first', @).focus()
| 75682 | View = require 'views/kinds/RootView'
template = require 'templates/play'
LevelSession = require 'models/LevelSession'
CocoCollection = require 'collections/CocoCollection'
class LevelSessionsCollection extends CocoCollection
url: ''
model: LevelSession
constructor: (model) ->
super()
@url = "/db/user/#{me.id}/level.sessions?project=state.complete,levelID"
module.exports = class PlayView extends View
id: "play-view"
template: template
constructor: (options) ->
super options
@levelStatusMap = {}
@sessions = new LevelSessionsCollection()
@sessions.fetch()
@listenToOnce @sessions, 'sync', @onSessionsLoaded
onSessionsLoaded: (e) ->
for session in @sessions.models
@levelStatusMap[session.get('levelID')] = if session.get('state')?.complete then 'complete' else 'started'
@render()
getRenderData: (context={}) ->
context = super(context)
context.home = true
context.notFound = @getQueryVariable 'not_found'
tutorials = [
{
name: 'Rescue Mission'
difficulty: 1
id: 'rescue-mission'
image: '/file/db/level/52740644904ac0411700067c/rescue_mission_icon.png'
description: "Tharin has been captured!"
}
{
name: 'Grab the Mushroom'
difficulty: 1
id: 'grab-the-mushroom'
image: '/file/db/level/529662dfe0df8f0000000007/grab_the_mushroom_icon.png'
description: "Grab a powerup and smash a big ogre."
}
{
name: 'Drink Me'
difficulty: 1
id: 'drink-me'
image: '/file/db/level/525dc5589a0765e496000006/drink_me_icon.png'
description: "Drink up and slay two munchkins."
}
{
name: 'Taunt the Guards'
difficulty: 1
id: 'taunt-the-guards'
image: '/file/db/level/5276c9bdcf83207a2801ff8f/taunt_icon.png'
description: "Tharin, if clever, can escape with Phoebe."
}
{
name: "It's a Trap"
difficulty: 1
id: 'its-a-trap'
image: '/file/db/level/528aea2d7f37fc4e0700016b/its_a_trap_icon.png'
description: "Organize a dungeon ambush with archers."
}
{
name: 'Break the Prison'
difficulty: 1
id: 'break-the-prison'
image: '/file/db/level/5275272c69abdcb12401216e/break_the_prison_icon.png'
description: "More comrades are imprisoned!"
}
{
name: 'Taunt'
difficulty: 1
id: 'taunt'
image: '/file/db/level/525f150306e1ab0962000018/taunt_icon.png'
description: "Taunt the ogre to claim victory."
}
{
name: 'Cowardly Taunt'
difficulty: 1
id: 'cowardly-taunt'
image: '/file/db/level/525abfd9b12777d78e000009/cowardly_taunt_icon.png'
description: "Lure infuriated ogres to their doom."
}
{
name: 'Commanding Followers'
difficulty: 1
id: 'commanding-followers'
image: '/file/db/level/525ef8ef06e1ab0962000003/commanding_followers_icon.png'
description: "Lead allied soldiers into battle."
}
{
name: 'Mobile <NAME>'
difficulty: 1
id: 'mobile-artillery'
image: '/file/db/level/525085419851b83f4b000001/mobile_artillery_icon.png'
description: "Blow ogres up!"
}
]
experienced = [
{
name: '<NAME>'
difficulty: 2
id: 'hunter-triplets'
image: '/file/db/level/526711d9add4f8965f000002/hunter_triplets_icon.png'
description: "Three soldiers go ogre hunting."
}
{
name: 'Emphasis on Aim'
difficulty: 2
id: 'emphasis-on-aim'
image: '/file/db/level/525f384d96cd77000000000f/munchkin_masher_icon.png'
description: "Chose your targets carefully."
}
{
name: 'Zone of D<NAME>'
difficulty: 3
id: 'zone-of-danger'
image: '/file/db/level/526ae95c1e5cd30000000008/zone_of_danger_icon.png'
description: "Target the ogres swarming into arrow range."
}
{
name: '<NAME>'
difficulty: 2
id: 'molotov-medic'
image: '/file/db/level/52602ecb026e8481e7000001/generic_1.png'
description: "Tharin must play support in this dungeon battle."
}
{
name: '<NAME>'
difficulty: 5
id: 'gridmancer'
image: '/file/db/level/52ae2460ef42c52f13000008/gridmancer_icon.png'
description: "Super algorithm challenge level!"
}
]
arenas = [
{
name: '<NAME>'
difficulty: 4
id: 'greed'
image: '/file/db/level/526fd3043c637ece50001bb2/the_herd_icon.png'
description: "Liked Dungeon Arena and Gold Rush? Put them together in this economic arena!"
levelPath: 'ladder'
}
{
name: 'Dungeon Arena'
difficulty: 3
id: 'dungeon-arena'
image: '/file/db/level/526ae95c1e5cd30000000008/zone_of_danger_icon.png'
description: "Play head-to-head against fellow Wizards in a dungeon melee!"
levelPath: 'ladder'
}
{
name: '<NAME>'
difficulty: 3
id: 'gold-rush'
image: '/file/db/level/52602ecb026e8481e7000001/generic_1.png'
description: "Prove you are better at collecting gold than your opponent!"
levelPath: 'ladder'
}
{
name: '<NAME>'
difficulty: 4
id: 'brawlwood'
image: '/file/db/level/525ef8ef06e1ab0962000003/commanding_followers_icon.png'
description: "Combat the armies of other Wizards in a strategic forest arena! (Fast computer required.)"
levelPath: 'ladder'
}
]
playerCreated = [
{
name: 'Extra Extrapolation'
difficulty: 2
id: 'extra-extrapolation'
image: '/file/db/level/526bda3fe79aefde2a003e36/mobile_artillery_icon.png'
description: "Predict your target's position for deadly aim. - by Sootn"
}
{
name: 'The Right Route'
difficulty: 1
id: 'the-right-route'
image: '/file/db/level/526fd3043c637ece50001bb2/the_herd_icon.png'
description: "Strike at the weak point in an array of enemies. - by Aftermath"
}
{
name: 'Sword Loop'
difficulty: 2
id: 'sword-loop'
image: '/file/db/level/525dc5589a0765e496000006/drink_me_icon.png'
description: 'Kill the ogres and save the peasants with for-loops. - by <NAME>'
}
{
name: 'Coin Mania'
difficulty: 2
id: 'coin-mania'
image: '/file/db/level/529662dfe0df8f0000000007/grab_the_mushroom_icon.png'
description: 'Learn while-loops to grab coins and potions. - by <NAME>'
}
{
name: 'Bubble Sort Bootcamp Battle'
difficulty: 3
id: 'bubble-sort-bootcamp-battle'
image: '/file/db/level/525ef8ef06e1ab0962000003/commanding_followers_icon.png'
description: "Write a bubble sort to organize your soldiers. - by <NAME>"
}
{
name: 'Ogres of Hanoi'
difficulty: 3
id: 'ogres-of-hanoi'
image: '/file/db/level/526fd3043c637ece50001bb2/the_herd_icon.png'
description: "Transfer a stack of ogres while preserving their honor. - by <NAME>"
}
{
name: 'Danger! Minefield'
difficulty: 3
id: 'danger-minefield'
image: '/file/db/level/526bda3fe79aefde2a003e36/mobile_artillery_icon.png'
description: "Learn how to find prime numbers while defusing mines! - by <NAME>"
}
{
name: 'Find the Spy'
difficulty: 2
id: 'find-the-spy'
image: '/file/db/level/526ae95c1e5cd30000000008/zone_of_danger_icon.png'
description: "Identify the spies hidden among your soldiers - by <NAME>"
}
{
name: 'Harvest Time'
difficulty: 2
id: 'harvest-time'
image: '/file/db/level/529662dfe0df8f0000000007/grab_the_mushroom_icon.png'
description: "Collect a hundred mushrooms in just five lines of code - by <NAME>"
}
]
context.campaigns = [
{id: "beginner", name: "Beginner Campaign", description: "... in which you learn the wizardry of programming.", levels: tutorials}
{id: "multiplayer", name: "Multiplayer Arenas", description: "... in which you code head-to-head against other players.", levels: arenas}
{id: "dev", name: "Random Harder Levels", description: "... in which you learn the interface while doing something a little harder.", levels: experienced}
{id: "player_created", name: "Player-Created", description: "... in which you battle against the creativity of your fellow <a href=\"/contribute#artisan\">Artisan Wizards</a>.", levels: playerCreated}
]
context.levelStatusMap = @levelStatusMap
context
afterRender: ->
super()
@$el.find('.modal').on 'shown.bs.modal', ->
$('input:visible:first', @).focus()
| true | View = require 'views/kinds/RootView'
template = require 'templates/play'
LevelSession = require 'models/LevelSession'
CocoCollection = require 'collections/CocoCollection'
class LevelSessionsCollection extends CocoCollection
url: ''
model: LevelSession
constructor: (model) ->
super()
@url = "/db/user/#{me.id}/level.sessions?project=state.complete,levelID"
module.exports = class PlayView extends View
id: "play-view"
template: template
constructor: (options) ->
super options
@levelStatusMap = {}
@sessions = new LevelSessionsCollection()
@sessions.fetch()
@listenToOnce @sessions, 'sync', @onSessionsLoaded
onSessionsLoaded: (e) ->
for session in @sessions.models
@levelStatusMap[session.get('levelID')] = if session.get('state')?.complete then 'complete' else 'started'
@render()
getRenderData: (context={}) ->
context = super(context)
context.home = true
context.notFound = @getQueryVariable 'not_found'
tutorials = [
{
name: 'Rescue Mission'
difficulty: 1
id: 'rescue-mission'
image: '/file/db/level/52740644904ac0411700067c/rescue_mission_icon.png'
description: "Tharin has been captured!"
}
{
name: 'Grab the Mushroom'
difficulty: 1
id: 'grab-the-mushroom'
image: '/file/db/level/529662dfe0df8f0000000007/grab_the_mushroom_icon.png'
description: "Grab a powerup and smash a big ogre."
}
{
name: 'Drink Me'
difficulty: 1
id: 'drink-me'
image: '/file/db/level/525dc5589a0765e496000006/drink_me_icon.png'
description: "Drink up and slay two munchkins."
}
{
name: 'Taunt the Guards'
difficulty: 1
id: 'taunt-the-guards'
image: '/file/db/level/5276c9bdcf83207a2801ff8f/taunt_icon.png'
description: "Tharin, if clever, can escape with Phoebe."
}
{
name: "It's a Trap"
difficulty: 1
id: 'its-a-trap'
image: '/file/db/level/528aea2d7f37fc4e0700016b/its_a_trap_icon.png'
description: "Organize a dungeon ambush with archers."
}
{
name: 'Break the Prison'
difficulty: 1
id: 'break-the-prison'
image: '/file/db/level/5275272c69abdcb12401216e/break_the_prison_icon.png'
description: "More comrades are imprisoned!"
}
{
name: 'Taunt'
difficulty: 1
id: 'taunt'
image: '/file/db/level/525f150306e1ab0962000018/taunt_icon.png'
description: "Taunt the ogre to claim victory."
}
{
name: 'Cowardly Taunt'
difficulty: 1
id: 'cowardly-taunt'
image: '/file/db/level/525abfd9b12777d78e000009/cowardly_taunt_icon.png'
description: "Lure infuriated ogres to their doom."
}
{
name: 'Commanding Followers'
difficulty: 1
id: 'commanding-followers'
image: '/file/db/level/525ef8ef06e1ab0962000003/commanding_followers_icon.png'
description: "Lead allied soldiers into battle."
}
{
name: 'Mobile PI:NAME:<NAME>END_PI'
difficulty: 1
id: 'mobile-artillery'
image: '/file/db/level/525085419851b83f4b000001/mobile_artillery_icon.png'
description: "Blow ogres up!"
}
]
experienced = [
{
name: 'PI:NAME:<NAME>END_PI'
difficulty: 2
id: 'hunter-triplets'
image: '/file/db/level/526711d9add4f8965f000002/hunter_triplets_icon.png'
description: "Three soldiers go ogre hunting."
}
{
name: 'Emphasis on Aim'
difficulty: 2
id: 'emphasis-on-aim'
image: '/file/db/level/525f384d96cd77000000000f/munchkin_masher_icon.png'
description: "Chose your targets carefully."
}
{
name: 'Zone of DPI:NAME:<NAME>END_PI'
difficulty: 3
id: 'zone-of-danger'
image: '/file/db/level/526ae95c1e5cd30000000008/zone_of_danger_icon.png'
description: "Target the ogres swarming into arrow range."
}
{
name: 'PI:NAME:<NAME>END_PI'
difficulty: 2
id: 'molotov-medic'
image: '/file/db/level/52602ecb026e8481e7000001/generic_1.png'
description: "Tharin must play support in this dungeon battle."
}
{
name: 'PI:NAME:<NAME>END_PI'
difficulty: 5
id: 'gridmancer'
image: '/file/db/level/52ae2460ef42c52f13000008/gridmancer_icon.png'
description: "Super algorithm challenge level!"
}
]
arenas = [
{
name: 'PI:NAME:<NAME>END_PI'
difficulty: 4
id: 'greed'
image: '/file/db/level/526fd3043c637ece50001bb2/the_herd_icon.png'
description: "Liked Dungeon Arena and Gold Rush? Put them together in this economic arena!"
levelPath: 'ladder'
}
{
name: 'Dungeon Arena'
difficulty: 3
id: 'dungeon-arena'
image: '/file/db/level/526ae95c1e5cd30000000008/zone_of_danger_icon.png'
description: "Play head-to-head against fellow Wizards in a dungeon melee!"
levelPath: 'ladder'
}
{
name: 'PI:NAME:<NAME>END_PI'
difficulty: 3
id: 'gold-rush'
image: '/file/db/level/52602ecb026e8481e7000001/generic_1.png'
description: "Prove you are better at collecting gold than your opponent!"
levelPath: 'ladder'
}
{
name: 'PI:NAME:<NAME>END_PI'
difficulty: 4
id: 'brawlwood'
image: '/file/db/level/525ef8ef06e1ab0962000003/commanding_followers_icon.png'
description: "Combat the armies of other Wizards in a strategic forest arena! (Fast computer required.)"
levelPath: 'ladder'
}
]
playerCreated = [
{
name: 'Extra Extrapolation'
difficulty: 2
id: 'extra-extrapolation'
image: '/file/db/level/526bda3fe79aefde2a003e36/mobile_artillery_icon.png'
description: "Predict your target's position for deadly aim. - by Sootn"
}
{
name: 'The Right Route'
difficulty: 1
id: 'the-right-route'
image: '/file/db/level/526fd3043c637ece50001bb2/the_herd_icon.png'
description: "Strike at the weak point in an array of enemies. - by Aftermath"
}
{
name: 'Sword Loop'
difficulty: 2
id: 'sword-loop'
image: '/file/db/level/525dc5589a0765e496000006/drink_me_icon.png'
description: 'Kill the ogres and save the peasants with for-loops. - by PI:NAME:<NAME>END_PI'
}
{
name: 'Coin Mania'
difficulty: 2
id: 'coin-mania'
image: '/file/db/level/529662dfe0df8f0000000007/grab_the_mushroom_icon.png'
description: 'Learn while-loops to grab coins and potions. - by PI:NAME:<NAME>END_PI'
}
{
name: 'Bubble Sort Bootcamp Battle'
difficulty: 3
id: 'bubble-sort-bootcamp-battle'
image: '/file/db/level/525ef8ef06e1ab0962000003/commanding_followers_icon.png'
description: "Write a bubble sort to organize your soldiers. - by PI:NAME:<NAME>END_PI"
}
{
name: 'Ogres of Hanoi'
difficulty: 3
id: 'ogres-of-hanoi'
image: '/file/db/level/526fd3043c637ece50001bb2/the_herd_icon.png'
description: "Transfer a stack of ogres while preserving their honor. - by PI:NAME:<NAME>END_PI"
}
{
name: 'Danger! Minefield'
difficulty: 3
id: 'danger-minefield'
image: '/file/db/level/526bda3fe79aefde2a003e36/mobile_artillery_icon.png'
description: "Learn how to find prime numbers while defusing mines! - by PI:NAME:<NAME>END_PI"
}
{
name: 'Find the Spy'
difficulty: 2
id: 'find-the-spy'
image: '/file/db/level/526ae95c1e5cd30000000008/zone_of_danger_icon.png'
description: "Identify the spies hidden among your soldiers - by PI:NAME:<NAME>END_PI"
}
{
name: 'Harvest Time'
difficulty: 2
id: 'harvest-time'
image: '/file/db/level/529662dfe0df8f0000000007/grab_the_mushroom_icon.png'
description: "Collect a hundred mushrooms in just five lines of code - by PI:NAME:<NAME>END_PI"
}
]
context.campaigns = [
{id: "beginner", name: "Beginner Campaign", description: "... in which you learn the wizardry of programming.", levels: tutorials}
{id: "multiplayer", name: "Multiplayer Arenas", description: "... in which you code head-to-head against other players.", levels: arenas}
{id: "dev", name: "Random Harder Levels", description: "... in which you learn the interface while doing something a little harder.", levels: experienced}
{id: "player_created", name: "Player-Created", description: "... in which you battle against the creativity of your fellow <a href=\"/contribute#artisan\">Artisan Wizards</a>.", levels: playerCreated}
]
context.levelStatusMap = @levelStatusMap
context
afterRender: ->
super()
@$el.find('.modal').on 'shown.bs.modal', ->
$('input:visible:first', @).focus()
|
[
{
"context": "', ($log) ->\n defaultUser = -> { displayName: 'Anonymous Curator', username: 'curator' }\n security =\n ",
"end": 208,
"score": 0.38701075315475464,
"start": 199,
"tag": "NAME",
"value": "Anonymous"
},
{
"context": " ->\n defaultUser = -> { displayName: 'Anon... | ModelCatalogueCorePlugin/grails-app/assets/javascripts/modelcatalogue/util/security.coffee | OxBRCInformatics/NHICModelCatalogue | 1 | angular.module('mc.util.security', ['http-auth-interceptor', 'mc.util.messages', 'ui.router']).provider('security', [ ->
noSecurityFactory = ['$log', ($log) ->
defaultUser = -> { displayName: 'Anonymous Curator', username: 'curator' }
security =
isUserLoggedIn: -> true
getCurrentUser: defaultUser
hasRole: -> true
hasRole: -> true
login: (username, password, rememberMe = false) -> security.getCurrentUser()
logout: -> $log.info "Logout requested on default security service"
refreshUserData: defaultUser
mock: true
]
readOnlySecurityFactory = ['$log', ($log) ->
defaultUser = -> { displayName: 'Anonymous Viewer', username: 'viewer' }
security =
isUserLoggedIn: -> true
getCurrentUser: defaultUser
hasRole: (role) -> role == 'VIEWER'
login: (username, password, rememberMe = false) -> security.getCurrentUser()
logout: -> $log.info "Logout requested on read only security service"
refreshUserData: defaultUser
mock: true
]
securityFactory = noSecurityFactory
securityProvider = {}
securityProvider.readOnly = ->
securityFactory = readOnlySecurityFactory
securityProvider.noSecurity = ->
securityFactory = noSecurityFactory
# you need login to return
securityProvider.springSecurity = (config = {}) ->
securityFactory = ['$http', '$rootScope', '$q', '$state', ($http, $rootScope, $q, $state) ->
httpMethod = config.httpMethod ? 'POST'
loginUrl = 'j_spring_security_check'
logoutUrl = 'logout'
userUrl = 'user/current'
changePasswordUrl = 'register/changePassword'
forgotPasswordUrl = 'register/forgotPassword'
registerUrl ='register/register'
usernameParam = config.username ? 'j_username'
passwordParam = config.password ? 'j_password'
rememberParam = config.rememberMe ? '_spring_security_remember_me'
if config.userUrl
userUrl = config.userUrl
else if config.contextPath
userUrl = "#{config.contextPath}/#{userUrl}"
if config.loginUrl
loginUrl = config.loginUrl
else if config.contextPath
loginUrl = "#{config.contextPath}/#{loginUrl}"
if config.logoutUrl
logoutUrl = config.logoutUrl
else if config.contextPath
logoutUrl = "#{config.contextPath}/#{logoutUrl}"
currentUser = config.currentUser
handleUserResponse = (result) ->
return result if not result.data.username
if result.data.success
currentUser = result.data
currentUser.displayName ?= currentUser.username
currentUser.roles ?= []
currentUser.classifications ?= []
for roleName, roleSynonyms of (config.roles ? [])
for role in roleSynonyms
if role in currentUser.roles
currentUser.roles.push roleName
else
currentUser = null
result
security =
oauthProviders: config.oauthProviders
allowRegistration: config.allowRegistration
canResetPassword: config.canResetPassword
contextPath: config.contextPath
isUserLoggedIn: ->
currentUser?
getCurrentUser: ->
currentUser
hasRole: (role) ->
return false if not currentUser?.roles
return role in currentUser.roles
login: (username, password, rememberMe = false) ->
params = {ajax: true}
params[usernameParam] = username
params[passwordParam] = password
if rememberMe
params[rememberParam] = 'on'
$http(
method: httpMethod,
url: loginUrl
params: params
).then handleUserResponse
logout: ->
$http(method: httpMethod, url: logoutUrl).then ->
currentUser = null
$state.go 'dashboard'
changePassword: (user)->
params = {oldPassword:user.oldPassword,password:user.password, password2:user.password2}
$http(
method: httpMethod,
url: changePasswordUrl
data: params
).then (result) ->
result
forgotPassword: (username,email)->
params = {username:username,email:email}
$http(
method: httpMethod,
url: forgotPasswordUrl,
data: params
).then (result) ->
result
register: (user)->
params =
password: user.password
password2:user.password2
username:user.username
email: user.email
firstName:user.firstName
lastName:user.lastName
$http(
method: httpMethod,
url: registerUrl
data: params
).then (result) ->
result
requireUser: ->
$http(method: 'GET', url: userUrl).then(handleUserResponse).then (result)->
if result.data?.success
return security.getCurrentUser()
$q.reject result
requireRole: (role) ->
security.requireUser().then ->
if security.hasRole(role)
return security.getCurrentUser()
$q.reject security.getCurrentUser()
refreshUserData: ->
currentUserPromise = $http(method: 'GET', url: userUrl)
currentUserPromise.then(handleUserResponse).then ->
if currentUser
$rootScope.$broadcast 'userLoggedIn', currentUser
return currentUser
return currentUserPromise
if currentUser
currentUser.success = true
handleUserResponse data: currentUser
else
security.refreshUserData()
return security
]
securityProvider.setup = (factory) ->
securityFactory = factory
# factory method
securityProvider.$get = [ '$injector', '$rootScope', '$q', '$log', ($injector, $rootScope, $q, $log) ->
if securityFactory == noSecurityFactory
$log.warn "You are using default security service. You should consider setting up more advanced one."
security = $injector.invoke securityFactory
throw new Error("Security service must not provide requireLogin() method. Factory: #{angular.toJson(securityFactory)}") if angular.isFunction(security.requireLogin)
throw new Error("Security service must provide isUserLoggedIn() method. Factory: #{angular.toJson(securityFactory)}") if not angular.isFunction(security.isUserLoggedIn)
throw new Error("Security service must provide getCurrentUser() method. Factory: #{angular.toJson(securityFactory)}") if not angular.isFunction(security.getCurrentUser)
throw new Error("Security service must provide hasRole(role) method. Factory: #{angular.toJson(securityFactory)}") if not angular.isFunction(security.hasRole)
throw new Error("Security service must provide login(username, password, rememberMe) method. Factory: #{angular.toJson(securityFactory)}") if not angular.isFunction(security.login)
throw new Error("Security service must provide logout() method. Factory: #{angular.toJson(securityFactory)}") if not angular.isFunction(security.logout)
# add event broadcast on login and logout
loginFn = security.login
security.login = (username, password, rememberMe) ->
$q.when(loginFn(username, password, rememberMe)).then (user) ->
if not user.errors
if user.username
$rootScope.$broadcast 'userLoggedIn', user
return user
else if angular.isFunction(security.refreshUserData)
security.refreshUserData()
return user
else
$log.warn "got wrong user object and don't know how to handle it", user
return $q.reject user
else
$log.warn "login finished with errors", user.errors
return $q.reject user
logoutFn = security.logout
security.logout = ->
oldUser = security.getCurrentUser()
$q.when(logoutFn()).then ->
$rootScope.$broadcast 'userLoggedOut', oldUser
security.requireLogin = ->
$rootScope.$broadcast 'event:auth-loginRequired'
security
]
securityProvider
]).run ['security', '$rootScope', 'messages', 'authService', '$state', (security, $rootScope, messages, authService, $state) ->
# installs the security listeners
loginShown = false
$rootScope.$on 'event:auth-loginRequired', ->
if security.mock
messages.error('You are trying to access protected resource',
'The application will not work as expected. Please, set up the security properly.').noTimeout()
else
return if loginShown
loginShown = true
messages.prompt('Login', null, type: 'login').then (success)->
loginShown = false
authService.loginConfirmed(success)
messages.clearAllMessages()
, ->
loginShown = false
messages.warning('You are trying to access protected resource', if security.isUserLoggedIn() then 'Please, sign in as different user' else 'Please, sign in').noTimeout()
$state.go 'dashboard'
$rootScope.$security = security
] | 44810 | angular.module('mc.util.security', ['http-auth-interceptor', 'mc.util.messages', 'ui.router']).provider('security', [ ->
noSecurityFactory = ['$log', ($log) ->
defaultUser = -> { displayName: '<NAME> Cur<NAME>', username: 'curator' }
security =
isUserLoggedIn: -> true
getCurrentUser: defaultUser
hasRole: -> true
hasRole: -> true
login: (username, password, rememberMe = false) -> security.getCurrentUser()
logout: -> $log.info "Logout requested on default security service"
refreshUserData: defaultUser
mock: true
]
readOnlySecurityFactory = ['$log', ($log) ->
defaultUser = -> { displayName: 'Anonymous Viewer', username: 'viewer' }
security =
isUserLoggedIn: -> true
getCurrentUser: defaultUser
hasRole: (role) -> role == 'VIEWER'
login: (username, password, rememberMe = false) -> security.getCurrentUser()
logout: -> $log.info "Logout requested on read only security service"
refreshUserData: defaultUser
mock: true
]
securityFactory = noSecurityFactory
securityProvider = {}
securityProvider.readOnly = ->
securityFactory = readOnlySecurityFactory
securityProvider.noSecurity = ->
securityFactory = noSecurityFactory
# you need login to return
securityProvider.springSecurity = (config = {}) ->
securityFactory = ['$http', '$rootScope', '$q', '$state', ($http, $rootScope, $q, $state) ->
httpMethod = config.httpMethod ? 'POST'
loginUrl = 'j_spring_security_check'
logoutUrl = 'logout'
userUrl = 'user/current'
changePasswordUrl = 'register/changePassword'
forgotPasswordUrl = 'register/forgotPassword'
registerUrl ='register/register'
usernameParam = config.username ? 'j_username'
passwordParam = config.password ? '<PASSWORD>'
rememberParam = config.rememberMe ? '_spring_security_remember_me'
if config.userUrl
userUrl = config.userUrl
else if config.contextPath
userUrl = "#{config.contextPath}/#{userUrl}"
if config.loginUrl
loginUrl = config.loginUrl
else if config.contextPath
loginUrl = "#{config.contextPath}/#{loginUrl}"
if config.logoutUrl
logoutUrl = config.logoutUrl
else if config.contextPath
logoutUrl = "#{config.contextPath}/#{logoutUrl}"
currentUser = config.currentUser
handleUserResponse = (result) ->
return result if not result.data.username
if result.data.success
currentUser = result.data
currentUser.displayName ?= currentUser.username
currentUser.roles ?= []
currentUser.classifications ?= []
for roleName, roleSynonyms of (config.roles ? [])
for role in roleSynonyms
if role in currentUser.roles
currentUser.roles.push roleName
else
currentUser = null
result
security =
oauthProviders: config.oauthProviders
allowRegistration: config.allowRegistration
canResetPassword: config.canResetPassword
contextPath: config.contextPath
isUserLoggedIn: ->
currentUser?
getCurrentUser: ->
currentUser
hasRole: (role) ->
return false if not currentUser?.roles
return role in currentUser.roles
login: (username, password, rememberMe = false) ->
params = {ajax: true}
params[usernameParam] = username
params[passwordParam] = <PASSWORD>
if rememberMe
params[rememberParam] = 'on'
$http(
method: httpMethod,
url: loginUrl
params: params
).then handleUserResponse
logout: ->
$http(method: httpMethod, url: logoutUrl).then ->
currentUser = null
$state.go 'dashboard'
changePassword: (user)->
params = {oldPassword:<PASSWORD>,password:<PASSWORD>, password2:<PASSWORD>}
$http(
method: httpMethod,
url: changePasswordUrl
data: params
).then (result) ->
result
forgotPassword: (username,email)->
params = {username:username,email:email}
$http(
method: httpMethod,
url: forgotPasswordUrl,
data: params
).then (result) ->
result
register: (user)->
params =
password: <PASSWORD>
password2:<PASSWORD>
username:user.username
email: user.email
firstName:user.firstName
lastName:user.lastName
$http(
method: httpMethod,
url: registerUrl
data: params
).then (result) ->
result
requireUser: ->
$http(method: 'GET', url: userUrl).then(handleUserResponse).then (result)->
if result.data?.success
return security.getCurrentUser()
$q.reject result
requireRole: (role) ->
security.requireUser().then ->
if security.hasRole(role)
return security.getCurrentUser()
$q.reject security.getCurrentUser()
refreshUserData: ->
currentUserPromise = $http(method: 'GET', url: userUrl)
currentUserPromise.then(handleUserResponse).then ->
if currentUser
$rootScope.$broadcast 'userLoggedIn', currentUser
return currentUser
return currentUserPromise
if currentUser
currentUser.success = true
handleUserResponse data: currentUser
else
security.refreshUserData()
return security
]
securityProvider.setup = (factory) ->
securityFactory = factory
# factory method
securityProvider.$get = [ '$injector', '$rootScope', '$q', '$log', ($injector, $rootScope, $q, $log) ->
if securityFactory == noSecurityFactory
$log.warn "You are using default security service. You should consider setting up more advanced one."
security = $injector.invoke securityFactory
throw new Error("Security service must not provide requireLogin() method. Factory: #{angular.toJson(securityFactory)}") if angular.isFunction(security.requireLogin)
throw new Error("Security service must provide isUserLoggedIn() method. Factory: #{angular.toJson(securityFactory)}") if not angular.isFunction(security.isUserLoggedIn)
throw new Error("Security service must provide getCurrentUser() method. Factory: #{angular.toJson(securityFactory)}") if not angular.isFunction(security.getCurrentUser)
throw new Error("Security service must provide hasRole(role) method. Factory: #{angular.toJson(securityFactory)}") if not angular.isFunction(security.hasRole)
throw new Error("Security service must provide login(username, password, rememberMe) method. Factory: #{angular.toJson(securityFactory)}") if not angular.isFunction(security.login)
throw new Error("Security service must provide logout() method. Factory: #{angular.toJson(securityFactory)}") if not angular.isFunction(security.logout)
# add event broadcast on login and logout
loginFn = security.login
security.login = (username, password, rememberMe) ->
$q.when(loginFn(username, password, rememberMe)).then (user) ->
if not user.errors
if user.username
$rootScope.$broadcast 'userLoggedIn', user
return user
else if angular.isFunction(security.refreshUserData)
security.refreshUserData()
return user
else
$log.warn "got wrong user object and don't know how to handle it", user
return $q.reject user
else
$log.warn "login finished with errors", user.errors
return $q.reject user
logoutFn = security.logout
security.logout = ->
oldUser = security.getCurrentUser()
$q.when(logoutFn()).then ->
$rootScope.$broadcast 'userLoggedOut', oldUser
security.requireLogin = ->
$rootScope.$broadcast 'event:auth-loginRequired'
security
]
securityProvider
]).run ['security', '$rootScope', 'messages', 'authService', '$state', (security, $rootScope, messages, authService, $state) ->
# installs the security listeners
loginShown = false
$rootScope.$on 'event:auth-loginRequired', ->
if security.mock
messages.error('You are trying to access protected resource',
'The application will not work as expected. Please, set up the security properly.').noTimeout()
else
return if loginShown
loginShown = true
messages.prompt('Login', null, type: 'login').then (success)->
loginShown = false
authService.loginConfirmed(success)
messages.clearAllMessages()
, ->
loginShown = false
messages.warning('You are trying to access protected resource', if security.isUserLoggedIn() then 'Please, sign in as different user' else 'Please, sign in').noTimeout()
$state.go 'dashboard'
$rootScope.$security = security
] | true | angular.module('mc.util.security', ['http-auth-interceptor', 'mc.util.messages', 'ui.router']).provider('security', [ ->
noSecurityFactory = ['$log', ($log) ->
defaultUser = -> { displayName: 'PI:NAME:<NAME>END_PI CurPI:NAME:<NAME>END_PI', username: 'curator' }
security =
isUserLoggedIn: -> true
getCurrentUser: defaultUser
hasRole: -> true
hasRole: -> true
login: (username, password, rememberMe = false) -> security.getCurrentUser()
logout: -> $log.info "Logout requested on default security service"
refreshUserData: defaultUser
mock: true
]
readOnlySecurityFactory = ['$log', ($log) ->
defaultUser = -> { displayName: 'Anonymous Viewer', username: 'viewer' }
security =
isUserLoggedIn: -> true
getCurrentUser: defaultUser
hasRole: (role) -> role == 'VIEWER'
login: (username, password, rememberMe = false) -> security.getCurrentUser()
logout: -> $log.info "Logout requested on read only security service"
refreshUserData: defaultUser
mock: true
]
securityFactory = noSecurityFactory
securityProvider = {}
securityProvider.readOnly = ->
securityFactory = readOnlySecurityFactory
securityProvider.noSecurity = ->
securityFactory = noSecurityFactory
# you need login to return
securityProvider.springSecurity = (config = {}) ->
securityFactory = ['$http', '$rootScope', '$q', '$state', ($http, $rootScope, $q, $state) ->
httpMethod = config.httpMethod ? 'POST'
loginUrl = 'j_spring_security_check'
logoutUrl = 'logout'
userUrl = 'user/current'
changePasswordUrl = 'register/changePassword'
forgotPasswordUrl = 'register/forgotPassword'
registerUrl ='register/register'
usernameParam = config.username ? 'j_username'
passwordParam = config.password ? 'PI:PASSWORD:<PASSWORD>END_PI'
rememberParam = config.rememberMe ? '_spring_security_remember_me'
if config.userUrl
userUrl = config.userUrl
else if config.contextPath
userUrl = "#{config.contextPath}/#{userUrl}"
if config.loginUrl
loginUrl = config.loginUrl
else if config.contextPath
loginUrl = "#{config.contextPath}/#{loginUrl}"
if config.logoutUrl
logoutUrl = config.logoutUrl
else if config.contextPath
logoutUrl = "#{config.contextPath}/#{logoutUrl}"
currentUser = config.currentUser
handleUserResponse = (result) ->
return result if not result.data.username
if result.data.success
currentUser = result.data
currentUser.displayName ?= currentUser.username
currentUser.roles ?= []
currentUser.classifications ?= []
for roleName, roleSynonyms of (config.roles ? [])
for role in roleSynonyms
if role in currentUser.roles
currentUser.roles.push roleName
else
currentUser = null
result
security =
oauthProviders: config.oauthProviders
allowRegistration: config.allowRegistration
canResetPassword: config.canResetPassword
contextPath: config.contextPath
isUserLoggedIn: ->
currentUser?
getCurrentUser: ->
currentUser
hasRole: (role) ->
return false if not currentUser?.roles
return role in currentUser.roles
login: (username, password, rememberMe = false) ->
params = {ajax: true}
params[usernameParam] = username
params[passwordParam] = PI:PASSWORD:<PASSWORD>END_PI
if rememberMe
params[rememberParam] = 'on'
$http(
method: httpMethod,
url: loginUrl
params: params
).then handleUserResponse
logout: ->
$http(method: httpMethod, url: logoutUrl).then ->
currentUser = null
$state.go 'dashboard'
changePassword: (user)->
params = {oldPassword:PI:PASSWORD:<PASSWORD>END_PI,password:PI:PASSWORD:<PASSWORD>END_PI, password2:PI:PASSWORD:<PASSWORD>END_PI}
$http(
method: httpMethod,
url: changePasswordUrl
data: params
).then (result) ->
result
forgotPassword: (username,email)->
params = {username:username,email:email}
$http(
method: httpMethod,
url: forgotPasswordUrl,
data: params
).then (result) ->
result
register: (user)->
params =
password: PI:PASSWORD:<PASSWORD>END_PI
password2:PI:PASSWORD:<PASSWORD>END_PI
username:user.username
email: user.email
firstName:user.firstName
lastName:user.lastName
$http(
method: httpMethod,
url: registerUrl
data: params
).then (result) ->
result
requireUser: ->
$http(method: 'GET', url: userUrl).then(handleUserResponse).then (result)->
if result.data?.success
return security.getCurrentUser()
$q.reject result
requireRole: (role) ->
security.requireUser().then ->
if security.hasRole(role)
return security.getCurrentUser()
$q.reject security.getCurrentUser()
refreshUserData: ->
currentUserPromise = $http(method: 'GET', url: userUrl)
currentUserPromise.then(handleUserResponse).then ->
if currentUser
$rootScope.$broadcast 'userLoggedIn', currentUser
return currentUser
return currentUserPromise
if currentUser
currentUser.success = true
handleUserResponse data: currentUser
else
security.refreshUserData()
return security
]
securityProvider.setup = (factory) ->
securityFactory = factory
# factory method
securityProvider.$get = [ '$injector', '$rootScope', '$q', '$log', ($injector, $rootScope, $q, $log) ->
if securityFactory == noSecurityFactory
$log.warn "You are using default security service. You should consider setting up more advanced one."
security = $injector.invoke securityFactory
throw new Error("Security service must not provide requireLogin() method. Factory: #{angular.toJson(securityFactory)}") if angular.isFunction(security.requireLogin)
throw new Error("Security service must provide isUserLoggedIn() method. Factory: #{angular.toJson(securityFactory)}") if not angular.isFunction(security.isUserLoggedIn)
throw new Error("Security service must provide getCurrentUser() method. Factory: #{angular.toJson(securityFactory)}") if not angular.isFunction(security.getCurrentUser)
throw new Error("Security service must provide hasRole(role) method. Factory: #{angular.toJson(securityFactory)}") if not angular.isFunction(security.hasRole)
throw new Error("Security service must provide login(username, password, rememberMe) method. Factory: #{angular.toJson(securityFactory)}") if not angular.isFunction(security.login)
throw new Error("Security service must provide logout() method. Factory: #{angular.toJson(securityFactory)}") if not angular.isFunction(security.logout)
# add event broadcast on login and logout
loginFn = security.login
security.login = (username, password, rememberMe) ->
$q.when(loginFn(username, password, rememberMe)).then (user) ->
if not user.errors
if user.username
$rootScope.$broadcast 'userLoggedIn', user
return user
else if angular.isFunction(security.refreshUserData)
security.refreshUserData()
return user
else
$log.warn "got wrong user object and don't know how to handle it", user
return $q.reject user
else
$log.warn "login finished with errors", user.errors
return $q.reject user
logoutFn = security.logout
security.logout = ->
oldUser = security.getCurrentUser()
$q.when(logoutFn()).then ->
$rootScope.$broadcast 'userLoggedOut', oldUser
security.requireLogin = ->
$rootScope.$broadcast 'event:auth-loginRequired'
security
]
securityProvider
]).run ['security', '$rootScope', 'messages', 'authService', '$state', (security, $rootScope, messages, authService, $state) ->
# installs the security listeners
loginShown = false
$rootScope.$on 'event:auth-loginRequired', ->
if security.mock
messages.error('You are trying to access protected resource',
'The application will not work as expected. Please, set up the security properly.').noTimeout()
else
return if loginShown
loginShown = true
messages.prompt('Login', null, type: 'login').then (success)->
loginShown = false
authService.loginConfirmed(success)
messages.clearAllMessages()
, ->
loginShown = false
messages.warning('You are trying to access protected resource', if security.isUserLoggedIn() then 'Please, sign in as different user' else 'Please, sign in').noTimeout()
$state.go 'dashboard'
$rootScope.$security = security
] |
[
{
"context": "mail and usenet posts. It was developed in 2004\nby John Gruber and adapted in a lot of projects and languages. S",
"end": 4052,
"score": 0.9998529553413391,
"start": 4041,
"tag": "NAME",
"value": "John Gruber"
}
] | src/api/index.coffee | alinex/node-report | 1 | ###
Elements
=====================================================
This is a documentation of all possible elements and how far they are supported
in the different input and output formats.

Not all of them are currently fully supported, but see below.
Builder API
------------------------------------------------------
This follows a common schema with most methods are available with its full name
and a short name. Block elements can be called completely with all data or with a
boolean value to open and close it separately.
As far as possible the API won't throw errors but interpret all calls like you maybe
wanted them using auto closing tags.
###
fs = require 'fs'
list = fs.readdirSync __dirname
.filter (e) -> not e.match /^index\./
.filter (e) -> e.match /\.(coffee|js)$/
require "#{__dirname}/#{file}" for file in list
###
Input Formats
------------------------------------------------------
Beside using the programmable API some other file formats may be used. They will
be parsed, but not every format can handle all elements. The main format is markdown
but you may also use one of the others. You also may mix the parsing formats and
place them into API calls.
But only markdown can at the moment be used to store and reread data without loss
of information. The concrete implementation is based on the standards but contains
some significant changes, too.C
__Support for Parsing__
| Element | API | MD | HTML | ADOC |
|:---------- |:---:|:----:|:----:|:----:|
| Text | X | X | | |
| Heading | X | X | | |
| Paragraph | X | X | | |
| Preformat | X | X | | |
| Code | X | X | | |
| Blockquote | X | X | | |
| ThemeBreak | X | X | | |
| List | X | X | | |
| Fixed | X | X | | |
| Emphasis | X | X | | |
| HTML | | X | | |
| Box | | | | |
| Style | | | | |
| ToC | | | | |
| Execute | | | | |
^`X` -> supported; `-` -> not possible; `(X)` -> partly supported;
empty -> not currently done^
Output Formats
------------------------------------------------------
But not every format can handle all elements. The markdown format is the only one
which can be used to store the report without loosing anything.
Each of the formats support different options you may set by configuration or on call
(see the {@link ../configSchema.coffee}).
| Element | MD | Text | HTML | ROFF | ADOC | LaTeX | RTF |
|:---------- |:---:|:----:|:----:|:----:|:----:|:-----:|:---:|
| Text | X | X | X | X | | X | X |
| Paragraph | X | X | X | X | | | |
| Heading | X | X | X | X | | | |
| Preformat | X | | | X | | | |
| Blockquote | X | | | | | | |
| ThemaBreak | X | X | X | X | | | |
| CharStyle | X | (X) | X | X | | | |
| List | X | X | X | | | | |
| HTML | X | | | | | | |
| Box | | | | | | | |
| Style | | | | | | | |
| ToC | | | | | | | |
| Execute | | | | | | | |
^`X` -> supported; `-` -> not possible; `(X)` -> partly supported;
empty -> not currently done^
Markdown
------------------------------------------------------
The **markdown** format is the base format of the report package and the most
powerful of all. It allows complete output without loss of information.
Markdown is a plain text format for writing structured documents, based on conventions
used for indicating formatting in email and usenet posts. It was developed in 2004
by John Gruber and adapted in a lot of projects and languages. Some of them extended
the original syntax with conventions for more elements. It is also used in different
web applications like GitHub, StackOverflow, Trello and more.
In contrast to other formats like AsciDoc it is more readable and easier to write.
The markdown parser is basically build to support the following specifications:
- [Daring Fireball](https://daringfireball.net/projects/markdown/)
- [CommonMark Specification](http://spec.commonmark.org/0.27/)
- [GitHub Flavored Markdown](https://help.github.com/categories/writing-on-github/)
See the elements itself of how much it is extended or optimized to this standards.
Also there are some more elements added like:
- ????
The output is based on the parser standards but may be optimized using the configuration
settings. But if you combine this with the parser you will often not get the exact same
output which was parsed earlier. But you will get an optimized version which contains
the exact same information.
All elements are divided into block level or inline elements and may or not may contain
further markdown. Read more about this in each element.
This is extended to also support GFM styles like:
- [Tables](https://help.github.com/articles/organizing-information-with-tables/)
- [TaskLists](https://help.github.com/articles/basic-writing-and-formatting-syntax/#task-lists)
- mentioning (maybe using linkify)
- emoji
HTML Output
---------------------------------------------
Like in all other formats you may specify the output by configuration.
The generated tags will be xhtml compliant and properly nested. But included raw
code may not follow these guidelines.
###
| 143210 | ###
Elements
=====================================================
This is a documentation of all possible elements and how far they are supported
in the different input and output formats.

Not all of them are currently fully supported, but see below.
Builder API
------------------------------------------------------
This follows a common schema with most methods are available with its full name
and a short name. Block elements can be called completely with all data or with a
boolean value to open and close it separately.
As far as possible the API won't throw errors but interpret all calls like you maybe
wanted them using auto closing tags.
###
fs = require 'fs'
list = fs.readdirSync __dirname
.filter (e) -> not e.match /^index\./
.filter (e) -> e.match /\.(coffee|js)$/
require "#{__dirname}/#{file}" for file in list
###
Input Formats
------------------------------------------------------
Beside using the programmable API some other file formats may be used. They will
be parsed, but not every format can handle all elements. The main format is markdown
but you may also use one of the others. You also may mix the parsing formats and
place them into API calls.
But only markdown can at the moment be used to store and reread data without loss
of information. The concrete implementation is based on the standards but contains
some significant changes, too.C
__Support for Parsing__
| Element | API | MD | HTML | ADOC |
|:---------- |:---:|:----:|:----:|:----:|
| Text | X | X | | |
| Heading | X | X | | |
| Paragraph | X | X | | |
| Preformat | X | X | | |
| Code | X | X | | |
| Blockquote | X | X | | |
| ThemeBreak | X | X | | |
| List | X | X | | |
| Fixed | X | X | | |
| Emphasis | X | X | | |
| HTML | | X | | |
| Box | | | | |
| Style | | | | |
| ToC | | | | |
| Execute | | | | |
^`X` -> supported; `-` -> not possible; `(X)` -> partly supported;
empty -> not currently done^
Output Formats
------------------------------------------------------
But not every format can handle all elements. The markdown format is the only one
which can be used to store the report without loosing anything.
Each of the formats support different options you may set by configuration or on call
(see the {@link ../configSchema.coffee}).
| Element | MD | Text | HTML | ROFF | ADOC | LaTeX | RTF |
|:---------- |:---:|:----:|:----:|:----:|:----:|:-----:|:---:|
| Text | X | X | X | X | | X | X |
| Paragraph | X | X | X | X | | | |
| Heading | X | X | X | X | | | |
| Preformat | X | | | X | | | |
| Blockquote | X | | | | | | |
| ThemaBreak | X | X | X | X | | | |
| CharStyle | X | (X) | X | X | | | |
| List | X | X | X | | | | |
| HTML | X | | | | | | |
| Box | | | | | | | |
| Style | | | | | | | |
| ToC | | | | | | | |
| Execute | | | | | | | |
^`X` -> supported; `-` -> not possible; `(X)` -> partly supported;
empty -> not currently done^
Markdown
------------------------------------------------------
The **markdown** format is the base format of the report package and the most
powerful of all. It allows complete output without loss of information.
Markdown is a plain text format for writing structured documents, based on conventions
used for indicating formatting in email and usenet posts. It was developed in 2004
by <NAME> and adapted in a lot of projects and languages. Some of them extended
the original syntax with conventions for more elements. It is also used in different
web applications like GitHub, StackOverflow, Trello and more.
In contrast to other formats like AsciDoc it is more readable and easier to write.
The markdown parser is basically build to support the following specifications:
- [Daring Fireball](https://daringfireball.net/projects/markdown/)
- [CommonMark Specification](http://spec.commonmark.org/0.27/)
- [GitHub Flavored Markdown](https://help.github.com/categories/writing-on-github/)
See the elements itself of how much it is extended or optimized to this standards.
Also there are some more elements added like:
- ????
The output is based on the parser standards but may be optimized using the configuration
settings. But if you combine this with the parser you will often not get the exact same
output which was parsed earlier. But you will get an optimized version which contains
the exact same information.
All elements are divided into block level or inline elements and may or not may contain
further markdown. Read more about this in each element.
This is extended to also support GFM styles like:
- [Tables](https://help.github.com/articles/organizing-information-with-tables/)
- [TaskLists](https://help.github.com/articles/basic-writing-and-formatting-syntax/#task-lists)
- mentioning (maybe using linkify)
- emoji
HTML Output
---------------------------------------------
Like in all other formats you may specify the output by configuration.
The generated tags will be xhtml compliant and properly nested. But included raw
code may not follow these guidelines.
###
| true | ###
Elements
=====================================================
This is a documentation of all possible elements and how far they are supported
in the different input and output formats.

Not all of them are currently fully supported, but see below.
Builder API
------------------------------------------------------
This follows a common schema with most methods are available with its full name
and a short name. Block elements can be called completely with all data or with a
boolean value to open and close it separately.
As far as possible the API won't throw errors but interpret all calls like you maybe
wanted them using auto closing tags.
###
fs = require 'fs'
list = fs.readdirSync __dirname
.filter (e) -> not e.match /^index\./
.filter (e) -> e.match /\.(coffee|js)$/
require "#{__dirname}/#{file}" for file in list
###
Input Formats
------------------------------------------------------
Beside using the programmable API some other file formats may be used. They will
be parsed, but not every format can handle all elements. The main format is markdown
but you may also use one of the others. You also may mix the parsing formats and
place them into API calls.
But only markdown can at the moment be used to store and reread data without loss
of information. The concrete implementation is based on the standards but contains
some significant changes, too.C
__Support for Parsing__
| Element | API | MD | HTML | ADOC |
|:---------- |:---:|:----:|:----:|:----:|
| Text | X | X | | |
| Heading | X | X | | |
| Paragraph | X | X | | |
| Preformat | X | X | | |
| Code | X | X | | |
| Blockquote | X | X | | |
| ThemeBreak | X | X | | |
| List | X | X | | |
| Fixed | X | X | | |
| Emphasis | X | X | | |
| HTML | | X | | |
| Box | | | | |
| Style | | | | |
| ToC | | | | |
| Execute | | | | |
^`X` -> supported; `-` -> not possible; `(X)` -> partly supported;
empty -> not currently done^
Output Formats
------------------------------------------------------
But not every format can handle all elements. The markdown format is the only one
which can be used to store the report without loosing anything.
Each of the formats support different options you may set by configuration or on call
(see the {@link ../configSchema.coffee}).
| Element | MD | Text | HTML | ROFF | ADOC | LaTeX | RTF |
|:---------- |:---:|:----:|:----:|:----:|:----:|:-----:|:---:|
| Text | X | X | X | X | | X | X |
| Paragraph | X | X | X | X | | | |
| Heading | X | X | X | X | | | |
| Preformat | X | | | X | | | |
| Blockquote | X | | | | | | |
| ThemaBreak | X | X | X | X | | | |
| CharStyle | X | (X) | X | X | | | |
| List | X | X | X | | | | |
| HTML | X | | | | | | |
| Box | | | | | | | |
| Style | | | | | | | |
| ToC | | | | | | | |
| Execute | | | | | | | |
^`X` -> supported; `-` -> not possible; `(X)` -> partly supported;
empty -> not currently done^
Markdown
------------------------------------------------------
The **markdown** format is the base format of the report package and the most
powerful of all. It allows complete output without loss of information.
Markdown is a plain text format for writing structured documents, based on conventions
used for indicating formatting in email and usenet posts. It was developed in 2004
by PI:NAME:<NAME>END_PI and adapted in a lot of projects and languages. Some of them extended
the original syntax with conventions for more elements. It is also used in different
web applications like GitHub, StackOverflow, Trello and more.
In contrast to other formats like AsciDoc it is more readable and easier to write.
The markdown parser is basically build to support the following specifications:
- [Daring Fireball](https://daringfireball.net/projects/markdown/)
- [CommonMark Specification](http://spec.commonmark.org/0.27/)
- [GitHub Flavored Markdown](https://help.github.com/categories/writing-on-github/)
See the elements itself of how much it is extended or optimized to this standards.
Also there are some more elements added like:
- ????
The output is based on the parser standards but may be optimized using the configuration
settings. But if you combine this with the parser you will often not get the exact same
output which was parsed earlier. But you will get an optimized version which contains
the exact same information.
All elements are divided into block level or inline elements and may or not may contain
further markdown. Read more about this in each element.
This is extended to also support GFM styles like:
- [Tables](https://help.github.com/articles/organizing-information-with-tables/)
- [TaskLists](https://help.github.com/articles/basic-writing-and-formatting-syntax/#task-lists)
- mentioning (maybe using linkify)
- emoji
HTML Output
---------------------------------------------
Like in all other formats you may specify the output by configuration.
The generated tags will be xhtml compliant and properly nested. But included raw
code may not follow these guidelines.
###
|
[
{
"context": " format - http://msgpack.org/\n# Copyright (c) 2011 Devon Govett\n# MIT LICENSE\n#\n# Permission is hereby granted, f",
"end": 119,
"score": 0.9995921850204468,
"start": 107,
"tag": "NAME",
"value": "Devon Govett"
},
{
"context": " # based on https://... | msgpack.coffee | devongovett/coffeepack | 2 | ###
# An implementation of the MessagePack serialization format - http://msgpack.org/
# Copyright (c) 2011 Devon Govett
# MIT LICENSE
#
# 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.
###
class MsgPack
# export the module to CommonJS or the browser
if module?.exports
module.exports = MsgPack
else
window.MsgPack = MsgPack
idx = 0
@pack: (data, byteArray = false) ->
bytes = pack(data, [])
return bytes if byteArray
fcc = String.fromCharCode
return (fcc byte for byte in bytes).join ''
@unpack: (data) ->
if typeof data is 'string'
data = (data.charCodeAt(i) & 0xff for i in [0...data.length])
idx = 0
unpack(data)
pack = (val, bytes) ->
# if the value has a toJSON function, call it
if val and typeof val is 'object' and typeof val.toJSON is 'function'
val = val.toJSON()
# null or undefined
if not val?
bytes.push 0xc0
# true
else if val is true
bytes.push 0xc3
# false
else if val is false
bytes.push 0xc2
else
switch typeof val
when 'number'
# NaN
if val isnt val
bytes.push 0xcb, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff
# infinity
else if val is Infinity
bytes.push 0xcb, 0x7f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
else if val is -Infinity
bytes.push 0xcb, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
# integer
else if Math.floor(val) is val and -0x8000000000000000 <= val < 0x10000000000000000
# fixnum
if -0x20 <= val < 0x80
val += 0x100 if val < 0
bytes.push val & 0xff
# (u)int8
else if -0x80 <= val < 0x100
type = if val < 0 then 0xd0 else 0xcc
val += 0x100 if val < 0
bytes.push type, val & 0xff
# (u)int16
else if -0x8000 <= val < 0x10000
type = if val < 0 then 0xd1 else 0xcd
val += 0x10000 if val < 0
bytes.push type, (val >>> 8) & 0xff, val & 0xff
# (u)int32
else if -0x80000000 <= val < 0x100000000
type = if val < 0 then 0xd2 else 0xce
val += 0x100000000 if val < 0
bytes.push type, (val >>> 24) & 0xff, (val >>> 16) & 0xff, (val >>> 8) & 0xff, val & 0xff
# (u)int64
else
type = if val < 0 then 0xd3 else 0xcf
high = Math.floor(val / 0x100000000)
low = val & 0xffffffff
bytes.push type, (high >>> 24) & 0xff, (high >>> 16) & 0xff,
(high >>> 8) & 0xff, high & 0xff,
(low >>> 24) & 0xff, (low >>> 16) & 0xff,
(low >>> 8) & 0xff, low & 0xff
# double
else
# TODO: encode single precision if possible
# based on http://javascript.g.hatena.ne.jp/edvakf/20101128/1291000731
sign = val < 0
val *= -1 if sign
# add offset 1023 to ensure positive
exp = ((Math.log(val) / Math.LN2) + 1023) | 0
# shift 52 - (exp - 1023) bits to make integer part exactly 53 bits,
# then throw away trash less than decimal point
frac = val * Math.pow(2, 52 + 1023 - exp)
low = frac & 0xffffffff
exp |= 0x800 if sign
high = ((frac / 0x100000000) & 0xfffff) | (exp << 20)
bytes.push 0xcb, (high >> 24) & 0xff, (high >> 16) & 0xff,
(high >> 8) & 0xff, high & 0xff,
(low >> 24) & 0xff, (low >> 16) & 0xff,
(low >> 8) & 0xff, low & 0xff
when 'string'
# utf-8 encode
# http://ecmanaut.blogspot.com/2006/07/encoding-decoding-utf8-in-javascript.html
val = unescape(encodeURIComponent(val))
size = val.length
# fixraw
if size < 0x20
bytes.push 0xa0 | size
# raw16
else if size < 0x10000
bytes.push 0xda, (size >>> 8) & 0xff, size & 0xff
# raw32
else if size < 0x100000000
bytes.push 0xdb, (size >>> 24) & 0xff, (size >>> 16) & 0xff, (size >>> 8) & 0xff, size & 0xff
else
throw 'String too long.'
for i in [0...size]
bytes.push val.charCodeAt(i)
when 'object'
# array
if Array.isArray(val)
len = val.length
# fixarray
if len < 16
bytes.push 0x90 + len
# array16
else if len < 0x10000
bytes.push 0xdc, (len >>> 8) & 0xff, len & 0xff
# array 32
else if len < 0x100000000
bytes.push 0xdd, (len >>> 24) & 0xff, (len >>> 16) & 0xff, (len >>> 8) & 0xff, len & 0xff
else
throw 'Array too long.'
pack item, bytes for item in val
# map
else
len = Object.keys(val).length
# fixmap
if len < 16
bytes.push 0x80 + len
# map16
else if len < 0x10000
bytes.push 0xde, (len >>> 8) & 0xff, len & 0xff
# map32
else if len < 0x100000000
bytes.push 0xdf, (len >>> 24) & 0xff, (len >>> 16) & 0xff, (len >>> 8) & 0xff, len & 0xff
else
throw 'Map has too many keys.'
for key, mapval of val
pack key, bytes
pack mapval, bytes
else
throw 'Unknown value.'
return bytes
unpack = (buf) ->
byte = buf[idx++]
# fixnum
if byte < 0x80
return byte
# negative fixnum
if byte >= 0xe0
return byte - 0x100
if byte >= 0xc0
switch byte
# null
when 0xc0
return null
# false
when 0xc2
return false
# true
when 0xc3
return true
# float
when 0xca
num = uint32(buf)
return 0.0 if not num or num is 0x80000000 # 0.0 or -0.0
sign = (num >> 31) * 2 + 1 # +1 or -1
exp = (num >> 23) & 0xff
frac = num & 0x7fffff
# NaN or Infinity
if exp is 0xff
return if frac then NaN else sign * Infinity
return sign * (frac | 0x00800000) * Math.pow(2, exp - 127 - 23)
# double
when 0xcb
num = uint32(buf)
if not num or num is 0x80000000 # 0.0 or -0.0
idx += 4
return 0.0
sign = (num >> 31) * 2 + 1 # +1 or -1
exp = (num >> 20) & 0x7ff
frac = num & 0xfffff
if exp is 0x7ff
idx += 4
return if frac then NaN else sign * Infinity
num = uint32(buf)
return sign * ((frac | 0x100000) * Math.pow(2, exp - 1023 - 20) + num * Math.pow(2, exp - 1023 - 52))
# uint8
when 0xcc
return buf[idx++]
# uint16
when 0xcd
return uint16(buf)
# uint32
when 0xce
return uint32(buf)
# uint64
when 0xcf
return uint32(buf) * 0x100000000 + uint32(buf)
# int8
when 0xd0
return buf[idx++] - 0x100
# int16
when 0xd1
return (buf[idx++] << 8) | buf[idx++] - 0x10000
# int32
when 0xd2
num = uint32(buf)
return if num < 0x80000000 then num else num - 0x100000000
# int64
when 0xd3
# based on https://github.com/uupaa/msgpack.js/blob/master/msgpack.js#L317
num = buf[idx++]
if num & 0x80 # avoid sign overflow
return ((num ^ 0xff) * 0x100000000000000 +
(buf[idx++] ^ 0xff) * 0x1000000000000 +
(buf[idx++] ^ 0xff) * 0x10000000000 +
(buf[idx++] ^ 0xff) * 0x100000000 +
(buf[idx++] ^ 0xff) * 0x1000000 +
(buf[idx++] ^ 0xff) * 0x10000 +
(buf[idx++] ^ 0xff) * 0x100 +
(buf[idx++] ^ 0xff) + 1) * -1
return num * 0x100000000000000 +
buf[idx++] * 0x1000000000000 +
buf[idx++] * 0x10000000000 +
buf[idx++] * 0x100000000 +
buf[idx++] * 0x1000000 +
buf[idx++] * 0x10000 +
buf[idx++] * 0x100 +
buf[idx++]
# raw16
when 0xda
return raw(buf, uint16(buf))
# raw32
when 0xdb
return raw(buf, uint32(buf))
# array16
when 0xdc
return array(buf, uint16(buf))
# array32
when 0xdd
return array(buf, uint32(buf))
# map16
when 0xde
return map(buf, uint16(buf))
# map32
when 0xdf
return map(buf, uint32(buf))
throw 'Invalid variable code'
# fixraw (utf8 decode)
if byte >= 0xa0
return raw(buf, byte & 0x1f)
# fixarray
if byte >= 0x90
return array(buf, byte & 0xf)
# fixmap
if byte >= 0x80
return map(buf, byte & 0xf)
throw "Unknown sequence encountered."
uint16 = (buf) ->
return (buf[idx++] << 8) | buf[idx++]
uint32 = (buf) ->
return (buf[idx++] << 24 >>> 0) + ((buf[idx++] << 16) | (buf[idx++] << 8) | buf[idx++])
raw = (buf, len) ->
iz = idx + len
out = []
fromCharCode = String.fromCharCode
while idx < iz
out.push fromCharCode buf[idx++]
# utf-8 decode
# http://ecmanaut.blogspot.com/2006/07/encoding-decoding-utf8-in-javascript.html
return decodeURIComponent(escape(out.join ''))
array = (buf, num) ->
out = []
while num--
out.push unpack(buf, idx)
return out
map = (buf, num) ->
out = {}
while num--
key = unpack(buf, idx)
out[key] = unpack(buf, idx)
return out | 204228 | ###
# An implementation of the MessagePack serialization format - http://msgpack.org/
# Copyright (c) 2011 <NAME>
# MIT LICENSE
#
# 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.
###
class MsgPack
# export the module to CommonJS or the browser
if module?.exports
module.exports = MsgPack
else
window.MsgPack = MsgPack
idx = 0
@pack: (data, byteArray = false) ->
bytes = pack(data, [])
return bytes if byteArray
fcc = String.fromCharCode
return (fcc byte for byte in bytes).join ''
@unpack: (data) ->
if typeof data is 'string'
data = (data.charCodeAt(i) & 0xff for i in [0...data.length])
idx = 0
unpack(data)
pack = (val, bytes) ->
# if the value has a toJSON function, call it
if val and typeof val is 'object' and typeof val.toJSON is 'function'
val = val.toJSON()
# null or undefined
if not val?
bytes.push 0xc0
# true
else if val is true
bytes.push 0xc3
# false
else if val is false
bytes.push 0xc2
else
switch typeof val
when 'number'
# NaN
if val isnt val
bytes.push 0xcb, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff
# infinity
else if val is Infinity
bytes.push 0xcb, 0x7f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
else if val is -Infinity
bytes.push 0xcb, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
# integer
else if Math.floor(val) is val and -0x8000000000000000 <= val < 0x10000000000000000
# fixnum
if -0x20 <= val < 0x80
val += 0x100 if val < 0
bytes.push val & 0xff
# (u)int8
else if -0x80 <= val < 0x100
type = if val < 0 then 0xd0 else 0xcc
val += 0x100 if val < 0
bytes.push type, val & 0xff
# (u)int16
else if -0x8000 <= val < 0x10000
type = if val < 0 then 0xd1 else 0xcd
val += 0x10000 if val < 0
bytes.push type, (val >>> 8) & 0xff, val & 0xff
# (u)int32
else if -0x80000000 <= val < 0x100000000
type = if val < 0 then 0xd2 else 0xce
val += 0x100000000 if val < 0
bytes.push type, (val >>> 24) & 0xff, (val >>> 16) & 0xff, (val >>> 8) & 0xff, val & 0xff
# (u)int64
else
type = if val < 0 then 0xd3 else 0xcf
high = Math.floor(val / 0x100000000)
low = val & 0xffffffff
bytes.push type, (high >>> 24) & 0xff, (high >>> 16) & 0xff,
(high >>> 8) & 0xff, high & 0xff,
(low >>> 24) & 0xff, (low >>> 16) & 0xff,
(low >>> 8) & 0xff, low & 0xff
# double
else
# TODO: encode single precision if possible
# based on http://javascript.g.hatena.ne.jp/edvakf/20101128/1291000731
sign = val < 0
val *= -1 if sign
# add offset 1023 to ensure positive
exp = ((Math.log(val) / Math.LN2) + 1023) | 0
# shift 52 - (exp - 1023) bits to make integer part exactly 53 bits,
# then throw away trash less than decimal point
frac = val * Math.pow(2, 52 + 1023 - exp)
low = frac & 0xffffffff
exp |= 0x800 if sign
high = ((frac / 0x100000000) & 0xfffff) | (exp << 20)
bytes.push 0xcb, (high >> 24) & 0xff, (high >> 16) & 0xff,
(high >> 8) & 0xff, high & 0xff,
(low >> 24) & 0xff, (low >> 16) & 0xff,
(low >> 8) & 0xff, low & 0xff
when 'string'
# utf-8 encode
# http://ecmanaut.blogspot.com/2006/07/encoding-decoding-utf8-in-javascript.html
val = unescape(encodeURIComponent(val))
size = val.length
# fixraw
if size < 0x20
bytes.push 0xa0 | size
# raw16
else if size < 0x10000
bytes.push 0xda, (size >>> 8) & 0xff, size & 0xff
# raw32
else if size < 0x100000000
bytes.push 0xdb, (size >>> 24) & 0xff, (size >>> 16) & 0xff, (size >>> 8) & 0xff, size & 0xff
else
throw 'String too long.'
for i in [0...size]
bytes.push val.charCodeAt(i)
when 'object'
# array
if Array.isArray(val)
len = val.length
# fixarray
if len < 16
bytes.push 0x90 + len
# array16
else if len < 0x10000
bytes.push 0xdc, (len >>> 8) & 0xff, len & 0xff
# array 32
else if len < 0x100000000
bytes.push 0xdd, (len >>> 24) & 0xff, (len >>> 16) & 0xff, (len >>> 8) & 0xff, len & 0xff
else
throw 'Array too long.'
pack item, bytes for item in val
# map
else
len = Object.keys(val).length
# fixmap
if len < 16
bytes.push 0x80 + len
# map16
else if len < 0x10000
bytes.push 0xde, (len >>> 8) & 0xff, len & 0xff
# map32
else if len < 0x100000000
bytes.push 0xdf, (len >>> 24) & 0xff, (len >>> 16) & 0xff, (len >>> 8) & 0xff, len & 0xff
else
throw 'Map has too many keys.'
for key, mapval of val
pack key, bytes
pack mapval, bytes
else
throw 'Unknown value.'
return bytes
unpack = (buf) ->
byte = buf[idx++]
# fixnum
if byte < 0x80
return byte
# negative fixnum
if byte >= 0xe0
return byte - 0x100
if byte >= 0xc0
switch byte
# null
when 0xc0
return null
# false
when 0xc2
return false
# true
when 0xc3
return true
# float
when 0xca
num = uint32(buf)
return 0.0 if not num or num is 0x80000000 # 0.0 or -0.0
sign = (num >> 31) * 2 + 1 # +1 or -1
exp = (num >> 23) & 0xff
frac = num & 0x7fffff
# NaN or Infinity
if exp is 0xff
return if frac then NaN else sign * Infinity
return sign * (frac | 0x00800000) * Math.pow(2, exp - 127 - 23)
# double
when 0xcb
num = uint32(buf)
if not num or num is 0x80000000 # 0.0 or -0.0
idx += 4
return 0.0
sign = (num >> 31) * 2 + 1 # +1 or -1
exp = (num >> 20) & 0x7ff
frac = num & 0xfffff
if exp is 0x7ff
idx += 4
return if frac then NaN else sign * Infinity
num = uint32(buf)
return sign * ((frac | 0x100000) * Math.pow(2, exp - 1023 - 20) + num * Math.pow(2, exp - 1023 - 52))
# uint8
when 0xcc
return buf[idx++]
# uint16
when 0xcd
return uint16(buf)
# uint32
when 0xce
return uint32(buf)
# uint64
when 0xcf
return uint32(buf) * 0x100000000 + uint32(buf)
# int8
when 0xd0
return buf[idx++] - 0x100
# int16
when 0xd1
return (buf[idx++] << 8) | buf[idx++] - 0x10000
# int32
when 0xd2
num = uint32(buf)
return if num < 0x80000000 then num else num - 0x100000000
# int64
when 0xd3
# based on https://github.com/uupaa/msgpack.js/blob/master/msgpack.js#L317
num = buf[idx++]
if num & 0x80 # avoid sign overflow
return ((num ^ 0xff) * 0x100000000000000 +
(buf[idx++] ^ 0xff) * 0x1000000000000 +
(buf[idx++] ^ 0xff) * 0x10000000000 +
(buf[idx++] ^ 0xff) * 0x100000000 +
(buf[idx++] ^ 0xff) * 0x1000000 +
(buf[idx++] ^ 0xff) * 0x10000 +
(buf[idx++] ^ 0xff) * 0x100 +
(buf[idx++] ^ 0xff) + 1) * -1
return num * 0x100000000000000 +
buf[idx++] * 0x1000000000000 +
buf[idx++] * 0x10000000000 +
buf[idx++] * 0x100000000 +
buf[idx++] * 0x1000000 +
buf[idx++] * 0x10000 +
buf[idx++] * 0x100 +
buf[idx++]
# raw16
when 0xda
return raw(buf, uint16(buf))
# raw32
when 0xdb
return raw(buf, uint32(buf))
# array16
when 0xdc
return array(buf, uint16(buf))
# array32
when 0xdd
return array(buf, uint32(buf))
# map16
when 0xde
return map(buf, uint16(buf))
# map32
when 0xdf
return map(buf, uint32(buf))
throw 'Invalid variable code'
# fixraw (utf8 decode)
if byte >= 0xa0
return raw(buf, byte & 0x1f)
# fixarray
if byte >= 0x90
return array(buf, byte & 0xf)
# fixmap
if byte >= 0x80
return map(buf, byte & 0xf)
throw "Unknown sequence encountered."
uint16 = (buf) ->
return (buf[idx++] << 8) | buf[idx++]
uint32 = (buf) ->
return (buf[idx++] << 24 >>> 0) + ((buf[idx++] << 16) | (buf[idx++] << 8) | buf[idx++])
raw = (buf, len) ->
iz = idx + len
out = []
fromCharCode = String.fromCharCode
while idx < iz
out.push fromCharCode buf[idx++]
# utf-8 decode
# http://ecmanaut.blogspot.com/2006/07/encoding-decoding-utf8-in-javascript.html
return decodeURIComponent(escape(out.join ''))
array = (buf, num) ->
out = []
while num--
out.push unpack(buf, idx)
return out
map = (buf, num) ->
out = {}
while num--
key = unpack(buf, idx)
out[key] = unpack(buf, idx)
return out | true | ###
# An implementation of the MessagePack serialization format - http://msgpack.org/
# Copyright (c) 2011 PI:NAME:<NAME>END_PI
# MIT LICENSE
#
# 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.
###
class MsgPack
# export the module to CommonJS or the browser
if module?.exports
module.exports = MsgPack
else
window.MsgPack = MsgPack
idx = 0
@pack: (data, byteArray = false) ->
bytes = pack(data, [])
return bytes if byteArray
fcc = String.fromCharCode
return (fcc byte for byte in bytes).join ''
@unpack: (data) ->
if typeof data is 'string'
data = (data.charCodeAt(i) & 0xff for i in [0...data.length])
idx = 0
unpack(data)
pack = (val, bytes) ->
# if the value has a toJSON function, call it
if val and typeof val is 'object' and typeof val.toJSON is 'function'
val = val.toJSON()
# null or undefined
if not val?
bytes.push 0xc0
# true
else if val is true
bytes.push 0xc3
# false
else if val is false
bytes.push 0xc2
else
switch typeof val
when 'number'
# NaN
if val isnt val
bytes.push 0xcb, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff
# infinity
else if val is Infinity
bytes.push 0xcb, 0x7f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
else if val is -Infinity
bytes.push 0xcb, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
# integer
else if Math.floor(val) is val and -0x8000000000000000 <= val < 0x10000000000000000
# fixnum
if -0x20 <= val < 0x80
val += 0x100 if val < 0
bytes.push val & 0xff
# (u)int8
else if -0x80 <= val < 0x100
type = if val < 0 then 0xd0 else 0xcc
val += 0x100 if val < 0
bytes.push type, val & 0xff
# (u)int16
else if -0x8000 <= val < 0x10000
type = if val < 0 then 0xd1 else 0xcd
val += 0x10000 if val < 0
bytes.push type, (val >>> 8) & 0xff, val & 0xff
# (u)int32
else if -0x80000000 <= val < 0x100000000
type = if val < 0 then 0xd2 else 0xce
val += 0x100000000 if val < 0
bytes.push type, (val >>> 24) & 0xff, (val >>> 16) & 0xff, (val >>> 8) & 0xff, val & 0xff
# (u)int64
else
type = if val < 0 then 0xd3 else 0xcf
high = Math.floor(val / 0x100000000)
low = val & 0xffffffff
bytes.push type, (high >>> 24) & 0xff, (high >>> 16) & 0xff,
(high >>> 8) & 0xff, high & 0xff,
(low >>> 24) & 0xff, (low >>> 16) & 0xff,
(low >>> 8) & 0xff, low & 0xff
# double
else
# TODO: encode single precision if possible
# based on http://javascript.g.hatena.ne.jp/edvakf/20101128/1291000731
sign = val < 0
val *= -1 if sign
# add offset 1023 to ensure positive
exp = ((Math.log(val) / Math.LN2) + 1023) | 0
# shift 52 - (exp - 1023) bits to make integer part exactly 53 bits,
# then throw away trash less than decimal point
frac = val * Math.pow(2, 52 + 1023 - exp)
low = frac & 0xffffffff
exp |= 0x800 if sign
high = ((frac / 0x100000000) & 0xfffff) | (exp << 20)
bytes.push 0xcb, (high >> 24) & 0xff, (high >> 16) & 0xff,
(high >> 8) & 0xff, high & 0xff,
(low >> 24) & 0xff, (low >> 16) & 0xff,
(low >> 8) & 0xff, low & 0xff
when 'string'
# utf-8 encode
# http://ecmanaut.blogspot.com/2006/07/encoding-decoding-utf8-in-javascript.html
val = unescape(encodeURIComponent(val))
size = val.length
# fixraw
if size < 0x20
bytes.push 0xa0 | size
# raw16
else if size < 0x10000
bytes.push 0xda, (size >>> 8) & 0xff, size & 0xff
# raw32
else if size < 0x100000000
bytes.push 0xdb, (size >>> 24) & 0xff, (size >>> 16) & 0xff, (size >>> 8) & 0xff, size & 0xff
else
throw 'String too long.'
for i in [0...size]
bytes.push val.charCodeAt(i)
when 'object'
# array
if Array.isArray(val)
len = val.length
# fixarray
if len < 16
bytes.push 0x90 + len
# array16
else if len < 0x10000
bytes.push 0xdc, (len >>> 8) & 0xff, len & 0xff
# array 32
else if len < 0x100000000
bytes.push 0xdd, (len >>> 24) & 0xff, (len >>> 16) & 0xff, (len >>> 8) & 0xff, len & 0xff
else
throw 'Array too long.'
pack item, bytes for item in val
# map
else
len = Object.keys(val).length
# fixmap
if len < 16
bytes.push 0x80 + len
# map16
else if len < 0x10000
bytes.push 0xde, (len >>> 8) & 0xff, len & 0xff
# map32
else if len < 0x100000000
bytes.push 0xdf, (len >>> 24) & 0xff, (len >>> 16) & 0xff, (len >>> 8) & 0xff, len & 0xff
else
throw 'Map has too many keys.'
for key, mapval of val
pack key, bytes
pack mapval, bytes
else
throw 'Unknown value.'
return bytes
unpack = (buf) ->
byte = buf[idx++]
# fixnum
if byte < 0x80
return byte
# negative fixnum
if byte >= 0xe0
return byte - 0x100
if byte >= 0xc0
switch byte
# null
when 0xc0
return null
# false
when 0xc2
return false
# true
when 0xc3
return true
# float
when 0xca
num = uint32(buf)
return 0.0 if not num or num is 0x80000000 # 0.0 or -0.0
sign = (num >> 31) * 2 + 1 # +1 or -1
exp = (num >> 23) & 0xff
frac = num & 0x7fffff
# NaN or Infinity
if exp is 0xff
return if frac then NaN else sign * Infinity
return sign * (frac | 0x00800000) * Math.pow(2, exp - 127 - 23)
# double
when 0xcb
num = uint32(buf)
if not num or num is 0x80000000 # 0.0 or -0.0
idx += 4
return 0.0
sign = (num >> 31) * 2 + 1 # +1 or -1
exp = (num >> 20) & 0x7ff
frac = num & 0xfffff
if exp is 0x7ff
idx += 4
return if frac then NaN else sign * Infinity
num = uint32(buf)
return sign * ((frac | 0x100000) * Math.pow(2, exp - 1023 - 20) + num * Math.pow(2, exp - 1023 - 52))
# uint8
when 0xcc
return buf[idx++]
# uint16
when 0xcd
return uint16(buf)
# uint32
when 0xce
return uint32(buf)
# uint64
when 0xcf
return uint32(buf) * 0x100000000 + uint32(buf)
# int8
when 0xd0
return buf[idx++] - 0x100
# int16
when 0xd1
return (buf[idx++] << 8) | buf[idx++] - 0x10000
# int32
when 0xd2
num = uint32(buf)
return if num < 0x80000000 then num else num - 0x100000000
# int64
when 0xd3
# based on https://github.com/uupaa/msgpack.js/blob/master/msgpack.js#L317
num = buf[idx++]
if num & 0x80 # avoid sign overflow
return ((num ^ 0xff) * 0x100000000000000 +
(buf[idx++] ^ 0xff) * 0x1000000000000 +
(buf[idx++] ^ 0xff) * 0x10000000000 +
(buf[idx++] ^ 0xff) * 0x100000000 +
(buf[idx++] ^ 0xff) * 0x1000000 +
(buf[idx++] ^ 0xff) * 0x10000 +
(buf[idx++] ^ 0xff) * 0x100 +
(buf[idx++] ^ 0xff) + 1) * -1
return num * 0x100000000000000 +
buf[idx++] * 0x1000000000000 +
buf[idx++] * 0x10000000000 +
buf[idx++] * 0x100000000 +
buf[idx++] * 0x1000000 +
buf[idx++] * 0x10000 +
buf[idx++] * 0x100 +
buf[idx++]
# raw16
when 0xda
return raw(buf, uint16(buf))
# raw32
when 0xdb
return raw(buf, uint32(buf))
# array16
when 0xdc
return array(buf, uint16(buf))
# array32
when 0xdd
return array(buf, uint32(buf))
# map16
when 0xde
return map(buf, uint16(buf))
# map32
when 0xdf
return map(buf, uint32(buf))
throw 'Invalid variable code'
# fixraw (utf8 decode)
if byte >= 0xa0
return raw(buf, byte & 0x1f)
# fixarray
if byte >= 0x90
return array(buf, byte & 0xf)
# fixmap
if byte >= 0x80
return map(buf, byte & 0xf)
throw "Unknown sequence encountered."
uint16 = (buf) ->
return (buf[idx++] << 8) | buf[idx++]
uint32 = (buf) ->
return (buf[idx++] << 24 >>> 0) + ((buf[idx++] << 16) | (buf[idx++] << 8) | buf[idx++])
raw = (buf, len) ->
iz = idx + len
out = []
fromCharCode = String.fromCharCode
while idx < iz
out.push fromCharCode buf[idx++]
# utf-8 decode
# http://ecmanaut.blogspot.com/2006/07/encoding-decoding-utf8-in-javascript.html
return decodeURIComponent(escape(out.join ''))
array = (buf, num) ->
out = []
while num--
out.push unpack(buf, idx)
return out
map = (buf, num) ->
out = {}
while num--
key = unpack(buf, idx)
out[key] = unpack(buf, idx)
return out |
[
{
"context": "#\n# * serializeForm\n# * https://github.com/danheberden/serializeForm\n# *\n# * Copyright (c) 2012 Dan Hebe",
"end": 54,
"score": 0.9993925094604492,
"start": 43,
"tag": "USERNAME",
"value": "danheberden"
},
{
"context": "nheberden/serializeForm\n# *\n# * Copyright (c)... | app/assets/javascripts/libraries/jquery.serialize-form.js.coffee | TeffenEllis/boardwalk | 0 | #
# * serializeForm
# * https://github.com/danheberden/serializeForm
# *
# * Copyright (c) 2012 Dan Heberden
# * Licensed under the MIT, GPL licenses.
#
(($) ->
$.fn.serializeForm = ->
# don't do anything if we didn't get any elements
return false if @length < 1
data = {}
lookup = data #current reference of data
selector = ":input[type!=\"checkbox\"][type!=\"radio\"], input:checked"
parse = ->
# data[a][b] becomes [ data, a, b ]
named = @name.replace(/\[([^\]]+)?\]/g, ",$1").split(",")
cap = named.length - 1
$el = $(this)
# Ensure that only elements with valid `name` properties will be serialized
if named[0]
i = 0
while i < cap
# move down the tree - create objects or array if necessary
lookup = lookup[named[i]] = lookup[named[i]] or ((if named[i + 1] is "" then [] else {}))
i++
# at the end, push or assign the value
if lookup.length isnt `undefined`
lookup.push $el.val()
else
lookup[named[cap]] = $el.val()
# assign the reference back to root
lookup = data
# first, check for elements passed into this function
@filter(selector).each parse
# then parse possible child elements
@find(selector).each parse
# return data
data
) jQuery | 169374 | #
# * serializeForm
# * https://github.com/danheberden/serializeForm
# *
# * Copyright (c) 2012 <NAME>
# * Licensed under the MIT, GPL licenses.
#
(($) ->
$.fn.serializeForm = ->
# don't do anything if we didn't get any elements
return false if @length < 1
data = {}
lookup = data #current reference of data
selector = ":input[type!=\"checkbox\"][type!=\"radio\"], input:checked"
parse = ->
# data[a][b] becomes [ data, a, b ]
named = @name.replace(/\[([^\]]+)?\]/g, ",$1").split(",")
cap = named.length - 1
$el = $(this)
# Ensure that only elements with valid `name` properties will be serialized
if named[0]
i = 0
while i < cap
# move down the tree - create objects or array if necessary
lookup = lookup[named[i]] = lookup[named[i]] or ((if named[i + 1] is "" then [] else {}))
i++
# at the end, push or assign the value
if lookup.length isnt `undefined`
lookup.push $el.val()
else
lookup[named[cap]] = $el.val()
# assign the reference back to root
lookup = data
# first, check for elements passed into this function
@filter(selector).each parse
# then parse possible child elements
@find(selector).each parse
# return data
data
) jQuery | true | #
# * serializeForm
# * https://github.com/danheberden/serializeForm
# *
# * Copyright (c) 2012 PI:NAME:<NAME>END_PI
# * Licensed under the MIT, GPL licenses.
#
(($) ->
$.fn.serializeForm = ->
# don't do anything if we didn't get any elements
return false if @length < 1
data = {}
lookup = data #current reference of data
selector = ":input[type!=\"checkbox\"][type!=\"radio\"], input:checked"
parse = ->
# data[a][b] becomes [ data, a, b ]
named = @name.replace(/\[([^\]]+)?\]/g, ",$1").split(",")
cap = named.length - 1
$el = $(this)
# Ensure that only elements with valid `name` properties will be serialized
if named[0]
i = 0
while i < cap
# move down the tree - create objects or array if necessary
lookup = lookup[named[i]] = lookup[named[i]] or ((if named[i + 1] is "" then [] else {}))
i++
# at the end, push or assign the value
if lookup.length isnt `undefined`
lookup.push $el.val()
else
lookup[named[cap]] = $el.val()
# assign the reference back to root
lookup = data
# first, check for elements passed into this function
@filter(selector).each parse
# then parse possible child elements
@find(selector).each parse
# return data
data
) jQuery |
[
{
"context": " from the options', ->\n testVal = { name: 'Bob', value: 7 }\n # XXX Breaking: Renderer\n ",
"end": 7363,
"score": 0.9997305870056152,
"start": 7360,
"tag": "NAME",
"value": "Bob"
},
{
"context": "ressing enter', ->\n # https://github.com/ocadot... | src/components/autocomplete/spec.coffee | p-koscielniak/hexagonjs | 61 | import chai from 'chai'
import { userFacingText } from 'utils/user-facing-text'
import { range } from 'utils/utils'
import { select, div, Selection } from 'utils/selection'
import logger from 'utils/logger'
import { Autocomplete, autocomplete } from 'components/autocomplete'
import { config as dropdownConfig } from 'components/dropdown'
import emit from 'test/utils/fake-event'
import installFakeTimers from 'test/utils/fake-time'
export default () ->
should = chai.should()
describe 'autocomplete', () ->
dropdownAnimateDelay = 150
inputDebounceDelay = 200
ac = undefined
stringItems = undefined
objectItems = undefined
input = undefined
clock = undefined
fixture = select('body').append('div').class('hx-test-autocomplete')
origConsoleError = console.error
origConsoleWarning = logger.warn
origDropdownAttachSelector = dropdownConfig.attachToSelector
beforeEach ->
ac = undefined
stringItems = [
'bee',
'cee'
'ay',
]
objectItems = [
{ name: 'bee', value: 2 }
{ name: 'cee', value: 3 }
{ name: 'ay', value: 1 }
]
input = fixture.append('input')
clock = installFakeTimers()
chai.spy.on(console, 'error')
logger.warn = chai.spy()
dropdownConfig.attachToSelector = fixture
afterEach ->
clock.restore()
console.error = origConsoleError
logger.warn = origConsoleWarning
dropdownConfig.attachToSelector = origDropdownAttachSelector
fixture.clear()
after ->
fixture.remove()
describe 'sets the user facing text', ->
it 'loading', ->
userFacingText('autocomplete','loading').should.equal('Loading...')
it 'noResultsFound', ->
userFacingText('autocomplete','noResultsFound').should.equal('No results found')
it 'otherResults', ->
userFacingText('autocomplete','otherResults').should.equal('Other Results')
it 'pleaseEnterMinCharacters', ->
userFacingText('autocomplete','pleaseEnterMinCharacters', true).should.equal('Please enter $minLength or more characters')
it 'minCharacters', ->
userFacingText('autocomplete','minCharacters', true).should.equal('Min length $minLength characters')
describe 'exports', ->
it 'Autocomplete', ->
should.exist(Autocomplete)
it 'autocomplete', ->
should.exist(autocomplete)
describe 'without items', ->
beforeEach ->
ac = new Autocomplete(input)
it 'shows a warning', ->
logger.warn.should.have.been.called()
it 'does not set up options', ->
should.not.exist(ac.options)
it 'does not set the component', ->
should.not.exist(input.api())
it 'does not set the named component', ->
should.not.exist(input.api('autocomplete'))
describe 'with string items', ->
beforeEach ->
ac = new Autocomplete(input, stringItems)
it 'sets up the component', ->
input.api('autocomplete').should.equal(ac)
describe 'calling clearCache', ->
data = undefined
beforeEach ->
data = ac._.data
ac.clearCache()
it 'resets the cache', ->
ac._.data.should.not.equal(data)
describe 'calling show', ->
beforeEach ->
ac.show()
clock.tick(dropdownAnimateDelay)
it 'creates the dropdown', ->
fixture.select('.hx-dropdown').empty().should.equal(false)
it 'renders the sorted items based on the value', ->
fixture.selectAll('.hx-menu-item').text().should.eql(['ay', 'bee', 'cee'])
describe 'then hide', ->
beforeEach ->
ac.hide()
clock.tick(dropdownAnimateDelay)
it 'should remove the dropdown', ->
fixture.select('.hx-dropdown').empty().should.equal(true)
describe 'calling hide', ->
it 'returns the autocomplete', ->
ac.hide().should.equal(ac)
describe 'calling value with arguments', ->
beforeEach ->
ac.value('bee')
it 'sets the value', ->
ac.value().should.equal('bee')
it 'sets the input correctly', ->
input.value().should.equal('bee')
it 'returns the autocomplete', ->
ac.value('cee').should.equal(ac)
describe 'sets the default option values', ->
it 'minLength', ->
ac.options.minLength.should.equal(0)
it 'showAll', ->
ac.options.showAll.should.equal(true)
it 'trimTrailingSpaces', ->
ac.options.trimTrailingSpaces.should.equal(false)
it 'mustMatch', ->
ac.options.mustMatch.should.equal(false)
it 'inputMap', ->
should.not.exist(ac.options.inputMap)
it 'renderer', ->
ac.options.renderer.should.be.a('function')
it 'matchType', ->
ac.options.matchType.should.equal('contains')
it 'placeholder', ->
should.not.exist(ac.options.placeholder)
it 'filter', ->
ac.options.filter.should.be.a('function')
it 'filterOptions', ->
ac.options.filterOptions.should.eql({})
it 'showOtherResults', ->
ac.options.showOtherResults.should.equal(false)
it 'allowTabCompletion', ->
ac.options.allowTabCompletion.should.equal(true)
it 'value', ->
should.not.exist(ac.options.value)
# XXX Breaking: Text keys (autocomplete -> autocomplete)
it 'loadingMessage', ->
ac.options.loadingMessage.should.equal(userFacingText('autocomplete', 'loading'))
it 'noResultsMessage', ->
ac.options.noResultsMessage.should.equal(userFacingText('autocomplete', 'noResultsFound'))
it 'otherResultsMessage', ->
ac.options.otherResultsMessage.should.equal(userFacingText('autocomplete', 'otherResults'))
it 'pleaseEnterMinCharactersMessage', ->
ac.options.pleaseEnterMinCharactersMessage.should.equal(userFacingText('autocomplete', 'pleaseEnterMinCharacters', true))
it 'minCharactersMessage', ->
ac.options.minCharactersMessage.should.equal(userFacingText('autocomplete', 'minCharacters', true))
describe 'and providing an initial value', ->
beforeEach ->
ac = new Autocomplete(input, stringItems, { value: 'ay'})
it 'calling value gets the value from the options', ->
ac.value().should.equal('ay')
describe 'calling show', ->
beforeEach ->
ac.show()
clock.tick(dropdownAnimateDelay)
it 'creates the dropdown', ->
fixture.select('.hx-dropdown').empty().should.equal(false)
it 'renders the ay item', ->
fixture.selectAll('.hx-menu-item').text().should.eql(['ay'])
describe 'when using object items', ->
beforeEach ->
ac = new Autocomplete(input, objectItems, {
value: { name: 'xx', value: 5 },
inputMap: (item) -> "#{item.name}, #{item.value}"
})
chai.spy.on(ac.options, 'inputMap')
it 'sets the initial value when it is not in the items', ->
ac.value().should.equal('xx, 5')
it 'sets the renderer using the inputMap from the options', ->
testVal = { name: 'Bob', value: 7 }
# XXX Breaking: Renderer
# ac.options.renderer(testVal)
ac.options.renderer(div(), testVal)
ac.options.inputMap.should.have.been.called.with(testVal)
describe 'when using a function with string items', ->
describe 'without delay', ->
functionItems = (term , cb) ->
cb(stringItems.filter((item) -> item.indexOf(term) > -1))
beforeEach () ->
ac = new Autocomplete(input, functionItems, { value: 'ay' })
it 'sets the initial value correctly from the options', ->
ac.value().should.equal('ay')
describe 'with delay', ->
functionDelay = 10000
functionItemsWithDelay = (term, cb) ->
setTimeout(
() -> cb(stringItems.filter((item) -> item.indexOf(term) > -1)),
functionDelay
)
beforeEach () ->
ac = new Autocomplete(input, functionItemsWithDelay, { value: 'ay' })
it 'sets the initial value correctly from the options', ->
ac.value().should.equal('ay')
describe 'before items are returned', ->
beforeEach () ->
chai.spy.on(ac, 'show')
emit(ac._.input.node(), 'focus')
clock.tick(dropdownAnimateDelay)
it 'shows the dropdown', ->
ac.show.should.have.been.called()
it 'shows the loading text', ->
fixture.select('.hx-menu-item').text().should.equal(userFacingText('autocomplete', 'loading'))
describe 'with delay and mustMatch', ->
it 'handles pressing enter', ->
# https://github.com/ocadotechnology/hexagonjs/issues/338
functionDelay = 10000
mustMatchFunctionItems = (term, cb) ->
setTimeout(
() -> cb(stringItems.filter((item) -> item.indexOf(term) > -1)),
functionDelay
)
ac = new Autocomplete(input, mustMatchFunctionItems, { mustMatch: true })
emit(ac._.input.node(), 'focus')
ac._.input.value('ayz')
emit(ac._.input.node(), 'input', {
target: ac._.input.node(),
preventDefault: () ->
})
clock.tick(inputDebounceDelay)
ac._.data.get('ayz').should.equal(true, 'data loading')
emit(ac._.input.node(), 'keydown', {
which: 13,
preventDefault: () ->
})
console.error.should.not.have.been.called()
input.value().should.equal('', 'input empty')
ac.value().should.equal('', 'ac value empty')
clock.tick(dropdownAnimateDelay)
fixture.selectAll('.hx-dropdown').empty().should.equal(true, 'dropdown empty')
describe 'autocomplete', ->
beforeEach ->
ac = autocomplete(stringItems, { testMergeOption: true })
it 'returns a selection', ->
(ac instanceof Selection).should.equal(true)
it 'has the Autocomplete component', ->
(ac.api('autocomplete') instanceof Autocomplete).should.equal(true)
it 'passes the options to the Autocomplete', ->
ac.api('autocomplete').options.testMergeOption.should.equal(true)
| 161307 | import chai from 'chai'
import { userFacingText } from 'utils/user-facing-text'
import { range } from 'utils/utils'
import { select, div, Selection } from 'utils/selection'
import logger from 'utils/logger'
import { Autocomplete, autocomplete } from 'components/autocomplete'
import { config as dropdownConfig } from 'components/dropdown'
import emit from 'test/utils/fake-event'
import installFakeTimers from 'test/utils/fake-time'
export default () ->
should = chai.should()
describe 'autocomplete', () ->
dropdownAnimateDelay = 150
inputDebounceDelay = 200
ac = undefined
stringItems = undefined
objectItems = undefined
input = undefined
clock = undefined
fixture = select('body').append('div').class('hx-test-autocomplete')
origConsoleError = console.error
origConsoleWarning = logger.warn
origDropdownAttachSelector = dropdownConfig.attachToSelector
beforeEach ->
ac = undefined
stringItems = [
'bee',
'cee'
'ay',
]
objectItems = [
{ name: 'bee', value: 2 }
{ name: 'cee', value: 3 }
{ name: 'ay', value: 1 }
]
input = fixture.append('input')
clock = installFakeTimers()
chai.spy.on(console, 'error')
logger.warn = chai.spy()
dropdownConfig.attachToSelector = fixture
afterEach ->
clock.restore()
console.error = origConsoleError
logger.warn = origConsoleWarning
dropdownConfig.attachToSelector = origDropdownAttachSelector
fixture.clear()
after ->
fixture.remove()
describe 'sets the user facing text', ->
it 'loading', ->
userFacingText('autocomplete','loading').should.equal('Loading...')
it 'noResultsFound', ->
userFacingText('autocomplete','noResultsFound').should.equal('No results found')
it 'otherResults', ->
userFacingText('autocomplete','otherResults').should.equal('Other Results')
it 'pleaseEnterMinCharacters', ->
userFacingText('autocomplete','pleaseEnterMinCharacters', true).should.equal('Please enter $minLength or more characters')
it 'minCharacters', ->
userFacingText('autocomplete','minCharacters', true).should.equal('Min length $minLength characters')
describe 'exports', ->
it 'Autocomplete', ->
should.exist(Autocomplete)
it 'autocomplete', ->
should.exist(autocomplete)
describe 'without items', ->
beforeEach ->
ac = new Autocomplete(input)
it 'shows a warning', ->
logger.warn.should.have.been.called()
it 'does not set up options', ->
should.not.exist(ac.options)
it 'does not set the component', ->
should.not.exist(input.api())
it 'does not set the named component', ->
should.not.exist(input.api('autocomplete'))
describe 'with string items', ->
beforeEach ->
ac = new Autocomplete(input, stringItems)
it 'sets up the component', ->
input.api('autocomplete').should.equal(ac)
describe 'calling clearCache', ->
data = undefined
beforeEach ->
data = ac._.data
ac.clearCache()
it 'resets the cache', ->
ac._.data.should.not.equal(data)
describe 'calling show', ->
beforeEach ->
ac.show()
clock.tick(dropdownAnimateDelay)
it 'creates the dropdown', ->
fixture.select('.hx-dropdown').empty().should.equal(false)
it 'renders the sorted items based on the value', ->
fixture.selectAll('.hx-menu-item').text().should.eql(['ay', 'bee', 'cee'])
describe 'then hide', ->
beforeEach ->
ac.hide()
clock.tick(dropdownAnimateDelay)
it 'should remove the dropdown', ->
fixture.select('.hx-dropdown').empty().should.equal(true)
describe 'calling hide', ->
it 'returns the autocomplete', ->
ac.hide().should.equal(ac)
describe 'calling value with arguments', ->
beforeEach ->
ac.value('bee')
it 'sets the value', ->
ac.value().should.equal('bee')
it 'sets the input correctly', ->
input.value().should.equal('bee')
it 'returns the autocomplete', ->
ac.value('cee').should.equal(ac)
describe 'sets the default option values', ->
it 'minLength', ->
ac.options.minLength.should.equal(0)
it 'showAll', ->
ac.options.showAll.should.equal(true)
it 'trimTrailingSpaces', ->
ac.options.trimTrailingSpaces.should.equal(false)
it 'mustMatch', ->
ac.options.mustMatch.should.equal(false)
it 'inputMap', ->
should.not.exist(ac.options.inputMap)
it 'renderer', ->
ac.options.renderer.should.be.a('function')
it 'matchType', ->
ac.options.matchType.should.equal('contains')
it 'placeholder', ->
should.not.exist(ac.options.placeholder)
it 'filter', ->
ac.options.filter.should.be.a('function')
it 'filterOptions', ->
ac.options.filterOptions.should.eql({})
it 'showOtherResults', ->
ac.options.showOtherResults.should.equal(false)
it 'allowTabCompletion', ->
ac.options.allowTabCompletion.should.equal(true)
it 'value', ->
should.not.exist(ac.options.value)
# XXX Breaking: Text keys (autocomplete -> autocomplete)
it 'loadingMessage', ->
ac.options.loadingMessage.should.equal(userFacingText('autocomplete', 'loading'))
it 'noResultsMessage', ->
ac.options.noResultsMessage.should.equal(userFacingText('autocomplete', 'noResultsFound'))
it 'otherResultsMessage', ->
ac.options.otherResultsMessage.should.equal(userFacingText('autocomplete', 'otherResults'))
it 'pleaseEnterMinCharactersMessage', ->
ac.options.pleaseEnterMinCharactersMessage.should.equal(userFacingText('autocomplete', 'pleaseEnterMinCharacters', true))
it 'minCharactersMessage', ->
ac.options.minCharactersMessage.should.equal(userFacingText('autocomplete', 'minCharacters', true))
describe 'and providing an initial value', ->
beforeEach ->
ac = new Autocomplete(input, stringItems, { value: 'ay'})
it 'calling value gets the value from the options', ->
ac.value().should.equal('ay')
describe 'calling show', ->
beforeEach ->
ac.show()
clock.tick(dropdownAnimateDelay)
it 'creates the dropdown', ->
fixture.select('.hx-dropdown').empty().should.equal(false)
it 'renders the ay item', ->
fixture.selectAll('.hx-menu-item').text().should.eql(['ay'])
describe 'when using object items', ->
beforeEach ->
ac = new Autocomplete(input, objectItems, {
value: { name: 'xx', value: 5 },
inputMap: (item) -> "#{item.name}, #{item.value}"
})
chai.spy.on(ac.options, 'inputMap')
it 'sets the initial value when it is not in the items', ->
ac.value().should.equal('xx, 5')
it 'sets the renderer using the inputMap from the options', ->
testVal = { name: '<NAME>', value: 7 }
# XXX Breaking: Renderer
# ac.options.renderer(testVal)
ac.options.renderer(div(), testVal)
ac.options.inputMap.should.have.been.called.with(testVal)
describe 'when using a function with string items', ->
describe 'without delay', ->
functionItems = (term , cb) ->
cb(stringItems.filter((item) -> item.indexOf(term) > -1))
beforeEach () ->
ac = new Autocomplete(input, functionItems, { value: 'ay' })
it 'sets the initial value correctly from the options', ->
ac.value().should.equal('ay')
describe 'with delay', ->
functionDelay = 10000
functionItemsWithDelay = (term, cb) ->
setTimeout(
() -> cb(stringItems.filter((item) -> item.indexOf(term) > -1)),
functionDelay
)
beforeEach () ->
ac = new Autocomplete(input, functionItemsWithDelay, { value: 'ay' })
it 'sets the initial value correctly from the options', ->
ac.value().should.equal('ay')
describe 'before items are returned', ->
beforeEach () ->
chai.spy.on(ac, 'show')
emit(ac._.input.node(), 'focus')
clock.tick(dropdownAnimateDelay)
it 'shows the dropdown', ->
ac.show.should.have.been.called()
it 'shows the loading text', ->
fixture.select('.hx-menu-item').text().should.equal(userFacingText('autocomplete', 'loading'))
describe 'with delay and mustMatch', ->
it 'handles pressing enter', ->
# https://github.com/ocadotechnology/hexagonjs/issues/338
functionDelay = 10000
mustMatchFunctionItems = (term, cb) ->
setTimeout(
() -> cb(stringItems.filter((item) -> item.indexOf(term) > -1)),
functionDelay
)
ac = new Autocomplete(input, mustMatchFunctionItems, { mustMatch: true })
emit(ac._.input.node(), 'focus')
ac._.input.value('ayz')
emit(ac._.input.node(), 'input', {
target: ac._.input.node(),
preventDefault: () ->
})
clock.tick(inputDebounceDelay)
ac._.data.get('ayz').should.equal(true, 'data loading')
emit(ac._.input.node(), 'keydown', {
which: 13,
preventDefault: () ->
})
console.error.should.not.have.been.called()
input.value().should.equal('', 'input empty')
ac.value().should.equal('', 'ac value empty')
clock.tick(dropdownAnimateDelay)
fixture.selectAll('.hx-dropdown').empty().should.equal(true, 'dropdown empty')
describe 'autocomplete', ->
beforeEach ->
ac = autocomplete(stringItems, { testMergeOption: true })
it 'returns a selection', ->
(ac instanceof Selection).should.equal(true)
it 'has the Autocomplete component', ->
(ac.api('autocomplete') instanceof Autocomplete).should.equal(true)
it 'passes the options to the Autocomplete', ->
ac.api('autocomplete').options.testMergeOption.should.equal(true)
| true | import chai from 'chai'
import { userFacingText } from 'utils/user-facing-text'
import { range } from 'utils/utils'
import { select, div, Selection } from 'utils/selection'
import logger from 'utils/logger'
import { Autocomplete, autocomplete } from 'components/autocomplete'
import { config as dropdownConfig } from 'components/dropdown'
import emit from 'test/utils/fake-event'
import installFakeTimers from 'test/utils/fake-time'
export default () ->
should = chai.should()
describe 'autocomplete', () ->
dropdownAnimateDelay = 150
inputDebounceDelay = 200
ac = undefined
stringItems = undefined
objectItems = undefined
input = undefined
clock = undefined
fixture = select('body').append('div').class('hx-test-autocomplete')
origConsoleError = console.error
origConsoleWarning = logger.warn
origDropdownAttachSelector = dropdownConfig.attachToSelector
beforeEach ->
ac = undefined
stringItems = [
'bee',
'cee'
'ay',
]
objectItems = [
{ name: 'bee', value: 2 }
{ name: 'cee', value: 3 }
{ name: 'ay', value: 1 }
]
input = fixture.append('input')
clock = installFakeTimers()
chai.spy.on(console, 'error')
logger.warn = chai.spy()
dropdownConfig.attachToSelector = fixture
afterEach ->
clock.restore()
console.error = origConsoleError
logger.warn = origConsoleWarning
dropdownConfig.attachToSelector = origDropdownAttachSelector
fixture.clear()
after ->
fixture.remove()
describe 'sets the user facing text', ->
it 'loading', ->
userFacingText('autocomplete','loading').should.equal('Loading...')
it 'noResultsFound', ->
userFacingText('autocomplete','noResultsFound').should.equal('No results found')
it 'otherResults', ->
userFacingText('autocomplete','otherResults').should.equal('Other Results')
it 'pleaseEnterMinCharacters', ->
userFacingText('autocomplete','pleaseEnterMinCharacters', true).should.equal('Please enter $minLength or more characters')
it 'minCharacters', ->
userFacingText('autocomplete','minCharacters', true).should.equal('Min length $minLength characters')
describe 'exports', ->
it 'Autocomplete', ->
should.exist(Autocomplete)
it 'autocomplete', ->
should.exist(autocomplete)
describe 'without items', ->
beforeEach ->
ac = new Autocomplete(input)
it 'shows a warning', ->
logger.warn.should.have.been.called()
it 'does not set up options', ->
should.not.exist(ac.options)
it 'does not set the component', ->
should.not.exist(input.api())
it 'does not set the named component', ->
should.not.exist(input.api('autocomplete'))
describe 'with string items', ->
beforeEach ->
ac = new Autocomplete(input, stringItems)
it 'sets up the component', ->
input.api('autocomplete').should.equal(ac)
describe 'calling clearCache', ->
data = undefined
beforeEach ->
data = ac._.data
ac.clearCache()
it 'resets the cache', ->
ac._.data.should.not.equal(data)
describe 'calling show', ->
beforeEach ->
ac.show()
clock.tick(dropdownAnimateDelay)
it 'creates the dropdown', ->
fixture.select('.hx-dropdown').empty().should.equal(false)
it 'renders the sorted items based on the value', ->
fixture.selectAll('.hx-menu-item').text().should.eql(['ay', 'bee', 'cee'])
describe 'then hide', ->
beforeEach ->
ac.hide()
clock.tick(dropdownAnimateDelay)
it 'should remove the dropdown', ->
fixture.select('.hx-dropdown').empty().should.equal(true)
describe 'calling hide', ->
it 'returns the autocomplete', ->
ac.hide().should.equal(ac)
describe 'calling value with arguments', ->
beforeEach ->
ac.value('bee')
it 'sets the value', ->
ac.value().should.equal('bee')
it 'sets the input correctly', ->
input.value().should.equal('bee')
it 'returns the autocomplete', ->
ac.value('cee').should.equal(ac)
describe 'sets the default option values', ->
it 'minLength', ->
ac.options.minLength.should.equal(0)
it 'showAll', ->
ac.options.showAll.should.equal(true)
it 'trimTrailingSpaces', ->
ac.options.trimTrailingSpaces.should.equal(false)
it 'mustMatch', ->
ac.options.mustMatch.should.equal(false)
it 'inputMap', ->
should.not.exist(ac.options.inputMap)
it 'renderer', ->
ac.options.renderer.should.be.a('function')
it 'matchType', ->
ac.options.matchType.should.equal('contains')
it 'placeholder', ->
should.not.exist(ac.options.placeholder)
it 'filter', ->
ac.options.filter.should.be.a('function')
it 'filterOptions', ->
ac.options.filterOptions.should.eql({})
it 'showOtherResults', ->
ac.options.showOtherResults.should.equal(false)
it 'allowTabCompletion', ->
ac.options.allowTabCompletion.should.equal(true)
it 'value', ->
should.not.exist(ac.options.value)
# XXX Breaking: Text keys (autocomplete -> autocomplete)
it 'loadingMessage', ->
ac.options.loadingMessage.should.equal(userFacingText('autocomplete', 'loading'))
it 'noResultsMessage', ->
ac.options.noResultsMessage.should.equal(userFacingText('autocomplete', 'noResultsFound'))
it 'otherResultsMessage', ->
ac.options.otherResultsMessage.should.equal(userFacingText('autocomplete', 'otherResults'))
it 'pleaseEnterMinCharactersMessage', ->
ac.options.pleaseEnterMinCharactersMessage.should.equal(userFacingText('autocomplete', 'pleaseEnterMinCharacters', true))
it 'minCharactersMessage', ->
ac.options.minCharactersMessage.should.equal(userFacingText('autocomplete', 'minCharacters', true))
describe 'and providing an initial value', ->
beforeEach ->
ac = new Autocomplete(input, stringItems, { value: 'ay'})
it 'calling value gets the value from the options', ->
ac.value().should.equal('ay')
describe 'calling show', ->
beforeEach ->
ac.show()
clock.tick(dropdownAnimateDelay)
it 'creates the dropdown', ->
fixture.select('.hx-dropdown').empty().should.equal(false)
it 'renders the ay item', ->
fixture.selectAll('.hx-menu-item').text().should.eql(['ay'])
describe 'when using object items', ->
beforeEach ->
ac = new Autocomplete(input, objectItems, {
value: { name: 'xx', value: 5 },
inputMap: (item) -> "#{item.name}, #{item.value}"
})
chai.spy.on(ac.options, 'inputMap')
it 'sets the initial value when it is not in the items', ->
ac.value().should.equal('xx, 5')
it 'sets the renderer using the inputMap from the options', ->
testVal = { name: 'PI:NAME:<NAME>END_PI', value: 7 }
# XXX Breaking: Renderer
# ac.options.renderer(testVal)
ac.options.renderer(div(), testVal)
ac.options.inputMap.should.have.been.called.with(testVal)
describe 'when using a function with string items', ->
describe 'without delay', ->
functionItems = (term , cb) ->
cb(stringItems.filter((item) -> item.indexOf(term) > -1))
beforeEach () ->
ac = new Autocomplete(input, functionItems, { value: 'ay' })
it 'sets the initial value correctly from the options', ->
ac.value().should.equal('ay')
describe 'with delay', ->
functionDelay = 10000
functionItemsWithDelay = (term, cb) ->
setTimeout(
() -> cb(stringItems.filter((item) -> item.indexOf(term) > -1)),
functionDelay
)
beforeEach () ->
ac = new Autocomplete(input, functionItemsWithDelay, { value: 'ay' })
it 'sets the initial value correctly from the options', ->
ac.value().should.equal('ay')
describe 'before items are returned', ->
beforeEach () ->
chai.spy.on(ac, 'show')
emit(ac._.input.node(), 'focus')
clock.tick(dropdownAnimateDelay)
it 'shows the dropdown', ->
ac.show.should.have.been.called()
it 'shows the loading text', ->
fixture.select('.hx-menu-item').text().should.equal(userFacingText('autocomplete', 'loading'))
describe 'with delay and mustMatch', ->
it 'handles pressing enter', ->
# https://github.com/ocadotechnology/hexagonjs/issues/338
functionDelay = 10000
mustMatchFunctionItems = (term, cb) ->
setTimeout(
() -> cb(stringItems.filter((item) -> item.indexOf(term) > -1)),
functionDelay
)
ac = new Autocomplete(input, mustMatchFunctionItems, { mustMatch: true })
emit(ac._.input.node(), 'focus')
ac._.input.value('ayz')
emit(ac._.input.node(), 'input', {
target: ac._.input.node(),
preventDefault: () ->
})
clock.tick(inputDebounceDelay)
ac._.data.get('ayz').should.equal(true, 'data loading')
emit(ac._.input.node(), 'keydown', {
which: 13,
preventDefault: () ->
})
console.error.should.not.have.been.called()
input.value().should.equal('', 'input empty')
ac.value().should.equal('', 'ac value empty')
clock.tick(dropdownAnimateDelay)
fixture.selectAll('.hx-dropdown').empty().should.equal(true, 'dropdown empty')
describe 'autocomplete', ->
beforeEach ->
ac = autocomplete(stringItems, { testMergeOption: true })
it 'returns a selection', ->
(ac instanceof Selection).should.equal(true)
it 'has the Autocomplete component', ->
(ac.api('autocomplete') instanceof Autocomplete).should.equal(true)
it 'passes the options to the Autocomplete', ->
ac.api('autocomplete').options.testMergeOption.should.equal(true)
|
[
{
"context": "###\n * cena_auth\n * https://github.com/1egoman/cena_app\n *\n * Copyright (c) 2015 Ryan Gaus\n * Li",
"end": 46,
"score": 0.9968822598457336,
"start": 39,
"tag": "USERNAME",
"value": "1egoman"
},
{
"context": "thub.com/1egoman/cena_app\n *\n * Copyright (c) 2015 Ryan ... | src/frontend/services/tags.coffee | 1egoman/cena_app | 0 | ###
* cena_auth
* https://github.com/1egoman/cena_app
*
* Copyright (c) 2015 Ryan Gaus
* Licensed under the MIT license.
###
'use strict';
# tags service
@app.factory "Tag", ($http, $resource) ->
$resource "/settings/tags/:name",
name: '@name'
| 105691 | ###
* cena_auth
* https://github.com/1egoman/cena_app
*
* Copyright (c) 2015 <NAME>
* Licensed under the MIT license.
###
'use strict';
# tags service
@app.factory "Tag", ($http, $resource) ->
$resource "/settings/tags/:name",
name: '@name'
| true | ###
* cena_auth
* https://github.com/1egoman/cena_app
*
* Copyright (c) 2015 PI:NAME:<NAME>END_PI
* Licensed under the MIT license.
###
'use strict';
# tags service
@app.factory "Tag", ($http, $resource) ->
$resource "/settings/tags/:name",
name: '@name'
|
[
{
"context": "d\n item =\n id: filter.id\n name: filtername\n count: filter.count\n\n # Compiles",
"end": 14082,
"score": 0.9316322803497314,
"start": 14076,
"tag": "NAME",
"value": "filter"
}
] | app/coffee/modules/search/facetsearch/views/engine.coffee | tetherless-world/magellan | 0 |
###*
# Please note that when passing in custom templates for
# listItemTemplate and orderByTemplate to keep the classes as
# they are used in the code at other locations as well.
###
# TODO - these should be abstracted or removed
defaults =
items: [{a:2,b:1,c:2},{a:2,b:2,c:1},{a:1,b:1,c:1},{a:3,b:3,c:1}],
facets: {'a': 'Title A', 'b': 'Title B', 'c': 'Title C'},
facetElement: '#facets'
listItemTemplate: '<div class="facetitem" id="<%= id %>"><%= name %> <span class="facetitemcount">(<%= count %>)</span></div>'
countTemplate: '<div class=facettotalcount>Results</div>'
resultTemplateBypass: null
orderByOptions:
'a': 'by A'
'b': 'by B'
'RANDOM': 'by random'
state:
orderBy: false
filters: {}
enablePagination: true
paginationCount: 20
###*
# This is the first function / variable that gets exported into the
# jQuery namespace. Pass in your own settings (see above) to initialize
# the faceted search
###
settings = {}
###*
# The following section contains the logic of the faceted search
###
###*
# initializes all facets and their individual filters
###
# Iterate over each facet
# Instantiates empty facet object in facetCollection registry
# TODO - this can be phased out once facetCollection IS a Backbone.Collection
createEmptyFacetCollection = ->
for facet in settings.facets
settings.facetCollection[facet.attribute] = {}
# Sets zero count for all settings.items?
# TODO - rename settings.items
setZeroCounts = ->
# Iterate over each item
for item in settings.items
# Aliases item
item = item.data
# intialize the count to be zero
for facet in settings.facets
# Item[facet] is an array...
if $.isArray(item[facet.attribute])
for facetitem in item[facet.attribute]
if typeof facetitem == 'object'
settings.facetCollection[facet.attribute][facetitem['@id']] = settings.facetCollection[facet.attribute][facetitem['@id']] ||
count: 0
id: _.uniqueId('facet_')
else
settings.facetCollection[facet.attribute][facetitem] = settings.facetCollection[facet.attribute][facetitem] or
count: 0
id: _.uniqueId('facet_')
# IF OBJECT OR @ID
else if typeof(item[facet.attribute]) == 'object' && (item[facet.attribute]['@id'] || item[facet.attribute]['@value'])
# Sets attrKey
attrKey = if item[facet.attribute]['@id'] then '@id' else '@value'
settings.facetCollection[facet.attribute][item[facet.attribute][attrKey]] = settings.facetCollection[facet.attribute][item[facet.attribute][attrKey]] ||
count: 0
id: _.uniqueId('facet_')
# Not an array or object...
else
if item[facet.attribute] != undefined
settings.facetCollection[facet.attribute][item[facet.attribute]] = settings.facetCollection[facet.attribute][item[facet.attribute]] or
count: 0
id: _.uniqueId('facet_')
# SORTS FACET COLLECTION
# TODO - rename?
sortFacetCollection = ->
# sort it:
for facettitle, facet of settings.facetCollection
sorted = _.keys(settings.facetCollection[facettitle]).sort()
if settings.facet_SortOption and settings.facet_SortOption[facettitle]
sorted = _.union(settings.facet_SortOption[facettitle], sorted)
sortedstore = {}
for el in sorted
sortedstore[el] = settings.facetCollection[facettitle][el]
settings.facetCollection[facettitle] = sortedstore
# Sets initial facet counts
initFacetCount = ->
# TODO - phase this out.
createEmptyFacetCollection()
# Set ZERO counts on all settings.items?
setZeroCounts()
# Sorts
sortFacetCollection()
###*
# resets the facet count
###
resetFacetCount = ->
for facetname, items of settings.facetCollection
for itemname, value of items
settings.facetCollection[facetname][itemname].count = 0
###*
# Filters all items from the settings according to the currently
# set filters and stores the results in the settings.currentResults.
# The number of items in each filter from each facet is also updated
###
filterSingleItem = (item) ->
# Bool for _.select / _.filter
filtersApply = true
# Aliases item.data
item = item.data
# Iterates over each filter
for facet, filter of settings.state.filters
# TODO - abstract this elsewhere, repeated
# TODO - document what's happening here
if $.isArray(item[facet])
if item[facet][0] && typeof(item[facet][0]) == 'object'
for f in item[facet]
if filter.length and _.indexOf(filter, f['@id']) == -1
filtersApply = false
else
inters = _.intersection(item[facet], filter)
if inters.length == 0
filtersApply = false
else if typeof(item[facet]) == 'object' && (item[facet]['@id'] || item[facet]['@value'])
# Sets attrKey
attrKey = if item[facet]['@id'] then '@id' else '@value'
if filter.length and _.indexOf(filter, item[facet][attrKey]) == -1
filtersApply = false
else
if filter.length and _.indexOf(filter, item[facet]) == -1
filtersApply = false
return filtersApply
# # # # #
# first apply the filters to the items
applyFilters = ->
settings.currentResults = _.select(settings.items, filterSingleItem)
# # # # #
updateFacetCollection = ->
# then reduce the items to get the current count for each facet
for facet in settings.facets
# Iterates over each currentResult
for item in settings.currentResults
item = item.data
# TODO - abstract this logic elswhere
# TODO - document what's happening here...
if $.isArray(item[facet.attribute])
_.each item[facet.attribute], (facetitem) ->
if typeof(facetitem) == 'object'
settings.facetCollection[facet.attribute][facetitem['@id']].count += 1
else
settings.facetCollection[facet.attribute][facetitem].count += 1
return
else if typeof(item[facet.attribute]) == 'object' && (item[facet.attribute]['@id'] || item[facet.attribute]['@value'])
attrKey = if item[facet.attribute]['@id'] then '@id' else '@value'
if item[facet.attribute][attrKey] != undefined
settings.facetCollection[facet.attribute][item[facet.attribute][attrKey]].count += 1
else
if item[facet.attribute] != undefined
settings.facetCollection[facet.attribute][item[facet.attribute]].count += 1
# # # # #
filter = ->
# Applies filters
applyFilters()
# DEXIE DATABASE CALL
# if (window.global){
# window.dexiePromise = window.global.queryDexie(appliedFilters)
# }
# Update the count for each facet and item:
# intialize the count to be zero
resetFacetCount()
# Updates the facet collection with the results
updateFacetCollection()
# Updates state???
settings.state.shownResults = 0
return
###*
# Orders the currentResults according to the settings.state.orderBy variable
###
order = ->
if settings.state.orderBy
# TODO - abstract into Backbone.View
$('.activeorderby').removeClass 'activeorderby'
$('#orderby_' + settings.state.orderBy).addClass 'activeorderby'
# Applies sort settings
settings.currentResults = _.sortBy settings.currentResults, (item) ->
if settings.state.orderBy == 'RANDOM'
Math.random() * 10000
else
item[settings.state.orderBy]
###*
# The given facetname and filtername are activated or deactivated
# depending on what they were beforehand. This causes the items to
# be filtered again and the UI is updated accordingly.
###
toggleFilter = (key, value) ->
settings.state.filters[key] = settings.state.filters[key] or []
if _.indexOf(settings.state.filters[key], value) == -1
settings.state.filters[key].push value
else
settings.state.filters[key] = _.without(settings.state.filters[key], value)
if settings.state.filters[key].length == 0
delete settings.state.filters[key]
filter()
return
###*
# The following section contains the presentation of the faceted search
###
###*
# This function is only called once, it creates the facets ui.
###
createFacetUI = ->
facetContainer = '<div class=facetsearch id=<%= id %> ></div>'
facetTitleTemplate = '<h3 class=facettitle><i class="icon"></i><%= title %><i class="fa fa-fw help" data-toggle="tooltip" data-placement="right" title="<%= tooltip %>"></i><br><span class="prefix <%= prefix %>"><%= prefix %> : <%= _id %></span></h3>'
facetListContainer = '<div class=facetlist></div>'
# Templates & HTML setup
itemtemplate = _.template(settings.listItemTemplate)
titletemplate = _.template(facetTitleTemplate)
containertemplate = _.template(facetContainer)
$(settings.facetElement).html('')
# Iterates over each setting...
# TODO - this will be replaced by the FACET_GROUP_COLLECTION_VIEW
# Each facet will have pagination, filtering, etc.
for facet in settings.facets
facetHtml = $(containertemplate(id: facet.attribute))
# Assembles facetItem
facetItem =
title: facet.label
tooltip: facet.tooltip
prefix: facet.prefix
_id: facet._id
# ABSTRACTION
# This is where we should collect the GROUPS of facets
# This MAY be accessible outside this little engine, passed in as settings.facets
# console.log(facetItem);
facetItemHtml = $(titletemplate(facetItem))
facetHtml.append facetItemHtml
facetlist = $(facetListContainer)
# Iterates over each filter
# TODO - this will be replaced by the FACET_ITEM_COLLECTION_VIEW
_.each settings.facetCollection[facet.attribute], (filter, filtername) ->
# Splits name, handles directories ending with '/'
# TODO - abstract into function
splitName = filtername.trim().split('/')
filtername = splitName.pop()
filtername ||= splitName.pop()
item =
id: filter.id
name: filtername
count: filter.count
# ABSTRACTION - this is where the INITIAL facets are populated into the UI
# FROM HERE, we start the collection of facet items
# console.log(item);
# Facet filter item CSS state
filteritem = $(itemtemplate(item))
if _.indexOf(settings.state.filters[facet.attribute], filtername) >= 0
filteritem.addClass('activefacet')
if item.count == 0
filteritem.addClass('no-match')
# Appends to list of facetItems
facetlist.append filteritem
return
# Appends HTML
facetHtml.append(facetlist)
$(settings.facetElement).append(facetHtml)
# Tooltips
$('[data-toggle=tooltip]').tooltip()
# # # # # # # # # # # # # # # # # # # #
# TODO - abstract into Backbone.View
# add the click event handler to each facet item:
$('.facetitem').click (event) ->
`var filter`
filter = getFilterById(@id)
toggleFilter(filter.facetname, filter.filtername)
# $(settings.facetElement).trigger 'facetedsearchfacetclick', filter
order()
updateFacetUI()
updateResults()
return
# # # # #
# TODO - ABSTRACT INTO SEPARATE VIEW
# FOR RESULT COUNTR AND ORDER CONTROLS
# Append total result count
bottomContainer = '<div class=bottomline></div>'
bottom = $(bottomContainer)
countHtml = _.template(settings.countTemplate, count: settings.currentResults.length or 0)
$(bottom).append(countHtml)
# generate the "order by" options:
orderByTemplate = '<div class=orderby><span class="orderby-title">Sort by: </span><ul><% _.each(options, function(value, key) { %>' + '<li class=orderbyitem id=orderby_<%= key %>>' + '<%= value %> </li> <% }); %></ul></div>'
ordertemplate = _.template(orderByTemplate)
itemHtml = $(ordertemplate('options': settings.orderByOptions))
$(bottom).append itemHtml
$(settings.facetElement).append bottom
$('.orderbyitem').each ->
id = @id.substr(8)
if settings.state.orderBy == id
$(this).addClass 'activeorderby'
return
# add the click event handler to each "order by" item:
# TODO - abstract into Backbone.View
$('.orderbyitem').click (event) ->
id = @id.substr(8)
settings.state.orderBy = id
# $(settings.facetElement).trigger 'facetedsearchorderby', id
settings.state.shownResults = 0
order()
updateResults()
return
# Append deselect filters button
# TODO - abstract into Backbone.View
deselectTemplate = '<div class=deselectstartover>Deselect all filters</div>'
deselect = $(deselectTemplate).click((event) ->
settings.state.filters = {}
jQuery.facetUpdate()
return
)
# Append DESELECT button
# TODO - abstract into Backbone.View
$(bottom).append(deselect)
# $(settings.facetElement).trigger 'facetuicreated'
return
###*
# get a facetname and filtername by the unique id that is created in the beginning
###
getFilterById = (id) ->
result = false
_.each settings.facetCollection, (facet, facetname) ->
_.each facet, (filter, filtername) ->
if filter.id == id
result =
'facetname': facetname
'filtername': filtername
return
return
result
###*
# This function is only called whenever a filter has been added or removed
# It adds a class to the active filters and shows the correct number for each
###
# Updates Facets after results are returned
updateFacetUI = ->
# Compiles listItemTemplate function
itemtemplate = _.template(settings.listItemTemplate)
# Iterates over each facet in @facetCollection
# TODO - abstract into Mn.CollectionView
_.each settings.facetCollection, (facet, facetname) ->
_.each facet, (filter, filtername) ->
# Splits name, handles directories ending with '/'
# TODO - abstract into function
# TODO - abstract into Backbone - FacetChildView, or decorator
splitName = filtername.trim().split('/')
filtername = splitName.pop()
filtername ||= splitName.pop()
# Assembles each item for template compilation
# TODO - remove when Backbone is implemented
item =
id: filter.id
name: filtername
count: filter.count
# Compiles itemTemplate and sets HTML
# TODO - abstract into Backbone - FacetChildView
filteritem = $(itemtemplate(item)).html()
$('#' + filter.id).html(filteritem)
# Sets activeFacet CSS
# TODO - abstract into Backbone - FacetChildView
if settings.state.filters[facetname] and _.indexOf(settings.state.filters[facetname], filtername) >= 0
$('#' + filter.id).addClass('activefacet')
else
$('#' + filter.id).removeClass('activefacet')
# Sets filterCount CSS
# TODO - abstract into Backbone - FacetChildView
if filter.count == 0
$('#' + filter.id).addClass('no-match')
else
$('#' + filter.id).removeClass('no-match')
return
return
# Appends Result Count to page
# TODO - abstract into Backbone View
countHtml = _.template(settings.countTemplate, count: settings.currentResults.length)
$(settings.facetElement + ' .facettotalcount').replaceWith(countHtml)
return
###*
# Updates the the list of results according to the filters that have been set
###
# TODO - abstract into Backbone.View
updateResults = ->
noResults = '<div class=results>Sorry, but no items match these criteria</div>'
# $(settings.resultElement).html if settings.currentResults.length == 0 then noResults else ''
showMoreResults()
return
showMoreResults = ->
`var itemHtml`
# ???
showNowCount = if settings.enablePagination then Math.min(settings.currentResults.length - (settings.state.shownResults), settings.paginationCount) else settings.currentResults.length
itemHtml = ''
# TODO - remove
if settings.beforeResultRender
settings.beforeResultRender()
# Iterates over each shown result
i = settings.state.shownResults
while i < settings.state.shownResults + showNowCount
item = settings.currentResults[i]
# item = $.extend(settings.currentResults[i],
# totalItemNr: i
# batchItemNr: i - (settings.state.shownResults)
# batchItemCount: showNowCount)
if settings.resultTemplateBypass
settings.resultTemplateBypass(item)
i++
# Appends itemHTML
# $(settings.resultElement).append itemHtml
# Append "MoreButton"
showMoreTemplate = '<a id=showmorebutton>Show more</a>'
# TODO - we will _probably_ paginate using BB.Mn
# TODO - pagination
# if !moreButton
# moreButton = $(showMoreTemplate).click(showMoreResults)
# $(settings.resultElement).after moreButton
# # ???/
# if settings.state.shownResults == 0
# moreButton.show()
# # ???
# settings.state.shownResults += showNowCount
# if settings.state.shownResults == settings.currentResults.length
# $(moreButton).hide()
# # Remove
# $(settings.resultElement).trigger 'facetedsearchresultupdate'
# return
jQuery.facetelize =
$.facetelize = (usersettings) ->
# Sets settings, defaults w/ user
$.extend settings, defaults, usersettings
# Stores results of current query
settings.currentResults = []
# Stores facetCollection?
settings.facetCollection = {}
# ????
$(settings.facetElement).data 'settings', settings
# Makes state globally accesssible (debug only)
window.state = settings.state
# Starts engine
initFacetCount()
filter()
order()
updateResults()
createFacetUI()
settings.state
###*
# This is the second function / variable that gets exported into the
# jQuery namespace. Use it to update everything if you messed with
# the settings object
###
jQuery.facetUpdate = ->
filter()
order()
updateFacetUI()
updateResults()
return
# TODO - this must be implemented in a cleaner way
# The 'ENGINE' should operate as its own class with a clearFilters method
jQuery.clearFacets = ->
settings.state.filters = {}
jQuery.facetUpdate()
return
# Shows more results
# moreButton = undefined
return
| 171346 |
###*
# Please note that when passing in custom templates for
# listItemTemplate and orderByTemplate to keep the classes as
# they are used in the code at other locations as well.
###
# TODO - these should be abstracted or removed
defaults =
items: [{a:2,b:1,c:2},{a:2,b:2,c:1},{a:1,b:1,c:1},{a:3,b:3,c:1}],
facets: {'a': 'Title A', 'b': 'Title B', 'c': 'Title C'},
facetElement: '#facets'
listItemTemplate: '<div class="facetitem" id="<%= id %>"><%= name %> <span class="facetitemcount">(<%= count %>)</span></div>'
countTemplate: '<div class=facettotalcount>Results</div>'
resultTemplateBypass: null
orderByOptions:
'a': 'by A'
'b': 'by B'
'RANDOM': 'by random'
state:
orderBy: false
filters: {}
enablePagination: true
paginationCount: 20
###*
# This is the first function / variable that gets exported into the
# jQuery namespace. Pass in your own settings (see above) to initialize
# the faceted search
###
settings = {}
###*
# The following section contains the logic of the faceted search
###
###*
# initializes all facets and their individual filters
###
# Iterate over each facet
# Instantiates empty facet object in facetCollection registry
# TODO - this can be phased out once facetCollection IS a Backbone.Collection
createEmptyFacetCollection = ->
for facet in settings.facets
settings.facetCollection[facet.attribute] = {}
# Sets zero count for all settings.items?
# TODO - rename settings.items
setZeroCounts = ->
# Iterate over each item
for item in settings.items
# Aliases item
item = item.data
# intialize the count to be zero
for facet in settings.facets
# Item[facet] is an array...
if $.isArray(item[facet.attribute])
for facetitem in item[facet.attribute]
if typeof facetitem == 'object'
settings.facetCollection[facet.attribute][facetitem['@id']] = settings.facetCollection[facet.attribute][facetitem['@id']] ||
count: 0
id: _.uniqueId('facet_')
else
settings.facetCollection[facet.attribute][facetitem] = settings.facetCollection[facet.attribute][facetitem] or
count: 0
id: _.uniqueId('facet_')
# IF OBJECT OR @ID
else if typeof(item[facet.attribute]) == 'object' && (item[facet.attribute]['@id'] || item[facet.attribute]['@value'])
# Sets attrKey
attrKey = if item[facet.attribute]['@id'] then '@id' else '@value'
settings.facetCollection[facet.attribute][item[facet.attribute][attrKey]] = settings.facetCollection[facet.attribute][item[facet.attribute][attrKey]] ||
count: 0
id: _.uniqueId('facet_')
# Not an array or object...
else
if item[facet.attribute] != undefined
settings.facetCollection[facet.attribute][item[facet.attribute]] = settings.facetCollection[facet.attribute][item[facet.attribute]] or
count: 0
id: _.uniqueId('facet_')
# SORTS FACET COLLECTION
# TODO - rename?
sortFacetCollection = ->
# sort it:
for facettitle, facet of settings.facetCollection
sorted = _.keys(settings.facetCollection[facettitle]).sort()
if settings.facet_SortOption and settings.facet_SortOption[facettitle]
sorted = _.union(settings.facet_SortOption[facettitle], sorted)
sortedstore = {}
for el in sorted
sortedstore[el] = settings.facetCollection[facettitle][el]
settings.facetCollection[facettitle] = sortedstore
# Sets initial facet counts
initFacetCount = ->
# TODO - phase this out.
createEmptyFacetCollection()
# Set ZERO counts on all settings.items?
setZeroCounts()
# Sorts
sortFacetCollection()
###*
# resets the facet count
###
resetFacetCount = ->
for facetname, items of settings.facetCollection
for itemname, value of items
settings.facetCollection[facetname][itemname].count = 0
###*
# Filters all items from the settings according to the currently
# set filters and stores the results in the settings.currentResults.
# The number of items in each filter from each facet is also updated
###
filterSingleItem = (item) ->
# Bool for _.select / _.filter
filtersApply = true
# Aliases item.data
item = item.data
# Iterates over each filter
for facet, filter of settings.state.filters
# TODO - abstract this elsewhere, repeated
# TODO - document what's happening here
if $.isArray(item[facet])
if item[facet][0] && typeof(item[facet][0]) == 'object'
for f in item[facet]
if filter.length and _.indexOf(filter, f['@id']) == -1
filtersApply = false
else
inters = _.intersection(item[facet], filter)
if inters.length == 0
filtersApply = false
else if typeof(item[facet]) == 'object' && (item[facet]['@id'] || item[facet]['@value'])
# Sets attrKey
attrKey = if item[facet]['@id'] then '@id' else '@value'
if filter.length and _.indexOf(filter, item[facet][attrKey]) == -1
filtersApply = false
else
if filter.length and _.indexOf(filter, item[facet]) == -1
filtersApply = false
return filtersApply
# # # # #
# first apply the filters to the items
applyFilters = ->
settings.currentResults = _.select(settings.items, filterSingleItem)
# # # # #
updateFacetCollection = ->
# then reduce the items to get the current count for each facet
for facet in settings.facets
# Iterates over each currentResult
for item in settings.currentResults
item = item.data
# TODO - abstract this logic elswhere
# TODO - document what's happening here...
if $.isArray(item[facet.attribute])
_.each item[facet.attribute], (facetitem) ->
if typeof(facetitem) == 'object'
settings.facetCollection[facet.attribute][facetitem['@id']].count += 1
else
settings.facetCollection[facet.attribute][facetitem].count += 1
return
else if typeof(item[facet.attribute]) == 'object' && (item[facet.attribute]['@id'] || item[facet.attribute]['@value'])
attrKey = if item[facet.attribute]['@id'] then '@id' else '@value'
if item[facet.attribute][attrKey] != undefined
settings.facetCollection[facet.attribute][item[facet.attribute][attrKey]].count += 1
else
if item[facet.attribute] != undefined
settings.facetCollection[facet.attribute][item[facet.attribute]].count += 1
# # # # #
filter = ->
# Applies filters
applyFilters()
# DEXIE DATABASE CALL
# if (window.global){
# window.dexiePromise = window.global.queryDexie(appliedFilters)
# }
# Update the count for each facet and item:
# intialize the count to be zero
resetFacetCount()
# Updates the facet collection with the results
updateFacetCollection()
# Updates state???
settings.state.shownResults = 0
return
###*
# Orders the currentResults according to the settings.state.orderBy variable
###
order = ->
if settings.state.orderBy
# TODO - abstract into Backbone.View
$('.activeorderby').removeClass 'activeorderby'
$('#orderby_' + settings.state.orderBy).addClass 'activeorderby'
# Applies sort settings
settings.currentResults = _.sortBy settings.currentResults, (item) ->
if settings.state.orderBy == 'RANDOM'
Math.random() * 10000
else
item[settings.state.orderBy]
###*
# The given facetname and filtername are activated or deactivated
# depending on what they were beforehand. This causes the items to
# be filtered again and the UI is updated accordingly.
###
toggleFilter = (key, value) ->
settings.state.filters[key] = settings.state.filters[key] or []
if _.indexOf(settings.state.filters[key], value) == -1
settings.state.filters[key].push value
else
settings.state.filters[key] = _.without(settings.state.filters[key], value)
if settings.state.filters[key].length == 0
delete settings.state.filters[key]
filter()
return
###*
# The following section contains the presentation of the faceted search
###
###*
# This function is only called once, it creates the facets ui.
###
createFacetUI = ->
facetContainer = '<div class=facetsearch id=<%= id %> ></div>'
facetTitleTemplate = '<h3 class=facettitle><i class="icon"></i><%= title %><i class="fa fa-fw help" data-toggle="tooltip" data-placement="right" title="<%= tooltip %>"></i><br><span class="prefix <%= prefix %>"><%= prefix %> : <%= _id %></span></h3>'
facetListContainer = '<div class=facetlist></div>'
# Templates & HTML setup
itemtemplate = _.template(settings.listItemTemplate)
titletemplate = _.template(facetTitleTemplate)
containertemplate = _.template(facetContainer)
$(settings.facetElement).html('')
# Iterates over each setting...
# TODO - this will be replaced by the FACET_GROUP_COLLECTION_VIEW
# Each facet will have pagination, filtering, etc.
for facet in settings.facets
facetHtml = $(containertemplate(id: facet.attribute))
# Assembles facetItem
facetItem =
title: facet.label
tooltip: facet.tooltip
prefix: facet.prefix
_id: facet._id
# ABSTRACTION
# This is where we should collect the GROUPS of facets
# This MAY be accessible outside this little engine, passed in as settings.facets
# console.log(facetItem);
facetItemHtml = $(titletemplate(facetItem))
facetHtml.append facetItemHtml
facetlist = $(facetListContainer)
# Iterates over each filter
# TODO - this will be replaced by the FACET_ITEM_COLLECTION_VIEW
_.each settings.facetCollection[facet.attribute], (filter, filtername) ->
# Splits name, handles directories ending with '/'
# TODO - abstract into function
splitName = filtername.trim().split('/')
filtername = splitName.pop()
filtername ||= splitName.pop()
item =
id: filter.id
name: filtername
count: filter.count
# ABSTRACTION - this is where the INITIAL facets are populated into the UI
# FROM HERE, we start the collection of facet items
# console.log(item);
# Facet filter item CSS state
filteritem = $(itemtemplate(item))
if _.indexOf(settings.state.filters[facet.attribute], filtername) >= 0
filteritem.addClass('activefacet')
if item.count == 0
filteritem.addClass('no-match')
# Appends to list of facetItems
facetlist.append filteritem
return
# Appends HTML
facetHtml.append(facetlist)
$(settings.facetElement).append(facetHtml)
# Tooltips
$('[data-toggle=tooltip]').tooltip()
# # # # # # # # # # # # # # # # # # # #
# TODO - abstract into Backbone.View
# add the click event handler to each facet item:
$('.facetitem').click (event) ->
`var filter`
filter = getFilterById(@id)
toggleFilter(filter.facetname, filter.filtername)
# $(settings.facetElement).trigger 'facetedsearchfacetclick', filter
order()
updateFacetUI()
updateResults()
return
# # # # #
# TODO - ABSTRACT INTO SEPARATE VIEW
# FOR RESULT COUNTR AND ORDER CONTROLS
# Append total result count
bottomContainer = '<div class=bottomline></div>'
bottom = $(bottomContainer)
countHtml = _.template(settings.countTemplate, count: settings.currentResults.length or 0)
$(bottom).append(countHtml)
# generate the "order by" options:
orderByTemplate = '<div class=orderby><span class="orderby-title">Sort by: </span><ul><% _.each(options, function(value, key) { %>' + '<li class=orderbyitem id=orderby_<%= key %>>' + '<%= value %> </li> <% }); %></ul></div>'
ordertemplate = _.template(orderByTemplate)
itemHtml = $(ordertemplate('options': settings.orderByOptions))
$(bottom).append itemHtml
$(settings.facetElement).append bottom
$('.orderbyitem').each ->
id = @id.substr(8)
if settings.state.orderBy == id
$(this).addClass 'activeorderby'
return
# add the click event handler to each "order by" item:
# TODO - abstract into Backbone.View
$('.orderbyitem').click (event) ->
id = @id.substr(8)
settings.state.orderBy = id
# $(settings.facetElement).trigger 'facetedsearchorderby', id
settings.state.shownResults = 0
order()
updateResults()
return
# Append deselect filters button
# TODO - abstract into Backbone.View
deselectTemplate = '<div class=deselectstartover>Deselect all filters</div>'
deselect = $(deselectTemplate).click((event) ->
settings.state.filters = {}
jQuery.facetUpdate()
return
)
# Append DESELECT button
# TODO - abstract into Backbone.View
$(bottom).append(deselect)
# $(settings.facetElement).trigger 'facetuicreated'
return
###*
# get a facetname and filtername by the unique id that is created in the beginning
###
getFilterById = (id) ->
result = false
_.each settings.facetCollection, (facet, facetname) ->
_.each facet, (filter, filtername) ->
if filter.id == id
result =
'facetname': facetname
'filtername': filtername
return
return
result
###*
# This function is only called whenever a filter has been added or removed
# It adds a class to the active filters and shows the correct number for each
###
# Updates Facets after results are returned
updateFacetUI = ->
# Compiles listItemTemplate function
itemtemplate = _.template(settings.listItemTemplate)
# Iterates over each facet in @facetCollection
# TODO - abstract into Mn.CollectionView
_.each settings.facetCollection, (facet, facetname) ->
_.each facet, (filter, filtername) ->
# Splits name, handles directories ending with '/'
# TODO - abstract into function
# TODO - abstract into Backbone - FacetChildView, or decorator
splitName = filtername.trim().split('/')
filtername = splitName.pop()
filtername ||= splitName.pop()
# Assembles each item for template compilation
# TODO - remove when Backbone is implemented
item =
id: filter.id
name: <NAME>name
count: filter.count
# Compiles itemTemplate and sets HTML
# TODO - abstract into Backbone - FacetChildView
filteritem = $(itemtemplate(item)).html()
$('#' + filter.id).html(filteritem)
# Sets activeFacet CSS
# TODO - abstract into Backbone - FacetChildView
if settings.state.filters[facetname] and _.indexOf(settings.state.filters[facetname], filtername) >= 0
$('#' + filter.id).addClass('activefacet')
else
$('#' + filter.id).removeClass('activefacet')
# Sets filterCount CSS
# TODO - abstract into Backbone - FacetChildView
if filter.count == 0
$('#' + filter.id).addClass('no-match')
else
$('#' + filter.id).removeClass('no-match')
return
return
# Appends Result Count to page
# TODO - abstract into Backbone View
countHtml = _.template(settings.countTemplate, count: settings.currentResults.length)
$(settings.facetElement + ' .facettotalcount').replaceWith(countHtml)
return
###*
# Updates the the list of results according to the filters that have been set
###
# TODO - abstract into Backbone.View
updateResults = ->
noResults = '<div class=results>Sorry, but no items match these criteria</div>'
# $(settings.resultElement).html if settings.currentResults.length == 0 then noResults else ''
showMoreResults()
return
showMoreResults = ->
`var itemHtml`
# ???
showNowCount = if settings.enablePagination then Math.min(settings.currentResults.length - (settings.state.shownResults), settings.paginationCount) else settings.currentResults.length
itemHtml = ''
# TODO - remove
if settings.beforeResultRender
settings.beforeResultRender()
# Iterates over each shown result
i = settings.state.shownResults
while i < settings.state.shownResults + showNowCount
item = settings.currentResults[i]
# item = $.extend(settings.currentResults[i],
# totalItemNr: i
# batchItemNr: i - (settings.state.shownResults)
# batchItemCount: showNowCount)
if settings.resultTemplateBypass
settings.resultTemplateBypass(item)
i++
# Appends itemHTML
# $(settings.resultElement).append itemHtml
# Append "MoreButton"
showMoreTemplate = '<a id=showmorebutton>Show more</a>'
# TODO - we will _probably_ paginate using BB.Mn
# TODO - pagination
# if !moreButton
# moreButton = $(showMoreTemplate).click(showMoreResults)
# $(settings.resultElement).after moreButton
# # ???/
# if settings.state.shownResults == 0
# moreButton.show()
# # ???
# settings.state.shownResults += showNowCount
# if settings.state.shownResults == settings.currentResults.length
# $(moreButton).hide()
# # Remove
# $(settings.resultElement).trigger 'facetedsearchresultupdate'
# return
jQuery.facetelize =
$.facetelize = (usersettings) ->
# Sets settings, defaults w/ user
$.extend settings, defaults, usersettings
# Stores results of current query
settings.currentResults = []
# Stores facetCollection?
settings.facetCollection = {}
# ????
$(settings.facetElement).data 'settings', settings
# Makes state globally accesssible (debug only)
window.state = settings.state
# Starts engine
initFacetCount()
filter()
order()
updateResults()
createFacetUI()
settings.state
###*
# This is the second function / variable that gets exported into the
# jQuery namespace. Use it to update everything if you messed with
# the settings object
###
jQuery.facetUpdate = ->
filter()
order()
updateFacetUI()
updateResults()
return
# TODO - this must be implemented in a cleaner way
# The 'ENGINE' should operate as its own class with a clearFilters method
jQuery.clearFacets = ->
settings.state.filters = {}
jQuery.facetUpdate()
return
# Shows more results
# moreButton = undefined
return
| true |
###*
# Please note that when passing in custom templates for
# listItemTemplate and orderByTemplate to keep the classes as
# they are used in the code at other locations as well.
###
# TODO - these should be abstracted or removed
defaults =
items: [{a:2,b:1,c:2},{a:2,b:2,c:1},{a:1,b:1,c:1},{a:3,b:3,c:1}],
facets: {'a': 'Title A', 'b': 'Title B', 'c': 'Title C'},
facetElement: '#facets'
listItemTemplate: '<div class="facetitem" id="<%= id %>"><%= name %> <span class="facetitemcount">(<%= count %>)</span></div>'
countTemplate: '<div class=facettotalcount>Results</div>'
resultTemplateBypass: null
orderByOptions:
'a': 'by A'
'b': 'by B'
'RANDOM': 'by random'
state:
orderBy: false
filters: {}
enablePagination: true
paginationCount: 20
###*
# This is the first function / variable that gets exported into the
# jQuery namespace. Pass in your own settings (see above) to initialize
# the faceted search
###
settings = {}
###*
# The following section contains the logic of the faceted search
###
###*
# initializes all facets and their individual filters
###
# Iterate over each facet
# Instantiates empty facet object in facetCollection registry
# TODO - this can be phased out once facetCollection IS a Backbone.Collection
createEmptyFacetCollection = ->
for facet in settings.facets
settings.facetCollection[facet.attribute] = {}
# Sets zero count for all settings.items?
# TODO - rename settings.items
setZeroCounts = ->
# Iterate over each item
for item in settings.items
# Aliases item
item = item.data
# intialize the count to be zero
for facet in settings.facets
# Item[facet] is an array...
if $.isArray(item[facet.attribute])
for facetitem in item[facet.attribute]
if typeof facetitem == 'object'
settings.facetCollection[facet.attribute][facetitem['@id']] = settings.facetCollection[facet.attribute][facetitem['@id']] ||
count: 0
id: _.uniqueId('facet_')
else
settings.facetCollection[facet.attribute][facetitem] = settings.facetCollection[facet.attribute][facetitem] or
count: 0
id: _.uniqueId('facet_')
# IF OBJECT OR @ID
else if typeof(item[facet.attribute]) == 'object' && (item[facet.attribute]['@id'] || item[facet.attribute]['@value'])
# Sets attrKey
attrKey = if item[facet.attribute]['@id'] then '@id' else '@value'
settings.facetCollection[facet.attribute][item[facet.attribute][attrKey]] = settings.facetCollection[facet.attribute][item[facet.attribute][attrKey]] ||
count: 0
id: _.uniqueId('facet_')
# Not an array or object...
else
if item[facet.attribute] != undefined
settings.facetCollection[facet.attribute][item[facet.attribute]] = settings.facetCollection[facet.attribute][item[facet.attribute]] or
count: 0
id: _.uniqueId('facet_')
# SORTS FACET COLLECTION
# TODO - rename?
sortFacetCollection = ->
# sort it:
for facettitle, facet of settings.facetCollection
sorted = _.keys(settings.facetCollection[facettitle]).sort()
if settings.facet_SortOption and settings.facet_SortOption[facettitle]
sorted = _.union(settings.facet_SortOption[facettitle], sorted)
sortedstore = {}
for el in sorted
sortedstore[el] = settings.facetCollection[facettitle][el]
settings.facetCollection[facettitle] = sortedstore
# Sets initial facet counts
initFacetCount = ->
# TODO - phase this out.
createEmptyFacetCollection()
# Set ZERO counts on all settings.items?
setZeroCounts()
# Sorts
sortFacetCollection()
###*
# resets the facet count
###
resetFacetCount = ->
for facetname, items of settings.facetCollection
for itemname, value of items
settings.facetCollection[facetname][itemname].count = 0
###*
# Filters all items from the settings according to the currently
# set filters and stores the results in the settings.currentResults.
# The number of items in each filter from each facet is also updated
###
filterSingleItem = (item) ->
# Bool for _.select / _.filter
filtersApply = true
# Aliases item.data
item = item.data
# Iterates over each filter
for facet, filter of settings.state.filters
# TODO - abstract this elsewhere, repeated
# TODO - document what's happening here
if $.isArray(item[facet])
if item[facet][0] && typeof(item[facet][0]) == 'object'
for f in item[facet]
if filter.length and _.indexOf(filter, f['@id']) == -1
filtersApply = false
else
inters = _.intersection(item[facet], filter)
if inters.length == 0
filtersApply = false
else if typeof(item[facet]) == 'object' && (item[facet]['@id'] || item[facet]['@value'])
# Sets attrKey
attrKey = if item[facet]['@id'] then '@id' else '@value'
if filter.length and _.indexOf(filter, item[facet][attrKey]) == -1
filtersApply = false
else
if filter.length and _.indexOf(filter, item[facet]) == -1
filtersApply = false
return filtersApply
# # # # #
# first apply the filters to the items
applyFilters = ->
settings.currentResults = _.select(settings.items, filterSingleItem)
# # # # #
updateFacetCollection = ->
# then reduce the items to get the current count for each facet
for facet in settings.facets
# Iterates over each currentResult
for item in settings.currentResults
item = item.data
# TODO - abstract this logic elswhere
# TODO - document what's happening here...
if $.isArray(item[facet.attribute])
_.each item[facet.attribute], (facetitem) ->
if typeof(facetitem) == 'object'
settings.facetCollection[facet.attribute][facetitem['@id']].count += 1
else
settings.facetCollection[facet.attribute][facetitem].count += 1
return
else if typeof(item[facet.attribute]) == 'object' && (item[facet.attribute]['@id'] || item[facet.attribute]['@value'])
attrKey = if item[facet.attribute]['@id'] then '@id' else '@value'
if item[facet.attribute][attrKey] != undefined
settings.facetCollection[facet.attribute][item[facet.attribute][attrKey]].count += 1
else
if item[facet.attribute] != undefined
settings.facetCollection[facet.attribute][item[facet.attribute]].count += 1
# # # # #
filter = ->
# Applies filters
applyFilters()
# DEXIE DATABASE CALL
# if (window.global){
# window.dexiePromise = window.global.queryDexie(appliedFilters)
# }
# Update the count for each facet and item:
# intialize the count to be zero
resetFacetCount()
# Updates the facet collection with the results
updateFacetCollection()
# Updates state???
settings.state.shownResults = 0
return
###*
# Orders the currentResults according to the settings.state.orderBy variable
###
order = ->
if settings.state.orderBy
# TODO - abstract into Backbone.View
$('.activeorderby').removeClass 'activeorderby'
$('#orderby_' + settings.state.orderBy).addClass 'activeorderby'
# Applies sort settings
settings.currentResults = _.sortBy settings.currentResults, (item) ->
if settings.state.orderBy == 'RANDOM'
Math.random() * 10000
else
item[settings.state.orderBy]
###*
# The given facetname and filtername are activated or deactivated
# depending on what they were beforehand. This causes the items to
# be filtered again and the UI is updated accordingly.
###
toggleFilter = (key, value) ->
settings.state.filters[key] = settings.state.filters[key] or []
if _.indexOf(settings.state.filters[key], value) == -1
settings.state.filters[key].push value
else
settings.state.filters[key] = _.without(settings.state.filters[key], value)
if settings.state.filters[key].length == 0
delete settings.state.filters[key]
filter()
return
###*
# The following section contains the presentation of the faceted search
###
###*
# This function is only called once, it creates the facets ui.
###
createFacetUI = ->
facetContainer = '<div class=facetsearch id=<%= id %> ></div>'
facetTitleTemplate = '<h3 class=facettitle><i class="icon"></i><%= title %><i class="fa fa-fw help" data-toggle="tooltip" data-placement="right" title="<%= tooltip %>"></i><br><span class="prefix <%= prefix %>"><%= prefix %> : <%= _id %></span></h3>'
facetListContainer = '<div class=facetlist></div>'
# Templates & HTML setup
itemtemplate = _.template(settings.listItemTemplate)
titletemplate = _.template(facetTitleTemplate)
containertemplate = _.template(facetContainer)
$(settings.facetElement).html('')
# Iterates over each setting...
# TODO - this will be replaced by the FACET_GROUP_COLLECTION_VIEW
# Each facet will have pagination, filtering, etc.
for facet in settings.facets
facetHtml = $(containertemplate(id: facet.attribute))
# Assembles facetItem
facetItem =
title: facet.label
tooltip: facet.tooltip
prefix: facet.prefix
_id: facet._id
# ABSTRACTION
# This is where we should collect the GROUPS of facets
# This MAY be accessible outside this little engine, passed in as settings.facets
# console.log(facetItem);
facetItemHtml = $(titletemplate(facetItem))
facetHtml.append facetItemHtml
facetlist = $(facetListContainer)
# Iterates over each filter
# TODO - this will be replaced by the FACET_ITEM_COLLECTION_VIEW
_.each settings.facetCollection[facet.attribute], (filter, filtername) ->
# Splits name, handles directories ending with '/'
# TODO - abstract into function
splitName = filtername.trim().split('/')
filtername = splitName.pop()
filtername ||= splitName.pop()
item =
id: filter.id
name: filtername
count: filter.count
# ABSTRACTION - this is where the INITIAL facets are populated into the UI
# FROM HERE, we start the collection of facet items
# console.log(item);
# Facet filter item CSS state
filteritem = $(itemtemplate(item))
if _.indexOf(settings.state.filters[facet.attribute], filtername) >= 0
filteritem.addClass('activefacet')
if item.count == 0
filteritem.addClass('no-match')
# Appends to list of facetItems
facetlist.append filteritem
return
# Appends HTML
facetHtml.append(facetlist)
$(settings.facetElement).append(facetHtml)
# Tooltips
$('[data-toggle=tooltip]').tooltip()
# # # # # # # # # # # # # # # # # # # #
# TODO - abstract into Backbone.View
# add the click event handler to each facet item:
$('.facetitem').click (event) ->
`var filter`
filter = getFilterById(@id)
toggleFilter(filter.facetname, filter.filtername)
# $(settings.facetElement).trigger 'facetedsearchfacetclick', filter
order()
updateFacetUI()
updateResults()
return
# # # # #
# TODO - ABSTRACT INTO SEPARATE VIEW
# FOR RESULT COUNTR AND ORDER CONTROLS
# Append total result count
bottomContainer = '<div class=bottomline></div>'
bottom = $(bottomContainer)
countHtml = _.template(settings.countTemplate, count: settings.currentResults.length or 0)
$(bottom).append(countHtml)
# generate the "order by" options:
orderByTemplate = '<div class=orderby><span class="orderby-title">Sort by: </span><ul><% _.each(options, function(value, key) { %>' + '<li class=orderbyitem id=orderby_<%= key %>>' + '<%= value %> </li> <% }); %></ul></div>'
ordertemplate = _.template(orderByTemplate)
itemHtml = $(ordertemplate('options': settings.orderByOptions))
$(bottom).append itemHtml
$(settings.facetElement).append bottom
$('.orderbyitem').each ->
id = @id.substr(8)
if settings.state.orderBy == id
$(this).addClass 'activeorderby'
return
# add the click event handler to each "order by" item:
# TODO - abstract into Backbone.View
$('.orderbyitem').click (event) ->
id = @id.substr(8)
settings.state.orderBy = id
# $(settings.facetElement).trigger 'facetedsearchorderby', id
settings.state.shownResults = 0
order()
updateResults()
return
# Append deselect filters button
# TODO - abstract into Backbone.View
deselectTemplate = '<div class=deselectstartover>Deselect all filters</div>'
deselect = $(deselectTemplate).click((event) ->
settings.state.filters = {}
jQuery.facetUpdate()
return
)
# Append DESELECT button
# TODO - abstract into Backbone.View
$(bottom).append(deselect)
# $(settings.facetElement).trigger 'facetuicreated'
return
###*
# get a facetname and filtername by the unique id that is created in the beginning
###
getFilterById = (id) ->
result = false
_.each settings.facetCollection, (facet, facetname) ->
_.each facet, (filter, filtername) ->
if filter.id == id
result =
'facetname': facetname
'filtername': filtername
return
return
result
###*
# This function is only called whenever a filter has been added or removed
# It adds a class to the active filters and shows the correct number for each
###
# Updates Facets after results are returned
updateFacetUI = ->
# Compiles listItemTemplate function
itemtemplate = _.template(settings.listItemTemplate)
# Iterates over each facet in @facetCollection
# TODO - abstract into Mn.CollectionView
_.each settings.facetCollection, (facet, facetname) ->
_.each facet, (filter, filtername) ->
# Splits name, handles directories ending with '/'
# TODO - abstract into function
# TODO - abstract into Backbone - FacetChildView, or decorator
splitName = filtername.trim().split('/')
filtername = splitName.pop()
filtername ||= splitName.pop()
# Assembles each item for template compilation
# TODO - remove when Backbone is implemented
item =
id: filter.id
name: PI:NAME:<NAME>END_PIname
count: filter.count
# Compiles itemTemplate and sets HTML
# TODO - abstract into Backbone - FacetChildView
filteritem = $(itemtemplate(item)).html()
$('#' + filter.id).html(filteritem)
# Sets activeFacet CSS
# TODO - abstract into Backbone - FacetChildView
if settings.state.filters[facetname] and _.indexOf(settings.state.filters[facetname], filtername) >= 0
$('#' + filter.id).addClass('activefacet')
else
$('#' + filter.id).removeClass('activefacet')
# Sets filterCount CSS
# TODO - abstract into Backbone - FacetChildView
if filter.count == 0
$('#' + filter.id).addClass('no-match')
else
$('#' + filter.id).removeClass('no-match')
return
return
# Appends Result Count to page
# TODO - abstract into Backbone View
countHtml = _.template(settings.countTemplate, count: settings.currentResults.length)
$(settings.facetElement + ' .facettotalcount').replaceWith(countHtml)
return
###*
# Updates the the list of results according to the filters that have been set
###
# TODO - abstract into Backbone.View
updateResults = ->
noResults = '<div class=results>Sorry, but no items match these criteria</div>'
# $(settings.resultElement).html if settings.currentResults.length == 0 then noResults else ''
showMoreResults()
return
showMoreResults = ->
`var itemHtml`
# ???
showNowCount = if settings.enablePagination then Math.min(settings.currentResults.length - (settings.state.shownResults), settings.paginationCount) else settings.currentResults.length
itemHtml = ''
# TODO - remove
if settings.beforeResultRender
settings.beforeResultRender()
# Iterates over each shown result
i = settings.state.shownResults
while i < settings.state.shownResults + showNowCount
item = settings.currentResults[i]
# item = $.extend(settings.currentResults[i],
# totalItemNr: i
# batchItemNr: i - (settings.state.shownResults)
# batchItemCount: showNowCount)
if settings.resultTemplateBypass
settings.resultTemplateBypass(item)
i++
# Appends itemHTML
# $(settings.resultElement).append itemHtml
# Append "MoreButton"
showMoreTemplate = '<a id=showmorebutton>Show more</a>'
# TODO - we will _probably_ paginate using BB.Mn
# TODO - pagination
# if !moreButton
# moreButton = $(showMoreTemplate).click(showMoreResults)
# $(settings.resultElement).after moreButton
# # ???/
# if settings.state.shownResults == 0
# moreButton.show()
# # ???
# settings.state.shownResults += showNowCount
# if settings.state.shownResults == settings.currentResults.length
# $(moreButton).hide()
# # Remove
# $(settings.resultElement).trigger 'facetedsearchresultupdate'
# return
jQuery.facetelize =
$.facetelize = (usersettings) ->
# Sets settings, defaults w/ user
$.extend settings, defaults, usersettings
# Stores results of current query
settings.currentResults = []
# Stores facetCollection?
settings.facetCollection = {}
# ????
$(settings.facetElement).data 'settings', settings
# Makes state globally accesssible (debug only)
window.state = settings.state
# Starts engine
initFacetCount()
filter()
order()
updateResults()
createFacetUI()
settings.state
###*
# This is the second function / variable that gets exported into the
# jQuery namespace. Use it to update everything if you messed with
# the settings object
###
jQuery.facetUpdate = ->
filter()
order()
updateFacetUI()
updateResults()
return
# TODO - this must be implemented in a cleaner way
# The 'ENGINE' should operate as its own class with a clearFilters method
jQuery.clearFacets = ->
settings.state.filters = {}
jQuery.facetUpdate()
return
# Shows more results
# moreButton = undefined
return
|
[
{
"context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public Li",
"end": 43,
"score": 0.9999133944511414,
"start": 29,
"tag": "EMAIL",
"value": "contact@ppy.sh"
}
] | resources/assets/coffee/react/_components/value-display.coffee | osu-katakuna/osu-katakuna-web | 5 | # Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
# See the LICENCE file in the repository root for full licence text.
import * as React from 'react'
import { div } from 'react-dom-factories'
bn = 'value-display'
export ValueDisplay = ({label, value, description, modifiers}) ->
div
className: osu.classWithModifiers(bn, modifiers)
div className: "#{bn}__label", label
div className: "#{bn}__value", value
if description?
div className: "#{bn}__description", description
| 202142 | # Copyright (c) ppy Pty Ltd <<EMAIL>>. Licensed under the GNU Affero General Public License v3.0.
# See the LICENCE file in the repository root for full licence text.
import * as React from 'react'
import { div } from 'react-dom-factories'
bn = 'value-display'
export ValueDisplay = ({label, value, description, modifiers}) ->
div
className: osu.classWithModifiers(bn, modifiers)
div className: "#{bn}__label", label
div className: "#{bn}__value", value
if description?
div className: "#{bn}__description", description
| true | # Copyright (c) ppy Pty Ltd <PI:EMAIL:<EMAIL>END_PI>. Licensed under the GNU Affero General Public License v3.0.
# See the LICENCE file in the repository root for full licence text.
import * as React from 'react'
import { div } from 'react-dom-factories'
bn = 'value-display'
export ValueDisplay = ({label, value, description, modifiers}) ->
div
className: osu.classWithModifiers(bn, modifiers)
div className: "#{bn}__label", label
div className: "#{bn}__value", value
if description?
div className: "#{bn}__description", description
|
[
{
"context": "#########################\n#\n# Mooqita\n# Created by Markus on 23/10/2016.\n#\n################################",
"end": 87,
"score": 0.9997142553329468,
"start": 81,
"tag": "NAME",
"value": "Markus"
}
] | both/1_init/collections.coffee | MooqitaSFH/worklearn | 0 | #######################################################
#
# Mooqita
# Created by Markus on 23/10/2016.
#
#######################################################
#######################################################
@Permissions = new Mongo.Collection("permissions")
@Admissions = new Mongo.Collection("admissions")
@Admin = new Mongo.Collection("admin")
#######################################################
@Recommendations = new Mongo.Collection("recommendations")
@Organizations = new Mongo.Collection("organizations")
@Invitations = new Mongo.Collection("invitations")
@Challenges = new Mongo.Collection("challenges")
@Questions = new Mongo.Collection("questions")
@Solutions = new Mongo.Collection("solutions")
@Feedback = new Mongo.Collection("feedback")
@Profiles = new Mongo.Collection("profiles")
@Messages = new Mongo.Collection("messages")
@Modules = new Mongo.Collection("modules")
@Reviews = new Mongo.Collection("reviews")
@Posts = new Mongo.Collection("posts")
@Jobs = new Mongo.Collection("jobs")
#######################################################
@PoolChallenges = new Mongo.Collection("pool_challenges")
#######################################################
@ChallengeSummaries = new Mongo.Collection("challenge_summaries")
#######################################################
@UserSummaries = new Mongo.Collection("user_summaries")
@UserResumes = new Mongo.Collection("user_resumes")
@TeamMembers = new Mongo.Collection("team_members")
#######################################################
@EduCertTemplate = new Mongo.Collection("edu_cert_templates")
@EduCertAssertions = new Mongo.Collection("edu_cert_assertions")
@EduCertRecipients = new Mongo.Collection("edu_cert_recipients")
| 178884 | #######################################################
#
# Mooqita
# Created by <NAME> on 23/10/2016.
#
#######################################################
#######################################################
@Permissions = new Mongo.Collection("permissions")
@Admissions = new Mongo.Collection("admissions")
@Admin = new Mongo.Collection("admin")
#######################################################
@Recommendations = new Mongo.Collection("recommendations")
@Organizations = new Mongo.Collection("organizations")
@Invitations = new Mongo.Collection("invitations")
@Challenges = new Mongo.Collection("challenges")
@Questions = new Mongo.Collection("questions")
@Solutions = new Mongo.Collection("solutions")
@Feedback = new Mongo.Collection("feedback")
@Profiles = new Mongo.Collection("profiles")
@Messages = new Mongo.Collection("messages")
@Modules = new Mongo.Collection("modules")
@Reviews = new Mongo.Collection("reviews")
@Posts = new Mongo.Collection("posts")
@Jobs = new Mongo.Collection("jobs")
#######################################################
@PoolChallenges = new Mongo.Collection("pool_challenges")
#######################################################
@ChallengeSummaries = new Mongo.Collection("challenge_summaries")
#######################################################
@UserSummaries = new Mongo.Collection("user_summaries")
@UserResumes = new Mongo.Collection("user_resumes")
@TeamMembers = new Mongo.Collection("team_members")
#######################################################
@EduCertTemplate = new Mongo.Collection("edu_cert_templates")
@EduCertAssertions = new Mongo.Collection("edu_cert_assertions")
@EduCertRecipients = new Mongo.Collection("edu_cert_recipients")
| true | #######################################################
#
# Mooqita
# Created by PI:NAME:<NAME>END_PI on 23/10/2016.
#
#######################################################
#######################################################
@Permissions = new Mongo.Collection("permissions")
@Admissions = new Mongo.Collection("admissions")
@Admin = new Mongo.Collection("admin")
#######################################################
@Recommendations = new Mongo.Collection("recommendations")
@Organizations = new Mongo.Collection("organizations")
@Invitations = new Mongo.Collection("invitations")
@Challenges = new Mongo.Collection("challenges")
@Questions = new Mongo.Collection("questions")
@Solutions = new Mongo.Collection("solutions")
@Feedback = new Mongo.Collection("feedback")
@Profiles = new Mongo.Collection("profiles")
@Messages = new Mongo.Collection("messages")
@Modules = new Mongo.Collection("modules")
@Reviews = new Mongo.Collection("reviews")
@Posts = new Mongo.Collection("posts")
@Jobs = new Mongo.Collection("jobs")
#######################################################
@PoolChallenges = new Mongo.Collection("pool_challenges")
#######################################################
@ChallengeSummaries = new Mongo.Collection("challenge_summaries")
#######################################################
@UserSummaries = new Mongo.Collection("user_summaries")
@UserResumes = new Mongo.Collection("user_resumes")
@TeamMembers = new Mongo.Collection("team_members")
#######################################################
@EduCertTemplate = new Mongo.Collection("edu_cert_templates")
@EduCertAssertions = new Mongo.Collection("edu_cert_assertions")
@EduCertRecipients = new Mongo.Collection("edu_cert_recipients")
|
[
{
"context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission",
"end": 18,
"score": 0.998796284198761,
"start": 12,
"tag": "NAME",
"value": "Joyent"
}
] | lib/_tls_legacy.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.
SlabBuffer = ->
@create()
return
# Base class of both CleartextStream and EncryptedStream
CryptoStream = (pair, options) ->
stream.Duplex.call this, options
@pair = pair
@_pending = null
@_pendingEncoding = ""
@_pendingCallback = null
@_doneFlag = false
@_retryAfterPartial = false
@_halfRead = false
@_sslOutCb = null
@_resumingSession = false
@_reading = true
@_destroyed = false
@_ended = false
@_finished = false
@_opposite = null
slabBuffer = new SlabBuffer() if util.isNull(slabBuffer)
@_buffer = slabBuffer
@once "finish", onCryptoStreamFinish
# net.Socket calls .onend too
@once "end", onCryptoStreamEnd
return
onCryptoStreamFinish = ->
@_finished = true
if this is @pair.cleartext
debug "cleartext.onfinish"
if @pair.ssl
# Generate close notify
# NOTE: first call checks if client has sent us shutdown,
# second call enqueues shutdown into the BIO.
if @pair.ssl.shutdown() isnt 1
return @pair.error() if @pair.ssl and @pair.ssl.error
@pair.ssl.shutdown()
return @pair.error() if @pair.ssl and @pair.ssl.error
else
debug "encrypted.onfinish"
# Try to read just to get sure that we won't miss EOF
@_opposite.read 0 if @_opposite.readable
if @_opposite._ended
@_done()
# No half-close, sorry
@_opposite._done() if this is @pair.cleartext
return
onCryptoStreamEnd = ->
@_ended = true
if this is @pair.cleartext
debug "cleartext.onend"
else
debug "encrypted.onend"
return
# NOTE: Called once `this._opposite` is set.
# Black-hole data
# When resuming session don't accept any new data.
# And do not put too much data into openssl, before writing it from encrypted
# side.
#
# TODO(indutny): Remove magic number, use watermark based limits
# Write current buffer now
# Handle and report errors
# Force SSL_read call to cycle some states/data inside OpenSSL
# Cycle encrypted data
# Get NPN and Server name when ready
# Whole buffer was written
# Invoke callback only when all data read from opposite stream
# Force SSL_read call to cycle some states/data inside OpenSSL
# No write has happened
# XXX: EOF?!
# Wait for session to be resumed
# Mark that we're done reading, but don't provide data or EOF
# Handle and report errors
# Get NPN and Server name when ready
# Create new buffer if previous was filled up
# Try writing pending data
# EOF when cleartext has finished and we have nothing to read
# Perform graceful shutdown
# No half-open, sorry!
# EOF
# EOF
# Bail out
# Give them requested data
# Let users know that we've some internal data to read
# Smart check to avoid invoking 'sslOutEnd' in the most of the cases
# Notify listeners about internal data end
# Write pending data first
# Wait for both `finish` and `end` events to ensure that all data that
# was written on this side was read from the other side.
# Destroy both ends
# Force EOF
# Emit 'close' event
# If both streams are done:
# readyState is deprecated. Don't use it.
CleartextStream = (pair, options) ->
CryptoStream.call this, pair, options
# This is a fake kludge to support how the http impl sits
# on top of net Sockets
self = this
@_handle =
readStop: ->
self._reading = false
return
readStart: ->
return if self._reading and self._readableState.length > 0
self._reading = true
self.read 0
self._opposite.read 0 if self._opposite.readable
return
return
EncryptedStream = (pair, options) ->
CryptoStream.call this, pair, options
return
onhandshakestart = ->
debug "onhandshakestart"
self = this
ssl = self.ssl
now = Timer.now()
assert now >= ssl.lastHandshakeTime
ssl.handshakes = 0 if (now - ssl.lastHandshakeTime) >= tls.CLIENT_RENEG_WINDOW * 1000
first = (ssl.lastHandshakeTime is 0)
ssl.lastHandshakeTime = now
return if first
if ++ssl.handshakes > tls.CLIENT_RENEG_LIMIT
# Defer the error event to the next tick. We're being called from OpenSSL's
# state machine and OpenSSL is not re-entrant. We cannot allow the user's
# callback to destroy the connection right now, it would crash and burn.
setImmediate ->
err = new Error("TLS session renegotiation attack detected.")
self.cleartext.emit "error", err if self.cleartext
return
return
onhandshakedone = ->
# for future use
debug "onhandshakedone"
return
onclienthello = (hello) ->
callback = (err, session) ->
return if once
once = true
return self.socket.destroy(err) if err
self.ssl.loadSession session
self.ssl.endParser()
# Cycle data
self._resumingSession = false
self.cleartext.read 0
self.encrypted.read 0
return
self = this
once = false
@_resumingSession = true
callback null, null if hello.sessionId.length <= 0 or not @server or not @server.emit("resumeSession", hello.sessionId, callback)
return
onnewsession = (key, session) ->
done = ->
return if once
once = true
self.ssl.newSessionDone() if self.ssl
return
return unless @server
self = this
once = false
done() unless self.server.emit("newSession", key, session, done)
return
onocspresponse = (resp) ->
@emit "OCSPResponse", resp
return
###*
Provides a pair of streams to do encrypted communication.
###
SecurePair = (context, isServer, requestCert, rejectUnauthorized, options) ->
return new SecurePair(context, isServer, requestCert, rejectUnauthorized, options) unless this instanceof SecurePair
self = this
options or (options = {})
events.EventEmitter.call this
@server = options.server
@_secureEstablished = false
@_isServer = (if isServer then true else false)
@_encWriteState = true
@_clearWriteState = true
@_doneFlag = false
@_destroying = false
unless context
@credentials = tls.createSecureContext()
else
@credentials = context
# For clients, we will always have either a given ca list or be using
# default one
requestCert = true unless @_isServer
@_rejectUnauthorized = (if rejectUnauthorized then true else false)
@_requestCert = (if requestCert then true else false)
@ssl = new Connection(@credentials.context, (if @_isServer then true else false), (if @_isServer then @_requestCert else options.servername), @_rejectUnauthorized)
if @_isServer
@ssl.onhandshakestart = onhandshakestart.bind(this)
@ssl.onhandshakedone = onhandshakedone.bind(this)
@ssl.onclienthello = onclienthello.bind(this)
@ssl.onnewsession = onnewsession.bind(this)
@ssl.lastHandshakeTime = 0
@ssl.handshakes = 0
else
@ssl.onocspresponse = onocspresponse.bind(this)
if process.features.tls_sni
@ssl.setSNICallback options.SNICallback if @_isServer and options.SNICallback
@servername = null
if process.features.tls_npn and options.NPNProtocols
@ssl.setNPNProtocols options.NPNProtocols
@npnProtocol = null
# Acts as a r/w stream to the cleartext side of the stream.
@cleartext = new CleartextStream(this, options.cleartext)
# Acts as a r/w stream to the encrypted side of the stream.
@encrypted = new EncryptedStream(this, options.encrypted)
# Let streams know about each other
@cleartext._opposite = @encrypted
@encrypted._opposite = @cleartext
@cleartext.init()
@encrypted.init()
process.nextTick ->
# The Connection may be destroyed by an abort call
if self.ssl
self.ssl.start()
self.ssl.requestOCSP() if options.requestOCSP
# In case of cipher suite failures - SSL_accept/SSL_connect may fail
self.error() if self.ssl and self.ssl.error
return
return
"use strict"
assert = require("assert")
events = require("events")
stream = require("stream")
tls = require("tls")
util = require("util")
common = require("_tls_common")
Timer = process.binding("timer_wrap").Timer
Connection = null
try
Connection = process.binding("crypto").Connection
catch e
throw new Error("node.js not compiled with openssl crypto support.")
debug = util.debuglog("tls-legacy")
SlabBuffer::create = create = ->
@isFull = false
@pool = new Buffer(tls.SLAB_BUFFER_SIZE)
@offset = 0
@remaining = @pool.length
return
SlabBuffer::use = use = (context, fn, size) ->
if @remaining is 0
@isFull = true
return 0
actualSize = @remaining
actualSize = Math.min(size, actualSize) unless util.isNull(size)
bytes = fn.call(context, @pool, @offset, actualSize)
if bytes > 0
@offset += bytes
@remaining -= bytes
assert @remaining >= 0
bytes
slabBuffer = null
util.inherits CryptoStream, stream.Duplex
CryptoStream::init = init = ->
self = this
@_opposite.on "sslOutEnd", ->
if self._sslOutCb
cb = self._sslOutCb
self._sslOutCb = null
cb null
return
return
CryptoStream::_write = write = (data, encoding, cb) ->
assert util.isNull(@_pending)
return cb(null) unless @pair.ssl
if not @_resumingSession and @_opposite._internallyPendingBytes() < 128 * 1024
written = undefined
if this is @pair.cleartext
debug "cleartext.write called with %d bytes", data.length
written = @pair.ssl.clearIn(data, 0, data.length)
else
debug "encrypted.write called with %d bytes", data.length
written = @pair.ssl.encIn(data, 0, data.length)
return cb(@pair.error(true)) if @pair.ssl and @pair.ssl.error
@pair.cleartext.read 0
@pair.encrypted.read 0 if @pair.encrypted._internallyPendingBytes()
@pair.maybeInitFinished()
if written is data.length
if this is @pair.cleartext
debug "cleartext.write succeed with " + written + " bytes"
else
debug "encrypted.write succeed with " + written + " bytes"
if @_opposite._halfRead
assert util.isNull(@_sslOutCb)
@_sslOutCb = cb
else
cb null
return
else if written isnt 0 and written isnt -1
assert not @_retryAfterPartial
@_retryAfterPartial = true
@_write data.slice(written), encoding, cb
@_retryAfterPartial = false
return
else
debug "cleartext.write queue is full"
@pair.cleartext.read 0
@_pending = data
@_pendingEncoding = encoding
@_pendingCallback = cb
if this is @pair.cleartext
debug "cleartext.write queued with %d bytes", data.length
else
debug "encrypted.write queued with %d bytes", data.length
return
CryptoStream::_writePending = writePending = ->
data = @_pending
encoding = @_pendingEncoding
cb = @_pendingCallback
@_pending = null
@_pendingEncoding = ""
@_pendingCallback = null
@_write data, encoding, cb
return
CryptoStream::_read = read = (size) ->
return @push(null) unless @pair.ssl
return @push("") if @_resumingSession or not @_reading
out = undefined
if this is @pair.cleartext
debug "cleartext.read called with %d bytes", size
out = @pair.ssl.clearOut
else
debug "encrypted.read called with %d bytes", size
out = @pair.ssl.encOut
bytesRead = 0
start = @_buffer.offset
last = start
loop
assert last is @_buffer.offset
read = @_buffer.use(@pair.ssl, out, size - bytesRead)
bytesRead += read if read > 0
last = @_buffer.offset
if @pair.ssl and @pair.ssl.error
@pair.error()
break
break unless read > 0 and not @_buffer.isFull and bytesRead < size and @pair.ssl isnt null
@pair.maybeInitFinished()
pool = @_buffer.pool
@_buffer.create() if @_buffer.isFull
assert bytesRead >= 0
if this is @pair.cleartext
debug "cleartext.read succeed with %d bytes", bytesRead
else
debug "encrypted.read succeed with %d bytes", bytesRead
@_writePending() unless util.isNull(@_pending)
@_opposite._writePending() unless util.isNull(@_opposite._pending)
if bytesRead is 0
if @_opposite._finished and @_internallyPendingBytes() is 0 or @pair.ssl and @pair.ssl.receivedShutdown
@_done()
if this is @pair.cleartext
@_opposite._done()
@push null
else @push null if not @pair.ssl or not @pair.ssl.receivedShutdown
else
@push ""
else
@push pool.slice(start, start + bytesRead)
halfRead = @_internallyPendingBytes() isnt 0
if @_halfRead isnt halfRead
@_halfRead = halfRead
unless halfRead
if this is @pair.cleartext
debug "cleartext.sslOutEnd"
else
debug "encrypted.sslOutEnd"
@emit "sslOutEnd"
return
CryptoStream::setTimeout = (timeout, callback) ->
@socket.setTimeout timeout, callback if @socket
return
CryptoStream::setNoDelay = (noDelay) ->
@socket.setNoDelay noDelay if @socket
return
CryptoStream::setKeepAlive = (enable, initialDelay) ->
@socket.setKeepAlive enable, initialDelay if @socket
return
CryptoStream::__defineGetter__ "bytesWritten", ->
(if @socket then @socket.bytesWritten else 0)
CryptoStream::getPeerCertificate = (detailed) ->
return common.translatePeerCertificate(@pair.ssl.getPeerCertificate(detailed)) if @pair.ssl
null
CryptoStream::getSession = ->
return @pair.ssl.getSession() if @pair.ssl
null
CryptoStream::isSessionReused = ->
return @pair.ssl.isSessionReused() if @pair.ssl
null
CryptoStream::getCipher = (err) ->
if @pair.ssl
@pair.ssl.getCurrentCipher()
else
null
CryptoStream::end = (chunk, encoding) ->
if this is @pair.cleartext
debug "cleartext.end"
else
debug "encrypted.end"
@_writePending() unless util.isNull(@_pending)
@writable = false
stream.Duplex::end.call this, chunk, encoding
return
CryptoStream::destroySoon = (err) ->
if this is @pair.cleartext
debug "cleartext.destroySoon"
else
debug "encrypted.destroySoon"
@end() if @writable
if @_writableState.finished and @_opposite._ended
@destroy()
else
self = this
waiting = 1
finish = ->
self.destroy() if --waiting is 0
return
@_opposite.once "end", finish
unless @_finished
@once "finish", finish
++waiting
return
CryptoStream::destroy = (err) ->
return if @_destroyed
@_destroyed = true
@readable = @writable = false
if this is @pair.cleartext
debug "cleartext.destroy"
else
debug "encrypted.destroy"
@_opposite.destroy()
self = this
process.nextTick ->
self.push null
self.emit "close", (if err then true else false)
return
return
CryptoStream::_done = ->
@_doneFlag = true
return @pair.error() if this is @pair.encrypted and not @pair._secureEstablished
@pair.destroy() if @pair.cleartext._doneFlag and @pair.encrypted._doneFlag and not @pair._doneFlag
return
Object.defineProperty CryptoStream::, "readyState",
get: ->
if @_connecting
"opening"
else if @readable and @writable
"open"
else if @readable and not @writable
"readOnly"
else if not @readable and @writable
"writeOnly"
else
"closed"
util.inherits CleartextStream, CryptoStream
CleartextStream::_internallyPendingBytes = ->
if @pair.ssl
@pair.ssl.clearPending()
else
0
CleartextStream::address = ->
@socket and @socket.address()
CleartextStream::__defineGetter__ "remoteAddress", ->
@socket and @socket.remoteAddress
CleartextStream::__defineGetter__ "remoteFamily", ->
@socket and @socket.remoteFamily
CleartextStream::__defineGetter__ "remotePort", ->
@socket and @socket.remotePort
CleartextStream::__defineGetter__ "localAddress", ->
@socket and @socket.localAddress
CleartextStream::__defineGetter__ "localPort", ->
@socket and @socket.localPort
util.inherits EncryptedStream, CryptoStream
EncryptedStream::_internallyPendingBytes = ->
if @pair.ssl
@pair.ssl.encPending()
else
0
util.inherits SecurePair, events.EventEmitter
exports.createSecurePair = (context, isServer, requestCert, rejectUnauthorized) ->
pair = new SecurePair(context, isServer, requestCert, rejectUnauthorized)
pair
SecurePair::maybeInitFinished = ->
if @ssl and not @_secureEstablished and @ssl.isInitFinished()
@npnProtocol = @ssl.getNegotiatedProtocol() if process.features.tls_npn
@servername = @ssl.getServername() if process.features.tls_sni
@_secureEstablished = true
debug "secure established"
@emit "secure"
return
SecurePair::destroy = ->
return if @_destroying
unless @_doneFlag
debug "SecurePair.destroy"
@_destroying = true
# SecurePair should be destroyed only after it's streams
@cleartext.destroy()
@encrypted.destroy()
@_doneFlag = true
@ssl.error = null
@ssl.close()
@ssl = null
return
SecurePair::error = (returnOnly) ->
err = @ssl.error
@ssl.error = null
unless @_secureEstablished
# Emit ECONNRESET instead of zero return
if not err or err.message is "ZERO_RETURN"
connReset = new Error("socket hang up")
connReset.code = "ECONNRESET"
connReset.sslError = err and err.message
err = connReset
@destroy()
@emit "error", err unless returnOnly
else if @_isServer and @_rejectUnauthorized and /peer did not return a certificate/.test(err.message)
# Not really an error.
@destroy()
else
@cleartext.emit "error", err unless returnOnly
err
exports.pipe = pipe = (pair, socket) ->
# Encrypted should be unpiped from socket to prevent possible
# write after destroy.
# cycle the data whenever the socket drains, so that
# we can pull some more into it. normally this would
# be handled by the fact that pipe() triggers read() calls
# on writable.drain, but CryptoStreams are a bit more
# complicated. Since the encrypted side actually gets
# its data from the cleartext side, we have to give it a
# light kick to get in motion again.
onerror = (e) ->
cleartext.emit "error", e if cleartext._controlReleased
return
onclose = ->
socket.removeListener "error", onerror
socket.removeListener "timeout", ontimeout
return
ontimeout = ->
cleartext.emit "timeout"
return
pair.encrypted.pipe socket
socket.pipe pair.encrypted
pair.encrypted.on "close", ->
process.nextTick ->
pair.encrypted.unpipe socket
socket.destroySoon()
return
return
pair.fd = socket.fd
cleartext = pair.cleartext
cleartext.socket = socket
cleartext.encrypted = pair.encrypted
cleartext.authorized = false
socket.on "drain", ->
pair.encrypted._writePending() if pair.encrypted._pending
pair.cleartext._writePending() if pair.cleartext._pending
pair.encrypted.read 0
pair.cleartext.read 0
return
socket.on "error", onerror
socket.on "close", onclose
socket.on "timeout", ontimeout
cleartext
| 192030 | # 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.
SlabBuffer = ->
@create()
return
# Base class of both CleartextStream and EncryptedStream
CryptoStream = (pair, options) ->
stream.Duplex.call this, options
@pair = pair
@_pending = null
@_pendingEncoding = ""
@_pendingCallback = null
@_doneFlag = false
@_retryAfterPartial = false
@_halfRead = false
@_sslOutCb = null
@_resumingSession = false
@_reading = true
@_destroyed = false
@_ended = false
@_finished = false
@_opposite = null
slabBuffer = new SlabBuffer() if util.isNull(slabBuffer)
@_buffer = slabBuffer
@once "finish", onCryptoStreamFinish
# net.Socket calls .onend too
@once "end", onCryptoStreamEnd
return
onCryptoStreamFinish = ->
@_finished = true
if this is @pair.cleartext
debug "cleartext.onfinish"
if @pair.ssl
# Generate close notify
# NOTE: first call checks if client has sent us shutdown,
# second call enqueues shutdown into the BIO.
if @pair.ssl.shutdown() isnt 1
return @pair.error() if @pair.ssl and @pair.ssl.error
@pair.ssl.shutdown()
return @pair.error() if @pair.ssl and @pair.ssl.error
else
debug "encrypted.onfinish"
# Try to read just to get sure that we won't miss EOF
@_opposite.read 0 if @_opposite.readable
if @_opposite._ended
@_done()
# No half-close, sorry
@_opposite._done() if this is @pair.cleartext
return
onCryptoStreamEnd = ->
@_ended = true
if this is @pair.cleartext
debug "cleartext.onend"
else
debug "encrypted.onend"
return
# NOTE: Called once `this._opposite` is set.
# Black-hole data
# When resuming session don't accept any new data.
# And do not put too much data into openssl, before writing it from encrypted
# side.
#
# TODO(indutny): Remove magic number, use watermark based limits
# Write current buffer now
# Handle and report errors
# Force SSL_read call to cycle some states/data inside OpenSSL
# Cycle encrypted data
# Get NPN and Server name when ready
# Whole buffer was written
# Invoke callback only when all data read from opposite stream
# Force SSL_read call to cycle some states/data inside OpenSSL
# No write has happened
# XXX: EOF?!
# Wait for session to be resumed
# Mark that we're done reading, but don't provide data or EOF
# Handle and report errors
# Get NPN and Server name when ready
# Create new buffer if previous was filled up
# Try writing pending data
# EOF when cleartext has finished and we have nothing to read
# Perform graceful shutdown
# No half-open, sorry!
# EOF
# EOF
# Bail out
# Give them requested data
# Let users know that we've some internal data to read
# Smart check to avoid invoking 'sslOutEnd' in the most of the cases
# Notify listeners about internal data end
# Write pending data first
# Wait for both `finish` and `end` events to ensure that all data that
# was written on this side was read from the other side.
# Destroy both ends
# Force EOF
# Emit 'close' event
# If both streams are done:
# readyState is deprecated. Don't use it.
CleartextStream = (pair, options) ->
CryptoStream.call this, pair, options
# This is a fake kludge to support how the http impl sits
# on top of net Sockets
self = this
@_handle =
readStop: ->
self._reading = false
return
readStart: ->
return if self._reading and self._readableState.length > 0
self._reading = true
self.read 0
self._opposite.read 0 if self._opposite.readable
return
return
EncryptedStream = (pair, options) ->
CryptoStream.call this, pair, options
return
onhandshakestart = ->
debug "onhandshakestart"
self = this
ssl = self.ssl
now = Timer.now()
assert now >= ssl.lastHandshakeTime
ssl.handshakes = 0 if (now - ssl.lastHandshakeTime) >= tls.CLIENT_RENEG_WINDOW * 1000
first = (ssl.lastHandshakeTime is 0)
ssl.lastHandshakeTime = now
return if first
if ++ssl.handshakes > tls.CLIENT_RENEG_LIMIT
# Defer the error event to the next tick. We're being called from OpenSSL's
# state machine and OpenSSL is not re-entrant. We cannot allow the user's
# callback to destroy the connection right now, it would crash and burn.
setImmediate ->
err = new Error("TLS session renegotiation attack detected.")
self.cleartext.emit "error", err if self.cleartext
return
return
onhandshakedone = ->
# for future use
debug "onhandshakedone"
return
onclienthello = (hello) ->
callback = (err, session) ->
return if once
once = true
return self.socket.destroy(err) if err
self.ssl.loadSession session
self.ssl.endParser()
# Cycle data
self._resumingSession = false
self.cleartext.read 0
self.encrypted.read 0
return
self = this
once = false
@_resumingSession = true
callback null, null if hello.sessionId.length <= 0 or not @server or not @server.emit("resumeSession", hello.sessionId, callback)
return
onnewsession = (key, session) ->
done = ->
return if once
once = true
self.ssl.newSessionDone() if self.ssl
return
return unless @server
self = this
once = false
done() unless self.server.emit("newSession", key, session, done)
return
onocspresponse = (resp) ->
@emit "OCSPResponse", resp
return
###*
Provides a pair of streams to do encrypted communication.
###
SecurePair = (context, isServer, requestCert, rejectUnauthorized, options) ->
return new SecurePair(context, isServer, requestCert, rejectUnauthorized, options) unless this instanceof SecurePair
self = this
options or (options = {})
events.EventEmitter.call this
@server = options.server
@_secureEstablished = false
@_isServer = (if isServer then true else false)
@_encWriteState = true
@_clearWriteState = true
@_doneFlag = false
@_destroying = false
unless context
@credentials = tls.createSecureContext()
else
@credentials = context
# For clients, we will always have either a given ca list or be using
# default one
requestCert = true unless @_isServer
@_rejectUnauthorized = (if rejectUnauthorized then true else false)
@_requestCert = (if requestCert then true else false)
@ssl = new Connection(@credentials.context, (if @_isServer then true else false), (if @_isServer then @_requestCert else options.servername), @_rejectUnauthorized)
if @_isServer
@ssl.onhandshakestart = onhandshakestart.bind(this)
@ssl.onhandshakedone = onhandshakedone.bind(this)
@ssl.onclienthello = onclienthello.bind(this)
@ssl.onnewsession = onnewsession.bind(this)
@ssl.lastHandshakeTime = 0
@ssl.handshakes = 0
else
@ssl.onocspresponse = onocspresponse.bind(this)
if process.features.tls_sni
@ssl.setSNICallback options.SNICallback if @_isServer and options.SNICallback
@servername = null
if process.features.tls_npn and options.NPNProtocols
@ssl.setNPNProtocols options.NPNProtocols
@npnProtocol = null
# Acts as a r/w stream to the cleartext side of the stream.
@cleartext = new CleartextStream(this, options.cleartext)
# Acts as a r/w stream to the encrypted side of the stream.
@encrypted = new EncryptedStream(this, options.encrypted)
# Let streams know about each other
@cleartext._opposite = @encrypted
@encrypted._opposite = @cleartext
@cleartext.init()
@encrypted.init()
process.nextTick ->
# The Connection may be destroyed by an abort call
if self.ssl
self.ssl.start()
self.ssl.requestOCSP() if options.requestOCSP
# In case of cipher suite failures - SSL_accept/SSL_connect may fail
self.error() if self.ssl and self.ssl.error
return
return
"use strict"
assert = require("assert")
events = require("events")
stream = require("stream")
tls = require("tls")
util = require("util")
common = require("_tls_common")
Timer = process.binding("timer_wrap").Timer
Connection = null
try
Connection = process.binding("crypto").Connection
catch e
throw new Error("node.js not compiled with openssl crypto support.")
debug = util.debuglog("tls-legacy")
SlabBuffer::create = create = ->
@isFull = false
@pool = new Buffer(tls.SLAB_BUFFER_SIZE)
@offset = 0
@remaining = @pool.length
return
SlabBuffer::use = use = (context, fn, size) ->
if @remaining is 0
@isFull = true
return 0
actualSize = @remaining
actualSize = Math.min(size, actualSize) unless util.isNull(size)
bytes = fn.call(context, @pool, @offset, actualSize)
if bytes > 0
@offset += bytes
@remaining -= bytes
assert @remaining >= 0
bytes
slabBuffer = null
util.inherits CryptoStream, stream.Duplex
CryptoStream::init = init = ->
self = this
@_opposite.on "sslOutEnd", ->
if self._sslOutCb
cb = self._sslOutCb
self._sslOutCb = null
cb null
return
return
CryptoStream::_write = write = (data, encoding, cb) ->
assert util.isNull(@_pending)
return cb(null) unless @pair.ssl
if not @_resumingSession and @_opposite._internallyPendingBytes() < 128 * 1024
written = undefined
if this is @pair.cleartext
debug "cleartext.write called with %d bytes", data.length
written = @pair.ssl.clearIn(data, 0, data.length)
else
debug "encrypted.write called with %d bytes", data.length
written = @pair.ssl.encIn(data, 0, data.length)
return cb(@pair.error(true)) if @pair.ssl and @pair.ssl.error
@pair.cleartext.read 0
@pair.encrypted.read 0 if @pair.encrypted._internallyPendingBytes()
@pair.maybeInitFinished()
if written is data.length
if this is @pair.cleartext
debug "cleartext.write succeed with " + written + " bytes"
else
debug "encrypted.write succeed with " + written + " bytes"
if @_opposite._halfRead
assert util.isNull(@_sslOutCb)
@_sslOutCb = cb
else
cb null
return
else if written isnt 0 and written isnt -1
assert not @_retryAfterPartial
@_retryAfterPartial = true
@_write data.slice(written), encoding, cb
@_retryAfterPartial = false
return
else
debug "cleartext.write queue is full"
@pair.cleartext.read 0
@_pending = data
@_pendingEncoding = encoding
@_pendingCallback = cb
if this is @pair.cleartext
debug "cleartext.write queued with %d bytes", data.length
else
debug "encrypted.write queued with %d bytes", data.length
return
CryptoStream::_writePending = writePending = ->
data = @_pending
encoding = @_pendingEncoding
cb = @_pendingCallback
@_pending = null
@_pendingEncoding = ""
@_pendingCallback = null
@_write data, encoding, cb
return
CryptoStream::_read = read = (size) ->
return @push(null) unless @pair.ssl
return @push("") if @_resumingSession or not @_reading
out = undefined
if this is @pair.cleartext
debug "cleartext.read called with %d bytes", size
out = @pair.ssl.clearOut
else
debug "encrypted.read called with %d bytes", size
out = @pair.ssl.encOut
bytesRead = 0
start = @_buffer.offset
last = start
loop
assert last is @_buffer.offset
read = @_buffer.use(@pair.ssl, out, size - bytesRead)
bytesRead += read if read > 0
last = @_buffer.offset
if @pair.ssl and @pair.ssl.error
@pair.error()
break
break unless read > 0 and not @_buffer.isFull and bytesRead < size and @pair.ssl isnt null
@pair.maybeInitFinished()
pool = @_buffer.pool
@_buffer.create() if @_buffer.isFull
assert bytesRead >= 0
if this is @pair.cleartext
debug "cleartext.read succeed with %d bytes", bytesRead
else
debug "encrypted.read succeed with %d bytes", bytesRead
@_writePending() unless util.isNull(@_pending)
@_opposite._writePending() unless util.isNull(@_opposite._pending)
if bytesRead is 0
if @_opposite._finished and @_internallyPendingBytes() is 0 or @pair.ssl and @pair.ssl.receivedShutdown
@_done()
if this is @pair.cleartext
@_opposite._done()
@push null
else @push null if not @pair.ssl or not @pair.ssl.receivedShutdown
else
@push ""
else
@push pool.slice(start, start + bytesRead)
halfRead = @_internallyPendingBytes() isnt 0
if @_halfRead isnt halfRead
@_halfRead = halfRead
unless halfRead
if this is @pair.cleartext
debug "cleartext.sslOutEnd"
else
debug "encrypted.sslOutEnd"
@emit "sslOutEnd"
return
CryptoStream::setTimeout = (timeout, callback) ->
@socket.setTimeout timeout, callback if @socket
return
CryptoStream::setNoDelay = (noDelay) ->
@socket.setNoDelay noDelay if @socket
return
CryptoStream::setKeepAlive = (enable, initialDelay) ->
@socket.setKeepAlive enable, initialDelay if @socket
return
CryptoStream::__defineGetter__ "bytesWritten", ->
(if @socket then @socket.bytesWritten else 0)
CryptoStream::getPeerCertificate = (detailed) ->
return common.translatePeerCertificate(@pair.ssl.getPeerCertificate(detailed)) if @pair.ssl
null
CryptoStream::getSession = ->
return @pair.ssl.getSession() if @pair.ssl
null
CryptoStream::isSessionReused = ->
return @pair.ssl.isSessionReused() if @pair.ssl
null
CryptoStream::getCipher = (err) ->
if @pair.ssl
@pair.ssl.getCurrentCipher()
else
null
CryptoStream::end = (chunk, encoding) ->
if this is @pair.cleartext
debug "cleartext.end"
else
debug "encrypted.end"
@_writePending() unless util.isNull(@_pending)
@writable = false
stream.Duplex::end.call this, chunk, encoding
return
CryptoStream::destroySoon = (err) ->
if this is @pair.cleartext
debug "cleartext.destroySoon"
else
debug "encrypted.destroySoon"
@end() if @writable
if @_writableState.finished and @_opposite._ended
@destroy()
else
self = this
waiting = 1
finish = ->
self.destroy() if --waiting is 0
return
@_opposite.once "end", finish
unless @_finished
@once "finish", finish
++waiting
return
CryptoStream::destroy = (err) ->
return if @_destroyed
@_destroyed = true
@readable = @writable = false
if this is @pair.cleartext
debug "cleartext.destroy"
else
debug "encrypted.destroy"
@_opposite.destroy()
self = this
process.nextTick ->
self.push null
self.emit "close", (if err then true else false)
return
return
CryptoStream::_done = ->
@_doneFlag = true
return @pair.error() if this is @pair.encrypted and not @pair._secureEstablished
@pair.destroy() if @pair.cleartext._doneFlag and @pair.encrypted._doneFlag and not @pair._doneFlag
return
Object.defineProperty CryptoStream::, "readyState",
get: ->
if @_connecting
"opening"
else if @readable and @writable
"open"
else if @readable and not @writable
"readOnly"
else if not @readable and @writable
"writeOnly"
else
"closed"
util.inherits CleartextStream, CryptoStream
CleartextStream::_internallyPendingBytes = ->
if @pair.ssl
@pair.ssl.clearPending()
else
0
CleartextStream::address = ->
@socket and @socket.address()
CleartextStream::__defineGetter__ "remoteAddress", ->
@socket and @socket.remoteAddress
CleartextStream::__defineGetter__ "remoteFamily", ->
@socket and @socket.remoteFamily
CleartextStream::__defineGetter__ "remotePort", ->
@socket and @socket.remotePort
CleartextStream::__defineGetter__ "localAddress", ->
@socket and @socket.localAddress
CleartextStream::__defineGetter__ "localPort", ->
@socket and @socket.localPort
util.inherits EncryptedStream, CryptoStream
EncryptedStream::_internallyPendingBytes = ->
if @pair.ssl
@pair.ssl.encPending()
else
0
util.inherits SecurePair, events.EventEmitter
exports.createSecurePair = (context, isServer, requestCert, rejectUnauthorized) ->
pair = new SecurePair(context, isServer, requestCert, rejectUnauthorized)
pair
SecurePair::maybeInitFinished = ->
if @ssl and not @_secureEstablished and @ssl.isInitFinished()
@npnProtocol = @ssl.getNegotiatedProtocol() if process.features.tls_npn
@servername = @ssl.getServername() if process.features.tls_sni
@_secureEstablished = true
debug "secure established"
@emit "secure"
return
SecurePair::destroy = ->
return if @_destroying
unless @_doneFlag
debug "SecurePair.destroy"
@_destroying = true
# SecurePair should be destroyed only after it's streams
@cleartext.destroy()
@encrypted.destroy()
@_doneFlag = true
@ssl.error = null
@ssl.close()
@ssl = null
return
SecurePair::error = (returnOnly) ->
err = @ssl.error
@ssl.error = null
unless @_secureEstablished
# Emit ECONNRESET instead of zero return
if not err or err.message is "ZERO_RETURN"
connReset = new Error("socket hang up")
connReset.code = "ECONNRESET"
connReset.sslError = err and err.message
err = connReset
@destroy()
@emit "error", err unless returnOnly
else if @_isServer and @_rejectUnauthorized and /peer did not return a certificate/.test(err.message)
# Not really an error.
@destroy()
else
@cleartext.emit "error", err unless returnOnly
err
exports.pipe = pipe = (pair, socket) ->
# Encrypted should be unpiped from socket to prevent possible
# write after destroy.
# cycle the data whenever the socket drains, so that
# we can pull some more into it. normally this would
# be handled by the fact that pipe() triggers read() calls
# on writable.drain, but CryptoStreams are a bit more
# complicated. Since the encrypted side actually gets
# its data from the cleartext side, we have to give it a
# light kick to get in motion again.
onerror = (e) ->
cleartext.emit "error", e if cleartext._controlReleased
return
onclose = ->
socket.removeListener "error", onerror
socket.removeListener "timeout", ontimeout
return
ontimeout = ->
cleartext.emit "timeout"
return
pair.encrypted.pipe socket
socket.pipe pair.encrypted
pair.encrypted.on "close", ->
process.nextTick ->
pair.encrypted.unpipe socket
socket.destroySoon()
return
return
pair.fd = socket.fd
cleartext = pair.cleartext
cleartext.socket = socket
cleartext.encrypted = pair.encrypted
cleartext.authorized = false
socket.on "drain", ->
pair.encrypted._writePending() if pair.encrypted._pending
pair.cleartext._writePending() if pair.cleartext._pending
pair.encrypted.read 0
pair.cleartext.read 0
return
socket.on "error", onerror
socket.on "close", onclose
socket.on "timeout", ontimeout
cleartext
| 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.
SlabBuffer = ->
@create()
return
# Base class of both CleartextStream and EncryptedStream
CryptoStream = (pair, options) ->
stream.Duplex.call this, options
@pair = pair
@_pending = null
@_pendingEncoding = ""
@_pendingCallback = null
@_doneFlag = false
@_retryAfterPartial = false
@_halfRead = false
@_sslOutCb = null
@_resumingSession = false
@_reading = true
@_destroyed = false
@_ended = false
@_finished = false
@_opposite = null
slabBuffer = new SlabBuffer() if util.isNull(slabBuffer)
@_buffer = slabBuffer
@once "finish", onCryptoStreamFinish
# net.Socket calls .onend too
@once "end", onCryptoStreamEnd
return
onCryptoStreamFinish = ->
@_finished = true
if this is @pair.cleartext
debug "cleartext.onfinish"
if @pair.ssl
# Generate close notify
# NOTE: first call checks if client has sent us shutdown,
# second call enqueues shutdown into the BIO.
if @pair.ssl.shutdown() isnt 1
return @pair.error() if @pair.ssl and @pair.ssl.error
@pair.ssl.shutdown()
return @pair.error() if @pair.ssl and @pair.ssl.error
else
debug "encrypted.onfinish"
# Try to read just to get sure that we won't miss EOF
@_opposite.read 0 if @_opposite.readable
if @_opposite._ended
@_done()
# No half-close, sorry
@_opposite._done() if this is @pair.cleartext
return
onCryptoStreamEnd = ->
@_ended = true
if this is @pair.cleartext
debug "cleartext.onend"
else
debug "encrypted.onend"
return
# NOTE: Called once `this._opposite` is set.
# Black-hole data
# When resuming session don't accept any new data.
# And do not put too much data into openssl, before writing it from encrypted
# side.
#
# TODO(indutny): Remove magic number, use watermark based limits
# Write current buffer now
# Handle and report errors
# Force SSL_read call to cycle some states/data inside OpenSSL
# Cycle encrypted data
# Get NPN and Server name when ready
# Whole buffer was written
# Invoke callback only when all data read from opposite stream
# Force SSL_read call to cycle some states/data inside OpenSSL
# No write has happened
# XXX: EOF?!
# Wait for session to be resumed
# Mark that we're done reading, but don't provide data or EOF
# Handle and report errors
# Get NPN and Server name when ready
# Create new buffer if previous was filled up
# Try writing pending data
# EOF when cleartext has finished and we have nothing to read
# Perform graceful shutdown
# No half-open, sorry!
# EOF
# EOF
# Bail out
# Give them requested data
# Let users know that we've some internal data to read
# Smart check to avoid invoking 'sslOutEnd' in the most of the cases
# Notify listeners about internal data end
# Write pending data first
# Wait for both `finish` and `end` events to ensure that all data that
# was written on this side was read from the other side.
# Destroy both ends
# Force EOF
# Emit 'close' event
# If both streams are done:
# readyState is deprecated. Don't use it.
CleartextStream = (pair, options) ->
CryptoStream.call this, pair, options
# This is a fake kludge to support how the http impl sits
# on top of net Sockets
self = this
@_handle =
readStop: ->
self._reading = false
return
readStart: ->
return if self._reading and self._readableState.length > 0
self._reading = true
self.read 0
self._opposite.read 0 if self._opposite.readable
return
return
EncryptedStream = (pair, options) ->
CryptoStream.call this, pair, options
return
onhandshakestart = ->
debug "onhandshakestart"
self = this
ssl = self.ssl
now = Timer.now()
assert now >= ssl.lastHandshakeTime
ssl.handshakes = 0 if (now - ssl.lastHandshakeTime) >= tls.CLIENT_RENEG_WINDOW * 1000
first = (ssl.lastHandshakeTime is 0)
ssl.lastHandshakeTime = now
return if first
if ++ssl.handshakes > tls.CLIENT_RENEG_LIMIT
# Defer the error event to the next tick. We're being called from OpenSSL's
# state machine and OpenSSL is not re-entrant. We cannot allow the user's
# callback to destroy the connection right now, it would crash and burn.
setImmediate ->
err = new Error("TLS session renegotiation attack detected.")
self.cleartext.emit "error", err if self.cleartext
return
return
onhandshakedone = ->
# for future use
debug "onhandshakedone"
return
onclienthello = (hello) ->
callback = (err, session) ->
return if once
once = true
return self.socket.destroy(err) if err
self.ssl.loadSession session
self.ssl.endParser()
# Cycle data
self._resumingSession = false
self.cleartext.read 0
self.encrypted.read 0
return
self = this
once = false
@_resumingSession = true
callback null, null if hello.sessionId.length <= 0 or not @server or not @server.emit("resumeSession", hello.sessionId, callback)
return
onnewsession = (key, session) ->
done = ->
return if once
once = true
self.ssl.newSessionDone() if self.ssl
return
return unless @server
self = this
once = false
done() unless self.server.emit("newSession", key, session, done)
return
onocspresponse = (resp) ->
@emit "OCSPResponse", resp
return
###*
Provides a pair of streams to do encrypted communication.
###
SecurePair = (context, isServer, requestCert, rejectUnauthorized, options) ->
return new SecurePair(context, isServer, requestCert, rejectUnauthorized, options) unless this instanceof SecurePair
self = this
options or (options = {})
events.EventEmitter.call this
@server = options.server
@_secureEstablished = false
@_isServer = (if isServer then true else false)
@_encWriteState = true
@_clearWriteState = true
@_doneFlag = false
@_destroying = false
unless context
@credentials = tls.createSecureContext()
else
@credentials = context
# For clients, we will always have either a given ca list or be using
# default one
requestCert = true unless @_isServer
@_rejectUnauthorized = (if rejectUnauthorized then true else false)
@_requestCert = (if requestCert then true else false)
@ssl = new Connection(@credentials.context, (if @_isServer then true else false), (if @_isServer then @_requestCert else options.servername), @_rejectUnauthorized)
if @_isServer
@ssl.onhandshakestart = onhandshakestart.bind(this)
@ssl.onhandshakedone = onhandshakedone.bind(this)
@ssl.onclienthello = onclienthello.bind(this)
@ssl.onnewsession = onnewsession.bind(this)
@ssl.lastHandshakeTime = 0
@ssl.handshakes = 0
else
@ssl.onocspresponse = onocspresponse.bind(this)
if process.features.tls_sni
@ssl.setSNICallback options.SNICallback if @_isServer and options.SNICallback
@servername = null
if process.features.tls_npn and options.NPNProtocols
@ssl.setNPNProtocols options.NPNProtocols
@npnProtocol = null
# Acts as a r/w stream to the cleartext side of the stream.
@cleartext = new CleartextStream(this, options.cleartext)
# Acts as a r/w stream to the encrypted side of the stream.
@encrypted = new EncryptedStream(this, options.encrypted)
# Let streams know about each other
@cleartext._opposite = @encrypted
@encrypted._opposite = @cleartext
@cleartext.init()
@encrypted.init()
process.nextTick ->
# The Connection may be destroyed by an abort call
if self.ssl
self.ssl.start()
self.ssl.requestOCSP() if options.requestOCSP
# In case of cipher suite failures - SSL_accept/SSL_connect may fail
self.error() if self.ssl and self.ssl.error
return
return
"use strict"
assert = require("assert")
events = require("events")
stream = require("stream")
tls = require("tls")
util = require("util")
common = require("_tls_common")
Timer = process.binding("timer_wrap").Timer
Connection = null
try
Connection = process.binding("crypto").Connection
catch e
throw new Error("node.js not compiled with openssl crypto support.")
debug = util.debuglog("tls-legacy")
SlabBuffer::create = create = ->
@isFull = false
@pool = new Buffer(tls.SLAB_BUFFER_SIZE)
@offset = 0
@remaining = @pool.length
return
SlabBuffer::use = use = (context, fn, size) ->
if @remaining is 0
@isFull = true
return 0
actualSize = @remaining
actualSize = Math.min(size, actualSize) unless util.isNull(size)
bytes = fn.call(context, @pool, @offset, actualSize)
if bytes > 0
@offset += bytes
@remaining -= bytes
assert @remaining >= 0
bytes
slabBuffer = null
util.inherits CryptoStream, stream.Duplex
CryptoStream::init = init = ->
self = this
@_opposite.on "sslOutEnd", ->
if self._sslOutCb
cb = self._sslOutCb
self._sslOutCb = null
cb null
return
return
CryptoStream::_write = write = (data, encoding, cb) ->
assert util.isNull(@_pending)
return cb(null) unless @pair.ssl
if not @_resumingSession and @_opposite._internallyPendingBytes() < 128 * 1024
written = undefined
if this is @pair.cleartext
debug "cleartext.write called with %d bytes", data.length
written = @pair.ssl.clearIn(data, 0, data.length)
else
debug "encrypted.write called with %d bytes", data.length
written = @pair.ssl.encIn(data, 0, data.length)
return cb(@pair.error(true)) if @pair.ssl and @pair.ssl.error
@pair.cleartext.read 0
@pair.encrypted.read 0 if @pair.encrypted._internallyPendingBytes()
@pair.maybeInitFinished()
if written is data.length
if this is @pair.cleartext
debug "cleartext.write succeed with " + written + " bytes"
else
debug "encrypted.write succeed with " + written + " bytes"
if @_opposite._halfRead
assert util.isNull(@_sslOutCb)
@_sslOutCb = cb
else
cb null
return
else if written isnt 0 and written isnt -1
assert not @_retryAfterPartial
@_retryAfterPartial = true
@_write data.slice(written), encoding, cb
@_retryAfterPartial = false
return
else
debug "cleartext.write queue is full"
@pair.cleartext.read 0
@_pending = data
@_pendingEncoding = encoding
@_pendingCallback = cb
if this is @pair.cleartext
debug "cleartext.write queued with %d bytes", data.length
else
debug "encrypted.write queued with %d bytes", data.length
return
CryptoStream::_writePending = writePending = ->
data = @_pending
encoding = @_pendingEncoding
cb = @_pendingCallback
@_pending = null
@_pendingEncoding = ""
@_pendingCallback = null
@_write data, encoding, cb
return
CryptoStream::_read = read = (size) ->
return @push(null) unless @pair.ssl
return @push("") if @_resumingSession or not @_reading
out = undefined
if this is @pair.cleartext
debug "cleartext.read called with %d bytes", size
out = @pair.ssl.clearOut
else
debug "encrypted.read called with %d bytes", size
out = @pair.ssl.encOut
bytesRead = 0
start = @_buffer.offset
last = start
loop
assert last is @_buffer.offset
read = @_buffer.use(@pair.ssl, out, size - bytesRead)
bytesRead += read if read > 0
last = @_buffer.offset
if @pair.ssl and @pair.ssl.error
@pair.error()
break
break unless read > 0 and not @_buffer.isFull and bytesRead < size and @pair.ssl isnt null
@pair.maybeInitFinished()
pool = @_buffer.pool
@_buffer.create() if @_buffer.isFull
assert bytesRead >= 0
if this is @pair.cleartext
debug "cleartext.read succeed with %d bytes", bytesRead
else
debug "encrypted.read succeed with %d bytes", bytesRead
@_writePending() unless util.isNull(@_pending)
@_opposite._writePending() unless util.isNull(@_opposite._pending)
if bytesRead is 0
if @_opposite._finished and @_internallyPendingBytes() is 0 or @pair.ssl and @pair.ssl.receivedShutdown
@_done()
if this is @pair.cleartext
@_opposite._done()
@push null
else @push null if not @pair.ssl or not @pair.ssl.receivedShutdown
else
@push ""
else
@push pool.slice(start, start + bytesRead)
halfRead = @_internallyPendingBytes() isnt 0
if @_halfRead isnt halfRead
@_halfRead = halfRead
unless halfRead
if this is @pair.cleartext
debug "cleartext.sslOutEnd"
else
debug "encrypted.sslOutEnd"
@emit "sslOutEnd"
return
CryptoStream::setTimeout = (timeout, callback) ->
@socket.setTimeout timeout, callback if @socket
return
CryptoStream::setNoDelay = (noDelay) ->
@socket.setNoDelay noDelay if @socket
return
CryptoStream::setKeepAlive = (enable, initialDelay) ->
@socket.setKeepAlive enable, initialDelay if @socket
return
CryptoStream::__defineGetter__ "bytesWritten", ->
(if @socket then @socket.bytesWritten else 0)
CryptoStream::getPeerCertificate = (detailed) ->
return common.translatePeerCertificate(@pair.ssl.getPeerCertificate(detailed)) if @pair.ssl
null
CryptoStream::getSession = ->
return @pair.ssl.getSession() if @pair.ssl
null
CryptoStream::isSessionReused = ->
return @pair.ssl.isSessionReused() if @pair.ssl
null
CryptoStream::getCipher = (err) ->
if @pair.ssl
@pair.ssl.getCurrentCipher()
else
null
CryptoStream::end = (chunk, encoding) ->
if this is @pair.cleartext
debug "cleartext.end"
else
debug "encrypted.end"
@_writePending() unless util.isNull(@_pending)
@writable = false
stream.Duplex::end.call this, chunk, encoding
return
CryptoStream::destroySoon = (err) ->
if this is @pair.cleartext
debug "cleartext.destroySoon"
else
debug "encrypted.destroySoon"
@end() if @writable
if @_writableState.finished and @_opposite._ended
@destroy()
else
self = this
waiting = 1
finish = ->
self.destroy() if --waiting is 0
return
@_opposite.once "end", finish
unless @_finished
@once "finish", finish
++waiting
return
CryptoStream::destroy = (err) ->
return if @_destroyed
@_destroyed = true
@readable = @writable = false
if this is @pair.cleartext
debug "cleartext.destroy"
else
debug "encrypted.destroy"
@_opposite.destroy()
self = this
process.nextTick ->
self.push null
self.emit "close", (if err then true else false)
return
return
CryptoStream::_done = ->
@_doneFlag = true
return @pair.error() if this is @pair.encrypted and not @pair._secureEstablished
@pair.destroy() if @pair.cleartext._doneFlag and @pair.encrypted._doneFlag and not @pair._doneFlag
return
Object.defineProperty CryptoStream::, "readyState",
get: ->
if @_connecting
"opening"
else if @readable and @writable
"open"
else if @readable and not @writable
"readOnly"
else if not @readable and @writable
"writeOnly"
else
"closed"
util.inherits CleartextStream, CryptoStream
CleartextStream::_internallyPendingBytes = ->
if @pair.ssl
@pair.ssl.clearPending()
else
0
CleartextStream::address = ->
@socket and @socket.address()
CleartextStream::__defineGetter__ "remoteAddress", ->
@socket and @socket.remoteAddress
CleartextStream::__defineGetter__ "remoteFamily", ->
@socket and @socket.remoteFamily
CleartextStream::__defineGetter__ "remotePort", ->
@socket and @socket.remotePort
CleartextStream::__defineGetter__ "localAddress", ->
@socket and @socket.localAddress
CleartextStream::__defineGetter__ "localPort", ->
@socket and @socket.localPort
util.inherits EncryptedStream, CryptoStream
EncryptedStream::_internallyPendingBytes = ->
if @pair.ssl
@pair.ssl.encPending()
else
0
util.inherits SecurePair, events.EventEmitter
exports.createSecurePair = (context, isServer, requestCert, rejectUnauthorized) ->
pair = new SecurePair(context, isServer, requestCert, rejectUnauthorized)
pair
SecurePair::maybeInitFinished = ->
if @ssl and not @_secureEstablished and @ssl.isInitFinished()
@npnProtocol = @ssl.getNegotiatedProtocol() if process.features.tls_npn
@servername = @ssl.getServername() if process.features.tls_sni
@_secureEstablished = true
debug "secure established"
@emit "secure"
return
SecurePair::destroy = ->
return if @_destroying
unless @_doneFlag
debug "SecurePair.destroy"
@_destroying = true
# SecurePair should be destroyed only after it's streams
@cleartext.destroy()
@encrypted.destroy()
@_doneFlag = true
@ssl.error = null
@ssl.close()
@ssl = null
return
SecurePair::error = (returnOnly) ->
err = @ssl.error
@ssl.error = null
unless @_secureEstablished
# Emit ECONNRESET instead of zero return
if not err or err.message is "ZERO_RETURN"
connReset = new Error("socket hang up")
connReset.code = "ECONNRESET"
connReset.sslError = err and err.message
err = connReset
@destroy()
@emit "error", err unless returnOnly
else if @_isServer and @_rejectUnauthorized and /peer did not return a certificate/.test(err.message)
# Not really an error.
@destroy()
else
@cleartext.emit "error", err unless returnOnly
err
exports.pipe = pipe = (pair, socket) ->
# Encrypted should be unpiped from socket to prevent possible
# write after destroy.
# cycle the data whenever the socket drains, so that
# we can pull some more into it. normally this would
# be handled by the fact that pipe() triggers read() calls
# on writable.drain, but CryptoStreams are a bit more
# complicated. Since the encrypted side actually gets
# its data from the cleartext side, we have to give it a
# light kick to get in motion again.
onerror = (e) ->
cleartext.emit "error", e if cleartext._controlReleased
return
onclose = ->
socket.removeListener "error", onerror
socket.removeListener "timeout", ontimeout
return
ontimeout = ->
cleartext.emit "timeout"
return
pair.encrypted.pipe socket
socket.pipe pair.encrypted
pair.encrypted.on "close", ->
process.nextTick ->
pair.encrypted.unpipe socket
socket.destroySoon()
return
return
pair.fd = socket.fd
cleartext = pair.cleartext
cleartext.socket = socket
cleartext.encrypted = pair.encrypted
cleartext.authorized = false
socket.on "drain", ->
pair.encrypted._writePending() if pair.encrypted._pending
pair.cleartext._writePending() if pair.cleartext._pending
pair.encrypted.read 0
pair.cleartext.read 0
return
socket.on "error", onerror
socket.on "close", onclose
socket.on "timeout", ontimeout
cleartext
|
[
{
"context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission",
"end": 18,
"score": 0.9990613460540771,
"start": 12,
"tag": "NAME",
"value": "Joyent"
}
] | test/simple/test-child-process-silent.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")
childProcess = require("child_process")
# Child pipe test
if process.argv[2] is "pipetest"
process.stdout.write "stdout message"
process.stderr.write "stderr message"
else if process.argv[2] is "ipctest"
# Child IPC test
process.send "message from child"
process.on "message", ->
process.send "got message from master"
return
else if process.argv[2] is "parent"
# Parent | start child pipe test
child = childProcess.fork(process.argv[1], ["pipetest"],
silent: true
)
# Allow child process to self terminate
child._channel.close()
child._channel = null
child.on "exit", ->
process.exit 0
return
else
# testcase | start parent && child IPC test
# testing: is stderr and stdout piped to parent
args = [
process.argv[1]
"parent"
]
parent = childProcess.spawn(process.execPath, args)
#got any stderr or std data
stdoutData = false
parent.stdout.on "data", ->
stdoutData = true
return
stderrData = false
parent.stdout.on "data", ->
stderrData = true
return
# testing: do message system work when using silent
child = childProcess.fork(process.argv[1], ["ipctest"],
silent: true
)
# Manual pipe so we will get errors
child.stderr.pipe process.stderr,
end: false
child.stdout.pipe process.stdout,
end: false
childSending = false
childReciveing = false
child.on "message", (message) ->
childSending = (message is "message from child") if childSending is false
childReciveing = (message is "got message from master") if childReciveing is false
child.kill() if childReciveing is true
return
child.send "message to child"
# Check all values
process.on "exit", ->
# clean up
child.kill()
parent.kill()
# Check std(out|err) pipes
assert.ok not stdoutData, "The stdout socket was piped to parent"
assert.ok not stderrData, "The stderr socket was piped to parent"
# Check message system
assert.ok childSending, "The child was able to send a message"
assert.ok childReciveing, "The child was able to receive a message"
return
| 182724 | # 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")
childProcess = require("child_process")
# Child pipe test
if process.argv[2] is "pipetest"
process.stdout.write "stdout message"
process.stderr.write "stderr message"
else if process.argv[2] is "ipctest"
# Child IPC test
process.send "message from child"
process.on "message", ->
process.send "got message from master"
return
else if process.argv[2] is "parent"
# Parent | start child pipe test
child = childProcess.fork(process.argv[1], ["pipetest"],
silent: true
)
# Allow child process to self terminate
child._channel.close()
child._channel = null
child.on "exit", ->
process.exit 0
return
else
# testcase | start parent && child IPC test
# testing: is stderr and stdout piped to parent
args = [
process.argv[1]
"parent"
]
parent = childProcess.spawn(process.execPath, args)
#got any stderr or std data
stdoutData = false
parent.stdout.on "data", ->
stdoutData = true
return
stderrData = false
parent.stdout.on "data", ->
stderrData = true
return
# testing: do message system work when using silent
child = childProcess.fork(process.argv[1], ["ipctest"],
silent: true
)
# Manual pipe so we will get errors
child.stderr.pipe process.stderr,
end: false
child.stdout.pipe process.stdout,
end: false
childSending = false
childReciveing = false
child.on "message", (message) ->
childSending = (message is "message from child") if childSending is false
childReciveing = (message is "got message from master") if childReciveing is false
child.kill() if childReciveing is true
return
child.send "message to child"
# Check all values
process.on "exit", ->
# clean up
child.kill()
parent.kill()
# Check std(out|err) pipes
assert.ok not stdoutData, "The stdout socket was piped to parent"
assert.ok not stderrData, "The stderr socket was piped to parent"
# Check message system
assert.ok childSending, "The child was able to send a message"
assert.ok childReciveing, "The child was able to receive a message"
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")
childProcess = require("child_process")
# Child pipe test
if process.argv[2] is "pipetest"
process.stdout.write "stdout message"
process.stderr.write "stderr message"
else if process.argv[2] is "ipctest"
# Child IPC test
process.send "message from child"
process.on "message", ->
process.send "got message from master"
return
else if process.argv[2] is "parent"
# Parent | start child pipe test
child = childProcess.fork(process.argv[1], ["pipetest"],
silent: true
)
# Allow child process to self terminate
child._channel.close()
child._channel = null
child.on "exit", ->
process.exit 0
return
else
# testcase | start parent && child IPC test
# testing: is stderr and stdout piped to parent
args = [
process.argv[1]
"parent"
]
parent = childProcess.spawn(process.execPath, args)
#got any stderr or std data
stdoutData = false
parent.stdout.on "data", ->
stdoutData = true
return
stderrData = false
parent.stdout.on "data", ->
stderrData = true
return
# testing: do message system work when using silent
child = childProcess.fork(process.argv[1], ["ipctest"],
silent: true
)
# Manual pipe so we will get errors
child.stderr.pipe process.stderr,
end: false
child.stdout.pipe process.stdout,
end: false
childSending = false
childReciveing = false
child.on "message", (message) ->
childSending = (message is "message from child") if childSending is false
childReciveing = (message is "got message from master") if childReciveing is false
child.kill() if childReciveing is true
return
child.send "message to child"
# Check all values
process.on "exit", ->
# clean up
child.kill()
parent.kill()
# Check std(out|err) pipes
assert.ok not stdoutData, "The stdout socket was piped to parent"
assert.ok not stderrData, "The stderr socket was piped to parent"
# Check message system
assert.ok childSending, "The child was able to send a message"
assert.ok childReciveing, "The child was able to receive a message"
return
|
[
{
"context": "om http://images.manchester.gov.uk\n#\n# Author:\n# robertocarroll\n\noldImage = [\n \"http://images.manchester.g",
"end": 292,
"score": 0.6058005094528198,
"start": 285,
"tag": "USERNAME",
"value": "roberto"
},
{
"context": "//images.manchester.gov.uk\n#\n# Author:\n... | old_scripts/oldimage.coffee | robertocarroll/chatui | 0 | # Description:
# Display a random image of the Central library from http://images.manchester.gov.uk
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Command:
# old image - Display a random image of the Central library from http://images.manchester.gov.uk
#
# Author:
# robertocarroll
oldImage = [
"http://images.manchester.gov.uk/web/objects/common/webmedia.php?irn=47834&size=190x157&format=jpg",
"http://images.manchester.gov.uk/web/objects/common/webmedia.php?irn=78097&size=190x157&format=jpg",
"http://images.manchester.gov.uk/web/objects/common/webmedia.php?irn=79027&size=190x157&format=jpg",
"http://images.manchester.gov.uk/web/objects/common/webmedia.php?irn=49227&size=190x157&format=jpg",
"http://images.manchester.gov.uk/web/objects/common/webmedia.php?irn=48640&size=190x157&format=jpg",
"http://images.manchester.gov.uk/web/objects/common/webmedia.php?irn=48639&size=190x157&format=jpg",
"http://images.manchester.gov.uk/web/objects/common/webmedia.php?irn=47909&size=190x157&format=jpg",
"http://images.manchester.gov.uk/web/objects/common/webmedia.php?irn=5447&size=190x157&format=jpg",
"http://images.manchester.gov.uk/web/objects/common/webmedia.php?irn=78031&size=190x157&format=jpg"
]
module.exports = (robot) ->
robot.hear /old image|old picture/i, (msg) ->
msg.send msg.random oldImage
| 81102 | # Description:
# Display a random image of the Central library from http://images.manchester.gov.uk
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Command:
# old image - Display a random image of the Central library from http://images.manchester.gov.uk
#
# Author:
# roberto<NAME>
oldImage = [
"http://images.manchester.gov.uk/web/objects/common/webmedia.php?irn=47834&size=190x157&format=jpg",
"http://images.manchester.gov.uk/web/objects/common/webmedia.php?irn=78097&size=190x157&format=jpg",
"http://images.manchester.gov.uk/web/objects/common/webmedia.php?irn=79027&size=190x157&format=jpg",
"http://images.manchester.gov.uk/web/objects/common/webmedia.php?irn=49227&size=190x157&format=jpg",
"http://images.manchester.gov.uk/web/objects/common/webmedia.php?irn=48640&size=190x157&format=jpg",
"http://images.manchester.gov.uk/web/objects/common/webmedia.php?irn=48639&size=190x157&format=jpg",
"http://images.manchester.gov.uk/web/objects/common/webmedia.php?irn=47909&size=190x157&format=jpg",
"http://images.manchester.gov.uk/web/objects/common/webmedia.php?irn=5447&size=190x157&format=jpg",
"http://images.manchester.gov.uk/web/objects/common/webmedia.php?irn=78031&size=190x157&format=jpg"
]
module.exports = (robot) ->
robot.hear /old image|old picture/i, (msg) ->
msg.send msg.random oldImage
| true | # Description:
# Display a random image of the Central library from http://images.manchester.gov.uk
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Command:
# old image - Display a random image of the Central library from http://images.manchester.gov.uk
#
# Author:
# robertoPI:NAME:<NAME>END_PI
oldImage = [
"http://images.manchester.gov.uk/web/objects/common/webmedia.php?irn=47834&size=190x157&format=jpg",
"http://images.manchester.gov.uk/web/objects/common/webmedia.php?irn=78097&size=190x157&format=jpg",
"http://images.manchester.gov.uk/web/objects/common/webmedia.php?irn=79027&size=190x157&format=jpg",
"http://images.manchester.gov.uk/web/objects/common/webmedia.php?irn=49227&size=190x157&format=jpg",
"http://images.manchester.gov.uk/web/objects/common/webmedia.php?irn=48640&size=190x157&format=jpg",
"http://images.manchester.gov.uk/web/objects/common/webmedia.php?irn=48639&size=190x157&format=jpg",
"http://images.manchester.gov.uk/web/objects/common/webmedia.php?irn=47909&size=190x157&format=jpg",
"http://images.manchester.gov.uk/web/objects/common/webmedia.php?irn=5447&size=190x157&format=jpg",
"http://images.manchester.gov.uk/web/objects/common/webmedia.php?irn=78031&size=190x157&format=jpg"
]
module.exports = (robot) ->
robot.hear /old image|old picture/i, (msg) ->
msg.send msg.random oldImage
|
[
{
"context": "apboxgl.LatLng = L.LatLng\nmapboxgl.accessToken = 'pk.eyJ1IjoibW9yaXR6c3RlZmFuZXIiLCJhIjoiUGs4LU1VZyJ9.oJh_Gi3geralmUvrJVWYaA'\n\nCOUCH_URL = \"https://starling.columba.uberspace",
"end": 145,
"score": 0.999721109867096,
"start": 71,
"tag": "KEY",
"value": "pk.eyJ1IjoibW9yaXR6c... | www/src/coffee/constants.coffee | MoritzStefaner/project-ukko-os | 2 | mapboxgl = L.mapbox
mapboxgl.LatLng = L.LatLng
mapboxgl.accessToken = 'pk.eyJ1IjoibW9yaXR6c3RlZmFuZXIiLCJhIjoiUGs4LU1VZyJ9.oJh_Gi3geralmUvrJVWYaA'
COUCH_URL = "https://starling.columba.uberspace.de/couchdb"
DB_NAME = "euporias"
$.couch.urlPrefix = COUCH_URL
DB = $.couch.db(DB_NAME)
| 218369 | mapboxgl = L.mapbox
mapboxgl.LatLng = L.LatLng
mapboxgl.accessToken = '<KEY>'
COUCH_URL = "https://starling.columba.uberspace.de/couchdb"
DB_NAME = "euporias"
$.couch.urlPrefix = COUCH_URL
DB = $.couch.db(DB_NAME)
| true | mapboxgl = L.mapbox
mapboxgl.LatLng = L.LatLng
mapboxgl.accessToken = 'PI:KEY:<KEY>END_PI'
COUCH_URL = "https://starling.columba.uberspace.de/couchdb"
DB_NAME = "euporias"
$.couch.urlPrefix = COUCH_URL
DB = $.couch.db(DB_NAME)
|
[
{
"context": " avalanche forecast from varsom.no\n#\n# Author:\n# Alastair Brunton\n\njsdom = require 'jsdom'\n\ngetScores = ($, cb) ->\n",
"end": 262,
"score": 0.9998679161071777,
"start": 246,
"tag": "NAME",
"value": "Alastair Brunton"
}
] | src/scripts/avalanche.coffee | Reelhouse/hubot-scripts | 1,450 | # Description:
# Displays the current avalanche forecast for norway.
#
# Dependencies:
# "jsdom": "0.2.14"
# Configuration:
# None
#
# Commands:
# hubot avy me - Return a breakdown of the avalanche forecast from varsom.no
#
# Author:
# Alastair Brunton
jsdom = require 'jsdom'
getScores = ($, cb) ->
results = []
area_scores = {}
trs = $("tr")
tr_length = trs.length
trs.each ((index) ->
getRiskValues($, $(this), (err, values) ->
results.push values
if results.length == tr_length - 1
cb null, results
else
# do nothing
)
)
getRiskValues = ($, element, cb) ->
riskValues = []
element.children("td.hazard").each((index) ->
riskValues.push $(this).text().trim()
if riskValues.length == 3
cb null, riskValues
else
# do nothing
)
getPlaces = ($, cb) ->
locations = $("span.location")
locationNames = []
numLocations = locations.length
locations.each((index) ->
$(this).children().each((index2) ->
locationNames.push $(this).text()
if locationNames.length == numLocations
cb null, locationNames
else
# do nothing
)
)
joinArs = (places, scores) ->
joinedAr = []
i = 0
for place in places
score = scores[i].join(" ")
joinedAr.push("#{place} #{score}")
i = i + 1
joinedAr.join("\n")
module.exports = (robot)->
robot.respond /avy me/i, (msg) ->
jsdom.env("http://varsom.no/Snoskred/", ['http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js'],
(errors, window) ->
$ = window.$
getScores($, (err, scores) ->
getPlaces($, (err, places) ->
avyReport = joinArs(places, scores)
msg.send avyReport
)
)
)
| 2329 | # Description:
# Displays the current avalanche forecast for norway.
#
# Dependencies:
# "jsdom": "0.2.14"
# Configuration:
# None
#
# Commands:
# hubot avy me - Return a breakdown of the avalanche forecast from varsom.no
#
# Author:
# <NAME>
jsdom = require 'jsdom'
getScores = ($, cb) ->
results = []
area_scores = {}
trs = $("tr")
tr_length = trs.length
trs.each ((index) ->
getRiskValues($, $(this), (err, values) ->
results.push values
if results.length == tr_length - 1
cb null, results
else
# do nothing
)
)
getRiskValues = ($, element, cb) ->
riskValues = []
element.children("td.hazard").each((index) ->
riskValues.push $(this).text().trim()
if riskValues.length == 3
cb null, riskValues
else
# do nothing
)
getPlaces = ($, cb) ->
locations = $("span.location")
locationNames = []
numLocations = locations.length
locations.each((index) ->
$(this).children().each((index2) ->
locationNames.push $(this).text()
if locationNames.length == numLocations
cb null, locationNames
else
# do nothing
)
)
joinArs = (places, scores) ->
joinedAr = []
i = 0
for place in places
score = scores[i].join(" ")
joinedAr.push("#{place} #{score}")
i = i + 1
joinedAr.join("\n")
module.exports = (robot)->
robot.respond /avy me/i, (msg) ->
jsdom.env("http://varsom.no/Snoskred/", ['http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js'],
(errors, window) ->
$ = window.$
getScores($, (err, scores) ->
getPlaces($, (err, places) ->
avyReport = joinArs(places, scores)
msg.send avyReport
)
)
)
| true | # Description:
# Displays the current avalanche forecast for norway.
#
# Dependencies:
# "jsdom": "0.2.14"
# Configuration:
# None
#
# Commands:
# hubot avy me - Return a breakdown of the avalanche forecast from varsom.no
#
# Author:
# PI:NAME:<NAME>END_PI
jsdom = require 'jsdom'
getScores = ($, cb) ->
results = []
area_scores = {}
trs = $("tr")
tr_length = trs.length
trs.each ((index) ->
getRiskValues($, $(this), (err, values) ->
results.push values
if results.length == tr_length - 1
cb null, results
else
# do nothing
)
)
getRiskValues = ($, element, cb) ->
riskValues = []
element.children("td.hazard").each((index) ->
riskValues.push $(this).text().trim()
if riskValues.length == 3
cb null, riskValues
else
# do nothing
)
getPlaces = ($, cb) ->
locations = $("span.location")
locationNames = []
numLocations = locations.length
locations.each((index) ->
$(this).children().each((index2) ->
locationNames.push $(this).text()
if locationNames.length == numLocations
cb null, locationNames
else
# do nothing
)
)
joinArs = (places, scores) ->
joinedAr = []
i = 0
for place in places
score = scores[i].join(" ")
joinedAr.push("#{place} #{score}")
i = i + 1
joinedAr.join("\n")
module.exports = (robot)->
robot.respond /avy me/i, (msg) ->
jsdom.env("http://varsom.no/Snoskred/", ['http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js'],
(errors, window) ->
$ = window.$
getScores($, (err, scores) ->
getPlaces($, (err, places) ->
avyReport = joinArs(places, scores)
msg.send avyReport
)
)
)
|
[
{
"context": "oGLib\n# Module | Stat Methods\n# Author | Sherif Emabrak\n# Description | The quantile methods partition by",
"end": 163,
"score": 0.9998744130134583,
"start": 149,
"tag": "NAME",
"value": "Sherif Emabrak"
}
] | src/lib/statistics/bin/quantile.coffee | Sherif-Embarak/gp-test | 0 | # ------------------------------------------------------------------------------
# Project | GoGLib
# Module | Stat Methods
# Author | Sherif Emabrak
# Description | The quantile methods partition by computing sample quantiles (such as quartiles, deciles, or percentiles).
# ------------------------------------------------------------------------------
quantile = () -> | 194461 | # ------------------------------------------------------------------------------
# Project | GoGLib
# Module | Stat Methods
# Author | <NAME>
# Description | The quantile methods partition by computing sample quantiles (such as quartiles, deciles, or percentiles).
# ------------------------------------------------------------------------------
quantile = () -> | true | # ------------------------------------------------------------------------------
# Project | GoGLib
# Module | Stat Methods
# Author | PI:NAME:<NAME>END_PI
# Description | The quantile methods partition by computing sample quantiles (such as quartiles, deciles, or percentiles).
# ------------------------------------------------------------------------------
quantile = () -> |
[
{
"context": "Disability\"\nlocation: \"Leeds\"\nphase: \"beta\"\nsro: \"Justin Russell\"\nservice_man: \"Adam Tostevin\"\nphase_history:\n di",
"end": 265,
"score": 0.9998643398284912,
"start": 251,
"tag": "NAME",
"value": "Justin Russell"
},
{
"context": "phase: \"beta\"\nsro: \"J... | app/data/projects/employment-support-allowance.cson | tsmorgan/dwp-ux-work | 0 | id: 3
name: "Employment and Support Allowance (ESA)"
description: "Lets customers who are unable to work through sickness or injury make a claim for Employment and Support Allowance."
theme: "Health & Disability"
location: "Leeds"
phase: "beta"
sro: "Justin Russell"
service_man: "Adam Tostevin"
phase_history:
discovery: [
{
label: "Completed"
date: "January 2016"
}
]
alpha: [
{
label: "Completed"
date: "July 2016"
}
]
beta: [
{
label: "Started"
date: "July 2016"
}
{
label: "Private beta started"
date: "September 2016"
}
{
label: "Public beta predicted"
date: "February 2017"
}
]
user_needs: [
{
asa: "person applying for Employment Support Allowance"
ineed: "to know at the earliest opportunity whether I am eligible or not"
}
{
asa: "person unable to work because of serious illness, injury or disability"
ineed: "I need financial support in order to survive"
}
{
asa: "person with a health condition"
ineed: "I need better information as to which benefits I can claim"
}
{
asa: "person with a health condition"
ineed: "I need a simple service"
so: "that I can easily claim Employment Support Allowance"
}
{
asa: "employer"
ineed: "I need more information available for Employment Support Allowance"
so: "that I can support my employee"
}
{
asa: "General Practioner"
ineed: "I need more information available for Employment Support Allowance"
so: "that I can support my patient"
}
{
asa: "Employment Support Allowance customer"
ineed: "I need to understand how a change in my circumstance could affect my claim"
}
{
asa: "person applying for Employment Support Allowance"
ineed: "I need to understand how other benefits may affect my claim"
}
{
asa: "person with an illness or health condition"
ineed: "I need a 'one stop shop'"
so: "that I can decide whether to claim a benefit"
}
{
asa: "Employment Support Allowance customer"
ineed: "I need a consistent service"
}
{
asa: "disadvantaged customer"
ineed: "I need assistance to make my claim for Employment Support Allowance"
}
{
asa: "low confidence user"
ineed: "I need assistance in making my claim for Employment Support Allowance"
}
{
asa: "person applying for Employment Support Allowance"
ineed: "I need to know the information I will be required to provide in order to make a claim"
}
{
asa: "Employment Support customer"
ineed: "I need support to help me get back into work"
}
{
asa: "General Practioner"
ineed: "I need a simple service with DWP"
}
{
asa: "person on Statutory Sick Pay (SSP)"
ineed: "I need to know what my options are when my SSP ends"
}
{
asa: "Employment Support Allowance customer"
ineed: "I need to understand what DWP'S expectations of me are"
}
{
asa: "person applying for Emplyment Support Allowance, I only want to provide information once in order to support my claim"
}
{
asa: "person applying for Employment Support Allowance, I want to make a claim at a time and location suitable to me"
}
{
asa: "person applying for Employment Support Allowance"
ineed: "I need to feel that my personal information is safe and secure"
}
{
asa: "self employed person"
ineed: "I need to know what what my benefit options are if I fall ill"
}
{
asa: "person claiming benefit"
ineed: "I need to understand my transition from one benefit onto Employment Support Allowance"
}
{
asa: "person leaving prison"
ineed: "I need money avalable as soon as I leave prison"
}
{
asa: "Employment Support Allowance customer"
ineed: "I need a service that is sympathetic to my health condition"
}
{
asa: "person in receipt of SSP"
ineed: "I need to know if I can get support to help me back into work rather than claim a benefit"
}
{
asa: "person claiming Employment Support Allowance whose health condition fluctuates"
ineed: "I need support as I am out of work"
}
{
asa: "short term employee, who has not been employed long enough to be entitled to SSP"
ineed: "I need to know what my options are"
}
{
asa: "person applying for Employment Support Allowance, I wish to commence my claim and be able to return to it to complete it"
}
{
asa: "person applying for Employment Support Allowance, without a landline telephone, I require a service that is fast in order to complete my application"
}
]
priority: "Top"
prototype: "http://esa-digital.herokuapp.com"
| 128023 | id: 3
name: "Employment and Support Allowance (ESA)"
description: "Lets customers who are unable to work through sickness or injury make a claim for Employment and Support Allowance."
theme: "Health & Disability"
location: "Leeds"
phase: "beta"
sro: "<NAME>"
service_man: "<NAME>"
phase_history:
discovery: [
{
label: "Completed"
date: "January 2016"
}
]
alpha: [
{
label: "Completed"
date: "July 2016"
}
]
beta: [
{
label: "Started"
date: "July 2016"
}
{
label: "Private beta started"
date: "September 2016"
}
{
label: "Public beta predicted"
date: "February 2017"
}
]
user_needs: [
{
asa: "person applying for Employment Support Allowance"
ineed: "to know at the earliest opportunity whether I am eligible or not"
}
{
asa: "person unable to work because of serious illness, injury or disability"
ineed: "I need financial support in order to survive"
}
{
asa: "person with a health condition"
ineed: "I need better information as to which benefits I can claim"
}
{
asa: "person with a health condition"
ineed: "I need a simple service"
so: "that I can easily claim Employment Support Allowance"
}
{
asa: "employer"
ineed: "I need more information available for Employment Support Allowance"
so: "that I can support my employee"
}
{
asa: "General Practioner"
ineed: "I need more information available for Employment Support Allowance"
so: "that I can support my patient"
}
{
asa: "Employment Support Allowance customer"
ineed: "I need to understand how a change in my circumstance could affect my claim"
}
{
asa: "person applying for Employment Support Allowance"
ineed: "I need to understand how other benefits may affect my claim"
}
{
asa: "person with an illness or health condition"
ineed: "I need a 'one stop shop'"
so: "that I can decide whether to claim a benefit"
}
{
asa: "Employment Support Allowance customer"
ineed: "I need a consistent service"
}
{
asa: "disadvantaged customer"
ineed: "I need assistance to make my claim for Employment Support Allowance"
}
{
asa: "low confidence user"
ineed: "I need assistance in making my claim for Employment Support Allowance"
}
{
asa: "person applying for Employment Support Allowance"
ineed: "I need to know the information I will be required to provide in order to make a claim"
}
{
asa: "Employment Support customer"
ineed: "I need support to help me get back into work"
}
{
asa: "General Practioner"
ineed: "I need a simple service with DWP"
}
{
asa: "person on Statutory Sick Pay (SSP)"
ineed: "I need to know what my options are when my SSP ends"
}
{
asa: "Employment Support Allowance customer"
ineed: "I need to understand what DWP'S expectations of me are"
}
{
asa: "person applying for Emplyment Support Allowance, I only want to provide information once in order to support my claim"
}
{
asa: "person applying for Employment Support Allowance, I want to make a claim at a time and location suitable to me"
}
{
asa: "person applying for Employment Support Allowance"
ineed: "I need to feel that my personal information is safe and secure"
}
{
asa: "self employed person"
ineed: "I need to know what what my benefit options are if I fall ill"
}
{
asa: "person claiming benefit"
ineed: "I need to understand my transition from one benefit onto Employment Support Allowance"
}
{
asa: "person leaving prison"
ineed: "I need money avalable as soon as I leave prison"
}
{
asa: "Employment Support Allowance customer"
ineed: "I need a service that is sympathetic to my health condition"
}
{
asa: "person in receipt of SSP"
ineed: "I need to know if I can get support to help me back into work rather than claim a benefit"
}
{
asa: "person claiming Employment Support Allowance whose health condition fluctuates"
ineed: "I need support as I am out of work"
}
{
asa: "short term employee, who has not been employed long enough to be entitled to SSP"
ineed: "I need to know what my options are"
}
{
asa: "person applying for Employment Support Allowance, I wish to commence my claim and be able to return to it to complete it"
}
{
asa: "person applying for Employment Support Allowance, without a landline telephone, I require a service that is fast in order to complete my application"
}
]
priority: "Top"
prototype: "http://esa-digital.herokuapp.com"
| true | id: 3
name: "Employment and Support Allowance (ESA)"
description: "Lets customers who are unable to work through sickness or injury make a claim for Employment and Support Allowance."
theme: "Health & Disability"
location: "Leeds"
phase: "beta"
sro: "PI:NAME:<NAME>END_PI"
service_man: "PI:NAME:<NAME>END_PI"
phase_history:
discovery: [
{
label: "Completed"
date: "January 2016"
}
]
alpha: [
{
label: "Completed"
date: "July 2016"
}
]
beta: [
{
label: "Started"
date: "July 2016"
}
{
label: "Private beta started"
date: "September 2016"
}
{
label: "Public beta predicted"
date: "February 2017"
}
]
user_needs: [
{
asa: "person applying for Employment Support Allowance"
ineed: "to know at the earliest opportunity whether I am eligible or not"
}
{
asa: "person unable to work because of serious illness, injury or disability"
ineed: "I need financial support in order to survive"
}
{
asa: "person with a health condition"
ineed: "I need better information as to which benefits I can claim"
}
{
asa: "person with a health condition"
ineed: "I need a simple service"
so: "that I can easily claim Employment Support Allowance"
}
{
asa: "employer"
ineed: "I need more information available for Employment Support Allowance"
so: "that I can support my employee"
}
{
asa: "General Practioner"
ineed: "I need more information available for Employment Support Allowance"
so: "that I can support my patient"
}
{
asa: "Employment Support Allowance customer"
ineed: "I need to understand how a change in my circumstance could affect my claim"
}
{
asa: "person applying for Employment Support Allowance"
ineed: "I need to understand how other benefits may affect my claim"
}
{
asa: "person with an illness or health condition"
ineed: "I need a 'one stop shop'"
so: "that I can decide whether to claim a benefit"
}
{
asa: "Employment Support Allowance customer"
ineed: "I need a consistent service"
}
{
asa: "disadvantaged customer"
ineed: "I need assistance to make my claim for Employment Support Allowance"
}
{
asa: "low confidence user"
ineed: "I need assistance in making my claim for Employment Support Allowance"
}
{
asa: "person applying for Employment Support Allowance"
ineed: "I need to know the information I will be required to provide in order to make a claim"
}
{
asa: "Employment Support customer"
ineed: "I need support to help me get back into work"
}
{
asa: "General Practioner"
ineed: "I need a simple service with DWP"
}
{
asa: "person on Statutory Sick Pay (SSP)"
ineed: "I need to know what my options are when my SSP ends"
}
{
asa: "Employment Support Allowance customer"
ineed: "I need to understand what DWP'S expectations of me are"
}
{
asa: "person applying for Emplyment Support Allowance, I only want to provide information once in order to support my claim"
}
{
asa: "person applying for Employment Support Allowance, I want to make a claim at a time and location suitable to me"
}
{
asa: "person applying for Employment Support Allowance"
ineed: "I need to feel that my personal information is safe and secure"
}
{
asa: "self employed person"
ineed: "I need to know what what my benefit options are if I fall ill"
}
{
asa: "person claiming benefit"
ineed: "I need to understand my transition from one benefit onto Employment Support Allowance"
}
{
asa: "person leaving prison"
ineed: "I need money avalable as soon as I leave prison"
}
{
asa: "Employment Support Allowance customer"
ineed: "I need a service that is sympathetic to my health condition"
}
{
asa: "person in receipt of SSP"
ineed: "I need to know if I can get support to help me back into work rather than claim a benefit"
}
{
asa: "person claiming Employment Support Allowance whose health condition fluctuates"
ineed: "I need support as I am out of work"
}
{
asa: "short term employee, who has not been employed long enough to be entitled to SSP"
ineed: "I need to know what my options are"
}
{
asa: "person applying for Employment Support Allowance, I wish to commence my claim and be able to return to it to complete it"
}
{
asa: "person applying for Employment Support Allowance, without a landline telephone, I require a service that is fast in order to complete my application"
}
]
priority: "Top"
prototype: "http://esa-digital.herokuapp.com"
|
[
{
"context": "mies: 'Врагов впереди'\n clips: 'Картриджей с патронами'\n bullets: 'Патронов в картридже'\n clips_found:",
"end": 6696,
"score": 0.6293697953224182,
"start": 6691,
"tag": "NAME",
"value": "онами"
},
{
"context": "же занял другой, более нормальный.\n \"\"\"\n head:... | game/translations/ru.coffee | Oreolek/shooter | 1 | module.exports.language =
terrible: "ужасно",
poor: "бедно",
mediocre: "средне",
fair: "нормально"
good: "хорошо"
great: "прекрасно"
superb: "идеально"
yes: "да"
no: "нет"
no_group_definition: "Невозможно найти определение группы {id}."
link_not_valid: "Ссылка '{link}' не выглядит правильной."
link_no_action: "Ссылка с ситуацией '.' должна иметь действие."
unknown_situation: "Вы не можете переместиться в неизвестную ситуацию {id}."
no_current_situation: "Я не могу отобразить, потому что у нас нет текущей ситуации."
no_local_storage: "Локальное хранилище недоступно."
random_seed_error: "Вы должны задать верное случайное зерно."
random_error: "Проинициализируйте Random с непустым зерном перед использованием."
dice_string_error: "не могу интерпретировать вашу cтроку кубиков: '{string}'."
erase_message: "Это навсегда удалит вашего персонажа и немедленно вернёт вас на старт игры. Вы уверены?"
start: (link) -> """
-- Антоша, тебе правда сейчас нужен пистолет?
Мы сидим, обнявшись, во дворе нашего дома.
Кристина #{link}.
Я поправляю кобуру на поясе.
"""
endintro: """
Раньше, чем я успеваю открыть рот, перед нами открывается большой зелёный портал,
из которого выходит высокий металлический человекоподобный робот с хромированным телом.
Он поднимает руку и наставляет её на Кристину.
Я выхватываю пистолет раньше, чем я успеваю увидеть короткую палочку в руке робота.
"""
firstmove: """
То, что я принял за робота, при попадании пули превращается в столб воды.
Он разливается по земле, потеряв палочку.
Кристина вскидывает руки в знак <i>Фитнаг.</i>
-- Стреляй во всё!
Как по команде, зелёная поверхность портала дрожит, и оттуда шагает хромированная нога.
"""
emptyclip: "Я выбрасываю пустой картридж."
player_hit:[
"""
Пуля прошивает голову существа, и оно превращается в воду, проливаясь на землю.
Но из портала уже выходит следующее.
""",
"""
Робот пытается увернуться, но попадает точнёхонько под пулю.
Он падает, разливаясь на землю.
""",
"""
Пуля разрывает жидкого робота на капли.
-- Слишком чистое небо для дождя, тебе не кажется?
""",
"""Враг разлетается на мелкие жидкие кусочки.""",
"""
Пуля пролетает сквозь робота и исчезает внутри портала.
На этой стороне остаётся только лужица жидкого хрома.
Судя по новому смертнику, выходящему из зелёной двери,
на той стороне я был не настолько точен.
"""
]
player_finished:[
"Я добиваю робота выстрелом в сердце.",
"Я добиваю врага точным выстрелом",
"Пуля пробивает голову робота, и он наконец разливается на пол.",
]
player_nicked:[
"Я отстреливаю ногу врага. Он падает, но продолжает медленно царапать путь ко мне руками."
"Я простреливаю руку робота. Он пошатывается и капает на землю, но продолжает идти."
]
shoot:[
"Выстрел",
"Бдыщь!",
"Выстрелить",
"Нажать на курок",
"Атака",
"Стрельба",
"СТРЕЛЯТЬ!",
"УБИТЬ ИХ ИЗ ПИСТОЛЕТА",
"НЕНАВИЖУ РОБОТОВ",
"АННИГИЛЯЦИЯ МЕХАНОИДОВ",
"Уничтожить механоидов",
"Отправить пулю в робота",
"Послать пулю взрывом",
"Нажать на курок во имя ЧЕЛОВЕЧЕСТВА",
"Присесть и выстрелить с колена",
"Взять пистолет в обе руки и нажать на курок",
"Не спеша прицелиться и выстрелить",
]
reload: "Перезарядить пистолет"
reload_response: "Я вставляю другой картридж в пистолет. Надеюсь, в нём есть патроны."
search: "Попросить Кристину поискать картриджи"
search_response:[
"""
-- Кристина! Патроны!
-- Ищу!
"""
"Я быстро оглядываюсь. Кристина бегает по дому в поисках моих заначек с патронами.",
"Я быстро оглядываюсь. Кристина уже ищет патроны.",
"Я надеюсь, она может держать барьер и искать патроны одновременно.",
"""
-- Кристина! Посмотри в морозилке!
-- Я клянусь, что ты и твои заначки...
Я надеюсь, она найдёт хотя бы наполовину потраченный картридж.
""",
"""
-- Кристина! В туалете, под сливным бачком!
-- Кто хранит патроны под сливным бачком?!
-- Ну я не помню, может, там уже их нет. Посмотри, прошу!
""",
"""
-- Кристина! Мне нужны патроны!
-- Ищу!
""",
]
finale:
"""
Ко мне подходит Кристина.
Она обнимает меня и целует.
-- Мой герой.
-- Тебе помочь закрыть портал?
-- Я сама виновата.
Не вспомнила про такую простую защиту.
-- Ну, ты могла бы в другой раз не унижать так много волшебников сразу.
Возможно, они бы не прислали своих големов или как это называется.
-- Конструкты. А ты мог бы быть лапушкой и держать свои патроны вместе с
оружием где-нибудь в оружейном сейфе.
-- А если...
-- А ты поставь второй секретный сейф.
-- Сделаю. Так что, мы ещё успеваем закончить романтический вечер?
-- Ты обещаешь быть жестоким и безоружным?
-- Я буду чист и многозаряден.
Я поцеловал Кристину и оставил её рядом с зелёным порталом.
Думаю, мне не надо беспокоиться за её безопасность.
Она может остановить любые пули и заклинания.
И всё-таки я оставлю тайник на чердаке с ракетами на всякий случай.
"""
finale_perfect: """
25 выстрелов.
Вот всё, что потребовалось.
Была ли это невероятная удача, или вмешательство высшей силы, но ещё осталось много времени.
Моя работа сделана.
А теперь наш вечер вдвоём будет таким, каким он должен быть.
"""
credits: """
<h3>КОНЕЦ</h3>
В игре использованы следующие звуковые эффекты и изображения в общественном достоянии и под лицензией CC-BY:
* SpartanX109 - [Desert Eagle Fire](http://freesound.org/people/SpartanX109/sounds/89147/)
* ngphil22 - [DEagle wCasing](http://freesound.org/people/ngphil22/sounds/233322/)
* watupgroupie - [gunshots](http://freesound.org/people/watupgroupie/sounds/36815/)
* Yoyodaman234 - [metal footstep 1](http://freesound.org/people/Yoyodaman234/sounds/223168/)
* qubodup - [Bullet silhoettes](https://openclipart.org/detail/29029/bullet-silhouettes)
"""
clips_not_found:[
"-- Не могу найти!",
"""
-- Ничего нет!
-- Ну хотя бы один!
-- Я держу барьер! Экономь патроны!
""",
"""
-- Пусто!
-- Ты посмотрела...
-- Да я везде уже посмотрела, нет больше твоих картриджей!
-- Ладно, дай тогда вспомню, где ещё были заначки.
""",
"-- Пусто!",
"-- Ничего!",
"-- Вспоминай лучше! Тут чисто!",
"""
-- Ты не можешь хранить все патроны в одном месте?!
Их не найти!
-- Это система!
-- Это мания!
""",
]
enemies: 'Врагов впереди'
clips: 'Картриджей с патронами'
bullets: 'Патронов в картридже'
clips_found:[
"Ага! Есть один. Надеюсь, в нём есть патроны.",
"А, вот какой-то. На вес тяжёлый -- надеюсь, в нём есть патроны."
]
player_missed:[
"Пуля пролетает над левым плечом робота.",
"Робот вовремя уворачивается от выстрела. Ничего, в следующий раз я не промахнусь.",
"Чёрт! Промазал.",
"Мимо! Ну что за невезение.",
"На заметку: надо чаще упражняться в стрельбе. Часто промахиваюсь.",
"Чёрт! Почему я промазал именно сейчас?!",
]
trick_shot: "Попробовать хитрый выстрел",
trick_shot_discover: (character) ->
"""
Я пересчитываю картриджи.
Осталось всего четыре.
Я убил #{character.sandbox.killed} роботов, то есть, впереди ещё... ой.
ОЙ.
Надо экономить патроны.
Я могу попробовать хитрые выстрелы, но это -- большой риск.
"""
player_trickshot: [
"""
Я разбегаюсь и прыгаю, стреляя в полёте.
Пуля пролетает сквозь голову робота прямо в следующего, вырубая обоих.
""",
"""
Я замечаю шевеление в портале.
Пуля пронзает робота и улетает сквозь портал.
Через зелёную дверь падает тело робота, растекаясь в полёте.
"""
]
christine: [
"пахнет сладким мёдом",
"смотрит вдаль, о чём-то задумавшись",
"крепко обнимает меня, впиваясь ногтями в плечо",
]
pacifist: """
-- Не стреляйте! Я пацифист!
Один из роботов поднимает руки вверх.
На его лице написана мольба.
"""
shoot_pacifist: (link) -> """
Я простреливаю его блестящую металлическую #{link}.
Из портала выходит другой робот, который ударом ноги валит на землю товарища.
Затем он наступает на его голову.
Странный робот стекает в лужу, но его место уже занял другой, более нормальный.
"""
head: "голову"
arm: "руку"
leg: "ногу"
spare_pacifist: """
Я опускаю пистолет.
-- Спасибо! -- кричит странный робот. -- Я обязательно...
Тут его толкают сзади, и он падает на землю лицом вниз.
-- Директива А028. Девиантное поведение. Уничтожить.
Робот, следующий за ним, наносит пацифисту мощный удар в затылок.
После этого он перешагивает через свежую лужицу и смотрит на меня злым взглядом.
Похоже, битва продолжается.
"""
firststeps: "Это шаги? Похоже, что-то приближается по ту сторону портала."
secondsteps: "Шаги становятся громче. Оно большое."
thirdsteps: "Уже близко. Совсем близко."
boss: """
Из портала вылезает гигантская блестящая Рука.
Она цепляется за край портала и начинает его растягивать.
Кристина кричит:
-- Оно слишком большое! Я не смогу удержать!
Из растянутого портала показывается ведро.
Это голова робота-титана, который мог бы таранить города.
Я точно не хочу впускать его на задний двор своего дома.
"""
shoot_boss: "Успокоить титана свинцом"
answer1_option: "Милая, я просто за тебя беспокоюсь."
answer1: """
-- Милая, я просто за тебя беспокоюсь.
-- Почему?
Я не на работе.
Ты не на работе.
Вокруг дома стоит надёжная защита.
"""
branch1_a_option: "Защиты недостаточно."
branch1_a: """
-- Защиты недостаточно. -- я кладу руку на рукоять пистолета.
-- Антоша, это -- наш романтический вечер. Ты можешь оставить пистолет в доме.
"""
branch1_b_option: "Я всегда держу его при себе."
branch1_b: """
-- Я всегда держу его при себе. Это нормально.
-- Антон!
Я три недели ждала, когда у нас наконец-то будет вечер на двоих.
Положи пистолет и расслабься.
"""
dlg_finale1_option: "Я и так расслаблен."
dlg_finale1: (link) -> """
-- О чём ты говоришь?
Я и так расслаблен.
Смотри, какой красивый закат, эти #{link}.
Только ты и я, как ты и хотела.
-- Да, но я не хочу ни в кого стрелять!
"""
dlg_finale1_cycle: [
"птички поют",
"цветочки растут",
"деревья так похожи на магические руны",
]
answer2_option: "Я его даже не трогаю."
answer2: """
-- Я его даже не трогаю.
-- Да, но ты держишь его рядом.
Ты не можешь расслабиться, я чувствую.
"""
lazy_option: "Я просто не вынимал его из кобуры."
lazy: """
-- Я просто не вынимал его из кобуры.
Какое это имеет значение?
-- Только не говори мне, что ты и на предохранитель поленился его поставить.
"""
shoot_pacifist_option: "Убить пацифиста"
spare_pacifist_option: "Опустить оружие"
endintro_option: "Объясниться и помириться"
lazy2_option: "Конечно, он на предохранителе."
lazy2: """
-- Конечно, он на предохранителе.
Видишь, ничего страшного. -- я вытащил пистолет, чтобы показать ей.
-- Антон!
Ты вообще меня слушаешь?!
Не трогай пистолет!
Я со вздохом возращаю оружие в кобуру.
"""
lazy3_option: "Я не собираюсь стрелять."
lazy3: """
-- Я не собираюсь стрелять.
-- Тогда зачем ты его взял?!
"""
dlg_finale2_option: "Это просто мой пистолет."
dlg_finale2: """
-- Это просто мой пистолет.
Лучше посмотри на эти розовые облака в небе.
Вон то похоже на зайчика, правда?
-- О Великие Боги, у тебя и патроны с собой?!
"""
| 146551 | module.exports.language =
terrible: "ужасно",
poor: "бедно",
mediocre: "средне",
fair: "нормально"
good: "хорошо"
great: "прекрасно"
superb: "идеально"
yes: "да"
no: "нет"
no_group_definition: "Невозможно найти определение группы {id}."
link_not_valid: "Ссылка '{link}' не выглядит правильной."
link_no_action: "Ссылка с ситуацией '.' должна иметь действие."
unknown_situation: "Вы не можете переместиться в неизвестную ситуацию {id}."
no_current_situation: "Я не могу отобразить, потому что у нас нет текущей ситуации."
no_local_storage: "Локальное хранилище недоступно."
random_seed_error: "Вы должны задать верное случайное зерно."
random_error: "Проинициализируйте Random с непустым зерном перед использованием."
dice_string_error: "не могу интерпретировать вашу cтроку кубиков: '{string}'."
erase_message: "Это навсегда удалит вашего персонажа и немедленно вернёт вас на старт игры. Вы уверены?"
start: (link) -> """
-- Антоша, тебе правда сейчас нужен пистолет?
Мы сидим, обнявшись, во дворе нашего дома.
Кристина #{link}.
Я поправляю кобуру на поясе.
"""
endintro: """
Раньше, чем я успеваю открыть рот, перед нами открывается большой зелёный портал,
из которого выходит высокий металлический человекоподобный робот с хромированным телом.
Он поднимает руку и наставляет её на Кристину.
Я выхватываю пистолет раньше, чем я успеваю увидеть короткую палочку в руке робота.
"""
firstmove: """
То, что я принял за робота, при попадании пули превращается в столб воды.
Он разливается по земле, потеряв палочку.
Кристина вскидывает руки в знак <i>Фитнаг.</i>
-- Стреляй во всё!
Как по команде, зелёная поверхность портала дрожит, и оттуда шагает хромированная нога.
"""
emptyclip: "Я выбрасываю пустой картридж."
player_hit:[
"""
Пуля прошивает голову существа, и оно превращается в воду, проливаясь на землю.
Но из портала уже выходит следующее.
""",
"""
Робот пытается увернуться, но попадает точнёхонько под пулю.
Он падает, разливаясь на землю.
""",
"""
Пуля разрывает жидкого робота на капли.
-- Слишком чистое небо для дождя, тебе не кажется?
""",
"""Враг разлетается на мелкие жидкие кусочки.""",
"""
Пуля пролетает сквозь робота и исчезает внутри портала.
На этой стороне остаётся только лужица жидкого хрома.
Судя по новому смертнику, выходящему из зелёной двери,
на той стороне я был не настолько точен.
"""
]
player_finished:[
"Я добиваю робота выстрелом в сердце.",
"Я добиваю врага точным выстрелом",
"Пуля пробивает голову робота, и он наконец разливается на пол.",
]
player_nicked:[
"Я отстреливаю ногу врага. Он падает, но продолжает медленно царапать путь ко мне руками."
"Я простреливаю руку робота. Он пошатывается и капает на землю, но продолжает идти."
]
shoot:[
"Выстрел",
"Бдыщь!",
"Выстрелить",
"Нажать на курок",
"Атака",
"Стрельба",
"СТРЕЛЯТЬ!",
"УБИТЬ ИХ ИЗ ПИСТОЛЕТА",
"НЕНАВИЖУ РОБОТОВ",
"АННИГИЛЯЦИЯ МЕХАНОИДОВ",
"Уничтожить механоидов",
"Отправить пулю в робота",
"Послать пулю взрывом",
"Нажать на курок во имя ЧЕЛОВЕЧЕСТВА",
"Присесть и выстрелить с колена",
"Взять пистолет в обе руки и нажать на курок",
"Не спеша прицелиться и выстрелить",
]
reload: "Перезарядить пистолет"
reload_response: "Я вставляю другой картридж в пистолет. Надеюсь, в нём есть патроны."
search: "Попросить Кристину поискать картриджи"
search_response:[
"""
-- Кристина! Патроны!
-- Ищу!
"""
"Я быстро оглядываюсь. Кристина бегает по дому в поисках моих заначек с патронами.",
"Я быстро оглядываюсь. Кристина уже ищет патроны.",
"Я надеюсь, она может держать барьер и искать патроны одновременно.",
"""
-- Кристина! Посмотри в морозилке!
-- Я клянусь, что ты и твои заначки...
Я надеюсь, она найдёт хотя бы наполовину потраченный картридж.
""",
"""
-- Кристина! В туалете, под сливным бачком!
-- Кто хранит патроны под сливным бачком?!
-- Ну я не помню, может, там уже их нет. Посмотри, прошу!
""",
"""
-- Кристина! Мне нужны патроны!
-- Ищу!
""",
]
finale:
"""
Ко мне подходит Кристина.
Она обнимает меня и целует.
-- Мой герой.
-- Тебе помочь закрыть портал?
-- Я сама виновата.
Не вспомнила про такую простую защиту.
-- Ну, ты могла бы в другой раз не унижать так много волшебников сразу.
Возможно, они бы не прислали своих големов или как это называется.
-- Конструкты. А ты мог бы быть лапушкой и держать свои патроны вместе с
оружием где-нибудь в оружейном сейфе.
-- А если...
-- А ты поставь второй секретный сейф.
-- Сделаю. Так что, мы ещё успеваем закончить романтический вечер?
-- Ты обещаешь быть жестоким и безоружным?
-- Я буду чист и многозаряден.
Я поцеловал Кристину и оставил её рядом с зелёным порталом.
Думаю, мне не надо беспокоиться за её безопасность.
Она может остановить любые пули и заклинания.
И всё-таки я оставлю тайник на чердаке с ракетами на всякий случай.
"""
finale_perfect: """
25 выстрелов.
Вот всё, что потребовалось.
Была ли это невероятная удача, или вмешательство высшей силы, но ещё осталось много времени.
Моя работа сделана.
А теперь наш вечер вдвоём будет таким, каким он должен быть.
"""
credits: """
<h3>КОНЕЦ</h3>
В игре использованы следующие звуковые эффекты и изображения в общественном достоянии и под лицензией CC-BY:
* SpartanX109 - [Desert Eagle Fire](http://freesound.org/people/SpartanX109/sounds/89147/)
* ngphil22 - [DEagle wCasing](http://freesound.org/people/ngphil22/sounds/233322/)
* watupgroupie - [gunshots](http://freesound.org/people/watupgroupie/sounds/36815/)
* Yoyodaman234 - [metal footstep 1](http://freesound.org/people/Yoyodaman234/sounds/223168/)
* qubodup - [Bullet silhoettes](https://openclipart.org/detail/29029/bullet-silhouettes)
"""
clips_not_found:[
"-- Не могу найти!",
"""
-- Ничего нет!
-- Ну хотя бы один!
-- Я держу барьер! Экономь патроны!
""",
"""
-- Пусто!
-- Ты посмотрела...
-- Да я везде уже посмотрела, нет больше твоих картриджей!
-- Ладно, дай тогда вспомню, где ещё были заначки.
""",
"-- Пусто!",
"-- Ничего!",
"-- Вспоминай лучше! Тут чисто!",
"""
-- Ты не можешь хранить все патроны в одном месте?!
Их не найти!
-- Это система!
-- Это мания!
""",
]
enemies: 'Врагов впереди'
clips: 'Картриджей с патр<NAME>'
bullets: 'Патронов в картридже'
clips_found:[
"Ага! Есть один. Надеюсь, в нём есть патроны.",
"А, вот какой-то. На вес тяжёлый -- надеюсь, в нём есть патроны."
]
player_missed:[
"Пуля пролетает над левым плечом робота.",
"Робот вовремя уворачивается от выстрела. Ничего, в следующий раз я не промахнусь.",
"Чёрт! Промазал.",
"Мимо! Ну что за невезение.",
"На заметку: надо чаще упражняться в стрельбе. Часто промахиваюсь.",
"Чёрт! Почему я промазал именно сейчас?!",
]
trick_shot: "Попробовать хитрый выстрел",
trick_shot_discover: (character) ->
"""
Я пересчитываю картриджи.
Осталось всего четыре.
Я убил #{character.sandbox.killed} роботов, то есть, впереди ещё... ой.
ОЙ.
Надо экономить патроны.
Я могу попробовать хитрые выстрелы, но это -- большой риск.
"""
player_trickshot: [
"""
Я разбегаюсь и прыгаю, стреляя в полёте.
Пуля пролетает сквозь голову робота прямо в следующего, вырубая обоих.
""",
"""
Я замечаю шевеление в портале.
Пуля пронзает робота и улетает сквозь портал.
Через зелёную дверь падает тело робота, растекаясь в полёте.
"""
]
christine: [
"пахнет сладким мёдом",
"смотрит вдаль, о чём-то задумавшись",
"крепко обнимает меня, впиваясь ногтями в плечо",
]
pacifist: """
-- Не стреляйте! Я пацифист!
Один из роботов поднимает руки вверх.
На его лице написана мольба.
"""
shoot_pacifist: (link) -> """
Я простреливаю его блестящую металлическую #{link}.
Из портала выходит другой робот, который ударом ноги валит на землю товарища.
Затем он наступает на его голову.
Странный робот стекает в лужу, но его место уже занял другой, более нормальный.
"""
head: "<NAME>"
arm: "руку"
leg: "ногу"
spare_pacifist: """
Я опускаю пистолет.
-- Спасибо! -- кричит странный робот. -- Я обязательно...
Тут его толкают сзади, и он падает на землю лицом вниз.
-- Директива А028. Девиантное поведение. Уничтожить.
Робот, следующий за ним, наносит пацифисту мощный удар в затылок.
После этого он перешагивает через свежую лужицу и смотрит на меня злым взглядом.
Похоже, битва продолжается.
"""
firststeps: "Это шаги? Похоже, что-то приближается по ту сторону портала."
secondsteps: "Шаги становятся громче. Оно большое."
thirdsteps: "Уже близко. Совсем близко."
boss: """
Из портала вылезает гигантская блестящая Рука.
Она цепляется за край портала и начинает его растягивать.
Кристина кричит:
-- Оно слишком большое! Я не смогу удержать!
Из растянутого портала показывается ведро.
Это голова робота-титана, который мог бы таранить города.
Я точно не хочу впускать его на задний двор своего дома.
"""
shoot_boss: "Успокоить титана свинцом"
answer1_option: "<NAME>, я просто за тебя беспокоюсь."
answer1: """
-- <NAME>, я просто за тебя беспокоюсь.
-- Почему?
Я не на работе.
Ты не на работе.
Вокруг дома стоит надёжная защита.
"""
branch1_a_option: "Защиты недостаточно."
branch1_a: """
-- Защиты недостаточно. -- я кладу руку на рукоять пистолета.
-- <NAME>, это -- наш романтический вечер. Ты можешь оставить пистолет в доме.
"""
branch1_b_option: "Я всегда держу его при себе."
branch1_b: """
-- Я всегда держу его при себе. Это нормально.
-- <NAME>!
Я три недели ждала, когда у нас наконец-то будет вечер на двоих.
Положи пистолет и расслабься.
"""
dlg_finale1_option: "Я и так расслаблен."
dlg_finale1: (link) -> """
-- О чём ты говоришь?
Я и так расслаблен.
Смотри, какой красивый закат, эти #{link}.
Только ты и я, как ты и хотела.
-- Да, но я не хочу ни в кого стрелять!
"""
dlg_finale1_cycle: [
"птички поют",
"цветочки растут",
"деревья так похожи на магические руны",
]
answer2_option: "Я его даже не трогаю."
answer2: """
-- Я его даже не трогаю.
-- Да, но ты держишь его рядом.
Ты не можешь расслабиться, я чувствую.
"""
lazy_option: "Я просто не вынимал его из кобуры."
lazy: """
-- Я просто не вынимал его из кобуры.
Какое это имеет значение?
-- Только не говори мне, что ты и на предохранитель поленился его поставить.
"""
shoot_pacifist_option: "Убить пацифиста"
spare_pacifist_option: "Опустить оружие"
endintro_option: "Объясниться и помириться"
lazy2_option: "Конечно, он на предохранителе."
lazy2: """
-- Конечно, он на предохранителе.
Видишь, ничего страшного. -- я вытащил пистолет, чтобы показать ей.
-- <NAME>!
Ты вообще меня слушаешь?!
Не трогай пистолет!
Я со вздохом возращаю оружие в кобуру.
"""
lazy3_option: "Я не собираюсь стрелять."
lazy3: """
-- Я не собираюсь стрелять.
-- Тогда зачем ты его взял?!
"""
dlg_finale2_option: "Это просто мой пистолет."
dlg_finale2: """
-- Это просто мой пистолет.
Лучше посмотри на эти розовые облака в небе.
Вон то похоже на зайчика, правда?
-- О Великие Боги, у тебя и патроны с собой?!
"""
| true | module.exports.language =
terrible: "ужасно",
poor: "бедно",
mediocre: "средне",
fair: "нормально"
good: "хорошо"
great: "прекрасно"
superb: "идеально"
yes: "да"
no: "нет"
no_group_definition: "Невозможно найти определение группы {id}."
link_not_valid: "Ссылка '{link}' не выглядит правильной."
link_no_action: "Ссылка с ситуацией '.' должна иметь действие."
unknown_situation: "Вы не можете переместиться в неизвестную ситуацию {id}."
no_current_situation: "Я не могу отобразить, потому что у нас нет текущей ситуации."
no_local_storage: "Локальное хранилище недоступно."
random_seed_error: "Вы должны задать верное случайное зерно."
random_error: "Проинициализируйте Random с непустым зерном перед использованием."
dice_string_error: "не могу интерпретировать вашу cтроку кубиков: '{string}'."
erase_message: "Это навсегда удалит вашего персонажа и немедленно вернёт вас на старт игры. Вы уверены?"
start: (link) -> """
-- Антоша, тебе правда сейчас нужен пистолет?
Мы сидим, обнявшись, во дворе нашего дома.
Кристина #{link}.
Я поправляю кобуру на поясе.
"""
endintro: """
Раньше, чем я успеваю открыть рот, перед нами открывается большой зелёный портал,
из которого выходит высокий металлический человекоподобный робот с хромированным телом.
Он поднимает руку и наставляет её на Кристину.
Я выхватываю пистолет раньше, чем я успеваю увидеть короткую палочку в руке робота.
"""
firstmove: """
То, что я принял за робота, при попадании пули превращается в столб воды.
Он разливается по земле, потеряв палочку.
Кристина вскидывает руки в знак <i>Фитнаг.</i>
-- Стреляй во всё!
Как по команде, зелёная поверхность портала дрожит, и оттуда шагает хромированная нога.
"""
emptyclip: "Я выбрасываю пустой картридж."
player_hit:[
"""
Пуля прошивает голову существа, и оно превращается в воду, проливаясь на землю.
Но из портала уже выходит следующее.
""",
"""
Робот пытается увернуться, но попадает точнёхонько под пулю.
Он падает, разливаясь на землю.
""",
"""
Пуля разрывает жидкого робота на капли.
-- Слишком чистое небо для дождя, тебе не кажется?
""",
"""Враг разлетается на мелкие жидкие кусочки.""",
"""
Пуля пролетает сквозь робота и исчезает внутри портала.
На этой стороне остаётся только лужица жидкого хрома.
Судя по новому смертнику, выходящему из зелёной двери,
на той стороне я был не настолько точен.
"""
]
player_finished:[
"Я добиваю робота выстрелом в сердце.",
"Я добиваю врага точным выстрелом",
"Пуля пробивает голову робота, и он наконец разливается на пол.",
]
player_nicked:[
"Я отстреливаю ногу врага. Он падает, но продолжает медленно царапать путь ко мне руками."
"Я простреливаю руку робота. Он пошатывается и капает на землю, но продолжает идти."
]
shoot:[
"Выстрел",
"Бдыщь!",
"Выстрелить",
"Нажать на курок",
"Атака",
"Стрельба",
"СТРЕЛЯТЬ!",
"УБИТЬ ИХ ИЗ ПИСТОЛЕТА",
"НЕНАВИЖУ РОБОТОВ",
"АННИГИЛЯЦИЯ МЕХАНОИДОВ",
"Уничтожить механоидов",
"Отправить пулю в робота",
"Послать пулю взрывом",
"Нажать на курок во имя ЧЕЛОВЕЧЕСТВА",
"Присесть и выстрелить с колена",
"Взять пистолет в обе руки и нажать на курок",
"Не спеша прицелиться и выстрелить",
]
reload: "Перезарядить пистолет"
reload_response: "Я вставляю другой картридж в пистолет. Надеюсь, в нём есть патроны."
search: "Попросить Кристину поискать картриджи"
search_response:[
"""
-- Кристина! Патроны!
-- Ищу!
"""
"Я быстро оглядываюсь. Кристина бегает по дому в поисках моих заначек с патронами.",
"Я быстро оглядываюсь. Кристина уже ищет патроны.",
"Я надеюсь, она может держать барьер и искать патроны одновременно.",
"""
-- Кристина! Посмотри в морозилке!
-- Я клянусь, что ты и твои заначки...
Я надеюсь, она найдёт хотя бы наполовину потраченный картридж.
""",
"""
-- Кристина! В туалете, под сливным бачком!
-- Кто хранит патроны под сливным бачком?!
-- Ну я не помню, может, там уже их нет. Посмотри, прошу!
""",
"""
-- Кристина! Мне нужны патроны!
-- Ищу!
""",
]
finale:
"""
Ко мне подходит Кристина.
Она обнимает меня и целует.
-- Мой герой.
-- Тебе помочь закрыть портал?
-- Я сама виновата.
Не вспомнила про такую простую защиту.
-- Ну, ты могла бы в другой раз не унижать так много волшебников сразу.
Возможно, они бы не прислали своих големов или как это называется.
-- Конструкты. А ты мог бы быть лапушкой и держать свои патроны вместе с
оружием где-нибудь в оружейном сейфе.
-- А если...
-- А ты поставь второй секретный сейф.
-- Сделаю. Так что, мы ещё успеваем закончить романтический вечер?
-- Ты обещаешь быть жестоким и безоружным?
-- Я буду чист и многозаряден.
Я поцеловал Кристину и оставил её рядом с зелёным порталом.
Думаю, мне не надо беспокоиться за её безопасность.
Она может остановить любые пули и заклинания.
И всё-таки я оставлю тайник на чердаке с ракетами на всякий случай.
"""
finale_perfect: """
25 выстрелов.
Вот всё, что потребовалось.
Была ли это невероятная удача, или вмешательство высшей силы, но ещё осталось много времени.
Моя работа сделана.
А теперь наш вечер вдвоём будет таким, каким он должен быть.
"""
credits: """
<h3>КОНЕЦ</h3>
В игре использованы следующие звуковые эффекты и изображения в общественном достоянии и под лицензией CC-BY:
* SpartanX109 - [Desert Eagle Fire](http://freesound.org/people/SpartanX109/sounds/89147/)
* ngphil22 - [DEagle wCasing](http://freesound.org/people/ngphil22/sounds/233322/)
* watupgroupie - [gunshots](http://freesound.org/people/watupgroupie/sounds/36815/)
* Yoyodaman234 - [metal footstep 1](http://freesound.org/people/Yoyodaman234/sounds/223168/)
* qubodup - [Bullet silhoettes](https://openclipart.org/detail/29029/bullet-silhouettes)
"""
clips_not_found:[
"-- Не могу найти!",
"""
-- Ничего нет!
-- Ну хотя бы один!
-- Я держу барьер! Экономь патроны!
""",
"""
-- Пусто!
-- Ты посмотрела...
-- Да я везде уже посмотрела, нет больше твоих картриджей!
-- Ладно, дай тогда вспомню, где ещё были заначки.
""",
"-- Пусто!",
"-- Ничего!",
"-- Вспоминай лучше! Тут чисто!",
"""
-- Ты не можешь хранить все патроны в одном месте?!
Их не найти!
-- Это система!
-- Это мания!
""",
]
enemies: 'Врагов впереди'
clips: 'Картриджей с патрPI:NAME:<NAME>END_PI'
bullets: 'Патронов в картридже'
clips_found:[
"Ага! Есть один. Надеюсь, в нём есть патроны.",
"А, вот какой-то. На вес тяжёлый -- надеюсь, в нём есть патроны."
]
player_missed:[
"Пуля пролетает над левым плечом робота.",
"Робот вовремя уворачивается от выстрела. Ничего, в следующий раз я не промахнусь.",
"Чёрт! Промазал.",
"Мимо! Ну что за невезение.",
"На заметку: надо чаще упражняться в стрельбе. Часто промахиваюсь.",
"Чёрт! Почему я промазал именно сейчас?!",
]
trick_shot: "Попробовать хитрый выстрел",
trick_shot_discover: (character) ->
"""
Я пересчитываю картриджи.
Осталось всего четыре.
Я убил #{character.sandbox.killed} роботов, то есть, впереди ещё... ой.
ОЙ.
Надо экономить патроны.
Я могу попробовать хитрые выстрелы, но это -- большой риск.
"""
player_trickshot: [
"""
Я разбегаюсь и прыгаю, стреляя в полёте.
Пуля пролетает сквозь голову робота прямо в следующего, вырубая обоих.
""",
"""
Я замечаю шевеление в портале.
Пуля пронзает робота и улетает сквозь портал.
Через зелёную дверь падает тело робота, растекаясь в полёте.
"""
]
christine: [
"пахнет сладким мёдом",
"смотрит вдаль, о чём-то задумавшись",
"крепко обнимает меня, впиваясь ногтями в плечо",
]
pacifist: """
-- Не стреляйте! Я пацифист!
Один из роботов поднимает руки вверх.
На его лице написана мольба.
"""
shoot_pacifist: (link) -> """
Я простреливаю его блестящую металлическую #{link}.
Из портала выходит другой робот, который ударом ноги валит на землю товарища.
Затем он наступает на его голову.
Странный робот стекает в лужу, но его место уже занял другой, более нормальный.
"""
head: "PI:NAME:<NAME>END_PI"
arm: "руку"
leg: "ногу"
spare_pacifist: """
Я опускаю пистолет.
-- Спасибо! -- кричит странный робот. -- Я обязательно...
Тут его толкают сзади, и он падает на землю лицом вниз.
-- Директива А028. Девиантное поведение. Уничтожить.
Робот, следующий за ним, наносит пацифисту мощный удар в затылок.
После этого он перешагивает через свежую лужицу и смотрит на меня злым взглядом.
Похоже, битва продолжается.
"""
firststeps: "Это шаги? Похоже, что-то приближается по ту сторону портала."
secondsteps: "Шаги становятся громче. Оно большое."
thirdsteps: "Уже близко. Совсем близко."
boss: """
Из портала вылезает гигантская блестящая Рука.
Она цепляется за край портала и начинает его растягивать.
Кристина кричит:
-- Оно слишком большое! Я не смогу удержать!
Из растянутого портала показывается ведро.
Это голова робота-титана, который мог бы таранить города.
Я точно не хочу впускать его на задний двор своего дома.
"""
shoot_boss: "Успокоить титана свинцом"
answer1_option: "PI:NAME:<NAME>END_PI, я просто за тебя беспокоюсь."
answer1: """
-- PI:NAME:<NAME>END_PI, я просто за тебя беспокоюсь.
-- Почему?
Я не на работе.
Ты не на работе.
Вокруг дома стоит надёжная защита.
"""
branch1_a_option: "Защиты недостаточно."
branch1_a: """
-- Защиты недостаточно. -- я кладу руку на рукоять пистолета.
-- PI:NAME:<NAME>END_PI, это -- наш романтический вечер. Ты можешь оставить пистолет в доме.
"""
branch1_b_option: "Я всегда держу его при себе."
branch1_b: """
-- Я всегда держу его при себе. Это нормально.
-- PI:NAME:<NAME>END_PI!
Я три недели ждала, когда у нас наконец-то будет вечер на двоих.
Положи пистолет и расслабься.
"""
dlg_finale1_option: "Я и так расслаблен."
dlg_finale1: (link) -> """
-- О чём ты говоришь?
Я и так расслаблен.
Смотри, какой красивый закат, эти #{link}.
Только ты и я, как ты и хотела.
-- Да, но я не хочу ни в кого стрелять!
"""
dlg_finale1_cycle: [
"птички поют",
"цветочки растут",
"деревья так похожи на магические руны",
]
answer2_option: "Я его даже не трогаю."
answer2: """
-- Я его даже не трогаю.
-- Да, но ты держишь его рядом.
Ты не можешь расслабиться, я чувствую.
"""
lazy_option: "Я просто не вынимал его из кобуры."
lazy: """
-- Я просто не вынимал его из кобуры.
Какое это имеет значение?
-- Только не говори мне, что ты и на предохранитель поленился его поставить.
"""
shoot_pacifist_option: "Убить пацифиста"
spare_pacifist_option: "Опустить оружие"
endintro_option: "Объясниться и помириться"
lazy2_option: "Конечно, он на предохранителе."
lazy2: """
-- Конечно, он на предохранителе.
Видишь, ничего страшного. -- я вытащил пистолет, чтобы показать ей.
-- PI:NAME:<NAME>END_PI!
Ты вообще меня слушаешь?!
Не трогай пистолет!
Я со вздохом возращаю оружие в кобуру.
"""
lazy3_option: "Я не собираюсь стрелять."
lazy3: """
-- Я не собираюсь стрелять.
-- Тогда зачем ты его взял?!
"""
dlg_finale2_option: "Это просто мой пистолет."
dlg_finale2: """
-- Это просто мой пистолет.
Лучше посмотри на эти розовые облака в небе.
Вон то похоже на зайчика, правда?
-- О Великие Боги, у тебя и патроны с собой?!
"""
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.