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": " checkMeeting presence.meeting\n connections[@connection.id] = presence.id\n presence.updated = new Date\n",
"end": 649,
"score": 0.7229645252227783,
"start": 636,
"tag": "EMAIL",
"value": "connection.id"
}
] | lib/presence.coffee | diomidov/comingle | 0 | import {Mongo} from 'meteor/mongo'
import {check, Match} from 'meteor/check'
import {validId, checkId} from './id.coffee'
import {checkMeeting} from './meetings.coffee'
export Presence = new Mongo.Collection 'presence'
## Mapping from Meteor connection id to presenceId [server only]
export connections = {}
Meteor.methods
presenceUpdate: (presence) ->
check presence,
id: Match.Where validId
meeting: Match.Where validId
name: String
rooms:
visible: [Match.Where validId]
invisible: [Match.Where validId]
unless @isSimulation
checkMeeting presence.meeting
connections[@connection.id] = presence.id
presence.updated = new Date
Presence.update
id: presence.id
meeting: presence.meeting
,
$set:
name: presence.name
rooms: presence.rooms
$setOnInsert:
id: presence.id
meeting: presence.meeting
,
upsert: true
presenceRemove: (presenceId) ->
checkId presenceId
Presence.remove id: presenceId
| 199997 | import {Mongo} from 'meteor/mongo'
import {check, Match} from 'meteor/check'
import {validId, checkId} from './id.coffee'
import {checkMeeting} from './meetings.coffee'
export Presence = new Mongo.Collection 'presence'
## Mapping from Meteor connection id to presenceId [server only]
export connections = {}
Meteor.methods
presenceUpdate: (presence) ->
check presence,
id: Match.Where validId
meeting: Match.Where validId
name: String
rooms:
visible: [Match.Where validId]
invisible: [Match.Where validId]
unless @isSimulation
checkMeeting presence.meeting
connections[@<EMAIL>] = presence.id
presence.updated = new Date
Presence.update
id: presence.id
meeting: presence.meeting
,
$set:
name: presence.name
rooms: presence.rooms
$setOnInsert:
id: presence.id
meeting: presence.meeting
,
upsert: true
presenceRemove: (presenceId) ->
checkId presenceId
Presence.remove id: presenceId
| true | import {Mongo} from 'meteor/mongo'
import {check, Match} from 'meteor/check'
import {validId, checkId} from './id.coffee'
import {checkMeeting} from './meetings.coffee'
export Presence = new Mongo.Collection 'presence'
## Mapping from Meteor connection id to presenceId [server only]
export connections = {}
Meteor.methods
presenceUpdate: (presence) ->
check presence,
id: Match.Where validId
meeting: Match.Where validId
name: String
rooms:
visible: [Match.Where validId]
invisible: [Match.Where validId]
unless @isSimulation
checkMeeting presence.meeting
connections[@PI:EMAIL:<EMAIL>END_PI] = presence.id
presence.updated = new Date
Presence.update
id: presence.id
meeting: presence.meeting
,
$set:
name: presence.name
rooms: presence.rooms
$setOnInsert:
id: presence.id
meeting: presence.meeting
,
upsert: true
presenceRemove: (presenceId) ->
checkId presenceId
Presence.remove id: presenceId
|
[
{
"context": " NEED_HEADROW: false\n PERSON_FULL_NAME: 'Chodorow, Stanley A. '\n FK_SPM_SPCL_MTG_CD: ' '\n ",
"end": 678,
"score": 0.9997825622558594,
"start": 659,
"tag": "NAME",
"value": "Chodorow, Stanley A"
},
{
"context": " NEED_HEADROW: false\n PERSON_FULL_NAME: 'Chodorow, Stanley A. '\n FK_SPM_SPCL_MTG_",
"end": 1545,
"score": 0.9835604429244995,
"start": 1537,
"tag": "NAME",
"value": "Chodorow"
},
{
"context": "_HEADROW: false\n PERSON_FULL_NAME: 'Chodorow, Stanley A. '\n FK_SPM_SPCL_MTG_CD: ' '\n ",
"end": 1556,
"score": 0.8761229515075684,
"start": 1547,
"tag": "NAME",
"value": "Stanley A"
},
{
"context": " NEED_HEADROW: false\n PERSON_FULL_NAME: 'Chodorow, Stanley A. '\n FK_SPM_SPCL_MTG_CD: ' '\n ",
"end": 2569,
"score": 0.9822962284088135,
"start": 2550,
"tag": "NAME",
"value": "Chodorow, Stanley A"
},
{
"context": " FK_SPM_SPCL_MTG_CD: ' '\n PERSON_ID: 'A16948219'\n BLDG_CODE: 'MANDE'\n SECT_CREDI",
"end": 2638,
"score": 0.6179056763648987,
"start": 2637,
"tag": "USERNAME",
"value": "1"
},
{
"context": "FK_SPM_SPCL_MTG_CD: ' '\n PERSON_ID: 'A16948219'\n BLDG_CODE: 'MANDE'\n SECT_CREDIT_HRS_P",
"end": 2645,
"score": 0.5529369115829468,
"start": 2643,
"tag": "USERNAME",
"value": "19"
},
{
"context": " NEED_HEADROW: false\n PERSON_FULL_NAME: 'Chodorow, Stanley A. '\n PB_FRIEND: true\n FK_SP",
"end": 3446,
"score": 0.9959011077880859,
"start": 3427,
"tag": "NAME",
"value": "Chodorow, Stanley A"
},
{
"context": " NEED_HEADROW: false\n PERSON_FULL_NAME: 'Miranda, Gregory Joseph '\n FK_SPM_SPCL_MTG_CD: ' '\n ",
"end": 4350,
"score": 0.95759516954422,
"start": 4327,
"tag": "NAME",
"value": "Miranda, Gregory Joseph"
},
{
"context": " NEED_HEADROW: false\n PERSON_FULL_NAME: 'Miranda, Gregory Joseph '\n FK_SPM_SPCL_MT",
"end": 5212,
"score": 0.9998000860214233,
"start": 5205,
"tag": "NAME",
"value": "Miranda"
},
{
"context": "D_HEADROW: false\n PERSON_FULL_NAME: 'Miranda, Gregory Joseph '\n FK_SPM_SPCL_MTG_CD: ' '\n ",
"end": 5228,
"score": 0.9911548495292664,
"start": 5214,
"tag": "NAME",
"value": "Gregory Joseph"
},
{
"context": " NEED_HEADROW: false\n PERSON_FULL_NAME: 'Miranda, Gregory Joseph '\n FK_SPM_SPCL_MTG_CD: ' '\n ",
"end": 6106,
"score": 0.9834927320480347,
"start": 6083,
"tag": "NAME",
"value": "Miranda, Gregory Joseph"
},
{
"context": " NEED_HEADROW: false\n PERSON_FULL_NAME: 'Miranda, Gregory Joseph '\n FK_SPM_SPCL_MT",
"end": 7101,
"score": 0.9997934103012085,
"start": 7094,
"tag": "NAME",
"value": "Miranda"
},
{
"context": "D_HEADROW: false\n PERSON_FULL_NAME: 'Miranda, Gregory Joseph '\n FK_SPM_SPCL_MTG_CD: ' '\n ",
"end": 7117,
"score": 0.9459205865859985,
"start": 7103,
"tag": "NAME",
"value": "Gregory Joseph"
},
{
"context": " NEED_HEADROW: false\n PERSON_FULL_NAME: 'Miranda, Gregory Joseph '\n PB_FRIEND: true",
"end": 7979,
"score": 0.9719293713569641,
"start": 7972,
"tag": "NAME",
"value": "Miranda"
},
{
"context": "D_HEADROW: false\n PERSON_FULL_NAME: 'Miranda, Gregory Joseph '\n PB_FRIEND: true\n FK_SPM_S",
"end": 7995,
"score": 0.9421898126602173,
"start": 7981,
"tag": "NAME",
"value": "Gregory Joseph"
},
{
"context": " NEED_HEADROW: false\n PERSON_FULL_NAME: 'Zelmanov, Efim I '\n FK_SPM_SPCL_MTG_CD: ' ",
"end": 8888,
"score": 0.9998642802238464,
"start": 8872,
"tag": "NAME",
"value": "Zelmanov, Efim I"
},
{
"context": "FK_SPM_SPCL_MTG_CD: ' '\n PERSON_ID: 'A16948219'\n BLDG_CODE: 'RCLAS'\n SECT_CREDIT_HRS_P",
"end": 8967,
"score": 0.6369014978408813,
"start": 8965,
"tag": "USERNAME",
"value": "19"
},
{
"context": " NEED_HEADROW: false\n PERSON_FULL_NAME: 'Zelmanov, Efim I '\n FK_SPM_SPCL_MTG_CD: ' ",
"end": 9766,
"score": 0.9998514652252197,
"start": 9750,
"tag": "NAME",
"value": "Zelmanov, Efim I"
},
{
"context": " NEED_HEADROW: false\n PERSON_FULL_NAME: 'Zelmanov, Efim I '\n FK_SPM_SPCL_MTG_CD: ' ",
"end": 10644,
"score": 0.9996111392974854,
"start": 10628,
"tag": "NAME",
"value": "Zelmanov, Efim I"
},
{
"context": " NEED_HEADROW: false\n PERSON_FULL_NAME: 'Zelmanov, Efim I '\n FK_SPM_SPCL_MTG_CD: ' ",
"end": 11654,
"score": 0.9998490810394287,
"start": 11638,
"tag": "NAME",
"value": "Zelmanov, Efim I"
},
{
"context": " NEED_HEADROW: false\n PERSON_FULL_NAME: 'Zelmanov, Efim I '\n PB_FRIEND: true\n F",
"end": 12522,
"score": 0.9997847080230713,
"start": 12506,
"tag": "NAME",
"value": "Zelmanov, Efim I"
},
{
"context": "ue\n FK_SPM_SPCL_MTG_CD: ''\n PERSON_ID: 'A16948219'\n BLDG_CODE: 'TBA'\n SECT_CREDIT_HRS_PL:",
"end": 12621,
"score": 0.9625036716461182,
"start": 12612,
"tag": "USERNAME",
"value": "A16948219"
},
{
"context": " NEED_HEADROW: false\n PERSON_FULL_NAME: 'Zelmanov, Efim I '\n PB_FRIEND: true\n F",
"end": 13418,
"score": 0.9998053312301636,
"start": 13402,
"tag": "NAME",
"value": "Zelmanov, Efim I"
},
{
"context": "\n FK_SPM_SPCL_MTG_CD: 'MI'\n PERSON_ID: 'A16948219'\n BLDG_CODE: 'RCLAS'\n SECT_CREDIT_HRS",
"end": 13517,
"score": 0.8261004686355591,
"start": 13510,
"tag": "USERNAME",
"value": "A169482"
},
{
"context": " NEED_HEADROW: false\n PERSON_FULL_NAME: 'Zelmanov, Efim I '\n PB_FRIEND: true\n F",
"end": 14318,
"score": 0.9995726346969604,
"start": 14302,
"tag": "NAME",
"value": "Zelmanov, Efim I"
},
{
"context": " NEED_HEADROW: false\n PERSON_FULL_NAME: 'Staff'\n FK_SPM_SPCL_MTG_CD: ' '\n PERSON_ID: ",
"end": 15209,
"score": 0.9978220462799072,
"start": 15204,
"tag": "NAME",
"value": "Staff"
},
{
"context": "\n FK_SPM_SPCL_MTG_CD: ' '\n PERSON_ID: 'A16948219'\n BLDG_CODE: 'CENTR'\n SECT_CREDIT_HRS_P",
"end": 15269,
"score": 0.9873300194740295,
"start": 15260,
"tag": "USERNAME",
"value": "A16948219"
},
{
"context": " NEED_HEADROW: false\n PERSON_FULL_NAME: 'Staff'\n FK_SPM_SPCL_MTG_CD: ' '\n PERSON_ID: ",
"end": 16059,
"score": 0.8590615391731262,
"start": 16054,
"tag": "USERNAME",
"value": "Staff"
},
{
"context": "\n FK_SPM_SPCL_MTG_CD: ' '\n PERSON_ID: 'A16948219'\n BLDG_CODE: 'CENTR'\n SECT_CREDIT_HRS_P",
"end": 16119,
"score": 0.9769231081008911,
"start": 16110,
"tag": "USERNAME",
"value": "A16948219"
},
{
"context": " NEED_HEADROW: false\n PERSON_FULL_NAME: 'Staff'\n FK_SPM_SPCL_MTG_CD: ' '\n PERSON_ID: ",
"end": 16909,
"score": 0.8691021800041199,
"start": 16904,
"tag": "USERNAME",
"value": "Staff"
},
{
"context": "\n FK_SPM_SPCL_MTG_CD: ' '\n PERSON_ID: 'A16948219'\n BLDG_CODE: 'CENTR'\n SECT_CREDIT_HRS_P",
"end": 16969,
"score": 0.9789689183235168,
"start": 16960,
"tag": "USERNAME",
"value": "A16948219"
},
{
"context": " NEED_HEADROW: false\n PERSON_FULL_NAME: 'Staff'\n FK_SPM_SPCL_MTG_CD: ' '\n PERSON_ID: ",
"end": 17894,
"score": 0.9963168501853943,
"start": 17889,
"tag": "NAME",
"value": "Staff"
},
{
"context": " NEED_HEADROW: false\n PERSON_FULL_NAME: 'Staff'\n PB_FRIEND: true\n FK_SPM_SPCL_MTG_CD: ",
"end": 18744,
"score": 0.9993723034858704,
"start": 18739,
"tag": "NAME",
"value": "Staff"
},
{
"context": "\n FK_SPM_SPCL_MTG_CD: 'MI'\n PERSON_ID: 'A16948219'\n BLDG_CODE: 'MOS '\n SECT_CREDIT_HRS_P",
"end": 18826,
"score": 0.8393670320510864,
"start": 18817,
"tag": "USERNAME",
"value": "A16948219"
},
{
"context": " NEED_HEADROW: false\n PERSON_FULL_NAME: 'Staff'\n PB_FRIEND: true\n FK_SPM_SPCL_MTG_CD: ",
"end": 19615,
"score": 0.9988808035850525,
"start": 19610,
"tag": "NAME",
"value": "Staff"
},
{
"context": "\n FK_SPM_SPCL_MTG_CD: 'FI'\n PERSON_ID: 'A16948219'\n BLDG_CODE: 'MOS '\n SECT_CREDIT_HRS_P",
"end": 19697,
"score": 0.9230296611785889,
"start": 19688,
"tag": "USERNAME",
"value": "A16948219"
}
] | src/schedule.coffee | SheepTester/uxdy | 1 | # This is my schedule! I'm hard-coding it for now
window.schedule =
[
{
END_MM_TIME: 50
LONG_DESC: ' '
TERM_CODE: 'FA21'
SECT_CREDIT_HRS: 4
BEGIN_HH_TIME: 9
SECTION_NUMBER: 50710
SUBJ_CODE: 'CAT '
GRADE_OPTN_CD_PLUS: ' '
WT_POS: ''
PRIMARY_INSTR_FLAG: 'Y'
ROOM_CODE: '0114 '
FK_PCH_INTRL_REFID: 2122934
CRSE_TITLE: 'Culture, Art & Technology 1 '
END_HH_TIME: 10
GRADE_OPTION: 'L'
START_DATE: '2021-09-23'
CRSE_CODE: ' 1 '
DAY_CODE: '2'
BEGIN_MM_TIME: 30
NEED_HEADROW: false
PERSON_FULL_NAME: 'Chodorow, Stanley A. '
FK_SPM_SPCL_MTG_CD: ' '
PERSON_ID: 'A16948219'
BLDG_CODE: 'MOS '
SECT_CREDIT_HRS_PL: ' '
SECTION_HEAD: 50717
ENROLL_STATUS: 'EN'
FK_CDI_INSTR_TYPE: 'LE'
SECT_CODE: 'D00'
FK_SEC_SCTN_NUM: 50717
}
{
END_MM_TIME: 50
LONG_DESC: ' '
TERM_CODE: 'FA21'
SECT_CREDIT_HRS: 4
BEGIN_HH_TIME: 9
SECTION_NUMBER: 50710
SUBJ_CODE: 'CAT '
GRADE_OPTN_CD_PLUS: ' '
WT_POS: ''
PRIMARY_INSTR_FLAG: 'Y'
ROOM_CODE: '0114 '
FK_PCH_INTRL_REFID: 2122934
CRSE_TITLE: 'Culture, Art & Technology 1 '
END_HH_TIME: 10
GRADE_OPTION: 'L'
START_DATE: '2021-09-23'
CRSE_CODE: ' 1 '
DAY_CODE: '4'
BEGIN_MM_TIME: 30
NEED_HEADROW: false
PERSON_FULL_NAME: 'Chodorow, Stanley A. '
FK_SPM_SPCL_MTG_CD: ' '
PERSON_ID: 'A16948219'
BLDG_CODE: 'MOS '
SECT_CREDIT_HRS_PL: ' '
SECTION_HEAD: 50717
ENROLL_STATUS: 'EN'
FK_CDI_INSTR_TYPE: 'LE'
SECT_CODE: 'D00'
FK_SEC_SCTN_NUM: 50717
}
{
END_MM_TIME: 50
LONG_DESC: ' '
SCTN_CPCTY_QTY: 17
TERM_CODE: 'FA21'
SCTN_ENRLT_QTY: 17
SECT_CREDIT_HRS: 4
BEGIN_HH_TIME: 12
END_DATE: '2021-12-03'
SECTION_NUMBER: 50717
STP_ENRLT_FLAG: 'N'
SUBJ_CODE: 'CAT '
GRADE_OPTN_CD_PLUS: ' '
WT_POS: ''
COUNT_ON_WAITLIST: null
PRIMARY_INSTR_FLAG: 'Y'
ROOM_CODE: 'B-146'
FK_PCH_INTRL_REFID: 2122934
CRSE_TITLE: 'Culture, Art & Technology 1 '
END_HH_TIME: 12
GRADE_OPTION: 'L'
START_DATE: '2021-09-23'
CRSE_CODE: ' 1 '
DAY_CODE: '4'
BEGIN_MM_TIME: 0
NEED_HEADROW: false
PERSON_FULL_NAME: 'Chodorow, Stanley A. '
FK_SPM_SPCL_MTG_CD: ' '
PERSON_ID: 'A16948219'
BLDG_CODE: 'MANDE'
SECT_CREDIT_HRS_PL: ' '
SECTION_HEAD: 50717
ENROLL_STATUS: 'EN'
FK_CDI_INSTR_TYPE: 'DI'
SECT_CODE: 'D07'
FK_SEC_SCTN_NUM: 50717
}
{
END_MM_TIME: 59
LONG_DESC: ' '
TERM_CODE: 'FA21'
SECT_CREDIT_HRS: 4
BEGIN_HH_TIME: 8
SECTION_NUMBER: 50710
SUBJ_CODE: 'CAT '
GRADE_OPTN_CD_PLUS: ' '
WT_POS: ''
PRIMARY_INSTR_FLAG: 'Y'
ROOM_CODE: '0114 '
FK_PCH_INTRL_REFID: 2122934
CRSE_TITLE: 'Culture, Art & Technology 1 '
END_HH_TIME: 10
GRADE_OPTION: 'L'
START_DATE: '2021-12-09'
CRSE_CODE: ' 1 '
DAY_CODE: '4'
BEGIN_MM_TIME: 0
NEED_HEADROW: false
PERSON_FULL_NAME: 'Chodorow, Stanley A. '
PB_FRIEND: true
FK_SPM_SPCL_MTG_CD: 'FI'
PERSON_ID: 'A16948219'
BLDG_CODE: 'MOS '
SECT_CREDIT_HRS_PL: ' '
SECTION_HEAD: 50717
ENROLL_STATUS: 'EN'
FK_CDI_INSTR_TYPE: 'FI'
SECT_CODE: 'D00'
FK_SEC_SCTN_NUM: 50717
}
{
END_MM_TIME: 50
LONG_DESC: ' '
TERM_CODE: 'FA21'
SECT_CREDIT_HRS: 4
BEGIN_HH_TIME: 16
SECTION_NUMBER: 53085
SUBJ_CODE: 'CSE '
GRADE_OPTN_CD_PLUS: '+'
WT_POS: ''
PRIMARY_INSTR_FLAG: 'Y'
ROOM_CODE: '119 '
FK_PCH_INTRL_REFID: 2122934
CRSE_TITLE: 'Accel. Intro to Programming '
END_HH_TIME: 16
GRADE_OPTION: 'L'
START_DATE: '2021-09-23'
CRSE_CODE: ' 11 '
DAY_CODE: '1'
BEGIN_MM_TIME: 0
NEED_HEADROW: false
PERSON_FULL_NAME: 'Miranda, Gregory Joseph '
FK_SPM_SPCL_MTG_CD: ' '
PERSON_ID: 'A16948219'
BLDG_CODE: 'CENTR'
SECT_CREDIT_HRS_PL: ' '
SECTION_HEAD: 53086
ENROLL_STATUS: 'EN'
FK_CDI_INSTR_TYPE: 'LE'
SECT_CODE: 'C00'
FK_SEC_SCTN_NUM: 53086
}
{
END_MM_TIME: 50
LONG_DESC: ' '
TERM_CODE: 'FA21'
SECT_CREDIT_HRS: 4
BEGIN_HH_TIME: 16
SECTION_NUMBER: 53085
SUBJ_CODE: 'CSE '
GRADE_OPTN_CD_PLUS: '+'
WT_POS: ''
PRIMARY_INSTR_FLAG: 'Y'
ROOM_CODE: '119 '
FK_PCH_INTRL_REFID: 2122934
CRSE_TITLE: 'Accel. Intro to Programming '
END_HH_TIME: 16
GRADE_OPTION: 'L'
START_DATE: '2021-09-23'
CRSE_CODE: ' 11 '
DAY_CODE: '3'
BEGIN_MM_TIME: 0
NEED_HEADROW: false
PERSON_FULL_NAME: 'Miranda, Gregory Joseph '
FK_SPM_SPCL_MTG_CD: ' '
PERSON_ID: 'A16948219'
BLDG_CODE: 'CENTR'
SECT_CREDIT_HRS_PL: ' '
SECTION_HEAD: 53086
ENROLL_STATUS: 'EN'
FK_CDI_INSTR_TYPE: 'LE'
SECT_CODE: 'C00'
FK_SEC_SCTN_NUM: 53086
}
{
END_MM_TIME: 50
LONG_DESC: ' '
TERM_CODE: 'FA21'
SECT_CREDIT_HRS: 4
BEGIN_HH_TIME: 16
SECTION_NUMBER: 53085
SUBJ_CODE: 'CSE '
GRADE_OPTN_CD_PLUS: '+'
WT_POS: ''
PRIMARY_INSTR_FLAG: 'Y'
ROOM_CODE: '119 '
FK_PCH_INTRL_REFID: 2122934
CRSE_TITLE: 'Accel. Intro to Programming '
END_HH_TIME: 16
GRADE_OPTION: 'L'
START_DATE: '2021-09-23'
CRSE_CODE: ' 11 '
DAY_CODE: '5'
BEGIN_MM_TIME: 0
NEED_HEADROW: false
PERSON_FULL_NAME: 'Miranda, Gregory Joseph '
FK_SPM_SPCL_MTG_CD: ' '
PERSON_ID: 'A16948219'
BLDG_CODE: 'CENTR'
SECT_CREDIT_HRS_PL: ' '
SECTION_HEAD: 53086
ENROLL_STATUS: 'EN'
FK_CDI_INSTR_TYPE: 'LE'
SECT_CODE: 'C00'
FK_SEC_SCTN_NUM: 53086
}
{
END_MM_TIME: 50
LONG_DESC: ' '
SCTN_CPCTY_QTY: 49
TERM_CODE: 'FA21'
SCTN_ENRLT_QTY: 49
SECT_CREDIT_HRS: 4
BEGIN_HH_TIME: 15
END_DATE: '2021-12-03'
SECTION_NUMBER: 53086
STP_ENRLT_FLAG: 'Y'
SUBJ_CODE: 'CSE '
GRADE_OPTN_CD_PLUS: '+'
WT_POS: ''
COUNT_ON_WAITLIST: 10
PRIMARY_INSTR_FLAG: 'Y'
ROOM_CODE: '120 '
FK_PCH_INTRL_REFID: 2122934
CRSE_TITLE: 'Accel. Intro to Programming '
END_HH_TIME: 15
GRADE_OPTION: 'L'
START_DATE: '2021-09-23'
CRSE_CODE: ' 11 '
DAY_CODE: '1'
BEGIN_MM_TIME: 0
NEED_HEADROW: false
PERSON_FULL_NAME: 'Miranda, Gregory Joseph '
FK_SPM_SPCL_MTG_CD: ' '
PERSON_ID: 'A16948219'
BLDG_CODE: 'PCYNH'
SECT_CREDIT_HRS_PL: ' '
SECTION_HEAD: 53086
ENROLL_STATUS: 'EN'
FK_CDI_INSTR_TYPE: 'DI'
SECT_CODE: 'C01'
FK_SEC_SCTN_NUM: 53086
}
{
END_MM_TIME: 59
LONG_DESC: ' '
TERM_CODE: 'FA21'
SECT_CREDIT_HRS: 4
BEGIN_HH_TIME: 15
SECTION_NUMBER: 53085
SUBJ_CODE: 'CSE '
GRADE_OPTN_CD_PLUS: '+'
WT_POS: ''
PRIMARY_INSTR_FLAG: 'Y'
ROOM_CODE: '115 '
FK_PCH_INTRL_REFID: 2122934
CRSE_TITLE: 'Accel. Intro to Programming '
END_HH_TIME: 17
GRADE_OPTION: 'L'
START_DATE: '2021-12-04'
CRSE_CODE: ' 11 '
DAY_CODE: '6'
BEGIN_MM_TIME: 0
NEED_HEADROW: false
PERSON_FULL_NAME: 'Miranda, Gregory Joseph '
PB_FRIEND: true
FK_SPM_SPCL_MTG_CD: 'FI'
PERSON_ID: 'A16948219'
BLDG_CODE: 'CENTR'
SECT_CREDIT_HRS_PL: ' '
SECTION_HEAD: 53086
ENROLL_STATUS: 'EN'
FK_CDI_INSTR_TYPE: 'FI'
SECT_CODE: 'C00'
FK_SEC_SCTN_NUM: 53086
}
{
END_MM_TIME: 50
LONG_DESC: ' '
TERM_CODE: 'FA21'
SECT_CREDIT_HRS: 4
BEGIN_HH_TIME: 13
SECTION_NUMBER: 51423
SUBJ_CODE: 'MATH'
GRADE_OPTN_CD_PLUS: '+'
WT_POS: ''
PRIMARY_INSTR_FLAG: 'Y'
ROOM_CODE: 'R107 '
FK_PCH_INTRL_REFID: 2122934
CRSE_TITLE: 'Linear Algebra '
END_HH_TIME: 13
GRADE_OPTION: 'L'
START_DATE: '2021-09-23'
CRSE_CODE: ' 18 '
DAY_CODE: '1'
BEGIN_MM_TIME: 0
NEED_HEADROW: false
PERSON_FULL_NAME: 'Zelmanov, Efim I '
FK_SPM_SPCL_MTG_CD: ' '
PERSON_ID: 'A16948219'
BLDG_CODE: 'RCLAS'
SECT_CREDIT_HRS_PL: ' '
SECTION_HEAD: 59172
ENROLL_STATUS: 'EN'
FK_CDI_INSTR_TYPE: 'LE'
SECT_CODE: 'B00'
FK_SEC_SCTN_NUM: 59172
}
{
END_MM_TIME: 50
LONG_DESC: ' '
TERM_CODE: 'FA21'
SECT_CREDIT_HRS: 4
BEGIN_HH_TIME: 13
SECTION_NUMBER: 51423
SUBJ_CODE: 'MATH'
GRADE_OPTN_CD_PLUS: '+'
WT_POS: ''
PRIMARY_INSTR_FLAG: 'Y'
ROOM_CODE: 'R107 '
FK_PCH_INTRL_REFID: 2122934
CRSE_TITLE: 'Linear Algebra '
END_HH_TIME: 13
GRADE_OPTION: 'L'
START_DATE: '2021-09-23'
CRSE_CODE: ' 18 '
DAY_CODE: '3'
BEGIN_MM_TIME: 0
NEED_HEADROW: false
PERSON_FULL_NAME: 'Zelmanov, Efim I '
FK_SPM_SPCL_MTG_CD: ' '
PERSON_ID: 'A16948219'
BLDG_CODE: 'RCLAS'
SECT_CREDIT_HRS_PL: ' '
SECTION_HEAD: 59172
ENROLL_STATUS: 'EN'
FK_CDI_INSTR_TYPE: 'LE'
SECT_CODE: 'B00'
FK_SEC_SCTN_NUM: 59172
}
{
END_MM_TIME: 50
LONG_DESC: ' '
TERM_CODE: 'FA21'
SECT_CREDIT_HRS: 4
BEGIN_HH_TIME: 13
SECTION_NUMBER: 51423
SUBJ_CODE: 'MATH'
GRADE_OPTN_CD_PLUS: '+'
WT_POS: ''
PRIMARY_INSTR_FLAG: 'Y'
ROOM_CODE: 'R107 '
FK_PCH_INTRL_REFID: 2122934
CRSE_TITLE: 'Linear Algebra '
END_HH_TIME: 13
GRADE_OPTION: 'L'
START_DATE: '2021-09-23'
CRSE_CODE: ' 18 '
DAY_CODE: '5'
BEGIN_MM_TIME: 0
NEED_HEADROW: false
PERSON_FULL_NAME: 'Zelmanov, Efim I '
FK_SPM_SPCL_MTG_CD: ' '
PERSON_ID: 'A16948219'
BLDG_CODE: 'RCLAS'
SECT_CREDIT_HRS_PL: ' '
SECTION_HEAD: 59172
ENROLL_STATUS: 'EN'
FK_CDI_INSTR_TYPE: 'LE'
SECT_CODE: 'B00'
FK_SEC_SCTN_NUM: 59172
}
{
END_MM_TIME: 50
LONG_DESC: ' '
SCTN_CPCTY_QTY: 26
TERM_CODE: 'FA21'
SCTN_ENRLT_QTY: 26
SECT_CREDIT_HRS: 4
BEGIN_HH_TIME: 12
END_DATE: '2021-12-03'
SECTION_NUMBER: 59172
STP_ENRLT_FLAG: 'Y'
SUBJ_CODE: 'MATH'
GRADE_OPTN_CD_PLUS: '+'
WT_POS: ''
COUNT_ON_WAITLIST: 1
PRIMARY_INSTR_FLAG: 'Y'
ROOM_CODE: '3000A'
FK_PCH_INTRL_REFID: 2122934
CRSE_TITLE: 'Linear Algebra '
END_HH_TIME: 12
GRADE_OPTION: 'L'
START_DATE: '2021-09-23'
CRSE_CODE: ' 18 '
DAY_CODE: '2'
BEGIN_MM_TIME: 0
NEED_HEADROW: false
PERSON_FULL_NAME: 'Zelmanov, Efim I '
FK_SPM_SPCL_MTG_CD: ' '
PERSON_ID: 'A16948219'
BLDG_CODE: 'YORK '
SECT_CREDIT_HRS_PL: ' '
SECTION_HEAD: 59172
ENROLL_STATUS: 'EN'
FK_CDI_INSTR_TYPE: 'DI'
SECT_CODE: 'B21'
FK_SEC_SCTN_NUM: 59172
}
{
END_MM_TIME: 0
LONG_DESC: ' '
TERM_CODE: 'FA21'
SECT_CREDIT_HRS: 4
BEGIN_HH_TIME: 0
SECTION_NUMBER: 51442
SUBJ_CODE: 'MATH'
GRADE_OPTN_CD_PLUS: '+'
WT_POS: ''
PRIMARY_INSTR_FLAG: 'Y'
ROOM_CODE: 'TBA'
FK_PCH_INTRL_REFID: 2122934
CRSE_TITLE: 'Linear Algebra '
END_HH_TIME: 0
GRADE_OPTION: 'L'
START_DATE: 'TBA'
CRSE_CODE: ' 18 '
DAY_CODE: 'TBA'
BEGIN_MM_TIME: 0
NEED_HEADROW: false
PERSON_FULL_NAME: 'Zelmanov, Efim I '
PB_FRIEND: true
FK_SPM_SPCL_MTG_CD: ''
PERSON_ID: 'A16948219'
BLDG_CODE: 'TBA'
SECT_CREDIT_HRS_PL: ' '
SECTION_HEAD: 59172
ENROLL_STATUS: 'EN'
FK_CDI_INSTR_TYPE: 'LA'
SECT_CODE: 'B50'
FK_SEC_SCTN_NUM: 59172
}
{
END_MM_TIME: 50
LONG_DESC: ' '
TERM_CODE: 'FA21'
SECT_CREDIT_HRS: 4
BEGIN_HH_TIME: 20
SECTION_NUMBER: 51423
SUBJ_CODE: 'MATH'
GRADE_OPTN_CD_PLUS: '+'
WT_POS: ''
PRIMARY_INSTR_FLAG: 'Y'
ROOM_CODE: 'R07 '
FK_PCH_INTRL_REFID: 2122934
CRSE_TITLE: 'Linear Algebra '
END_HH_TIME: 21
GRADE_OPTION: 'L'
START_DATE: '2021-11-01'
CRSE_CODE: ' 18 '
DAY_CODE: '1'
BEGIN_MM_TIME: 0
NEED_HEADROW: false
PERSON_FULL_NAME: 'Zelmanov, Efim I '
PB_FRIEND: true
FK_SPM_SPCL_MTG_CD: 'MI'
PERSON_ID: 'A16948219'
BLDG_CODE: 'RCLAS'
SECT_CREDIT_HRS_PL: ' '
SECTION_HEAD: 59172
ENROLL_STATUS: 'EN'
FK_CDI_INSTR_TYPE: 'MI'
SECT_CODE: 'B00'
FK_SEC_SCTN_NUM: 59172
}
{
END_MM_TIME: 59
LONG_DESC: ' '
TERM_CODE: 'FA21'
SECT_CREDIT_HRS: 4
BEGIN_HH_TIME: 19
SECTION_NUMBER: 51423
SUBJ_CODE: 'MATH'
GRADE_OPTN_CD_PLUS: '+'
WT_POS: ''
PRIMARY_INSTR_FLAG: 'Y'
ROOM_CODE: 'R01 '
FK_PCH_INTRL_REFID: 2122934
CRSE_TITLE: 'Linear Algebra '
END_HH_TIME: 21
GRADE_OPTION: 'L'
START_DATE: '2021-12-04'
CRSE_CODE: ' 18 '
DAY_CODE: '6'
BEGIN_MM_TIME: 0
NEED_HEADROW: false
PERSON_FULL_NAME: 'Zelmanov, Efim I '
PB_FRIEND: true
FK_SPM_SPCL_MTG_CD: 'FI'
PERSON_ID: 'A16948219'
BLDG_CODE: 'RCLAS'
SECT_CREDIT_HRS_PL: ' '
SECTION_HEAD: 59172
ENROLL_STATUS: 'EN'
FK_CDI_INSTR_TYPE: 'FI'
SECT_CODE: 'B00'
FK_SEC_SCTN_NUM: 59172
}
{
END_MM_TIME: 50
LONG_DESC: ' '
TERM_CODE: 'FA21'
SECT_CREDIT_HRS: 4
BEGIN_HH_TIME: 17
SECTION_NUMBER: 51573
SUBJ_CODE: 'MATH'
GRADE_OPTN_CD_PLUS: '+'
WT_POS: ''
PRIMARY_INSTR_FLAG: 'TBA'
ROOM_CODE: '115 '
FK_PCH_INTRL_REFID: 2122934
CRSE_TITLE: 'Calculus&Analyt Geom/Sci&Engnr'
END_HH_TIME: 17
GRADE_OPTION: 'L'
START_DATE: '2021-09-23'
CRSE_CODE: ' 20C '
DAY_CODE: '1'
BEGIN_MM_TIME: 0
NEED_HEADROW: false
PERSON_FULL_NAME: 'Staff'
FK_SPM_SPCL_MTG_CD: ' '
PERSON_ID: 'A16948219'
BLDG_CODE: 'CENTR'
SECT_CREDIT_HRS_PL: ' '
SECTION_HEAD: 51579
ENROLL_STATUS: 'EN'
FK_CDI_INSTR_TYPE: 'LE'
SECT_CODE: 'E00'
FK_SEC_SCTN_NUM: 51579
}
{
END_MM_TIME: 50
LONG_DESC: ' '
TERM_CODE: 'FA21'
SECT_CREDIT_HRS: 4
BEGIN_HH_TIME: 17
SECTION_NUMBER: 51573
SUBJ_CODE: 'MATH'
GRADE_OPTN_CD_PLUS: '+'
WT_POS: ''
PRIMARY_INSTR_FLAG: 'TBA'
ROOM_CODE: '115 '
FK_PCH_INTRL_REFID: 2122934
CRSE_TITLE: 'Calculus&Analyt Geom/Sci&Engnr'
END_HH_TIME: 17
GRADE_OPTION: 'L'
START_DATE: '2021-09-23'
CRSE_CODE: ' 20C '
DAY_CODE: '3'
BEGIN_MM_TIME: 0
NEED_HEADROW: false
PERSON_FULL_NAME: 'Staff'
FK_SPM_SPCL_MTG_CD: ' '
PERSON_ID: 'A16948219'
BLDG_CODE: 'CENTR'
SECT_CREDIT_HRS_PL: ' '
SECTION_HEAD: 51579
ENROLL_STATUS: 'EN'
FK_CDI_INSTR_TYPE: 'LE'
SECT_CODE: 'E00'
FK_SEC_SCTN_NUM: 51579
}
{
END_MM_TIME: 50
LONG_DESC: ' '
TERM_CODE: 'FA21'
SECT_CREDIT_HRS: 4
BEGIN_HH_TIME: 17
SECTION_NUMBER: 51573
SUBJ_CODE: 'MATH'
GRADE_OPTN_CD_PLUS: '+'
WT_POS: ''
PRIMARY_INSTR_FLAG: 'TBA'
ROOM_CODE: '115 '
FK_PCH_INTRL_REFID: 2122934
CRSE_TITLE: 'Calculus&Analyt Geom/Sci&Engnr'
END_HH_TIME: 17
GRADE_OPTION: 'L'
START_DATE: '2021-09-23'
CRSE_CODE: ' 20C '
DAY_CODE: '5'
BEGIN_MM_TIME: 0
NEED_HEADROW: false
PERSON_FULL_NAME: 'Staff'
FK_SPM_SPCL_MTG_CD: ' '
PERSON_ID: 'A16948219'
BLDG_CODE: 'CENTR'
SECT_CREDIT_HRS_PL: ' '
SECTION_HEAD: 51579
ENROLL_STATUS: 'EN'
FK_CDI_INSTR_TYPE: 'LE'
SECT_CODE: 'E00'
FK_SEC_SCTN_NUM: 51579
}
{
END_MM_TIME: 50
LONG_DESC: ' '
SCTN_CPCTY_QTY: 33
TERM_CODE: 'FA21'
SCTN_ENRLT_QTY: 12
SECT_CREDIT_HRS: 4
BEGIN_HH_TIME: 11
END_DATE: '2021-12-03'
SECTION_NUMBER: 51579
STP_ENRLT_FLAG: 'N'
SUBJ_CODE: 'MATH'
GRADE_OPTN_CD_PLUS: '+'
WT_POS: ''
COUNT_ON_WAITLIST: null
PRIMARY_INSTR_FLAG: 'TBA'
ROOM_CODE: '3000A'
FK_PCH_INTRL_REFID: 2122934
CRSE_TITLE: 'Calculus&Analyt Geom/Sci&Engnr'
END_HH_TIME: 11
GRADE_OPTION: 'L'
START_DATE: '2021-09-23'
CRSE_CODE: ' 20C '
DAY_CODE: '4'
BEGIN_MM_TIME: 0
NEED_HEADROW: false
PERSON_FULL_NAME: 'Staff'
FK_SPM_SPCL_MTG_CD: ' '
PERSON_ID: 'A16948219'
BLDG_CODE: 'YORK '
SECT_CREDIT_HRS_PL: ' '
SECTION_HEAD: 51579
ENROLL_STATUS: 'EN'
FK_CDI_INSTR_TYPE: 'DI'
SECT_CODE: 'E06'
FK_SEC_SCTN_NUM: 51579
}
{
END_MM_TIME: 50
LONG_DESC: ' '
TERM_CODE: 'FA21'
SECT_CREDIT_HRS: 4
BEGIN_HH_TIME: 20
SECTION_NUMBER: 51573
SUBJ_CODE: 'MATH'
GRADE_OPTN_CD_PLUS: '+'
WT_POS: ''
PRIMARY_INSTR_FLAG: 'TBA'
ROOM_CODE: '0113 '
FK_PCH_INTRL_REFID: 2122934
CRSE_TITLE: 'Calculus&Analyt Geom/Sci&Engnr'
END_HH_TIME: 21
GRADE_OPTION: 'L'
START_DATE: '2021-11-02'
CRSE_CODE: ' 20C '
DAY_CODE: '2'
BEGIN_MM_TIME: 0
NEED_HEADROW: false
PERSON_FULL_NAME: 'Staff'
PB_FRIEND: true
FK_SPM_SPCL_MTG_CD: 'MI'
PERSON_ID: 'A16948219'
BLDG_CODE: 'MOS '
SECT_CREDIT_HRS_PL: ' '
SECTION_HEAD: 51579
ENROLL_STATUS: 'EN'
FK_CDI_INSTR_TYPE: 'MI'
SECT_CODE: 'E00'
FK_SEC_SCTN_NUM: 51579
}
{
END_MM_TIME: 59
LONG_DESC: ' '
TERM_CODE: 'FA21'
SECT_CREDIT_HRS: 4
BEGIN_HH_TIME: 8
SECTION_NUMBER: 51573
SUBJ_CODE: 'MATH'
GRADE_OPTN_CD_PLUS: '+'
WT_POS: ''
PRIMARY_INSTR_FLAG: 'TBA'
ROOM_CODE: '0113 '
FK_PCH_INTRL_REFID: 2122934
CRSE_TITLE: 'Calculus&Analyt Geom/Sci&Engnr'
END_HH_TIME: 10
GRADE_OPTION: 'L'
START_DATE: '2021-12-04'
CRSE_CODE: ' 20C '
DAY_CODE: '6'
BEGIN_MM_TIME: 0
NEED_HEADROW: false
PERSON_FULL_NAME: 'Staff'
PB_FRIEND: true
FK_SPM_SPCL_MTG_CD: 'FI'
PERSON_ID: 'A16948219'
BLDG_CODE: 'MOS '
SECT_CREDIT_HRS_PL: ' '
SECTION_HEAD: 51579
ENROLL_STATUS: 'EN'
FK_CDI_INSTR_TYPE: 'FI'
SECT_CODE: 'E00'
FK_SEC_SCTN_NUM: 51579
}
]
| 121041 | # This is my schedule! I'm hard-coding it for now
window.schedule =
[
{
END_MM_TIME: 50
LONG_DESC: ' '
TERM_CODE: 'FA21'
SECT_CREDIT_HRS: 4
BEGIN_HH_TIME: 9
SECTION_NUMBER: 50710
SUBJ_CODE: 'CAT '
GRADE_OPTN_CD_PLUS: ' '
WT_POS: ''
PRIMARY_INSTR_FLAG: 'Y'
ROOM_CODE: '0114 '
FK_PCH_INTRL_REFID: 2122934
CRSE_TITLE: 'Culture, Art & Technology 1 '
END_HH_TIME: 10
GRADE_OPTION: 'L'
START_DATE: '2021-09-23'
CRSE_CODE: ' 1 '
DAY_CODE: '2'
BEGIN_MM_TIME: 30
NEED_HEADROW: false
PERSON_FULL_NAME: '<NAME>. '
FK_SPM_SPCL_MTG_CD: ' '
PERSON_ID: 'A16948219'
BLDG_CODE: 'MOS '
SECT_CREDIT_HRS_PL: ' '
SECTION_HEAD: 50717
ENROLL_STATUS: 'EN'
FK_CDI_INSTR_TYPE: 'LE'
SECT_CODE: 'D00'
FK_SEC_SCTN_NUM: 50717
}
{
END_MM_TIME: 50
LONG_DESC: ' '
TERM_CODE: 'FA21'
SECT_CREDIT_HRS: 4
BEGIN_HH_TIME: 9
SECTION_NUMBER: 50710
SUBJ_CODE: 'CAT '
GRADE_OPTN_CD_PLUS: ' '
WT_POS: ''
PRIMARY_INSTR_FLAG: 'Y'
ROOM_CODE: '0114 '
FK_PCH_INTRL_REFID: 2122934
CRSE_TITLE: 'Culture, Art & Technology 1 '
END_HH_TIME: 10
GRADE_OPTION: 'L'
START_DATE: '2021-09-23'
CRSE_CODE: ' 1 '
DAY_CODE: '4'
BEGIN_MM_TIME: 30
NEED_HEADROW: false
PERSON_FULL_NAME: '<NAME>, <NAME>. '
FK_SPM_SPCL_MTG_CD: ' '
PERSON_ID: 'A16948219'
BLDG_CODE: 'MOS '
SECT_CREDIT_HRS_PL: ' '
SECTION_HEAD: 50717
ENROLL_STATUS: 'EN'
FK_CDI_INSTR_TYPE: 'LE'
SECT_CODE: 'D00'
FK_SEC_SCTN_NUM: 50717
}
{
END_MM_TIME: 50
LONG_DESC: ' '
SCTN_CPCTY_QTY: 17
TERM_CODE: 'FA21'
SCTN_ENRLT_QTY: 17
SECT_CREDIT_HRS: 4
BEGIN_HH_TIME: 12
END_DATE: '2021-12-03'
SECTION_NUMBER: 50717
STP_ENRLT_FLAG: 'N'
SUBJ_CODE: 'CAT '
GRADE_OPTN_CD_PLUS: ' '
WT_POS: ''
COUNT_ON_WAITLIST: null
PRIMARY_INSTR_FLAG: 'Y'
ROOM_CODE: 'B-146'
FK_PCH_INTRL_REFID: 2122934
CRSE_TITLE: 'Culture, Art & Technology 1 '
END_HH_TIME: 12
GRADE_OPTION: 'L'
START_DATE: '2021-09-23'
CRSE_CODE: ' 1 '
DAY_CODE: '4'
BEGIN_MM_TIME: 0
NEED_HEADROW: false
PERSON_FULL_NAME: '<NAME>. '
FK_SPM_SPCL_MTG_CD: ' '
PERSON_ID: 'A16948219'
BLDG_CODE: 'MANDE'
SECT_CREDIT_HRS_PL: ' '
SECTION_HEAD: 50717
ENROLL_STATUS: 'EN'
FK_CDI_INSTR_TYPE: 'DI'
SECT_CODE: 'D07'
FK_SEC_SCTN_NUM: 50717
}
{
END_MM_TIME: 59
LONG_DESC: ' '
TERM_CODE: 'FA21'
SECT_CREDIT_HRS: 4
BEGIN_HH_TIME: 8
SECTION_NUMBER: 50710
SUBJ_CODE: 'CAT '
GRADE_OPTN_CD_PLUS: ' '
WT_POS: ''
PRIMARY_INSTR_FLAG: 'Y'
ROOM_CODE: '0114 '
FK_PCH_INTRL_REFID: 2122934
CRSE_TITLE: 'Culture, Art & Technology 1 '
END_HH_TIME: 10
GRADE_OPTION: 'L'
START_DATE: '2021-12-09'
CRSE_CODE: ' 1 '
DAY_CODE: '4'
BEGIN_MM_TIME: 0
NEED_HEADROW: false
PERSON_FULL_NAME: '<NAME>. '
PB_FRIEND: true
FK_SPM_SPCL_MTG_CD: 'FI'
PERSON_ID: 'A16948219'
BLDG_CODE: 'MOS '
SECT_CREDIT_HRS_PL: ' '
SECTION_HEAD: 50717
ENROLL_STATUS: 'EN'
FK_CDI_INSTR_TYPE: 'FI'
SECT_CODE: 'D00'
FK_SEC_SCTN_NUM: 50717
}
{
END_MM_TIME: 50
LONG_DESC: ' '
TERM_CODE: 'FA21'
SECT_CREDIT_HRS: 4
BEGIN_HH_TIME: 16
SECTION_NUMBER: 53085
SUBJ_CODE: 'CSE '
GRADE_OPTN_CD_PLUS: '+'
WT_POS: ''
PRIMARY_INSTR_FLAG: 'Y'
ROOM_CODE: '119 '
FK_PCH_INTRL_REFID: 2122934
CRSE_TITLE: 'Accel. Intro to Programming '
END_HH_TIME: 16
GRADE_OPTION: 'L'
START_DATE: '2021-09-23'
CRSE_CODE: ' 11 '
DAY_CODE: '1'
BEGIN_MM_TIME: 0
NEED_HEADROW: false
PERSON_FULL_NAME: '<NAME> '
FK_SPM_SPCL_MTG_CD: ' '
PERSON_ID: 'A16948219'
BLDG_CODE: 'CENTR'
SECT_CREDIT_HRS_PL: ' '
SECTION_HEAD: 53086
ENROLL_STATUS: 'EN'
FK_CDI_INSTR_TYPE: 'LE'
SECT_CODE: 'C00'
FK_SEC_SCTN_NUM: 53086
}
{
END_MM_TIME: 50
LONG_DESC: ' '
TERM_CODE: 'FA21'
SECT_CREDIT_HRS: 4
BEGIN_HH_TIME: 16
SECTION_NUMBER: 53085
SUBJ_CODE: 'CSE '
GRADE_OPTN_CD_PLUS: '+'
WT_POS: ''
PRIMARY_INSTR_FLAG: 'Y'
ROOM_CODE: '119 '
FK_PCH_INTRL_REFID: 2122934
CRSE_TITLE: 'Accel. Intro to Programming '
END_HH_TIME: 16
GRADE_OPTION: 'L'
START_DATE: '2021-09-23'
CRSE_CODE: ' 11 '
DAY_CODE: '3'
BEGIN_MM_TIME: 0
NEED_HEADROW: false
PERSON_FULL_NAME: '<NAME>, <NAME> '
FK_SPM_SPCL_MTG_CD: ' '
PERSON_ID: 'A16948219'
BLDG_CODE: 'CENTR'
SECT_CREDIT_HRS_PL: ' '
SECTION_HEAD: 53086
ENROLL_STATUS: 'EN'
FK_CDI_INSTR_TYPE: 'LE'
SECT_CODE: 'C00'
FK_SEC_SCTN_NUM: 53086
}
{
END_MM_TIME: 50
LONG_DESC: ' '
TERM_CODE: 'FA21'
SECT_CREDIT_HRS: 4
BEGIN_HH_TIME: 16
SECTION_NUMBER: 53085
SUBJ_CODE: 'CSE '
GRADE_OPTN_CD_PLUS: '+'
WT_POS: ''
PRIMARY_INSTR_FLAG: 'Y'
ROOM_CODE: '119 '
FK_PCH_INTRL_REFID: 2122934
CRSE_TITLE: 'Accel. Intro to Programming '
END_HH_TIME: 16
GRADE_OPTION: 'L'
START_DATE: '2021-09-23'
CRSE_CODE: ' 11 '
DAY_CODE: '5'
BEGIN_MM_TIME: 0
NEED_HEADROW: false
PERSON_FULL_NAME: '<NAME> '
FK_SPM_SPCL_MTG_CD: ' '
PERSON_ID: 'A16948219'
BLDG_CODE: 'CENTR'
SECT_CREDIT_HRS_PL: ' '
SECTION_HEAD: 53086
ENROLL_STATUS: 'EN'
FK_CDI_INSTR_TYPE: 'LE'
SECT_CODE: 'C00'
FK_SEC_SCTN_NUM: 53086
}
{
END_MM_TIME: 50
LONG_DESC: ' '
SCTN_CPCTY_QTY: 49
TERM_CODE: 'FA21'
SCTN_ENRLT_QTY: 49
SECT_CREDIT_HRS: 4
BEGIN_HH_TIME: 15
END_DATE: '2021-12-03'
SECTION_NUMBER: 53086
STP_ENRLT_FLAG: 'Y'
SUBJ_CODE: 'CSE '
GRADE_OPTN_CD_PLUS: '+'
WT_POS: ''
COUNT_ON_WAITLIST: 10
PRIMARY_INSTR_FLAG: 'Y'
ROOM_CODE: '120 '
FK_PCH_INTRL_REFID: 2122934
CRSE_TITLE: 'Accel. Intro to Programming '
END_HH_TIME: 15
GRADE_OPTION: 'L'
START_DATE: '2021-09-23'
CRSE_CODE: ' 11 '
DAY_CODE: '1'
BEGIN_MM_TIME: 0
NEED_HEADROW: false
PERSON_FULL_NAME: '<NAME>, <NAME> '
FK_SPM_SPCL_MTG_CD: ' '
PERSON_ID: 'A16948219'
BLDG_CODE: 'PCYNH'
SECT_CREDIT_HRS_PL: ' '
SECTION_HEAD: 53086
ENROLL_STATUS: 'EN'
FK_CDI_INSTR_TYPE: 'DI'
SECT_CODE: 'C01'
FK_SEC_SCTN_NUM: 53086
}
{
END_MM_TIME: 59
LONG_DESC: ' '
TERM_CODE: 'FA21'
SECT_CREDIT_HRS: 4
BEGIN_HH_TIME: 15
SECTION_NUMBER: 53085
SUBJ_CODE: 'CSE '
GRADE_OPTN_CD_PLUS: '+'
WT_POS: ''
PRIMARY_INSTR_FLAG: 'Y'
ROOM_CODE: '115 '
FK_PCH_INTRL_REFID: 2122934
CRSE_TITLE: 'Accel. Intro to Programming '
END_HH_TIME: 17
GRADE_OPTION: 'L'
START_DATE: '2021-12-04'
CRSE_CODE: ' 11 '
DAY_CODE: '6'
BEGIN_MM_TIME: 0
NEED_HEADROW: false
PERSON_FULL_NAME: '<NAME>, <NAME> '
PB_FRIEND: true
FK_SPM_SPCL_MTG_CD: 'FI'
PERSON_ID: 'A16948219'
BLDG_CODE: 'CENTR'
SECT_CREDIT_HRS_PL: ' '
SECTION_HEAD: 53086
ENROLL_STATUS: 'EN'
FK_CDI_INSTR_TYPE: 'FI'
SECT_CODE: 'C00'
FK_SEC_SCTN_NUM: 53086
}
{
END_MM_TIME: 50
LONG_DESC: ' '
TERM_CODE: 'FA21'
SECT_CREDIT_HRS: 4
BEGIN_HH_TIME: 13
SECTION_NUMBER: 51423
SUBJ_CODE: 'MATH'
GRADE_OPTN_CD_PLUS: '+'
WT_POS: ''
PRIMARY_INSTR_FLAG: 'Y'
ROOM_CODE: 'R107 '
FK_PCH_INTRL_REFID: 2122934
CRSE_TITLE: 'Linear Algebra '
END_HH_TIME: 13
GRADE_OPTION: 'L'
START_DATE: '2021-09-23'
CRSE_CODE: ' 18 '
DAY_CODE: '1'
BEGIN_MM_TIME: 0
NEED_HEADROW: false
PERSON_FULL_NAME: '<NAME> '
FK_SPM_SPCL_MTG_CD: ' '
PERSON_ID: 'A16948219'
BLDG_CODE: 'RCLAS'
SECT_CREDIT_HRS_PL: ' '
SECTION_HEAD: 59172
ENROLL_STATUS: 'EN'
FK_CDI_INSTR_TYPE: 'LE'
SECT_CODE: 'B00'
FK_SEC_SCTN_NUM: 59172
}
{
END_MM_TIME: 50
LONG_DESC: ' '
TERM_CODE: 'FA21'
SECT_CREDIT_HRS: 4
BEGIN_HH_TIME: 13
SECTION_NUMBER: 51423
SUBJ_CODE: 'MATH'
GRADE_OPTN_CD_PLUS: '+'
WT_POS: ''
PRIMARY_INSTR_FLAG: 'Y'
ROOM_CODE: 'R107 '
FK_PCH_INTRL_REFID: 2122934
CRSE_TITLE: 'Linear Algebra '
END_HH_TIME: 13
GRADE_OPTION: 'L'
START_DATE: '2021-09-23'
CRSE_CODE: ' 18 '
DAY_CODE: '3'
BEGIN_MM_TIME: 0
NEED_HEADROW: false
PERSON_FULL_NAME: '<NAME> '
FK_SPM_SPCL_MTG_CD: ' '
PERSON_ID: 'A16948219'
BLDG_CODE: 'RCLAS'
SECT_CREDIT_HRS_PL: ' '
SECTION_HEAD: 59172
ENROLL_STATUS: 'EN'
FK_CDI_INSTR_TYPE: 'LE'
SECT_CODE: 'B00'
FK_SEC_SCTN_NUM: 59172
}
{
END_MM_TIME: 50
LONG_DESC: ' '
TERM_CODE: 'FA21'
SECT_CREDIT_HRS: 4
BEGIN_HH_TIME: 13
SECTION_NUMBER: 51423
SUBJ_CODE: 'MATH'
GRADE_OPTN_CD_PLUS: '+'
WT_POS: ''
PRIMARY_INSTR_FLAG: 'Y'
ROOM_CODE: 'R107 '
FK_PCH_INTRL_REFID: 2122934
CRSE_TITLE: 'Linear Algebra '
END_HH_TIME: 13
GRADE_OPTION: 'L'
START_DATE: '2021-09-23'
CRSE_CODE: ' 18 '
DAY_CODE: '5'
BEGIN_MM_TIME: 0
NEED_HEADROW: false
PERSON_FULL_NAME: '<NAME> '
FK_SPM_SPCL_MTG_CD: ' '
PERSON_ID: 'A16948219'
BLDG_CODE: 'RCLAS'
SECT_CREDIT_HRS_PL: ' '
SECTION_HEAD: 59172
ENROLL_STATUS: 'EN'
FK_CDI_INSTR_TYPE: 'LE'
SECT_CODE: 'B00'
FK_SEC_SCTN_NUM: 59172
}
{
END_MM_TIME: 50
LONG_DESC: ' '
SCTN_CPCTY_QTY: 26
TERM_CODE: 'FA21'
SCTN_ENRLT_QTY: 26
SECT_CREDIT_HRS: 4
BEGIN_HH_TIME: 12
END_DATE: '2021-12-03'
SECTION_NUMBER: 59172
STP_ENRLT_FLAG: 'Y'
SUBJ_CODE: 'MATH'
GRADE_OPTN_CD_PLUS: '+'
WT_POS: ''
COUNT_ON_WAITLIST: 1
PRIMARY_INSTR_FLAG: 'Y'
ROOM_CODE: '3000A'
FK_PCH_INTRL_REFID: 2122934
CRSE_TITLE: 'Linear Algebra '
END_HH_TIME: 12
GRADE_OPTION: 'L'
START_DATE: '2021-09-23'
CRSE_CODE: ' 18 '
DAY_CODE: '2'
BEGIN_MM_TIME: 0
NEED_HEADROW: false
PERSON_FULL_NAME: '<NAME> '
FK_SPM_SPCL_MTG_CD: ' '
PERSON_ID: 'A16948219'
BLDG_CODE: 'YORK '
SECT_CREDIT_HRS_PL: ' '
SECTION_HEAD: 59172
ENROLL_STATUS: 'EN'
FK_CDI_INSTR_TYPE: 'DI'
SECT_CODE: 'B21'
FK_SEC_SCTN_NUM: 59172
}
{
END_MM_TIME: 0
LONG_DESC: ' '
TERM_CODE: 'FA21'
SECT_CREDIT_HRS: 4
BEGIN_HH_TIME: 0
SECTION_NUMBER: 51442
SUBJ_CODE: 'MATH'
GRADE_OPTN_CD_PLUS: '+'
WT_POS: ''
PRIMARY_INSTR_FLAG: 'Y'
ROOM_CODE: 'TBA'
FK_PCH_INTRL_REFID: 2122934
CRSE_TITLE: 'Linear Algebra '
END_HH_TIME: 0
GRADE_OPTION: 'L'
START_DATE: 'TBA'
CRSE_CODE: ' 18 '
DAY_CODE: 'TBA'
BEGIN_MM_TIME: 0
NEED_HEADROW: false
PERSON_FULL_NAME: '<NAME> '
PB_FRIEND: true
FK_SPM_SPCL_MTG_CD: ''
PERSON_ID: 'A16948219'
BLDG_CODE: 'TBA'
SECT_CREDIT_HRS_PL: ' '
SECTION_HEAD: 59172
ENROLL_STATUS: 'EN'
FK_CDI_INSTR_TYPE: 'LA'
SECT_CODE: 'B50'
FK_SEC_SCTN_NUM: 59172
}
{
END_MM_TIME: 50
LONG_DESC: ' '
TERM_CODE: 'FA21'
SECT_CREDIT_HRS: 4
BEGIN_HH_TIME: 20
SECTION_NUMBER: 51423
SUBJ_CODE: 'MATH'
GRADE_OPTN_CD_PLUS: '+'
WT_POS: ''
PRIMARY_INSTR_FLAG: 'Y'
ROOM_CODE: 'R07 '
FK_PCH_INTRL_REFID: 2122934
CRSE_TITLE: 'Linear Algebra '
END_HH_TIME: 21
GRADE_OPTION: 'L'
START_DATE: '2021-11-01'
CRSE_CODE: ' 18 '
DAY_CODE: '1'
BEGIN_MM_TIME: 0
NEED_HEADROW: false
PERSON_FULL_NAME: '<NAME> '
PB_FRIEND: true
FK_SPM_SPCL_MTG_CD: 'MI'
PERSON_ID: 'A16948219'
BLDG_CODE: 'RCLAS'
SECT_CREDIT_HRS_PL: ' '
SECTION_HEAD: 59172
ENROLL_STATUS: 'EN'
FK_CDI_INSTR_TYPE: 'MI'
SECT_CODE: 'B00'
FK_SEC_SCTN_NUM: 59172
}
{
END_MM_TIME: 59
LONG_DESC: ' '
TERM_CODE: 'FA21'
SECT_CREDIT_HRS: 4
BEGIN_HH_TIME: 19
SECTION_NUMBER: 51423
SUBJ_CODE: 'MATH'
GRADE_OPTN_CD_PLUS: '+'
WT_POS: ''
PRIMARY_INSTR_FLAG: 'Y'
ROOM_CODE: 'R01 '
FK_PCH_INTRL_REFID: 2122934
CRSE_TITLE: 'Linear Algebra '
END_HH_TIME: 21
GRADE_OPTION: 'L'
START_DATE: '2021-12-04'
CRSE_CODE: ' 18 '
DAY_CODE: '6'
BEGIN_MM_TIME: 0
NEED_HEADROW: false
PERSON_FULL_NAME: '<NAME> '
PB_FRIEND: true
FK_SPM_SPCL_MTG_CD: 'FI'
PERSON_ID: 'A16948219'
BLDG_CODE: 'RCLAS'
SECT_CREDIT_HRS_PL: ' '
SECTION_HEAD: 59172
ENROLL_STATUS: 'EN'
FK_CDI_INSTR_TYPE: 'FI'
SECT_CODE: 'B00'
FK_SEC_SCTN_NUM: 59172
}
{
END_MM_TIME: 50
LONG_DESC: ' '
TERM_CODE: 'FA21'
SECT_CREDIT_HRS: 4
BEGIN_HH_TIME: 17
SECTION_NUMBER: 51573
SUBJ_CODE: 'MATH'
GRADE_OPTN_CD_PLUS: '+'
WT_POS: ''
PRIMARY_INSTR_FLAG: 'TBA'
ROOM_CODE: '115 '
FK_PCH_INTRL_REFID: 2122934
CRSE_TITLE: 'Calculus&Analyt Geom/Sci&Engnr'
END_HH_TIME: 17
GRADE_OPTION: 'L'
START_DATE: '2021-09-23'
CRSE_CODE: ' 20C '
DAY_CODE: '1'
BEGIN_MM_TIME: 0
NEED_HEADROW: false
PERSON_FULL_NAME: '<NAME>'
FK_SPM_SPCL_MTG_CD: ' '
PERSON_ID: 'A16948219'
BLDG_CODE: 'CENTR'
SECT_CREDIT_HRS_PL: ' '
SECTION_HEAD: 51579
ENROLL_STATUS: 'EN'
FK_CDI_INSTR_TYPE: 'LE'
SECT_CODE: 'E00'
FK_SEC_SCTN_NUM: 51579
}
{
END_MM_TIME: 50
LONG_DESC: ' '
TERM_CODE: 'FA21'
SECT_CREDIT_HRS: 4
BEGIN_HH_TIME: 17
SECTION_NUMBER: 51573
SUBJ_CODE: 'MATH'
GRADE_OPTN_CD_PLUS: '+'
WT_POS: ''
PRIMARY_INSTR_FLAG: 'TBA'
ROOM_CODE: '115 '
FK_PCH_INTRL_REFID: 2122934
CRSE_TITLE: 'Calculus&Analyt Geom/Sci&Engnr'
END_HH_TIME: 17
GRADE_OPTION: 'L'
START_DATE: '2021-09-23'
CRSE_CODE: ' 20C '
DAY_CODE: '3'
BEGIN_MM_TIME: 0
NEED_HEADROW: false
PERSON_FULL_NAME: 'Staff'
FK_SPM_SPCL_MTG_CD: ' '
PERSON_ID: 'A16948219'
BLDG_CODE: 'CENTR'
SECT_CREDIT_HRS_PL: ' '
SECTION_HEAD: 51579
ENROLL_STATUS: 'EN'
FK_CDI_INSTR_TYPE: 'LE'
SECT_CODE: 'E00'
FK_SEC_SCTN_NUM: 51579
}
{
END_MM_TIME: 50
LONG_DESC: ' '
TERM_CODE: 'FA21'
SECT_CREDIT_HRS: 4
BEGIN_HH_TIME: 17
SECTION_NUMBER: 51573
SUBJ_CODE: 'MATH'
GRADE_OPTN_CD_PLUS: '+'
WT_POS: ''
PRIMARY_INSTR_FLAG: 'TBA'
ROOM_CODE: '115 '
FK_PCH_INTRL_REFID: 2122934
CRSE_TITLE: 'Calculus&Analyt Geom/Sci&Engnr'
END_HH_TIME: 17
GRADE_OPTION: 'L'
START_DATE: '2021-09-23'
CRSE_CODE: ' 20C '
DAY_CODE: '5'
BEGIN_MM_TIME: 0
NEED_HEADROW: false
PERSON_FULL_NAME: 'Staff'
FK_SPM_SPCL_MTG_CD: ' '
PERSON_ID: 'A16948219'
BLDG_CODE: 'CENTR'
SECT_CREDIT_HRS_PL: ' '
SECTION_HEAD: 51579
ENROLL_STATUS: 'EN'
FK_CDI_INSTR_TYPE: 'LE'
SECT_CODE: 'E00'
FK_SEC_SCTN_NUM: 51579
}
{
END_MM_TIME: 50
LONG_DESC: ' '
SCTN_CPCTY_QTY: 33
TERM_CODE: 'FA21'
SCTN_ENRLT_QTY: 12
SECT_CREDIT_HRS: 4
BEGIN_HH_TIME: 11
END_DATE: '2021-12-03'
SECTION_NUMBER: 51579
STP_ENRLT_FLAG: 'N'
SUBJ_CODE: 'MATH'
GRADE_OPTN_CD_PLUS: '+'
WT_POS: ''
COUNT_ON_WAITLIST: null
PRIMARY_INSTR_FLAG: 'TBA'
ROOM_CODE: '3000A'
FK_PCH_INTRL_REFID: 2122934
CRSE_TITLE: 'Calculus&Analyt Geom/Sci&Engnr'
END_HH_TIME: 11
GRADE_OPTION: 'L'
START_DATE: '2021-09-23'
CRSE_CODE: ' 20C '
DAY_CODE: '4'
BEGIN_MM_TIME: 0
NEED_HEADROW: false
PERSON_FULL_NAME: '<NAME>'
FK_SPM_SPCL_MTG_CD: ' '
PERSON_ID: 'A16948219'
BLDG_CODE: 'YORK '
SECT_CREDIT_HRS_PL: ' '
SECTION_HEAD: 51579
ENROLL_STATUS: 'EN'
FK_CDI_INSTR_TYPE: 'DI'
SECT_CODE: 'E06'
FK_SEC_SCTN_NUM: 51579
}
{
END_MM_TIME: 50
LONG_DESC: ' '
TERM_CODE: 'FA21'
SECT_CREDIT_HRS: 4
BEGIN_HH_TIME: 20
SECTION_NUMBER: 51573
SUBJ_CODE: 'MATH'
GRADE_OPTN_CD_PLUS: '+'
WT_POS: ''
PRIMARY_INSTR_FLAG: 'TBA'
ROOM_CODE: '0113 '
FK_PCH_INTRL_REFID: 2122934
CRSE_TITLE: 'Calculus&Analyt Geom/Sci&Engnr'
END_HH_TIME: 21
GRADE_OPTION: 'L'
START_DATE: '2021-11-02'
CRSE_CODE: ' 20C '
DAY_CODE: '2'
BEGIN_MM_TIME: 0
NEED_HEADROW: false
PERSON_FULL_NAME: '<NAME>'
PB_FRIEND: true
FK_SPM_SPCL_MTG_CD: 'MI'
PERSON_ID: 'A16948219'
BLDG_CODE: 'MOS '
SECT_CREDIT_HRS_PL: ' '
SECTION_HEAD: 51579
ENROLL_STATUS: 'EN'
FK_CDI_INSTR_TYPE: 'MI'
SECT_CODE: 'E00'
FK_SEC_SCTN_NUM: 51579
}
{
END_MM_TIME: 59
LONG_DESC: ' '
TERM_CODE: 'FA21'
SECT_CREDIT_HRS: 4
BEGIN_HH_TIME: 8
SECTION_NUMBER: 51573
SUBJ_CODE: 'MATH'
GRADE_OPTN_CD_PLUS: '+'
WT_POS: ''
PRIMARY_INSTR_FLAG: 'TBA'
ROOM_CODE: '0113 '
FK_PCH_INTRL_REFID: 2122934
CRSE_TITLE: 'Calculus&Analyt Geom/Sci&Engnr'
END_HH_TIME: 10
GRADE_OPTION: 'L'
START_DATE: '2021-12-04'
CRSE_CODE: ' 20C '
DAY_CODE: '6'
BEGIN_MM_TIME: 0
NEED_HEADROW: false
PERSON_FULL_NAME: '<NAME>'
PB_FRIEND: true
FK_SPM_SPCL_MTG_CD: 'FI'
PERSON_ID: 'A16948219'
BLDG_CODE: 'MOS '
SECT_CREDIT_HRS_PL: ' '
SECTION_HEAD: 51579
ENROLL_STATUS: 'EN'
FK_CDI_INSTR_TYPE: 'FI'
SECT_CODE: 'E00'
FK_SEC_SCTN_NUM: 51579
}
]
| true | # This is my schedule! I'm hard-coding it for now
window.schedule =
[
{
END_MM_TIME: 50
LONG_DESC: ' '
TERM_CODE: 'FA21'
SECT_CREDIT_HRS: 4
BEGIN_HH_TIME: 9
SECTION_NUMBER: 50710
SUBJ_CODE: 'CAT '
GRADE_OPTN_CD_PLUS: ' '
WT_POS: ''
PRIMARY_INSTR_FLAG: 'Y'
ROOM_CODE: '0114 '
FK_PCH_INTRL_REFID: 2122934
CRSE_TITLE: 'Culture, Art & Technology 1 '
END_HH_TIME: 10
GRADE_OPTION: 'L'
START_DATE: '2021-09-23'
CRSE_CODE: ' 1 '
DAY_CODE: '2'
BEGIN_MM_TIME: 30
NEED_HEADROW: false
PERSON_FULL_NAME: 'PI:NAME:<NAME>END_PI. '
FK_SPM_SPCL_MTG_CD: ' '
PERSON_ID: 'A16948219'
BLDG_CODE: 'MOS '
SECT_CREDIT_HRS_PL: ' '
SECTION_HEAD: 50717
ENROLL_STATUS: 'EN'
FK_CDI_INSTR_TYPE: 'LE'
SECT_CODE: 'D00'
FK_SEC_SCTN_NUM: 50717
}
{
END_MM_TIME: 50
LONG_DESC: ' '
TERM_CODE: 'FA21'
SECT_CREDIT_HRS: 4
BEGIN_HH_TIME: 9
SECTION_NUMBER: 50710
SUBJ_CODE: 'CAT '
GRADE_OPTN_CD_PLUS: ' '
WT_POS: ''
PRIMARY_INSTR_FLAG: 'Y'
ROOM_CODE: '0114 '
FK_PCH_INTRL_REFID: 2122934
CRSE_TITLE: 'Culture, Art & Technology 1 '
END_HH_TIME: 10
GRADE_OPTION: 'L'
START_DATE: '2021-09-23'
CRSE_CODE: ' 1 '
DAY_CODE: '4'
BEGIN_MM_TIME: 30
NEED_HEADROW: false
PERSON_FULL_NAME: 'PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI. '
FK_SPM_SPCL_MTG_CD: ' '
PERSON_ID: 'A16948219'
BLDG_CODE: 'MOS '
SECT_CREDIT_HRS_PL: ' '
SECTION_HEAD: 50717
ENROLL_STATUS: 'EN'
FK_CDI_INSTR_TYPE: 'LE'
SECT_CODE: 'D00'
FK_SEC_SCTN_NUM: 50717
}
{
END_MM_TIME: 50
LONG_DESC: ' '
SCTN_CPCTY_QTY: 17
TERM_CODE: 'FA21'
SCTN_ENRLT_QTY: 17
SECT_CREDIT_HRS: 4
BEGIN_HH_TIME: 12
END_DATE: '2021-12-03'
SECTION_NUMBER: 50717
STP_ENRLT_FLAG: 'N'
SUBJ_CODE: 'CAT '
GRADE_OPTN_CD_PLUS: ' '
WT_POS: ''
COUNT_ON_WAITLIST: null
PRIMARY_INSTR_FLAG: 'Y'
ROOM_CODE: 'B-146'
FK_PCH_INTRL_REFID: 2122934
CRSE_TITLE: 'Culture, Art & Technology 1 '
END_HH_TIME: 12
GRADE_OPTION: 'L'
START_DATE: '2021-09-23'
CRSE_CODE: ' 1 '
DAY_CODE: '4'
BEGIN_MM_TIME: 0
NEED_HEADROW: false
PERSON_FULL_NAME: 'PI:NAME:<NAME>END_PI. '
FK_SPM_SPCL_MTG_CD: ' '
PERSON_ID: 'A16948219'
BLDG_CODE: 'MANDE'
SECT_CREDIT_HRS_PL: ' '
SECTION_HEAD: 50717
ENROLL_STATUS: 'EN'
FK_CDI_INSTR_TYPE: 'DI'
SECT_CODE: 'D07'
FK_SEC_SCTN_NUM: 50717
}
{
END_MM_TIME: 59
LONG_DESC: ' '
TERM_CODE: 'FA21'
SECT_CREDIT_HRS: 4
BEGIN_HH_TIME: 8
SECTION_NUMBER: 50710
SUBJ_CODE: 'CAT '
GRADE_OPTN_CD_PLUS: ' '
WT_POS: ''
PRIMARY_INSTR_FLAG: 'Y'
ROOM_CODE: '0114 '
FK_PCH_INTRL_REFID: 2122934
CRSE_TITLE: 'Culture, Art & Technology 1 '
END_HH_TIME: 10
GRADE_OPTION: 'L'
START_DATE: '2021-12-09'
CRSE_CODE: ' 1 '
DAY_CODE: '4'
BEGIN_MM_TIME: 0
NEED_HEADROW: false
PERSON_FULL_NAME: 'PI:NAME:<NAME>END_PI. '
PB_FRIEND: true
FK_SPM_SPCL_MTG_CD: 'FI'
PERSON_ID: 'A16948219'
BLDG_CODE: 'MOS '
SECT_CREDIT_HRS_PL: ' '
SECTION_HEAD: 50717
ENROLL_STATUS: 'EN'
FK_CDI_INSTR_TYPE: 'FI'
SECT_CODE: 'D00'
FK_SEC_SCTN_NUM: 50717
}
{
END_MM_TIME: 50
LONG_DESC: ' '
TERM_CODE: 'FA21'
SECT_CREDIT_HRS: 4
BEGIN_HH_TIME: 16
SECTION_NUMBER: 53085
SUBJ_CODE: 'CSE '
GRADE_OPTN_CD_PLUS: '+'
WT_POS: ''
PRIMARY_INSTR_FLAG: 'Y'
ROOM_CODE: '119 '
FK_PCH_INTRL_REFID: 2122934
CRSE_TITLE: 'Accel. Intro to Programming '
END_HH_TIME: 16
GRADE_OPTION: 'L'
START_DATE: '2021-09-23'
CRSE_CODE: ' 11 '
DAY_CODE: '1'
BEGIN_MM_TIME: 0
NEED_HEADROW: false
PERSON_FULL_NAME: 'PI:NAME:<NAME>END_PI '
FK_SPM_SPCL_MTG_CD: ' '
PERSON_ID: 'A16948219'
BLDG_CODE: 'CENTR'
SECT_CREDIT_HRS_PL: ' '
SECTION_HEAD: 53086
ENROLL_STATUS: 'EN'
FK_CDI_INSTR_TYPE: 'LE'
SECT_CODE: 'C00'
FK_SEC_SCTN_NUM: 53086
}
{
END_MM_TIME: 50
LONG_DESC: ' '
TERM_CODE: 'FA21'
SECT_CREDIT_HRS: 4
BEGIN_HH_TIME: 16
SECTION_NUMBER: 53085
SUBJ_CODE: 'CSE '
GRADE_OPTN_CD_PLUS: '+'
WT_POS: ''
PRIMARY_INSTR_FLAG: 'Y'
ROOM_CODE: '119 '
FK_PCH_INTRL_REFID: 2122934
CRSE_TITLE: 'Accel. Intro to Programming '
END_HH_TIME: 16
GRADE_OPTION: 'L'
START_DATE: '2021-09-23'
CRSE_CODE: ' 11 '
DAY_CODE: '3'
BEGIN_MM_TIME: 0
NEED_HEADROW: false
PERSON_FULL_NAME: 'PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI '
FK_SPM_SPCL_MTG_CD: ' '
PERSON_ID: 'A16948219'
BLDG_CODE: 'CENTR'
SECT_CREDIT_HRS_PL: ' '
SECTION_HEAD: 53086
ENROLL_STATUS: 'EN'
FK_CDI_INSTR_TYPE: 'LE'
SECT_CODE: 'C00'
FK_SEC_SCTN_NUM: 53086
}
{
END_MM_TIME: 50
LONG_DESC: ' '
TERM_CODE: 'FA21'
SECT_CREDIT_HRS: 4
BEGIN_HH_TIME: 16
SECTION_NUMBER: 53085
SUBJ_CODE: 'CSE '
GRADE_OPTN_CD_PLUS: '+'
WT_POS: ''
PRIMARY_INSTR_FLAG: 'Y'
ROOM_CODE: '119 '
FK_PCH_INTRL_REFID: 2122934
CRSE_TITLE: 'Accel. Intro to Programming '
END_HH_TIME: 16
GRADE_OPTION: 'L'
START_DATE: '2021-09-23'
CRSE_CODE: ' 11 '
DAY_CODE: '5'
BEGIN_MM_TIME: 0
NEED_HEADROW: false
PERSON_FULL_NAME: 'PI:NAME:<NAME>END_PI '
FK_SPM_SPCL_MTG_CD: ' '
PERSON_ID: 'A16948219'
BLDG_CODE: 'CENTR'
SECT_CREDIT_HRS_PL: ' '
SECTION_HEAD: 53086
ENROLL_STATUS: 'EN'
FK_CDI_INSTR_TYPE: 'LE'
SECT_CODE: 'C00'
FK_SEC_SCTN_NUM: 53086
}
{
END_MM_TIME: 50
LONG_DESC: ' '
SCTN_CPCTY_QTY: 49
TERM_CODE: 'FA21'
SCTN_ENRLT_QTY: 49
SECT_CREDIT_HRS: 4
BEGIN_HH_TIME: 15
END_DATE: '2021-12-03'
SECTION_NUMBER: 53086
STP_ENRLT_FLAG: 'Y'
SUBJ_CODE: 'CSE '
GRADE_OPTN_CD_PLUS: '+'
WT_POS: ''
COUNT_ON_WAITLIST: 10
PRIMARY_INSTR_FLAG: 'Y'
ROOM_CODE: '120 '
FK_PCH_INTRL_REFID: 2122934
CRSE_TITLE: 'Accel. Intro to Programming '
END_HH_TIME: 15
GRADE_OPTION: 'L'
START_DATE: '2021-09-23'
CRSE_CODE: ' 11 '
DAY_CODE: '1'
BEGIN_MM_TIME: 0
NEED_HEADROW: false
PERSON_FULL_NAME: 'PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI '
FK_SPM_SPCL_MTG_CD: ' '
PERSON_ID: 'A16948219'
BLDG_CODE: 'PCYNH'
SECT_CREDIT_HRS_PL: ' '
SECTION_HEAD: 53086
ENROLL_STATUS: 'EN'
FK_CDI_INSTR_TYPE: 'DI'
SECT_CODE: 'C01'
FK_SEC_SCTN_NUM: 53086
}
{
END_MM_TIME: 59
LONG_DESC: ' '
TERM_CODE: 'FA21'
SECT_CREDIT_HRS: 4
BEGIN_HH_TIME: 15
SECTION_NUMBER: 53085
SUBJ_CODE: 'CSE '
GRADE_OPTN_CD_PLUS: '+'
WT_POS: ''
PRIMARY_INSTR_FLAG: 'Y'
ROOM_CODE: '115 '
FK_PCH_INTRL_REFID: 2122934
CRSE_TITLE: 'Accel. Intro to Programming '
END_HH_TIME: 17
GRADE_OPTION: 'L'
START_DATE: '2021-12-04'
CRSE_CODE: ' 11 '
DAY_CODE: '6'
BEGIN_MM_TIME: 0
NEED_HEADROW: false
PERSON_FULL_NAME: 'PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI '
PB_FRIEND: true
FK_SPM_SPCL_MTG_CD: 'FI'
PERSON_ID: 'A16948219'
BLDG_CODE: 'CENTR'
SECT_CREDIT_HRS_PL: ' '
SECTION_HEAD: 53086
ENROLL_STATUS: 'EN'
FK_CDI_INSTR_TYPE: 'FI'
SECT_CODE: 'C00'
FK_SEC_SCTN_NUM: 53086
}
{
END_MM_TIME: 50
LONG_DESC: ' '
TERM_CODE: 'FA21'
SECT_CREDIT_HRS: 4
BEGIN_HH_TIME: 13
SECTION_NUMBER: 51423
SUBJ_CODE: 'MATH'
GRADE_OPTN_CD_PLUS: '+'
WT_POS: ''
PRIMARY_INSTR_FLAG: 'Y'
ROOM_CODE: 'R107 '
FK_PCH_INTRL_REFID: 2122934
CRSE_TITLE: 'Linear Algebra '
END_HH_TIME: 13
GRADE_OPTION: 'L'
START_DATE: '2021-09-23'
CRSE_CODE: ' 18 '
DAY_CODE: '1'
BEGIN_MM_TIME: 0
NEED_HEADROW: false
PERSON_FULL_NAME: 'PI:NAME:<NAME>END_PI '
FK_SPM_SPCL_MTG_CD: ' '
PERSON_ID: 'A16948219'
BLDG_CODE: 'RCLAS'
SECT_CREDIT_HRS_PL: ' '
SECTION_HEAD: 59172
ENROLL_STATUS: 'EN'
FK_CDI_INSTR_TYPE: 'LE'
SECT_CODE: 'B00'
FK_SEC_SCTN_NUM: 59172
}
{
END_MM_TIME: 50
LONG_DESC: ' '
TERM_CODE: 'FA21'
SECT_CREDIT_HRS: 4
BEGIN_HH_TIME: 13
SECTION_NUMBER: 51423
SUBJ_CODE: 'MATH'
GRADE_OPTN_CD_PLUS: '+'
WT_POS: ''
PRIMARY_INSTR_FLAG: 'Y'
ROOM_CODE: 'R107 '
FK_PCH_INTRL_REFID: 2122934
CRSE_TITLE: 'Linear Algebra '
END_HH_TIME: 13
GRADE_OPTION: 'L'
START_DATE: '2021-09-23'
CRSE_CODE: ' 18 '
DAY_CODE: '3'
BEGIN_MM_TIME: 0
NEED_HEADROW: false
PERSON_FULL_NAME: 'PI:NAME:<NAME>END_PI '
FK_SPM_SPCL_MTG_CD: ' '
PERSON_ID: 'A16948219'
BLDG_CODE: 'RCLAS'
SECT_CREDIT_HRS_PL: ' '
SECTION_HEAD: 59172
ENROLL_STATUS: 'EN'
FK_CDI_INSTR_TYPE: 'LE'
SECT_CODE: 'B00'
FK_SEC_SCTN_NUM: 59172
}
{
END_MM_TIME: 50
LONG_DESC: ' '
TERM_CODE: 'FA21'
SECT_CREDIT_HRS: 4
BEGIN_HH_TIME: 13
SECTION_NUMBER: 51423
SUBJ_CODE: 'MATH'
GRADE_OPTN_CD_PLUS: '+'
WT_POS: ''
PRIMARY_INSTR_FLAG: 'Y'
ROOM_CODE: 'R107 '
FK_PCH_INTRL_REFID: 2122934
CRSE_TITLE: 'Linear Algebra '
END_HH_TIME: 13
GRADE_OPTION: 'L'
START_DATE: '2021-09-23'
CRSE_CODE: ' 18 '
DAY_CODE: '5'
BEGIN_MM_TIME: 0
NEED_HEADROW: false
PERSON_FULL_NAME: 'PI:NAME:<NAME>END_PI '
FK_SPM_SPCL_MTG_CD: ' '
PERSON_ID: 'A16948219'
BLDG_CODE: 'RCLAS'
SECT_CREDIT_HRS_PL: ' '
SECTION_HEAD: 59172
ENROLL_STATUS: 'EN'
FK_CDI_INSTR_TYPE: 'LE'
SECT_CODE: 'B00'
FK_SEC_SCTN_NUM: 59172
}
{
END_MM_TIME: 50
LONG_DESC: ' '
SCTN_CPCTY_QTY: 26
TERM_CODE: 'FA21'
SCTN_ENRLT_QTY: 26
SECT_CREDIT_HRS: 4
BEGIN_HH_TIME: 12
END_DATE: '2021-12-03'
SECTION_NUMBER: 59172
STP_ENRLT_FLAG: 'Y'
SUBJ_CODE: 'MATH'
GRADE_OPTN_CD_PLUS: '+'
WT_POS: ''
COUNT_ON_WAITLIST: 1
PRIMARY_INSTR_FLAG: 'Y'
ROOM_CODE: '3000A'
FK_PCH_INTRL_REFID: 2122934
CRSE_TITLE: 'Linear Algebra '
END_HH_TIME: 12
GRADE_OPTION: 'L'
START_DATE: '2021-09-23'
CRSE_CODE: ' 18 '
DAY_CODE: '2'
BEGIN_MM_TIME: 0
NEED_HEADROW: false
PERSON_FULL_NAME: 'PI:NAME:<NAME>END_PI '
FK_SPM_SPCL_MTG_CD: ' '
PERSON_ID: 'A16948219'
BLDG_CODE: 'YORK '
SECT_CREDIT_HRS_PL: ' '
SECTION_HEAD: 59172
ENROLL_STATUS: 'EN'
FK_CDI_INSTR_TYPE: 'DI'
SECT_CODE: 'B21'
FK_SEC_SCTN_NUM: 59172
}
{
END_MM_TIME: 0
LONG_DESC: ' '
TERM_CODE: 'FA21'
SECT_CREDIT_HRS: 4
BEGIN_HH_TIME: 0
SECTION_NUMBER: 51442
SUBJ_CODE: 'MATH'
GRADE_OPTN_CD_PLUS: '+'
WT_POS: ''
PRIMARY_INSTR_FLAG: 'Y'
ROOM_CODE: 'TBA'
FK_PCH_INTRL_REFID: 2122934
CRSE_TITLE: 'Linear Algebra '
END_HH_TIME: 0
GRADE_OPTION: 'L'
START_DATE: 'TBA'
CRSE_CODE: ' 18 '
DAY_CODE: 'TBA'
BEGIN_MM_TIME: 0
NEED_HEADROW: false
PERSON_FULL_NAME: 'PI:NAME:<NAME>END_PI '
PB_FRIEND: true
FK_SPM_SPCL_MTG_CD: ''
PERSON_ID: 'A16948219'
BLDG_CODE: 'TBA'
SECT_CREDIT_HRS_PL: ' '
SECTION_HEAD: 59172
ENROLL_STATUS: 'EN'
FK_CDI_INSTR_TYPE: 'LA'
SECT_CODE: 'B50'
FK_SEC_SCTN_NUM: 59172
}
{
END_MM_TIME: 50
LONG_DESC: ' '
TERM_CODE: 'FA21'
SECT_CREDIT_HRS: 4
BEGIN_HH_TIME: 20
SECTION_NUMBER: 51423
SUBJ_CODE: 'MATH'
GRADE_OPTN_CD_PLUS: '+'
WT_POS: ''
PRIMARY_INSTR_FLAG: 'Y'
ROOM_CODE: 'R07 '
FK_PCH_INTRL_REFID: 2122934
CRSE_TITLE: 'Linear Algebra '
END_HH_TIME: 21
GRADE_OPTION: 'L'
START_DATE: '2021-11-01'
CRSE_CODE: ' 18 '
DAY_CODE: '1'
BEGIN_MM_TIME: 0
NEED_HEADROW: false
PERSON_FULL_NAME: 'PI:NAME:<NAME>END_PI '
PB_FRIEND: true
FK_SPM_SPCL_MTG_CD: 'MI'
PERSON_ID: 'A16948219'
BLDG_CODE: 'RCLAS'
SECT_CREDIT_HRS_PL: ' '
SECTION_HEAD: 59172
ENROLL_STATUS: 'EN'
FK_CDI_INSTR_TYPE: 'MI'
SECT_CODE: 'B00'
FK_SEC_SCTN_NUM: 59172
}
{
END_MM_TIME: 59
LONG_DESC: ' '
TERM_CODE: 'FA21'
SECT_CREDIT_HRS: 4
BEGIN_HH_TIME: 19
SECTION_NUMBER: 51423
SUBJ_CODE: 'MATH'
GRADE_OPTN_CD_PLUS: '+'
WT_POS: ''
PRIMARY_INSTR_FLAG: 'Y'
ROOM_CODE: 'R01 '
FK_PCH_INTRL_REFID: 2122934
CRSE_TITLE: 'Linear Algebra '
END_HH_TIME: 21
GRADE_OPTION: 'L'
START_DATE: '2021-12-04'
CRSE_CODE: ' 18 '
DAY_CODE: '6'
BEGIN_MM_TIME: 0
NEED_HEADROW: false
PERSON_FULL_NAME: 'PI:NAME:<NAME>END_PI '
PB_FRIEND: true
FK_SPM_SPCL_MTG_CD: 'FI'
PERSON_ID: 'A16948219'
BLDG_CODE: 'RCLAS'
SECT_CREDIT_HRS_PL: ' '
SECTION_HEAD: 59172
ENROLL_STATUS: 'EN'
FK_CDI_INSTR_TYPE: 'FI'
SECT_CODE: 'B00'
FK_SEC_SCTN_NUM: 59172
}
{
END_MM_TIME: 50
LONG_DESC: ' '
TERM_CODE: 'FA21'
SECT_CREDIT_HRS: 4
BEGIN_HH_TIME: 17
SECTION_NUMBER: 51573
SUBJ_CODE: 'MATH'
GRADE_OPTN_CD_PLUS: '+'
WT_POS: ''
PRIMARY_INSTR_FLAG: 'TBA'
ROOM_CODE: '115 '
FK_PCH_INTRL_REFID: 2122934
CRSE_TITLE: 'Calculus&Analyt Geom/Sci&Engnr'
END_HH_TIME: 17
GRADE_OPTION: 'L'
START_DATE: '2021-09-23'
CRSE_CODE: ' 20C '
DAY_CODE: '1'
BEGIN_MM_TIME: 0
NEED_HEADROW: false
PERSON_FULL_NAME: 'PI:NAME:<NAME>END_PI'
FK_SPM_SPCL_MTG_CD: ' '
PERSON_ID: 'A16948219'
BLDG_CODE: 'CENTR'
SECT_CREDIT_HRS_PL: ' '
SECTION_HEAD: 51579
ENROLL_STATUS: 'EN'
FK_CDI_INSTR_TYPE: 'LE'
SECT_CODE: 'E00'
FK_SEC_SCTN_NUM: 51579
}
{
END_MM_TIME: 50
LONG_DESC: ' '
TERM_CODE: 'FA21'
SECT_CREDIT_HRS: 4
BEGIN_HH_TIME: 17
SECTION_NUMBER: 51573
SUBJ_CODE: 'MATH'
GRADE_OPTN_CD_PLUS: '+'
WT_POS: ''
PRIMARY_INSTR_FLAG: 'TBA'
ROOM_CODE: '115 '
FK_PCH_INTRL_REFID: 2122934
CRSE_TITLE: 'Calculus&Analyt Geom/Sci&Engnr'
END_HH_TIME: 17
GRADE_OPTION: 'L'
START_DATE: '2021-09-23'
CRSE_CODE: ' 20C '
DAY_CODE: '3'
BEGIN_MM_TIME: 0
NEED_HEADROW: false
PERSON_FULL_NAME: 'Staff'
FK_SPM_SPCL_MTG_CD: ' '
PERSON_ID: 'A16948219'
BLDG_CODE: 'CENTR'
SECT_CREDIT_HRS_PL: ' '
SECTION_HEAD: 51579
ENROLL_STATUS: 'EN'
FK_CDI_INSTR_TYPE: 'LE'
SECT_CODE: 'E00'
FK_SEC_SCTN_NUM: 51579
}
{
END_MM_TIME: 50
LONG_DESC: ' '
TERM_CODE: 'FA21'
SECT_CREDIT_HRS: 4
BEGIN_HH_TIME: 17
SECTION_NUMBER: 51573
SUBJ_CODE: 'MATH'
GRADE_OPTN_CD_PLUS: '+'
WT_POS: ''
PRIMARY_INSTR_FLAG: 'TBA'
ROOM_CODE: '115 '
FK_PCH_INTRL_REFID: 2122934
CRSE_TITLE: 'Calculus&Analyt Geom/Sci&Engnr'
END_HH_TIME: 17
GRADE_OPTION: 'L'
START_DATE: '2021-09-23'
CRSE_CODE: ' 20C '
DAY_CODE: '5'
BEGIN_MM_TIME: 0
NEED_HEADROW: false
PERSON_FULL_NAME: 'Staff'
FK_SPM_SPCL_MTG_CD: ' '
PERSON_ID: 'A16948219'
BLDG_CODE: 'CENTR'
SECT_CREDIT_HRS_PL: ' '
SECTION_HEAD: 51579
ENROLL_STATUS: 'EN'
FK_CDI_INSTR_TYPE: 'LE'
SECT_CODE: 'E00'
FK_SEC_SCTN_NUM: 51579
}
{
END_MM_TIME: 50
LONG_DESC: ' '
SCTN_CPCTY_QTY: 33
TERM_CODE: 'FA21'
SCTN_ENRLT_QTY: 12
SECT_CREDIT_HRS: 4
BEGIN_HH_TIME: 11
END_DATE: '2021-12-03'
SECTION_NUMBER: 51579
STP_ENRLT_FLAG: 'N'
SUBJ_CODE: 'MATH'
GRADE_OPTN_CD_PLUS: '+'
WT_POS: ''
COUNT_ON_WAITLIST: null
PRIMARY_INSTR_FLAG: 'TBA'
ROOM_CODE: '3000A'
FK_PCH_INTRL_REFID: 2122934
CRSE_TITLE: 'Calculus&Analyt Geom/Sci&Engnr'
END_HH_TIME: 11
GRADE_OPTION: 'L'
START_DATE: '2021-09-23'
CRSE_CODE: ' 20C '
DAY_CODE: '4'
BEGIN_MM_TIME: 0
NEED_HEADROW: false
PERSON_FULL_NAME: 'PI:NAME:<NAME>END_PI'
FK_SPM_SPCL_MTG_CD: ' '
PERSON_ID: 'A16948219'
BLDG_CODE: 'YORK '
SECT_CREDIT_HRS_PL: ' '
SECTION_HEAD: 51579
ENROLL_STATUS: 'EN'
FK_CDI_INSTR_TYPE: 'DI'
SECT_CODE: 'E06'
FK_SEC_SCTN_NUM: 51579
}
{
END_MM_TIME: 50
LONG_DESC: ' '
TERM_CODE: 'FA21'
SECT_CREDIT_HRS: 4
BEGIN_HH_TIME: 20
SECTION_NUMBER: 51573
SUBJ_CODE: 'MATH'
GRADE_OPTN_CD_PLUS: '+'
WT_POS: ''
PRIMARY_INSTR_FLAG: 'TBA'
ROOM_CODE: '0113 '
FK_PCH_INTRL_REFID: 2122934
CRSE_TITLE: 'Calculus&Analyt Geom/Sci&Engnr'
END_HH_TIME: 21
GRADE_OPTION: 'L'
START_DATE: '2021-11-02'
CRSE_CODE: ' 20C '
DAY_CODE: '2'
BEGIN_MM_TIME: 0
NEED_HEADROW: false
PERSON_FULL_NAME: 'PI:NAME:<NAME>END_PI'
PB_FRIEND: true
FK_SPM_SPCL_MTG_CD: 'MI'
PERSON_ID: 'A16948219'
BLDG_CODE: 'MOS '
SECT_CREDIT_HRS_PL: ' '
SECTION_HEAD: 51579
ENROLL_STATUS: 'EN'
FK_CDI_INSTR_TYPE: 'MI'
SECT_CODE: 'E00'
FK_SEC_SCTN_NUM: 51579
}
{
END_MM_TIME: 59
LONG_DESC: ' '
TERM_CODE: 'FA21'
SECT_CREDIT_HRS: 4
BEGIN_HH_TIME: 8
SECTION_NUMBER: 51573
SUBJ_CODE: 'MATH'
GRADE_OPTN_CD_PLUS: '+'
WT_POS: ''
PRIMARY_INSTR_FLAG: 'TBA'
ROOM_CODE: '0113 '
FK_PCH_INTRL_REFID: 2122934
CRSE_TITLE: 'Calculus&Analyt Geom/Sci&Engnr'
END_HH_TIME: 10
GRADE_OPTION: 'L'
START_DATE: '2021-12-04'
CRSE_CODE: ' 20C '
DAY_CODE: '6'
BEGIN_MM_TIME: 0
NEED_HEADROW: false
PERSON_FULL_NAME: 'PI:NAME:<NAME>END_PI'
PB_FRIEND: true
FK_SPM_SPCL_MTG_CD: 'FI'
PERSON_ID: 'A16948219'
BLDG_CODE: 'MOS '
SECT_CREDIT_HRS_PL: ' '
SECTION_HEAD: 51579
ENROLL_STATUS: 'EN'
FK_CDI_INSTR_TYPE: 'FI'
SECT_CODE: 'E00'
FK_SEC_SCTN_NUM: 51579
}
]
|
[
{
"context": "or form', ->\n @rendered.should.containEql 'Edit Halley Johnson'\n @rendered.should.containEql 'value=\"Halley J",
"end": 1254,
"score": 0.8815126419067383,
"start": 1240,
"tag": "NAME",
"value": "Halley Johnson"
},
{
"context": " Johnson'\n @rendered.should.containEql 'value=\"Halley Johnson\"'\n @rendered.should.containEql 'value=\"kanaabe",
"end": 1310,
"score": 0.9996806979179382,
"start": 1296,
"tag": "NAME",
"value": "Halley Johnson"
},
{
"context": "ponent, 'author-edit__twitter'\n input.value = 'artsyeditorial'\n r.simulate.change input\n @component.state",
"end": 1562,
"score": 0.7189214825630188,
"start": 1548,
"tag": "USERNAME",
"value": "artsyeditorial"
},
{
"context": "mponent.state.author.twitter_handle.should.equal 'artsyeditorial'\n\n it 'updates name state on input changes', ->\n",
"end": 1663,
"score": 0.8523440361022949,
"start": 1649,
"tag": "USERNAME",
"value": "artsyeditorial"
},
{
"context": "component, 'author-edit__name'\n input.value = 'Owen Dodd'\n r.simulate.change input\n @component.state",
"end": 1792,
"score": 0.9997873902320862,
"start": 1783,
"tag": "NAME",
"value": "Owen Dodd"
},
{
"context": "ut\n @component.state.author.name.should.equal 'Owen Dodd'\n\n it 'updates bio state on input changes', ->\n ",
"end": 1878,
"score": 0.9998088479042053,
"start": 1869,
"tag": "NAME",
"value": "Owen Dodd"
}
] | src/client/apps/settings/test/client/authors/author_modal.test.coffee | craigspaeth/positron | 76 | _ = require 'underscore'
benv = require 'benv'
sinon = require 'sinon'
{ resolve } = require 'path'
fixtures = require '../../../../../../test/helpers/fixtures'
React = require 'react'
ReactDOM = require 'react-dom'
ReactTestUtils = require 'react-dom/test-utils'
ReactDOMServer = require 'react-dom/server'
r =
find: ReactTestUtils.findRenderedDOMComponentWithClass
simulate: ReactTestUtils.Simulate
describe 'AuthorModal', ->
beforeEach (done) ->
benv.setup =>
benv.expose $: benv.require 'jquery'
AuthorModal = benv.requireWithJadeify(
resolve(__dirname, '../../../client/authors/author_modal')
['icons']
)
AuthorModal.__set__ 'AuthorImage', @AuthorImage = sinon.stub()
props =
author: fixtures().authors
isOpen: true
onSave: @onSave = sinon.stub()
onClose: @onClose = sinon.stub()
@rendered = ReactDOMServer.renderToString(
React.createElement(AuthorModal, props)
)
@component = ReactDOM.render(
React.createElement(AuthorModal, props),
(@$el = $ "<div></div>")[0],
=>
)
done()
afterEach ->
benv.teardown()
it 'renders author form', ->
@rendered.should.containEql 'Edit Halley Johnson'
@rendered.should.containEql 'value="Halley Johnson"'
@rendered.should.containEql 'value="kanaabe"'
@rendered.should.containEql 'Writer based in NYC'
it 'updates twitter_handle state on input changes', ->
input = r.find @component, 'author-edit__twitter'
input.value = 'artsyeditorial'
r.simulate.change input
@component.state.author.twitter_handle.should.equal 'artsyeditorial'
it 'updates name state on input changes', ->
input = r.find @component, 'author-edit__name'
input.value = 'Owen Dodd'
r.simulate.change input
@component.state.author.name.should.equal 'Owen Dodd'
it 'updates bio state on input changes', ->
input = r.find @component, 'author-edit__bio'
input.value = 'This is a new bio.'
r.simulate.change input
@component.state.author.bio.should.equal 'This is a new bio.'
@component.state.remainingChars.should.equal 182
it 'updates image on change', ->
@component.onImageChange 'https://artsy.net/new-image.jpg'
@component.state.author.image_url.should.equal 'https://artsy.net/new-image.jpg'
| 82521 | _ = require 'underscore'
benv = require 'benv'
sinon = require 'sinon'
{ resolve } = require 'path'
fixtures = require '../../../../../../test/helpers/fixtures'
React = require 'react'
ReactDOM = require 'react-dom'
ReactTestUtils = require 'react-dom/test-utils'
ReactDOMServer = require 'react-dom/server'
r =
find: ReactTestUtils.findRenderedDOMComponentWithClass
simulate: ReactTestUtils.Simulate
describe 'AuthorModal', ->
beforeEach (done) ->
benv.setup =>
benv.expose $: benv.require 'jquery'
AuthorModal = benv.requireWithJadeify(
resolve(__dirname, '../../../client/authors/author_modal')
['icons']
)
AuthorModal.__set__ 'AuthorImage', @AuthorImage = sinon.stub()
props =
author: fixtures().authors
isOpen: true
onSave: @onSave = sinon.stub()
onClose: @onClose = sinon.stub()
@rendered = ReactDOMServer.renderToString(
React.createElement(AuthorModal, props)
)
@component = ReactDOM.render(
React.createElement(AuthorModal, props),
(@$el = $ "<div></div>")[0],
=>
)
done()
afterEach ->
benv.teardown()
it 'renders author form', ->
@rendered.should.containEql 'Edit <NAME>'
@rendered.should.containEql 'value="<NAME>"'
@rendered.should.containEql 'value="kanaabe"'
@rendered.should.containEql 'Writer based in NYC'
it 'updates twitter_handle state on input changes', ->
input = r.find @component, 'author-edit__twitter'
input.value = 'artsyeditorial'
r.simulate.change input
@component.state.author.twitter_handle.should.equal 'artsyeditorial'
it 'updates name state on input changes', ->
input = r.find @component, 'author-edit__name'
input.value = '<NAME>'
r.simulate.change input
@component.state.author.name.should.equal '<NAME>'
it 'updates bio state on input changes', ->
input = r.find @component, 'author-edit__bio'
input.value = 'This is a new bio.'
r.simulate.change input
@component.state.author.bio.should.equal 'This is a new bio.'
@component.state.remainingChars.should.equal 182
it 'updates image on change', ->
@component.onImageChange 'https://artsy.net/new-image.jpg'
@component.state.author.image_url.should.equal 'https://artsy.net/new-image.jpg'
| true | _ = require 'underscore'
benv = require 'benv'
sinon = require 'sinon'
{ resolve } = require 'path'
fixtures = require '../../../../../../test/helpers/fixtures'
React = require 'react'
ReactDOM = require 'react-dom'
ReactTestUtils = require 'react-dom/test-utils'
ReactDOMServer = require 'react-dom/server'
r =
find: ReactTestUtils.findRenderedDOMComponentWithClass
simulate: ReactTestUtils.Simulate
describe 'AuthorModal', ->
beforeEach (done) ->
benv.setup =>
benv.expose $: benv.require 'jquery'
AuthorModal = benv.requireWithJadeify(
resolve(__dirname, '../../../client/authors/author_modal')
['icons']
)
AuthorModal.__set__ 'AuthorImage', @AuthorImage = sinon.stub()
props =
author: fixtures().authors
isOpen: true
onSave: @onSave = sinon.stub()
onClose: @onClose = sinon.stub()
@rendered = ReactDOMServer.renderToString(
React.createElement(AuthorModal, props)
)
@component = ReactDOM.render(
React.createElement(AuthorModal, props),
(@$el = $ "<div></div>")[0],
=>
)
done()
afterEach ->
benv.teardown()
it 'renders author form', ->
@rendered.should.containEql 'Edit PI:NAME:<NAME>END_PI'
@rendered.should.containEql 'value="PI:NAME:<NAME>END_PI"'
@rendered.should.containEql 'value="kanaabe"'
@rendered.should.containEql 'Writer based in NYC'
it 'updates twitter_handle state on input changes', ->
input = r.find @component, 'author-edit__twitter'
input.value = 'artsyeditorial'
r.simulate.change input
@component.state.author.twitter_handle.should.equal 'artsyeditorial'
it 'updates name state on input changes', ->
input = r.find @component, 'author-edit__name'
input.value = 'PI:NAME:<NAME>END_PI'
r.simulate.change input
@component.state.author.name.should.equal 'PI:NAME:<NAME>END_PI'
it 'updates bio state on input changes', ->
input = r.find @component, 'author-edit__bio'
input.value = 'This is a new bio.'
r.simulate.change input
@component.state.author.bio.should.equal 'This is a new bio.'
@component.state.remainingChars.should.equal 182
it 'updates image on change', ->
@component.onImageChange 'https://artsy.net/new-image.jpg'
@component.state.author.image_url.should.equal 'https://artsy.net/new-image.jpg'
|
[
{
"context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public Li",
"end": 43,
"score": 0.9999141693115234,
"start": 29,
"tag": "EMAIL",
"value": "contact@ppy.sh"
}
] | resources/assets/coffee/_classes/nav-button.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 @NavButton
constructor: ->
@containers = document.getElementsByClassName 'js-nav-button--container'
@items = document.getElementsByClassName 'js-nav-button--item'
@main = document.getElementsByClassName 'js-nav-button'
addEventListener 'turbolinks:load', @load
load: =>
if !@listening
@listening = true
$(window).on 'throttled-resize', @hideOrShow
return if @main.length == 0
# assumes:
# - the width never changes once the page loads
# - items all have same width
@itemWidth = @items[0].offsetWidth
@defaultWidth = 0
@defaultWidth += c.offsetWidth for c in @containers
@hideOrShow()
hideOrShow: =>
return if @main.length == 0
currentMaxWidth = @main[0].offsetWidth
currentWidth = @defaultWidth
i.classList.remove 'hidden' for i in @items
if currentMaxWidth < currentWidth
for item in @items
currentWidth -= @itemWidth
item.classList.add 'hidden'
return if currentMaxWidth >= currentWidth
| 180467 | # 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 @NavButton
constructor: ->
@containers = document.getElementsByClassName 'js-nav-button--container'
@items = document.getElementsByClassName 'js-nav-button--item'
@main = document.getElementsByClassName 'js-nav-button'
addEventListener 'turbolinks:load', @load
load: =>
if !@listening
@listening = true
$(window).on 'throttled-resize', @hideOrShow
return if @main.length == 0
# assumes:
# - the width never changes once the page loads
# - items all have same width
@itemWidth = @items[0].offsetWidth
@defaultWidth = 0
@defaultWidth += c.offsetWidth for c in @containers
@hideOrShow()
hideOrShow: =>
return if @main.length == 0
currentMaxWidth = @main[0].offsetWidth
currentWidth = @defaultWidth
i.classList.remove 'hidden' for i in @items
if currentMaxWidth < currentWidth
for item in @items
currentWidth -= @itemWidth
item.classList.add 'hidden'
return if currentMaxWidth >= currentWidth
| 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 @NavButton
constructor: ->
@containers = document.getElementsByClassName 'js-nav-button--container'
@items = document.getElementsByClassName 'js-nav-button--item'
@main = document.getElementsByClassName 'js-nav-button'
addEventListener 'turbolinks:load', @load
load: =>
if !@listening
@listening = true
$(window).on 'throttled-resize', @hideOrShow
return if @main.length == 0
# assumes:
# - the width never changes once the page loads
# - items all have same width
@itemWidth = @items[0].offsetWidth
@defaultWidth = 0
@defaultWidth += c.offsetWidth for c in @containers
@hideOrShow()
hideOrShow: =>
return if @main.length == 0
currentMaxWidth = @main[0].offsetWidth
currentWidth = @defaultWidth
i.classList.remove 'hidden' for i in @items
if currentMaxWidth < currentWidth
for item in @items
currentWidth -= @itemWidth
item.classList.add 'hidden'
return if currentMaxWidth >= currentWidth
|
[
{
"context": "User({role: 'teacher'})\n# yield utils.loginUser(@teacher)\n# done()\n# \n# describe 'when recipientID is",
"end": 430,
"score": 0.9011542797088623,
"start": 422,
"tag": "USERNAME",
"value": "@teacher"
},
{
"context": "# done()\n# \n# describe 'when recipientID is \"schools@codecombat.com\"', ->\n# it 'sends to that email', utils.wrap (",
"end": 504,
"score": 0.9999277591705322,
"start": 482,
"tag": "EMAIL",
"value": "schools@codecombat.com"
},
{
"context": "rl: getURL('/contact'), json: {\n# sender: 'some@email.com'\n# message: 'A message'\n# recipient",
"end": 674,
"score": 0.999921977519989,
"start": 660,
"tag": "EMAIL",
"value": "some@email.com"
},
{
"context": " message: 'A message'\n# recipientID: 'schools@codecombat.com'\n# }})\n# expect(sendwithus.api.send).to",
"end": 751,
"score": 0.9999274015426636,
"start": 729,
"tag": "EMAIL",
"value": "schools@codecombat.com"
},
{
"context": "HaveBeenCalled()\n# user = yield User.findById(@teacher.id)\n# yield new Promise((resolve) -> setTime",
"end": 860,
"score": 0.8859381079673767,
"start": 852,
"tag": "USERNAME",
"value": "@teacher"
}
] | spec/server/functional/contact.spec.coffee | johanvl/codecombat | 2 | utils = require '../utils'
sendwithus = require '../../../server/sendwithus'
request = require '../request'
User = require '../../../server/models/User'
# TODO: need to update this test since /contact calls external Close.io API now
#xdescribe 'POST /contact', ->
#
# beforeEach utils.wrap (done) ->
# spyOn(sendwithus.api, 'send')
# @teacher = yield utils.initUser({role: 'teacher'})
# yield utils.loginUser(@teacher)
# done()
#
# describe 'when recipientID is "schools@codecombat.com"', ->
# it 'sends to that email', utils.wrap (done) ->
# [res, body] = yield request.postAsync({url: getURL('/contact'), json: {
# sender: 'some@email.com'
# message: 'A message'
# recipientID: 'schools@codecombat.com'
# }})
# expect(sendwithus.api.send).toHaveBeenCalled()
# user = yield User.findById(@teacher.id)
# yield new Promise((resolve) -> setTimeout(resolve, 10))
# expect(user.get('enrollmentRequestSent')).toBe(true)
# done()
| 58558 | utils = require '../utils'
sendwithus = require '../../../server/sendwithus'
request = require '../request'
User = require '../../../server/models/User'
# TODO: need to update this test since /contact calls external Close.io API now
#xdescribe 'POST /contact', ->
#
# beforeEach utils.wrap (done) ->
# spyOn(sendwithus.api, 'send')
# @teacher = yield utils.initUser({role: 'teacher'})
# yield utils.loginUser(@teacher)
# done()
#
# describe 'when recipientID is "<EMAIL>"', ->
# it 'sends to that email', utils.wrap (done) ->
# [res, body] = yield request.postAsync({url: getURL('/contact'), json: {
# sender: '<EMAIL>'
# message: 'A message'
# recipientID: '<EMAIL>'
# }})
# expect(sendwithus.api.send).toHaveBeenCalled()
# user = yield User.findById(@teacher.id)
# yield new Promise((resolve) -> setTimeout(resolve, 10))
# expect(user.get('enrollmentRequestSent')).toBe(true)
# done()
| true | utils = require '../utils'
sendwithus = require '../../../server/sendwithus'
request = require '../request'
User = require '../../../server/models/User'
# TODO: need to update this test since /contact calls external Close.io API now
#xdescribe 'POST /contact', ->
#
# beforeEach utils.wrap (done) ->
# spyOn(sendwithus.api, 'send')
# @teacher = yield utils.initUser({role: 'teacher'})
# yield utils.loginUser(@teacher)
# done()
#
# describe 'when recipientID is "PI:EMAIL:<EMAIL>END_PI"', ->
# it 'sends to that email', utils.wrap (done) ->
# [res, body] = yield request.postAsync({url: getURL('/contact'), json: {
# sender: 'PI:EMAIL:<EMAIL>END_PI'
# message: 'A message'
# recipientID: 'PI:EMAIL:<EMAIL>END_PI'
# }})
# expect(sendwithus.api.send).toHaveBeenCalled()
# user = yield User.findById(@teacher.id)
# yield new Promise((resolve) -> setTimeout(resolve, 10))
# expect(user.get('enrollmentRequestSent')).toBe(true)
# done()
|
[
{
"context": "ength\n\t\t\tdeepEq {id: 3, sex: 'F', age: 34, name: 'Elaine Benes'}, res[2]\n\n\t\t# TODO\n\t\t# it.only 'date', ->\n\t\t# \tr",
"end": 849,
"score": 0.9998611211776733,
"start": 837,
"tag": "NAME",
"value": "Elaine Benes"
},
{
"context": "son: _ {name: {like: '%Mi%'}}\n\t\t\t\tdeepEq [{name: 'Michael Bolton'}, {name: 'Milton Waddams'}], res\n\n\t\t\tit 'ilike',",
"end": 1481,
"score": 0.9998971223831177,
"start": 1467,
"tag": "NAME",
"value": "Michael Bolton"
},
{
"context": "'}}\n\t\t\t\tdeepEq [{name: 'Michael Bolton'}, {name: 'Milton Waddams'}], res\n\n\t\t\tit 'ilike', ->\n\t\t\t\tres = f Person: _ ",
"end": 1507,
"score": 0.9998812079429626,
"start": 1493,
"tag": "NAME",
"value": "Milton Waddams"
},
{
"context": "on: _ {name: {ilike: '%Mi%'}}\n\t\t\t\tdeepEq [{name: 'Samir Nagheenanajar'},\n\t\t\t\t{name: 'Michael Bolton'}, {name: 'Milton W",
"end": 1620,
"score": 0.9998971819877625,
"start": 1601,
"tag": "NAME",
"value": "Samir Nagheenanajar"
},
{
"context": "eepEq [{name: 'Samir Nagheenanajar'},\n\t\t\t\t{name: 'Michael Bolton'}, {name: 'Milton Waddams'}], res\n\n\t\t\tit 'notlike",
"end": 1650,
"score": 0.9998884797096252,
"start": 1636,
"tag": "NAME",
"value": "Michael Bolton"
},
{
"context": "enanajar'},\n\t\t\t\t{name: 'Michael Bolton'}, {name: 'Milton Waddams'}], res\n\n\t\t\tit 'notlike', ->\n\t\t\t\tres = f Person: ",
"end": 1676,
"score": 0.9998825192451477,
"start": 1662,
"tag": "NAME",
"value": "Milton Waddams"
}
] | src/test__ramda.coffee | Cottin/popsiql | 0 | {F, gt, gte, join, length, lt, lte, pluck, where} = R = require 'ramda' # auto_require: ramda
{$} = RE = require 'ramda-extras' # auto_require: ramda-extras
[ːid, ːtext, ːamount, ːage, ːsex, ːname, ːALL] = ['id', 'text', 'amount', 'age', 'sex', 'name', 'ALL'] #auto_sugar
{eq, deepEq} = require 'testhelp' #auto_require: testhelp
{read} = require './ramda'
model = require './testModel'
seed = require './testSeed'
f = (query) -> read query, seed, model
_ = (...xs) -> xs
describe 'ramda', ->
describe 'read', ->
it 'simple', ->
deepEq [{id: 1, sex: 'M'}], f Person: _ {id: 1, ːsex}
it 'no where', ->
res = f Person: _ {ːid, ːsex, ːage}
eq 18, $ res, length
deepEq {id: 3, sex: 'F', age: 34}, res[2]
it 'ALL', ->
res = f Person: _ {ːALL}
eq 18, $ res, length
deepEq {id: 3, sex: 'F', age: 34, name: 'Elaine Benes'}, res[2]
# TODO
# it.only 'date', ->
# res = f WorkEntry: _ {date: {gt: '1993-03-05', lt: '1993-03-21'}}
# console.log res
# eq 3, $ res, length
# # deepEq {id: 3, sex: 'F', age: 34}, res[2]
describe 'predicates', ->
it 'gt, lt, gte, lte', ->
deepEq [{id: 3, age: 34}], f Person: _ {id: {gt: 2, lt: 8}, age: {lte: 34, gte: 31}}
it 'ne', ->
deepEq [{sex: 'F'}, {sex: 'F'}], f Person: _ {sex: {ne: 'M'}}
it 'in', ->
deepEq [{age: 32}, {age: 32}, {age: 12}], f Person: _ {age: {in: [32, 12]}}
it 'like', ->
res = f Person: _ {name: {like: '%Mi%'}}
deepEq [{name: 'Michael Bolton'}, {name: 'Milton Waddams'}], res
it 'ilike', ->
res = f Person: _ {name: {ilike: '%Mi%'}}
deepEq [{name: 'Samir Nagheenanajar'},
{name: 'Michael Bolton'}, {name: 'Milton Waddams'}], res
it 'notlike', ->
res = f Person: _ {name: {notlike: '%S%'}, ːid}
deepEq [1, 2, 3, 4, 5, 6, 10, 11, 12, 13, 14, 15, 16, 17, 18], pluck 'id', res
it 'notilike', ->
res = f Person: _ {name: {notilike: '%S%'}, ːid}
deepEq [1, 4, 6, 10, 13, 15, 16, 17, 18], pluck 'id', res
it 'deep join', ->
query =
Person: _ {id: {in: [3, 4]}, ːname},
roles: _ {name: 'Guest'},
project: _ {ːid, ːname},
company: _ {ːname}
entries: _ {date: {gt: '1993-02-03'}, ːamount}
res = f query
eq 1, res[0].roles.length
eq 2, res[0].entries.length
eq 'Vandelay Industries', res[1].roles[1].project.company.name
it 'multiple join', ->
query =
adults:
Person: _ {age: {gte: 18}, ːname},
roles: _ {ːname}
entries: _ {ːid, ːtext}
children:
Person: _ {age: {lt: 18}, ːname},
roles: _ {ːname}
entries: _ {ːid, ːtext}
res = f query
eq 14, res.adults.length
eq 4, res.children.length
eq 'Project leader', res.adults[4].roles[1].name
| 50738 | {F, gt, gte, join, length, lt, lte, pluck, where} = R = require 'ramda' # auto_require: ramda
{$} = RE = require 'ramda-extras' # auto_require: ramda-extras
[ːid, ːtext, ːamount, ːage, ːsex, ːname, ːALL] = ['id', 'text', 'amount', 'age', 'sex', 'name', 'ALL'] #auto_sugar
{eq, deepEq} = require 'testhelp' #auto_require: testhelp
{read} = require './ramda'
model = require './testModel'
seed = require './testSeed'
f = (query) -> read query, seed, model
_ = (...xs) -> xs
describe 'ramda', ->
describe 'read', ->
it 'simple', ->
deepEq [{id: 1, sex: 'M'}], f Person: _ {id: 1, ːsex}
it 'no where', ->
res = f Person: _ {ːid, ːsex, ːage}
eq 18, $ res, length
deepEq {id: 3, sex: 'F', age: 34}, res[2]
it 'ALL', ->
res = f Person: _ {ːALL}
eq 18, $ res, length
deepEq {id: 3, sex: 'F', age: 34, name: '<NAME>'}, res[2]
# TODO
# it.only 'date', ->
# res = f WorkEntry: _ {date: {gt: '1993-03-05', lt: '1993-03-21'}}
# console.log res
# eq 3, $ res, length
# # deepEq {id: 3, sex: 'F', age: 34}, res[2]
describe 'predicates', ->
it 'gt, lt, gte, lte', ->
deepEq [{id: 3, age: 34}], f Person: _ {id: {gt: 2, lt: 8}, age: {lte: 34, gte: 31}}
it 'ne', ->
deepEq [{sex: 'F'}, {sex: 'F'}], f Person: _ {sex: {ne: 'M'}}
it 'in', ->
deepEq [{age: 32}, {age: 32}, {age: 12}], f Person: _ {age: {in: [32, 12]}}
it 'like', ->
res = f Person: _ {name: {like: '%Mi%'}}
deepEq [{name: '<NAME>'}, {name: '<NAME>'}], res
it 'ilike', ->
res = f Person: _ {name: {ilike: '%Mi%'}}
deepEq [{name: '<NAME>'},
{name: '<NAME>'}, {name: '<NAME>'}], res
it 'notlike', ->
res = f Person: _ {name: {notlike: '%S%'}, ːid}
deepEq [1, 2, 3, 4, 5, 6, 10, 11, 12, 13, 14, 15, 16, 17, 18], pluck 'id', res
it 'notilike', ->
res = f Person: _ {name: {notilike: '%S%'}, ːid}
deepEq [1, 4, 6, 10, 13, 15, 16, 17, 18], pluck 'id', res
it 'deep join', ->
query =
Person: _ {id: {in: [3, 4]}, ːname},
roles: _ {name: 'Guest'},
project: _ {ːid, ːname},
company: _ {ːname}
entries: _ {date: {gt: '1993-02-03'}, ːamount}
res = f query
eq 1, res[0].roles.length
eq 2, res[0].entries.length
eq 'Vandelay Industries', res[1].roles[1].project.company.name
it 'multiple join', ->
query =
adults:
Person: _ {age: {gte: 18}, ːname},
roles: _ {ːname}
entries: _ {ːid, ːtext}
children:
Person: _ {age: {lt: 18}, ːname},
roles: _ {ːname}
entries: _ {ːid, ːtext}
res = f query
eq 14, res.adults.length
eq 4, res.children.length
eq 'Project leader', res.adults[4].roles[1].name
| true | {F, gt, gte, join, length, lt, lte, pluck, where} = R = require 'ramda' # auto_require: ramda
{$} = RE = require 'ramda-extras' # auto_require: ramda-extras
[ːid, ːtext, ːamount, ːage, ːsex, ːname, ːALL] = ['id', 'text', 'amount', 'age', 'sex', 'name', 'ALL'] #auto_sugar
{eq, deepEq} = require 'testhelp' #auto_require: testhelp
{read} = require './ramda'
model = require './testModel'
seed = require './testSeed'
f = (query) -> read query, seed, model
_ = (...xs) -> xs
describe 'ramda', ->
describe 'read', ->
it 'simple', ->
deepEq [{id: 1, sex: 'M'}], f Person: _ {id: 1, ːsex}
it 'no where', ->
res = f Person: _ {ːid, ːsex, ːage}
eq 18, $ res, length
deepEq {id: 3, sex: 'F', age: 34}, res[2]
it 'ALL', ->
res = f Person: _ {ːALL}
eq 18, $ res, length
deepEq {id: 3, sex: 'F', age: 34, name: 'PI:NAME:<NAME>END_PI'}, res[2]
# TODO
# it.only 'date', ->
# res = f WorkEntry: _ {date: {gt: '1993-03-05', lt: '1993-03-21'}}
# console.log res
# eq 3, $ res, length
# # deepEq {id: 3, sex: 'F', age: 34}, res[2]
describe 'predicates', ->
it 'gt, lt, gte, lte', ->
deepEq [{id: 3, age: 34}], f Person: _ {id: {gt: 2, lt: 8}, age: {lte: 34, gte: 31}}
it 'ne', ->
deepEq [{sex: 'F'}, {sex: 'F'}], f Person: _ {sex: {ne: 'M'}}
it 'in', ->
deepEq [{age: 32}, {age: 32}, {age: 12}], f Person: _ {age: {in: [32, 12]}}
it 'like', ->
res = f Person: _ {name: {like: '%Mi%'}}
deepEq [{name: 'PI:NAME:<NAME>END_PI'}, {name: 'PI:NAME:<NAME>END_PI'}], res
it 'ilike', ->
res = f Person: _ {name: {ilike: '%Mi%'}}
deepEq [{name: 'PI:NAME:<NAME>END_PI'},
{name: 'PI:NAME:<NAME>END_PI'}, {name: 'PI:NAME:<NAME>END_PI'}], res
it 'notlike', ->
res = f Person: _ {name: {notlike: '%S%'}, ːid}
deepEq [1, 2, 3, 4, 5, 6, 10, 11, 12, 13, 14, 15, 16, 17, 18], pluck 'id', res
it 'notilike', ->
res = f Person: _ {name: {notilike: '%S%'}, ːid}
deepEq [1, 4, 6, 10, 13, 15, 16, 17, 18], pluck 'id', res
it 'deep join', ->
query =
Person: _ {id: {in: [3, 4]}, ːname},
roles: _ {name: 'Guest'},
project: _ {ːid, ːname},
company: _ {ːname}
entries: _ {date: {gt: '1993-02-03'}, ːamount}
res = f query
eq 1, res[0].roles.length
eq 2, res[0].entries.length
eq 'Vandelay Industries', res[1].roles[1].project.company.name
it 'multiple join', ->
query =
adults:
Person: _ {age: {gte: 18}, ːname},
roles: _ {ːname}
entries: _ {ːid, ːtext}
children:
Person: _ {age: {lt: 18}, ːname},
roles: _ {ːname}
entries: _ {ːid, ːtext}
res = f query
eq 14, res.adults.length
eq 4, res.children.length
eq 'Project leader', res.adults[4].roles[1].name
|
[
{
"context": "#\n knockback.js 0.19.1\n Copyright (c) 2011-2014 Kevin Malakoff.\n License: MIT (http://www.opensource.org/licens",
"end": 67,
"score": 0.9997554421424866,
"start": 53,
"tag": "NAME",
"value": "Kevin Malakoff"
},
{
"context": "ses/mit-license.php)\n Source: https://github.com/kmalakoff/knockback\n Dependencies: Knockout.js, Backbone.j",
"end": 175,
"score": 0.9929566383361816,
"start": 166,
"tag": "USERNAME",
"value": "kmalakoff"
},
{
"context": "rn trigger_count++\n# });\n# emitter.set(name: 'bob'); # trigger_count: 1\n# emitter.set(name:",
"end": 1001,
"score": 0.9992539286613464,
"start": 998,
"tag": "NAME",
"value": "bob"
},
{
"context": "; # trigger_count: 1\n# emitter.set(name: 'george'); # trigger_count: 2\n# emitter.set(last: 's",
"end": 1059,
"score": 0.9828139543533325,
"start": 1053,
"tag": "NAME",
"value": "george"
},
{
"context": "e'); # trigger_count: 2\n# emitter.set(last: 'smith'); # trigger_count: 3\nmodule.exports = class ",
"end": 1113,
"score": 0.9994263648986816,
"start": 1108,
"tag": "NAME",
"value": "smith"
}
] | src/triggering/triggered-observable.coffee | metacommunications/knockback | 0 | ###
knockback.js 0.19.1
Copyright (c) 2011-2014 Kevin Malakoff.
License: MIT (http://www.opensource.org/licenses/mit-license.php)
Source: https://github.com/kmalakoff/knockback
Dependencies: Knockout.js, Backbone.js, and Underscore.js (or LoDash.js).
Optional dependencies: Backbone.ModelRef.js and BackboneORM.
###
{_, ko} = kb = require '../core/kb'
KEYS_PUBLISH = ['destroy']
# Class for observing emitter events.
#
# @example create an observable whose subscriptions are notified with the change event is triggered.
# var triggered_observable = kb.triggeredObservable(name, 'change');
#
# @example How to watch a emitter for events.
# var trigger_count = 0;
# var emitter = new Backbone.Model();
# var view_emitter = {
# triggered_observable: kb.triggeredObservable(emitter, 'change')
# };
# view_emitter.counter = ko.computed(function() {
# view_emitter.triggered_observable() // add a dependency
# return trigger_count++
# });
# emitter.set(name: 'bob'); # trigger_count: 1
# emitter.set(name: 'george'); # trigger_count: 2
# emitter.set(last: 'smith'); # trigger_count: 3
module.exports = class kb.TriggeredObservable
# Used to create a new kb.Observable.
#
# @param [Model] emitter the emitter to observe (can be null)
# @param [String] event_selector the event name to trigger Knockout subscriptions on.
# @return [ko.observable] the constructor does not return 'this' but a ko.observable
# @note the constructor does not return 'this' but a ko.observable
constructor: (emitter, @event_selector) ->
emitter or kb._throwMissing(this, 'emitter')
@event_selector or kb._throwMissing(this, 'event_selector')
# internal state
@vo = ko.observable()
observable = kb.utils.wrappedObservable(@, ko.computed(=> @vo()))
# publish public interface on the observable and return instead of this
kb.publishMethods(observable, @, KEYS_PUBLISH)
# create emitter observable
kb.utils.wrappedEventWatcher(@, new kb.EventWatcher(emitter, @, {emitter: _.bind(@emitter, @), update: _.bind(@update, @), event_selector: @event_selector}))
return observable
# Required clean up function to break cycles, release view models, etc.
# Can be called directly, via kb.release(object) or as a consequence of ko.releaseNode(element).
destroy: -> kb.utils.wrappedDestroy(@)
# Dual-purpose getter/setter for the observed emitter.
#
# @overload emitter()
# Gets the emitter or emitter reference
# @return [Model|ModelRef|Collection] the emitter whose events are being bound (can be null)
# @overload emitter(new_emitter)
# Sets the emitter or emitter reference
# @param [Model|ModelRef|Collection] new_emitter the emitter whose events will be bound (can be null)
emitter: (new_emitter) ->
# get or no change
return @ee if (arguments.length == 0) or (@ee is new_emitter)
@update() if (@ee = new_emitter)
####################################################
# Internal
####################################################
# @private
update: ->
return unless @ee # do not trigger if there is no emitter
if @vo() isnt @ee then @vo(@ee) else @vo.valueHasMutated() # manually trigger the dependable
# factory function
kb.triggeredObservable = (emitter, event_selector) -> return new kb.TriggeredObservable(emitter, event_selector) | 46281 | ###
knockback.js 0.19.1
Copyright (c) 2011-2014 <NAME>.
License: MIT (http://www.opensource.org/licenses/mit-license.php)
Source: https://github.com/kmalakoff/knockback
Dependencies: Knockout.js, Backbone.js, and Underscore.js (or LoDash.js).
Optional dependencies: Backbone.ModelRef.js and BackboneORM.
###
{_, ko} = kb = require '../core/kb'
KEYS_PUBLISH = ['destroy']
# Class for observing emitter events.
#
# @example create an observable whose subscriptions are notified with the change event is triggered.
# var triggered_observable = kb.triggeredObservable(name, 'change');
#
# @example How to watch a emitter for events.
# var trigger_count = 0;
# var emitter = new Backbone.Model();
# var view_emitter = {
# triggered_observable: kb.triggeredObservable(emitter, 'change')
# };
# view_emitter.counter = ko.computed(function() {
# view_emitter.triggered_observable() // add a dependency
# return trigger_count++
# });
# emitter.set(name: '<NAME>'); # trigger_count: 1
# emitter.set(name: '<NAME>'); # trigger_count: 2
# emitter.set(last: '<NAME>'); # trigger_count: 3
module.exports = class kb.TriggeredObservable
# Used to create a new kb.Observable.
#
# @param [Model] emitter the emitter to observe (can be null)
# @param [String] event_selector the event name to trigger Knockout subscriptions on.
# @return [ko.observable] the constructor does not return 'this' but a ko.observable
# @note the constructor does not return 'this' but a ko.observable
constructor: (emitter, @event_selector) ->
emitter or kb._throwMissing(this, 'emitter')
@event_selector or kb._throwMissing(this, 'event_selector')
# internal state
@vo = ko.observable()
observable = kb.utils.wrappedObservable(@, ko.computed(=> @vo()))
# publish public interface on the observable and return instead of this
kb.publishMethods(observable, @, KEYS_PUBLISH)
# create emitter observable
kb.utils.wrappedEventWatcher(@, new kb.EventWatcher(emitter, @, {emitter: _.bind(@emitter, @), update: _.bind(@update, @), event_selector: @event_selector}))
return observable
# Required clean up function to break cycles, release view models, etc.
# Can be called directly, via kb.release(object) or as a consequence of ko.releaseNode(element).
destroy: -> kb.utils.wrappedDestroy(@)
# Dual-purpose getter/setter for the observed emitter.
#
# @overload emitter()
# Gets the emitter or emitter reference
# @return [Model|ModelRef|Collection] the emitter whose events are being bound (can be null)
# @overload emitter(new_emitter)
# Sets the emitter or emitter reference
# @param [Model|ModelRef|Collection] new_emitter the emitter whose events will be bound (can be null)
emitter: (new_emitter) ->
# get or no change
return @ee if (arguments.length == 0) or (@ee is new_emitter)
@update() if (@ee = new_emitter)
####################################################
# Internal
####################################################
# @private
update: ->
return unless @ee # do not trigger if there is no emitter
if @vo() isnt @ee then @vo(@ee) else @vo.valueHasMutated() # manually trigger the dependable
# factory function
kb.triggeredObservable = (emitter, event_selector) -> return new kb.TriggeredObservable(emitter, event_selector) | true | ###
knockback.js 0.19.1
Copyright (c) 2011-2014 PI:NAME:<NAME>END_PI.
License: MIT (http://www.opensource.org/licenses/mit-license.php)
Source: https://github.com/kmalakoff/knockback
Dependencies: Knockout.js, Backbone.js, and Underscore.js (or LoDash.js).
Optional dependencies: Backbone.ModelRef.js and BackboneORM.
###
{_, ko} = kb = require '../core/kb'
KEYS_PUBLISH = ['destroy']
# Class for observing emitter events.
#
# @example create an observable whose subscriptions are notified with the change event is triggered.
# var triggered_observable = kb.triggeredObservable(name, 'change');
#
# @example How to watch a emitter for events.
# var trigger_count = 0;
# var emitter = new Backbone.Model();
# var view_emitter = {
# triggered_observable: kb.triggeredObservable(emitter, 'change')
# };
# view_emitter.counter = ko.computed(function() {
# view_emitter.triggered_observable() // add a dependency
# return trigger_count++
# });
# emitter.set(name: 'PI:NAME:<NAME>END_PI'); # trigger_count: 1
# emitter.set(name: 'PI:NAME:<NAME>END_PI'); # trigger_count: 2
# emitter.set(last: 'PI:NAME:<NAME>END_PI'); # trigger_count: 3
module.exports = class kb.TriggeredObservable
# Used to create a new kb.Observable.
#
# @param [Model] emitter the emitter to observe (can be null)
# @param [String] event_selector the event name to trigger Knockout subscriptions on.
# @return [ko.observable] the constructor does not return 'this' but a ko.observable
# @note the constructor does not return 'this' but a ko.observable
constructor: (emitter, @event_selector) ->
emitter or kb._throwMissing(this, 'emitter')
@event_selector or kb._throwMissing(this, 'event_selector')
# internal state
@vo = ko.observable()
observable = kb.utils.wrappedObservable(@, ko.computed(=> @vo()))
# publish public interface on the observable and return instead of this
kb.publishMethods(observable, @, KEYS_PUBLISH)
# create emitter observable
kb.utils.wrappedEventWatcher(@, new kb.EventWatcher(emitter, @, {emitter: _.bind(@emitter, @), update: _.bind(@update, @), event_selector: @event_selector}))
return observable
# Required clean up function to break cycles, release view models, etc.
# Can be called directly, via kb.release(object) or as a consequence of ko.releaseNode(element).
destroy: -> kb.utils.wrappedDestroy(@)
# Dual-purpose getter/setter for the observed emitter.
#
# @overload emitter()
# Gets the emitter or emitter reference
# @return [Model|ModelRef|Collection] the emitter whose events are being bound (can be null)
# @overload emitter(new_emitter)
# Sets the emitter or emitter reference
# @param [Model|ModelRef|Collection] new_emitter the emitter whose events will be bound (can be null)
emitter: (new_emitter) ->
# get or no change
return @ee if (arguments.length == 0) or (@ee is new_emitter)
@update() if (@ee = new_emitter)
####################################################
# Internal
####################################################
# @private
update: ->
return unless @ee # do not trigger if there is no emitter
if @vo() isnt @ee then @vo(@ee) else @vo.valueHasMutated() # manually trigger the dependable
# factory function
kb.triggeredObservable = (emitter, event_selector) -> return new kb.TriggeredObservable(emitter, event_selector) |
[
{
"context": "put#user_email'\n username: '.js-form input#user_username'\n password: '.js-form input#user_password'\n ",
"end": 357,
"score": 0.77559494972229,
"start": 349,
"tag": "USERNAME",
"value": "username"
},
{
"context": "name: '.js-form input#user_username'\n password: '.js-form input#user_password'\n password_confirmation: '.js-fo",
"end": 388,
"score": 0.8451117277145386,
"start": 373,
"tag": "PASSWORD",
"value": "'.js-form input"
},
{
"context": "user_username'\n password: '.js-form input#user_password'\n password_confirmation: '.js-form input#user_",
"end": 402,
"score": 0.5600019693374634,
"start": 394,
"tag": "PASSWORD",
"value": "password"
},
{
"context": ":\n email: @ui.email.val()\n username: @ui.username.val()\n password: @ui.password.val()\n ",
"end": 974,
"score": 0.7905865907669067,
"start": 962,
"tag": "USERNAME",
"value": "@ui.username"
},
{
"context": " username: @ui.username.val()\n password: @ui.password.val()\n password_confirmation: @ui.password_con",
"end": 1015,
"score": 0.8963682651519775,
"start": 999,
"tag": "PASSWORD",
"value": "@ui.password.val"
},
{
"context": " @ui.password.val()\n password_confirmation: @ui.password_confirmation.val()\n terms_and_conditions: if @ui.terms_",
"end": 1074,
"score": 0.787919282913208,
"start": 1049,
"tag": "PASSWORD",
"value": "@ui.password_confirmation"
},
{
"context": " password_confirmation: @ui.password_confirmation.val()\n terms_and_conditions: if @ui.terms_and_",
"end": 1078,
"score": 0.6354895234107971,
"start": 1075,
"tag": "PASSWORD",
"value": "val"
}
] | app/assets/javascripts/views/authentication/signup.coffee | brettclanton001/Dashous | 4 | class Dashous.Views.Authentication.Signup extends Dashous.Views.Authentication.Base
template: 'authentication/signup'
ui:
form: '.js-form'
inputs: '.js-form input'
submitButton: '.js-form input[type="submit"]'
errorMessages: '.js-form .js-error-message'
email: '.js-form input#user_email'
username: '.js-form input#user_username'
password: '.js-form input#user_password'
password_confirmation: '.js-form input#user_password_confirmation'
terms_and_conditions: '.js-form input#user_terms_and_conditions'
successMessage: '.js-success'
initialize: ->
@registration = new Backbone.Model
@registration.url = '/api/v1/authentication/registrations'
##################################################################
submitForm: (e) ->
e.preventDefault()
@disableSubmit()
@registration.save
authenticity_token: Dashous.formToken
user:
email: @ui.email.val()
username: @ui.username.val()
password: @ui.password.val()
password_confirmation: @ui.password_confirmation.val()
terms_and_conditions: if @ui.terms_and_conditions.is(':checked') then '1' else '0'
.fail (data) =>
@handleFailure(data)
.success =>
@handleSuccess()
handleSuccess: ->
@ui.form.hide()
@ui.successMessage.show()
handleFailure: (data) ->
@ui.errorMessages.text ''
@ui.inputs.removeClass 'error'
$.each data.responseJSON, (field, message) =>
@ui[field].addClass 'error'
@ui.form.find(".field[data-field-for='#{field}'] .js-error-message").text message[0]
@enableSubmit()
| 34765 | class Dashous.Views.Authentication.Signup extends Dashous.Views.Authentication.Base
template: 'authentication/signup'
ui:
form: '.js-form'
inputs: '.js-form input'
submitButton: '.js-form input[type="submit"]'
errorMessages: '.js-form .js-error-message'
email: '.js-form input#user_email'
username: '.js-form input#user_username'
password: <PASSWORD>#user_<PASSWORD>'
password_confirmation: '.js-form input#user_password_confirmation'
terms_and_conditions: '.js-form input#user_terms_and_conditions'
successMessage: '.js-success'
initialize: ->
@registration = new Backbone.Model
@registration.url = '/api/v1/authentication/registrations'
##################################################################
submitForm: (e) ->
e.preventDefault()
@disableSubmit()
@registration.save
authenticity_token: Dashous.formToken
user:
email: @ui.email.val()
username: @ui.username.val()
password: <PASSWORD>()
password_confirmation: <PASSWORD>.<PASSWORD>()
terms_and_conditions: if @ui.terms_and_conditions.is(':checked') then '1' else '0'
.fail (data) =>
@handleFailure(data)
.success =>
@handleSuccess()
handleSuccess: ->
@ui.form.hide()
@ui.successMessage.show()
handleFailure: (data) ->
@ui.errorMessages.text ''
@ui.inputs.removeClass 'error'
$.each data.responseJSON, (field, message) =>
@ui[field].addClass 'error'
@ui.form.find(".field[data-field-for='#{field}'] .js-error-message").text message[0]
@enableSubmit()
| true | class Dashous.Views.Authentication.Signup extends Dashous.Views.Authentication.Base
template: 'authentication/signup'
ui:
form: '.js-form'
inputs: '.js-form input'
submitButton: '.js-form input[type="submit"]'
errorMessages: '.js-form .js-error-message'
email: '.js-form input#user_email'
username: '.js-form input#user_username'
password: PI:PASSWORD:<PASSWORD>END_PI#user_PI:PASSWORD:<PASSWORD>END_PI'
password_confirmation: '.js-form input#user_password_confirmation'
terms_and_conditions: '.js-form input#user_terms_and_conditions'
successMessage: '.js-success'
initialize: ->
@registration = new Backbone.Model
@registration.url = '/api/v1/authentication/registrations'
##################################################################
submitForm: (e) ->
e.preventDefault()
@disableSubmit()
@registration.save
authenticity_token: Dashous.formToken
user:
email: @ui.email.val()
username: @ui.username.val()
password: PI:PASSWORD:<PASSWORD>END_PI()
password_confirmation: PI:PASSWORD:<PASSWORD>END_PI.PI:PASSWORD:<PASSWORD>END_PI()
terms_and_conditions: if @ui.terms_and_conditions.is(':checked') then '1' else '0'
.fail (data) =>
@handleFailure(data)
.success =>
@handleSuccess()
handleSuccess: ->
@ui.form.hide()
@ui.successMessage.show()
handleFailure: (data) ->
@ui.errorMessages.text ''
@ui.inputs.removeClass 'error'
$.each data.responseJSON, (field, message) =>
@ui[field].addClass 'error'
@ui.form.find(".field[data-field-for='#{field}'] .js-error-message").text message[0]
@enableSubmit()
|
[
{
"context": "disallow unnecessary curly braces in JSX\n# @author Jacky Ho\n###\n'use strict'\n\n# For better readability on tes",
"end": 104,
"score": 0.999799907207489,
"start": 96,
"tag": "NAME",
"value": "Jacky Ho"
}
] | src/tests/rules/jsx-curly-brace-presence.coffee | helixbass/eslint-plugin-coffee | 21 | ###*
# @fileoverview Enforce curly braces or disallow unnecessary curly braces in JSX
# @author Jacky Ho
###
'use strict'
# For better readability on tests involving quotes
### eslint-disable quotes ###
### eslint-disable coffee/no-template-curly-in-string ###
# ------------------------------------------------------------------------------
# Requirements
# ------------------------------------------------------------------------------
rule = require 'eslint-plugin-react/lib/rules/jsx-curly-brace-presence'
{RuleTester} = require 'eslint'
path = require 'path'
missingCurlyMessage = 'Need to wrap this literal in a JSX expression.'
unnecessaryCurlyMessage = 'Curly braces are unnecessary here.'
# ------------------------------------------------------------------------------
# Tests
# ------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'jsx-curly-brace-presence', rule,
valid: [
code: '<App {...props}>foo</App>'
,
code: '<>foo</>'
,
# parser: 'babel-eslint'
code: '<App {...props}>foo</App>'
options: [props: 'never']
,
###
# There is no way to inject the space into JSX without an expression container
# so this format should always be allowed regardless of the `children` option.
###
code: "<App>{' '}</App>"
,
code: "<App>{' '}</App>"
,
code: "<App>{' '}</App>"
options: [children: 'never']
,
code: "<App>{' '}</App>"
options: [children: 'never']
,
code: "<App>{' '}</App>"
options: [children: 'always']
,
code: "<App>{' '}</App>"
options: [children: 'always']
,
code: '<App {...props}>foo</App>'
options: [props: 'always']
,
code: '<App>{"Hello #{word} World"}</App>'
options: [children: 'never']
,
code: '<App>{"Hello \\n World"}</App>'
options: [children: 'never']
,
code: '<App>{"Hello #{word} World"}{"foo"}</App>'
options: [children: 'never']
,
code: '<App prop={"foo #{word} bar"}>foo</App>'
options: [props: 'never']
,
code: '<App prop={"foo #{word} bar"} />'
options: [props: 'never']
,
code: '<App>{<myApp></myApp>}</App>'
options: [children: 'always']
,
code: '<App>{[]}</App>'
,
code: '<App>foo</App>'
,
code: '<App>{"foo"}{<Component>bar</Component>}</App>'
,
code: "<App prop='bar'>foo</App>"
,
code: '<App prop={true}>foo</App>'
,
code: '<App prop>foo</App>'
,
code: "<App prop='bar'>{'foo \\n bar'}</App>"
,
code: "<MyComponent prop='bar'>foo</MyComponent>"
options: [props: 'never']
,
code: '<MyComponent prop="bar">foo</MyComponent>'
options: [props: 'never']
,
code: '<MyComponent>foo</MyComponent>'
options: [children: 'never']
,
code: '<MyComponent>{<App/>}{"123"}</MyComponent>'
options: [children: 'never']
,
code: '<App>{"foo \'bar\' \\"foo\\" bar"}</App>'
options: [children: 'never']
,
code: "<MyComponent prop={'bar'}>foo</MyComponent>"
options: [props: 'always']
,
code: "<MyComponent>{'foo'}</MyComponent>"
options: [children: 'always']
,
code: '<MyComponent prop={"bar"}>foo</MyComponent>'
options: [props: 'always']
,
code: '<MyComponent>{"foo"}</MyComponent>'
options: [children: 'always']
,
code: "<MyComponent>{'foo'}</MyComponent>"
options: [children: 'ignore']
,
code: "<MyComponent prop={'bar'}>foo</MyComponent>"
options: [props: 'ignore']
,
code: '<MyComponent>foo</MyComponent>'
options: [children: 'ignore']
,
code: "<MyComponent prop='bar'>foo</MyComponent>"
options: [props: 'ignore']
,
code: '<MyComponent prop="bar">foo</MyComponent>'
options: [props: 'ignore']
,
code: "<MyComponent prop='bar'>{'foo'}</MyComponent>"
options: [children: 'always', props: 'never']
,
code: "<MyComponent prop={'bar'}>foo</MyComponent>"
options: [children: 'never', props: 'always']
,
code: "<MyComponent prop={'bar'}>{'foo'}</MyComponent>"
options: ['always']
,
code: '<MyComponent prop={"bar"}>{"foo"}</MyComponent>'
options: ['always']
,
code: '<MyComponent prop={"bar"} attr={\'foo\'} />'
options: ['always']
,
code: '<MyComponent prop="bar" attr=\'foo\' />'
options: ['never']
,
code: "<MyComponent prop='bar'>foo</MyComponent>"
options: ['never']
,
code: '<MyComponent prop={"bar #{word} foo"}>{"foo #{word}"}</MyComponent>'
options: ['never']
,
code: '<MyComponent>{"div { margin-top: 0; }"}</MyComponent>'
options: ['never']
,
code: '<MyComponent>{"<Foo />"}</MyComponent>'
options: ['never']
,
code: '<MyComponent prop={"Hello \\u1026 world"}>bar</MyComponent>'
options: ['never']
,
code: '<MyComponent>{"Hello \\u1026 world"}</MyComponent>'
options: ['never']
,
code: '<MyComponent prop={"Hello · world"}>bar</MyComponent>'
options: ['never']
,
code: '<MyComponent>{"Hello · world"}</MyComponent>'
options: ['never']
,
code: '<MyComponent>{"Hello \\n world"}</MyComponent>'
options: ['never']
,
code: ['<a a={"start\\', '\\', 'end"}/>'].join '/n'
options: ['never']
]
invalid: [
code: '<App prop={"foo"} />'
output: '<App prop="foo" />'
options: [props: 'never']
errors: [message: unnecessaryCurlyMessage]
,
code: '<App>{<myApp></myApp>}</App>'
output: '<App><myApp></myApp></App>'
options: [children: 'never']
errors: [message: unnecessaryCurlyMessage]
,
code: '<App>{<myApp></myApp>}</App>'
output: '<App><myApp></myApp></App>'
errors: [message: unnecessaryCurlyMessage]
,
code: "<App prop={'foo'}>foo</App>"
output: '<App prop="foo">foo</App>'
options: [props: 'never']
errors: [message: unnecessaryCurlyMessage]
,
code: '<App>{"foo"}</App>'
output: '<App>foo</App>'
options: [children: 'never']
errors: [message: unnecessaryCurlyMessage]
,
# TODO: uncomment once fragment transformation works
# ,
# code: '<>{"foo"}</>'
# output: '<>foo</>'
# # parser: 'babel-eslint'
# options: [children: 'never']
# errors: [message: unnecessaryCurlyMessage]
code: "<MyComponent>{'foo'}</MyComponent>"
output: '<MyComponent>foo</MyComponent>'
errors: [message: unnecessaryCurlyMessage]
,
code: "<MyComponent prop={'bar'}>foo</MyComponent>"
output: '<MyComponent prop="bar">foo</MyComponent>'
errors: [message: unnecessaryCurlyMessage]
,
code: "<MyComponent>{'foo'}</MyComponent>"
output: '<MyComponent>foo</MyComponent>'
options: [children: 'never']
errors: [message: unnecessaryCurlyMessage]
,
code: "<MyComponent prop={'bar'}>foo</MyComponent>"
output: '<MyComponent prop="bar">foo</MyComponent>'
options: [props: 'never']
errors: [message: unnecessaryCurlyMessage]
,
code: "<MyComponent prop='bar'>foo</MyComponent>"
output: '<MyComponent prop={"bar"}>foo</MyComponent>'
options: [props: 'always']
errors: [message: missingCurlyMessage]
,
code: '<MyComponent prop="foo \'bar\'">foo</MyComponent>'
output: '<MyComponent prop={"foo \'bar\'"}>foo</MyComponent>'
options: [props: 'always']
errors: [message: missingCurlyMessage]
,
code: '<MyComponent prop=\'foo "bar"\'>foo</MyComponent>'
output: '<MyComponent prop={"foo \\"bar\\""}>foo</MyComponent>'
options: [props: 'always']
errors: [message: missingCurlyMessage]
,
code: '<MyComponent prop="foo \'bar\'">foo</MyComponent>'
output: '<MyComponent prop={"foo \'bar\'"}>foo</MyComponent>'
options: [props: 'always']
errors: [message: missingCurlyMessage]
,
code: '<MyComponent>foo bar </MyComponent>'
output: '<MyComponent>{"foo bar "}</MyComponent>'
options: [children: 'always']
errors: [message: missingCurlyMessage]
,
code: '<MyComponent prop="foo \'bar\' \\n ">foo</MyComponent>'
output: '<MyComponent prop={"foo \'bar\' \\\\n "}>foo</MyComponent>'
options: [props: 'always']
errors: [message: missingCurlyMessage]
,
code: '<MyComponent>foo bar \\r </MyComponent>'
output: '<MyComponent>{"foo bar \\\\r "}</MyComponent>'
options: [children: 'always']
errors: [message: missingCurlyMessage]
,
code: "<MyComponent>foo bar 'foo'</MyComponent>"
output: '<MyComponent>{"foo bar \'foo\'"}</MyComponent>'
options: [children: 'always']
errors: [message: missingCurlyMessage]
,
code: '<MyComponent>foo bar "foo"</MyComponent>'
output: '<MyComponent>{"foo bar \\"foo\\""}</MyComponent>'
options: [children: 'always']
errors: [message: missingCurlyMessage]
,
code: '<MyComponent>foo bar <App/></MyComponent>'
output: '<MyComponent>{"foo bar "}<App/></MyComponent>'
options: [children: 'always']
errors: [message: missingCurlyMessage]
,
code: '<MyComponent>foo \\n bar</MyComponent>'
output: '<MyComponent>{"foo \\\\n bar"}</MyComponent>'
options: [children: 'always']
errors: [message: missingCurlyMessage]
,
code: '<MyComponent>foo \\u1234 bar</MyComponent>'
output: '<MyComponent>{"foo \\\\u1234 bar"}</MyComponent>'
options: [children: 'always']
errors: [message: missingCurlyMessage]
,
code: "<MyComponent prop='foo \\u1234 bar' />"
output: '<MyComponent prop={"foo \\\\u1234 bar"} />'
options: [props: 'always']
errors: [message: missingCurlyMessage]
,
code: "<MyComponent prop={'bar'}>{'foo'}</MyComponent>"
output: '<MyComponent prop="bar">foo</MyComponent>'
options: ['never']
errors: [
message: unnecessaryCurlyMessage
,
message: unnecessaryCurlyMessage
]
,
code: "<MyComponent prop='bar'>foo</MyComponent>"
output: '<MyComponent prop={"bar"}>{"foo"}</MyComponent>'
options: ['always']
errors: [{message: missingCurlyMessage}, {message: missingCurlyMessage}]
,
code: '<App prop={\'foo\'} attr={" foo "} />'
output: '<App prop="foo" attr=" foo " />'
errors: [
message: unnecessaryCurlyMessage
,
message: unnecessaryCurlyMessage
]
options: [props: 'never']
,
code: '<App prop=\'foo\' attr="bar" />'
output: '<App prop={"foo"} attr={"bar"} />'
errors: [{message: missingCurlyMessage}, {message: missingCurlyMessage}]
options: [props: 'always']
,
code: '<App prop=\'foo\' attr={"bar"} />'
output: '<App prop={"foo"} attr={"bar"} />'
errors: [message: missingCurlyMessage]
options: [props: 'always']
,
code: "<App prop={'foo'} attr='bar' />"
output: '<App prop={\'foo\'} attr={"bar"} />'
errors: [message: missingCurlyMessage]
options: [props: 'always']
,
code: "<App prop='foo · bar' />"
errors: [message: missingCurlyMessage]
options: [props: 'always']
,
code: '<App>foo · bar</App>'
errors: [message: missingCurlyMessage]
options: [children: 'always']
,
code: '<App>{\'foo "bar"\'}</App>'
output: '<App>foo "bar"</App>'
errors: [message: unnecessaryCurlyMessage]
options: [children: 'never']
,
code: '<App>{"foo \'bar\'"}</App>'
output: "<App>foo 'bar'</App>"
errors: [message: unnecessaryCurlyMessage]
options: [children: 'never']
,
code: [
'<App prop=" '
' a '
' b c'
' d'
'">'
' a'
' b c '
' d '
'</App>'
].join '\n'
errors: [{message: missingCurlyMessage}, {message: missingCurlyMessage}]
options: ['always']
,
code: [
"<App prop=' "
' a '
' b c'
' d'
"'>"
' a'
' b c '
' d '
'</App>'
].join '\n'
errors: [{message: missingCurlyMessage}, {message: missingCurlyMessage}]
options: ['always']
,
code: '<MyComponent prop={"{ style: true }"}>bar</MyComponent>'
output: '<MyComponent prop="{ style: true }">bar</MyComponent>'
errors: [message: unnecessaryCurlyMessage]
options: ['never']
,
code: '<MyComponent prop={"< style: true >"}>foo</MyComponent>'
output: '<MyComponent prop="< style: true >">foo</MyComponent>'
errors: [message: unnecessaryCurlyMessage]
options: ['never']
]
| 208015 | ###*
# @fileoverview Enforce curly braces or disallow unnecessary curly braces in JSX
# @author <NAME>
###
'use strict'
# For better readability on tests involving quotes
### eslint-disable quotes ###
### eslint-disable coffee/no-template-curly-in-string ###
# ------------------------------------------------------------------------------
# Requirements
# ------------------------------------------------------------------------------
rule = require 'eslint-plugin-react/lib/rules/jsx-curly-brace-presence'
{RuleTester} = require 'eslint'
path = require 'path'
missingCurlyMessage = 'Need to wrap this literal in a JSX expression.'
unnecessaryCurlyMessage = 'Curly braces are unnecessary here.'
# ------------------------------------------------------------------------------
# Tests
# ------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'jsx-curly-brace-presence', rule,
valid: [
code: '<App {...props}>foo</App>'
,
code: '<>foo</>'
,
# parser: 'babel-eslint'
code: '<App {...props}>foo</App>'
options: [props: 'never']
,
###
# There is no way to inject the space into JSX without an expression container
# so this format should always be allowed regardless of the `children` option.
###
code: "<App>{' '}</App>"
,
code: "<App>{' '}</App>"
,
code: "<App>{' '}</App>"
options: [children: 'never']
,
code: "<App>{' '}</App>"
options: [children: 'never']
,
code: "<App>{' '}</App>"
options: [children: 'always']
,
code: "<App>{' '}</App>"
options: [children: 'always']
,
code: '<App {...props}>foo</App>'
options: [props: 'always']
,
code: '<App>{"Hello #{word} World"}</App>'
options: [children: 'never']
,
code: '<App>{"Hello \\n World"}</App>'
options: [children: 'never']
,
code: '<App>{"Hello #{word} World"}{"foo"}</App>'
options: [children: 'never']
,
code: '<App prop={"foo #{word} bar"}>foo</App>'
options: [props: 'never']
,
code: '<App prop={"foo #{word} bar"} />'
options: [props: 'never']
,
code: '<App>{<myApp></myApp>}</App>'
options: [children: 'always']
,
code: '<App>{[]}</App>'
,
code: '<App>foo</App>'
,
code: '<App>{"foo"}{<Component>bar</Component>}</App>'
,
code: "<App prop='bar'>foo</App>"
,
code: '<App prop={true}>foo</App>'
,
code: '<App prop>foo</App>'
,
code: "<App prop='bar'>{'foo \\n bar'}</App>"
,
code: "<MyComponent prop='bar'>foo</MyComponent>"
options: [props: 'never']
,
code: '<MyComponent prop="bar">foo</MyComponent>'
options: [props: 'never']
,
code: '<MyComponent>foo</MyComponent>'
options: [children: 'never']
,
code: '<MyComponent>{<App/>}{"123"}</MyComponent>'
options: [children: 'never']
,
code: '<App>{"foo \'bar\' \\"foo\\" bar"}</App>'
options: [children: 'never']
,
code: "<MyComponent prop={'bar'}>foo</MyComponent>"
options: [props: 'always']
,
code: "<MyComponent>{'foo'}</MyComponent>"
options: [children: 'always']
,
code: '<MyComponent prop={"bar"}>foo</MyComponent>'
options: [props: 'always']
,
code: '<MyComponent>{"foo"}</MyComponent>'
options: [children: 'always']
,
code: "<MyComponent>{'foo'}</MyComponent>"
options: [children: 'ignore']
,
code: "<MyComponent prop={'bar'}>foo</MyComponent>"
options: [props: 'ignore']
,
code: '<MyComponent>foo</MyComponent>'
options: [children: 'ignore']
,
code: "<MyComponent prop='bar'>foo</MyComponent>"
options: [props: 'ignore']
,
code: '<MyComponent prop="bar">foo</MyComponent>'
options: [props: 'ignore']
,
code: "<MyComponent prop='bar'>{'foo'}</MyComponent>"
options: [children: 'always', props: 'never']
,
code: "<MyComponent prop={'bar'}>foo</MyComponent>"
options: [children: 'never', props: 'always']
,
code: "<MyComponent prop={'bar'}>{'foo'}</MyComponent>"
options: ['always']
,
code: '<MyComponent prop={"bar"}>{"foo"}</MyComponent>'
options: ['always']
,
code: '<MyComponent prop={"bar"} attr={\'foo\'} />'
options: ['always']
,
code: '<MyComponent prop="bar" attr=\'foo\' />'
options: ['never']
,
code: "<MyComponent prop='bar'>foo</MyComponent>"
options: ['never']
,
code: '<MyComponent prop={"bar #{word} foo"}>{"foo #{word}"}</MyComponent>'
options: ['never']
,
code: '<MyComponent>{"div { margin-top: 0; }"}</MyComponent>'
options: ['never']
,
code: '<MyComponent>{"<Foo />"}</MyComponent>'
options: ['never']
,
code: '<MyComponent prop={"Hello \\u1026 world"}>bar</MyComponent>'
options: ['never']
,
code: '<MyComponent>{"Hello \\u1026 world"}</MyComponent>'
options: ['never']
,
code: '<MyComponent prop={"Hello · world"}>bar</MyComponent>'
options: ['never']
,
code: '<MyComponent>{"Hello · world"}</MyComponent>'
options: ['never']
,
code: '<MyComponent>{"Hello \\n world"}</MyComponent>'
options: ['never']
,
code: ['<a a={"start\\', '\\', 'end"}/>'].join '/n'
options: ['never']
]
invalid: [
code: '<App prop={"foo"} />'
output: '<App prop="foo" />'
options: [props: 'never']
errors: [message: unnecessaryCurlyMessage]
,
code: '<App>{<myApp></myApp>}</App>'
output: '<App><myApp></myApp></App>'
options: [children: 'never']
errors: [message: unnecessaryCurlyMessage]
,
code: '<App>{<myApp></myApp>}</App>'
output: '<App><myApp></myApp></App>'
errors: [message: unnecessaryCurlyMessage]
,
code: "<App prop={'foo'}>foo</App>"
output: '<App prop="foo">foo</App>'
options: [props: 'never']
errors: [message: unnecessaryCurlyMessage]
,
code: '<App>{"foo"}</App>'
output: '<App>foo</App>'
options: [children: 'never']
errors: [message: unnecessaryCurlyMessage]
,
# TODO: uncomment once fragment transformation works
# ,
# code: '<>{"foo"}</>'
# output: '<>foo</>'
# # parser: 'babel-eslint'
# options: [children: 'never']
# errors: [message: unnecessaryCurlyMessage]
code: "<MyComponent>{'foo'}</MyComponent>"
output: '<MyComponent>foo</MyComponent>'
errors: [message: unnecessaryCurlyMessage]
,
code: "<MyComponent prop={'bar'}>foo</MyComponent>"
output: '<MyComponent prop="bar">foo</MyComponent>'
errors: [message: unnecessaryCurlyMessage]
,
code: "<MyComponent>{'foo'}</MyComponent>"
output: '<MyComponent>foo</MyComponent>'
options: [children: 'never']
errors: [message: unnecessaryCurlyMessage]
,
code: "<MyComponent prop={'bar'}>foo</MyComponent>"
output: '<MyComponent prop="bar">foo</MyComponent>'
options: [props: 'never']
errors: [message: unnecessaryCurlyMessage]
,
code: "<MyComponent prop='bar'>foo</MyComponent>"
output: '<MyComponent prop={"bar"}>foo</MyComponent>'
options: [props: 'always']
errors: [message: missingCurlyMessage]
,
code: '<MyComponent prop="foo \'bar\'">foo</MyComponent>'
output: '<MyComponent prop={"foo \'bar\'"}>foo</MyComponent>'
options: [props: 'always']
errors: [message: missingCurlyMessage]
,
code: '<MyComponent prop=\'foo "bar"\'>foo</MyComponent>'
output: '<MyComponent prop={"foo \\"bar\\""}>foo</MyComponent>'
options: [props: 'always']
errors: [message: missingCurlyMessage]
,
code: '<MyComponent prop="foo \'bar\'">foo</MyComponent>'
output: '<MyComponent prop={"foo \'bar\'"}>foo</MyComponent>'
options: [props: 'always']
errors: [message: missingCurlyMessage]
,
code: '<MyComponent>foo bar </MyComponent>'
output: '<MyComponent>{"foo bar "}</MyComponent>'
options: [children: 'always']
errors: [message: missingCurlyMessage]
,
code: '<MyComponent prop="foo \'bar\' \\n ">foo</MyComponent>'
output: '<MyComponent prop={"foo \'bar\' \\\\n "}>foo</MyComponent>'
options: [props: 'always']
errors: [message: missingCurlyMessage]
,
code: '<MyComponent>foo bar \\r </MyComponent>'
output: '<MyComponent>{"foo bar \\\\r "}</MyComponent>'
options: [children: 'always']
errors: [message: missingCurlyMessage]
,
code: "<MyComponent>foo bar 'foo'</MyComponent>"
output: '<MyComponent>{"foo bar \'foo\'"}</MyComponent>'
options: [children: 'always']
errors: [message: missingCurlyMessage]
,
code: '<MyComponent>foo bar "foo"</MyComponent>'
output: '<MyComponent>{"foo bar \\"foo\\""}</MyComponent>'
options: [children: 'always']
errors: [message: missingCurlyMessage]
,
code: '<MyComponent>foo bar <App/></MyComponent>'
output: '<MyComponent>{"foo bar "}<App/></MyComponent>'
options: [children: 'always']
errors: [message: missingCurlyMessage]
,
code: '<MyComponent>foo \\n bar</MyComponent>'
output: '<MyComponent>{"foo \\\\n bar"}</MyComponent>'
options: [children: 'always']
errors: [message: missingCurlyMessage]
,
code: '<MyComponent>foo \\u1234 bar</MyComponent>'
output: '<MyComponent>{"foo \\\\u1234 bar"}</MyComponent>'
options: [children: 'always']
errors: [message: missingCurlyMessage]
,
code: "<MyComponent prop='foo \\u1234 bar' />"
output: '<MyComponent prop={"foo \\\\u1234 bar"} />'
options: [props: 'always']
errors: [message: missingCurlyMessage]
,
code: "<MyComponent prop={'bar'}>{'foo'}</MyComponent>"
output: '<MyComponent prop="bar">foo</MyComponent>'
options: ['never']
errors: [
message: unnecessaryCurlyMessage
,
message: unnecessaryCurlyMessage
]
,
code: "<MyComponent prop='bar'>foo</MyComponent>"
output: '<MyComponent prop={"bar"}>{"foo"}</MyComponent>'
options: ['always']
errors: [{message: missingCurlyMessage}, {message: missingCurlyMessage}]
,
code: '<App prop={\'foo\'} attr={" foo "} />'
output: '<App prop="foo" attr=" foo " />'
errors: [
message: unnecessaryCurlyMessage
,
message: unnecessaryCurlyMessage
]
options: [props: 'never']
,
code: '<App prop=\'foo\' attr="bar" />'
output: '<App prop={"foo"} attr={"bar"} />'
errors: [{message: missingCurlyMessage}, {message: missingCurlyMessage}]
options: [props: 'always']
,
code: '<App prop=\'foo\' attr={"bar"} />'
output: '<App prop={"foo"} attr={"bar"} />'
errors: [message: missingCurlyMessage]
options: [props: 'always']
,
code: "<App prop={'foo'} attr='bar' />"
output: '<App prop={\'foo\'} attr={"bar"} />'
errors: [message: missingCurlyMessage]
options: [props: 'always']
,
code: "<App prop='foo · bar' />"
errors: [message: missingCurlyMessage]
options: [props: 'always']
,
code: '<App>foo · bar</App>'
errors: [message: missingCurlyMessage]
options: [children: 'always']
,
code: '<App>{\'foo "bar"\'}</App>'
output: '<App>foo "bar"</App>'
errors: [message: unnecessaryCurlyMessage]
options: [children: 'never']
,
code: '<App>{"foo \'bar\'"}</App>'
output: "<App>foo 'bar'</App>"
errors: [message: unnecessaryCurlyMessage]
options: [children: 'never']
,
code: [
'<App prop=" '
' a '
' b c'
' d'
'">'
' a'
' b c '
' d '
'</App>'
].join '\n'
errors: [{message: missingCurlyMessage}, {message: missingCurlyMessage}]
options: ['always']
,
code: [
"<App prop=' "
' a '
' b c'
' d'
"'>"
' a'
' b c '
' d '
'</App>'
].join '\n'
errors: [{message: missingCurlyMessage}, {message: missingCurlyMessage}]
options: ['always']
,
code: '<MyComponent prop={"{ style: true }"}>bar</MyComponent>'
output: '<MyComponent prop="{ style: true }">bar</MyComponent>'
errors: [message: unnecessaryCurlyMessage]
options: ['never']
,
code: '<MyComponent prop={"< style: true >"}>foo</MyComponent>'
output: '<MyComponent prop="< style: true >">foo</MyComponent>'
errors: [message: unnecessaryCurlyMessage]
options: ['never']
]
| true | ###*
# @fileoverview Enforce curly braces or disallow unnecessary curly braces in JSX
# @author PI:NAME:<NAME>END_PI
###
'use strict'
# For better readability on tests involving quotes
### eslint-disable quotes ###
### eslint-disable coffee/no-template-curly-in-string ###
# ------------------------------------------------------------------------------
# Requirements
# ------------------------------------------------------------------------------
rule = require 'eslint-plugin-react/lib/rules/jsx-curly-brace-presence'
{RuleTester} = require 'eslint'
path = require 'path'
missingCurlyMessage = 'Need to wrap this literal in a JSX expression.'
unnecessaryCurlyMessage = 'Curly braces are unnecessary here.'
# ------------------------------------------------------------------------------
# Tests
# ------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'jsx-curly-brace-presence', rule,
valid: [
code: '<App {...props}>foo</App>'
,
code: '<>foo</>'
,
# parser: 'babel-eslint'
code: '<App {...props}>foo</App>'
options: [props: 'never']
,
###
# There is no way to inject the space into JSX without an expression container
# so this format should always be allowed regardless of the `children` option.
###
code: "<App>{' '}</App>"
,
code: "<App>{' '}</App>"
,
code: "<App>{' '}</App>"
options: [children: 'never']
,
code: "<App>{' '}</App>"
options: [children: 'never']
,
code: "<App>{' '}</App>"
options: [children: 'always']
,
code: "<App>{' '}</App>"
options: [children: 'always']
,
code: '<App {...props}>foo</App>'
options: [props: 'always']
,
code: '<App>{"Hello #{word} World"}</App>'
options: [children: 'never']
,
code: '<App>{"Hello \\n World"}</App>'
options: [children: 'never']
,
code: '<App>{"Hello #{word} World"}{"foo"}</App>'
options: [children: 'never']
,
code: '<App prop={"foo #{word} bar"}>foo</App>'
options: [props: 'never']
,
code: '<App prop={"foo #{word} bar"} />'
options: [props: 'never']
,
code: '<App>{<myApp></myApp>}</App>'
options: [children: 'always']
,
code: '<App>{[]}</App>'
,
code: '<App>foo</App>'
,
code: '<App>{"foo"}{<Component>bar</Component>}</App>'
,
code: "<App prop='bar'>foo</App>"
,
code: '<App prop={true}>foo</App>'
,
code: '<App prop>foo</App>'
,
code: "<App prop='bar'>{'foo \\n bar'}</App>"
,
code: "<MyComponent prop='bar'>foo</MyComponent>"
options: [props: 'never']
,
code: '<MyComponent prop="bar">foo</MyComponent>'
options: [props: 'never']
,
code: '<MyComponent>foo</MyComponent>'
options: [children: 'never']
,
code: '<MyComponent>{<App/>}{"123"}</MyComponent>'
options: [children: 'never']
,
code: '<App>{"foo \'bar\' \\"foo\\" bar"}</App>'
options: [children: 'never']
,
code: "<MyComponent prop={'bar'}>foo</MyComponent>"
options: [props: 'always']
,
code: "<MyComponent>{'foo'}</MyComponent>"
options: [children: 'always']
,
code: '<MyComponent prop={"bar"}>foo</MyComponent>'
options: [props: 'always']
,
code: '<MyComponent>{"foo"}</MyComponent>'
options: [children: 'always']
,
code: "<MyComponent>{'foo'}</MyComponent>"
options: [children: 'ignore']
,
code: "<MyComponent prop={'bar'}>foo</MyComponent>"
options: [props: 'ignore']
,
code: '<MyComponent>foo</MyComponent>'
options: [children: 'ignore']
,
code: "<MyComponent prop='bar'>foo</MyComponent>"
options: [props: 'ignore']
,
code: '<MyComponent prop="bar">foo</MyComponent>'
options: [props: 'ignore']
,
code: "<MyComponent prop='bar'>{'foo'}</MyComponent>"
options: [children: 'always', props: 'never']
,
code: "<MyComponent prop={'bar'}>foo</MyComponent>"
options: [children: 'never', props: 'always']
,
code: "<MyComponent prop={'bar'}>{'foo'}</MyComponent>"
options: ['always']
,
code: '<MyComponent prop={"bar"}>{"foo"}</MyComponent>'
options: ['always']
,
code: '<MyComponent prop={"bar"} attr={\'foo\'} />'
options: ['always']
,
code: '<MyComponent prop="bar" attr=\'foo\' />'
options: ['never']
,
code: "<MyComponent prop='bar'>foo</MyComponent>"
options: ['never']
,
code: '<MyComponent prop={"bar #{word} foo"}>{"foo #{word}"}</MyComponent>'
options: ['never']
,
code: '<MyComponent>{"div { margin-top: 0; }"}</MyComponent>'
options: ['never']
,
code: '<MyComponent>{"<Foo />"}</MyComponent>'
options: ['never']
,
code: '<MyComponent prop={"Hello \\u1026 world"}>bar</MyComponent>'
options: ['never']
,
code: '<MyComponent>{"Hello \\u1026 world"}</MyComponent>'
options: ['never']
,
code: '<MyComponent prop={"Hello · world"}>bar</MyComponent>'
options: ['never']
,
code: '<MyComponent>{"Hello · world"}</MyComponent>'
options: ['never']
,
code: '<MyComponent>{"Hello \\n world"}</MyComponent>'
options: ['never']
,
code: ['<a a={"start\\', '\\', 'end"}/>'].join '/n'
options: ['never']
]
invalid: [
code: '<App prop={"foo"} />'
output: '<App prop="foo" />'
options: [props: 'never']
errors: [message: unnecessaryCurlyMessage]
,
code: '<App>{<myApp></myApp>}</App>'
output: '<App><myApp></myApp></App>'
options: [children: 'never']
errors: [message: unnecessaryCurlyMessage]
,
code: '<App>{<myApp></myApp>}</App>'
output: '<App><myApp></myApp></App>'
errors: [message: unnecessaryCurlyMessage]
,
code: "<App prop={'foo'}>foo</App>"
output: '<App prop="foo">foo</App>'
options: [props: 'never']
errors: [message: unnecessaryCurlyMessage]
,
code: '<App>{"foo"}</App>'
output: '<App>foo</App>'
options: [children: 'never']
errors: [message: unnecessaryCurlyMessage]
,
# TODO: uncomment once fragment transformation works
# ,
# code: '<>{"foo"}</>'
# output: '<>foo</>'
# # parser: 'babel-eslint'
# options: [children: 'never']
# errors: [message: unnecessaryCurlyMessage]
code: "<MyComponent>{'foo'}</MyComponent>"
output: '<MyComponent>foo</MyComponent>'
errors: [message: unnecessaryCurlyMessage]
,
code: "<MyComponent prop={'bar'}>foo</MyComponent>"
output: '<MyComponent prop="bar">foo</MyComponent>'
errors: [message: unnecessaryCurlyMessage]
,
code: "<MyComponent>{'foo'}</MyComponent>"
output: '<MyComponent>foo</MyComponent>'
options: [children: 'never']
errors: [message: unnecessaryCurlyMessage]
,
code: "<MyComponent prop={'bar'}>foo</MyComponent>"
output: '<MyComponent prop="bar">foo</MyComponent>'
options: [props: 'never']
errors: [message: unnecessaryCurlyMessage]
,
code: "<MyComponent prop='bar'>foo</MyComponent>"
output: '<MyComponent prop={"bar"}>foo</MyComponent>'
options: [props: 'always']
errors: [message: missingCurlyMessage]
,
code: '<MyComponent prop="foo \'bar\'">foo</MyComponent>'
output: '<MyComponent prop={"foo \'bar\'"}>foo</MyComponent>'
options: [props: 'always']
errors: [message: missingCurlyMessage]
,
code: '<MyComponent prop=\'foo "bar"\'>foo</MyComponent>'
output: '<MyComponent prop={"foo \\"bar\\""}>foo</MyComponent>'
options: [props: 'always']
errors: [message: missingCurlyMessage]
,
code: '<MyComponent prop="foo \'bar\'">foo</MyComponent>'
output: '<MyComponent prop={"foo \'bar\'"}>foo</MyComponent>'
options: [props: 'always']
errors: [message: missingCurlyMessage]
,
code: '<MyComponent>foo bar </MyComponent>'
output: '<MyComponent>{"foo bar "}</MyComponent>'
options: [children: 'always']
errors: [message: missingCurlyMessage]
,
code: '<MyComponent prop="foo \'bar\' \\n ">foo</MyComponent>'
output: '<MyComponent prop={"foo \'bar\' \\\\n "}>foo</MyComponent>'
options: [props: 'always']
errors: [message: missingCurlyMessage]
,
code: '<MyComponent>foo bar \\r </MyComponent>'
output: '<MyComponent>{"foo bar \\\\r "}</MyComponent>'
options: [children: 'always']
errors: [message: missingCurlyMessage]
,
code: "<MyComponent>foo bar 'foo'</MyComponent>"
output: '<MyComponent>{"foo bar \'foo\'"}</MyComponent>'
options: [children: 'always']
errors: [message: missingCurlyMessage]
,
code: '<MyComponent>foo bar "foo"</MyComponent>'
output: '<MyComponent>{"foo bar \\"foo\\""}</MyComponent>'
options: [children: 'always']
errors: [message: missingCurlyMessage]
,
code: '<MyComponent>foo bar <App/></MyComponent>'
output: '<MyComponent>{"foo bar "}<App/></MyComponent>'
options: [children: 'always']
errors: [message: missingCurlyMessage]
,
code: '<MyComponent>foo \\n bar</MyComponent>'
output: '<MyComponent>{"foo \\\\n bar"}</MyComponent>'
options: [children: 'always']
errors: [message: missingCurlyMessage]
,
code: '<MyComponent>foo \\u1234 bar</MyComponent>'
output: '<MyComponent>{"foo \\\\u1234 bar"}</MyComponent>'
options: [children: 'always']
errors: [message: missingCurlyMessage]
,
code: "<MyComponent prop='foo \\u1234 bar' />"
output: '<MyComponent prop={"foo \\\\u1234 bar"} />'
options: [props: 'always']
errors: [message: missingCurlyMessage]
,
code: "<MyComponent prop={'bar'}>{'foo'}</MyComponent>"
output: '<MyComponent prop="bar">foo</MyComponent>'
options: ['never']
errors: [
message: unnecessaryCurlyMessage
,
message: unnecessaryCurlyMessage
]
,
code: "<MyComponent prop='bar'>foo</MyComponent>"
output: '<MyComponent prop={"bar"}>{"foo"}</MyComponent>'
options: ['always']
errors: [{message: missingCurlyMessage}, {message: missingCurlyMessage}]
,
code: '<App prop={\'foo\'} attr={" foo "} />'
output: '<App prop="foo" attr=" foo " />'
errors: [
message: unnecessaryCurlyMessage
,
message: unnecessaryCurlyMessage
]
options: [props: 'never']
,
code: '<App prop=\'foo\' attr="bar" />'
output: '<App prop={"foo"} attr={"bar"} />'
errors: [{message: missingCurlyMessage}, {message: missingCurlyMessage}]
options: [props: 'always']
,
code: '<App prop=\'foo\' attr={"bar"} />'
output: '<App prop={"foo"} attr={"bar"} />'
errors: [message: missingCurlyMessage]
options: [props: 'always']
,
code: "<App prop={'foo'} attr='bar' />"
output: '<App prop={\'foo\'} attr={"bar"} />'
errors: [message: missingCurlyMessage]
options: [props: 'always']
,
code: "<App prop='foo · bar' />"
errors: [message: missingCurlyMessage]
options: [props: 'always']
,
code: '<App>foo · bar</App>'
errors: [message: missingCurlyMessage]
options: [children: 'always']
,
code: '<App>{\'foo "bar"\'}</App>'
output: '<App>foo "bar"</App>'
errors: [message: unnecessaryCurlyMessage]
options: [children: 'never']
,
code: '<App>{"foo \'bar\'"}</App>'
output: "<App>foo 'bar'</App>"
errors: [message: unnecessaryCurlyMessage]
options: [children: 'never']
,
code: [
'<App prop=" '
' a '
' b c'
' d'
'">'
' a'
' b c '
' d '
'</App>'
].join '\n'
errors: [{message: missingCurlyMessage}, {message: missingCurlyMessage}]
options: ['always']
,
code: [
"<App prop=' "
' a '
' b c'
' d'
"'>"
' a'
' b c '
' d '
'</App>'
].join '\n'
errors: [{message: missingCurlyMessage}, {message: missingCurlyMessage}]
options: ['always']
,
code: '<MyComponent prop={"{ style: true }"}>bar</MyComponent>'
output: '<MyComponent prop="{ style: true }">bar</MyComponent>'
errors: [message: unnecessaryCurlyMessage]
options: ['never']
,
code: '<MyComponent prop={"< style: true >"}>foo</MyComponent>'
output: '<MyComponent prop="< style: true >">foo</MyComponent>'
errors: [message: unnecessaryCurlyMessage]
options: ['never']
]
|
[
{
"context": "ERRORS_KEY = \"signinErrors\"\n\nTemplate.signin.created = ->\n Session.se",
"end": 20,
"score": 0.5901243090629578,
"start": 14,
"tag": "KEY",
"value": "signin"
},
{
"context": "l is required\" unless email\n errors.password = \"Password is required\" unless password\n Session.set ERRORS_KEY, error",
"end": 514,
"score": 0.9718301296234131,
"start": 494,
"tag": "PASSWORD",
"value": "Password is required"
}
] | client/templates/auth-signin.coffee | mcgwier/workhandle | 0 | ERRORS_KEY = "signinErrors"
Template.signin.created = ->
Session.set ERRORS_KEY, {}
Template.signin.helpers
errorMessages: ->
_.values Session.get(ERRORS_KEY)
errorClass: (key) ->
Session.get(ERRORS_KEY)[key] and "error"
Template.signin.events submit: (event, template) ->
event.preventDefault()
email = template.$("[name=email]").val()
password = template.$("[name=password]").val()
errors = {}
errors.email = "Email is required" unless email
errors.password = "Password is required" unless password
Session.set ERRORS_KEY, errors
return if _.keys(errors).length
Meteor.loginWithPassword email, password, (error) ->
if error
Session.set(ERRORS_KEY, none: error.reason)
else
Router.go "home"
| 191523 | ERRORS_KEY = "<KEY>Errors"
Template.signin.created = ->
Session.set ERRORS_KEY, {}
Template.signin.helpers
errorMessages: ->
_.values Session.get(ERRORS_KEY)
errorClass: (key) ->
Session.get(ERRORS_KEY)[key] and "error"
Template.signin.events submit: (event, template) ->
event.preventDefault()
email = template.$("[name=email]").val()
password = template.$("[name=password]").val()
errors = {}
errors.email = "Email is required" unless email
errors.password = "<PASSWORD>" unless password
Session.set ERRORS_KEY, errors
return if _.keys(errors).length
Meteor.loginWithPassword email, password, (error) ->
if error
Session.set(ERRORS_KEY, none: error.reason)
else
Router.go "home"
| true | ERRORS_KEY = "PI:KEY:<KEY>END_PIErrors"
Template.signin.created = ->
Session.set ERRORS_KEY, {}
Template.signin.helpers
errorMessages: ->
_.values Session.get(ERRORS_KEY)
errorClass: (key) ->
Session.get(ERRORS_KEY)[key] and "error"
Template.signin.events submit: (event, template) ->
event.preventDefault()
email = template.$("[name=email]").val()
password = template.$("[name=password]").val()
errors = {}
errors.email = "Email is required" unless email
errors.password = "PI:PASSWORD:<PASSWORD>END_PI" unless password
Session.set ERRORS_KEY, errors
return if _.keys(errors).length
Meteor.loginWithPassword email, password, (error) ->
if error
Session.set(ERRORS_KEY, none: error.reason)
else
Router.go "home"
|
[
{
"context": "dsc.models.page\n\n@edsc.help = do ($=jQuery, config=@edsc.config, wait = @edsc.util.xhr.wait, page=@edsc.page, Pre",
"end": 153,
"score": 0.8411334156990051,
"start": 141,
"tag": "USERNAME",
"value": "@edsc.config"
},
{
"context": "ns = $.extend({}, defaultHelpOptions, stop, key: \"tour_#{i}\")\n queue.push(options)\n\n showCurrent()\n",
"end": 12156,
"score": 0.7718932628631592,
"start": 12149,
"tag": "KEY",
"value": "tour_#{"
}
] | app/assets/javascripts/modules/help.js.coffee | kant/earthdata-search | 1 |
#= require models/data/preferences
data = @edsc.models.data
ui = @edsc.models.ui
ns = @edsc.models.page
@edsc.help = do ($=jQuery, config=@edsc.config, wait = @edsc.util.xhr.wait, page=@edsc.page, PreferencesModel = data.Preferences, urlUtil=@edsc.util.url) ->
tourOptions =
tour_end:
title: 'Tour Ended'
element: '#main-toolbar h1 a'
placement: 'bottom'
content: 'Your tour has ended. At any point you may restart it by visiting the home page and clicking
on the "Take a Tour" link.'
defaultTemplate = "<div class='popover tour'>
<div class='arrow'></div>
<h3 class='popover-title'></h3>
<div class='popover-content'></div>
<div class='popover-navigation'>
<div class='btn-group'>
<button class='button-small secondary' data-role='prev'><i class='fa fa-arrow-circle-left'></i> Prev</button>
<button class='button-small' data-role='next'>Next <i class='fa fa-arrow-circle-right'></i></button>
</div>
<button class='button-small pull-left' data-role='end'>End Tour</button>
<label class='pull-left'>
<input data-role='toggleHideTour' class='toggleHideTour' type='checkbox' />
<small>Do not show again</small>
</label>
</div>
</div>"
tour = [{
title: "Search"
content: '<p>Use Earthdata Search\'s natural language processing-enabled search tool to quickly narrow
down to relevant collections. An example search phrase could be <em>Land Surface Temperature over
Texas last month</em>. Results will be displayed in the collection panel below.</p>
<p>You can also add filters to refine your search:</p>
<ul>
<li><i class="fa fa-fw fa-clock-o"></i> Pick a temporal range from a calendar</li>
<li><i class="fa fa-fw fa-crop"></i> Manually set spatial boundaries</li>
<li><i class="fa fa-fw fa-eraser"></i> Clear all of your filters</li>
</ul>'
element: '#keywords'
placement: 'bottom'
showNext: true
},{
title: "Search Results"
content: '<p>Search results will be shown in the Matching Collections panel below. Each result will have summary
information along with relevant badges to allow you to quickly scan your search results to find the
right collection. The panel can be resized by clicking and dragging the bar above the <em>Matching
Collections</em> tab.</p>
<p>Collection options include:</p>
<ul>
<li><i class="fa fa-fw fa-info-circle"></i> View more information about a collection</li>
<li><i class="fa fa-fw fa-plus"></i> Add collections to your project to compare</li>
</ul>
<p>Click anywhere on a collection to view granules available for download</p>'
element: '#collection-results-list'
placement: 'top'
showNext: true
},{
title: "Facets"
content: '<p>Refine your search further with available facets, such as:
<div class="tour-list">
<ul class="bullet-list">
<li>
<span class="tour-list-title">Features</span> - has map imagery, is near-real-time, or is subsettable
</li>
<li>
<span class="tour-list-title">Keywords</span> - science terms describing collections
</li>
<li>
<span class="tour-list-title">Platforms</span> - satellite, aircraft, etc. hosting Instruments
</li>
<li>
<span class="tour-list-title">Instruments</span> - devices that make measurements
</li>
<li>
<span class="tour-list-title">Organizations</span> - responsible for archiving and/or producing data
</li>
<li>
<span class="tour-list-title">Projects</span> - mission or science project
</li>
<li>
<span class="tour-list-title">Processing Levels</span> - raw, geophysical variables, grid, or model
</li>
</ul>
</div>
</p>'
element: "#master-overlay-parent"
placement: 'right'
showNext: true
top: null
}, {
title: "Map Tools"
content: '<p>Use these map tools to configure and position the map as well as enable certain spatial tools.
<table><tr>
<td>
<ul class="icon-list">
<li class="leaflet-draw-list"><i class="icon-leaflet-draw-edit-remove"></i> Delete a layer</li>
<li class="leaflet-draw-list"><i class="icon-leaflet-draw-edit-edit"></i> Edit a layer</li>
<li class="leaflet-draw-list"><i class="icon-leaflet-draw-draw-marker"></i> Spatial coordinate search </li>
<li class="leaflet-draw-list"><i class="icon-leaflet-draw-draw-rectangle"></i> Bounding box search</li>
<li class="leaflet-draw-list"><i class="icon-leaflet-draw-draw-polygon"></i> Polygon search</li>
</ul>
</td>
<td>
<ul class="icon-list">
<li class="projection-draw-list"><i class="icon-projection-draw-arctic"></i> North Polar projection</li>
<li class="projection-draw-list"><i class="icon-projection-draw-geographic"></i> Geographic projection</li>
<li class="projection-draw-list"><i class="icon-projection-draw-antarctic"></i> South Polar projection</li>
<li class="zoom-draw-list"><i class="fa fa-fw fa-plus"></i> Zoom in </li>
<li class="zoom-draw-list"><i class="fa fa-fw fa-home"></i> Reset zoom </li>
<li class="zoom-draw-list"><i class="fa fa-fw fa-minus"></i> Zoom out </li>
<li><i class="icon-map-layers"></i> Map layers</li></ul>
</td>
</tr></table>
</p>'
placement: 'top'
element: '.projection-switcher-arctic'
showNext: true
}, {
title: 'Toolbar'
content: '<p>This is the end of the tour. Using this toolbar, you can:
<div class="tour-list">
<ul>
<li class="toolbar-draw-list"><i class="fa fa-bullhorn"></i> Provide feedback</li>
<li class="toolbar-draw-list"><i class="fa fa-lock"></i> Login to Earthdata for more user tools</li>
</ul>
</div>
</p>
<p>When logged in, you can also:
<div class="tour-list">
<ul class="bullet-list">
<li> Save your current project</li>
<li> View profile information, recent downloads, saved projects, or show this tour again</li>
</ul>
</div>
</p>'
element: '.user-info'
placement: 'bottom'
}]
defaultHelpOptions =
placement: 'auto left'
html: true
wait: true
trigger: 'manual'
template: defaultTemplate
container: 'body'
defaultTourOptions =
reflex: true
placement: 'left'
queue = []
shown = {}
index = 0
next = null
close = null
tourRunning = false
doNotShowTourAgain = false
toggleHideTour = ->
doNotShowTourAgain = if doNotShowTourAgain then false else true
$('input:checkbox.toggleHideTour').prop 'checked', doNotShowTourAgain
hideCurrent = ->
if queue[index]?
queue[index].cleanup?(next, close)
$(queue[index].element).popover('destroy')
$('.popover-advance').removeClass('popover-advance')
close = ->
$('#sitetourModal').modal('hide')
hideCurrent()
queue = []
index = 0
tourRunning = false
prev = ->
if index > 0
hideCurrent()
index--
showCurrent()
next = ->
if index < queue.length - 1
hideCurrent()
index++
showCurrent()
else
close()
showCurrentImmediate = ->
$('.popover-advance').removeClass('popover-advance')
$el = $(queue[index].element)
if $el.length > 1
console.error "Too many elements matched selector #{queue[index].element}. Showing the first.", $el
$el = $el.first()
$el.popover(queue[index])
$el.attr('data-original-title', '')
$el.popover('show')
$el.popover({ html : true })
shown[queue[index].key] = true
unless queue[index].advanceHook
$(queue[index].target ? $el).addClass('popover-advance')
# console.log "Popover: #{queue[index].element} -> #{$el.length}"
queue[index].advanceHook?(next, close)
queue[index].closeHook?(close)
$('input:checkbox.toggleHideTour').prop 'checked', doNotShowTourAgain
if $el.data('bs.popover')?
$tip = $el.data('bs.popover').$tip
$tip.toggleClass('is-popover-single', queue.length == 1)
if tourRunning
if index == 0
$tip.find('[data-role=prev]').hide()
if index < queue.length - 1
$tip.find('[data-role=end]').addClass('secondary')
$tip.find('[data-role=next]').toggle(queue[index].showNext)
else
$tip.find('[data-role=end]').text('Close')
$tip.find('[data-role=prev]').toggle(index != 0)
$tip.find('[data-role=next]').toggle(index != queue.length - 1)
showCurrent = ->
if queue[index].wait
wait(showCurrentImmediate)
else if queue[index].waitOnAnimate
setTimeout((-> wait(showCurrentImmediate)), config.defaultAnimationDurationMs + 200)
else
showCurrentImmediate()
$(document).on 'click', '.popover [data-role=prev]', prev
$(document).on 'click', '.popover [data-role=next], .popover-advance', next
$(document).on 'click', '.popover [data-role=toggleHideTour]', toggleHideTour
$(document).on 'click', '.popover [data-role=end]', ->
if tourRunning
preferences = new PreferencesModel()
preferences.showTour(false)
preferences.doNotShowTourAgain(doNotShowTourAgain.toString())
preferences.save()
close()
add('tour_end')
else
close()
$(document).on 'click', '.show-tour', (e) ->
unless window.edscportal
e.preventDefault()
startTour()
$(window).on 'statechange', ->
$('[id^="show-tour-"]').toggle(urlUtil.cleanPath()?.split('?')[0] in ["/search", "/", ""])
$(document).on 'ready', ->
$('[id^="show-tour-"]').toggle(urlUtil.cleanPath()?.split('?')[0] in ["/search", "/", ""])
# TL: We can probably find a nicer way to handle this. Currently, just hiding the menu based on
# scroll position. Until we look at scrolling behavior on non-full-page pages, this should work fine
$ ()->
$('.main-content-scrollable').on 'scroll', (e) ->
if ($(e.target).scrollTop() > 20)
$('.toolbar-secondary').hide()
return
$('.toolbar-secondary').show()
add = (key, options={}) ->
unless tourRunning
options = $.extend({}, defaultHelpOptions, tourOptions[key], options, key: key)
for item in queue
return if item.key == key
unless options.once && shown[key]
queue.push(options)
showCurrent()
remove = (key) ->
if queue[0]?.key == key
next()
else
queue = (item for item in queue when item.key != key)
current = ->
if tourRunning then nil else queue[index]
startTour = ->
close()
tourRunning = true
for stop, i in tour
options = $.extend({}, defaultHelpOptions, stop, key: "tour_#{i}")
queue.push(options)
showCurrent()
exports =
add: add
remove: remove
current: current
next: next
prev: prev
close: close
startTour: startTour
| 61551 |
#= require models/data/preferences
data = @edsc.models.data
ui = @edsc.models.ui
ns = @edsc.models.page
@edsc.help = do ($=jQuery, config=@edsc.config, wait = @edsc.util.xhr.wait, page=@edsc.page, PreferencesModel = data.Preferences, urlUtil=@edsc.util.url) ->
tourOptions =
tour_end:
title: 'Tour Ended'
element: '#main-toolbar h1 a'
placement: 'bottom'
content: 'Your tour has ended. At any point you may restart it by visiting the home page and clicking
on the "Take a Tour" link.'
defaultTemplate = "<div class='popover tour'>
<div class='arrow'></div>
<h3 class='popover-title'></h3>
<div class='popover-content'></div>
<div class='popover-navigation'>
<div class='btn-group'>
<button class='button-small secondary' data-role='prev'><i class='fa fa-arrow-circle-left'></i> Prev</button>
<button class='button-small' data-role='next'>Next <i class='fa fa-arrow-circle-right'></i></button>
</div>
<button class='button-small pull-left' data-role='end'>End Tour</button>
<label class='pull-left'>
<input data-role='toggleHideTour' class='toggleHideTour' type='checkbox' />
<small>Do not show again</small>
</label>
</div>
</div>"
tour = [{
title: "Search"
content: '<p>Use Earthdata Search\'s natural language processing-enabled search tool to quickly narrow
down to relevant collections. An example search phrase could be <em>Land Surface Temperature over
Texas last month</em>. Results will be displayed in the collection panel below.</p>
<p>You can also add filters to refine your search:</p>
<ul>
<li><i class="fa fa-fw fa-clock-o"></i> Pick a temporal range from a calendar</li>
<li><i class="fa fa-fw fa-crop"></i> Manually set spatial boundaries</li>
<li><i class="fa fa-fw fa-eraser"></i> Clear all of your filters</li>
</ul>'
element: '#keywords'
placement: 'bottom'
showNext: true
},{
title: "Search Results"
content: '<p>Search results will be shown in the Matching Collections panel below. Each result will have summary
information along with relevant badges to allow you to quickly scan your search results to find the
right collection. The panel can be resized by clicking and dragging the bar above the <em>Matching
Collections</em> tab.</p>
<p>Collection options include:</p>
<ul>
<li><i class="fa fa-fw fa-info-circle"></i> View more information about a collection</li>
<li><i class="fa fa-fw fa-plus"></i> Add collections to your project to compare</li>
</ul>
<p>Click anywhere on a collection to view granules available for download</p>'
element: '#collection-results-list'
placement: 'top'
showNext: true
},{
title: "Facets"
content: '<p>Refine your search further with available facets, such as:
<div class="tour-list">
<ul class="bullet-list">
<li>
<span class="tour-list-title">Features</span> - has map imagery, is near-real-time, or is subsettable
</li>
<li>
<span class="tour-list-title">Keywords</span> - science terms describing collections
</li>
<li>
<span class="tour-list-title">Platforms</span> - satellite, aircraft, etc. hosting Instruments
</li>
<li>
<span class="tour-list-title">Instruments</span> - devices that make measurements
</li>
<li>
<span class="tour-list-title">Organizations</span> - responsible for archiving and/or producing data
</li>
<li>
<span class="tour-list-title">Projects</span> - mission or science project
</li>
<li>
<span class="tour-list-title">Processing Levels</span> - raw, geophysical variables, grid, or model
</li>
</ul>
</div>
</p>'
element: "#master-overlay-parent"
placement: 'right'
showNext: true
top: null
}, {
title: "Map Tools"
content: '<p>Use these map tools to configure and position the map as well as enable certain spatial tools.
<table><tr>
<td>
<ul class="icon-list">
<li class="leaflet-draw-list"><i class="icon-leaflet-draw-edit-remove"></i> Delete a layer</li>
<li class="leaflet-draw-list"><i class="icon-leaflet-draw-edit-edit"></i> Edit a layer</li>
<li class="leaflet-draw-list"><i class="icon-leaflet-draw-draw-marker"></i> Spatial coordinate search </li>
<li class="leaflet-draw-list"><i class="icon-leaflet-draw-draw-rectangle"></i> Bounding box search</li>
<li class="leaflet-draw-list"><i class="icon-leaflet-draw-draw-polygon"></i> Polygon search</li>
</ul>
</td>
<td>
<ul class="icon-list">
<li class="projection-draw-list"><i class="icon-projection-draw-arctic"></i> North Polar projection</li>
<li class="projection-draw-list"><i class="icon-projection-draw-geographic"></i> Geographic projection</li>
<li class="projection-draw-list"><i class="icon-projection-draw-antarctic"></i> South Polar projection</li>
<li class="zoom-draw-list"><i class="fa fa-fw fa-plus"></i> Zoom in </li>
<li class="zoom-draw-list"><i class="fa fa-fw fa-home"></i> Reset zoom </li>
<li class="zoom-draw-list"><i class="fa fa-fw fa-minus"></i> Zoom out </li>
<li><i class="icon-map-layers"></i> Map layers</li></ul>
</td>
</tr></table>
</p>'
placement: 'top'
element: '.projection-switcher-arctic'
showNext: true
}, {
title: 'Toolbar'
content: '<p>This is the end of the tour. Using this toolbar, you can:
<div class="tour-list">
<ul>
<li class="toolbar-draw-list"><i class="fa fa-bullhorn"></i> Provide feedback</li>
<li class="toolbar-draw-list"><i class="fa fa-lock"></i> Login to Earthdata for more user tools</li>
</ul>
</div>
</p>
<p>When logged in, you can also:
<div class="tour-list">
<ul class="bullet-list">
<li> Save your current project</li>
<li> View profile information, recent downloads, saved projects, or show this tour again</li>
</ul>
</div>
</p>'
element: '.user-info'
placement: 'bottom'
}]
defaultHelpOptions =
placement: 'auto left'
html: true
wait: true
trigger: 'manual'
template: defaultTemplate
container: 'body'
defaultTourOptions =
reflex: true
placement: 'left'
queue = []
shown = {}
index = 0
next = null
close = null
tourRunning = false
doNotShowTourAgain = false
toggleHideTour = ->
doNotShowTourAgain = if doNotShowTourAgain then false else true
$('input:checkbox.toggleHideTour').prop 'checked', doNotShowTourAgain
hideCurrent = ->
if queue[index]?
queue[index].cleanup?(next, close)
$(queue[index].element).popover('destroy')
$('.popover-advance').removeClass('popover-advance')
close = ->
$('#sitetourModal').modal('hide')
hideCurrent()
queue = []
index = 0
tourRunning = false
prev = ->
if index > 0
hideCurrent()
index--
showCurrent()
next = ->
if index < queue.length - 1
hideCurrent()
index++
showCurrent()
else
close()
showCurrentImmediate = ->
$('.popover-advance').removeClass('popover-advance')
$el = $(queue[index].element)
if $el.length > 1
console.error "Too many elements matched selector #{queue[index].element}. Showing the first.", $el
$el = $el.first()
$el.popover(queue[index])
$el.attr('data-original-title', '')
$el.popover('show')
$el.popover({ html : true })
shown[queue[index].key] = true
unless queue[index].advanceHook
$(queue[index].target ? $el).addClass('popover-advance')
# console.log "Popover: #{queue[index].element} -> #{$el.length}"
queue[index].advanceHook?(next, close)
queue[index].closeHook?(close)
$('input:checkbox.toggleHideTour').prop 'checked', doNotShowTourAgain
if $el.data('bs.popover')?
$tip = $el.data('bs.popover').$tip
$tip.toggleClass('is-popover-single', queue.length == 1)
if tourRunning
if index == 0
$tip.find('[data-role=prev]').hide()
if index < queue.length - 1
$tip.find('[data-role=end]').addClass('secondary')
$tip.find('[data-role=next]').toggle(queue[index].showNext)
else
$tip.find('[data-role=end]').text('Close')
$tip.find('[data-role=prev]').toggle(index != 0)
$tip.find('[data-role=next]').toggle(index != queue.length - 1)
showCurrent = ->
if queue[index].wait
wait(showCurrentImmediate)
else if queue[index].waitOnAnimate
setTimeout((-> wait(showCurrentImmediate)), config.defaultAnimationDurationMs + 200)
else
showCurrentImmediate()
$(document).on 'click', '.popover [data-role=prev]', prev
$(document).on 'click', '.popover [data-role=next], .popover-advance', next
$(document).on 'click', '.popover [data-role=toggleHideTour]', toggleHideTour
$(document).on 'click', '.popover [data-role=end]', ->
if tourRunning
preferences = new PreferencesModel()
preferences.showTour(false)
preferences.doNotShowTourAgain(doNotShowTourAgain.toString())
preferences.save()
close()
add('tour_end')
else
close()
$(document).on 'click', '.show-tour', (e) ->
unless window.edscportal
e.preventDefault()
startTour()
$(window).on 'statechange', ->
$('[id^="show-tour-"]').toggle(urlUtil.cleanPath()?.split('?')[0] in ["/search", "/", ""])
$(document).on 'ready', ->
$('[id^="show-tour-"]').toggle(urlUtil.cleanPath()?.split('?')[0] in ["/search", "/", ""])
# TL: We can probably find a nicer way to handle this. Currently, just hiding the menu based on
# scroll position. Until we look at scrolling behavior on non-full-page pages, this should work fine
$ ()->
$('.main-content-scrollable').on 'scroll', (e) ->
if ($(e.target).scrollTop() > 20)
$('.toolbar-secondary').hide()
return
$('.toolbar-secondary').show()
add = (key, options={}) ->
unless tourRunning
options = $.extend({}, defaultHelpOptions, tourOptions[key], options, key: key)
for item in queue
return if item.key == key
unless options.once && shown[key]
queue.push(options)
showCurrent()
remove = (key) ->
if queue[0]?.key == key
next()
else
queue = (item for item in queue when item.key != key)
current = ->
if tourRunning then nil else queue[index]
startTour = ->
close()
tourRunning = true
for stop, i in tour
options = $.extend({}, defaultHelpOptions, stop, key: "<KEY>i}")
queue.push(options)
showCurrent()
exports =
add: add
remove: remove
current: current
next: next
prev: prev
close: close
startTour: startTour
| true |
#= require models/data/preferences
data = @edsc.models.data
ui = @edsc.models.ui
ns = @edsc.models.page
@edsc.help = do ($=jQuery, config=@edsc.config, wait = @edsc.util.xhr.wait, page=@edsc.page, PreferencesModel = data.Preferences, urlUtil=@edsc.util.url) ->
tourOptions =
tour_end:
title: 'Tour Ended'
element: '#main-toolbar h1 a'
placement: 'bottom'
content: 'Your tour has ended. At any point you may restart it by visiting the home page and clicking
on the "Take a Tour" link.'
defaultTemplate = "<div class='popover tour'>
<div class='arrow'></div>
<h3 class='popover-title'></h3>
<div class='popover-content'></div>
<div class='popover-navigation'>
<div class='btn-group'>
<button class='button-small secondary' data-role='prev'><i class='fa fa-arrow-circle-left'></i> Prev</button>
<button class='button-small' data-role='next'>Next <i class='fa fa-arrow-circle-right'></i></button>
</div>
<button class='button-small pull-left' data-role='end'>End Tour</button>
<label class='pull-left'>
<input data-role='toggleHideTour' class='toggleHideTour' type='checkbox' />
<small>Do not show again</small>
</label>
</div>
</div>"
tour = [{
title: "Search"
content: '<p>Use Earthdata Search\'s natural language processing-enabled search tool to quickly narrow
down to relevant collections. An example search phrase could be <em>Land Surface Temperature over
Texas last month</em>. Results will be displayed in the collection panel below.</p>
<p>You can also add filters to refine your search:</p>
<ul>
<li><i class="fa fa-fw fa-clock-o"></i> Pick a temporal range from a calendar</li>
<li><i class="fa fa-fw fa-crop"></i> Manually set spatial boundaries</li>
<li><i class="fa fa-fw fa-eraser"></i> Clear all of your filters</li>
</ul>'
element: '#keywords'
placement: 'bottom'
showNext: true
},{
title: "Search Results"
content: '<p>Search results will be shown in the Matching Collections panel below. Each result will have summary
information along with relevant badges to allow you to quickly scan your search results to find the
right collection. The panel can be resized by clicking and dragging the bar above the <em>Matching
Collections</em> tab.</p>
<p>Collection options include:</p>
<ul>
<li><i class="fa fa-fw fa-info-circle"></i> View more information about a collection</li>
<li><i class="fa fa-fw fa-plus"></i> Add collections to your project to compare</li>
</ul>
<p>Click anywhere on a collection to view granules available for download</p>'
element: '#collection-results-list'
placement: 'top'
showNext: true
},{
title: "Facets"
content: '<p>Refine your search further with available facets, such as:
<div class="tour-list">
<ul class="bullet-list">
<li>
<span class="tour-list-title">Features</span> - has map imagery, is near-real-time, or is subsettable
</li>
<li>
<span class="tour-list-title">Keywords</span> - science terms describing collections
</li>
<li>
<span class="tour-list-title">Platforms</span> - satellite, aircraft, etc. hosting Instruments
</li>
<li>
<span class="tour-list-title">Instruments</span> - devices that make measurements
</li>
<li>
<span class="tour-list-title">Organizations</span> - responsible for archiving and/or producing data
</li>
<li>
<span class="tour-list-title">Projects</span> - mission or science project
</li>
<li>
<span class="tour-list-title">Processing Levels</span> - raw, geophysical variables, grid, or model
</li>
</ul>
</div>
</p>'
element: "#master-overlay-parent"
placement: 'right'
showNext: true
top: null
}, {
title: "Map Tools"
content: '<p>Use these map tools to configure and position the map as well as enable certain spatial tools.
<table><tr>
<td>
<ul class="icon-list">
<li class="leaflet-draw-list"><i class="icon-leaflet-draw-edit-remove"></i> Delete a layer</li>
<li class="leaflet-draw-list"><i class="icon-leaflet-draw-edit-edit"></i> Edit a layer</li>
<li class="leaflet-draw-list"><i class="icon-leaflet-draw-draw-marker"></i> Spatial coordinate search </li>
<li class="leaflet-draw-list"><i class="icon-leaflet-draw-draw-rectangle"></i> Bounding box search</li>
<li class="leaflet-draw-list"><i class="icon-leaflet-draw-draw-polygon"></i> Polygon search</li>
</ul>
</td>
<td>
<ul class="icon-list">
<li class="projection-draw-list"><i class="icon-projection-draw-arctic"></i> North Polar projection</li>
<li class="projection-draw-list"><i class="icon-projection-draw-geographic"></i> Geographic projection</li>
<li class="projection-draw-list"><i class="icon-projection-draw-antarctic"></i> South Polar projection</li>
<li class="zoom-draw-list"><i class="fa fa-fw fa-plus"></i> Zoom in </li>
<li class="zoom-draw-list"><i class="fa fa-fw fa-home"></i> Reset zoom </li>
<li class="zoom-draw-list"><i class="fa fa-fw fa-minus"></i> Zoom out </li>
<li><i class="icon-map-layers"></i> Map layers</li></ul>
</td>
</tr></table>
</p>'
placement: 'top'
element: '.projection-switcher-arctic'
showNext: true
}, {
title: 'Toolbar'
content: '<p>This is the end of the tour. Using this toolbar, you can:
<div class="tour-list">
<ul>
<li class="toolbar-draw-list"><i class="fa fa-bullhorn"></i> Provide feedback</li>
<li class="toolbar-draw-list"><i class="fa fa-lock"></i> Login to Earthdata for more user tools</li>
</ul>
</div>
</p>
<p>When logged in, you can also:
<div class="tour-list">
<ul class="bullet-list">
<li> Save your current project</li>
<li> View profile information, recent downloads, saved projects, or show this tour again</li>
</ul>
</div>
</p>'
element: '.user-info'
placement: 'bottom'
}]
defaultHelpOptions =
placement: 'auto left'
html: true
wait: true
trigger: 'manual'
template: defaultTemplate
container: 'body'
defaultTourOptions =
reflex: true
placement: 'left'
queue = []
shown = {}
index = 0
next = null
close = null
tourRunning = false
doNotShowTourAgain = false
toggleHideTour = ->
doNotShowTourAgain = if doNotShowTourAgain then false else true
$('input:checkbox.toggleHideTour').prop 'checked', doNotShowTourAgain
hideCurrent = ->
if queue[index]?
queue[index].cleanup?(next, close)
$(queue[index].element).popover('destroy')
$('.popover-advance').removeClass('popover-advance')
close = ->
$('#sitetourModal').modal('hide')
hideCurrent()
queue = []
index = 0
tourRunning = false
prev = ->
if index > 0
hideCurrent()
index--
showCurrent()
next = ->
if index < queue.length - 1
hideCurrent()
index++
showCurrent()
else
close()
showCurrentImmediate = ->
$('.popover-advance').removeClass('popover-advance')
$el = $(queue[index].element)
if $el.length > 1
console.error "Too many elements matched selector #{queue[index].element}. Showing the first.", $el
$el = $el.first()
$el.popover(queue[index])
$el.attr('data-original-title', '')
$el.popover('show')
$el.popover({ html : true })
shown[queue[index].key] = true
unless queue[index].advanceHook
$(queue[index].target ? $el).addClass('popover-advance')
# console.log "Popover: #{queue[index].element} -> #{$el.length}"
queue[index].advanceHook?(next, close)
queue[index].closeHook?(close)
$('input:checkbox.toggleHideTour').prop 'checked', doNotShowTourAgain
if $el.data('bs.popover')?
$tip = $el.data('bs.popover').$tip
$tip.toggleClass('is-popover-single', queue.length == 1)
if tourRunning
if index == 0
$tip.find('[data-role=prev]').hide()
if index < queue.length - 1
$tip.find('[data-role=end]').addClass('secondary')
$tip.find('[data-role=next]').toggle(queue[index].showNext)
else
$tip.find('[data-role=end]').text('Close')
$tip.find('[data-role=prev]').toggle(index != 0)
$tip.find('[data-role=next]').toggle(index != queue.length - 1)
showCurrent = ->
if queue[index].wait
wait(showCurrentImmediate)
else if queue[index].waitOnAnimate
setTimeout((-> wait(showCurrentImmediate)), config.defaultAnimationDurationMs + 200)
else
showCurrentImmediate()
$(document).on 'click', '.popover [data-role=prev]', prev
$(document).on 'click', '.popover [data-role=next], .popover-advance', next
$(document).on 'click', '.popover [data-role=toggleHideTour]', toggleHideTour
$(document).on 'click', '.popover [data-role=end]', ->
if tourRunning
preferences = new PreferencesModel()
preferences.showTour(false)
preferences.doNotShowTourAgain(doNotShowTourAgain.toString())
preferences.save()
close()
add('tour_end')
else
close()
$(document).on 'click', '.show-tour', (e) ->
unless window.edscportal
e.preventDefault()
startTour()
$(window).on 'statechange', ->
$('[id^="show-tour-"]').toggle(urlUtil.cleanPath()?.split('?')[0] in ["/search", "/", ""])
$(document).on 'ready', ->
$('[id^="show-tour-"]').toggle(urlUtil.cleanPath()?.split('?')[0] in ["/search", "/", ""])
# TL: We can probably find a nicer way to handle this. Currently, just hiding the menu based on
# scroll position. Until we look at scrolling behavior on non-full-page pages, this should work fine
$ ()->
$('.main-content-scrollable').on 'scroll', (e) ->
if ($(e.target).scrollTop() > 20)
$('.toolbar-secondary').hide()
return
$('.toolbar-secondary').show()
add = (key, options={}) ->
unless tourRunning
options = $.extend({}, defaultHelpOptions, tourOptions[key], options, key: key)
for item in queue
return if item.key == key
unless options.once && shown[key]
queue.push(options)
showCurrent()
remove = (key) ->
if queue[0]?.key == key
next()
else
queue = (item for item in queue when item.key != key)
current = ->
if tourRunning then nil else queue[index]
startTour = ->
close()
tourRunning = true
for stop, i in tour
options = $.extend({}, defaultHelpOptions, stop, key: "PI:KEY:<KEY>END_PIi}")
queue.push(options)
showCurrent()
exports =
add: add
remove: remove
current: current
next: next
prev: prev
close: close
startTour: startTour
|
[
{
"context": " true\n keys:\n user:\n title: \"Username\"\n description: \"the username to log into",
"end": 2750,
"score": 0.887231171131134,
"start": 2742,
"tag": "USERNAME",
"value": "Username"
},
{
"context": "ype: 'string'\n password:\n title: \"Password\"\n description: \"the password for login\"\n",
"end": 2878,
"score": 0.9809101223945618,
"start": 2870,
"tag": "PASSWORD",
"value": "Password"
}
] | src/configSchema.coffee | alinex/node-mailman | 2 | # Configuration Schema
# =================================================
email = require('alinex-mail/lib/configSchema.js').email
# Complete Schema Definition
# -------------------------------------------------
command =
title: "Command Setup"
description: "the definition of a single command to execute"
type: 'object'
allowedKeys: true
keys:
title:
title: "Title"
description: "the short title of the job to be used in display"
type: 'string'
description:
title: "Description"
description: "a short abstract of what this job will retrieve"
type: 'string'
filter:
title: "Filter Conditions"
description: "the conditions to filter mails which are seen as linked to
this command"
type: 'object'
allowedKeys: true
keys:
subject:
title: "Subject"
description: "the case insenitive part of the subject which must be there"
type: 'string'
from:
title: "Allowed Sender"
description: "the list of allowed users by name part of the email address"
type: 'array'
toArray: true
entries:
type: 'string'
lowerCase: true
variables:
type: 'object'
entries: [
type: 'object'
mandatoryKeys: ['type']
keys:
type:
type: 'string'
]
exec:
title: "Commandline"
description: "the real call on commandline"
type: 'object'
allowedKeys: true
mandatoryKeys: ['cmd']
keys:
cmd:
title: "Executable"
description: "the executable to run"
type: 'string'
args:
title: "Parameters"
description: "the parameters to send"
type: 'array'
toArray: true
entries:
type: 'handlebars'
env:
title: "Environment Settings"
description: "the environment settings"
type: 'object'
cwd:
title: "Working Directory"
description: "the directory in which to start the process"
type: 'string'
email: email
emailOnlyOnError:
title: "Email only on Error"
description: "the flag to send email only on error"
type: 'boolean'
# Complete Schema Definition
# -------------------------------------------------
module.exports =
title: "Mailman Setup"
description: "the configuration for the mail manager system"
type: 'object'
allowedKeys: true
keys:
mailcheck:
title: "IMAP Setup"
description: "the mailserver on which to check for new commands"
type: 'object'
allowedKeys: true
keys:
user:
title: "Username"
description: "the username to log into server"
type: 'string'
password:
title: "Password"
description: "the password for login"
type: 'string'
host:
title: "Hostname or IP"
description: "the imap host"
type: 'hostname'
port:
title: "Port"
description: "the port number to use for connection"
type: 'port'
optional: true
tls:
title: "Secure Login"
description: "a flag to use secure login over TLS"
type: 'boolean'
default: false
autotls:
title: "TLS Upgrade"
description: "the value decides when to upgrade to a secure session"
type: 'string'
values: ['always', 'required', 'never']
default: 'never'
connTimeout:
title: "Connection Timeout"
description: "the time in milliseconds to wait to establish connection"
type: 'interval'
min: 100
default: 10000
authTimeout:
title: "Authentication Timeout"
description: "the time in milliseconds to wait to authenticate user"
type: 'interval'
min: 100
default: 5000
command:
title: "Command Setup"
description: "the configuration for the calling command"
type: 'object'
allowedKeys: true
entries: [command]
email:
title: "Email Templates"
description: "the possible templates used for sending emails"
type: 'object'
entries: [email]
daemon:
title: "Setup Daemon"
description: "the setup of the daemon mode"
type: 'object'
allowedKeys: true
keys:
maxJobs:
title: "Number of Jobs"
description: "the maximum number of jobs to run"
type: 'integer'
min: 1
default: 5
interval:
title: "Check Interval"
description: "the time to recheck for new emails in daemon mode"
type: 'interval'
default: 300000
| 28172 | # Configuration Schema
# =================================================
email = require('alinex-mail/lib/configSchema.js').email
# Complete Schema Definition
# -------------------------------------------------
command =
title: "Command Setup"
description: "the definition of a single command to execute"
type: 'object'
allowedKeys: true
keys:
title:
title: "Title"
description: "the short title of the job to be used in display"
type: 'string'
description:
title: "Description"
description: "a short abstract of what this job will retrieve"
type: 'string'
filter:
title: "Filter Conditions"
description: "the conditions to filter mails which are seen as linked to
this command"
type: 'object'
allowedKeys: true
keys:
subject:
title: "Subject"
description: "the case insenitive part of the subject which must be there"
type: 'string'
from:
title: "Allowed Sender"
description: "the list of allowed users by name part of the email address"
type: 'array'
toArray: true
entries:
type: 'string'
lowerCase: true
variables:
type: 'object'
entries: [
type: 'object'
mandatoryKeys: ['type']
keys:
type:
type: 'string'
]
exec:
title: "Commandline"
description: "the real call on commandline"
type: 'object'
allowedKeys: true
mandatoryKeys: ['cmd']
keys:
cmd:
title: "Executable"
description: "the executable to run"
type: 'string'
args:
title: "Parameters"
description: "the parameters to send"
type: 'array'
toArray: true
entries:
type: 'handlebars'
env:
title: "Environment Settings"
description: "the environment settings"
type: 'object'
cwd:
title: "Working Directory"
description: "the directory in which to start the process"
type: 'string'
email: email
emailOnlyOnError:
title: "Email only on Error"
description: "the flag to send email only on error"
type: 'boolean'
# Complete Schema Definition
# -------------------------------------------------
module.exports =
title: "Mailman Setup"
description: "the configuration for the mail manager system"
type: 'object'
allowedKeys: true
keys:
mailcheck:
title: "IMAP Setup"
description: "the mailserver on which to check for new commands"
type: 'object'
allowedKeys: true
keys:
user:
title: "Username"
description: "the username to log into server"
type: 'string'
password:
title: "<PASSWORD>"
description: "the password for login"
type: 'string'
host:
title: "Hostname or IP"
description: "the imap host"
type: 'hostname'
port:
title: "Port"
description: "the port number to use for connection"
type: 'port'
optional: true
tls:
title: "Secure Login"
description: "a flag to use secure login over TLS"
type: 'boolean'
default: false
autotls:
title: "TLS Upgrade"
description: "the value decides when to upgrade to a secure session"
type: 'string'
values: ['always', 'required', 'never']
default: 'never'
connTimeout:
title: "Connection Timeout"
description: "the time in milliseconds to wait to establish connection"
type: 'interval'
min: 100
default: 10000
authTimeout:
title: "Authentication Timeout"
description: "the time in milliseconds to wait to authenticate user"
type: 'interval'
min: 100
default: 5000
command:
title: "Command Setup"
description: "the configuration for the calling command"
type: 'object'
allowedKeys: true
entries: [command]
email:
title: "Email Templates"
description: "the possible templates used for sending emails"
type: 'object'
entries: [email]
daemon:
title: "Setup Daemon"
description: "the setup of the daemon mode"
type: 'object'
allowedKeys: true
keys:
maxJobs:
title: "Number of Jobs"
description: "the maximum number of jobs to run"
type: 'integer'
min: 1
default: 5
interval:
title: "Check Interval"
description: "the time to recheck for new emails in daemon mode"
type: 'interval'
default: 300000
| true | # Configuration Schema
# =================================================
email = require('alinex-mail/lib/configSchema.js').email
# Complete Schema Definition
# -------------------------------------------------
command =
title: "Command Setup"
description: "the definition of a single command to execute"
type: 'object'
allowedKeys: true
keys:
title:
title: "Title"
description: "the short title of the job to be used in display"
type: 'string'
description:
title: "Description"
description: "a short abstract of what this job will retrieve"
type: 'string'
filter:
title: "Filter Conditions"
description: "the conditions to filter mails which are seen as linked to
this command"
type: 'object'
allowedKeys: true
keys:
subject:
title: "Subject"
description: "the case insenitive part of the subject which must be there"
type: 'string'
from:
title: "Allowed Sender"
description: "the list of allowed users by name part of the email address"
type: 'array'
toArray: true
entries:
type: 'string'
lowerCase: true
variables:
type: 'object'
entries: [
type: 'object'
mandatoryKeys: ['type']
keys:
type:
type: 'string'
]
exec:
title: "Commandline"
description: "the real call on commandline"
type: 'object'
allowedKeys: true
mandatoryKeys: ['cmd']
keys:
cmd:
title: "Executable"
description: "the executable to run"
type: 'string'
args:
title: "Parameters"
description: "the parameters to send"
type: 'array'
toArray: true
entries:
type: 'handlebars'
env:
title: "Environment Settings"
description: "the environment settings"
type: 'object'
cwd:
title: "Working Directory"
description: "the directory in which to start the process"
type: 'string'
email: email
emailOnlyOnError:
title: "Email only on Error"
description: "the flag to send email only on error"
type: 'boolean'
# Complete Schema Definition
# -------------------------------------------------
module.exports =
title: "Mailman Setup"
description: "the configuration for the mail manager system"
type: 'object'
allowedKeys: true
keys:
mailcheck:
title: "IMAP Setup"
description: "the mailserver on which to check for new commands"
type: 'object'
allowedKeys: true
keys:
user:
title: "Username"
description: "the username to log into server"
type: 'string'
password:
title: "PI:PASSWORD:<PASSWORD>END_PI"
description: "the password for login"
type: 'string'
host:
title: "Hostname or IP"
description: "the imap host"
type: 'hostname'
port:
title: "Port"
description: "the port number to use for connection"
type: 'port'
optional: true
tls:
title: "Secure Login"
description: "a flag to use secure login over TLS"
type: 'boolean'
default: false
autotls:
title: "TLS Upgrade"
description: "the value decides when to upgrade to a secure session"
type: 'string'
values: ['always', 'required', 'never']
default: 'never'
connTimeout:
title: "Connection Timeout"
description: "the time in milliseconds to wait to establish connection"
type: 'interval'
min: 100
default: 10000
authTimeout:
title: "Authentication Timeout"
description: "the time in milliseconds to wait to authenticate user"
type: 'interval'
min: 100
default: 5000
command:
title: "Command Setup"
description: "the configuration for the calling command"
type: 'object'
allowedKeys: true
entries: [command]
email:
title: "Email Templates"
description: "the possible templates used for sending emails"
type: 'object'
entries: [email]
daemon:
title: "Setup Daemon"
description: "the setup of the daemon mode"
type: 'object'
allowedKeys: true
keys:
maxJobs:
title: "Number of Jobs"
description: "the maximum number of jobs to run"
type: 'integer'
min: 1
default: 5
interval:
title: "Check Interval"
description: "the time to recheck for new emails in daemon mode"
type: 'interval'
default: 300000
|
[
{
"context": "exports =\n classic:\n move:\n key: 'classic-move'\n src: classicDir + 'move.wav'\n rotate:\n ",
"end": 129,
"score": 0.6950150728225708,
"start": 125,
"tag": "KEY",
"value": "move"
},
{
"context": ": classicDir + 'move.wav'\n rotate:\n key: 'classic-rotate'\n src: classicDir + 'rotate.wav'\n f",
"end": 198,
"score": 0.6934466361999512,
"start": 190,
"tag": "KEY",
"value": "classic-"
},
{
"context": " classicDir + 'rotate.wav'\n fixed:\n key: 'classic-fixed'\n src: classicDir + 'fixed.wav'\n end:\n ",
"end": 279,
"score": 0.7305261492729187,
"start": 266,
"tag": "KEY",
"value": "classic-fixed"
},
{
"context": "rc: classicDir + 'fixed.wav'\n end:\n key: 'classic-end'\n src: classicDir + 'end.mp3'\n",
"end": 349,
"score": 0.685617983341217,
"start": 338,
"tag": "KEY",
"value": "classic-end"
}
] | app/coffee/tetris/player/player-sounds.coffee | tanguymario/Phaser-Tetris | 0 | mainDir = 'assets/snd/effects/'
classicDir = mainDir + 'classic/'
module.exports =
classic:
move:
key: 'classic-move'
src: classicDir + 'move.wav'
rotate:
key: 'classic-rotate'
src: classicDir + 'rotate.wav'
fixed:
key: 'classic-fixed'
src: classicDir + 'fixed.wav'
end:
key: 'classic-end'
src: classicDir + 'end.mp3'
| 56587 | mainDir = 'assets/snd/effects/'
classicDir = mainDir + 'classic/'
module.exports =
classic:
move:
key: 'classic-<KEY>'
src: classicDir + 'move.wav'
rotate:
key: '<KEY>rotate'
src: classicDir + 'rotate.wav'
fixed:
key: '<KEY>'
src: classicDir + 'fixed.wav'
end:
key: '<KEY>'
src: classicDir + 'end.mp3'
| true | mainDir = 'assets/snd/effects/'
classicDir = mainDir + 'classic/'
module.exports =
classic:
move:
key: 'classic-PI:KEY:<KEY>END_PI'
src: classicDir + 'move.wav'
rotate:
key: 'PI:KEY:<KEY>END_PIrotate'
src: classicDir + 'rotate.wav'
fixed:
key: 'PI:KEY:<KEY>END_PI'
src: classicDir + 'fixed.wav'
end:
key: 'PI:KEY:<KEY>END_PI'
src: classicDir + 'end.mp3'
|
[
{
"context": "STER_PASSWORD set! Run again with MASTER_PASSWORD=yourcrazypassword\")\n process.exit(1)\n\nsockets = []\nwaitingForContr",
"end": 300,
"score": 0.9989976286888123,
"start": 283,
"tag": "PASSWORD",
"value": "yourcrazypassword"
},
{
"context": "authentication: ({password}) =>\n if password is MASTER_PASSWORD\n @socket.emit('authentication-success')\n ",
"end": 5071,
"score": 0.5954070091247559,
"start": 5056,
"tag": "PASSWORD",
"value": "MASTER_PASSWORD"
}
] | index.coffee | socoded/so-slot-car-socket | 2 | fs = require('fs')
io = require("socket.io").listen(12346)
track = io.of("/track")
master = io.of("/master")
MASTER_PASSWORD = process.env.MASTER_PASSWORD
if !MASTER_PASSWORD? or MASTER_PASSWORD.match(/^\s*$/)
console.error("No MASTER_PASSWORD set! Run again with MASTER_PASSWORD=yourcrazypassword")
process.exit(1)
sockets = []
waitingForControll = []
controllers = []
ArrayHelper =
removeFromLists: (item, lists...) ->
ArrayHelper.removeFromList(item, list) for list in lists
removeFromList: (item, list) ->
index = list.indexOf(item)
return if index < 0
list.splice(index, 1)
SerialPort = require("serialport").SerialPort
class Controllers
constructor: ->
@controllerCodes = {
0: 's'
1: 't'
}
@angles = {}
@angleConfig = {}
for controller, code of @controllerCodes
@angles[controller] = 0
@angleConfig[controller] = {min: 0, max: 10}
@configFile = __dirname + '/angle_config.json'
@loadConfig()
reset: (device) =>
@serialOptions = {baudrate: 19200, databits: 8, stopbits: 1, parity: 'none'}
@device = device
@openSerialPort()
openSerialPort: =>
@serialPort.close() if @serialPort?
@serialPort = new SerialPort @device, @serialOptions
@resetAngleSettings()
resetAngleSettings: =>
@serialPort.write 'r'
@serialPort.flush()
override: (controller) =>
@overrides ||= {}
@overrides[controller] = true
release: (controller) =>
return unless @overrides?
delete @overrides[controller]
reconnect: =>
return unless @isReady()
@openSerialPort()
isReady: =>
@serialPort?
isOverridden: (controller) =>
return false unless @overrides?
@overrides[controller]
setThrust: (controller, thrust) =>
controllerCode = @controllerCodes[controller]
return unless controllerCode?
thrust = Math.max(0, thrust)
thrust = Math.min(1, thrust)
angelConfig = @angleConfig[controller]
way = 1.0 * angelConfig.max - angelConfig.min
angle = angelConfig.min + (way * thrust)
@setAngle(controller, angle)
setAngle: (controller, angle) =>
controllerCode = @controllerCodes[controller]
return unless controllerCode?
angle = parseInt(angle, 10)
console.log("SET ANGLE", controller, angle)
@serialPort.write "#{angle}#{controllerCode}"
@serialPort.flush()
@angles[controller] = angle
setMax: (controller, angle) =>
@angleConfig[controller].max = angle
@saveConfig()
setMin: (controller, angle) =>
@angleConfig[controller].min = angle
@saveConfig()
saveConfig: =>
fs.writeFile(@configFile, JSON.stringify(@angleConfig))
loadConfig: =>
return unless fs.existsSync(@configFile)
fs.readFile @configFile, (err, data) =>
return if err?
@angleConfig = JSON.parse(data)
controllers = new Controllers
class ClientManager
constructor: (@rawControllers)->
@clients = []
@waitingForControll = []
@controllers = []
clientConnected: (socket) =>
client = new Client(@, socket)
@clients.push client
socket.on 'controller-proposal', => @receiveControllerProposal(client)
socket.on 'thrust', ({thrust}) =>
@rawControllers.setThrust(client.trackNo, thrust) if @isController(client)
socket.emit('controller-auction') if @controllers.length < 2
clientDisconnected: (client) =>
wasController = @isController(client)
console.log("OLD CONTROLLERS", @controllers.length)
ArrayHelper.removeFromLists(client, @clients, @waitingForControll, @controllers)
console.log("NEW CONTROLLERS", @controllers.length)
if wasController
client.socket.emit('controller-auction') for client in @clients when !@isController(client)
receiveControllerProposal: (client) =>
return if @controllers.length > 1
newTrackNo = 0
if @controllers.length > 0
newTrackNo = if @controllers[0].trackNo is 1 then 0 else 1
client.trackNo = newTrackNo
@controllers.push(client)
console.log("ACCEPTED AS", @controllers.length, client.trackNo, newTrackNo)
client.socket.emit('accepted-as-controller', track: client.trackNo)
isController: (client) =>
@controllers.indexOf(client) >= 0
class Client
constructor: (@manager, @socket) ->
@socket.on "disconnect", @disconnected
disconnected: =>
@manager.clientDisconnected(@)
class Master
constructor: (@socket, @controllers) ->
@socket.on 'authentication-response', @authentication
@socket.on 'list-devices', @listDevices
@socket.on 'get-status', @getStatus
@socket.on 'get-overrides', @getOverrides
@socket.on 'get-angle-config', @getAngleConfig
@socket.on 'setup', @setup
@socket.on 'override', @override
@socket.on 'release', @release
@socket.on 'set-angle', @setAngle
@socket.on 'reconnect', @reconnect
@socket.on 'set-max', @setMax
@socket.on 'set-min', @setMin
@socket.on 'reset-angle-settings', @resetAngleSettings
@socket.emit('authentication-challenge')
authentication: ({password}) =>
if password is MASTER_PASSWORD
@socket.emit('authentication-success')
else
@socket.emit('authentication-failed')
@socket.disconnect()
listDevices: =>
fs.readdir '/dev', (err, files) =>
return if err?
realFiles = []
realFiles.push file for file in files when file.match(/usb/i)
@socket.emit('devices-list', devices: realFiles)
getStatus: =>
@socket.emit('status-update', ready: @controllers.isReady())
getOverrides: =>
@socket.emit('overrides-update', overrides: @controllers.overrides || {})
getAngleConfig: =>
@socket.emit('angle-config-update', angleConfig: @controllers.angleConfig)
setup: ({device}) =>
@controllers.reset("/dev/#{device}")
@getStatus()
override: ({controller}) =>
@controllers.override(controller)
@getOverrides()
release: ({controller}) =>
@controllers.release(controller)
@getOverrides()
setAngle: ({controller, angle}) =>
return unless @controllers.isOverridden(controller)
@controllers.setAngle(controller, angle)
reconnect: =>
@controllers.reconnect()
setMax: ({controller, angle}) =>
@controllers.setMax(controller, angle)
@getAngleConfig()
setMin: ({controller, angle}) =>
@controllers.setMin(controller, angle)
@getAngleConfig()
resetAngleSettings: =>
@controllers.resetAngleSettings()
clientManager = new ClientManager(controllers)
track.on "connection", clientManager.clientConnected
master.on "connection", (socket) ->
new Master(socket, controllers) | 92989 | fs = require('fs')
io = require("socket.io").listen(12346)
track = io.of("/track")
master = io.of("/master")
MASTER_PASSWORD = process.env.MASTER_PASSWORD
if !MASTER_PASSWORD? or MASTER_PASSWORD.match(/^\s*$/)
console.error("No MASTER_PASSWORD set! Run again with MASTER_PASSWORD=<PASSWORD>")
process.exit(1)
sockets = []
waitingForControll = []
controllers = []
ArrayHelper =
removeFromLists: (item, lists...) ->
ArrayHelper.removeFromList(item, list) for list in lists
removeFromList: (item, list) ->
index = list.indexOf(item)
return if index < 0
list.splice(index, 1)
SerialPort = require("serialport").SerialPort
class Controllers
constructor: ->
@controllerCodes = {
0: 's'
1: 't'
}
@angles = {}
@angleConfig = {}
for controller, code of @controllerCodes
@angles[controller] = 0
@angleConfig[controller] = {min: 0, max: 10}
@configFile = __dirname + '/angle_config.json'
@loadConfig()
reset: (device) =>
@serialOptions = {baudrate: 19200, databits: 8, stopbits: 1, parity: 'none'}
@device = device
@openSerialPort()
openSerialPort: =>
@serialPort.close() if @serialPort?
@serialPort = new SerialPort @device, @serialOptions
@resetAngleSettings()
resetAngleSettings: =>
@serialPort.write 'r'
@serialPort.flush()
override: (controller) =>
@overrides ||= {}
@overrides[controller] = true
release: (controller) =>
return unless @overrides?
delete @overrides[controller]
reconnect: =>
return unless @isReady()
@openSerialPort()
isReady: =>
@serialPort?
isOverridden: (controller) =>
return false unless @overrides?
@overrides[controller]
setThrust: (controller, thrust) =>
controllerCode = @controllerCodes[controller]
return unless controllerCode?
thrust = Math.max(0, thrust)
thrust = Math.min(1, thrust)
angelConfig = @angleConfig[controller]
way = 1.0 * angelConfig.max - angelConfig.min
angle = angelConfig.min + (way * thrust)
@setAngle(controller, angle)
setAngle: (controller, angle) =>
controllerCode = @controllerCodes[controller]
return unless controllerCode?
angle = parseInt(angle, 10)
console.log("SET ANGLE", controller, angle)
@serialPort.write "#{angle}#{controllerCode}"
@serialPort.flush()
@angles[controller] = angle
setMax: (controller, angle) =>
@angleConfig[controller].max = angle
@saveConfig()
setMin: (controller, angle) =>
@angleConfig[controller].min = angle
@saveConfig()
saveConfig: =>
fs.writeFile(@configFile, JSON.stringify(@angleConfig))
loadConfig: =>
return unless fs.existsSync(@configFile)
fs.readFile @configFile, (err, data) =>
return if err?
@angleConfig = JSON.parse(data)
controllers = new Controllers
class ClientManager
constructor: (@rawControllers)->
@clients = []
@waitingForControll = []
@controllers = []
clientConnected: (socket) =>
client = new Client(@, socket)
@clients.push client
socket.on 'controller-proposal', => @receiveControllerProposal(client)
socket.on 'thrust', ({thrust}) =>
@rawControllers.setThrust(client.trackNo, thrust) if @isController(client)
socket.emit('controller-auction') if @controllers.length < 2
clientDisconnected: (client) =>
wasController = @isController(client)
console.log("OLD CONTROLLERS", @controllers.length)
ArrayHelper.removeFromLists(client, @clients, @waitingForControll, @controllers)
console.log("NEW CONTROLLERS", @controllers.length)
if wasController
client.socket.emit('controller-auction') for client in @clients when !@isController(client)
receiveControllerProposal: (client) =>
return if @controllers.length > 1
newTrackNo = 0
if @controllers.length > 0
newTrackNo = if @controllers[0].trackNo is 1 then 0 else 1
client.trackNo = newTrackNo
@controllers.push(client)
console.log("ACCEPTED AS", @controllers.length, client.trackNo, newTrackNo)
client.socket.emit('accepted-as-controller', track: client.trackNo)
isController: (client) =>
@controllers.indexOf(client) >= 0
class Client
constructor: (@manager, @socket) ->
@socket.on "disconnect", @disconnected
disconnected: =>
@manager.clientDisconnected(@)
class Master
constructor: (@socket, @controllers) ->
@socket.on 'authentication-response', @authentication
@socket.on 'list-devices', @listDevices
@socket.on 'get-status', @getStatus
@socket.on 'get-overrides', @getOverrides
@socket.on 'get-angle-config', @getAngleConfig
@socket.on 'setup', @setup
@socket.on 'override', @override
@socket.on 'release', @release
@socket.on 'set-angle', @setAngle
@socket.on 'reconnect', @reconnect
@socket.on 'set-max', @setMax
@socket.on 'set-min', @setMin
@socket.on 'reset-angle-settings', @resetAngleSettings
@socket.emit('authentication-challenge')
authentication: ({password}) =>
if password is <PASSWORD>
@socket.emit('authentication-success')
else
@socket.emit('authentication-failed')
@socket.disconnect()
listDevices: =>
fs.readdir '/dev', (err, files) =>
return if err?
realFiles = []
realFiles.push file for file in files when file.match(/usb/i)
@socket.emit('devices-list', devices: realFiles)
getStatus: =>
@socket.emit('status-update', ready: @controllers.isReady())
getOverrides: =>
@socket.emit('overrides-update', overrides: @controllers.overrides || {})
getAngleConfig: =>
@socket.emit('angle-config-update', angleConfig: @controllers.angleConfig)
setup: ({device}) =>
@controllers.reset("/dev/#{device}")
@getStatus()
override: ({controller}) =>
@controllers.override(controller)
@getOverrides()
release: ({controller}) =>
@controllers.release(controller)
@getOverrides()
setAngle: ({controller, angle}) =>
return unless @controllers.isOverridden(controller)
@controllers.setAngle(controller, angle)
reconnect: =>
@controllers.reconnect()
setMax: ({controller, angle}) =>
@controllers.setMax(controller, angle)
@getAngleConfig()
setMin: ({controller, angle}) =>
@controllers.setMin(controller, angle)
@getAngleConfig()
resetAngleSettings: =>
@controllers.resetAngleSettings()
clientManager = new ClientManager(controllers)
track.on "connection", clientManager.clientConnected
master.on "connection", (socket) ->
new Master(socket, controllers) | true | fs = require('fs')
io = require("socket.io").listen(12346)
track = io.of("/track")
master = io.of("/master")
MASTER_PASSWORD = process.env.MASTER_PASSWORD
if !MASTER_PASSWORD? or MASTER_PASSWORD.match(/^\s*$/)
console.error("No MASTER_PASSWORD set! Run again with MASTER_PASSWORD=PI:PASSWORD:<PASSWORD>END_PI")
process.exit(1)
sockets = []
waitingForControll = []
controllers = []
ArrayHelper =
removeFromLists: (item, lists...) ->
ArrayHelper.removeFromList(item, list) for list in lists
removeFromList: (item, list) ->
index = list.indexOf(item)
return if index < 0
list.splice(index, 1)
SerialPort = require("serialport").SerialPort
class Controllers
constructor: ->
@controllerCodes = {
0: 's'
1: 't'
}
@angles = {}
@angleConfig = {}
for controller, code of @controllerCodes
@angles[controller] = 0
@angleConfig[controller] = {min: 0, max: 10}
@configFile = __dirname + '/angle_config.json'
@loadConfig()
reset: (device) =>
@serialOptions = {baudrate: 19200, databits: 8, stopbits: 1, parity: 'none'}
@device = device
@openSerialPort()
openSerialPort: =>
@serialPort.close() if @serialPort?
@serialPort = new SerialPort @device, @serialOptions
@resetAngleSettings()
resetAngleSettings: =>
@serialPort.write 'r'
@serialPort.flush()
override: (controller) =>
@overrides ||= {}
@overrides[controller] = true
release: (controller) =>
return unless @overrides?
delete @overrides[controller]
reconnect: =>
return unless @isReady()
@openSerialPort()
isReady: =>
@serialPort?
isOverridden: (controller) =>
return false unless @overrides?
@overrides[controller]
setThrust: (controller, thrust) =>
controllerCode = @controllerCodes[controller]
return unless controllerCode?
thrust = Math.max(0, thrust)
thrust = Math.min(1, thrust)
angelConfig = @angleConfig[controller]
way = 1.0 * angelConfig.max - angelConfig.min
angle = angelConfig.min + (way * thrust)
@setAngle(controller, angle)
setAngle: (controller, angle) =>
controllerCode = @controllerCodes[controller]
return unless controllerCode?
angle = parseInt(angle, 10)
console.log("SET ANGLE", controller, angle)
@serialPort.write "#{angle}#{controllerCode}"
@serialPort.flush()
@angles[controller] = angle
setMax: (controller, angle) =>
@angleConfig[controller].max = angle
@saveConfig()
setMin: (controller, angle) =>
@angleConfig[controller].min = angle
@saveConfig()
saveConfig: =>
fs.writeFile(@configFile, JSON.stringify(@angleConfig))
loadConfig: =>
return unless fs.existsSync(@configFile)
fs.readFile @configFile, (err, data) =>
return if err?
@angleConfig = JSON.parse(data)
controllers = new Controllers
class ClientManager
constructor: (@rawControllers)->
@clients = []
@waitingForControll = []
@controllers = []
clientConnected: (socket) =>
client = new Client(@, socket)
@clients.push client
socket.on 'controller-proposal', => @receiveControllerProposal(client)
socket.on 'thrust', ({thrust}) =>
@rawControllers.setThrust(client.trackNo, thrust) if @isController(client)
socket.emit('controller-auction') if @controllers.length < 2
clientDisconnected: (client) =>
wasController = @isController(client)
console.log("OLD CONTROLLERS", @controllers.length)
ArrayHelper.removeFromLists(client, @clients, @waitingForControll, @controllers)
console.log("NEW CONTROLLERS", @controllers.length)
if wasController
client.socket.emit('controller-auction') for client in @clients when !@isController(client)
receiveControllerProposal: (client) =>
return if @controllers.length > 1
newTrackNo = 0
if @controllers.length > 0
newTrackNo = if @controllers[0].trackNo is 1 then 0 else 1
client.trackNo = newTrackNo
@controllers.push(client)
console.log("ACCEPTED AS", @controllers.length, client.trackNo, newTrackNo)
client.socket.emit('accepted-as-controller', track: client.trackNo)
isController: (client) =>
@controllers.indexOf(client) >= 0
class Client
constructor: (@manager, @socket) ->
@socket.on "disconnect", @disconnected
disconnected: =>
@manager.clientDisconnected(@)
class Master
constructor: (@socket, @controllers) ->
@socket.on 'authentication-response', @authentication
@socket.on 'list-devices', @listDevices
@socket.on 'get-status', @getStatus
@socket.on 'get-overrides', @getOverrides
@socket.on 'get-angle-config', @getAngleConfig
@socket.on 'setup', @setup
@socket.on 'override', @override
@socket.on 'release', @release
@socket.on 'set-angle', @setAngle
@socket.on 'reconnect', @reconnect
@socket.on 'set-max', @setMax
@socket.on 'set-min', @setMin
@socket.on 'reset-angle-settings', @resetAngleSettings
@socket.emit('authentication-challenge')
authentication: ({password}) =>
if password is PI:PASSWORD:<PASSWORD>END_PI
@socket.emit('authentication-success')
else
@socket.emit('authentication-failed')
@socket.disconnect()
listDevices: =>
fs.readdir '/dev', (err, files) =>
return if err?
realFiles = []
realFiles.push file for file in files when file.match(/usb/i)
@socket.emit('devices-list', devices: realFiles)
getStatus: =>
@socket.emit('status-update', ready: @controllers.isReady())
getOverrides: =>
@socket.emit('overrides-update', overrides: @controllers.overrides || {})
getAngleConfig: =>
@socket.emit('angle-config-update', angleConfig: @controllers.angleConfig)
setup: ({device}) =>
@controllers.reset("/dev/#{device}")
@getStatus()
override: ({controller}) =>
@controllers.override(controller)
@getOverrides()
release: ({controller}) =>
@controllers.release(controller)
@getOverrides()
setAngle: ({controller, angle}) =>
return unless @controllers.isOverridden(controller)
@controllers.setAngle(controller, angle)
reconnect: =>
@controllers.reconnect()
setMax: ({controller, angle}) =>
@controllers.setMax(controller, angle)
@getAngleConfig()
setMin: ({controller, angle}) =>
@controllers.setMin(controller, angle)
@getAngleConfig()
resetAngleSettings: =>
@controllers.resetAngleSettings()
clientManager = new ClientManager(controllers)
track.on "connection", clientManager.clientConnected
master.on "connection", (socket) ->
new Master(socket, controllers) |
[
{
"context": "s\" : {\n \"def\" : [ {\n \"name\" : \"Patient\",\n \"context\" : \"Patient\",\n ",
"end": 895,
"score": 0.9995624423027039,
"start": 888,
"tag": "NAME",
"value": "Patient"
},
{
"context": " \"localId\" : \"3\",\n \"name\" : \"Foo\",\n \"context\" : \"Patient\",\n ",
"end": 1298,
"score": 0.999765932559967,
"start": 1295,
"tag": "NAME",
"value": "Foo"
},
{
"context": "s\" : {\n \"def\" : [ {\n \"name\" : \"Patient\",\n \"context\" : \"Patient\",\n ",
"end": 2733,
"score": 0.999230146408081,
"start": 2726,
"tag": "NAME",
"value": "Patient"
},
{
"context": " \"localId\" : \"3\",\n \"name\" : \"Life\",\n \"context\" : \"Patient\",\n ",
"end": 3137,
"score": 0.9979442954063416,
"start": 3133,
"tag": "NAME",
"value": "Life"
},
{
"context": " \"localId\" : \"5\",\n \"name\" : \"Foo\",\n \"context\" : \"Patient\",\n ",
"end": 3786,
"score": 0.9996390342712402,
"start": 3783,
"tag": "NAME",
"value": "Foo"
},
{
"context": " \"localId\" : \"4\",\n \"name\" : \"Life\",\n \"type\" : \"ExpressionRef\"\n ",
"end": 4369,
"score": 0.997921347618103,
"start": 4365,
"tag": "NAME",
"value": "Life"
},
{
"context": "rary\" : {\n \"identifier\" : {\n \"id\" : \"TestSnippet\",\n \"version\" : \"1\"\n },\n ",
"end": 4740,
"score": 0.6465609669685364,
"start": 4736,
"tag": "NAME",
"value": "Test"
},
{
"context": "s\" : {\n \"def\" : [ {\n \"name\" : \"Patient\",\n \"context\" : \"Patient\",\n ",
"end": 5233,
"score": 0.9906044602394104,
"start": 5226,
"tag": "NAME",
"value": "Patient"
},
{
"context": " \"localId\" : \"7\",\n \"name\" : \"foo bar\",\n \"context\" : \"Patient\",\n ",
"end": 5640,
"score": 0.9971359968185425,
"start": 5633,
"tag": "NAME",
"value": "foo bar"
},
{
"context": " \"localId\" : \"4\",\n \"name\" : \"a\",\n \"type\" : \"OperandRef\"\n ",
"end": 7302,
"score": 0.9659749865531921,
"start": 7301,
"tag": "NAME",
"value": "a"
},
{
"context": " \"localId\" : \"5\",\n \"name\" : \"b\",\n \"type\" : \"OperandRef\"\n ",
"end": 7429,
"score": 0.9817615747451782,
"start": 7428,
"tag": "NAME",
"value": "b"
},
{
"context": " \"operand\" : [ {\n \"name\" : \"a\",\n \"operandTypeSpecifier\" : {\n ",
"end": 7560,
"score": 0.8049078583717346,
"start": 7559,
"tag": "NAME",
"value": "a"
},
{
"context": " }\n }, {\n \"name\" : \"b\",\n \"operandTypeSpecifier\" : {\n ",
"end": 7812,
"score": 0.7845683097839355,
"start": 7811,
"tag": "NAME",
"value": "b"
},
{
"context": " \"localId\" : \"11\",\n \"name\" : \"testValue\",\n \"context\" : \"Patient\",\n ",
"end": 8112,
"score": 0.9944121837615967,
"start": 8103,
"tag": "NAME",
"value": "testValue"
},
{
"context": "s\" : {\n \"def\" : [ {\n \"name\" : \"Patient\",\n \"context\" : \"Patient\",\n ",
"end": 10142,
"score": 0.9996687173843384,
"start": 10135,
"tag": "NAME",
"value": "Patient"
},
{
"context": " \"localId\" : \"6\",\n \"name\" : \"foo bar\",\n \"context\" : \"Patient\",\n ",
"end": 10549,
"score": 0.9974985122680664,
"start": 10542,
"tag": "NAME",
"value": "foo bar"
},
{
"context": " \"localId\" : \"3\",\n \"name\" : \"a\",\n \"type\" : \"OperandRef\"\n ",
"end": 11854,
"score": 0.9683415293693542,
"start": 11853,
"tag": "NAME",
"value": "a"
},
{
"context": " \"localId\" : \"11\",\n \"name\" : \"foo bar\",\n \"context\" : \"Patient\",\n ",
"end": 12477,
"score": 0.9987155795097351,
"start": 12470,
"tag": "NAME",
"value": "foo bar"
},
{
"context": " \"localId\" : \"9\",\n \"name\" : \"a\",\n \"type\" : \"OperandRef\"\n ",
"end": 14139,
"score": 0.9057295918464661,
"start": 14138,
"tag": "NAME",
"value": "a"
},
{
"context": " \"localId\" : \"14\",\n \"name\" : \"testValue1\",\n \"context\" : \"Patient\",\n ",
"end": 14570,
"score": 0.7012388706207275,
"start": 14560,
"tag": "NAME",
"value": "testValue1"
},
{
"context": " \"localId\" : \"13\",\n \"name\" : \"foo bar\",\n \"type\" : \"FunctionRef\",\n ",
"end": 15221,
"score": 0.9990177750587463,
"start": 15214,
"tag": "NAME",
"value": "foo bar"
},
{
"context": " \"localId\" : \"17\",\n \"name\" : \"testValue2\",\n \"context\" : \"Patient\",\n ",
"end": 15578,
"score": 0.981835126876831,
"start": 15568,
"tag": "NAME",
"value": "testValue2"
},
{
"context": " \"localId\" : \"16\",\n \"name\" : \"foo bar\",\n \"type\" : \"FunctionRef\",\n ",
"end": 16428,
"score": 0.9991161227226257,
"start": 16421,
"tag": "NAME",
"value": "foo bar"
}
] | test/elm/reusable/data.coffee | luis1van/cql-execution-1 | 0 | ###
WARNING: This is a GENERATED file. Do not manually edit!
To generate this file:
- Edit data.cql to add a CQL Snippet
- From java dir: ./gradlew :cql-to-elm:generateTestData
###
### ExpressionDef
library TestSnippet version '1'
using QUICK
context Patient
define Foo: 'Bar'
###
module.exports['ExpressionDef'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localId" : "1",
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"statements" : {
"def" : [ {
"name" : "Patient",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"localId" : "3",
"name" : "Foo",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "3",
"s" : [ {
"value" : [ "define ","Foo",": " ]
}, {
"r" : "2",
"s" : [ {
"value" : [ "'Bar'" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "2",
"valueType" : "{urn:hl7-org:elm-types:r1}String",
"value" : "Bar",
"type" : "Literal"
}
} ]
}
}
}
### ExpressionRef
library TestSnippet version '1'
using QUICK
context Patient
define Life: 42
define Foo: Life
###
module.exports['ExpressionRef'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localId" : "1",
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"statements" : {
"def" : [ {
"name" : "Patient",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"localId" : "3",
"name" : "Life",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "3",
"s" : [ {
"r" : "2",
"value" : [ "define ","Life",": ","42" ]
} ]
}
} ],
"expression" : {
"localId" : "2",
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "42",
"type" : "Literal"
}
}, {
"localId" : "5",
"name" : "Foo",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "5",
"s" : [ {
"value" : [ "define ","Foo",": " ]
}, {
"r" : "4",
"s" : [ {
"value" : [ "Life" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "4",
"name" : "Life",
"type" : "ExpressionRef"
}
} ]
}
}
}
### FunctionDefinitions
library TestSnippet version '1'
using QUICK
context Patient
define function "foo bar"(a Integer, b Integer) :
a + b
define testValue: "foo bar" (1,2)
###
module.exports['FunctionDefinitions'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localId" : "1",
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"statements" : {
"def" : [ {
"name" : "Patient",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"localId" : "7",
"name" : "foo bar",
"context" : "Patient",
"accessLevel" : "Public",
"type" : "FunctionDef",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "7",
"s" : [ {
"value" : [ "define function ","\"foo bar\"","(","a"," " ]
}, {
"r" : "2",
"s" : [ {
"value" : [ "Integer" ]
} ]
}, {
"value" : [ ", ","b"," " ]
}, {
"r" : "3",
"s" : [ {
"value" : [ "Integer" ]
} ]
}, {
"value" : [ ") :\n " ]
}, {
"r" : "6",
"s" : [ {
"r" : "6",
"s" : [ {
"r" : "4",
"s" : [ {
"value" : [ "a" ]
} ]
}, {
"value" : [ " + " ]
}, {
"r" : "5",
"s" : [ {
"value" : [ "b" ]
} ]
} ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "6",
"type" : "Add",
"operand" : [ {
"localId" : "4",
"name" : "a",
"type" : "OperandRef"
}, {
"localId" : "5",
"name" : "b",
"type" : "OperandRef"
} ]
},
"operand" : [ {
"name" : "a",
"operandTypeSpecifier" : {
"localId" : "2",
"name" : "{urn:hl7-org:elm-types:r1}Integer",
"type" : "NamedTypeSpecifier"
}
}, {
"name" : "b",
"operandTypeSpecifier" : {
"localId" : "3",
"name" : "{urn:hl7-org:elm-types:r1}Integer",
"type" : "NamedTypeSpecifier"
}
} ]
}, {
"localId" : "11",
"name" : "testValue",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "11",
"s" : [ {
"value" : [ "define ","testValue",": " ]
}, {
"r" : "10",
"s" : [ {
"r" : "8",
"value" : [ "\"foo bar\""," (","1",",","2",")" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "10",
"name" : "foo bar",
"type" : "FunctionRef",
"operand" : [ {
"localId" : "8",
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
}, {
"localId" : "9",
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "2",
"type" : "Literal"
} ]
}
} ]
}
}
}
### FunctionOverloads
library TestSnippet version '1'
using QUICK
context Patient
define function "foo bar" (a System.Integer) :
a + 1
define function "foo bar" (a System.String) :
'Hello ' + a
define testValue1: "foo bar"(1)
define testValue2: "foo bar"('World')
###
module.exports['FunctionOverloads'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localId" : "1",
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"statements" : {
"def" : [ {
"name" : "Patient",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"localId" : "6",
"name" : "foo bar",
"context" : "Patient",
"accessLevel" : "Public",
"type" : "FunctionDef",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "6",
"s" : [ {
"value" : [ "define function ","\"foo bar\""," (","a"," " ]
}, {
"r" : "2",
"s" : [ {
"value" : [ "System",".","Integer" ]
} ]
}, {
"value" : [ ") :\n " ]
}, {
"r" : "5",
"s" : [ {
"r" : "5",
"s" : [ {
"r" : "3",
"s" : [ {
"value" : [ "a" ]
} ]
}, {
"r" : "4",
"value" : [ " + ","1" ]
} ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "5",
"type" : "Add",
"operand" : [ {
"localId" : "3",
"name" : "a",
"type" : "OperandRef"
}, {
"localId" : "4",
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
} ]
},
"operand" : [ {
"name" : "a",
"operandTypeSpecifier" : {
"localId" : "2",
"name" : "{urn:hl7-org:elm-types:r1}Integer",
"type" : "NamedTypeSpecifier"
}
} ]
}, {
"localId" : "11",
"name" : "foo bar",
"context" : "Patient",
"accessLevel" : "Public",
"type" : "FunctionDef",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "11",
"s" : [ {
"value" : [ "define function ","\"foo bar\""," (","a"," " ]
}, {
"r" : "7",
"s" : [ {
"value" : [ "System",".","String" ]
} ]
}, {
"value" : [ ") :\n " ]
}, {
"r" : "10",
"s" : [ {
"r" : "10",
"s" : [ {
"r" : "8",
"s" : [ {
"value" : [ "'Hello '" ]
} ]
}, {
"value" : [ " + " ]
}, {
"r" : "9",
"s" : [ {
"value" : [ "a" ]
} ]
} ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "10",
"type" : "Concatenate",
"operand" : [ {
"localId" : "8",
"valueType" : "{urn:hl7-org:elm-types:r1}String",
"value" : "Hello ",
"type" : "Literal"
}, {
"localId" : "9",
"name" : "a",
"type" : "OperandRef"
} ]
},
"operand" : [ {
"name" : "a",
"operandTypeSpecifier" : {
"localId" : "7",
"name" : "{urn:hl7-org:elm-types:r1}String",
"type" : "NamedTypeSpecifier"
}
} ]
}, {
"localId" : "14",
"name" : "testValue1",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "14",
"s" : [ {
"value" : [ "define ","testValue1",": " ]
}, {
"r" : "13",
"s" : [ {
"r" : "12",
"value" : [ "\"foo bar\"","(","1",")" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "13",
"name" : "foo bar",
"type" : "FunctionRef",
"operand" : [ {
"localId" : "12",
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
} ]
}
}, {
"localId" : "17",
"name" : "testValue2",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "17",
"s" : [ {
"value" : [ "define ","testValue2",": " ]
}, {
"r" : "16",
"s" : [ {
"value" : [ "\"foo bar\"","(" ]
}, {
"r" : "15",
"s" : [ {
"value" : [ "'World'" ]
} ]
}, {
"value" : [ ")" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "16",
"name" : "foo bar",
"type" : "FunctionRef",
"operand" : [ {
"localId" : "15",
"valueType" : "{urn:hl7-org:elm-types:r1}String",
"value" : "World",
"type" : "Literal"
} ]
}
} ]
}
}
}
| 188045 | ###
WARNING: This is a GENERATED file. Do not manually edit!
To generate this file:
- Edit data.cql to add a CQL Snippet
- From java dir: ./gradlew :cql-to-elm:generateTestData
###
### ExpressionDef
library TestSnippet version '1'
using QUICK
context Patient
define Foo: 'Bar'
###
module.exports['ExpressionDef'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localId" : "1",
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"statements" : {
"def" : [ {
"name" : "<NAME>",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"localId" : "3",
"name" : "<NAME>",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "3",
"s" : [ {
"value" : [ "define ","Foo",": " ]
}, {
"r" : "2",
"s" : [ {
"value" : [ "'Bar'" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "2",
"valueType" : "{urn:hl7-org:elm-types:r1}String",
"value" : "Bar",
"type" : "Literal"
}
} ]
}
}
}
### ExpressionRef
library TestSnippet version '1'
using QUICK
context Patient
define Life: 42
define Foo: Life
###
module.exports['ExpressionRef'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localId" : "1",
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"statements" : {
"def" : [ {
"name" : "<NAME>",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"localId" : "3",
"name" : "<NAME>",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "3",
"s" : [ {
"r" : "2",
"value" : [ "define ","Life",": ","42" ]
} ]
}
} ],
"expression" : {
"localId" : "2",
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "42",
"type" : "Literal"
}
}, {
"localId" : "5",
"name" : "<NAME>",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "5",
"s" : [ {
"value" : [ "define ","Foo",": " ]
}, {
"r" : "4",
"s" : [ {
"value" : [ "Life" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "4",
"name" : "<NAME>",
"type" : "ExpressionRef"
}
} ]
}
}
}
### FunctionDefinitions
library TestSnippet version '1'
using QUICK
context Patient
define function "foo bar"(a Integer, b Integer) :
a + b
define testValue: "foo bar" (1,2)
###
module.exports['FunctionDefinitions'] = {
"library" : {
"identifier" : {
"id" : "<NAME>Snippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localId" : "1",
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"statements" : {
"def" : [ {
"name" : "<NAME>",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"localId" : "7",
"name" : "<NAME>",
"context" : "Patient",
"accessLevel" : "Public",
"type" : "FunctionDef",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "7",
"s" : [ {
"value" : [ "define function ","\"foo bar\"","(","a"," " ]
}, {
"r" : "2",
"s" : [ {
"value" : [ "Integer" ]
} ]
}, {
"value" : [ ", ","b"," " ]
}, {
"r" : "3",
"s" : [ {
"value" : [ "Integer" ]
} ]
}, {
"value" : [ ") :\n " ]
}, {
"r" : "6",
"s" : [ {
"r" : "6",
"s" : [ {
"r" : "4",
"s" : [ {
"value" : [ "a" ]
} ]
}, {
"value" : [ " + " ]
}, {
"r" : "5",
"s" : [ {
"value" : [ "b" ]
} ]
} ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "6",
"type" : "Add",
"operand" : [ {
"localId" : "4",
"name" : "<NAME>",
"type" : "OperandRef"
}, {
"localId" : "5",
"name" : "<NAME>",
"type" : "OperandRef"
} ]
},
"operand" : [ {
"name" : "<NAME>",
"operandTypeSpecifier" : {
"localId" : "2",
"name" : "{urn:hl7-org:elm-types:r1}Integer",
"type" : "NamedTypeSpecifier"
}
}, {
"name" : "<NAME>",
"operandTypeSpecifier" : {
"localId" : "3",
"name" : "{urn:hl7-org:elm-types:r1}Integer",
"type" : "NamedTypeSpecifier"
}
} ]
}, {
"localId" : "11",
"name" : "<NAME>",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "11",
"s" : [ {
"value" : [ "define ","testValue",": " ]
}, {
"r" : "10",
"s" : [ {
"r" : "8",
"value" : [ "\"foo bar\""," (","1",",","2",")" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "10",
"name" : "foo bar",
"type" : "FunctionRef",
"operand" : [ {
"localId" : "8",
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
}, {
"localId" : "9",
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "2",
"type" : "Literal"
} ]
}
} ]
}
}
}
### FunctionOverloads
library TestSnippet version '1'
using QUICK
context Patient
define function "foo bar" (a System.Integer) :
a + 1
define function "foo bar" (a System.String) :
'Hello ' + a
define testValue1: "foo bar"(1)
define testValue2: "foo bar"('World')
###
module.exports['FunctionOverloads'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localId" : "1",
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"statements" : {
"def" : [ {
"name" : "<NAME>",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"localId" : "6",
"name" : "<NAME>",
"context" : "Patient",
"accessLevel" : "Public",
"type" : "FunctionDef",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "6",
"s" : [ {
"value" : [ "define function ","\"foo bar\""," (","a"," " ]
}, {
"r" : "2",
"s" : [ {
"value" : [ "System",".","Integer" ]
} ]
}, {
"value" : [ ") :\n " ]
}, {
"r" : "5",
"s" : [ {
"r" : "5",
"s" : [ {
"r" : "3",
"s" : [ {
"value" : [ "a" ]
} ]
}, {
"r" : "4",
"value" : [ " + ","1" ]
} ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "5",
"type" : "Add",
"operand" : [ {
"localId" : "3",
"name" : "<NAME>",
"type" : "OperandRef"
}, {
"localId" : "4",
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
} ]
},
"operand" : [ {
"name" : "a",
"operandTypeSpecifier" : {
"localId" : "2",
"name" : "{urn:hl7-org:elm-types:r1}Integer",
"type" : "NamedTypeSpecifier"
}
} ]
}, {
"localId" : "11",
"name" : "<NAME>",
"context" : "Patient",
"accessLevel" : "Public",
"type" : "FunctionDef",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "11",
"s" : [ {
"value" : [ "define function ","\"foo bar\""," (","a"," " ]
}, {
"r" : "7",
"s" : [ {
"value" : [ "System",".","String" ]
} ]
}, {
"value" : [ ") :\n " ]
}, {
"r" : "10",
"s" : [ {
"r" : "10",
"s" : [ {
"r" : "8",
"s" : [ {
"value" : [ "'Hello '" ]
} ]
}, {
"value" : [ " + " ]
}, {
"r" : "9",
"s" : [ {
"value" : [ "a" ]
} ]
} ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "10",
"type" : "Concatenate",
"operand" : [ {
"localId" : "8",
"valueType" : "{urn:hl7-org:elm-types:r1}String",
"value" : "Hello ",
"type" : "Literal"
}, {
"localId" : "9",
"name" : "<NAME>",
"type" : "OperandRef"
} ]
},
"operand" : [ {
"name" : "a",
"operandTypeSpecifier" : {
"localId" : "7",
"name" : "{urn:hl7-org:elm-types:r1}String",
"type" : "NamedTypeSpecifier"
}
} ]
}, {
"localId" : "14",
"name" : "<NAME>",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "14",
"s" : [ {
"value" : [ "define ","testValue1",": " ]
}, {
"r" : "13",
"s" : [ {
"r" : "12",
"value" : [ "\"foo bar\"","(","1",")" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "13",
"name" : "<NAME>",
"type" : "FunctionRef",
"operand" : [ {
"localId" : "12",
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
} ]
}
}, {
"localId" : "17",
"name" : "<NAME>",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "17",
"s" : [ {
"value" : [ "define ","testValue2",": " ]
}, {
"r" : "16",
"s" : [ {
"value" : [ "\"foo bar\"","(" ]
}, {
"r" : "15",
"s" : [ {
"value" : [ "'World'" ]
} ]
}, {
"value" : [ ")" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "16",
"name" : "<NAME>",
"type" : "FunctionRef",
"operand" : [ {
"localId" : "15",
"valueType" : "{urn:hl7-org:elm-types:r1}String",
"value" : "World",
"type" : "Literal"
} ]
}
} ]
}
}
}
| true | ###
WARNING: This is a GENERATED file. Do not manually edit!
To generate this file:
- Edit data.cql to add a CQL Snippet
- From java dir: ./gradlew :cql-to-elm:generateTestData
###
### ExpressionDef
library TestSnippet version '1'
using QUICK
context Patient
define Foo: 'Bar'
###
module.exports['ExpressionDef'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localId" : "1",
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"statements" : {
"def" : [ {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"localId" : "3",
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "3",
"s" : [ {
"value" : [ "define ","Foo",": " ]
}, {
"r" : "2",
"s" : [ {
"value" : [ "'Bar'" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "2",
"valueType" : "{urn:hl7-org:elm-types:r1}String",
"value" : "Bar",
"type" : "Literal"
}
} ]
}
}
}
### ExpressionRef
library TestSnippet version '1'
using QUICK
context Patient
define Life: 42
define Foo: Life
###
module.exports['ExpressionRef'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localId" : "1",
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"statements" : {
"def" : [ {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"localId" : "3",
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "3",
"s" : [ {
"r" : "2",
"value" : [ "define ","Life",": ","42" ]
} ]
}
} ],
"expression" : {
"localId" : "2",
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "42",
"type" : "Literal"
}
}, {
"localId" : "5",
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "5",
"s" : [ {
"value" : [ "define ","Foo",": " ]
}, {
"r" : "4",
"s" : [ {
"value" : [ "Life" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "4",
"name" : "PI:NAME:<NAME>END_PI",
"type" : "ExpressionRef"
}
} ]
}
}
}
### FunctionDefinitions
library TestSnippet version '1'
using QUICK
context Patient
define function "foo bar"(a Integer, b Integer) :
a + b
define testValue: "foo bar" (1,2)
###
module.exports['FunctionDefinitions'] = {
"library" : {
"identifier" : {
"id" : "PI:NAME:<NAME>END_PISnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localId" : "1",
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"statements" : {
"def" : [ {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"localId" : "7",
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"accessLevel" : "Public",
"type" : "FunctionDef",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "7",
"s" : [ {
"value" : [ "define function ","\"foo bar\"","(","a"," " ]
}, {
"r" : "2",
"s" : [ {
"value" : [ "Integer" ]
} ]
}, {
"value" : [ ", ","b"," " ]
}, {
"r" : "3",
"s" : [ {
"value" : [ "Integer" ]
} ]
}, {
"value" : [ ") :\n " ]
}, {
"r" : "6",
"s" : [ {
"r" : "6",
"s" : [ {
"r" : "4",
"s" : [ {
"value" : [ "a" ]
} ]
}, {
"value" : [ " + " ]
}, {
"r" : "5",
"s" : [ {
"value" : [ "b" ]
} ]
} ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "6",
"type" : "Add",
"operand" : [ {
"localId" : "4",
"name" : "PI:NAME:<NAME>END_PI",
"type" : "OperandRef"
}, {
"localId" : "5",
"name" : "PI:NAME:<NAME>END_PI",
"type" : "OperandRef"
} ]
},
"operand" : [ {
"name" : "PI:NAME:<NAME>END_PI",
"operandTypeSpecifier" : {
"localId" : "2",
"name" : "{urn:hl7-org:elm-types:r1}Integer",
"type" : "NamedTypeSpecifier"
}
}, {
"name" : "PI:NAME:<NAME>END_PI",
"operandTypeSpecifier" : {
"localId" : "3",
"name" : "{urn:hl7-org:elm-types:r1}Integer",
"type" : "NamedTypeSpecifier"
}
} ]
}, {
"localId" : "11",
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "11",
"s" : [ {
"value" : [ "define ","testValue",": " ]
}, {
"r" : "10",
"s" : [ {
"r" : "8",
"value" : [ "\"foo bar\""," (","1",",","2",")" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "10",
"name" : "foo bar",
"type" : "FunctionRef",
"operand" : [ {
"localId" : "8",
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
}, {
"localId" : "9",
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "2",
"type" : "Literal"
} ]
}
} ]
}
}
}
### FunctionOverloads
library TestSnippet version '1'
using QUICK
context Patient
define function "foo bar" (a System.Integer) :
a + 1
define function "foo bar" (a System.String) :
'Hello ' + a
define testValue1: "foo bar"(1)
define testValue2: "foo bar"('World')
###
module.exports['FunctionOverloads'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localId" : "1",
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"statements" : {
"def" : [ {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"localId" : "6",
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"accessLevel" : "Public",
"type" : "FunctionDef",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "6",
"s" : [ {
"value" : [ "define function ","\"foo bar\""," (","a"," " ]
}, {
"r" : "2",
"s" : [ {
"value" : [ "System",".","Integer" ]
} ]
}, {
"value" : [ ") :\n " ]
}, {
"r" : "5",
"s" : [ {
"r" : "5",
"s" : [ {
"r" : "3",
"s" : [ {
"value" : [ "a" ]
} ]
}, {
"r" : "4",
"value" : [ " + ","1" ]
} ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "5",
"type" : "Add",
"operand" : [ {
"localId" : "3",
"name" : "PI:NAME:<NAME>END_PI",
"type" : "OperandRef"
}, {
"localId" : "4",
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
} ]
},
"operand" : [ {
"name" : "a",
"operandTypeSpecifier" : {
"localId" : "2",
"name" : "{urn:hl7-org:elm-types:r1}Integer",
"type" : "NamedTypeSpecifier"
}
} ]
}, {
"localId" : "11",
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"accessLevel" : "Public",
"type" : "FunctionDef",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "11",
"s" : [ {
"value" : [ "define function ","\"foo bar\""," (","a"," " ]
}, {
"r" : "7",
"s" : [ {
"value" : [ "System",".","String" ]
} ]
}, {
"value" : [ ") :\n " ]
}, {
"r" : "10",
"s" : [ {
"r" : "10",
"s" : [ {
"r" : "8",
"s" : [ {
"value" : [ "'Hello '" ]
} ]
}, {
"value" : [ " + " ]
}, {
"r" : "9",
"s" : [ {
"value" : [ "a" ]
} ]
} ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "10",
"type" : "Concatenate",
"operand" : [ {
"localId" : "8",
"valueType" : "{urn:hl7-org:elm-types:r1}String",
"value" : "Hello ",
"type" : "Literal"
}, {
"localId" : "9",
"name" : "PI:NAME:<NAME>END_PI",
"type" : "OperandRef"
} ]
},
"operand" : [ {
"name" : "a",
"operandTypeSpecifier" : {
"localId" : "7",
"name" : "{urn:hl7-org:elm-types:r1}String",
"type" : "NamedTypeSpecifier"
}
} ]
}, {
"localId" : "14",
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "14",
"s" : [ {
"value" : [ "define ","testValue1",": " ]
}, {
"r" : "13",
"s" : [ {
"r" : "12",
"value" : [ "\"foo bar\"","(","1",")" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "13",
"name" : "PI:NAME:<NAME>END_PI",
"type" : "FunctionRef",
"operand" : [ {
"localId" : "12",
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
} ]
}
}, {
"localId" : "17",
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "17",
"s" : [ {
"value" : [ "define ","testValue2",": " ]
}, {
"r" : "16",
"s" : [ {
"value" : [ "\"foo bar\"","(" ]
}, {
"r" : "15",
"s" : [ {
"value" : [ "'World'" ]
} ]
}, {
"value" : [ ")" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "16",
"name" : "PI:NAME:<NAME>END_PI",
"type" : "FunctionRef",
"operand" : [ {
"localId" : "15",
"valueType" : "{urn:hl7-org:elm-types:r1}String",
"value" : "World",
"type" : "Literal"
} ]
}
} ]
}
}
}
|
[
{
"context": "rty()\n query = DataModel.where 'name', equal: 'enju'\n expect(query).toMatchSnapshot()\n\ntest 'Save ",
"end": 7350,
"score": 0.9504369497299194,
"start": 7346,
"tag": "NAME",
"value": "enju"
},
{
"context": "ersion: 0\n data = new DataModel\n name: 'enju'\n data.save().then (result) ->\n expect(",
"end": 7767,
"score": 0.9891037940979004,
"start": 7763,
"tag": "NAME",
"value": "enju"
},
{
"context": "ersion: 0\n data = new DataModel\n name: 'enju'\n data.save(yes).then (result) ->\n expe",
"end": 8268,
"score": 0.9895130395889282,
"start": 8264,
"tag": "NAME",
"value": "enju"
},
{
"context": "a = new DataModel\n id: 'id'\n name: 'enju'\n data.delete().then ->\n expect(DataMod",
"end": 8750,
"score": 0.9891006946563721,
"start": 8746,
"tag": "NAME",
"value": "enju"
},
{
"context": "a = new DataModel\n id: 'id'\n name: 'enju'\n data.delete(yes).then ->\n expect(Data",
"end": 9179,
"score": 0.8025559186935425,
"start": 9175,
"tag": "NAME",
"value": "enju"
}
] | __tests__/document.coffee | kelp404/enju | 12 | config = require 'config'
enju = require '../'
utils = require '../lib/utils'
Query = require '../lib/query'
exceptions = require '../lib/exceptions'
DataModel = null
generateDataModel = ->
class DataModel extends enju.Document
@_index = 'index'
@_settings =
analysis:
normalizer:
lowercase_filter:
type: 'custom'
filter: ['lowercase']
@define
name: new enju.StringProperty()
gender: new enju.KeywordProperty()
bio: new enju.TextProperty()
isAdmin: new enju.BooleanProperty
default: no
dbField: 'is_admin'
score: new enju.FloatProperty()
age: new enju.IntegerProperty()
createTime: new enju.DateProperty
dbField: 'create_time'
beforeEach ->
DataModel = generateDataModel()
afterEach ->
jest.restoreAllMocks()
test 'Define model.', ->
class DataModelA extends enju.Document
@_index = 'index'
@_settings =
analysis:
normalizer:
lowercase_filter:
type: 'custom'
filter: ['lowercase']
@define
name: new enju.StringProperty()
DataModelB = enju.Document.define 'DataModelB',
name: new enju.StringProperty()
expect(DataModelA).toMatchSnapshot()
expect(DataModelA._properties).toMatchSnapshot()
expect(DataModelA._settings).toMatchSnapshot()
expect(DataModelB).toMatchSnapshot()
expect(DataModelB._properties).toMatchSnapshot()
test 'Get error when define the model with wrong arguments.', ->
func = ->
class DataModel extends enju.Document
@_index = 'index'
@define {}, {}
expect(func).toThrow exceptions.ArgumentError
test 'Update the model mapping.', ->
DataModel._es.indices.create = jest.fn (args, callback) ->
expect(args).toMatchSnapshot()
callback null
DataModel._es.indices.close = jest.fn (args, callback) ->
expect(args).toMatchSnapshot()
callback null
DataModel._es.indices.putSettings = jest.fn (args, callback) ->
expect(args).toMatchSnapshot()
callback null
DataModel._es.indices.putMapping = jest.fn (args, callback) ->
expect(args).toMatchSnapshot()
callback null
DataModel._es.indices.open = jest.fn (args, callback) ->
expect(args).toMatchSnapshot()
callback null
DataModel.updateMapping().then ->
expect(DataModel._es.indices.create).toBeCalled()
expect(DataModel._es.indices.close).toBeCalled()
expect(DataModel._es.indices.putSettings).toBeCalled()
expect(DataModel._es.indices.putMapping).toBeCalled()
expect(DataModel._es.indices.open).toBeCalled()
test 'Get the index prefix of the model.', ->
jest.spyOn(utils, 'getIndexPrefix').mockImplementation -> config.enju.indexPrefix
result = DataModel.getIndexName()
expect(result).toBe "#{config.enju.indexPrefix}index"
expect(utils.getIndexPrefix).toBeCalled()
test 'Get the type of the model.', ->
class DataModelA extends enju.Document
@_index = 'index'
class DataModelB extends enju.Document
@_type = 'DataModel'
@_index = 'index'
expect(DataModelA.getDocumentType()).toBe 'DataModelA'
expect(DataModelB.getDocumentType()).toBe 'DataModel'
test 'Model.get() will return null without query id.', ->
Promise.all [
DataModel.get('').then (result) -> expect(result).toBeNull()
DataModel.get(null).then (result) -> expect(result).toBeNull()
DataModel.get(undefined ).then (result) -> expect(result).toBeNull()
DataModel.get([]).then (result) -> expect(result).toEqual []
]
test 'Get the document by id without reference.', ->
class DataModel extends enju.Document
@_index = 'index'
@define
name: new enju.StringProperty()
DataModel._es.get = jest.fn (args, callback) ->
expect(args).toMatchSnapshot()
callback null,
_id: 'id'
_version: 0
_source:
name: 'enju'
DataModel.get('id', no).then (document) ->
expect(document).toMatchSnapshot()
test 'Get the document by id with reference.', ->
class DataModel extends enju.Document
@_index = 'index'
@define
name: new enju.StringProperty()
DataModel._es.get = jest.fn (args, callback) ->
expect(args).toMatchSnapshot()
callback null,
_id: 'id'
_version: 0
_source:
name: 'enju'
jest.spyOn(utils, 'updateReferenceProperties').mockImplementation (documents) -> new Promise (resolve) ->
expect(documents).toMatchSnapshot()
resolve()
DataModel.get('id').then ->
expect(utils.updateReferenceProperties).toBeCalled()
test 'Get documents by ids without reference.', ->
class DataModel extends enju.Document
@_index = 'index'
@define
name: new enju.StringProperty()
DataModel._es.mget = jest.fn (args, callback) ->
expect(args).toMatchSnapshot()
callback null,
docs: [
found: yes
_id: 'id'
_version: 0
_source:
name: 'enju'
]
DataModel.get(['id'], no).then (documents) ->
expect(documents).toMatchSnapshot()
test 'Get documents by ids with reference.', ->
class DataModel extends enju.Document
@_index = 'index'
@define
name: new enju.StringProperty()
DataModel._es.mget = jest.fn (args, callback) ->
expect(args).toMatchSnapshot()
callback null,
docs: [
found: yes
_id: 'id'
_version: 0
_source:
name: 'enju'
]
jest.spyOn(utils, 'updateReferenceProperties').mockImplementation (documents) -> new Promise (resolve) ->
expect(documents).toMatchSnapshot()
resolve()
DataModel.get(['id']).then ->
expect(utils.updateReferenceProperties).toBeCalled()
test 'Is the document exists.', ->
class DataModel extends enju.Document
@_index = 'index'
@define
name: new enju.StringProperty()
DataModel._es.exists = jest.fn (args, callback) ->
expect(args).toMatchSnapshot()
callback null, yes
DataModel.exists('id').then (result) ->
expect(result).toBe yes
test 'Generate a query of the model.', ->
query = DataModel.all()
expect(query).toMatchSnapshot()
test 'Refresh the model.', ->
class DataModel extends enju.Document
@_index = 'index'
@define
name: new enju.StringProperty()
DataModel._es.indices.refresh = jest.fn (args, callback) ->
expect(args).toMatchSnapshot()
callback null, yes
DataModel.refresh().then ->
expect(DataModel._es.indices.refresh).toBeCalled()
test 'Generate a query via where().', ->
class DataModel extends enju.Document
@_index = 'index'
@define
name: new enju.StringProperty()
query = DataModel.where 'name', equal: 'enju'
expect(query).toMatchSnapshot()
test 'Save a document without refresh.', ->
class DataModel extends enju.Document
@_index = 'index'
@define
name: new enju.StringProperty()
DataModel._es.index = jest.fn (args, callback) ->
expect(args).toMatchSnapshot()
callback null,
_id: 'id'
_version: 0
data = new DataModel
name: 'enju'
data.save().then (result) ->
expect(result).toMatchSnapshot()
expect(DataModel._es.index).toBeCalled()
test 'Save a document with refresh.', ->
class DataModel extends enju.Document
@_index = 'index'
@define
name: new enju.StringProperty()
DataModel._es.index = jest.fn (args, callback) ->
expect(args).toMatchSnapshot()
callback null,
_id: 'id'
_version: 0
data = new DataModel
name: 'enju'
data.save(yes).then (result) ->
expect(result).toMatchSnapshot()
expect(DataModel._es.index).toBeCalled()
test 'Delete the document without refresh.', ->
class DataModel extends enju.Document
@_index = 'index'
@define
name: new enju.StringProperty()
DataModel._es.delete = jest.fn (args, callback) ->
expect(args).toMatchSnapshot()
callback null
data = new DataModel
id: 'id'
name: 'enju'
data.delete().then ->
expect(DataModel._es.delete).toBeCalled()
test 'Delete the document with refresh.', ->
class DataModel extends enju.Document
@_index = 'index'
@define
name: new enju.StringProperty()
DataModel._es.delete = jest.fn (args, callback) ->
expect(args).toMatchSnapshot()
callback null
data = new DataModel
id: 'id'
name: 'enju'
data.delete(yes).then ->
expect(DataModel._es.delete).toBeCalled()
| 93135 | config = require 'config'
enju = require '../'
utils = require '../lib/utils'
Query = require '../lib/query'
exceptions = require '../lib/exceptions'
DataModel = null
generateDataModel = ->
class DataModel extends enju.Document
@_index = 'index'
@_settings =
analysis:
normalizer:
lowercase_filter:
type: 'custom'
filter: ['lowercase']
@define
name: new enju.StringProperty()
gender: new enju.KeywordProperty()
bio: new enju.TextProperty()
isAdmin: new enju.BooleanProperty
default: no
dbField: 'is_admin'
score: new enju.FloatProperty()
age: new enju.IntegerProperty()
createTime: new enju.DateProperty
dbField: 'create_time'
beforeEach ->
DataModel = generateDataModel()
afterEach ->
jest.restoreAllMocks()
test 'Define model.', ->
class DataModelA extends enju.Document
@_index = 'index'
@_settings =
analysis:
normalizer:
lowercase_filter:
type: 'custom'
filter: ['lowercase']
@define
name: new enju.StringProperty()
DataModelB = enju.Document.define 'DataModelB',
name: new enju.StringProperty()
expect(DataModelA).toMatchSnapshot()
expect(DataModelA._properties).toMatchSnapshot()
expect(DataModelA._settings).toMatchSnapshot()
expect(DataModelB).toMatchSnapshot()
expect(DataModelB._properties).toMatchSnapshot()
test 'Get error when define the model with wrong arguments.', ->
func = ->
class DataModel extends enju.Document
@_index = 'index'
@define {}, {}
expect(func).toThrow exceptions.ArgumentError
test 'Update the model mapping.', ->
DataModel._es.indices.create = jest.fn (args, callback) ->
expect(args).toMatchSnapshot()
callback null
DataModel._es.indices.close = jest.fn (args, callback) ->
expect(args).toMatchSnapshot()
callback null
DataModel._es.indices.putSettings = jest.fn (args, callback) ->
expect(args).toMatchSnapshot()
callback null
DataModel._es.indices.putMapping = jest.fn (args, callback) ->
expect(args).toMatchSnapshot()
callback null
DataModel._es.indices.open = jest.fn (args, callback) ->
expect(args).toMatchSnapshot()
callback null
DataModel.updateMapping().then ->
expect(DataModel._es.indices.create).toBeCalled()
expect(DataModel._es.indices.close).toBeCalled()
expect(DataModel._es.indices.putSettings).toBeCalled()
expect(DataModel._es.indices.putMapping).toBeCalled()
expect(DataModel._es.indices.open).toBeCalled()
test 'Get the index prefix of the model.', ->
jest.spyOn(utils, 'getIndexPrefix').mockImplementation -> config.enju.indexPrefix
result = DataModel.getIndexName()
expect(result).toBe "#{config.enju.indexPrefix}index"
expect(utils.getIndexPrefix).toBeCalled()
test 'Get the type of the model.', ->
class DataModelA extends enju.Document
@_index = 'index'
class DataModelB extends enju.Document
@_type = 'DataModel'
@_index = 'index'
expect(DataModelA.getDocumentType()).toBe 'DataModelA'
expect(DataModelB.getDocumentType()).toBe 'DataModel'
test 'Model.get() will return null without query id.', ->
Promise.all [
DataModel.get('').then (result) -> expect(result).toBeNull()
DataModel.get(null).then (result) -> expect(result).toBeNull()
DataModel.get(undefined ).then (result) -> expect(result).toBeNull()
DataModel.get([]).then (result) -> expect(result).toEqual []
]
test 'Get the document by id without reference.', ->
class DataModel extends enju.Document
@_index = 'index'
@define
name: new enju.StringProperty()
DataModel._es.get = jest.fn (args, callback) ->
expect(args).toMatchSnapshot()
callback null,
_id: 'id'
_version: 0
_source:
name: 'enju'
DataModel.get('id', no).then (document) ->
expect(document).toMatchSnapshot()
test 'Get the document by id with reference.', ->
class DataModel extends enju.Document
@_index = 'index'
@define
name: new enju.StringProperty()
DataModel._es.get = jest.fn (args, callback) ->
expect(args).toMatchSnapshot()
callback null,
_id: 'id'
_version: 0
_source:
name: 'enju'
jest.spyOn(utils, 'updateReferenceProperties').mockImplementation (documents) -> new Promise (resolve) ->
expect(documents).toMatchSnapshot()
resolve()
DataModel.get('id').then ->
expect(utils.updateReferenceProperties).toBeCalled()
test 'Get documents by ids without reference.', ->
class DataModel extends enju.Document
@_index = 'index'
@define
name: new enju.StringProperty()
DataModel._es.mget = jest.fn (args, callback) ->
expect(args).toMatchSnapshot()
callback null,
docs: [
found: yes
_id: 'id'
_version: 0
_source:
name: 'enju'
]
DataModel.get(['id'], no).then (documents) ->
expect(documents).toMatchSnapshot()
test 'Get documents by ids with reference.', ->
class DataModel extends enju.Document
@_index = 'index'
@define
name: new enju.StringProperty()
DataModel._es.mget = jest.fn (args, callback) ->
expect(args).toMatchSnapshot()
callback null,
docs: [
found: yes
_id: 'id'
_version: 0
_source:
name: 'enju'
]
jest.spyOn(utils, 'updateReferenceProperties').mockImplementation (documents) -> new Promise (resolve) ->
expect(documents).toMatchSnapshot()
resolve()
DataModel.get(['id']).then ->
expect(utils.updateReferenceProperties).toBeCalled()
test 'Is the document exists.', ->
class DataModel extends enju.Document
@_index = 'index'
@define
name: new enju.StringProperty()
DataModel._es.exists = jest.fn (args, callback) ->
expect(args).toMatchSnapshot()
callback null, yes
DataModel.exists('id').then (result) ->
expect(result).toBe yes
test 'Generate a query of the model.', ->
query = DataModel.all()
expect(query).toMatchSnapshot()
test 'Refresh the model.', ->
class DataModel extends enju.Document
@_index = 'index'
@define
name: new enju.StringProperty()
DataModel._es.indices.refresh = jest.fn (args, callback) ->
expect(args).toMatchSnapshot()
callback null, yes
DataModel.refresh().then ->
expect(DataModel._es.indices.refresh).toBeCalled()
test 'Generate a query via where().', ->
class DataModel extends enju.Document
@_index = 'index'
@define
name: new enju.StringProperty()
query = DataModel.where 'name', equal: '<NAME>'
expect(query).toMatchSnapshot()
test 'Save a document without refresh.', ->
class DataModel extends enju.Document
@_index = 'index'
@define
name: new enju.StringProperty()
DataModel._es.index = jest.fn (args, callback) ->
expect(args).toMatchSnapshot()
callback null,
_id: 'id'
_version: 0
data = new DataModel
name: '<NAME>'
data.save().then (result) ->
expect(result).toMatchSnapshot()
expect(DataModel._es.index).toBeCalled()
test 'Save a document with refresh.', ->
class DataModel extends enju.Document
@_index = 'index'
@define
name: new enju.StringProperty()
DataModel._es.index = jest.fn (args, callback) ->
expect(args).toMatchSnapshot()
callback null,
_id: 'id'
_version: 0
data = new DataModel
name: '<NAME>'
data.save(yes).then (result) ->
expect(result).toMatchSnapshot()
expect(DataModel._es.index).toBeCalled()
test 'Delete the document without refresh.', ->
class DataModel extends enju.Document
@_index = 'index'
@define
name: new enju.StringProperty()
DataModel._es.delete = jest.fn (args, callback) ->
expect(args).toMatchSnapshot()
callback null
data = new DataModel
id: 'id'
name: '<NAME>'
data.delete().then ->
expect(DataModel._es.delete).toBeCalled()
test 'Delete the document with refresh.', ->
class DataModel extends enju.Document
@_index = 'index'
@define
name: new enju.StringProperty()
DataModel._es.delete = jest.fn (args, callback) ->
expect(args).toMatchSnapshot()
callback null
data = new DataModel
id: 'id'
name: '<NAME>'
data.delete(yes).then ->
expect(DataModel._es.delete).toBeCalled()
| true | config = require 'config'
enju = require '../'
utils = require '../lib/utils'
Query = require '../lib/query'
exceptions = require '../lib/exceptions'
DataModel = null
generateDataModel = ->
class DataModel extends enju.Document
@_index = 'index'
@_settings =
analysis:
normalizer:
lowercase_filter:
type: 'custom'
filter: ['lowercase']
@define
name: new enju.StringProperty()
gender: new enju.KeywordProperty()
bio: new enju.TextProperty()
isAdmin: new enju.BooleanProperty
default: no
dbField: 'is_admin'
score: new enju.FloatProperty()
age: new enju.IntegerProperty()
createTime: new enju.DateProperty
dbField: 'create_time'
beforeEach ->
DataModel = generateDataModel()
afterEach ->
jest.restoreAllMocks()
test 'Define model.', ->
class DataModelA extends enju.Document
@_index = 'index'
@_settings =
analysis:
normalizer:
lowercase_filter:
type: 'custom'
filter: ['lowercase']
@define
name: new enju.StringProperty()
DataModelB = enju.Document.define 'DataModelB',
name: new enju.StringProperty()
expect(DataModelA).toMatchSnapshot()
expect(DataModelA._properties).toMatchSnapshot()
expect(DataModelA._settings).toMatchSnapshot()
expect(DataModelB).toMatchSnapshot()
expect(DataModelB._properties).toMatchSnapshot()
test 'Get error when define the model with wrong arguments.', ->
func = ->
class DataModel extends enju.Document
@_index = 'index'
@define {}, {}
expect(func).toThrow exceptions.ArgumentError
test 'Update the model mapping.', ->
DataModel._es.indices.create = jest.fn (args, callback) ->
expect(args).toMatchSnapshot()
callback null
DataModel._es.indices.close = jest.fn (args, callback) ->
expect(args).toMatchSnapshot()
callback null
DataModel._es.indices.putSettings = jest.fn (args, callback) ->
expect(args).toMatchSnapshot()
callback null
DataModel._es.indices.putMapping = jest.fn (args, callback) ->
expect(args).toMatchSnapshot()
callback null
DataModel._es.indices.open = jest.fn (args, callback) ->
expect(args).toMatchSnapshot()
callback null
DataModel.updateMapping().then ->
expect(DataModel._es.indices.create).toBeCalled()
expect(DataModel._es.indices.close).toBeCalled()
expect(DataModel._es.indices.putSettings).toBeCalled()
expect(DataModel._es.indices.putMapping).toBeCalled()
expect(DataModel._es.indices.open).toBeCalled()
test 'Get the index prefix of the model.', ->
jest.spyOn(utils, 'getIndexPrefix').mockImplementation -> config.enju.indexPrefix
result = DataModel.getIndexName()
expect(result).toBe "#{config.enju.indexPrefix}index"
expect(utils.getIndexPrefix).toBeCalled()
test 'Get the type of the model.', ->
class DataModelA extends enju.Document
@_index = 'index'
class DataModelB extends enju.Document
@_type = 'DataModel'
@_index = 'index'
expect(DataModelA.getDocumentType()).toBe 'DataModelA'
expect(DataModelB.getDocumentType()).toBe 'DataModel'
test 'Model.get() will return null without query id.', ->
Promise.all [
DataModel.get('').then (result) -> expect(result).toBeNull()
DataModel.get(null).then (result) -> expect(result).toBeNull()
DataModel.get(undefined ).then (result) -> expect(result).toBeNull()
DataModel.get([]).then (result) -> expect(result).toEqual []
]
test 'Get the document by id without reference.', ->
class DataModel extends enju.Document
@_index = 'index'
@define
name: new enju.StringProperty()
DataModel._es.get = jest.fn (args, callback) ->
expect(args).toMatchSnapshot()
callback null,
_id: 'id'
_version: 0
_source:
name: 'enju'
DataModel.get('id', no).then (document) ->
expect(document).toMatchSnapshot()
test 'Get the document by id with reference.', ->
class DataModel extends enju.Document
@_index = 'index'
@define
name: new enju.StringProperty()
DataModel._es.get = jest.fn (args, callback) ->
expect(args).toMatchSnapshot()
callback null,
_id: 'id'
_version: 0
_source:
name: 'enju'
jest.spyOn(utils, 'updateReferenceProperties').mockImplementation (documents) -> new Promise (resolve) ->
expect(documents).toMatchSnapshot()
resolve()
DataModel.get('id').then ->
expect(utils.updateReferenceProperties).toBeCalled()
test 'Get documents by ids without reference.', ->
class DataModel extends enju.Document
@_index = 'index'
@define
name: new enju.StringProperty()
DataModel._es.mget = jest.fn (args, callback) ->
expect(args).toMatchSnapshot()
callback null,
docs: [
found: yes
_id: 'id'
_version: 0
_source:
name: 'enju'
]
DataModel.get(['id'], no).then (documents) ->
expect(documents).toMatchSnapshot()
test 'Get documents by ids with reference.', ->
class DataModel extends enju.Document
@_index = 'index'
@define
name: new enju.StringProperty()
DataModel._es.mget = jest.fn (args, callback) ->
expect(args).toMatchSnapshot()
callback null,
docs: [
found: yes
_id: 'id'
_version: 0
_source:
name: 'enju'
]
jest.spyOn(utils, 'updateReferenceProperties').mockImplementation (documents) -> new Promise (resolve) ->
expect(documents).toMatchSnapshot()
resolve()
DataModel.get(['id']).then ->
expect(utils.updateReferenceProperties).toBeCalled()
test 'Is the document exists.', ->
class DataModel extends enju.Document
@_index = 'index'
@define
name: new enju.StringProperty()
DataModel._es.exists = jest.fn (args, callback) ->
expect(args).toMatchSnapshot()
callback null, yes
DataModel.exists('id').then (result) ->
expect(result).toBe yes
test 'Generate a query of the model.', ->
query = DataModel.all()
expect(query).toMatchSnapshot()
test 'Refresh the model.', ->
class DataModel extends enju.Document
@_index = 'index'
@define
name: new enju.StringProperty()
DataModel._es.indices.refresh = jest.fn (args, callback) ->
expect(args).toMatchSnapshot()
callback null, yes
DataModel.refresh().then ->
expect(DataModel._es.indices.refresh).toBeCalled()
test 'Generate a query via where().', ->
class DataModel extends enju.Document
@_index = 'index'
@define
name: new enju.StringProperty()
query = DataModel.where 'name', equal: 'PI:NAME:<NAME>END_PI'
expect(query).toMatchSnapshot()
test 'Save a document without refresh.', ->
class DataModel extends enju.Document
@_index = 'index'
@define
name: new enju.StringProperty()
DataModel._es.index = jest.fn (args, callback) ->
expect(args).toMatchSnapshot()
callback null,
_id: 'id'
_version: 0
data = new DataModel
name: 'PI:NAME:<NAME>END_PI'
data.save().then (result) ->
expect(result).toMatchSnapshot()
expect(DataModel._es.index).toBeCalled()
test 'Save a document with refresh.', ->
class DataModel extends enju.Document
@_index = 'index'
@define
name: new enju.StringProperty()
DataModel._es.index = jest.fn (args, callback) ->
expect(args).toMatchSnapshot()
callback null,
_id: 'id'
_version: 0
data = new DataModel
name: 'PI:NAME:<NAME>END_PI'
data.save(yes).then (result) ->
expect(result).toMatchSnapshot()
expect(DataModel._es.index).toBeCalled()
test 'Delete the document without refresh.', ->
class DataModel extends enju.Document
@_index = 'index'
@define
name: new enju.StringProperty()
DataModel._es.delete = jest.fn (args, callback) ->
expect(args).toMatchSnapshot()
callback null
data = new DataModel
id: 'id'
name: 'PI:NAME:<NAME>END_PI'
data.delete().then ->
expect(DataModel._es.delete).toBeCalled()
test 'Delete the document with refresh.', ->
class DataModel extends enju.Document
@_index = 'index'
@define
name: new enju.StringProperty()
DataModel._es.delete = jest.fn (args, callback) ->
expect(args).toMatchSnapshot()
callback null
data = new DataModel
id: 'id'
name: 'PI:NAME:<NAME>END_PI'
data.delete(yes).then ->
expect(DataModel._es.delete).toBeCalled()
|
[
{
"context": "# Copyright (c) 2014-2015 Riceball LEE, MIT License\npath = require('pat",
"end": 38,
"score": 0.9997751116752625,
"start": 26,
"tag": "NAME",
"value": "Riceball LEE"
}
] | src/cache-factory.coffee | snowyu/cache-factory | 0 | # Copyright (c) 2014-2015 Riceball LEE, MIT License
path = require('path.js/lib/path').path
customFactory = require('custom-factory')
injectMethods = require('util-ex/lib/injectMethods')
inherits = require('inherits-ex/lib/inherits')
isInheritedFrom = require('inherits-ex/lib/isInheritedFrom')
createObject = require('inherits-ex/lib/createObject')
extend = require('inherits-ex/lib/_extend')
extendFilter = require('util-ex/lib/extend')
isFunction = require('util-ex/lib/is/type/function')
isString = require('util-ex/lib/is/type/string')
isObject = require('util-ex/lib/is/type/object')
isNumber = require('util-ex/lib/is/type/number')
Cache = require('secondary-cache')
Codec = require('buffer-codec-bytewise')
bytewise = Codec('bytewise')
module.exports = (Factory, aOptions)->
return Factory if Factory._cache?
cacheSettings =
capacity: 8192
fixedCapacity: 8192
extendFilter cacheSettings, aOptions, (k, v)->
k in ['capacity', 'fixedCapacity', 'expires', 'cleanInterval'] and
isNumber(v)
# the Static(Class) Methods for Factory:
extend Factory,
_cache: instanceCache = Cache(cacheSettings)
customFactory(Factory, aOptions) unless Factory::_objects
registeredObjects = Factory::_objects
aliases = Factory::_aliases
###
# result:
# * false: no cache and create a new object instance always.
# * 'string': the cache name.
# * undefined: no cache and using the global object instance.
###
Factory.getCacheName = getCacheName = (aOptions, aTypeClass)->
cached = aOptions.cached if aOptions?
cached = cached.name if isObject(cached) and cached.name?
if cached
if isString cached
cached = Factory.formatName cached
else
# no cache name, so 'hash' it.
opts = extend {}, aOptions
delete opts.cached
delete opts.name
# encode as cache name.
cached = bytewise.encode(opts)
if isString(cached) and cached.length
if cached[0] isnt '/'
#aTypeClass = Factory.registeredClass aName unless aTypeClass
cached = path.join(Factory.path(aTypeClass), cached)
cached
Factory.getCacheItem = getCacheItem = (aClass, aOptions)->
cached = aOptions.cached if aOptions?
if cached?
popped = cached.popped
cachedName = getCacheName aOptions, aClass
if cachedName is false
# create a new instance always.
result = createObject aClass, undefined, aOptions
else if isString cachedName
result = instanceCache.get(cachedName)
if result is undefined
result = createObject aClass, undefined, aOptions
unless popped
cached = undefined unless isObject cached
result.cached = cachedName
instanceCache.set cachedName, result, cached
else if popped
instanceCache.del(cachedName)
result
getInstance = (aName, aOptions)->
cached = aOptions.cached if aOptions?
if cached?
cls = Factory.registeredClass aName
return unless cls
result = getCacheItem cls, aOptions
else
result = Factory._get(aName, aOptions)
unless result?
aName = aOptions.name unless aName
if aName and isString(aName) and aName[0] isnt '/'
# arguments.callee is forbidden if strict mode enabled.
# arguments.callee.caller = CustomFactory
try vCaller = arguments.callee.caller.caller
if vCaller and isInheritedFrom vCaller, Factory
cls = vCaller
vCaller = vCaller.caller
#get farest hierarchical registered class
while isInheritedFrom vCaller, cls
cls = vCaller
vCaller = vCaller.caller
aName = path.join(Factory.path(cls), Factory.formatName(aName))
result = instanceCache.get(aName)
return result
Factory.get = getInstance if getInstance isnt Factory.get
| 169219 | # Copyright (c) 2014-2015 <NAME>, MIT License
path = require('path.js/lib/path').path
customFactory = require('custom-factory')
injectMethods = require('util-ex/lib/injectMethods')
inherits = require('inherits-ex/lib/inherits')
isInheritedFrom = require('inherits-ex/lib/isInheritedFrom')
createObject = require('inherits-ex/lib/createObject')
extend = require('inherits-ex/lib/_extend')
extendFilter = require('util-ex/lib/extend')
isFunction = require('util-ex/lib/is/type/function')
isString = require('util-ex/lib/is/type/string')
isObject = require('util-ex/lib/is/type/object')
isNumber = require('util-ex/lib/is/type/number')
Cache = require('secondary-cache')
Codec = require('buffer-codec-bytewise')
bytewise = Codec('bytewise')
module.exports = (Factory, aOptions)->
return Factory if Factory._cache?
cacheSettings =
capacity: 8192
fixedCapacity: 8192
extendFilter cacheSettings, aOptions, (k, v)->
k in ['capacity', 'fixedCapacity', 'expires', 'cleanInterval'] and
isNumber(v)
# the Static(Class) Methods for Factory:
extend Factory,
_cache: instanceCache = Cache(cacheSettings)
customFactory(Factory, aOptions) unless Factory::_objects
registeredObjects = Factory::_objects
aliases = Factory::_aliases
###
# result:
# * false: no cache and create a new object instance always.
# * 'string': the cache name.
# * undefined: no cache and using the global object instance.
###
Factory.getCacheName = getCacheName = (aOptions, aTypeClass)->
cached = aOptions.cached if aOptions?
cached = cached.name if isObject(cached) and cached.name?
if cached
if isString cached
cached = Factory.formatName cached
else
# no cache name, so 'hash' it.
opts = extend {}, aOptions
delete opts.cached
delete opts.name
# encode as cache name.
cached = bytewise.encode(opts)
if isString(cached) and cached.length
if cached[0] isnt '/'
#aTypeClass = Factory.registeredClass aName unless aTypeClass
cached = path.join(Factory.path(aTypeClass), cached)
cached
Factory.getCacheItem = getCacheItem = (aClass, aOptions)->
cached = aOptions.cached if aOptions?
if cached?
popped = cached.popped
cachedName = getCacheName aOptions, aClass
if cachedName is false
# create a new instance always.
result = createObject aClass, undefined, aOptions
else if isString cachedName
result = instanceCache.get(cachedName)
if result is undefined
result = createObject aClass, undefined, aOptions
unless popped
cached = undefined unless isObject cached
result.cached = cachedName
instanceCache.set cachedName, result, cached
else if popped
instanceCache.del(cachedName)
result
getInstance = (aName, aOptions)->
cached = aOptions.cached if aOptions?
if cached?
cls = Factory.registeredClass aName
return unless cls
result = getCacheItem cls, aOptions
else
result = Factory._get(aName, aOptions)
unless result?
aName = aOptions.name unless aName
if aName and isString(aName) and aName[0] isnt '/'
# arguments.callee is forbidden if strict mode enabled.
# arguments.callee.caller = CustomFactory
try vCaller = arguments.callee.caller.caller
if vCaller and isInheritedFrom vCaller, Factory
cls = vCaller
vCaller = vCaller.caller
#get farest hierarchical registered class
while isInheritedFrom vCaller, cls
cls = vCaller
vCaller = vCaller.caller
aName = path.join(Factory.path(cls), Factory.formatName(aName))
result = instanceCache.get(aName)
return result
Factory.get = getInstance if getInstance isnt Factory.get
| true | # Copyright (c) 2014-2015 PI:NAME:<NAME>END_PI, MIT License
path = require('path.js/lib/path').path
customFactory = require('custom-factory')
injectMethods = require('util-ex/lib/injectMethods')
inherits = require('inherits-ex/lib/inherits')
isInheritedFrom = require('inherits-ex/lib/isInheritedFrom')
createObject = require('inherits-ex/lib/createObject')
extend = require('inherits-ex/lib/_extend')
extendFilter = require('util-ex/lib/extend')
isFunction = require('util-ex/lib/is/type/function')
isString = require('util-ex/lib/is/type/string')
isObject = require('util-ex/lib/is/type/object')
isNumber = require('util-ex/lib/is/type/number')
Cache = require('secondary-cache')
Codec = require('buffer-codec-bytewise')
bytewise = Codec('bytewise')
module.exports = (Factory, aOptions)->
return Factory if Factory._cache?
cacheSettings =
capacity: 8192
fixedCapacity: 8192
extendFilter cacheSettings, aOptions, (k, v)->
k in ['capacity', 'fixedCapacity', 'expires', 'cleanInterval'] and
isNumber(v)
# the Static(Class) Methods for Factory:
extend Factory,
_cache: instanceCache = Cache(cacheSettings)
customFactory(Factory, aOptions) unless Factory::_objects
registeredObjects = Factory::_objects
aliases = Factory::_aliases
###
# result:
# * false: no cache and create a new object instance always.
# * 'string': the cache name.
# * undefined: no cache and using the global object instance.
###
Factory.getCacheName = getCacheName = (aOptions, aTypeClass)->
cached = aOptions.cached if aOptions?
cached = cached.name if isObject(cached) and cached.name?
if cached
if isString cached
cached = Factory.formatName cached
else
# no cache name, so 'hash' it.
opts = extend {}, aOptions
delete opts.cached
delete opts.name
# encode as cache name.
cached = bytewise.encode(opts)
if isString(cached) and cached.length
if cached[0] isnt '/'
#aTypeClass = Factory.registeredClass aName unless aTypeClass
cached = path.join(Factory.path(aTypeClass), cached)
cached
Factory.getCacheItem = getCacheItem = (aClass, aOptions)->
cached = aOptions.cached if aOptions?
if cached?
popped = cached.popped
cachedName = getCacheName aOptions, aClass
if cachedName is false
# create a new instance always.
result = createObject aClass, undefined, aOptions
else if isString cachedName
result = instanceCache.get(cachedName)
if result is undefined
result = createObject aClass, undefined, aOptions
unless popped
cached = undefined unless isObject cached
result.cached = cachedName
instanceCache.set cachedName, result, cached
else if popped
instanceCache.del(cachedName)
result
getInstance = (aName, aOptions)->
cached = aOptions.cached if aOptions?
if cached?
cls = Factory.registeredClass aName
return unless cls
result = getCacheItem cls, aOptions
else
result = Factory._get(aName, aOptions)
unless result?
aName = aOptions.name unless aName
if aName and isString(aName) and aName[0] isnt '/'
# arguments.callee is forbidden if strict mode enabled.
# arguments.callee.caller = CustomFactory
try vCaller = arguments.callee.caller.caller
if vCaller and isInheritedFrom vCaller, Factory
cls = vCaller
vCaller = vCaller.caller
#get farest hierarchical registered class
while isInheritedFrom vCaller, cls
cls = vCaller
vCaller = vCaller.caller
aName = path.join(Factory.path(cls), Factory.formatName(aName))
result = instanceCache.get(aName)
return result
Factory.get = getInstance if getInstance isnt Factory.get
|
[
{
"context": "f Oz')\n book.meta.author.should.equal('L. Frank Baum')\n book.meta.bookId.should.equal('this",
"end": 612,
"score": 0.9998003244400024,
"start": 599,
"tag": "NAME",
"value": "L. Frank Baum"
}
] | scripts/test/loadepub.coffee | baldurbjarnason/bookmaker | 1 | 'use strict'
chai = require 'chai'
should = chai.should()
index = require '../src/index'
Book = index.Book
testbook = {}
describe 'EpubLoader',
() ->
beforeEach (done) ->
load = (err, book) ->
testbook = book
done()
book = Book.fromEpub('test/files/test.epub', 'test/files/epubloader/', load)
describe '#loadEpub',
() ->
it 'Loads the book from an epub',
() ->
book = testbook
# console.log book
book.meta.title.should.equal('The Wonderful Wizard of Oz')
book.meta.author.should.equal('L. Frank Baum')
book.meta.bookId.should.equal('this-is-an-id')
book.meta.lang.should.equal('en')
# book.meta.modified.isoDate.should.equal("2013-06-27T01:29:06Z")
book.meta.date.isoDate.should.equal("2013-05-15T00:00:00Z")
book.meta.version.should.equal("1.0")
book.meta.publisher.should.equal("Bar")
book.meta.subject1.should.equal("Foobar")
book.meta.cover.should.equal("assets/cover.jpg")
book.chapters[0].title.should.equal('Markdown')
book.chapters[0].body.should.equal('\n\t\n\t\t<h1 id="header">header</h1>\n<p class="noindent" id="p-1">Test</p>\n\n\t\n')
book.chapters[1].title.should.equal('HTML')
book.chapters[1].body.should.equal('\n\t\n\t\t<h1 id="h1-1">header</h1><p class="noindent" id="p-1">Test<br />‘—’“–” </p>\n\t\n')
book.chapters[2].title.should.equal('XHTML')
book.chapters[2].body.should.equal('\n\t\n\t\t<h1>header</h1><p>Test<br/></p>\n\t\n')
book.chapters[3].title.should.equal('Template')
book.chapters[3].body.should.equal('\n\t\n\t\t<h1 id="h1-1">Template</h1><p class="noindent" id="p-1">Test<br />‘—’“–” </p>\n\t\n')
book.assets.root.should.equal('test/files/epubloader') | 142390 | 'use strict'
chai = require 'chai'
should = chai.should()
index = require '../src/index'
Book = index.Book
testbook = {}
describe 'EpubLoader',
() ->
beforeEach (done) ->
load = (err, book) ->
testbook = book
done()
book = Book.fromEpub('test/files/test.epub', 'test/files/epubloader/', load)
describe '#loadEpub',
() ->
it 'Loads the book from an epub',
() ->
book = testbook
# console.log book
book.meta.title.should.equal('The Wonderful Wizard of Oz')
book.meta.author.should.equal('<NAME>')
book.meta.bookId.should.equal('this-is-an-id')
book.meta.lang.should.equal('en')
# book.meta.modified.isoDate.should.equal("2013-06-27T01:29:06Z")
book.meta.date.isoDate.should.equal("2013-05-15T00:00:00Z")
book.meta.version.should.equal("1.0")
book.meta.publisher.should.equal("Bar")
book.meta.subject1.should.equal("Foobar")
book.meta.cover.should.equal("assets/cover.jpg")
book.chapters[0].title.should.equal('Markdown')
book.chapters[0].body.should.equal('\n\t\n\t\t<h1 id="header">header</h1>\n<p class="noindent" id="p-1">Test</p>\n\n\t\n')
book.chapters[1].title.should.equal('HTML')
book.chapters[1].body.should.equal('\n\t\n\t\t<h1 id="h1-1">header</h1><p class="noindent" id="p-1">Test<br />‘—’“–” </p>\n\t\n')
book.chapters[2].title.should.equal('XHTML')
book.chapters[2].body.should.equal('\n\t\n\t\t<h1>header</h1><p>Test<br/></p>\n\t\n')
book.chapters[3].title.should.equal('Template')
book.chapters[3].body.should.equal('\n\t\n\t\t<h1 id="h1-1">Template</h1><p class="noindent" id="p-1">Test<br />‘—’“–” </p>\n\t\n')
book.assets.root.should.equal('test/files/epubloader') | true | 'use strict'
chai = require 'chai'
should = chai.should()
index = require '../src/index'
Book = index.Book
testbook = {}
describe 'EpubLoader',
() ->
beforeEach (done) ->
load = (err, book) ->
testbook = book
done()
book = Book.fromEpub('test/files/test.epub', 'test/files/epubloader/', load)
describe '#loadEpub',
() ->
it 'Loads the book from an epub',
() ->
book = testbook
# console.log book
book.meta.title.should.equal('The Wonderful Wizard of Oz')
book.meta.author.should.equal('PI:NAME:<NAME>END_PI')
book.meta.bookId.should.equal('this-is-an-id')
book.meta.lang.should.equal('en')
# book.meta.modified.isoDate.should.equal("2013-06-27T01:29:06Z")
book.meta.date.isoDate.should.equal("2013-05-15T00:00:00Z")
book.meta.version.should.equal("1.0")
book.meta.publisher.should.equal("Bar")
book.meta.subject1.should.equal("Foobar")
book.meta.cover.should.equal("assets/cover.jpg")
book.chapters[0].title.should.equal('Markdown')
book.chapters[0].body.should.equal('\n\t\n\t\t<h1 id="header">header</h1>\n<p class="noindent" id="p-1">Test</p>\n\n\t\n')
book.chapters[1].title.should.equal('HTML')
book.chapters[1].body.should.equal('\n\t\n\t\t<h1 id="h1-1">header</h1><p class="noindent" id="p-1">Test<br />‘—’“–” </p>\n\t\n')
book.chapters[2].title.should.equal('XHTML')
book.chapters[2].body.should.equal('\n\t\n\t\t<h1>header</h1><p>Test<br/></p>\n\t\n')
book.chapters[3].title.should.equal('Template')
book.chapters[3].body.should.equal('\n\t\n\t\t<h1 id="h1-1">Template</h1><p class="noindent" id="p-1">Test<br />‘—’“–” </p>\n\t\n')
book.assets.root.should.equal('test/files/epubloader') |
[
{
"context": "@robot = robot\n\n save: ->\n attrs =\n name: @name\n score: @score\n @robot.brain.set 'ast",
"end": 121,
"score": 0.599962055683136,
"start": 121,
"tag": "NAME",
"value": ""
},
{
"context": "er.name} <#{player.email}>\"\n mailgun.sendText \"noreply+scrumbot@example.com\", [\n # addresses\n ], subject, body, \"nore",
"end": 652,
"score": 0.9996172189712524,
"start": 624,
"tag": "EMAIL",
"value": "noreply+scrumbot@example.com"
},
{
"context": ".com\", [\n # addresses\n ], subject, body, \"noreply+scrumbot@example.com\", {}, (err) ->\n if err\n console.log \"",
"end": 726,
"score": 0.9997687339782715,
"start": 698,
"tag": "EMAIL",
"value": "noreply+scrumbot@example.com"
}
] | src/models/team.coffee | airbrake/hubot-scrum | 3 | Player = require('./player')
class Team
constructor: (robot) ->
@robot = robot
save: ->
attrs =
name: @name
score: @score
@robot.brain.set 'astroscrum-team', attrs
name: ->
@robot.adapter.client.team.name
score: ->
10
players: ->
players = []
for own key, user of @robot.brain.data.users
roles = user.roles or []
if 'scrum' in roles
players.push new Player(user)
return players
##
# Mail the scrum participants
mail: (subject, body) ->
addresses = @players().map (player) -> "#{player.name} <#{player.email}>"
mailgun.sendText "noreply+scrumbot@example.com", [
# addresses
], subject, body, "noreply+scrumbot@example.com", {}, (err) ->
if err
console.log "[mailgun] Oh noes: " + err
else
console.log "[mailgun] Success!"
return
module.exports = Team
| 107698 | Player = require('./player')
class Team
constructor: (robot) ->
@robot = robot
save: ->
attrs =
name:<NAME> @name
score: @score
@robot.brain.set 'astroscrum-team', attrs
name: ->
@robot.adapter.client.team.name
score: ->
10
players: ->
players = []
for own key, user of @robot.brain.data.users
roles = user.roles or []
if 'scrum' in roles
players.push new Player(user)
return players
##
# Mail the scrum participants
mail: (subject, body) ->
addresses = @players().map (player) -> "#{player.name} <#{player.email}>"
mailgun.sendText "<EMAIL>", [
# addresses
], subject, body, "<EMAIL>", {}, (err) ->
if err
console.log "[mailgun] Oh noes: " + err
else
console.log "[mailgun] Success!"
return
module.exports = Team
| true | Player = require('./player')
class Team
constructor: (robot) ->
@robot = robot
save: ->
attrs =
name:PI:NAME:<NAME>END_PI @name
score: @score
@robot.brain.set 'astroscrum-team', attrs
name: ->
@robot.adapter.client.team.name
score: ->
10
players: ->
players = []
for own key, user of @robot.brain.data.users
roles = user.roles or []
if 'scrum' in roles
players.push new Player(user)
return players
##
# Mail the scrum participants
mail: (subject, body) ->
addresses = @players().map (player) -> "#{player.name} <#{player.email}>"
mailgun.sendText "PI:EMAIL:<EMAIL>END_PI", [
# addresses
], subject, body, "PI:EMAIL:<EMAIL>END_PI", {}, (err) ->
if err
console.log "[mailgun] Oh noes: " + err
else
console.log "[mailgun] Success!"
return
module.exports = Team
|
[
{
"context": "login = ->\n Auth.login(\n username: $scope.username\n password: $scope.password\n rememberMe:",
"end": 335,
"score": 0.6590627431869507,
"start": 327,
"tag": "USERNAME",
"value": "username"
},
{
"context": "n(\n username: $scope.username\n password: $scope.password\n rememberMe: $scope.rememberMe).then(->\n ",
"end": 367,
"score": 0.9767359495162964,
"start": 352,
"tag": "PASSWORD",
"value": "$scope.password"
}
] | src/main/webapp/scripts/app/account/login/login.controller.coffee | BulkSecurityGeneratorProject/solrpress | 0 | 'use strict'
angular.module('solrpressApp').controller 'LoginController', ($rootScope, $scope, $state, $timeout, Auth) ->
$scope.user = {}
$scope.errors = {}
$scope.rememberMe = true
$timeout ->
angular.element('[ng-model="username"]').focus()
return
$scope.login = ->
Auth.login(
username: $scope.username
password: $scope.password
rememberMe: $scope.rememberMe).then(->
$scope.authenticationError = false
if $rootScope.previousStateName == 'register'
$state.go 'home'
else
$rootScope.back()
return
).catch ->
$scope.authenticationError = true
return
return
return
| 135545 | 'use strict'
angular.module('solrpressApp').controller 'LoginController', ($rootScope, $scope, $state, $timeout, Auth) ->
$scope.user = {}
$scope.errors = {}
$scope.rememberMe = true
$timeout ->
angular.element('[ng-model="username"]').focus()
return
$scope.login = ->
Auth.login(
username: $scope.username
password: <PASSWORD>
rememberMe: $scope.rememberMe).then(->
$scope.authenticationError = false
if $rootScope.previousStateName == 'register'
$state.go 'home'
else
$rootScope.back()
return
).catch ->
$scope.authenticationError = true
return
return
return
| true | 'use strict'
angular.module('solrpressApp').controller 'LoginController', ($rootScope, $scope, $state, $timeout, Auth) ->
$scope.user = {}
$scope.errors = {}
$scope.rememberMe = true
$timeout ->
angular.element('[ng-model="username"]').focus()
return
$scope.login = ->
Auth.login(
username: $scope.username
password: PI:PASSWORD:<PASSWORD>END_PI
rememberMe: $scope.rememberMe).then(->
$scope.authenticationError = false
if $rootScope.previousStateName == 'register'
$state.go 'home'
else
$rootScope.back()
return
).catch ->
$scope.authenticationError = true
return
return
return
|
[
{
"context": "verview Tests for the no-new-symbol rule\n# @author Alberto Rodríguez\n###\n\n'use strict'\n\n#-----------------------------",
"end": 81,
"score": 0.9998635053634644,
"start": 64,
"tag": "NAME",
"value": "Alberto Rodríguez"
}
] | src/tests/rules/no-new-symbol.coffee | danielbayley/eslint-plugin-coffee | 21 | ###*
# @fileoverview Tests for the no-new-symbol rule
# @author Alberto Rodríguez
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require 'eslint/lib/rules/no-new-symbol'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester(
parser: path.join(__dirname, '../../..'), env: es6: yes
)
ruleTester.run 'no-new-symbol', rule,
valid: [
"foo = Symbol('foo')"
"(Symbol) -> baz = new Symbol 'baz'"
'''
Symbol = ->
new Symbol()
'''
]
invalid: [
code: "foo = new Symbol('foo')"
errors: [message: '`Symbol` cannot be called as a constructor.']
,
code: '''
->
Symbol = ->
baz = new Symbol('baz')
'''
errors: [message: '`Symbol` cannot be called as a constructor.']
]
| 152828 | ###*
# @fileoverview Tests for the no-new-symbol rule
# @author <NAME>
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require 'eslint/lib/rules/no-new-symbol'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester(
parser: path.join(__dirname, '../../..'), env: es6: yes
)
ruleTester.run 'no-new-symbol', rule,
valid: [
"foo = Symbol('foo')"
"(Symbol) -> baz = new Symbol 'baz'"
'''
Symbol = ->
new Symbol()
'''
]
invalid: [
code: "foo = new Symbol('foo')"
errors: [message: '`Symbol` cannot be called as a constructor.']
,
code: '''
->
Symbol = ->
baz = new Symbol('baz')
'''
errors: [message: '`Symbol` cannot be called as a constructor.']
]
| true | ###*
# @fileoverview Tests for the no-new-symbol rule
# @author PI:NAME:<NAME>END_PI
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require 'eslint/lib/rules/no-new-symbol'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester(
parser: path.join(__dirname, '../../..'), env: es6: yes
)
ruleTester.run 'no-new-symbol', rule,
valid: [
"foo = Symbol('foo')"
"(Symbol) -> baz = new Symbol 'baz'"
'''
Symbol = ->
new Symbol()
'''
]
invalid: [
code: "foo = new Symbol('foo')"
errors: [message: '`Symbol` cannot be called as a constructor.']
,
code: '''
->
Symbol = ->
baz = new Symbol('baz')
'''
errors: [message: '`Symbol` cannot be called as a constructor.']
]
|
[
{
"context": " header:\n showAll: 'Zooniverse Team'\n adamMcMaster:\n title: 'Infrastructure Engineer'",
"end": 506,
"score": 0.5740760564804077,
"start": 502,
"tag": "USERNAME",
"value": "adam"
},
{
"context": " title: 'Infrastructure Engineer'\n bio: '''Adam is responsible for managing the Zooniverse's web ",
"end": 577,
"score": 0.998267650604248,
"start": 573,
"tag": "NAME",
"value": "Adam"
},
{
"context": "ing on a degree in astronomy with the OU.'''\n alexBowyer:\n title: 'Web Science Architect'\n",
"end": 828,
"score": 0.7356126308441162,
"start": 827,
"tag": "NAME",
"value": "a"
},
{
"context": "g on a degree in astronomy with the OU.'''\n alexBowyer:\n title: 'Web Science Architect'\n b",
"end": 837,
"score": 0.7352229356765747,
"start": 828,
"tag": "USERNAME",
"value": "lexBowyer"
},
{
"context": " title: 'Web Science Architect'\n bio: '''Alex worked remotely for Zooniverse from his home in N",
"end": 898,
"score": 0.998427152633667,
"start": 894,
"tag": "NAME",
"value": "Alex"
},
{
"context": "s and developed infrastructure and front-end code. Alex\n is a Dad of three, an improv player, a bo",
"end": 1067,
"score": 0.9983686804771423,
"start": 1063,
"tag": "NAME",
"value": "Alex"
},
{
"context": "d is running five half-marathons in 2016.'''\n alexWeiksnar:\n title: 'Developer'\n bi",
"end": 1182,
"score": 0.6256661415100098,
"start": 1181,
"tag": "NAME",
"value": "a"
},
{
"context": "is running five half-marathons in 2016.'''\n alexWeiksnar:\n title: 'Developer'\n bio: '''Alex ",
"end": 1193,
"score": 0.8614157438278198,
"start": 1182,
"tag": "USERNAME",
"value": "lexWeiksnar"
},
{
"context": "ksnar:\n title: 'Developer'\n bio: '''Alex previously attended University of Miami, where he",
"end": 1242,
"score": 0.9968104362487793,
"start": 1238,
"tag": "NAME",
"value": "Alex"
},
{
"context": " studied Psychology,\n Biology, and English. Alex enjoys reading, coding, and sailing in his free t",
"end": 1347,
"score": 0.9957428574562073,
"start": 1343,
"tag": "NAME",
"value": "Alex"
},
{
"context": "coding, and sailing in his free time.'''\n aliSwanson:\n title: 'Researcher'\n bio: '''Ali ",
"end": 1421,
"score": 0.7966632843017578,
"start": 1414,
"tag": "USERNAME",
"value": "Swanson"
},
{
"context": "nson:\n title: 'Researcher'\n bio: '''Ali spent most of her PhD chasing lions around the Se",
"end": 1470,
"score": 0.995951771736145,
"start": 1467,
"tag": "NAME",
"value": "Ali"
},
{
"context": "Postdoc in Ecology and Citizen Science.'''\n # amitKapadia:\n # title: 'Developer'\n # bio: '''A",
"end": 1735,
"score": 0.6283712983131409,
"start": 1724,
"tag": "USERNAME",
"value": "amitKapadia"
},
{
"context": "a:\n # title: 'Developer'\n # bio: '''Amit was a developer at the Adler Planetarium.'''\n ",
"end": 1788,
"score": 0.9981034398078918,
"start": 1784,
"tag": "NAME",
"value": "Amit"
},
{
"context": "was a developer at the Adler Planetarium.'''\n amyBoyer:\n title: 'Developer'\n bio: '",
"end": 1841,
"score": 0.41575273871421814,
"start": 1840,
"tag": "NAME",
"value": "a"
},
{
"context": "s a developer at the Adler Planetarium.'''\n amyBoyer:\n title: 'Developer'\n bio: '''Am",
"end": 1845,
"score": 0.5745405554771423,
"start": 1841,
"tag": "USERNAME",
"value": "myBo"
},
{
"context": "Boyer:\n title: 'Developer'\n bio: '''Amy has been a Zooniverse developer at the Adler sinc",
"end": 1896,
"score": 0.9975197315216064,
"start": 1893,
"tag": "NAME",
"value": "Amy"
},
{
"context": " couldn't be happier to have landed here.'''\n andreaSimenstad:\n title: 'Developer'\n b",
"end": 2159,
"score": 0.7808599472045898,
"start": 2156,
"tag": "NAME",
"value": "and"
},
{
"context": "ldn't be happier to have landed here.'''\n andreaSimenstad:\n title: 'Developer'\n bio: ''",
"end": 2165,
"score": 0.5866526365280151,
"start": 2159,
"tag": "USERNAME",
"value": "reaSim"
},
{
"context": "be happier to have landed here.'''\n andreaSimenstad:\n title: 'Developer'\n bio: '''Andre",
"end": 2171,
"score": 0.5995508432388306,
"start": 2165,
"tag": "NAME",
"value": "enstad"
},
{
"context": "nstad:\n title: 'Developer'\n bio: '''Andrea joined Zooniverse as a developer at the Universit",
"end": 2222,
"score": 0.9982503652572632,
"start": 2216,
"tag": "NAME",
"value": "Andrea"
},
{
"context": "llege with a degree in Cognitive Science.'''\n arfonSmith:\n title: 'Technical Lead'\n ",
"end": 2484,
"score": 0.6645645499229431,
"start": 2482,
"tag": "NAME",
"value": "ar"
},
{
"context": "ge with a degree in Cognitive Science.'''\n arfonSmith:\n title: 'Technical Lead'\n bio: ",
"end": 2489,
"score": 0.6780115962028503,
"start": 2484,
"tag": "USERNAME",
"value": "fonSm"
},
{
"context": "th a degree in Cognitive Science.'''\n arfonSmith:\n title: 'Technical Lead'\n bio: '''",
"end": 2492,
"score": 0.46901935338974,
"start": 2489,
"tag": "NAME",
"value": "ith"
},
{
"context": ":\n title: 'Technical Lead'\n bio: '''Arfon was co-founder and Technical Lead of the Zooniver",
"end": 2547,
"score": 0.9903024435043335,
"start": 2542,
"tag": "NAME",
"value": "Arfon"
},
{
"context": "e for the first five years of the project.\n Arfon served as Director of Citizen Science at the Adle",
"end": 2654,
"score": 0.8037453293800354,
"start": 2649,
"tag": "NAME",
"value": "Arfon"
},
{
"context": "o-lead of the Zooniverse until fall 2013.'''\n beckyRother:\n title: 'Visual Designer'\n ",
"end": 2776,
"score": 0.5034002661705017,
"start": 2774,
"tag": "NAME",
"value": "be"
},
{
"context": "ead of the Zooniverse until fall 2013.'''\n beckyRother:\n title: 'Visual Designer'\n bi",
"end": 2780,
"score": 0.4734431207180023,
"start": 2776,
"tag": "USERNAME",
"value": "ckyR"
},
{
"context": "of the Zooniverse until fall 2013.'''\n beckyRother:\n title: 'Visual Designer'\n bio: ''",
"end": 2785,
"score": 0.4482395052909851,
"start": 2780,
"tag": "NAME",
"value": "other"
},
{
"context": "\n title: 'Visual Designer'\n bio: '''Becky joined the Zooniverse team as designer in 2017. W",
"end": 2841,
"score": 0.9825859665870667,
"start": 2836,
"tag": "NAME",
"value": "Becky"
},
{
"context": " title: 'Web Developer Intern'\n bio: '''Beverley is an English and German literature graduate and ",
"end": 3124,
"score": 0.9335891604423523,
"start": 3116,
"tag": "NAME",
"value": "Beverley"
},
{
"context": "avid fan of geese and enjoys motorbiking.'''\n brianCarstensen:\n title: 'UX Developer'\n ",
"end": 3305,
"score": 0.5690627098083496,
"start": 3300,
"tag": "NAME",
"value": "brian"
},
{
"context": "of geese and enjoys motorbiking.'''\n brianCarstensen:\n title: 'UX Developer'\n bio: '''Br",
"end": 3315,
"score": 0.5808045268058777,
"start": 3308,
"tag": "NAME",
"value": "stensen"
},
{
"context": "en:\n title: 'UX Developer'\n bio: '''Brian Carstensen moved from Chicago to Oxford and back again. Bria",
"end": 3379,
"score": 0.9996094107627869,
"start": 3363,
"tag": "NAME",
"value": "Brian Carstensen"
},
{
"context": "ensen moved from Chicago to Oxford and back again. Brian has a degree\n in graphic design from Colum",
"end": 3430,
"score": 0.9987387657165527,
"start": 3425,
"tag": "NAME",
"value": "Brian"
},
{
"context": " enjoys playing an obscure form of rugby.'''\n chrisLintott:\n title: 'Zooniverse PI'\n bi",
"end": 4097,
"score": 0.7729400396347046,
"start": 4092,
"tag": "NAME",
"value": "chris"
},
{
"context": "s playing an obscure form of rugby.'''\n chrisLintott:\n title: 'Zooniverse PI'\n bio: '",
"end": 4101,
"score": 0.5451034307479858,
"start": 4097,
"tag": "USERNAME",
"value": "Lint"
},
{
"context": "aying an obscure form of rugby.'''\n chrisLintott:\n title: 'Zooniverse PI'\n bio: '''A",
"end": 4104,
"score": 0.9721443057060242,
"start": 4101,
"tag": "NAME",
"value": "ott"
},
{
"context": " Zoo and the Zooniverse that grew from it,\n Chris is interested in how galaxies form and evolve, ho",
"end": 4249,
"score": 0.9988535642623901,
"start": 4244,
"tag": "NAME",
"value": "Chris"
},
{
"context": " Chicago Fire can get their act together.'''\n chrisSnyder:\n title: 'Project Manager'\n ",
"end": 4415,
"score": 0.912816047668457,
"start": 4413,
"tag": "NAME",
"value": "ch"
},
{
"context": "icago Fire can get their act together.'''\n chrisSnyder:\n title: 'Project Manager'\n bio: ''",
"end": 4424,
"score": 0.7948226928710938,
"start": 4415,
"tag": "USERNAME",
"value": "risSnyder"
},
{
"context": "\n title: 'Project Manager'\n bio: '''Chris Snyder began working on the Zooniverse team in fall 2012",
"end": 4487,
"score": 0.999700665473938,
"start": 4475,
"tag": "NAME",
"value": "Chris Snyder"
},
{
"context": "er science from the University of Dayton.'''\n christopherDoogue:\n title: 'Project Assistant'\n ",
"end": 4713,
"score": 0.8000003099441528,
"start": 4702,
"tag": "NAME",
"value": "christopher"
},
{
"context": "rom the University of Dayton.'''\n christopherDoogue:\n title: 'Project Assistant'\n ",
"end": 4714,
"score": 0.7409682869911194,
"start": 4713,
"tag": "USERNAME",
"value": "D"
},
{
"context": "om the University of Dayton.'''\n christopherDoogue:\n title: 'Project Assistant'\n bio: ",
"end": 4719,
"score": 0.8742009401321411,
"start": 4714,
"tag": "NAME",
"value": "oogue"
},
{
"context": " title: 'Project Assistant'\n bio: '''Chris supported the Zooniverse Oxford team from 2014-16",
"end": 4777,
"score": 0.9992870092391968,
"start": 4772,
"tag": "NAME",
"value": "Chris"
},
{
"context": "ke he's smiling in the face of adversity!'''\n colemanKrawczyk:\n title: 'Data Scientist'\n ",
"end": 5062,
"score": 0.8782647848129272,
"start": 5060,
"tag": "NAME",
"value": "co"
},
{
"context": "he's smiling in the face of adversity!'''\n colemanKrawczyk:\n title: 'Data Scientist'\n b",
"end": 5068,
"score": 0.6585912704467773,
"start": 5062,
"tag": "USERNAME",
"value": "lemanK"
},
{
"context": "miling in the face of adversity!'''\n colemanKrawczyk:\n title: 'Data Scientist'\n bio: '''",
"end": 5075,
"score": 0.8919845819473267,
"start": 5068,
"tag": "NAME",
"value": "rawczyk"
},
{
"context": ":\n title: 'Data Scientist'\n bio: '''Coleman is helping to create new data analysis and visual",
"end": 5132,
"score": 0.9971272945404053,
"start": 5125,
"tag": "NAME",
"value": "Coleman"
},
{
"context": "D in astrophysics from Drexel University.'''\n darrenMcRoy:\n title: 'Community Manager'\n ",
"end": 5390,
"score": 0.9010316729545593,
"start": 5387,
"tag": "NAME",
"value": "dar"
},
{
"context": " astrophysics from Drexel University.'''\n darrenMcRoy:\n title: 'Community Manager'\n bio:",
"end": 5397,
"score": 0.6447913646697998,
"start": 5390,
"tag": "USERNAME",
"value": "renMcRo"
},
{
"context": "hysics from Drexel University.'''\n darrenMcRoy:\n title: 'Community Manager'\n bio: ",
"end": 5398,
"score": 0.7897369265556335,
"start": 5397,
"tag": "NAME",
"value": "y"
},
{
"context": " title: 'Community Manager'\n bio: '''Darren (DZM) served as a liaison to the Zooniverse commu",
"end": 5457,
"score": 0.9966893196105957,
"start": 5451,
"tag": "NAME",
"value": "Darren"
},
{
"context": "mateur author, and hopeless animal lover.'''\n darrylWright:\n title: 'Researcher'\n b",
"end": 5707,
"score": 0.6006752252578735,
"start": 5706,
"tag": "NAME",
"value": "d"
},
{
"context": "teur author, and hopeless animal lover.'''\n darrylWright:\n title: 'Researcher'\n bio: 'D",
"end": 5713,
"score": 0.6737079620361328,
"start": 5707,
"tag": "USERNAME",
"value": "arrylW"
},
{
"context": "uthor, and hopeless animal lover.'''\n darrylWright:\n title: 'Researcher'\n bio: 'Darryl",
"end": 5718,
"score": 0.7064256072044373,
"start": 5713,
"tag": "NAME",
"value": "right"
},
{
"context": "Wright:\n title: 'Researcher'\n bio: 'Darryl is doing machine learning research with the Zooni",
"end": 5768,
"score": 0.9969813227653503,
"start": 5762,
"tag": "NAME",
"value": "Darryl"
},
{
"context": "rch with the Zooniverse, based in Oxford.'\n # edPaget:\n # title: 'Developer'\n # bio: '''E",
"end": 5858,
"score": 0.9273675084114075,
"start": 5851,
"tag": "USERNAME",
"value": "edPaget"
},
{
"context": "t:\n # title: 'Developer'\n # bio: '''Ed Paget joined Adler's Zooniverse Team as a software deve",
"end": 5915,
"score": 0.9993993639945984,
"start": 5907,
"tag": "NAME",
"value": "Ed Paget"
},
{
"context": "worked as a freelance programmer and photographer. Ed graduated from\n # Northwestern University ",
"end": 6064,
"score": 0.6479154229164124,
"start": 6062,
"tag": "NAME",
"value": "Ed"
},
{
"context": "University with a major in Radio/TV/Film.'''\n grantMiller:\n title: 'Communications Lead'\n ",
"end": 6159,
"score": 0.7017934918403625,
"start": 6154,
"tag": "NAME",
"value": "grant"
},
{
"context": "sity with a major in Radio/TV/Film.'''\n grantMiller:\n title: 'Communications Lead'\n ",
"end": 6160,
"score": 0.6857417225837708,
"start": 6159,
"tag": "USERNAME",
"value": "M"
},
{
"context": "ity with a major in Radio/TV/Film.'''\n grantMiller:\n title: 'Communications Lead'\n bio",
"end": 6165,
"score": 0.6537421941757202,
"start": 6160,
"tag": "NAME",
"value": "iller"
},
{
"context": "'\n bio: '''A former exoplanetary scientist, Grant is now responsible for communicating with our vol",
"end": 6258,
"score": 0.9966576099395752,
"start": 6253,
"tag": "NAME",
"value": "Grant"
},
{
"context": " and publishes the Daily Zooniverse blog.'''\n hannahSewell:\n title: 'Web Development placement studen",
"end": 6463,
"score": 0.8118225336074829,
"start": 6451,
"tag": "NAME",
"value": "hannahSewell"
},
{
"context": "eb Development placement student'\n bio: '''Hannah is a PhD student in plant genetics from The Unive",
"end": 6538,
"score": 0.9980738759040833,
"start": 6532,
"tag": "NAME",
"value": "Hannah"
},
{
"context": "w months and is definitely not an intern.'''\n helenSpiers:\n title: 'Researcher'\n bio: '''Afte",
"end": 6753,
"score": 0.943058967590332,
"start": 6742,
"tag": "NAME",
"value": "helenSpiers"
},
{
"context": " an intern.'''\n helenSpiers:\n title: 'Researcher'\n bio: '''After finishing a PhD studying t",
"end": 6781,
"score": 0.8832241296768188,
"start": 6771,
"tag": "NAME",
"value": "Researcher"
},
{
"context": "ng the molecular basis of human brain development, Helen joined the Zooniverse as a Postdoc in citizen sci",
"end": 6883,
"score": 0.9966568946838379,
"start": 6878,
"tag": "NAME",
"value": "Helen"
},
{
"context": " in citizen science and medical research.'''\n gregHines:\n title: 'Data Scientist'\n bio: '''",
"end": 6978,
"score": 0.9350836873054504,
"start": 6969,
"tag": "NAME",
"value": "gregHines"
},
{
"context": "cal research.'''\n gregHines:\n title: 'Data Scientist'\n bio: '''Greg used machine learning and s",
"end": 7010,
"score": 0.9038199782371521,
"start": 6996,
"tag": "NAME",
"value": "Data Scientist"
},
{
"context": ":\n title: 'Data Scientist'\n bio: '''Greg used machine learning and statistics to help proj",
"end": 7032,
"score": 0.995132565498352,
"start": 7028,
"tag": "NAME",
"value": "Greg"
},
{
"context": "ience from University of Waterloo, Canada.\n Greg loves to eat pancakes with real maple syrup and r",
"end": 7218,
"score": 0.9874504804611206,
"start": 7214,
"tag": "NAME",
"value": "Greg"
},
{
"context": " real maple syrup and run ultramarathons.'''\n heathVanSingel:\n title: 'Designer'\n bio: '''Heath ",
"end": 7310,
"score": 0.945440948009491,
"start": 7296,
"tag": "NAME",
"value": "heathVanSingel"
},
{
"context": "rathons.'''\n heathVanSingel:\n title: 'Designer'\n bio: '''Heath was the UX/UI Designer at ",
"end": 7336,
"score": 0.9021393656730652,
"start": 7328,
"tag": "NAME",
"value": "Designer"
},
{
"context": "Singel:\n title: 'Designer'\n bio: '''Heath was the UX/UI Designer at the Zooniverse where he",
"end": 7359,
"score": 0.983573317527771,
"start": 7354,
"tag": "NAME",
"value": "Heath"
},
{
"context": "ng his new home in the Pacific Northwest.'''\n hughDickinson:\n title: 'Researcher'\n bio: '''Hugh",
"end": 7642,
"score": 0.9243548512458801,
"start": 7629,
"tag": "NAME",
"value": "hughDickinson"
},
{
"context": "orthwest.'''\n hughDickinson:\n title: 'Researcher'\n bio: '''Hugh is a postdoc studying the Z",
"end": 7670,
"score": 0.7047228217124939,
"start": 7660,
"tag": "NAME",
"value": "Researcher"
},
{
"context": "nson:\n title: 'Researcher'\n bio: '''Hugh is a postdoc studying the Zooniverse.'''\n ja",
"end": 7692,
"score": 0.9940532445907593,
"start": 7688,
"tag": "NAME",
"value": "Hugh"
},
{
"context": "ugh is a postdoc studying the Zooniverse.'''\n jamesArtz:\n title: 'Developer'\n bio: '''James",
"end": 7749,
"score": 0.9184554815292358,
"start": 7740,
"tag": "NAME",
"value": "jamesArtz"
},
{
"context": "e Zooniverse.'''\n jamesArtz:\n title: 'Developer'\n bio: '''James joined the Zooniverse team",
"end": 7776,
"score": 0.9305791854858398,
"start": 7767,
"tag": "NAME",
"value": "Developer"
},
{
"context": "sArtz:\n title: 'Developer'\n bio: '''James joined the Zooniverse team in 2017. Before discov",
"end": 7799,
"score": 0.996129035949707,
"start": 7794,
"tag": "NAME",
"value": "James"
},
{
"context": "king and the ancient art of fermentation.'''\n jimODonnell:\n title: 'UX Developer'\n ",
"end": 8075,
"score": 0.529021680355072,
"start": 8074,
"tag": "NAME",
"value": "j"
},
{
"context": " the ancient art of fermentation.'''\n jimODonnell:\n title: 'UX Developer'\n bio: '''Pr",
"end": 8085,
"score": 0.9728320837020874,
"start": 8081,
"tag": "NAME",
"value": "nell"
},
{
"context": "Standards organiser, Amnesty UK activist.'''\n jenGupta:\n title: 'Educator'\n bio: ''",
"end": 8277,
"score": 0.9457510113716125,
"start": 8276,
"tag": "NAME",
"value": "j"
},
{
"context": "andards organiser, Amnesty UK activist.'''\n jenGupta:\n title: 'Educator'\n bio: '''Jen",
"end": 8281,
"score": 0.6545730829238892,
"start": 8277,
"tag": "USERNAME",
"value": "enGu"
},
{
"context": "rds organiser, Amnesty UK activist.'''\n jenGupta:\n title: 'Educator'\n bio: '''Jen wo",
"end": 8284,
"score": 0.7198923826217651,
"start": 8281,
"tag": "NAME",
"value": "pta"
},
{
"context": "nGupta:\n title: 'Educator'\n bio: '''Jen works on Galaxy Zoo education in her role as the ",
"end": 8331,
"score": 0.9986982345581055,
"start": 8328,
"tag": "NAME",
"value": "Jen"
},
{
"context": " galactic nuclei were her first love.'''\n jordanMartin:\n title: 'Visual Designer'\n ",
"end": 8560,
"score": 0.9754477739334106,
"start": 8559,
"tag": "NAME",
"value": "j"
},
{
"context": " galactic nuclei were her first love.'''\n jordanMartin:\n title: 'Visual Designer'\n bio: ",
"end": 8569,
"score": 0.5859271287918091,
"start": 8560,
"tag": "USERNAME",
"value": "ordanMart"
},
{
"context": "ic nuclei were her first love.'''\n jordanMartin:\n title: 'Visual Designer'\n bio: ''",
"end": 8571,
"score": 0.8408925533294678,
"start": 8569,
"tag": "NAME",
"value": "in"
},
{
"context": "\n title: 'Visual Designer'\n bio: '''Jordan joined at the Adler Planetarium as Zooniverse's V",
"end": 8628,
"score": 0.9993563890457153,
"start": 8622,
"tag": "NAME",
"value": "Jordan"
},
{
"context": "er\n two cats and many houseplants.'''\n julieFeldt:\n title: 'Educator'\n bio: '''J",
"end": 8908,
"score": 0.8392281532287598,
"start": 8903,
"tag": "NAME",
"value": "julie"
},
{
"context": " two cats and many houseplants.'''\n julieFeldt:\n title: 'Educator'\n bio: '''Ju",
"end": 8909,
"score": 0.5213552117347717,
"start": 8908,
"tag": "USERNAME",
"value": "F"
},
{
"context": " two cats and many houseplants.'''\n julieFeldt:\n title: 'Educator'\n bio: '''Julie ",
"end": 8913,
"score": 0.9489805698394775,
"start": 8909,
"tag": "NAME",
"value": "eldt"
},
{
"context": "eFeldt:\n title: 'Educator'\n bio: '''Julie has a background in space physics and museum stud",
"end": 8962,
"score": 0.9992997646331787,
"start": 8957,
"tag": "NAME",
"value": "Julie"
},
{
"context": "e for her love of cupcakes and chocolate.'''\n karenMasters:\n title: 'Researcher'\n b",
"end": 9215,
"score": 0.9330561757087708,
"start": 9214,
"tag": "NAME",
"value": "k"
},
{
"context": "for her love of cupcakes and chocolate.'''\n karenMasters:\n title: 'Researcher'\n bio: '",
"end": 9220,
"score": 0.6541153192520142,
"start": 9215,
"tag": "USERNAME",
"value": "arenM"
},
{
"context": "er love of cupcakes and chocolate.'''\n karenMasters:\n title: 'Researcher'\n bio: '''Kare",
"end": 9226,
"score": 0.7084664702415466,
"start": 9220,
"tag": "NAME",
"value": "asters"
},
{
"context": "ters:\n title: 'Researcher'\n bio: '''Karen is an astronomer and the Project Scientist of Gal",
"end": 9277,
"score": 0.9993739128112793,
"start": 9272,
"tag": "NAME",
"value": "Karen"
},
{
"context": "the evolution of\n spiral galaxies.'''\n kellyBorden:\n title: 'Educator'\n bio:",
"end": 9486,
"score": 0.9691704511642456,
"start": 9485,
"tag": "NAME",
"value": "k"
},
{
"context": "e evolution of\n spiral galaxies.'''\n kellyBorden:\n title: 'Educator'\n bio: '''W",
"end": 9491,
"score": 0.5815200805664062,
"start": 9486,
"tag": "USERNAME",
"value": "ellyB"
},
{
"context": "lution of\n spiral galaxies.'''\n kellyBorden:\n title: 'Educator'\n bio: '''With a",
"end": 9496,
"score": 0.8897367119789124,
"start": 9491,
"tag": "NAME",
"value": "orden"
},
{
"context": " bio: '''With a background in museum education, Kelly joined the Zooniverse in 2011 to bring\n an",
"end": 9584,
"score": 0.9991048574447632,
"start": 9579,
"tag": "NAME",
"value": "Kelly"
},
{
"context": "colate, cats, coffee, and more chocolate.'''\n kyleWillett:\n title: 'Researcher'\n bi",
"end": 9799,
"score": 0.9595384001731873,
"start": 9798,
"tag": "NAME",
"value": "k"
},
{
"context": "late, cats, coffee, and more chocolate.'''\n kyleWillett:\n title: 'Researcher'\n bio: '",
"end": 9803,
"score": 0.7450422048568726,
"start": 9799,
"tag": "USERNAME",
"value": "yleW"
},
{
"context": ", cats, coffee, and more chocolate.'''\n kyleWillett:\n title: 'Researcher'\n bio: '''Kyle",
"end": 9809,
"score": 0.810025691986084,
"start": 9803,
"tag": "NAME",
"value": "illett"
},
{
"context": "lett:\n title: 'Researcher'\n bio: '''Kyle is an astronomer who studies galaxies, masers, an",
"end": 9859,
"score": 0.999523401260376,
"start": 9855,
"tag": "NAME",
"value": "Kyle"
},
{
"context": "eloped advanced tools for the volunteers.'''\n lauraTrouille:\n title: 'Zooniverse co-I'\n ",
"end": 10106,
"score": 0.7738508582115173,
"start": 10101,
"tag": "NAME",
"value": "laura"
},
{
"context": "e: 'Zooniverse co-I'\n bio: '''In July 2015, Laura became Director of Citizen Science at the Adler P",
"end": 10184,
"score": 0.9937475919723511,
"start": 10179,
"tag": "NAME",
"value": "Laura"
},
{
"context": "erby queen aptly named ‘The Big Bang’.'''\n lauraWhyte:\n title: 'Adler Planetarium Zooniverse Dir",
"end": 10450,
"score": 0.8971361517906189,
"start": 10442,
"tag": "USERNAME",
"value": "uraWhyte"
},
{
"context": " Planetarium Zooniverse Director'\n bio: '''Laura was the Director of Citizen Science at Adler Plan",
"end": 10528,
"score": 0.9888102412223816,
"start": 10523,
"tag": "NAME",
"value": "Laura"
},
{
"context": "Zooniverse from fall 2013 to summer 2015.'''\n lucyFortson:\n title: 'University of Minnesota Zooniver",
"end": 10675,
"score": 0.8402779698371887,
"start": 10664,
"tag": "USERNAME",
"value": "lucyFortson"
},
{
"context": "eze a bit of galaxy evolution science in.'''\n mariamSaeedi:\n title: 'Web Developer Intern'\n bi",
"end": 11038,
"score": 0.8685348629951477,
"start": 11026,
"tag": "NAME",
"value": "mariamSaeedi"
},
{
"context": " title: 'Web Developer Intern'\n bio: '''Mariam is the 2017 Web Development Intern at Zooniverse.",
"end": 11100,
"score": 0.9987306594848633,
"start": 11094,
"tag": "NAME",
"value": "Mariam"
},
{
"context": " currently learning JavaScript and Rails.'''\n markBouslog:\n title: 'Developer'\n bio: '''Mark ",
"end": 11263,
"score": 0.7964676022529602,
"start": 11252,
"tag": "USERNAME",
"value": "markBouslog"
},
{
"context": "uslog:\n title: 'Developer'\n bio: '''Mark is a front-end web developer for the Zooniverse t",
"end": 11312,
"score": 0.9950222969055176,
"start": 11308,
"tag": "NAME",
"value": "Mark"
},
{
"context": " programming, citizen science and coffee.'''\n martenVeldthuis:\n title: 'Developer'\n ",
"end": 11627,
"score": 0.5862351655960083,
"start": 11626,
"tag": "NAME",
"value": "m"
},
{
"context": "rogramming, citizen science and coffee.'''\n martenVeldthuis:\n title: 'Developer'\n bio: '''Ma",
"end": 11638,
"score": 0.8736141324043274,
"start": 11627,
"tag": "USERNAME",
"value": "artenVeldth"
},
{
"context": " citizen science and coffee.'''\n martenVeldthuis:\n title: 'Developer'\n bio: '''Marte",
"end": 11641,
"score": 0.5042429566383362,
"start": 11638,
"tag": "NAME",
"value": "uis"
},
{
"context": "thuis:\n title: 'Developer'\n bio: '''Marten joined the development team in 2015. He has a deg",
"end": 11692,
"score": 0.998172402381897,
"start": 11686,
"tag": "NAME",
"value": "Marten"
},
{
"context": "science and enjoys crafting maintainable software. Marten learned about orbital\n mechanics from Kerb",
"end": 11823,
"score": 0.9955114722251892,
"start": 11817,
"tag": "NAME",
"value": "Marten"
},
{
"context": "'s therefore basically an astrophysicist.'''\n megSchwamb:\n title: 'Researcher'\n bio: '''Meg ",
"end": 11969,
"score": 0.7881763577461243,
"start": 11959,
"tag": "USERNAME",
"value": "megSchwamb"
},
{
"context": "wamb:\n title: 'Researcher'\n bio: '''Meg is a planetary scientist and astronomer involved ",
"end": 12018,
"score": 0.6116432547569275,
"start": 12015,
"tag": "NAME",
"value": "Meg"
},
{
"context": "ndness for baking, soccer, and champagne.'''\n melanieBeck:\n title: 'Researcher'\n bio",
"end": 12300,
"score": 0.8063534498214722,
"start": 12298,
"tag": "NAME",
"value": "me"
},
{
"context": "ess for baking, soccer, and champagne.'''\n melanieBeck:\n title: 'Researcher'\n bio: '''A ",
"end": 12307,
"score": 0.7664422392845154,
"start": 12300,
"tag": "USERNAME",
"value": "lanieBe"
},
{
"context": " baking, soccer, and champagne.'''\n melanieBeck:\n title: 'Researcher'\n bio: '''A Ph",
"end": 12309,
"score": 0.650037944316864,
"start": 12307,
"tag": "NAME",
"value": "ck"
},
{
"context": ": '''A PhD student at the University of Minnesota, Melanie works on combining machine learning\n with ",
"end": 12408,
"score": 0.9966536164283752,
"start": 12401,
"tag": "NAME",
"value": "Melanie"
},
{
"context": "galaxies that future telescopes will see.'''\n michaelParrish:\n title: 'Rails/Backend Devel",
"end": 12628,
"score": 0.8160425424575806,
"start": 12627,
"tag": "NAME",
"value": "m"
},
{
"context": "laxies that future telescopes will see.'''\n michaelParrish:\n title: 'Rails/Backend Developer'\n ",
"end": 12635,
"score": 0.917242705821991,
"start": 12628,
"tag": "USERNAME",
"value": "ichaelP"
},
{
"context": "that future telescopes will see.'''\n michaelParrish:\n title: 'Rails/Backend Developer'\n ",
"end": 12638,
"score": 0.4943746328353882,
"start": 12635,
"tag": "NAME",
"value": "arr"
},
{
"context": "t future telescopes will see.'''\n michaelParrish:\n title: 'Rails/Backend Developer'\n ",
"end": 12641,
"score": 0.5191287994384766,
"start": 12638,
"tag": "USERNAME",
"value": "ish"
},
{
"context": "daily. Dog, fishing, snakes, and bourbon.'''\n noahMalmed: \n title: 'Mobile App Developer'\n ",
"end": 12811,
"score": 0.6969313621520996,
"start": 12807,
"tag": "NAME",
"value": "noah"
},
{
"context": ". Dog, fishing, snakes, and bourbon.'''\n noahMalmed: \n title: 'Mobile App Developer'\n ",
"end": 12814,
"score": 0.7744672894477844,
"start": 12811,
"tag": "USERNAME",
"value": "Mal"
},
{
"context": "og, fishing, snakes, and bourbon.'''\n noahMalmed: \n title: 'Mobile App Developer'\n b",
"end": 12817,
"score": 0.5684101581573486,
"start": 12814,
"tag": "NAME",
"value": "med"
},
{
"context": " title: 'Mobile App Developer'\n bio: '''Noah mainly has a background in mobile app developme",
"end": 12876,
"score": 0.8719095587730408,
"start": 12874,
"tag": "NAME",
"value": "No"
},
{
"context": " and backend experience. \n Outside of work, Noah enjoys cooking, baking and climbing.'''\n per",
"end": 13008,
"score": 0.7552205920219421,
"start": 13004,
"tag": "NAME",
"value": "Noah"
},
{
"context": "Noah enjoys cooking, baking and climbing.'''\n perryRoper:\n title: 'Developer'\n bio: 'Pe",
"end": 13060,
"score": 0.7733008861541748,
"start": 13055,
"tag": "NAME",
"value": "perry"
},
{
"context": "njoys cooking, baking and climbing.'''\n perryRoper:\n title: 'Developer'\n bio: 'Per",
"end": 13061,
"score": 0.6395263075828552,
"start": 13060,
"tag": "USERNAME",
"value": "R"
},
{
"context": "joys cooking, baking and climbing.'''\n perryRoper:\n title: 'Developer'\n bio: 'Perry w",
"end": 13065,
"score": 0.8916316628456116,
"start": 13061,
"tag": "NAME",
"value": "oper"
},
{
"context": "ryRoper:\n title: 'Developer'\n bio: 'Perry was a developer with the Zooniverse, based in Oxf",
"end": 13113,
"score": 0.9974828362464905,
"start": 13108,
"tag": "NAME",
"value": "Perry"
},
{
"context": "loper with the Zooniverse, based in Oxford.'\n rebeccaSmethurst:\n title: 'Researcher'\n bio: '''Beck",
"end": 13191,
"score": 0.9329699277877808,
"start": 13175,
"tag": "NAME",
"value": "rebeccaSmethurst"
},
{
"context": " Oxford.'\n rebeccaSmethurst:\n title: 'Researcher'\n bio: '''Becky is an astrophysicist worki",
"end": 13219,
"score": 0.7535349130630493,
"start": 13209,
"tag": "NAME",
"value": "Researcher"
},
{
"context": "urst:\n title: 'Researcher'\n bio: '''Becky is an astrophysicist working towards her doctorat",
"end": 13242,
"score": 0.9799520373344421,
"start": 13237,
"tag": "NAME",
"value": "Becky"
},
{
"context": " outreach, the Zooniverse and everything.'''\n robinSchaaf:\n title: 'Mobile App Developer'\n ",
"end": 13485,
"score": 0.8809878826141357,
"start": 13480,
"tag": "NAME",
"value": "robin"
},
{
"context": "ach, the Zooniverse and everything.'''\n robinSchaaf:\n title: 'Mobile App Developer'\n ",
"end": 13486,
"score": 0.5082099437713623,
"start": 13485,
"tag": "USERNAME",
"value": "S"
},
{
"context": "ch, the Zooniverse and everything.'''\n robinSchaaf:\n title: 'Mobile App Developer'\n bi",
"end": 13491,
"score": 0.8634673357009888,
"start": 13486,
"tag": "NAME",
"value": "chaaf"
},
{
"context": " title: 'Mobile App Developer'\n bio: '''Robin has a background in web development for education",
"end": 13552,
"score": 0.9976484775543213,
"start": 13547,
"tag": "NAME",
"value": "Robin"
},
{
"context": "joys board games and playing bass guitar.'''\n robertSimpson:\n title: 'Developer'\n bio: '",
"end": 13700,
"score": 0.7584576606750488,
"start": 13694,
"tag": "NAME",
"value": "robert"
},
{
"context": "ard games and playing bass guitar.'''\n robertSimpson:\n title: 'Developer'\n bio: 'Robe",
"end": 13704,
"score": 0.8793908953666687,
"start": 13700,
"tag": "USERNAME",
"value": "Simp"
},
{
"context": "games and playing bass guitar.'''\n robertSimpson:\n title: 'Developer'\n bio: 'Robert ",
"end": 13707,
"score": 0.6110891103744507,
"start": 13704,
"tag": "NAME",
"value": "son"
},
{
"context": "Simpson:\n title: 'Developer'\n bio: 'Robert was one of the founding developers of the Zoonive",
"end": 13756,
"score": 0.9994325637817383,
"start": 13750,
"tag": "NAME",
"value": "Robert"
},
{
"context": "nd you are losing theirs, you are probably\n Rob Simpson.'\n rogerHutchings:\n title: 'Developer",
"end": 13937,
"score": 0.9993529319763184,
"start": 13926,
"tag": "NAME",
"value": "Rob Simpson"
},
{
"context": "eirs, you are probably\n Rob Simpson.'\n rogerHutchings:\n title: 'Developer'\n bio:",
"end": 13951,
"score": 0.6646283864974976,
"start": 13946,
"tag": "NAME",
"value": "roger"
},
{
"context": "you are probably\n Rob Simpson.'\n rogerHutchings:\n title: 'Developer'\n bio: ",
"end": 13952,
"score": 0.5593200325965881,
"start": 13951,
"tag": "USERNAME",
"value": "H"
},
{
"context": "ou are probably\n Rob Simpson.'\n rogerHutchings:\n title: 'Developer'\n bio: '''Roger",
"end": 13960,
"score": 0.6513842344284058,
"start": 13952,
"tag": "NAME",
"value": "utchings"
},
{
"context": "hings:\n title: 'Developer'\n bio: '''Roger builds front end interfaces for the Zooniverse, a",
"end": 14010,
"score": 0.990414559841156,
"start": 14005,
"tag": "NAME",
"value": "Roger"
},
{
"context": "ing\n motorbikes in his spare time.'''\n samanthaBlickhan:\n title: 'IMLS Postdoctoral Fellow'\n ",
"end": 14162,
"score": 0.9556424021720886,
"start": 14146,
"tag": "USERNAME",
"value": "samanthaBlickhan"
},
{
"context": "title: 'IMLS Postdoctoral Fellow'\n bio: '''Samantha Blickhan is the IMLS Postdoctoral Fellow in the Department",
"end": 14239,
"score": 0.9998964667320251,
"start": 14222,
"tag": "NAME",
"value": "Samantha Blickhan"
},
{
"context": "writing systems, technology and pedagogy.'''\n sandorKruk:\n title: 'Researcher'\n bio: '''Sand",
"end": 14703,
"score": 0.9461343288421631,
"start": 14693,
"tag": "USERNAME",
"value": "sandorKruk"
},
{
"context": "Kruk:\n title: 'Researcher'\n bio: '''Sandor is a graduate student working on his PhD in Astro",
"end": 14755,
"score": 0.9981051683425903,
"start": 14749,
"tag": "NAME",
"value": "Sandor"
},
{
"context": "telescopes, and dancing in his free time.'''\n sarahAllen:\n title: 'Developer'\n bio: '''Sarah",
"end": 14994,
"score": 0.8179970979690552,
"start": 14984,
"tag": "USERNAME",
"value": "sarahAllen"
},
{
"context": "Allen:\n title: 'Developer'\n bio: '''Sarah Allen is a front-end web developer for the Zooniverse t",
"end": 15050,
"score": 0.9998366832733154,
"start": 15039,
"tag": "NAME",
"value": "Sarah Allen"
},
{
"context": " and live concerts in her free time.'''\n saschaIshikawa:\n title: 'Developer'\n bio: '",
"end": 15275,
"score": 0.6092082858085632,
"start": 15269,
"tag": "USERNAME",
"value": "aschaI"
},
{
"context": "ikawa:\n title: 'Developer'\n bio: '''Sascha joined the Zooniverse team in November 2013 as a ",
"end": 15333,
"score": 0.9955872893333435,
"start": 15327,
"tag": "NAME",
"value": "Sascha"
},
{
"context": "puter science and mechanical engineering.'''\n shaunANoordin:\n title: 'Developer'\n bio: ''",
"end": 15566,
"score": 0.7983722686767578,
"start": 15559,
"tag": "USERNAME",
"value": "shaunAN"
},
{
"context": "ordin:\n title: 'Developer'\n bio: '''Shaun was raised by Nintendo consoles and somehow trans",
"end": 15622,
"score": 0.9477906823158264,
"start": 15617,
"tag": "NAME",
"value": "Shaun"
},
{
"context": "ign and\n coding experimental apps.'''\n simoneDuca:\n title: 'Web Developer'\n bio: '''S",
"end": 15914,
"score": 0.7213234901428223,
"start": 15904,
"tag": "USERNAME",
"value": "simoneDuca"
},
{
"context": "a:\n title: 'Web Developer'\n bio: '''Simone is a front end web developer at the Zooniverse. H",
"end": 15969,
"score": 0.9674052596092224,
"start": 15963,
"tag": "NAME",
"value": "Simone"
},
{
"context": "y\n from Bristol and loves cooking.'''\n stuartLynn:\n title: 'Developer'\n bio: '''Stuar",
"end": 16114,
"score": 0.6999953985214233,
"start": 16104,
"tag": "USERNAME",
"value": "stuartLynn"
},
{
"context": "tLynn:\n title: 'Developer'\n bio: '''Stuart arrived at the Adler as a developer in July 2011,",
"end": 16165,
"score": 0.9916203022003174,
"start": 16159,
"tag": "NAME",
"value": "Stuart"
},
{
"context": " Data analysis maestro and web developer.'''\n steveRaden:\n title: 'Developer'\n bio: 'St",
"end": 16474,
"score": 0.4578375816345215,
"start": 16469,
"tag": "NAME",
"value": "steve"
},
{
"context": "analysis maestro and web developer.'''\n steveRaden:\n title: 'Developer'\n bio: 'Steve",
"end": 16477,
"score": 0.5654937624931335,
"start": 16474,
"tag": "USERNAME",
"value": "Rad"
},
{
"context": "lysis maestro and web developer.'''\n steveRaden:\n title: 'Developer'\n bio: 'Steve R",
"end": 16479,
"score": 0.6539555191993713,
"start": 16477,
"tag": "NAME",
"value": "en"
},
{
"context": "veRaden:\n title: 'Developer'\n bio: 'Steve Raden was a developer at the Adler in Chicago.'\n v",
"end": 16533,
"score": 0.9996177554130554,
"start": 16522,
"tag": "NAME",
"value": "Steve Raden"
},
{
"context": " from Syracuse University.'''\n victoriaVanHyning:\n title: 'Researcher'\n bio: '''Vict",
"end": 16922,
"score": 0.6408834457397461,
"start": 16917,
"tag": "NAME",
"value": "yning"
},
{
"context": "ning:\n title: 'Researcher'\n bio: '''Victoria is a British Academy postdoctoral fellow i",
"end": 16969,
"score": 0.5456375479698181,
"start": 16968,
"tag": "NAME",
"value": "V"
},
{
"context": ":\n title: 'Researcher'\n bio: '''Victoria is a British Academy postdoctoral fellow in Engli",
"end": 16976,
"score": 0.5884003043174744,
"start": 16972,
"tag": "NAME",
"value": "oria"
},
{
"context": "nventions all over the midwest.'''\nteamMembers =\n adamMcMaster:\n name: \"Adam McMaster\"\n twitter: \"astopy\"\n",
"end": 17811,
"score": 0.7545989155769348,
"start": 17799,
"tag": "USERNAME",
"value": "adamMcMaster"
},
{
"context": "west.'''\nteamMembers =\n adamMcMaster:\n name: \"Adam McMaster\"\n twitter: \"astopy\"\n title: counterpart \"te",
"end": 17837,
"score": 0.9997956156730652,
"start": 17824,
"tag": "NAME",
"value": "Adam McMaster"
},
{
"context": "McMaster:\n name: \"Adam McMaster\"\n twitter: \"astopy\"\n title: counterpart \"team.content.adamMcMaste",
"end": 17859,
"score": 0.9995230436325073,
"start": 17853,
"tag": "USERNAME",
"value": "astopy"
},
{
"context": ": \"/assets/team/adam.jpg\"\n location: \"oxford\"\n alexBowyer:\n name: \"Alex Bowyer\"\n twitter: \"alexb",
"end": 18036,
"score": 0.5675162076950073,
"start": 18031,
"tag": "USERNAME",
"value": "alexB"
},
{
"context": "\"\n location: \"oxford\"\n alexBowyer:\n name: \"Alex Bowyer\"\n twitter: \"alexbfree\"\n title: counterpart ",
"end": 18065,
"score": 0.9998906254768372,
"start": 18054,
"tag": "NAME",
"value": "Alex Bowyer"
},
{
"context": "alexBowyer:\n name: \"Alex Bowyer\"\n twitter: \"alexbfree\"\n title: counterpart \"team.content.alexBow",
"end": 18086,
"score": 0.9995094537734985,
"start": 18081,
"tag": "USERNAME",
"value": "alexb"
},
{
"context": " location: \"alumni\"\n # amitKapadia:\n # name: \"Amit Kapadia\"\n # title: counterpart \"team.content.amitKapad",
"end": 18305,
"score": 0.9999038577079773,
"start": 18293,
"tag": "NAME",
"value": "Amit Kapadia"
},
{
"context": "\"/assets/team/amit.jpg\"\n # location: \"alumni\"\n amyBoyer:\n name: \"Amy Boyer\"\n title: counterpart \"te",
"end": 18491,
"score": 0.6233227252960205,
"start": 18483,
"tag": "USERNAME",
"value": "amyBoyer"
},
{
"context": "\"\n # location: \"alumni\"\n amyBoyer:\n name: \"Amy Boyer\"\n title: counterpart \"team.content.amyBoyer.ti",
"end": 18513,
"score": 0.9998993277549744,
"start": 18504,
"tag": "NAME",
"value": "Amy Boyer"
},
{
"context": ": \"/assets/team/amy.png\"\n location: \"chicago\"\n alexWeiksnar:\n name: \"Alex Weiksnar\"\n title: counterpart",
"end": 18689,
"score": 0.9436095356941223,
"start": 18677,
"tag": "NAME",
"value": "alexWeiksnar"
},
{
"context": " location: \"chicago\"\n alexWeiksnar:\n name: \"Alex Weiksnar\"\n title: counterpart \"team.content.alexWeiksna",
"end": 18715,
"score": 0.999891459941864,
"start": 18702,
"tag": "NAME",
"value": "Alex Weiksnar"
},
{
"context": "\"\n location: \"alumni\"\n aliSwanson:\n name: \"Ali Swanson\"\n twitter: \"alicatzoo\"\n title: counterpart ",
"end": 18921,
"score": 0.9999015927314758,
"start": 18910,
"tag": "NAME",
"value": "Ali Swanson"
},
{
"context": "aliSwanson:\n name: \"Ali Swanson\"\n twitter: \"alicatzoo\"\n title: counterpart \"team.content.aliSwanson.",
"end": 18946,
"score": 0.9996616244316101,
"start": 18937,
"tag": "USERNAME",
"value": "alicatzoo"
},
{
"context": "\"/assets/team/ali.jpg\"\n location: \"alumni\"\n arfonSmith:\n name: \"Arfon Smith\"\n title: counterp",
"end": 19118,
"score": 0.5721648335456848,
"start": 19115,
"tag": "USERNAME",
"value": "fon"
},
{
"context": "\"\n location: \"alumni\"\n arfonSmith:\n name: \"Arfon Smith\"\n title: counterpart \"team.content.arfonSmith.",
"end": 19147,
"score": 0.9998947978019714,
"start": 19136,
"tag": "NAME",
"value": "Arfon Smith"
},
{
"context": "ssets/team/arfon.jpg\"\n location: \"alumni\"\n andreaSimenstad:\n name: \"Andrea Simenstad\"\n title:",
"end": 19322,
"score": 0.6784346103668213,
"start": 19319,
"tag": "USERNAME",
"value": "rea"
},
{
"context": "/arfon.jpg\"\n location: \"alumni\"\n andreaSimenstad:\n name: \"Andrea Simenstad\"\n title: counterp",
"end": 19331,
"score": 0.43550926446914673,
"start": 19329,
"tag": "USERNAME",
"value": "ad"
},
{
"context": " location: \"alumni\"\n andreaSimenstad:\n name: \"Andrea Simenstad\"\n title: counterpart \"team.content.andreaSimen",
"end": 19360,
"score": 0.9998904466629028,
"start": 19344,
"tag": "NAME",
"value": "Andrea Simenstad"
},
{
"context": "ocation: \"minnesota\"\n beverleyNewing:\n name: \"Beverley Newing\"\n twitter: \"WebDevBev\"\n title: counterpart ",
"end": 19585,
"score": 0.999880313873291,
"start": 19570,
"tag": "NAME",
"value": "Beverley Newing"
},
{
"context": "Newing:\n name: \"Beverley Newing\"\n twitter: \"WebDevBev\"\n title: counterpart \"team.content.beverleyNew",
"end": 19610,
"score": 0.9995800852775574,
"start": 19601,
"tag": "USERNAME",
"value": "WebDevBev"
},
{
"context": "\n location: \"alumni\"\n beckyRother:\n name: \"Becky Rother\"\n twitter: \"beckyrother\"\n title: counterpar",
"end": 19826,
"score": 0.9998877644538879,
"start": 19814,
"tag": "NAME",
"value": "Becky Rother"
},
{
"context": "ckyRother:\n name: \"Becky Rother\"\n twitter: \"beckyrother\"\n title: counterpart \"team.content.beckyRother",
"end": 19853,
"score": 0.9995561838150024,
"start": 19842,
"tag": "USERNAME",
"value": "beckyrother"
},
{
"context": "ts/team/beckyrother.jpg\"\n location: \"chicago\"\n brianCarstensen:\n name: \"Brian Carstensen\"\n twitt",
"end": 20036,
"score": 0.827424168586731,
"start": 20031,
"tag": "NAME",
"value": "brian"
},
{
"context": "m/beckyrother.jpg\"\n location: \"chicago\"\n brianCarstensen:\n name: \"Brian Carstensen\"\n twitter:",
"end": 20039,
"score": 0.4905971586704254,
"start": 20036,
"tag": "USERNAME",
"value": "Car"
},
{
"context": "eckyrother.jpg\"\n location: \"chicago\"\n brianCarstensen:\n name: \"Brian Carstensen\"\n twitter: \"__bri",
"end": 20046,
"score": 0.9485378861427307,
"start": 20039,
"tag": "NAME",
"value": "stensen"
},
{
"context": "location: \"chicago\"\n brianCarstensen:\n name: \"Brian Carstensen\"\n twitter: \"__brian_c__\"\n title: counterpar",
"end": 20075,
"score": 0.9998710751533508,
"start": 20059,
"tag": "NAME",
"value": "Brian Carstensen"
},
{
"context": "stensen:\n name: \"Brian Carstensen\"\n twitter: \"__brian_c__\"\n title: counterpart \"team.content.brianCarste",
"end": 20102,
"score": 0.9984543919563293,
"start": 20090,
"tag": "USERNAME",
"value": "\"__brian_c__"
},
{
"context": "sets/team/brian.jpg\"\n location: \"alumni\"\n brookeSimmons:\n name: \"Brooke Simmons\"\n twitter: \"",
"end": 20287,
"score": 0.37025532126426697,
"start": 20285,
"tag": "NAME",
"value": "ke"
},
{
"context": "ts/team/brian.jpg\"\n location: \"alumni\"\n brookeSimmons:\n name: \"Brooke Simmons\"\n twitter: \"vrooje",
"end": 20293,
"score": 0.5047537088394165,
"start": 20287,
"tag": "USERNAME",
"value": "Simmon"
},
{
"context": " location: \"alumni\"\n brookeSimmons:\n name: \"Brooke Simmons\"\n twitter: \"vrooje\"\n title: counterpart \"te",
"end": 20321,
"score": 0.9998736381530762,
"start": 20307,
"tag": "NAME",
"value": "Brooke Simmons"
},
{
"context": "Simmons:\n name: \"Brooke Simmons\"\n twitter: \"vrooje\"\n title: counterpart \"team.content.brookeSimmo",
"end": 20343,
"score": 0.9995608329772949,
"start": 20337,
"tag": "USERNAME",
"value": "vrooje"
},
{
"context": " location: \"california\"\n camAllen:\n name: \"Campbell Allen\"\n title: counterpart \"team.content.camAllen.ti",
"end": 20558,
"score": 0.9998724460601807,
"start": 20544,
"tag": "NAME",
"value": "Campbell Allen"
},
{
"context": " location: \"oxford\"\n chrisLintott:\n name: \"Chris Lintott\"\n twitter: \"chrislintott\"\n title: counterpa",
"end": 20759,
"score": 0.9998782277107239,
"start": 20746,
"tag": "NAME",
"value": "Chris Lintott"
},
{
"context": "sLintott:\n name: \"Chris Lintott\"\n twitter: \"chrislintott\"\n title: counterpart \"team.content.chrisLintot",
"end": 20787,
"score": 0.9996443390846252,
"start": 20775,
"tag": "USERNAME",
"value": "chrislintott"
},
{
"context": "s/team/chris-l.png\"\n location: \"oxford\"\n chrisSnyder:\n name: \"Chris Snyder\"\n twitter: \"bumishnes",
"end": 20973,
"score": 0.4783402681350708,
"start": 20967,
"tag": "USERNAME",
"value": "Snyder"
},
{
"context": "\n location: \"oxford\"\n chrisSnyder:\n name: \"Chris Snyder\"\n twitter: \"bumishness\"\n title: counterpart",
"end": 20998,
"score": 0.9998838305473328,
"start": 20986,
"tag": "NAME",
"value": "Chris Snyder"
},
{
"context": "risSnyder:\n name: \"Chris Snyder\"\n twitter: \"bumishness\"\n title: counterpart \"team.content.chrisSnyder",
"end": 21024,
"score": 0.9995282292366028,
"start": 21014,
"tag": "USERNAME",
"value": "bumishness"
},
{
"context": "\"/assets/team/chriss.png\"\n location: \"alumni\"\n christopherDoogue:\n name: \"Christopher Doogue\"\n title: ",
"end": 21207,
"score": 0.6061571836471558,
"start": 21196,
"tag": "NAME",
"value": "christopher"
},
{
"context": "/chriss.png\"\n location: \"alumni\"\n christopherDoogue:\n name: \"Christopher Doogue\"\n title: counte",
"end": 21213,
"score": 0.6927759647369385,
"start": 21208,
"tag": "NAME",
"value": "oogue"
},
{
"context": "ocation: \"alumni\"\n christopherDoogue:\n name: \"Christopher Doogue\"\n title: counterpart \"team.content.christopher",
"end": 21244,
"score": 0.9999063611030579,
"start": 21226,
"tag": "NAME",
"value": "Christopher Doogue"
},
{
"context": "/assets/team/chris-d.jpg\"\n location: \"alumni\"\n colemanKrawczyk:\n name: \"Coleman Krawczyk\"\n twitter",
"end": 21436,
"score": 0.47020480036735535,
"start": 21429,
"tag": "NAME",
"value": "coleman"
},
{
"context": "eam/chris-d.jpg\"\n location: \"alumni\"\n colemanKrawczyk:\n name: \"Coleman Krawczyk\"\n twitter: \"C",
"end": 21440,
"score": 0.5761038661003113,
"start": 21437,
"tag": "NAME",
"value": "raw"
},
{
"context": "chris-d.jpg\"\n location: \"alumni\"\n colemanKrawczyk:\n name: \"Coleman Krawczyk\"\n twitter: \"Colem",
"end": 21444,
"score": 0.6108563542366028,
"start": 21441,
"tag": "NAME",
"value": "zyk"
},
{
"context": " location: \"alumni\"\n colemanKrawczyk:\n name: \"Coleman Krawczyk\"\n twitter: \"ColemanKrawczyk\"\n title: counte",
"end": 21473,
"score": 0.9999057650566101,
"start": 21457,
"tag": "NAME",
"value": "Coleman Krawczyk"
},
{
"context": "wczyk:\n name: \"Coleman Krawczyk\"\n twitter: \"ColemanKrawczyk\"\n title: counterpart \"team.content.colemanKraw",
"end": 21504,
"score": 0.9996218681335449,
"start": 21489,
"tag": "USERNAME",
"value": "ColemanKrawczyk"
},
{
"context": "ets/team/coleman.jpg\"\n location: \"portsmouth\"\n darrenMcRoy:\n name: \"Darren McRoy\"\n title: counter",
"end": 21695,
"score": 0.5631961822509766,
"start": 21689,
"tag": "NAME",
"value": "darren"
},
{
"context": "leman.jpg\"\n location: \"portsmouth\"\n darrenMcRoy:\n name: \"Darren McRoy\"\n title: counterpart ",
"end": 21700,
"score": 0.5767093896865845,
"start": 21699,
"tag": "NAME",
"value": "y"
},
{
"context": " location: \"portsmouth\"\n darrenMcRoy:\n name: \"Darren McRoy\"\n title: counterpart \"team.content.darrenMcRoy",
"end": 21725,
"score": 0.9999024271965027,
"start": 21713,
"tag": "NAME",
"value": "Darren McRoy"
},
{
"context": " location: \"alumni\"\n darrylWright:\n name: \"Darryl Wright\"\n title: counterpart \"team.content.darrylWrigh",
"end": 21935,
"score": 0.9999083280563354,
"start": 21922,
"tag": "NAME",
"value": "Darryl Wright"
},
{
"context": "\n location: \"oxford\"\n # edPaget:\n # name: \"Ed Paget\"\n # twitter: \"edpaget\"\n # title: counterpar",
"end": 22153,
"score": 0.9998993873596191,
"start": 22145,
"tag": "NAME",
"value": "Ed Paget"
},
{
"context": "# edPaget:\n # name: \"Ed Paget\"\n # twitter: \"edpaget\"\n # title: counterpart \"team.content.edPaget.t",
"end": 22178,
"score": 0.9996707439422607,
"start": 22171,
"tag": "USERNAME",
"value": "edpaget"
},
{
"context": " # location: \"alumni\"\n grantMiller:\n name: \"Grant Robert MacKinnon Miller\"\n twitter: \"mrniaboc\"\n title: counterpart \"",
"end": 22399,
"score": 0.9998931884765625,
"start": 22370,
"tag": "NAME",
"value": "Grant Robert MacKinnon Miller"
},
{
"context": "me: \"Grant Robert MacKinnon Miller\"\n twitter: \"mrniaboc\"\n title: counterpart \"team.content.grantMiller",
"end": 22423,
"score": 0.9996582865715027,
"start": 22415,
"tag": "USERNAME",
"value": "mrniaboc"
},
{
"context": " location: \"oxford\"\n hannahSewell:\n name: \"Hannah Sewell\"\n twitter: \"hannahsewell2\"\n title: coun",
"end": 22634,
"score": 0.9999008178710938,
"start": 22621,
"tag": "NAME",
"value": "Hannah Sewell"
},
{
"context": "well:\n name: \"Hannah Sewell\"\n twitter: \"hannahsewell2\"\n title: counterpart \"team.content.hannahSew",
"end": 22665,
"score": 0.9996725916862488,
"start": 22652,
"tag": "USERNAME",
"value": "hannahsewell2"
},
{
"context": " location: \"oxford\"\n helenSpiers:\n name: \"Helen Spiers\"\n twitter: \"H_Spiers\"\n title: counterpart \"",
"end": 22885,
"score": 0.9998971819877625,
"start": 22873,
"tag": "NAME",
"value": "Helen Spiers"
},
{
"context": "lenSpiers:\n name: \"Helen Spiers\"\n twitter: \"H_Spiers\"\n title: counterpart \"team.content.helenSpiers",
"end": 22909,
"score": 0.9996857643127441,
"start": 22901,
"tag": "USERNAME",
"value": "H_Spiers"
},
{
"context": "ets/team/helenspiers.jpg\"\n location: \"oxford\"\n gregHines:\n name: \"Greg Hines\"\n title: counterpart \"t",
"end": 23095,
"score": 0.7621874809265137,
"start": 23086,
"tag": "NAME",
"value": "gregHines"
},
{
"context": "g\"\n location: \"oxford\"\n gregHines:\n name: \"Greg Hines\"\n title: counterpart \"team.content.gregHines.t",
"end": 23118,
"score": 0.9998793601989746,
"start": 23108,
"tag": "NAME",
"value": "Greg Hines"
},
{
"context": " location: \"alumni\"\n heathVanSingel:\n name: \"Heath van Singel\"\n title: counterpart \"team.content.heathVanSin",
"end": 23327,
"score": 0.9998823404312134,
"start": 23311,
"tag": "NAME",
"value": "Heath van Singel"
},
{
"context": "/assets/team/heath.png\"\n location: \"alumni\"\n hughDickinson:\n name: \"Hugh Dickinson\"\n title: c",
"end": 23508,
"score": 0.5500839352607727,
"start": 23505,
"tag": "NAME",
"value": "ugh"
},
{
"context": "/team/heath.png\"\n location: \"alumni\"\n hughDickinson:\n name: \"Hugh Dickinson\"\n title: counter",
"end": 23514,
"score": 0.5202664732933044,
"start": 23512,
"tag": "NAME",
"value": "in"
},
{
"context": " location: \"alumni\"\n hughDickinson:\n name: \"Hugh Dickinson\"\n title: counterpart \"team.content.hughDickins",
"end": 23544,
"score": 0.9998693466186523,
"start": 23530,
"tag": "NAME",
"value": "Hugh Dickinson"
},
{
"context": " location: \"minnesota\"\n jamesArtz:\n name: \"James Artz\"\n title: counterpart \"team.content.jamesArtz.t",
"end": 23753,
"score": 0.9998704791069031,
"start": 23743,
"tag": "NAME",
"value": "James Artz"
},
{
"context": "g\"\n location: \"chicago\"\n jenGupta:\n name: \"Jen Gupta\"\n twitter: \"jen_gupta\"\n title: counterpart ",
"end": 23951,
"score": 0.9998743534088135,
"start": 23942,
"tag": "NAME",
"value": "Jen Gupta"
},
{
"context": "\"\n jenGupta:\n name: \"Jen Gupta\"\n twitter: \"jen_gupta\"\n title: counterpart \"team.content.jenGupta.ti",
"end": 23976,
"score": 0.9996386766433716,
"start": 23967,
"tag": "USERNAME",
"value": "jen_gupta"
},
{
"context": " location: \"portsmouth\"\n jimODonnell:\n name: \"Jim O'Donnell\"\n twitter: \"pekingspring\"\n title: counterpa",
"end": 24186,
"score": 0.999893844127655,
"start": 24173,
"tag": "NAME",
"value": "Jim O'Donnell"
},
{
"context": "ODonnell:\n name: \"Jim O'Donnell\"\n twitter: \"pekingspring\"\n title: counterpart \"team.content.jimODonnell",
"end": 24214,
"score": 0.9996566772460938,
"start": 24202,
"tag": "USERNAME",
"value": "pekingspring"
},
{
"context": " \"/assets/team/jim.jpg\"\n location: \"oxford\"\n jordanMartin:\n name: \"Jordan Martin\"\n twitter: \"Jo",
"end": 24389,
"score": 0.43479669094085693,
"start": 24384,
"tag": "NAME",
"value": "ordan"
},
{
"context": "sets/team/jim.jpg\"\n location: \"oxford\"\n jordanMartin:\n name: \"Jordan Martin\"\n twitter: \"Jordan",
"end": 24393,
"score": 0.45050522685050964,
"start": 24389,
"tag": "USERNAME",
"value": "Mart"
},
{
"context": "/team/jim.jpg\"\n location: \"oxford\"\n jordanMartin:\n name: \"Jordan Martin\"\n twitter: \"Jordanwh",
"end": 24395,
"score": 0.46535274386405945,
"start": 24393,
"tag": "NAME",
"value": "in"
},
{
"context": " location: \"oxford\"\n jordanMartin:\n name: \"Jordan Martin\"\n twitter: \"Jordanwhitneym\"\n title: counter",
"end": 24421,
"score": 0.9998789429664612,
"start": 24408,
"tag": "NAME",
"value": "Jordan Martin"
},
{
"context": "anMartin:\n name: \"Jordan Martin\"\n twitter: \"Jordanwhitneym\"\n title: counterpart \"team.content.jordanMarti",
"end": 24451,
"score": 0.9996557235717773,
"start": 24437,
"tag": "USERNAME",
"value": "Jordanwhitneym"
},
{
"context": "\"/assets/team/jordan.jpg\"\n location: \"alumni\"\n julieFeldt:\n name: \"Julie Feldt\"\n title: counterpart \"",
"end": 24635,
"score": 0.8824132084846497,
"start": 24625,
"tag": "NAME",
"value": "julieFeldt"
},
{
"context": "\"\n location: \"alumni\"\n julieFeldt:\n name: \"Julie Feldt\"\n title: counterpart \"team.content.julieFeldt.",
"end": 24659,
"score": 0.9998806118965149,
"start": 24648,
"tag": "NAME",
"value": "Julie Feldt"
},
{
"context": "assets/team/julie.png\"\n location: \"chicago\"\n karenMasters:\n name: \"Karen Masters\"\n twitter: \"k",
"end": 24834,
"score": 0.465573787689209,
"start": 24830,
"tag": "NAME",
"value": "aren"
},
{
"context": "s/team/julie.png\"\n location: \"chicago\"\n karenMasters:\n name: \"Karen Masters\"\n twitter: \"karenlma",
"end": 24841,
"score": 0.5998139381408691,
"start": 24835,
"tag": "NAME",
"value": "asters"
},
{
"context": " location: \"chicago\"\n karenMasters:\n name: \"Karen Masters\"\n twitter: \"karenlmasters\"\n title: counterp",
"end": 24867,
"score": 0.9998854994773865,
"start": 24854,
"tag": "NAME",
"value": "Karen Masters"
},
{
"context": "nMasters:\n name: \"Karen Masters\"\n twitter: \"karenlmasters\"\n title: counterpart \"team.content.karenMaster",
"end": 24896,
"score": 0.9996520280838013,
"start": 24883,
"tag": "USERNAME",
"value": "karenlmasters"
},
{
"context": "ets/team/karen.jpg\"\n location: \"portsmouth\"\n kellyBorden:\n name: \"Kelly Borden\"\n twitter: \"Bord",
"end": 25079,
"score": 0.5106151700019836,
"start": 25074,
"tag": "USERNAME",
"value": "ellyB"
},
{
"context": "eam/karen.jpg\"\n location: \"portsmouth\"\n kellyBorden:\n name: \"Kelly Borden\"\n twitter: \"BordenKel",
"end": 25084,
"score": 0.507244348526001,
"start": 25079,
"tag": "NAME",
"value": "orden"
},
{
"context": " location: \"portsmouth\"\n kellyBorden:\n name: \"Kelly Borden\"\n twitter: \"BordenKelly\"\n title: counterpar",
"end": 25109,
"score": 0.9998932480812073,
"start": 25097,
"tag": "NAME",
"value": "Kelly Borden"
},
{
"context": "llyBorden:\n name: \"Kelly Borden\"\n twitter: \"BordenKelly\"\n title: counterpart \"team.content.kellyBorden",
"end": 25136,
"score": 0.9996817111968994,
"start": 25125,
"tag": "USERNAME",
"value": "BordenKelly"
},
{
"context": "\"/assets/team/kelly.jpg\"\n location: \"chicago\"\n kyleWillett:\n name: \"Kyle Willett\"\n twitter: \"kw",
"end": 25312,
"score": 0.4743348956108093,
"start": 25308,
"tag": "NAME",
"value": "kyle"
},
{
"context": "ets/team/kelly.jpg\"\n location: \"chicago\"\n kyleWillett:\n name: \"Kyle Willett\"\n twitter: \"kww",
"end": 25313,
"score": 0.6533995866775513,
"start": 25312,
"tag": "USERNAME",
"value": "W"
},
{
"context": "ts/team/kelly.jpg\"\n location: \"chicago\"\n kyleWillett:\n name: \"Kyle Willett\"\n twitter: \"kwwillett",
"end": 25319,
"score": 0.5187355875968933,
"start": 25313,
"tag": "NAME",
"value": "illett"
},
{
"context": " location: \"chicago\"\n kyleWillett:\n name: \"Kyle Willett\"\n twitter: \"kwwillett\"\n title: counterpart ",
"end": 25344,
"score": 0.9998836517333984,
"start": 25332,
"tag": "NAME",
"value": "Kyle Willett"
},
{
"context": "leWillett:\n name: \"Kyle Willett\"\n twitter: \"kwwillett\"\n title: counterpart \"team.content.kyleWillett",
"end": 25369,
"score": 0.9996349811553955,
"start": 25360,
"tag": "USERNAME",
"value": "kwwillett"
},
{
"context": " location: \"alumni\"\n lauraTrouille:\n name: \"Laura Trouille\"\n twitter: \"windycityastro\"\n title: counter",
"end": 25579,
"score": 0.9998881220817566,
"start": 25565,
"tag": "NAME",
"value": "Laura Trouille"
},
{
"context": "rouille:\n name: \"Laura Trouille\"\n twitter: \"windycityastro\"\n title: counterpart \"team.content.lauraTrouil",
"end": 25609,
"score": 0.9995619058609009,
"start": 25595,
"tag": "USERNAME",
"value": "windycityastro"
},
{
"context": "\n location: \"chicago\"\n lauraWhyte:\n name: \"Laura Whyte\"\n title: counterpart \"team.content.lauraWhyte.",
"end": 25819,
"score": 0.9998888373374939,
"start": 25808,
"tag": "NAME",
"value": "Laura Whyte"
},
{
"context": "\n location: \"alumni\"\n lucyFortson:\n name: \"Lucy Fortson\"\n twitter: \"lucyfortson\"\n title: counterpar",
"end": 26026,
"score": 0.9998705387115479,
"start": 26014,
"tag": "NAME",
"value": "Lucy Fortson"
},
{
"context": "cyFortson:\n name: \"Lucy Fortson\"\n twitter: \"lucyfortson\"\n title: counterpart \"team.content.lucyFortson",
"end": 26053,
"score": 0.9995719194412231,
"start": 26042,
"tag": "USERNAME",
"value": "lucyfortson"
},
{
"context": " location: \"minnesota\"\n mariamSaeedi:\n name: \"Mariam Saeedi\"\n twitter: \"tweetsmariam\"\n title: counterpa",
"end": 26264,
"score": 0.9998854994773865,
"start": 26251,
"tag": "NAME",
"value": "Mariam Saeedi"
},
{
"context": "amSaeedi:\n name: \"Mariam Saeedi\"\n twitter: \"tweetsmariam\"\n title: counterpart \"team.content.mariamSaeed",
"end": 26292,
"score": 0.9996285438537598,
"start": 26280,
"tag": "USERNAME",
"value": "tweetsmariam"
},
{
"context": "\n location: \"oxford\"\n markBouslog:\n name: \"Mark Bouslog\"\n title: counterpart \"team.content.markBouslog",
"end": 26504,
"score": 0.9998857378959656,
"start": 26492,
"tag": "NAME",
"value": "Mark Bouslog"
},
{
"context": "location: \"chicago\"\n martenVeldthuis:\n name: \"Marten Veldthuis\"\n twitter: \"mveldth\"\n title: counterpart \"t",
"end": 26719,
"score": 0.9998885989189148,
"start": 26703,
"tag": "NAME",
"value": "Marten Veldthuis"
},
{
"context": "thuis:\n name: \"Marten Veldthuis\"\n twitter: \"mveldth\"\n title: counterpart \"team.content.martenVeldt",
"end": 26742,
"score": 0.9996426701545715,
"start": 26735,
"tag": "USERNAME",
"value": "mveldth"
},
{
"context": "\"/assets/team/marten.jpg\"\n location: \"oxford\"\n megSchwamb:\n name: \"Meg Schwamb\"\n twitter: \"megsch",
"end": 26928,
"score": 0.848989725112915,
"start": 26922,
"tag": "USERNAME",
"value": "megSch"
},
{
"context": "s/team/marten.jpg\"\n location: \"oxford\"\n megSchwamb:\n name: \"Meg Schwamb\"\n twitter: \"megschwamb",
"end": 26932,
"score": 0.615827202796936,
"start": 26928,
"tag": "NAME",
"value": "wamb"
},
{
"context": "\"\n location: \"oxford\"\n megSchwamb:\n name: \"Meg Schwamb\"\n twitter: \"megschwamb\"\n title: counterpart",
"end": 26956,
"score": 0.9997209310531616,
"start": 26945,
"tag": "NAME",
"value": "Meg Schwamb"
},
{
"context": "megSchwamb:\n name: \"Meg Schwamb\"\n twitter: \"megschwamb\"\n title: counterpart \"team.content.megSchwamb.",
"end": 26982,
"score": 0.9996191263198853,
"start": 26972,
"tag": "USERNAME",
"value": "megschwamb"
},
{
"context": "g\"\n location: \"hilo\"\n melanieBeck:\n name: \"Melanie Beck\"\n twitter: \"highzgal\"\n title: counterpart \"",
"end": 27183,
"score": 0.9998993277549744,
"start": 27171,
"tag": "NAME",
"value": "Melanie Beck"
},
{
"context": "lanieBeck:\n name: \"Melanie Beck\"\n twitter: \"highzgal\"\n title: counterpart \"team.content.melanieBeck",
"end": 27207,
"score": 0.9996050000190735,
"start": 27199,
"tag": "USERNAME",
"value": "highzgal"
},
{
"context": "sets/team/melanie.jpg\"\n location: \"minnesota\"\n michaelParrish:\n name: \"Michael Parrish\"\n twitter: ",
"end": 27390,
"score": 0.48480919003486633,
"start": 27383,
"tag": "NAME",
"value": "michael"
},
{
"context": "/melanie.jpg\"\n location: \"minnesota\"\n michaelParrish:\n name: \"Michael Parrish\"\n twitter: \"michae",
"end": 27397,
"score": 0.8477016687393188,
"start": 27391,
"tag": "NAME",
"value": "arrish"
},
{
"context": "ocation: \"minnesota\"\n michaelParrish:\n name: \"Michael Parrish\"\n twitter: \"michael_parrish\"\n title: counte",
"end": 27425,
"score": 0.9999032616615295,
"start": 27410,
"tag": "NAME",
"value": "Michael Parrish"
},
{
"context": "arrish:\n name: \"Michael Parrish\"\n twitter: \"michael_parrish\"\n title: counterpart \"team.content.michaelParr",
"end": 27456,
"score": 0.9996642470359802,
"start": 27441,
"tag": "USERNAME",
"value": "michael_parrish"
},
{
"context": "\n location: \"alumni\"\n noahMalmed: \n name: \"Noah Malmed\"\n title: counterpart \"team.content.noahMalmed.",
"end": 27670,
"score": 0.9998913407325745,
"start": 27659,
"tag": "NAME",
"value": "Noah Malmed"
},
{
"context": "\n location: \"chicago\"\n perryRoper:\n name: \"Perry Roper\"\n title: counterpart \"team.content.perryRoper.",
"end": 27873,
"score": 0.9998964071273804,
"start": 27862,
"tag": "NAME",
"value": "Perry Roper"
},
{
"context": "m/perry.jpg\"\n location: \"alumni\"\n rebeccaSmethurst:\n name: \"Rebecca Smethurst\"\n twitter: \"beck",
"end": 28058,
"score": 0.5212517380714417,
"start": 28054,
"tag": "NAME",
"value": "urst"
},
{
"context": "location: \"alumni\"\n rebeccaSmethurst:\n name: \"Rebecca Smethurst\"\n twitter: \"becky1505\"\n title: counterpart ",
"end": 28088,
"score": 0.9999017715454102,
"start": 28071,
"tag": "NAME",
"value": "Rebecca Smethurst"
},
{
"context": "urst:\n name: \"Rebecca Smethurst\"\n twitter: \"becky1505\"\n title: counterpart \"team.content.rebeccaSmet",
"end": 28113,
"score": 0.9996382594108582,
"start": 28104,
"tag": "USERNAME",
"value": "becky1505"
},
{
"context": "\n location: \"oxford\"\n robinSchaaf:\n name: \"Robin Schaaf\"\n title: counterpart \"team.content.robinSchaaf",
"end": 28330,
"score": 0.9998866319656372,
"start": 28318,
"tag": "NAME",
"value": "Robin Schaaf"
},
{
"context": " \"/assets/team/robin.jpg\"\n location: \"alumni\"\n rogerHutchings:\n name: \"Roger Hutchings\"\n title: counterpa",
"end": 28515,
"score": 0.7908016443252563,
"start": 28501,
"tag": "NAME",
"value": "rogerHutchings"
},
{
"context": " location: \"alumni\"\n rogerHutchings:\n name: \"Roger Hutchings\"\n title: counterpart \"team.content.rogerHutchi",
"end": 28543,
"score": 0.9998913407325745,
"start": 28528,
"tag": "NAME",
"value": "Roger Hutchings"
},
{
"context": " \"/assets/team/roger.jpg\"\n location: \"oxford\"\n robertSimpson:\n name: \"Robert Simpson\"\n title: counterpar",
"end": 28733,
"score": 0.6197668313980103,
"start": 28720,
"tag": "NAME",
"value": "robertSimpson"
},
{
"context": " location: \"oxford\"\n robertSimpson:\n name: \"Robert Simpson\"\n title: counterpart \"team.content.robertSimps",
"end": 28760,
"score": 0.9998642206192017,
"start": 28746,
"tag": "NAME",
"value": "Robert Simpson"
},
{
"context": "e: \"/assets/team/rob.jpg\"\n location: \"alumni\"\n samanthaBlickhan:\n name: \"Samantha Blickhan\"\n twitte",
"end": 28941,
"score": 0.6922626495361328,
"start": 28933,
"tag": "NAME",
"value": "samantha"
},
{
"context": "s/team/rob.jpg\"\n location: \"alumni\"\n samanthaBlickhan:\n name: \"Samantha Blickhan\"\n twitter: \"snbl",
"end": 28949,
"score": 0.7299497723579407,
"start": 28942,
"tag": "NAME",
"value": "lickhan"
},
{
"context": "location: \"alumni\"\n samanthaBlickhan:\n name: \"Samantha Blickhan\"\n twitter: \"snblickhan\"\n title: counterpart",
"end": 28979,
"score": 0.9998881220817566,
"start": 28962,
"tag": "NAME",
"value": "Samantha Blickhan"
},
{
"context": "khan:\n name: \"Samantha Blickhan\"\n twitter: \"snblickhan\"\n title: counterpart \"team.content.samanthaBli",
"end": 29005,
"score": 0.9996559619903564,
"start": 28995,
"tag": "USERNAME",
"value": "snblickhan"
},
{
"context": "\"/assets/team/sam.jpg\"\n location: \"chicago\"\n sandorKruk:\n name: \"Sandor Kruk\"\n twitter: \"kruksandor",
"end": 29195,
"score": 0.7751058340072632,
"start": 29186,
"tag": "NAME",
"value": "andorKruk"
},
{
"context": "\n location: \"chicago\"\n sandorKruk:\n name: \"Sandor Kruk\"\n twitter: \"kruksandor\"\n title: counterpart",
"end": 29219,
"score": 0.9998876452445984,
"start": 29208,
"tag": "NAME",
"value": "Sandor Kruk"
},
{
"context": "sandorKruk:\n name: \"Sandor Kruk\"\n twitter: \"kruksandor\"\n title: counterpart \"team.content.sandorKruk.",
"end": 29245,
"score": 0.9996712803840637,
"start": 29235,
"tag": "USERNAME",
"value": "kruksandor"
},
{
"context": "\"\n location: \"oxford\"\n sarahAllen:\n name: \"Sarah Allen\"\n title: counterpart \"team.content.sarahAllen.",
"end": 29449,
"score": 0.9998856782913208,
"start": 29438,
"tag": "NAME",
"value": "Sarah Allen"
},
{
"context": " location: \"chicago\"\n saschaIshikawa:\n name: \"Sascha Ishikawa\"\n twitter: \"sascha_ishikawa\"\n title: counte",
"end": 29661,
"score": 0.9998944401741028,
"start": 29646,
"tag": "NAME",
"value": "Sascha Ishikawa"
},
{
"context": "hikawa:\n name: \"Sascha Ishikawa\"\n twitter: \"sascha_ishikawa\"\n title: counterpart \"team.content.saschaIshik",
"end": 29692,
"score": 0.9996612668037415,
"start": 29677,
"tag": "USERNAME",
"value": "sascha_ishikawa"
},
{
"context": " location: \"alumni\"\n shaunANoordin:\n name: \"Shaun A. Noordin\"\n title: counterpart \"team.content.shaunANoord",
"end": 29912,
"score": 0.9998567700386047,
"start": 29896,
"tag": "NAME",
"value": "Shaun A. Noordin"
},
{
"context": "am/shaunanoordin.jpg\"\n location: \"oxford\"\n simoneDuca:\n name: \"Simone Duca\"\n title: counterpa",
"end": 30101,
"score": 0.5291052460670471,
"start": 30098,
"tag": "NAME",
"value": "one"
},
{
"context": "\"\n location: \"oxford\"\n simoneDuca:\n name: \"Simone Duca\"\n title: counterpart \"team.content.simoneDuca.",
"end": 30129,
"score": 0.9998871088027954,
"start": 30118,
"tag": "NAME",
"value": "Simone Duca"
},
{
"context": "\"/assets/team/simone.jpg\"\n location: \"oxford\"\n stuartLynn:\n name: \"Stuart Lynn\"\n title: count",
"end": 30301,
"score": 0.5837340354919434,
"start": 30299,
"tag": "NAME",
"value": "st"
},
{
"context": "\"\n location: \"oxford\"\n stuartLynn:\n name: \"Stuart Lynn\"\n title: counterpart \"team.content.stuartLynn.",
"end": 30333,
"score": 0.9998849630355835,
"start": 30322,
"tag": "NAME",
"value": "Stuart Lynn"
},
{
"context": "\"/assets/team/stuart.png\"\n location: \"alumni\"\n steveRaden:\n name: \"Steve Raden\"\n title: counterpart \"",
"end": 30513,
"score": 0.9612634181976318,
"start": 30503,
"tag": "NAME",
"value": "steveRaden"
},
{
"context": "\"\n location: \"alumni\"\n steveRaden:\n name: \"Steve Raden\"\n title: counterpart \"team.content.steveRaden.",
"end": 30537,
"score": 0.9998798370361328,
"start": 30526,
"tag": "NAME",
"value": "Steve Raden"
},
{
"context": " \"/assets/team/steve.png\"\n location: \"alumni\"\n veronicaMaidel:\n name: \"Veronica Maidel\"\n title: counterpa",
"end": 30720,
"score": 0.725662887096405,
"start": 30706,
"tag": "NAME",
"value": "veronicaMaidel"
},
{
"context": " location: \"alumni\"\n veronicaMaidel:\n name: \"Veronica Maidel\"\n title: counterpart \"team.content.veronicaMai",
"end": 30748,
"score": 0.999876856803894,
"start": 30733,
"tag": "NAME",
"value": "Veronica Maidel"
},
{
"context": "eronica.jpg\"\n location: \"alumni\"\n victoriaVanHyning:\n name: \"Victoria Van Hyning\"\n twitter: \"Va",
"end": 30945,
"score": 0.7477078437805176,
"start": 30940,
"tag": "NAME",
"value": "yning"
},
{
"context": "ocation: \"alumni\"\n victoriaVanHyning:\n name: \"Victoria Van Hyning\"\n twitter: \"VanHyningV\"\n title: counterpart",
"end": 30977,
"score": 0.9998943209648132,
"start": 30958,
"tag": "NAME",
"value": "Victoria Van Hyning"
},
{
"context": "ng:\n name: \"Victoria Van Hyning\"\n twitter: \"VanHyningV\"\n title: counterpart \"team.content.victoriaVan",
"end": 31003,
"score": 0.9996964335441589,
"start": 30993,
"tag": "USERNAME",
"value": "VanHyningV"
},
{
"context": "\n location: \"oxford\"\n willGranger:\n name: \"Will Granger\"\n title: counterpart \"team.content.willGranger",
"end": 31225,
"score": 0.9998833537101746,
"start": 31213,
"tag": "NAME",
"value": "Will Granger"
},
{
"context": "ocation: \"chicago\"\n zachWolfenbarger:\n name: \"Zach Wolfenbarger\"\n title: counterpart \"team.content.zachWolfenb",
"end": 31442,
"score": 0.9998636841773987,
"start": 31425,
"tag": "NAME",
"value": "Zach Wolfenbarger"
}
] | app/pages/about/team-page.cjsx | tlalka/Panoptes-Front-End | 0 | counterpart = require 'counterpart'
React = require 'react'
createReactClass = require 'create-react-class'
Translate = require 'react-translate-component'
counterpart.registerTranslations 'en',
team:
nav:
showAll: 'Show All'
oxford: 'Oxford'
chicago: 'The Adler Planetarium'
minnesota: 'Minnesota'
portsmouth: 'Portsmouth'
california: 'California'
hilo: 'Hilo'
alumni: 'Alumni'
content:
header:
showAll: 'Zooniverse Team'
adamMcMaster:
title: 'Infrastructure Engineer'
bio: '''Adam is responsible for managing the Zooniverse's web hosting infrastructure.
He has a computer science degree and has worked in web hosting and development for many years.
He's also working on a degree in astronomy with the OU.'''
alexBowyer:
title: 'Web Science Architect'
bio: '''Alex worked remotely for Zooniverse from his home in Northumberland.
He designed and ran Zooniverse experiments and developed infrastructure and front-end code. Alex
is a Dad of three, an improv player, a board gamer, and is running five half-marathons in 2016.'''
alexWeiksnar:
title: 'Developer'
bio: '''Alex previously attended University of Miami, where he studied Psychology,
Biology, and English. Alex enjoys reading, coding, and sailing in his free time.'''
aliSwanson:
title: 'Researcher'
bio: '''Ali spent most of her PhD chasing lions around the Serengeti. She finished
her PhD in Ecology, Evolution, and Behavior at the University of Minnesota in 2014,
and joined the Zooniverse as a Postdoc in Ecology and Citizen Science.'''
# amitKapadia:
# title: 'Developer'
# bio: '''Amit was a developer at the Adler Planetarium.'''
amyBoyer:
title: 'Developer'
bio: '''Amy has been a Zooniverse developer at the Adler since November 2015. She holds a BS and
MS in computer science and has over a decade of industry experience. An aspiring astronomer as
a child, she couldn't be happier to have landed here.'''
andreaSimenstad:
title: 'Developer'
bio: '''Andrea joined Zooniverse as a developer at the University of Minnesota in 2015. When she is not captivated by code, she can be found enjoying snow on skis and exploring lakes by kayak. She graduated from Carleton College with a degree in Cognitive Science.'''
arfonSmith:
title: 'Technical Lead'
bio: '''Arfon was co-founder and Technical Lead of the Zooniverse for the first five years of the project.
Arfon served as Director of Citizen Science at the Adler Planetarium and co-lead of the Zooniverse until fall 2013.'''
beckyRother:
title: 'Visual Designer'
bio: '''Becky joined the Zooniverse team as designer in 2017. With a background in mobile apps and product design and a degree in journalism, she's excited to use her powers for good with the Zooniverse team.'''
beverleyNewing:
title: 'Web Developer Intern'
bio: '''Beverley is an English and German literature graduate and worked as a Web Developer Intern at Zooniverse. In her spare time she's an avid fan of geese and enjoys motorbiking.'''
brianCarstensen:
title: 'UX Developer'
bio: '''Brian Carstensen moved from Chicago to Oxford and back again. Brian has a degree
in graphic design from Columbia College in Chicago, and worked in that field for a
number of years before finding a niche in web development.'''
brookeSimmons:
title: 'Researcher'
bio: 'Brooke is an astrophysicist studying black holes, galaxies, and how citizen
science can be applied to other non-traditional problems.'
camAllen:
title: 'Developer'
bio: '''Responsible for building the Zooniverse's API infrastructure.
Cam considers himself a music and fine wine connoisseur - others do not.
In his spare time he enjoys playing an obscure form of rugby.'''
chrisLintott:
title: 'Zooniverse PI'
bio: '''Astronomer and co-founder of both Galaxy Zoo and the Zooniverse that grew from it,
Chris is interested in how galaxies form and evolve, how citizen science can change the
world, and whether the Chicago Fire can get their act together.'''
chrisSnyder:
title: 'Project Manager'
bio: '''Chris Snyder began working on the Zooniverse team in fall 2012 as a web developer. In July 2013,
he became the technical project manager. He received a degree in computer science from the University of Dayton.'''
christopherDoogue:
title: 'Project Assistant'
bio: '''Chris supported the Zooniverse Oxford team from 2014-16. He had been with the Department
of Astrophysics for over 2 years administratively supporting various projects. A former trained actor,
he has the ability to look like he's smiling in the face of adversity!'''
colemanKrawczyk:
title: 'Data Scientist'
bio: '''Coleman is helping to create new data analysis and visualization tools for existing Zooniverse
projects as well as identifying new projects within the University of Portsmouth. He received
his PhD in astrophysics from Drexel University.'''
darrenMcRoy:
title: 'Community Manager'
bio: '''Darren (DZM) served as a liaison to the Zooniverse community and assisted with strategic
content for projects. A Northwestern University graduate in journalism, he is also a golf addict,
amateur author, and hopeless animal lover.'''
darrylWright:
title: 'Researcher'
bio: 'Darryl is doing machine learning research with the Zooniverse, based in Oxford.'
# edPaget:
# title: 'Developer'
# bio: '''Ed Paget joined Adler's Zooniverse Team as a software developer in August 2012.
# He previously worked as a freelance programmer and photographer. Ed graduated from
# Northwestern University with a major in Radio/TV/Film.'''
grantMiller:
title: 'Communications Lead'
bio: '''A former exoplanetary scientist, Grant is now responsible for communicating with our volunteers and researchers. He is also behind the Zooniverse's presence on
social media and publishes the Daily Zooniverse blog.'''
hannahSewell:
title: 'Web Development placement student'
bio: '''Hannah is a PhD student in plant genetics from The University of Sheffield.
She is visiting Zooniverse on a placement to learn web development for a few months and is definitely not an intern.'''
helenSpiers:
title: 'Researcher'
bio: '''After finishing a PhD studying the molecular basis of human brain development, Helen joined the Zooniverse as a Postdoc in citizen science and medical research.'''
gregHines:
title: 'Data Scientist'
bio: '''Greg used machine learning and statistics to help projects analyse their volunteer
classifications. He has a PhD in Computer Science from University of Waterloo, Canada.
Greg loves to eat pancakes with real maple syrup and run ultramarathons.'''
heathVanSingel:
title: 'Designer'
bio: '''Heath was the UX/UI Designer at the Zooniverse where he worked to craft thoughtful and
engaging user experiences. Apart from design, Heath also enjoys illustration, a good sci-fi or fantasy
novel, and exploring his new home in the Pacific Northwest.'''
hughDickinson:
title: 'Researcher'
bio: '''Hugh is a postdoc studying the Zooniverse.'''
jamesArtz:
title: 'Developer'
bio: '''James joined the Zooniverse team in 2017. Before discovering his passion for code,
he received a Ph.D in Mediterranean Archaeology from SUNY Buffalo, focusing on ancient Greece.
In his free time he enjoys wood working and the ancient art of fermentation.'''
jimODonnell:
title: 'UX Developer'
bio: '''Professional cynic but his heart's not in it. Web developer for the Zooniverse,
Web Standards organiser, Amnesty UK activist.'''
jenGupta:
title: 'Educator'
bio: '''Jen works on Galaxy Zoo education in her role as the SEPnet/Ogden Outreach Officer
for the Institute of Cosmology and Gravitation, and has a PhD in astrophysics. Active
galactic nuclei were her first love.'''
jordanMartin:
title: 'Visual Designer'
bio: '''Jordan joined at the Adler Planetarium as Zooniverse's Visual Designer
starting in 2015. She spent her time making our user interfaces beautiful,
engaging, and a rewarding experience. At home she spends time with her
two cats and many houseplants.'''
julieFeldt:
title: 'Educator'
bio: '''Julie has a background in space physics and museum studies. She works on educational
experiences, and Skype in the Classroom lessons for the Zooniverse. She loves to run, mostly
to compensate for her love of cupcakes and chocolate.'''
karenMasters:
title: 'Researcher'
bio: '''Karen is an astronomer and the Project Scientist of Galaxy Zoo, which she's been
involved in as a researcher since 2008. She's particularly interested in the evolution of
spiral galaxies.'''
kellyBorden:
title: 'Educator'
bio: '''With a background in museum education, Kelly joined the Zooniverse in 2011 to bring
an educator's perspective and spread the word amongst teachers and students. She's fond of
several C's: chocolate, cats, coffee, and more chocolate.'''
kyleWillett:
title: 'Researcher'
bio: '''Kyle is an astronomer who studies galaxies, masers, and black holes (although he's
been getting more into data science). He worked on both Galaxy Zoo and Radio Galaxy Zoo,
and developed advanced tools for the volunteers.'''
lauraTrouille:
title: 'Zooniverse co-I'
bio: '''In July 2015, Laura became Director of Citizen Science at the Adler Planetarium and
co-I of the Zooniverse. While earning her Ph.D. in 2010 studying galaxy evolution,
she embodied cosmic collisions as a roller derby queen aptly named ‘The Big Bang’.'''
lauraWhyte:
title: 'Adler Planetarium Zooniverse Director'
bio: '''Laura was the Director of Citizen Science at Adler Planetarium and co-lead of the
Zooniverse from fall 2013 to summer 2015.'''
lucyFortson:
title: 'University of Minnesota Zooniverse Director'
bio: '''Associate Professor of Physics and Astronomy at the University of Minnesota. One of the Zooniverse
co-founders, she helps with project wrangling (aka management) and strategic planning while trying
to squeeze a bit of galaxy evolution science in.'''
mariamSaeedi:
title: 'Web Developer Intern'
bio: '''Mariam is the 2017 Web Development Intern at Zooniverse.
She is proficient with HTML and CSS and is currently learning JavaScript and Rails.'''
markBouslog:
title: 'Developer'
bio: '''Mark is a front-end web developer for the Zooniverse team at the Adler Planetarium. Joining in
November 2015 from a career in accounting, he’s thrilled to focus his number crunching to 1’s and 0’s
and is constantly inspired and humbled by the power of programming, citizen science and coffee.'''
martenVeldthuis:
title: 'Developer'
bio: '''Marten joined the development team in 2015. He has a degree in
computer science and enjoys crafting maintainable software. Marten learned about orbital
mechanics from Kerbal Space Program, and feels like he's therefore basically an astrophysicist.'''
megSchwamb:
title: 'Researcher'
bio: '''Meg is a planetary scientist and astronomer involved in the Planet Four projects,
and Comet Hunters for which she is project scientist. She studies small bodies in the
Solar System, exoplanets, and Mars. Meg has a fondness for baking, soccer, and champagne.'''
melanieBeck:
title: 'Researcher'
bio: '''A PhD student at the University of Minnesota, Melanie works on combining machine learning
with volunteer votes for classification tasks on the Galaxy Zoo project with the goal of classifying
*billions* of galaxies that future telescopes will see.'''
michaelParrish:
title: 'Rails/Backend Developer'
bio: '''Software developer at the Zooniverse. He pwns databases daily. Dog, fishing, snakes, and bourbon.'''
noahMalmed:
title: 'Mobile App Developer'
bio: '''Noah mainly has a background in mobile app development as well as some firmware and backend experience.
Outside of work, Noah enjoys cooking, baking and climbing.'''
perryRoper:
title: 'Developer'
bio: 'Perry was a developer with the Zooniverse, based in Oxford.'
rebeccaSmethurst:
title: 'Researcher'
bio: '''Becky is an astrophysicist working towards her doctorate in Oxford. She is
interested in how galaxies change over time and how we can track this evolution.
Happy-go-lucky about outreach, the Zooniverse and everything.'''
robinSchaaf:
title: 'Mobile App Developer'
bio: '''Robin has a background in web development for educational institutions. In her free time she enjoys board games and playing bass guitar.'''
robertSimpson:
title: 'Developer'
bio: 'Robert was one of the founding developers of the Zooniverse, based in Oxford.
If you can keep your head when all around you are losing theirs, you are probably
Rob Simpson.'
rogerHutchings:
title: 'Developer'
bio: '''Roger builds front end interfaces for the Zooniverse, and enjoys coding, music and rebuilding
motorbikes in his spare time.'''
samanthaBlickhan:
title: 'IMLS Postdoctoral Fellow'
bio: '''Samantha Blickhan is the IMLS Postdoctoral Fellow in the Department of Citizen Science at the Adler Planetarium, working on transcription projects for the Zooniverse. She received her Ph.D. in Musicology from Royal Holloway, University of London, with a thesis on the palaeography of British song notation in the 12th and 13th centuries. Her research interests include music and perception, and their relationships with writing systems, technology and pedagogy.'''
sandorKruk:
title: 'Researcher'
bio: '''Sandor is a graduate student working on his PhD in Astrophysics at Oxford.
He is looking at how galaxies evolve using data from Galaxy Zoo and enjoys stargazing,
using telescopes, and dancing in his free time.'''
sarahAllen:
title: 'Developer'
bio: '''Sarah Allen is a front-end web developer for the Zooniverse team at the Adler
Planetarium starting in September 2014. She also has a degree in music and enjoys cooking
and live concerts in her free time.'''
saschaIshikawa:
title: 'Developer'
bio: '''Sascha joined the Zooniverse team in November 2013 as a front-end developer.
A former researcher and software developer at NASA Ames, he received degrees in both
computer science and mechanical engineering.'''
shaunANoordin:
title: 'Developer'
bio: '''Shaun was raised by Nintendo consoles and somehow transformed his love
for video games into a love for creating interactive experiences. When not at
his PC playing games or reading comics, he's at his PC studying web design and
coding experimental apps.'''
simoneDuca:
title: 'Web Developer'
bio: '''Simone is a front end web developer at the Zooniverse. He has a Phd in logic and philosophy
from Bristol and loves cooking.'''
stuartLynn:
title: 'Developer'
bio: '''Stuart arrived at the Adler as a developer in July 2011, having been one of the founding
developers at Oxford. He studied mathematical physics at Edinburgh University and received his doctorate
in astrophysics from Royal Observatory Edinburgh. Data analysis maestro and web developer.'''
steveRaden:
title: 'Developer'
bio: 'Steve Raden was a developer at the Adler in Chicago.'
veronicaMaidel:
title: 'Data Scientist'
bio: '''Veronica is a Data Scientist who worked on discovering patterns in Zooniverse data, by manipulating
it and using it to create machine learning models. She received a PhD in Information Science and Technology
from Syracuse University.'''
victoriaVanHyning:
title: 'Researcher'
bio: '''Victoria is a British Academy postdoctoral fellow in English at Oxford, and is the humanities PI
at Zooniverse. She works on Science Gossip, Annotate, and Shakespeare's World and more. Coffee is her lifeblood.'''
willGranger:
title: 'Developer'
bio: '''Will joined the Adler Planetarium in 2016 as a front-end developer for the Zooniverse.
In the past, he has taught English overseas, toured in bands, and helped open a music venue in Alabama.'''
zachWolfenbarger:
title: 'Developer'
bio: '''Zach is a software developer. He was a molecular biologist, but then the lab needed some code
to be written and the die was cast. He’s also in a couple of bands and can be found playing shows at bars
and comic conventions all over the midwest.'''
teamMembers =
adamMcMaster:
name: "Adam McMaster"
twitter: "astopy"
title: counterpart "team.content.adamMcMaster.title"
bio: counterpart "team.content.adamMcMaster.bio"
image: "/assets/team/adam.jpg"
location: "oxford"
alexBowyer:
name: "Alex Bowyer"
twitter: "alexbfree"
title: counterpart "team.content.alexBowyer.title"
bio: counterpart "team.content.alexBowyer.bio"
image: "/assets/team/alex_bowyer.jpg"
location: "alumni"
# amitKapadia:
# name: "Amit Kapadia"
# title: counterpart "team.content.amitKapadia.title"
# bio: counterpart "team.content.amitKapadia.bio"
# image: "/assets/team/amit.jpg"
# location: "alumni"
amyBoyer:
name: "Amy Boyer"
title: counterpart "team.content.amyBoyer.title"
bio: counterpart "team.content.amyBoyer.bio"
image: "/assets/team/amy.png"
location: "chicago"
alexWeiksnar:
name: "Alex Weiksnar"
title: counterpart "team.content.alexWeiksnar.title"
bio: counterpart "team.content.alexWeiksnar.bio"
image: "/assets/team/alex.jpg"
location: "alumni"
aliSwanson:
name: "Ali Swanson"
twitter: "alicatzoo"
title: counterpart "team.content.aliSwanson.title"
bio: counterpart "team.content.aliSwanson.bio"
image: "/assets/team/ali.jpg"
location: "alumni"
arfonSmith:
name: "Arfon Smith"
title: counterpart "team.content.arfonSmith.title"
bio: counterpart "team.content.arfonSmith.bio"
image: "/assets/team/arfon.jpg"
location: "alumni"
andreaSimenstad:
name: "Andrea Simenstad"
title: counterpart "team.content.andreaSimenstad.title"
bio: counterpart "team.content.andreaSimenstad.bio"
image: "/assets/team/andrea.jpg"
location: "minnesota"
beverleyNewing:
name: "Beverley Newing"
twitter: "WebDevBev"
title: counterpart "team.content.beverleyNewing.title"
bio: counterpart "team.content.beverleyNewing.bio"
image: "/assets/team/beverley.jpg"
location: "alumni"
beckyRother:
name: "Becky Rother"
twitter: "beckyrother"
title: counterpart "team.content.beckyRother.title"
bio: counterpart "team.content.beckyRother.bio"
image: "/assets/team/beckyrother.jpg"
location: "chicago"
brianCarstensen:
name: "Brian Carstensen"
twitter: "__brian_c__"
title: counterpart "team.content.brianCarstensen.title"
bio: counterpart "team.content.brianCarstensen.bio"
image: "/assets/team/brian.jpg"
location: "alumni"
brookeSimmons:
name: "Brooke Simmons"
twitter: "vrooje"
title: counterpart "team.content.brookeSimmons.title"
bio: counterpart "team.content.brookeSimmons.bio"
image: "/assets/team/brooke.jpg"
location: "california"
camAllen:
name: "Campbell Allen"
title: counterpart "team.content.camAllen.title"
bio: counterpart "team.content.camAllen.bio"
image: "/assets/team/cam.jpg"
location: "oxford"
chrisLintott:
name: "Chris Lintott"
twitter: "chrislintott"
title: counterpart "team.content.chrisLintott.title"
bio: counterpart "team.content.chrisLintott.bio"
image: "/assets/team/chris-l.png"
location: "oxford"
chrisSnyder:
name: "Chris Snyder"
twitter: "bumishness"
title: counterpart "team.content.chrisSnyder.title"
bio: counterpart "team.content.chrisSnyder.bio"
image: "/assets/team/chriss.png"
location: "alumni"
christopherDoogue:
name: "Christopher Doogue"
title: counterpart "team.content.christopherDoogue.title"
bio: counterpart "team.content.christopherDoogue.bio"
image: "/assets/team/chris-d.jpg"
location: "alumni"
colemanKrawczyk:
name: "Coleman Krawczyk"
twitter: "ColemanKrawczyk"
title: counterpart "team.content.colemanKrawczyk.title"
bio: counterpart "team.content.colemanKrawczyk.bio"
image: "/assets/team/coleman.jpg"
location: "portsmouth"
darrenMcRoy:
name: "Darren McRoy"
title: counterpart "team.content.darrenMcRoy.title"
bio: counterpart "team.content.darrenMcRoy.bio"
image: "/assets/team/darren.jpg"
location: "alumni"
darrylWright:
name: "Darryl Wright"
title: counterpart "team.content.darrylWright.title"
bio: counterpart "team.content.darrylWright.bio"
image: "/assets/team/team-member-avatar.jpg"
location: "oxford"
# edPaget:
# name: "Ed Paget"
# twitter: "edpaget"
# title: counterpart "team.content.edPaget.title"
# bio: counterpart "team.content.edPaget.bio"
# image: "/assets/team/ed.png"
# location: "alumni"
grantMiller:
name: "Grant Robert MacKinnon Miller"
twitter: "mrniaboc"
title: counterpart "team.content.grantMiller.title"
bio: counterpart "team.content.grantMiller.bio"
image: "/assets/team/grant.jpg"
location: "oxford"
hannahSewell:
name: "Hannah Sewell"
twitter: "hannahsewell2"
title: counterpart "team.content.hannahSewell.title"
bio: counterpart "team.content.hannahSewell.bio"
image: "/assets/team/hannah_s.jpg"
location: "oxford"
helenSpiers:
name: "Helen Spiers"
twitter: "H_Spiers"
title: counterpart "team.content.helenSpiers.title"
bio: counterpart "team.content.helenSpiers.bio"
image: "/assets/team/helenspiers.jpg"
location: "oxford"
gregHines:
name: "Greg Hines"
title: counterpart "team.content.gregHines.title"
bio: counterpart "team.content.gregHines.bio"
image: "/assets/team/greg.jpg"
location: "alumni"
heathVanSingel:
name: "Heath van Singel"
title: counterpart "team.content.heathVanSingel.title"
bio: counterpart "team.content.heathVanSingel.bio"
image: "/assets/team/heath.png"
location: "alumni"
hughDickinson:
name: "Hugh Dickinson"
title: counterpart "team.content.hughDickinson.title"
bio: counterpart "team.content.hughDickinson.bio"
image: "/assets/team/hugh.jpg"
location: "minnesota"
jamesArtz:
name: "James Artz"
title: counterpart "team.content.jamesArtz.title"
bio: counterpart "team.content.jamesArtz.bio"
image: "/assets/team/james.jpg"
location: "chicago"
jenGupta:
name: "Jen Gupta"
twitter: "jen_gupta"
title: counterpart "team.content.jenGupta.title"
bio: counterpart "team.content.jenGupta.bio"
image: "/assets/team/jen_gupta.jpg"
location: "portsmouth"
jimODonnell:
name: "Jim O'Donnell"
twitter: "pekingspring"
title: counterpart "team.content.jimODonnell.title"
bio: counterpart "team.content.jimODonnell.bio"
image: "/assets/team/jim.jpg"
location: "oxford"
jordanMartin:
name: "Jordan Martin"
twitter: "Jordanwhitneym"
title: counterpart "team.content.jordanMartin.title"
bio: counterpart "team.content.jordanMartin.bio"
image: "/assets/team/jordan.jpg"
location: "alumni"
julieFeldt:
name: "Julie Feldt"
title: counterpart "team.content.julieFeldt.title"
bio: counterpart "team.content.julieFeldt.bio"
image: "/assets/team/julie.png"
location: "chicago"
karenMasters:
name: "Karen Masters"
twitter: "karenlmasters"
title: counterpart "team.content.karenMasters.title"
bio: counterpart "team.content.karenMasters.bio"
image: "/assets/team/karen.jpg"
location: "portsmouth"
kellyBorden:
name: "Kelly Borden"
twitter: "BordenKelly"
title: counterpart "team.content.kellyBorden.title"
bio: counterpart "team.content.kellyBorden.bio"
image: "/assets/team/kelly.jpg"
location: "chicago"
kyleWillett:
name: "Kyle Willett"
twitter: "kwwillett"
title: counterpart "team.content.kyleWillett.title"
bio: counterpart "team.content.kyleWillett.bio"
image: "/assets/team/kyle.jpg"
location: "alumni"
lauraTrouille:
name: "Laura Trouille"
twitter: "windycityastro"
title: counterpart "team.content.lauraTrouille.title"
bio: counterpart "team.content.lauraTrouille.bio"
image: "/assets/team/laura.jpg"
location: "chicago"
lauraWhyte:
name: "Laura Whyte"
title: counterpart "team.content.lauraWhyte.title"
bio: counterpart "team.content.lauraWhyte.bio"
image: "/assets/team/laura_w.jpg"
location: "alumni"
lucyFortson:
name: "Lucy Fortson"
twitter: "lucyfortson"
title: counterpart "team.content.lucyFortson.title"
bio: counterpart "team.content.lucyFortson.bio"
image: "/assets/team/lucy.jpg"
location: "minnesota"
mariamSaeedi:
name: "Mariam Saeedi"
twitter: "tweetsmariam"
title: counterpart "team.content.mariamSaeedi.title"
bio: counterpart "team.content.mariamSaeedi.bio"
image: "/assets/team/mariam_s.jpg"
location: "oxford"
markBouslog:
name: "Mark Bouslog"
title: counterpart "team.content.markBouslog.title"
bio: counterpart "team.content.markBouslog.bio"
image: "/assets/team/mark.jpg"
location: "chicago"
martenVeldthuis:
name: "Marten Veldthuis"
twitter: "mveldth"
title: counterpart "team.content.martenVeldthuis.title"
bio: counterpart "team.content.martenVeldthuis.bio"
image: "/assets/team/marten.jpg"
location: "oxford"
megSchwamb:
name: "Meg Schwamb"
twitter: "megschwamb"
title: counterpart "team.content.megSchwamb.title"
bio: counterpart "team.content.megSchwamb.bio"
image: "/assets/team/meg.jpg"
location: "hilo"
melanieBeck:
name: "Melanie Beck"
twitter: "highzgal"
title: counterpart "team.content.melanieBeck.title"
bio: counterpart "team.content.melanieBeck.bio"
image: "/assets/team/melanie.jpg"
location: "minnesota"
michaelParrish:
name: "Michael Parrish"
twitter: "michael_parrish"
title: counterpart "team.content.michaelParrish.title"
bio: counterpart "team.content.michaelParrish.bio"
image: "/assets/team/michael.png"
location: "alumni"
noahMalmed:
name: "Noah Malmed"
title: counterpart "team.content.noahMalmed.title"
bio: counterpart "team.content.noahMalmed.bio"
image: "/assets/team/noah.jpg"
location: "chicago"
perryRoper:
name: "Perry Roper"
title: counterpart "team.content.perryRoper.title"
bio: counterpart "team.content.perryRoper.bio"
image: "/assets/team/perry.jpg"
location: "alumni"
rebeccaSmethurst:
name: "Rebecca Smethurst"
twitter: "becky1505"
title: counterpart "team.content.rebeccaSmethurst.title"
bio: counterpart "team.content.rebeccaSmethurst.bio"
image: "/assets/team/becky.jpg"
location: "oxford"
robinSchaaf:
name: "Robin Schaaf"
title: counterpart "team.content.robinSchaaf.title"
bio: counterpart "team.content.robinSchaaf.bio"
image: "/assets/team/robin.jpg"
location: "alumni"
rogerHutchings:
name: "Roger Hutchings"
title: counterpart "team.content.rogerHutchings.title"
bio: counterpart "team.content.rogerHutchings.bio"
image: "/assets/team/roger.jpg"
location: "oxford"
robertSimpson:
name: "Robert Simpson"
title: counterpart "team.content.robertSimpson.title"
bio: counterpart "team.content.robertSimpson.bio"
image: "/assets/team/rob.jpg"
location: "alumni"
samanthaBlickhan:
name: "Samantha Blickhan"
twitter: "snblickhan"
title: counterpart "team.content.samanthaBlickhan.title"
bio: counterpart "team.content.samanthaBlickhan.bio"
image: "/assets/team/sam.jpg"
location: "chicago"
sandorKruk:
name: "Sandor Kruk"
twitter: "kruksandor"
title: counterpart "team.content.sandorKruk.title"
bio: counterpart "team.content.sandorKruk.bio"
image: "/assets/team/sandor.jpg"
location: "oxford"
sarahAllen:
name: "Sarah Allen"
title: counterpart "team.content.sarahAllen.title"
bio: counterpart "team.content.sarahAllen.bio"
image: "/assets/team/sarah.jpg"
location: "chicago"
saschaIshikawa:
name: "Sascha Ishikawa"
twitter: "sascha_ishikawa"
title: counterpart "team.content.saschaIshikawa.title"
bio: counterpart "team.content.saschaIshikawa.bio"
image: "/assets/team/sascha.png"
location: "alumni"
shaunANoordin:
name: "Shaun A. Noordin"
title: counterpart "team.content.shaunANoordin.title"
bio: counterpart "team.content.shaunANoordin.bio"
image: "/assets/team/shaunanoordin.jpg"
location: "oxford"
simoneDuca:
name: "Simone Duca"
title: counterpart "team.content.simoneDuca.title"
bio: counterpart "team.content.simoneDuca.bio"
image: "/assets/team/simone.jpg"
location: "oxford"
stuartLynn:
name: "Stuart Lynn"
title: counterpart "team.content.stuartLynn.title"
bio: counterpart "team.content.stuartLynn.bio"
image: "/assets/team/stuart.png"
location: "alumni"
steveRaden:
name: "Steve Raden"
title: counterpart "team.content.steveRaden.title"
bio: counterpart "team.content.steveRaden.bio"
image: "/assets/team/steve.png"
location: "alumni"
veronicaMaidel:
name: "Veronica Maidel"
title: counterpart "team.content.veronicaMaidel.title"
bio: counterpart "team.content.veronicaMaidel.bio"
image: "/assets/team/veronica.jpg"
location: "alumni"
victoriaVanHyning:
name: "Victoria Van Hyning"
twitter: "VanHyningV"
title: counterpart "team.content.victoriaVanHyning.title"
bio: counterpart "team.content.victoriaVanHyning.bio"
image: "/assets/team/victoria.JPG"
location: "oxford"
willGranger:
name: "Will Granger"
title: counterpart "team.content.willGranger.title"
bio: counterpart "team.content.willGranger.bio"
image: "/assets/team/will.jpg"
location: "chicago"
zachWolfenbarger:
name: "Zach Wolfenbarger"
title: counterpart "team.content.zachWolfenbarger.title"
bio: counterpart "team.content.zachWolfenbarger.bio"
image: "/assets/team/zach.JPG"
location: "chicago"
module.exports = createReactClass
displayName: 'TeamPage'
getInitialState: ->
currentSort: 'showAll'
sumArray: (object) ->
array.reduce (x, y) -> x + y
getCounts: ->
counts = {}
for teamMember, details of teamMembers
if details.location of counts
counts[details.location] += 1
else
counts[details.location] = 1
allCount = 0
for key, value of counts
if key isnt "alumni"
allCount += value
counts["showAll"] = allCount
return counts
render: ->
sideBarNav = counterpart "team.nav"
<div className="team-page secondary-page-copy">
<aside className="secondary-page-side-bar">
<nav ref="sideBarNav">
{for navItem of sideBarNav
counts = @getCounts(navItem)
<button key={navItem} ref={navItem} className="secret-button nav-#{navItem} side-bar-button" style={fontWeight: 700 if @state.currentSort is navItem} onClick={@showPeopleList.bind(null, navItem)}><Translate content="team.nav.#{navItem}" /> ({counts[navItem]})</button>}
</nav>
</aside>
<section className="team-member-list">
<h2>{if @state.currentSort is 'showAll'
<Translate content="team.content.header.showAll" />
else
@state.currentSort
}</h2>
{for teamMember, details of teamMembers
if (@state.currentSort is details.location) or (@state.currentSort is 'showAll' and details.location isnt 'alumni')
imageSrc = details.image
<div key={teamMember} className="team-member">
<img src={imageSrc} alt="#{details.name}" />
<div className="team-member-details">
<h3>{details.name}, {details.title} {if details.twitter then <a href="http://twitter.com/#{details.twitter}" target="_blank"><i className="fa fa-twitter"></i></a> }</h3>
<p>{details.bio}</p>
</div>
</div>
}
</section>
</div>
showPeopleList: (navItem) ->
@setState currentSort: navItem
| 67286 | counterpart = require 'counterpart'
React = require 'react'
createReactClass = require 'create-react-class'
Translate = require 'react-translate-component'
counterpart.registerTranslations 'en',
team:
nav:
showAll: 'Show All'
oxford: 'Oxford'
chicago: 'The Adler Planetarium'
minnesota: 'Minnesota'
portsmouth: 'Portsmouth'
california: 'California'
hilo: 'Hilo'
alumni: 'Alumni'
content:
header:
showAll: 'Zooniverse Team'
adamMcMaster:
title: 'Infrastructure Engineer'
bio: '''<NAME> is responsible for managing the Zooniverse's web hosting infrastructure.
He has a computer science degree and has worked in web hosting and development for many years.
He's also working on a degree in astronomy with the OU.'''
<NAME>lexBowyer:
title: 'Web Science Architect'
bio: '''<NAME> worked remotely for Zooniverse from his home in Northumberland.
He designed and ran Zooniverse experiments and developed infrastructure and front-end code. <NAME>
is a Dad of three, an improv player, a board gamer, and is running five half-marathons in 2016.'''
<NAME>lexWeiksnar:
title: 'Developer'
bio: '''<NAME> previously attended University of Miami, where he studied Psychology,
Biology, and English. <NAME> enjoys reading, coding, and sailing in his free time.'''
aliSwanson:
title: 'Researcher'
bio: '''<NAME> spent most of her PhD chasing lions around the Serengeti. She finished
her PhD in Ecology, Evolution, and Behavior at the University of Minnesota in 2014,
and joined the Zooniverse as a Postdoc in Ecology and Citizen Science.'''
# amitKapadia:
# title: 'Developer'
# bio: '''<NAME> was a developer at the Adler Planetarium.'''
<NAME>myBoyer:
title: 'Developer'
bio: '''<NAME> has been a Zooniverse developer at the Adler since November 2015. She holds a BS and
MS in computer science and has over a decade of industry experience. An aspiring astronomer as
a child, she couldn't be happier to have landed here.'''
<NAME>reaSim<NAME>:
title: 'Developer'
bio: '''<NAME> joined Zooniverse as a developer at the University of Minnesota in 2015. When she is not captivated by code, she can be found enjoying snow on skis and exploring lakes by kayak. She graduated from Carleton College with a degree in Cognitive Science.'''
<NAME>fonSm<NAME>:
title: 'Technical Lead'
bio: '''<NAME> was co-founder and Technical Lead of the Zooniverse for the first five years of the project.
<NAME> served as Director of Citizen Science at the Adler Planetarium and co-lead of the Zooniverse until fall 2013.'''
<NAME>ckyR<NAME>:
title: 'Visual Designer'
bio: '''<NAME> joined the Zooniverse team as designer in 2017. With a background in mobile apps and product design and a degree in journalism, she's excited to use her powers for good with the Zooniverse team.'''
beverleyNewing:
title: 'Web Developer Intern'
bio: '''<NAME> is an English and German literature graduate and worked as a Web Developer Intern at Zooniverse. In her spare time she's an avid fan of geese and enjoys motorbiking.'''
<NAME>Car<NAME>:
title: 'UX Developer'
bio: '''<NAME> moved from Chicago to Oxford and back again. <NAME> has a degree
in graphic design from Columbia College in Chicago, and worked in that field for a
number of years before finding a niche in web development.'''
brookeSimmons:
title: 'Researcher'
bio: 'Brooke is an astrophysicist studying black holes, galaxies, and how citizen
science can be applied to other non-traditional problems.'
camAllen:
title: 'Developer'
bio: '''Responsible for building the Zooniverse's API infrastructure.
Cam considers himself a music and fine wine connoisseur - others do not.
In his spare time he enjoys playing an obscure form of rugby.'''
<NAME>Lint<NAME>:
title: 'Zooniverse PI'
bio: '''Astronomer and co-founder of both Galaxy Zoo and the Zooniverse that grew from it,
<NAME> is interested in how galaxies form and evolve, how citizen science can change the
world, and whether the Chicago Fire can get their act together.'''
<NAME>risSnyder:
title: 'Project Manager'
bio: '''<NAME> began working on the Zooniverse team in fall 2012 as a web developer. In July 2013,
he became the technical project manager. He received a degree in computer science from the University of Dayton.'''
<NAME>D<NAME>:
title: 'Project Assistant'
bio: '''<NAME> supported the Zooniverse Oxford team from 2014-16. He had been with the Department
of Astrophysics for over 2 years administratively supporting various projects. A former trained actor,
he has the ability to look like he's smiling in the face of adversity!'''
<NAME>lemanK<NAME>:
title: 'Data Scientist'
bio: '''<NAME> is helping to create new data analysis and visualization tools for existing Zooniverse
projects as well as identifying new projects within the University of Portsmouth. He received
his PhD in astrophysics from Drexel University.'''
<NAME>renMcRo<NAME>:
title: 'Community Manager'
bio: '''<NAME> (DZM) served as a liaison to the Zooniverse community and assisted with strategic
content for projects. A Northwestern University graduate in journalism, he is also a golf addict,
amateur author, and hopeless animal lover.'''
<NAME>arrylW<NAME>:
title: 'Researcher'
bio: '<NAME> is doing machine learning research with the Zooniverse, based in Oxford.'
# edPaget:
# title: 'Developer'
# bio: '''<NAME> joined Adler's Zooniverse Team as a software developer in August 2012.
# He previously worked as a freelance programmer and photographer. <NAME> graduated from
# Northwestern University with a major in Radio/TV/Film.'''
<NAME>M<NAME>:
title: 'Communications Lead'
bio: '''A former exoplanetary scientist, <NAME> is now responsible for communicating with our volunteers and researchers. He is also behind the Zooniverse's presence on
social media and publishes the Daily Zooniverse blog.'''
<NAME>:
title: 'Web Development placement student'
bio: '''<NAME> is a PhD student in plant genetics from The University of Sheffield.
She is visiting Zooniverse on a placement to learn web development for a few months and is definitely not an intern.'''
<NAME>:
title: '<NAME>'
bio: '''After finishing a PhD studying the molecular basis of human brain development, <NAME> joined the Zooniverse as a Postdoc in citizen science and medical research.'''
<NAME>:
title: '<NAME>'
bio: '''<NAME> used machine learning and statistics to help projects analyse their volunteer
classifications. He has a PhD in Computer Science from University of Waterloo, Canada.
<NAME> loves to eat pancakes with real maple syrup and run ultramarathons.'''
<NAME>:
title: '<NAME>'
bio: '''<NAME> was the UX/UI Designer at the Zooniverse where he worked to craft thoughtful and
engaging user experiences. Apart from design, Heath also enjoys illustration, a good sci-fi or fantasy
novel, and exploring his new home in the Pacific Northwest.'''
<NAME>:
title: '<NAME>'
bio: '''<NAME> is a postdoc studying the Zooniverse.'''
<NAME>:
title: '<NAME>'
bio: '''<NAME> joined the Zooniverse team in 2017. Before discovering his passion for code,
he received a Ph.D in Mediterranean Archaeology from SUNY Buffalo, focusing on ancient Greece.
In his free time he enjoys wood working and the ancient art of fermentation.'''
<NAME>imODon<NAME>:
title: 'UX Developer'
bio: '''Professional cynic but his heart's not in it. Web developer for the Zooniverse,
Web Standards organiser, Amnesty UK activist.'''
<NAME>enGu<NAME>:
title: 'Educator'
bio: '''<NAME> works on Galaxy Zoo education in her role as the SEPnet/Ogden Outreach Officer
for the Institute of Cosmology and Gravitation, and has a PhD in astrophysics. Active
galactic nuclei were her first love.'''
<NAME>ordanMart<NAME>:
title: 'Visual Designer'
bio: '''<NAME> joined at the Adler Planetarium as Zooniverse's Visual Designer
starting in 2015. She spent her time making our user interfaces beautiful,
engaging, and a rewarding experience. At home she spends time with her
two cats and many houseplants.'''
<NAME>F<NAME>:
title: 'Educator'
bio: '''<NAME> has a background in space physics and museum studies. She works on educational
experiences, and Skype in the Classroom lessons for the Zooniverse. She loves to run, mostly
to compensate for her love of cupcakes and chocolate.'''
<NAME>arenM<NAME>:
title: 'Researcher'
bio: '''<NAME> is an astronomer and the Project Scientist of Galaxy Zoo, which she's been
involved in as a researcher since 2008. She's particularly interested in the evolution of
spiral galaxies.'''
<NAME>ellyB<NAME>:
title: 'Educator'
bio: '''With a background in museum education, <NAME> joined the Zooniverse in 2011 to bring
an educator's perspective and spread the word amongst teachers and students. She's fond of
several C's: chocolate, cats, coffee, and more chocolate.'''
<NAME>yleW<NAME>:
title: 'Researcher'
bio: '''<NAME> is an astronomer who studies galaxies, masers, and black holes (although he's
been getting more into data science). He worked on both Galaxy Zoo and Radio Galaxy Zoo,
and developed advanced tools for the volunteers.'''
<NAME>Trouille:
title: 'Zooniverse co-I'
bio: '''In July 2015, <NAME> became Director of Citizen Science at the Adler Planetarium and
co-I of the Zooniverse. While earning her Ph.D. in 2010 studying galaxy evolution,
she embodied cosmic collisions as a roller derby queen aptly named ‘The Big Bang’.'''
lauraWhyte:
title: 'Adler Planetarium Zooniverse Director'
bio: '''<NAME> was the Director of Citizen Science at Adler Planetarium and co-lead of the
Zooniverse from fall 2013 to summer 2015.'''
lucyFortson:
title: 'University of Minnesota Zooniverse Director'
bio: '''Associate Professor of Physics and Astronomy at the University of Minnesota. One of the Zooniverse
co-founders, she helps with project wrangling (aka management) and strategic planning while trying
to squeeze a bit of galaxy evolution science in.'''
<NAME>:
title: 'Web Developer Intern'
bio: '''<NAME> is the 2017 Web Development Intern at Zooniverse.
She is proficient with HTML and CSS and is currently learning JavaScript and Rails.'''
markBouslog:
title: 'Developer'
bio: '''<NAME> is a front-end web developer for the Zooniverse team at the Adler Planetarium. Joining in
November 2015 from a career in accounting, he’s thrilled to focus his number crunching to 1’s and 0’s
and is constantly inspired and humbled by the power of programming, citizen science and coffee.'''
<NAME>artenVeldth<NAME>:
title: 'Developer'
bio: '''<NAME> joined the development team in 2015. He has a degree in
computer science and enjoys crafting maintainable software. <NAME> learned about orbital
mechanics from Kerbal Space Program, and feels like he's therefore basically an astrophysicist.'''
megSchwamb:
title: 'Researcher'
bio: '''<NAME> is a planetary scientist and astronomer involved in the Planet Four projects,
and Comet Hunters for which she is project scientist. She studies small bodies in the
Solar System, exoplanets, and Mars. Meg has a fondness for baking, soccer, and champagne.'''
<NAME>lanieBe<NAME>:
title: 'Researcher'
bio: '''A PhD student at the University of Minnesota, <NAME> works on combining machine learning
with volunteer votes for classification tasks on the Galaxy Zoo project with the goal of classifying
*billions* of galaxies that future telescopes will see.'''
<NAME>ichaelP<NAME>ish:
title: 'Rails/Backend Developer'
bio: '''Software developer at the Zooniverse. He pwns databases daily. Dog, fishing, snakes, and bourbon.'''
<NAME>Mal<NAME>:
title: 'Mobile App Developer'
bio: '''<NAME>ah mainly has a background in mobile app development as well as some firmware and backend experience.
Outside of work, <NAME> enjoys cooking, baking and climbing.'''
<NAME>R<NAME>:
title: 'Developer'
bio: '<NAME> was a developer with the Zooniverse, based in Oxford.'
<NAME>:
title: '<NAME>'
bio: '''<NAME> is an astrophysicist working towards her doctorate in Oxford. She is
interested in how galaxies change over time and how we can track this evolution.
Happy-go-lucky about outreach, the Zooniverse and everything.'''
<NAME>S<NAME>:
title: 'Mobile App Developer'
bio: '''<NAME> has a background in web development for educational institutions. In her free time she enjoys board games and playing bass guitar.'''
<NAME>Simp<NAME>:
title: 'Developer'
bio: '<NAME> was one of the founding developers of the Zooniverse, based in Oxford.
If you can keep your head when all around you are losing theirs, you are probably
<NAME>.'
<NAME>H<NAME>:
title: 'Developer'
bio: '''<NAME> builds front end interfaces for the Zooniverse, and enjoys coding, music and rebuilding
motorbikes in his spare time.'''
samanthaBlickhan:
title: 'IMLS Postdoctoral Fellow'
bio: '''<NAME> is the IMLS Postdoctoral Fellow in the Department of Citizen Science at the Adler Planetarium, working on transcription projects for the Zooniverse. She received her Ph.D. in Musicology from Royal Holloway, University of London, with a thesis on the palaeography of British song notation in the 12th and 13th centuries. Her research interests include music and perception, and their relationships with writing systems, technology and pedagogy.'''
sandorKruk:
title: 'Researcher'
bio: '''<NAME> is a graduate student working on his PhD in Astrophysics at Oxford.
He is looking at how galaxies evolve using data from Galaxy Zoo and enjoys stargazing,
using telescopes, and dancing in his free time.'''
sarahAllen:
title: 'Developer'
bio: '''<NAME> is a front-end web developer for the Zooniverse team at the Adler
Planetarium starting in September 2014. She also has a degree in music and enjoys cooking
and live concerts in her free time.'''
saschaIshikawa:
title: 'Developer'
bio: '''<NAME> joined the Zooniverse team in November 2013 as a front-end developer.
A former researcher and software developer at NASA Ames, he received degrees in both
computer science and mechanical engineering.'''
shaunANoordin:
title: 'Developer'
bio: '''<NAME> was raised by Nintendo consoles and somehow transformed his love
for video games into a love for creating interactive experiences. When not at
his PC playing games or reading comics, he's at his PC studying web design and
coding experimental apps.'''
simoneDuca:
title: 'Web Developer'
bio: '''<NAME> is a front end web developer at the Zooniverse. He has a Phd in logic and philosophy
from Bristol and loves cooking.'''
stuartLynn:
title: 'Developer'
bio: '''<NAME> arrived at the Adler as a developer in July 2011, having been one of the founding
developers at Oxford. He studied mathematical physics at Edinburgh University and received his doctorate
in astrophysics from Royal Observatory Edinburgh. Data analysis maestro and web developer.'''
<NAME>Rad<NAME>:
title: 'Developer'
bio: '<NAME> was a developer at the Adler in Chicago.'
veronicaMaidel:
title: 'Data Scientist'
bio: '''Veronica is a Data Scientist who worked on discovering patterns in Zooniverse data, by manipulating
it and using it to create machine learning models. She received a PhD in Information Science and Technology
from Syracuse University.'''
victoriaVanH<NAME>:
title: 'Researcher'
bio: '''<NAME>ict<NAME> is a British Academy postdoctoral fellow in English at Oxford, and is the humanities PI
at Zooniverse. She works on Science Gossip, Annotate, and Shakespeare's World and more. Coffee is her lifeblood.'''
willGranger:
title: 'Developer'
bio: '''Will joined the Adler Planetarium in 2016 as a front-end developer for the Zooniverse.
In the past, he has taught English overseas, toured in bands, and helped open a music venue in Alabama.'''
zachWolfenbarger:
title: 'Developer'
bio: '''Zach is a software developer. He was a molecular biologist, but then the lab needed some code
to be written and the die was cast. He’s also in a couple of bands and can be found playing shows at bars
and comic conventions all over the midwest.'''
teamMembers =
adamMcMaster:
name: "<NAME>"
twitter: "astopy"
title: counterpart "team.content.adamMcMaster.title"
bio: counterpart "team.content.adamMcMaster.bio"
image: "/assets/team/adam.jpg"
location: "oxford"
alexBowyer:
name: "<NAME>"
twitter: "alexbfree"
title: counterpart "team.content.alexBowyer.title"
bio: counterpart "team.content.alexBowyer.bio"
image: "/assets/team/alex_bowyer.jpg"
location: "alumni"
# amitKapadia:
# name: "<NAME>"
# title: counterpart "team.content.amitKapadia.title"
# bio: counterpart "team.content.amitKapadia.bio"
# image: "/assets/team/amit.jpg"
# location: "alumni"
amyBoyer:
name: "<NAME>"
title: counterpart "team.content.amyBoyer.title"
bio: counterpart "team.content.amyBoyer.bio"
image: "/assets/team/amy.png"
location: "chicago"
<NAME>:
name: "<NAME>"
title: counterpart "team.content.alexWeiksnar.title"
bio: counterpart "team.content.alexWeiksnar.bio"
image: "/assets/team/alex.jpg"
location: "alumni"
aliSwanson:
name: "<NAME>"
twitter: "alicatzoo"
title: counterpart "team.content.aliSwanson.title"
bio: counterpart "team.content.aliSwanson.bio"
image: "/assets/team/ali.jpg"
location: "alumni"
arfonSmith:
name: "<NAME>"
title: counterpart "team.content.arfonSmith.title"
bio: counterpart "team.content.arfonSmith.bio"
image: "/assets/team/arfon.jpg"
location: "alumni"
andreaSimenstad:
name: "<NAME>"
title: counterpart "team.content.andreaSimenstad.title"
bio: counterpart "team.content.andreaSimenstad.bio"
image: "/assets/team/andrea.jpg"
location: "minnesota"
beverleyNewing:
name: "<NAME>"
twitter: "WebDevBev"
title: counterpart "team.content.beverleyNewing.title"
bio: counterpart "team.content.beverleyNewing.bio"
image: "/assets/team/beverley.jpg"
location: "alumni"
beckyRother:
name: "<NAME>"
twitter: "beckyrother"
title: counterpart "team.content.beckyRother.title"
bio: counterpart "team.content.beckyRother.bio"
image: "/assets/team/beckyrother.jpg"
location: "chicago"
<NAME>Car<NAME>:
name: "<NAME>"
twitter: "__brian_c__"
title: counterpart "team.content.brianCarstensen.title"
bio: counterpart "team.content.brianCarstensen.bio"
image: "/assets/team/brian.jpg"
location: "alumni"
broo<NAME>Simmons:
name: "<NAME>"
twitter: "vrooje"
title: counterpart "team.content.brookeSimmons.title"
bio: counterpart "team.content.brookeSimmons.bio"
image: "/assets/team/brooke.jpg"
location: "california"
camAllen:
name: "<NAME>"
title: counterpart "team.content.camAllen.title"
bio: counterpart "team.content.camAllen.bio"
image: "/assets/team/cam.jpg"
location: "oxford"
chrisLintott:
name: "<NAME>"
twitter: "chrislintott"
title: counterpart "team.content.chrisLintott.title"
bio: counterpart "team.content.chrisLintott.bio"
image: "/assets/team/chris-l.png"
location: "oxford"
chrisSnyder:
name: "<NAME>"
twitter: "bumishness"
title: counterpart "team.content.chrisSnyder.title"
bio: counterpart "team.content.chrisSnyder.bio"
image: "/assets/team/chriss.png"
location: "alumni"
<NAME>D<NAME>:
name: "<NAME>"
title: counterpart "team.content.christopherDoogue.title"
bio: counterpart "team.content.christopherDoogue.bio"
image: "/assets/team/chris-d.jpg"
location: "alumni"
<NAME>K<NAME>c<NAME>:
name: "<NAME>"
twitter: "ColemanKrawczyk"
title: counterpart "team.content.colemanKrawczyk.title"
bio: counterpart "team.content.colemanKrawczyk.bio"
image: "/assets/team/coleman.jpg"
location: "portsmouth"
<NAME>McRo<NAME>:
name: "<NAME>"
title: counterpart "team.content.darrenMcRoy.title"
bio: counterpart "team.content.darrenMcRoy.bio"
image: "/assets/team/darren.jpg"
location: "alumni"
darrylWright:
name: "<NAME>"
title: counterpart "team.content.darrylWright.title"
bio: counterpart "team.content.darrylWright.bio"
image: "/assets/team/team-member-avatar.jpg"
location: "oxford"
# edPaget:
# name: "<NAME>"
# twitter: "edpaget"
# title: counterpart "team.content.edPaget.title"
# bio: counterpart "team.content.edPaget.bio"
# image: "/assets/team/ed.png"
# location: "alumni"
grantMiller:
name: "<NAME>"
twitter: "mrniaboc"
title: counterpart "team.content.grantMiller.title"
bio: counterpart "team.content.grantMiller.bio"
image: "/assets/team/grant.jpg"
location: "oxford"
hannahSewell:
name: "<NAME>"
twitter: "hannahsewell2"
title: counterpart "team.content.hannahSewell.title"
bio: counterpart "team.content.hannahSewell.bio"
image: "/assets/team/hannah_s.jpg"
location: "oxford"
helenSpiers:
name: "<NAME>"
twitter: "H_Spiers"
title: counterpart "team.content.helenSpiers.title"
bio: counterpart "team.content.helenSpiers.bio"
image: "/assets/team/helenspiers.jpg"
location: "oxford"
<NAME>:
name: "<NAME>"
title: counterpart "team.content.gregHines.title"
bio: counterpart "team.content.gregHines.bio"
image: "/assets/team/greg.jpg"
location: "alumni"
heathVanSingel:
name: "<NAME>"
title: counterpart "team.content.heathVanSingel.title"
bio: counterpart "team.content.heathVanSingel.bio"
image: "/assets/team/heath.png"
location: "alumni"
h<NAME>Dick<NAME>son:
name: "<NAME>"
title: counterpart "team.content.hughDickinson.title"
bio: counterpart "team.content.hughDickinson.bio"
image: "/assets/team/hugh.jpg"
location: "minnesota"
jamesArtz:
name: "<NAME>"
title: counterpart "team.content.jamesArtz.title"
bio: counterpart "team.content.jamesArtz.bio"
image: "/assets/team/james.jpg"
location: "chicago"
jenGupta:
name: "<NAME>"
twitter: "jen_gupta"
title: counterpart "team.content.jenGupta.title"
bio: counterpart "team.content.jenGupta.bio"
image: "/assets/team/jen_gupta.jpg"
location: "portsmouth"
jimODonnell:
name: "<NAME>"
twitter: "pekingspring"
title: counterpart "team.content.jimODonnell.title"
bio: counterpart "team.content.jimODonnell.bio"
image: "/assets/team/jim.jpg"
location: "oxford"
j<NAME>Mart<NAME>:
name: "<NAME>"
twitter: "Jordanwhitneym"
title: counterpart "team.content.jordanMartin.title"
bio: counterpart "team.content.jordanMartin.bio"
image: "/assets/team/jordan.jpg"
location: "alumni"
<NAME>:
name: "<NAME>"
title: counterpart "team.content.julieFeldt.title"
bio: counterpart "team.content.julieFeldt.bio"
image: "/assets/team/julie.png"
location: "chicago"
k<NAME>M<NAME>:
name: "<NAME>"
twitter: "karenlmasters"
title: counterpart "team.content.karenMasters.title"
bio: counterpart "team.content.karenMasters.bio"
image: "/assets/team/karen.jpg"
location: "portsmouth"
kellyB<NAME>:
name: "<NAME>"
twitter: "BordenKelly"
title: counterpart "team.content.kellyBorden.title"
bio: counterpart "team.content.kellyBorden.bio"
image: "/assets/team/kelly.jpg"
location: "chicago"
<NAME>W<NAME>:
name: "<NAME>"
twitter: "kwwillett"
title: counterpart "team.content.kyleWillett.title"
bio: counterpart "team.content.kyleWillett.bio"
image: "/assets/team/kyle.jpg"
location: "alumni"
lauraTrouille:
name: "<NAME>"
twitter: "windycityastro"
title: counterpart "team.content.lauraTrouille.title"
bio: counterpart "team.content.lauraTrouille.bio"
image: "/assets/team/laura.jpg"
location: "chicago"
lauraWhyte:
name: "<NAME>"
title: counterpart "team.content.lauraWhyte.title"
bio: counterpart "team.content.lauraWhyte.bio"
image: "/assets/team/laura_w.jpg"
location: "alumni"
lucyFortson:
name: "<NAME>"
twitter: "lucyfortson"
title: counterpart "team.content.lucyFortson.title"
bio: counterpart "team.content.lucyFortson.bio"
image: "/assets/team/lucy.jpg"
location: "minnesota"
mariamSaeedi:
name: "<NAME>"
twitter: "tweetsmariam"
title: counterpart "team.content.mariamSaeedi.title"
bio: counterpart "team.content.mariamSaeedi.bio"
image: "/assets/team/mariam_s.jpg"
location: "oxford"
markBouslog:
name: "<NAME>"
title: counterpart "team.content.markBouslog.title"
bio: counterpart "team.content.markBouslog.bio"
image: "/assets/team/mark.jpg"
location: "chicago"
martenVeldthuis:
name: "<NAME>"
twitter: "mveldth"
title: counterpart "team.content.martenVeldthuis.title"
bio: counterpart "team.content.martenVeldthuis.bio"
image: "/assets/team/marten.jpg"
location: "oxford"
megSch<NAME>:
name: "<NAME>"
twitter: "megschwamb"
title: counterpart "team.content.megSchwamb.title"
bio: counterpart "team.content.megSchwamb.bio"
image: "/assets/team/meg.jpg"
location: "hilo"
melanieBeck:
name: "<NAME>"
twitter: "highzgal"
title: counterpart "team.content.melanieBeck.title"
bio: counterpart "team.content.melanieBeck.bio"
image: "/assets/team/melanie.jpg"
location: "minnesota"
<NAME>P<NAME>:
name: "<NAME>"
twitter: "michael_parrish"
title: counterpart "team.content.michaelParrish.title"
bio: counterpart "team.content.michaelParrish.bio"
image: "/assets/team/michael.png"
location: "alumni"
noahMalmed:
name: "<NAME>"
title: counterpart "team.content.noahMalmed.title"
bio: counterpart "team.content.noahMalmed.bio"
image: "/assets/team/noah.jpg"
location: "chicago"
perryRoper:
name: "<NAME>"
title: counterpart "team.content.perryRoper.title"
bio: counterpart "team.content.perryRoper.bio"
image: "/assets/team/perry.jpg"
location: "alumni"
rebeccaSmeth<NAME>:
name: "<NAME>"
twitter: "becky1505"
title: counterpart "team.content.rebeccaSmethurst.title"
bio: counterpart "team.content.rebeccaSmethurst.bio"
image: "/assets/team/becky.jpg"
location: "oxford"
robinSchaaf:
name: "<NAME>"
title: counterpart "team.content.robinSchaaf.title"
bio: counterpart "team.content.robinSchaaf.bio"
image: "/assets/team/robin.jpg"
location: "alumni"
<NAME>:
name: "<NAME>"
title: counterpart "team.content.rogerHutchings.title"
bio: counterpart "team.content.rogerHutchings.bio"
image: "/assets/team/roger.jpg"
location: "oxford"
<NAME>:
name: "<NAME>"
title: counterpart "team.content.robertSimpson.title"
bio: counterpart "team.content.robertSimpson.bio"
image: "/assets/team/rob.jpg"
location: "alumni"
<NAME>B<NAME>:
name: "<NAME>"
twitter: "snblickhan"
title: counterpart "team.content.samanthaBlickhan.title"
bio: counterpart "team.content.samanthaBlickhan.bio"
image: "/assets/team/sam.jpg"
location: "chicago"
s<NAME>:
name: "<NAME>"
twitter: "kruksandor"
title: counterpart "team.content.sandorKruk.title"
bio: counterpart "team.content.sandorKruk.bio"
image: "/assets/team/sandor.jpg"
location: "oxford"
sarahAllen:
name: "<NAME>"
title: counterpart "team.content.sarahAllen.title"
bio: counterpart "team.content.sarahAllen.bio"
image: "/assets/team/sarah.jpg"
location: "chicago"
saschaIshikawa:
name: "<NAME>"
twitter: "sascha_ishikawa"
title: counterpart "team.content.saschaIshikawa.title"
bio: counterpart "team.content.saschaIshikawa.bio"
image: "/assets/team/sascha.png"
location: "alumni"
shaunANoordin:
name: "<NAME>"
title: counterpart "team.content.shaunANoordin.title"
bio: counterpart "team.content.shaunANoordin.bio"
image: "/assets/team/shaunanoordin.jpg"
location: "oxford"
sim<NAME>Duca:
name: "<NAME>"
title: counterpart "team.content.simoneDuca.title"
bio: counterpart "team.content.simoneDuca.bio"
image: "/assets/team/simone.jpg"
location: "oxford"
<NAME>uartLynn:
name: "<NAME>"
title: counterpart "team.content.stuartLynn.title"
bio: counterpart "team.content.stuartLynn.bio"
image: "/assets/team/stuart.png"
location: "alumni"
<NAME>:
name: "<NAME>"
title: counterpart "team.content.steveRaden.title"
bio: counterpart "team.content.steveRaden.bio"
image: "/assets/team/steve.png"
location: "alumni"
<NAME>:
name: "<NAME>"
title: counterpart "team.content.veronicaMaidel.title"
bio: counterpart "team.content.veronicaMaidel.bio"
image: "/assets/team/veronica.jpg"
location: "alumni"
victoriaVanH<NAME>:
name: "<NAME>"
twitter: "VanHyningV"
title: counterpart "team.content.victoriaVanHyning.title"
bio: counterpart "team.content.victoriaVanHyning.bio"
image: "/assets/team/victoria.JPG"
location: "oxford"
willGranger:
name: "<NAME>"
title: counterpart "team.content.willGranger.title"
bio: counterpart "team.content.willGranger.bio"
image: "/assets/team/will.jpg"
location: "chicago"
zachWolfenbarger:
name: "<NAME>"
title: counterpart "team.content.zachWolfenbarger.title"
bio: counterpart "team.content.zachWolfenbarger.bio"
image: "/assets/team/zach.JPG"
location: "chicago"
module.exports = createReactClass
displayName: 'TeamPage'
getInitialState: ->
currentSort: 'showAll'
sumArray: (object) ->
array.reduce (x, y) -> x + y
getCounts: ->
counts = {}
for teamMember, details of teamMembers
if details.location of counts
counts[details.location] += 1
else
counts[details.location] = 1
allCount = 0
for key, value of counts
if key isnt "alumni"
allCount += value
counts["showAll"] = allCount
return counts
render: ->
sideBarNav = counterpart "team.nav"
<div className="team-page secondary-page-copy">
<aside className="secondary-page-side-bar">
<nav ref="sideBarNav">
{for navItem of sideBarNav
counts = @getCounts(navItem)
<button key={navItem} ref={navItem} className="secret-button nav-#{navItem} side-bar-button" style={fontWeight: 700 if @state.currentSort is navItem} onClick={@showPeopleList.bind(null, navItem)}><Translate content="team.nav.#{navItem}" /> ({counts[navItem]})</button>}
</nav>
</aside>
<section className="team-member-list">
<h2>{if @state.currentSort is 'showAll'
<Translate content="team.content.header.showAll" />
else
@state.currentSort
}</h2>
{for teamMember, details of teamMembers
if (@state.currentSort is details.location) or (@state.currentSort is 'showAll' and details.location isnt 'alumni')
imageSrc = details.image
<div key={teamMember} className="team-member">
<img src={imageSrc} alt="#{details.name}" />
<div className="team-member-details">
<h3>{details.name}, {details.title} {if details.twitter then <a href="http://twitter.com/#{details.twitter}" target="_blank"><i className="fa fa-twitter"></i></a> }</h3>
<p>{details.bio}</p>
</div>
</div>
}
</section>
</div>
showPeopleList: (navItem) ->
@setState currentSort: navItem
| true | counterpart = require 'counterpart'
React = require 'react'
createReactClass = require 'create-react-class'
Translate = require 'react-translate-component'
counterpart.registerTranslations 'en',
team:
nav:
showAll: 'Show All'
oxford: 'Oxford'
chicago: 'The Adler Planetarium'
minnesota: 'Minnesota'
portsmouth: 'Portsmouth'
california: 'California'
hilo: 'Hilo'
alumni: 'Alumni'
content:
header:
showAll: 'Zooniverse Team'
adamMcMaster:
title: 'Infrastructure Engineer'
bio: '''PI:NAME:<NAME>END_PI is responsible for managing the Zooniverse's web hosting infrastructure.
He has a computer science degree and has worked in web hosting and development for many years.
He's also working on a degree in astronomy with the OU.'''
PI:NAME:<NAME>END_PIlexBowyer:
title: 'Web Science Architect'
bio: '''PI:NAME:<NAME>END_PI worked remotely for Zooniverse from his home in Northumberland.
He designed and ran Zooniverse experiments and developed infrastructure and front-end code. PI:NAME:<NAME>END_PI
is a Dad of three, an improv player, a board gamer, and is running five half-marathons in 2016.'''
PI:NAME:<NAME>END_PIlexWeiksnar:
title: 'Developer'
bio: '''PI:NAME:<NAME>END_PI previously attended University of Miami, where he studied Psychology,
Biology, and English. PI:NAME:<NAME>END_PI enjoys reading, coding, and sailing in his free time.'''
aliSwanson:
title: 'Researcher'
bio: '''PI:NAME:<NAME>END_PI spent most of her PhD chasing lions around the Serengeti. She finished
her PhD in Ecology, Evolution, and Behavior at the University of Minnesota in 2014,
and joined the Zooniverse as a Postdoc in Ecology and Citizen Science.'''
# amitKapadia:
# title: 'Developer'
# bio: '''PI:NAME:<NAME>END_PI was a developer at the Adler Planetarium.'''
PI:NAME:<NAME>END_PImyBoyer:
title: 'Developer'
bio: '''PI:NAME:<NAME>END_PI has been a Zooniverse developer at the Adler since November 2015. She holds a BS and
MS in computer science and has over a decade of industry experience. An aspiring astronomer as
a child, she couldn't be happier to have landed here.'''
PI:NAME:<NAME>END_PIreaSimPI:NAME:<NAME>END_PI:
title: 'Developer'
bio: '''PI:NAME:<NAME>END_PI joined Zooniverse as a developer at the University of Minnesota in 2015. When she is not captivated by code, she can be found enjoying snow on skis and exploring lakes by kayak. She graduated from Carleton College with a degree in Cognitive Science.'''
PI:NAME:<NAME>END_PIfonSmPI:NAME:<NAME>END_PI:
title: 'Technical Lead'
bio: '''PI:NAME:<NAME>END_PI was co-founder and Technical Lead of the Zooniverse for the first five years of the project.
PI:NAME:<NAME>END_PI served as Director of Citizen Science at the Adler Planetarium and co-lead of the Zooniverse until fall 2013.'''
PI:NAME:<NAME>END_PIckyRPI:NAME:<NAME>END_PI:
title: 'Visual Designer'
bio: '''PI:NAME:<NAME>END_PI joined the Zooniverse team as designer in 2017. With a background in mobile apps and product design and a degree in journalism, she's excited to use her powers for good with the Zooniverse team.'''
beverleyNewing:
title: 'Web Developer Intern'
bio: '''PI:NAME:<NAME>END_PI is an English and German literature graduate and worked as a Web Developer Intern at Zooniverse. In her spare time she's an avid fan of geese and enjoys motorbiking.'''
PI:NAME:<NAME>END_PICarPI:NAME:<NAME>END_PI:
title: 'UX Developer'
bio: '''PI:NAME:<NAME>END_PI moved from Chicago to Oxford and back again. PI:NAME:<NAME>END_PI has a degree
in graphic design from Columbia College in Chicago, and worked in that field for a
number of years before finding a niche in web development.'''
brookeSimmons:
title: 'Researcher'
bio: 'Brooke is an astrophysicist studying black holes, galaxies, and how citizen
science can be applied to other non-traditional problems.'
camAllen:
title: 'Developer'
bio: '''Responsible for building the Zooniverse's API infrastructure.
Cam considers himself a music and fine wine connoisseur - others do not.
In his spare time he enjoys playing an obscure form of rugby.'''
PI:NAME:<NAME>END_PILintPI:NAME:<NAME>END_PI:
title: 'Zooniverse PI'
bio: '''Astronomer and co-founder of both Galaxy Zoo and the Zooniverse that grew from it,
PI:NAME:<NAME>END_PI is interested in how galaxies form and evolve, how citizen science can change the
world, and whether the Chicago Fire can get their act together.'''
PI:NAME:<NAME>END_PIrisSnyder:
title: 'Project Manager'
bio: '''PI:NAME:<NAME>END_PI began working on the Zooniverse team in fall 2012 as a web developer. In July 2013,
he became the technical project manager. He received a degree in computer science from the University of Dayton.'''
PI:NAME:<NAME>END_PIDPI:NAME:<NAME>END_PI:
title: 'Project Assistant'
bio: '''PI:NAME:<NAME>END_PI supported the Zooniverse Oxford team from 2014-16. He had been with the Department
of Astrophysics for over 2 years administratively supporting various projects. A former trained actor,
he has the ability to look like he's smiling in the face of adversity!'''
PI:NAME:<NAME>END_PIlemanKPI:NAME:<NAME>END_PI:
title: 'Data Scientist'
bio: '''PI:NAME:<NAME>END_PI is helping to create new data analysis and visualization tools for existing Zooniverse
projects as well as identifying new projects within the University of Portsmouth. He received
his PhD in astrophysics from Drexel University.'''
PI:NAME:<NAME>END_PIrenMcRoPI:NAME:<NAME>END_PI:
title: 'Community Manager'
bio: '''PI:NAME:<NAME>END_PI (DZM) served as a liaison to the Zooniverse community and assisted with strategic
content for projects. A Northwestern University graduate in journalism, he is also a golf addict,
amateur author, and hopeless animal lover.'''
PI:NAME:<NAME>END_PIarrylWPI:NAME:<NAME>END_PI:
title: 'Researcher'
bio: 'PI:NAME:<NAME>END_PI is doing machine learning research with the Zooniverse, based in Oxford.'
# edPaget:
# title: 'Developer'
# bio: '''PI:NAME:<NAME>END_PI joined Adler's Zooniverse Team as a software developer in August 2012.
# He previously worked as a freelance programmer and photographer. PI:NAME:<NAME>END_PI graduated from
# Northwestern University with a major in Radio/TV/Film.'''
PI:NAME:<NAME>END_PIMPI:NAME:<NAME>END_PI:
title: 'Communications Lead'
bio: '''A former exoplanetary scientist, PI:NAME:<NAME>END_PI is now responsible for communicating with our volunteers and researchers. He is also behind the Zooniverse's presence on
social media and publishes the Daily Zooniverse blog.'''
PI:NAME:<NAME>END_PI:
title: 'Web Development placement student'
bio: '''PI:NAME:<NAME>END_PI is a PhD student in plant genetics from The University of Sheffield.
She is visiting Zooniverse on a placement to learn web development for a few months and is definitely not an intern.'''
PI:NAME:<NAME>END_PI:
title: 'PI:NAME:<NAME>END_PI'
bio: '''After finishing a PhD studying the molecular basis of human brain development, PI:NAME:<NAME>END_PI joined the Zooniverse as a Postdoc in citizen science and medical research.'''
PI:NAME:<NAME>END_PI:
title: 'PI:NAME:<NAME>END_PI'
bio: '''PI:NAME:<NAME>END_PI used machine learning and statistics to help projects analyse their volunteer
classifications. He has a PhD in Computer Science from University of Waterloo, Canada.
PI:NAME:<NAME>END_PI loves to eat pancakes with real maple syrup and run ultramarathons.'''
PI:NAME:<NAME>END_PI:
title: 'PI:NAME:<NAME>END_PI'
bio: '''PI:NAME:<NAME>END_PI was the UX/UI Designer at the Zooniverse where he worked to craft thoughtful and
engaging user experiences. Apart from design, Heath also enjoys illustration, a good sci-fi or fantasy
novel, and exploring his new home in the Pacific Northwest.'''
PI:NAME:<NAME>END_PI:
title: 'PI:NAME:<NAME>END_PI'
bio: '''PI:NAME:<NAME>END_PI is a postdoc studying the Zooniverse.'''
PI:NAME:<NAME>END_PI:
title: 'PI:NAME:<NAME>END_PI'
bio: '''PI:NAME:<NAME>END_PI joined the Zooniverse team in 2017. Before discovering his passion for code,
he received a Ph.D in Mediterranean Archaeology from SUNY Buffalo, focusing on ancient Greece.
In his free time he enjoys wood working and the ancient art of fermentation.'''
PI:NAME:<NAME>END_PIimODonPI:NAME:<NAME>END_PI:
title: 'UX Developer'
bio: '''Professional cynic but his heart's not in it. Web developer for the Zooniverse,
Web Standards organiser, Amnesty UK activist.'''
PI:NAME:<NAME>END_PIenGuPI:NAME:<NAME>END_PI:
title: 'Educator'
bio: '''PI:NAME:<NAME>END_PI works on Galaxy Zoo education in her role as the SEPnet/Ogden Outreach Officer
for the Institute of Cosmology and Gravitation, and has a PhD in astrophysics. Active
galactic nuclei were her first love.'''
PI:NAME:<NAME>END_PIordanMartPI:NAME:<NAME>END_PI:
title: 'Visual Designer'
bio: '''PI:NAME:<NAME>END_PI joined at the Adler Planetarium as Zooniverse's Visual Designer
starting in 2015. She spent her time making our user interfaces beautiful,
engaging, and a rewarding experience. At home she spends time with her
two cats and many houseplants.'''
PI:NAME:<NAME>END_PIFPI:NAME:<NAME>END_PI:
title: 'Educator'
bio: '''PI:NAME:<NAME>END_PI has a background in space physics and museum studies. She works on educational
experiences, and Skype in the Classroom lessons for the Zooniverse. She loves to run, mostly
to compensate for her love of cupcakes and chocolate.'''
PI:NAME:<NAME>END_PIarenMPI:NAME:<NAME>END_PI:
title: 'Researcher'
bio: '''PI:NAME:<NAME>END_PI is an astronomer and the Project Scientist of Galaxy Zoo, which she's been
involved in as a researcher since 2008. She's particularly interested in the evolution of
spiral galaxies.'''
PI:NAME:<NAME>END_PIellyBPI:NAME:<NAME>END_PI:
title: 'Educator'
bio: '''With a background in museum education, PI:NAME:<NAME>END_PI joined the Zooniverse in 2011 to bring
an educator's perspective and spread the word amongst teachers and students. She's fond of
several C's: chocolate, cats, coffee, and more chocolate.'''
PI:NAME:<NAME>END_PIyleWPI:NAME:<NAME>END_PI:
title: 'Researcher'
bio: '''PI:NAME:<NAME>END_PI is an astronomer who studies galaxies, masers, and black holes (although he's
been getting more into data science). He worked on both Galaxy Zoo and Radio Galaxy Zoo,
and developed advanced tools for the volunteers.'''
PI:NAME:<NAME>END_PITrouille:
title: 'Zooniverse co-I'
bio: '''In July 2015, PI:NAME:<NAME>END_PI became Director of Citizen Science at the Adler Planetarium and
co-I of the Zooniverse. While earning her Ph.D. in 2010 studying galaxy evolution,
she embodied cosmic collisions as a roller derby queen aptly named ‘The Big Bang’.'''
lauraWhyte:
title: 'Adler Planetarium Zooniverse Director'
bio: '''PI:NAME:<NAME>END_PI was the Director of Citizen Science at Adler Planetarium and co-lead of the
Zooniverse from fall 2013 to summer 2015.'''
lucyFortson:
title: 'University of Minnesota Zooniverse Director'
bio: '''Associate Professor of Physics and Astronomy at the University of Minnesota. One of the Zooniverse
co-founders, she helps with project wrangling (aka management) and strategic planning while trying
to squeeze a bit of galaxy evolution science in.'''
PI:NAME:<NAME>END_PI:
title: 'Web Developer Intern'
bio: '''PI:NAME:<NAME>END_PI is the 2017 Web Development Intern at Zooniverse.
She is proficient with HTML and CSS and is currently learning JavaScript and Rails.'''
markBouslog:
title: 'Developer'
bio: '''PI:NAME:<NAME>END_PI is a front-end web developer for the Zooniverse team at the Adler Planetarium. Joining in
November 2015 from a career in accounting, he’s thrilled to focus his number crunching to 1’s and 0’s
and is constantly inspired and humbled by the power of programming, citizen science and coffee.'''
PI:NAME:<NAME>END_PIartenVeldthPI:NAME:<NAME>END_PI:
title: 'Developer'
bio: '''PI:NAME:<NAME>END_PI joined the development team in 2015. He has a degree in
computer science and enjoys crafting maintainable software. PI:NAME:<NAME>END_PI learned about orbital
mechanics from Kerbal Space Program, and feels like he's therefore basically an astrophysicist.'''
megSchwamb:
title: 'Researcher'
bio: '''PI:NAME:<NAME>END_PI is a planetary scientist and astronomer involved in the Planet Four projects,
and Comet Hunters for which she is project scientist. She studies small bodies in the
Solar System, exoplanets, and Mars. Meg has a fondness for baking, soccer, and champagne.'''
PI:NAME:<NAME>END_PIlanieBePI:NAME:<NAME>END_PI:
title: 'Researcher'
bio: '''A PhD student at the University of Minnesota, PI:NAME:<NAME>END_PI works on combining machine learning
with volunteer votes for classification tasks on the Galaxy Zoo project with the goal of classifying
*billions* of galaxies that future telescopes will see.'''
PI:NAME:<NAME>END_PIichaelPPI:NAME:<NAME>END_PIish:
title: 'Rails/Backend Developer'
bio: '''Software developer at the Zooniverse. He pwns databases daily. Dog, fishing, snakes, and bourbon.'''
PI:NAME:<NAME>END_PIMalPI:NAME:<NAME>END_PI:
title: 'Mobile App Developer'
bio: '''PI:NAME:<NAME>END_PIah mainly has a background in mobile app development as well as some firmware and backend experience.
Outside of work, PI:NAME:<NAME>END_PI enjoys cooking, baking and climbing.'''
PI:NAME:<NAME>END_PIRPI:NAME:<NAME>END_PI:
title: 'Developer'
bio: 'PI:NAME:<NAME>END_PI was a developer with the Zooniverse, based in Oxford.'
PI:NAME:<NAME>END_PI:
title: 'PI:NAME:<NAME>END_PI'
bio: '''PI:NAME:<NAME>END_PI is an astrophysicist working towards her doctorate in Oxford. She is
interested in how galaxies change over time and how we can track this evolution.
Happy-go-lucky about outreach, the Zooniverse and everything.'''
PI:NAME:<NAME>END_PISPI:NAME:<NAME>END_PI:
title: 'Mobile App Developer'
bio: '''PI:NAME:<NAME>END_PI has a background in web development for educational institutions. In her free time she enjoys board games and playing bass guitar.'''
PI:NAME:<NAME>END_PISimpPI:NAME:<NAME>END_PI:
title: 'Developer'
bio: 'PI:NAME:<NAME>END_PI was one of the founding developers of the Zooniverse, based in Oxford.
If you can keep your head when all around you are losing theirs, you are probably
PI:NAME:<NAME>END_PI.'
PI:NAME:<NAME>END_PIHPI:NAME:<NAME>END_PI:
title: 'Developer'
bio: '''PI:NAME:<NAME>END_PI builds front end interfaces for the Zooniverse, and enjoys coding, music and rebuilding
motorbikes in his spare time.'''
samanthaBlickhan:
title: 'IMLS Postdoctoral Fellow'
bio: '''PI:NAME:<NAME>END_PI is the IMLS Postdoctoral Fellow in the Department of Citizen Science at the Adler Planetarium, working on transcription projects for the Zooniverse. She received her Ph.D. in Musicology from Royal Holloway, University of London, with a thesis on the palaeography of British song notation in the 12th and 13th centuries. Her research interests include music and perception, and their relationships with writing systems, technology and pedagogy.'''
sandorKruk:
title: 'Researcher'
bio: '''PI:NAME:<NAME>END_PI is a graduate student working on his PhD in Astrophysics at Oxford.
He is looking at how galaxies evolve using data from Galaxy Zoo and enjoys stargazing,
using telescopes, and dancing in his free time.'''
sarahAllen:
title: 'Developer'
bio: '''PI:NAME:<NAME>END_PI is a front-end web developer for the Zooniverse team at the Adler
Planetarium starting in September 2014. She also has a degree in music and enjoys cooking
and live concerts in her free time.'''
saschaIshikawa:
title: 'Developer'
bio: '''PI:NAME:<NAME>END_PI joined the Zooniverse team in November 2013 as a front-end developer.
A former researcher and software developer at NASA Ames, he received degrees in both
computer science and mechanical engineering.'''
shaunANoordin:
title: 'Developer'
bio: '''PI:NAME:<NAME>END_PI was raised by Nintendo consoles and somehow transformed his love
for video games into a love for creating interactive experiences. When not at
his PC playing games or reading comics, he's at his PC studying web design and
coding experimental apps.'''
simoneDuca:
title: 'Web Developer'
bio: '''PI:NAME:<NAME>END_PI is a front end web developer at the Zooniverse. He has a Phd in logic and philosophy
from Bristol and loves cooking.'''
stuartLynn:
title: 'Developer'
bio: '''PI:NAME:<NAME>END_PI arrived at the Adler as a developer in July 2011, having been one of the founding
developers at Oxford. He studied mathematical physics at Edinburgh University and received his doctorate
in astrophysics from Royal Observatory Edinburgh. Data analysis maestro and web developer.'''
PI:NAME:<NAME>END_PIRadPI:NAME:<NAME>END_PI:
title: 'Developer'
bio: 'PI:NAME:<NAME>END_PI was a developer at the Adler in Chicago.'
veronicaMaidel:
title: 'Data Scientist'
bio: '''Veronica is a Data Scientist who worked on discovering patterns in Zooniverse data, by manipulating
it and using it to create machine learning models. She received a PhD in Information Science and Technology
from Syracuse University.'''
victoriaVanHPI:NAME:<NAME>END_PI:
title: 'Researcher'
bio: '''PI:NAME:<NAME>END_PIictPI:NAME:<NAME>END_PI is a British Academy postdoctoral fellow in English at Oxford, and is the humanities PI
at Zooniverse. She works on Science Gossip, Annotate, and Shakespeare's World and more. Coffee is her lifeblood.'''
willGranger:
title: 'Developer'
bio: '''Will joined the Adler Planetarium in 2016 as a front-end developer for the Zooniverse.
In the past, he has taught English overseas, toured in bands, and helped open a music venue in Alabama.'''
zachWolfenbarger:
title: 'Developer'
bio: '''Zach is a software developer. He was a molecular biologist, but then the lab needed some code
to be written and the die was cast. He’s also in a couple of bands and can be found playing shows at bars
and comic conventions all over the midwest.'''
teamMembers =
adamMcMaster:
name: "PI:NAME:<NAME>END_PI"
twitter: "astopy"
title: counterpart "team.content.adamMcMaster.title"
bio: counterpart "team.content.adamMcMaster.bio"
image: "/assets/team/adam.jpg"
location: "oxford"
alexBowyer:
name: "PI:NAME:<NAME>END_PI"
twitter: "alexbfree"
title: counterpart "team.content.alexBowyer.title"
bio: counterpart "team.content.alexBowyer.bio"
image: "/assets/team/alex_bowyer.jpg"
location: "alumni"
# amitKapadia:
# name: "PI:NAME:<NAME>END_PI"
# title: counterpart "team.content.amitKapadia.title"
# bio: counterpart "team.content.amitKapadia.bio"
# image: "/assets/team/amit.jpg"
# location: "alumni"
amyBoyer:
name: "PI:NAME:<NAME>END_PI"
title: counterpart "team.content.amyBoyer.title"
bio: counterpart "team.content.amyBoyer.bio"
image: "/assets/team/amy.png"
location: "chicago"
PI:NAME:<NAME>END_PI:
name: "PI:NAME:<NAME>END_PI"
title: counterpart "team.content.alexWeiksnar.title"
bio: counterpart "team.content.alexWeiksnar.bio"
image: "/assets/team/alex.jpg"
location: "alumni"
aliSwanson:
name: "PI:NAME:<NAME>END_PI"
twitter: "alicatzoo"
title: counterpart "team.content.aliSwanson.title"
bio: counterpart "team.content.aliSwanson.bio"
image: "/assets/team/ali.jpg"
location: "alumni"
arfonSmith:
name: "PI:NAME:<NAME>END_PI"
title: counterpart "team.content.arfonSmith.title"
bio: counterpart "team.content.arfonSmith.bio"
image: "/assets/team/arfon.jpg"
location: "alumni"
andreaSimenstad:
name: "PI:NAME:<NAME>END_PI"
title: counterpart "team.content.andreaSimenstad.title"
bio: counterpart "team.content.andreaSimenstad.bio"
image: "/assets/team/andrea.jpg"
location: "minnesota"
beverleyNewing:
name: "PI:NAME:<NAME>END_PI"
twitter: "WebDevBev"
title: counterpart "team.content.beverleyNewing.title"
bio: counterpart "team.content.beverleyNewing.bio"
image: "/assets/team/beverley.jpg"
location: "alumni"
beckyRother:
name: "PI:NAME:<NAME>END_PI"
twitter: "beckyrother"
title: counterpart "team.content.beckyRother.title"
bio: counterpart "team.content.beckyRother.bio"
image: "/assets/team/beckyrother.jpg"
location: "chicago"
PI:NAME:<NAME>END_PICarPI:NAME:<NAME>END_PI:
name: "PI:NAME:<NAME>END_PI"
twitter: "__brian_c__"
title: counterpart "team.content.brianCarstensen.title"
bio: counterpart "team.content.brianCarstensen.bio"
image: "/assets/team/brian.jpg"
location: "alumni"
brooPI:NAME:<NAME>END_PISimmons:
name: "PI:NAME:<NAME>END_PI"
twitter: "vrooje"
title: counterpart "team.content.brookeSimmons.title"
bio: counterpart "team.content.brookeSimmons.bio"
image: "/assets/team/brooke.jpg"
location: "california"
camAllen:
name: "PI:NAME:<NAME>END_PI"
title: counterpart "team.content.camAllen.title"
bio: counterpart "team.content.camAllen.bio"
image: "/assets/team/cam.jpg"
location: "oxford"
chrisLintott:
name: "PI:NAME:<NAME>END_PI"
twitter: "chrislintott"
title: counterpart "team.content.chrisLintott.title"
bio: counterpart "team.content.chrisLintott.bio"
image: "/assets/team/chris-l.png"
location: "oxford"
chrisSnyder:
name: "PI:NAME:<NAME>END_PI"
twitter: "bumishness"
title: counterpart "team.content.chrisSnyder.title"
bio: counterpart "team.content.chrisSnyder.bio"
image: "/assets/team/chriss.png"
location: "alumni"
PI:NAME:<NAME>END_PIDPI:NAME:<NAME>END_PI:
name: "PI:NAME:<NAME>END_PI"
title: counterpart "team.content.christopherDoogue.title"
bio: counterpart "team.content.christopherDoogue.bio"
image: "/assets/team/chris-d.jpg"
location: "alumni"
PI:NAME:<NAME>END_PIKPI:NAME:<NAME>END_PIcPI:NAME:<NAME>END_PI:
name: "PI:NAME:<NAME>END_PI"
twitter: "ColemanKrawczyk"
title: counterpart "team.content.colemanKrawczyk.title"
bio: counterpart "team.content.colemanKrawczyk.bio"
image: "/assets/team/coleman.jpg"
location: "portsmouth"
PI:NAME:<NAME>END_PIMcRoPI:NAME:<NAME>END_PI:
name: "PI:NAME:<NAME>END_PI"
title: counterpart "team.content.darrenMcRoy.title"
bio: counterpart "team.content.darrenMcRoy.bio"
image: "/assets/team/darren.jpg"
location: "alumni"
darrylWright:
name: "PI:NAME:<NAME>END_PI"
title: counterpart "team.content.darrylWright.title"
bio: counterpart "team.content.darrylWright.bio"
image: "/assets/team/team-member-avatar.jpg"
location: "oxford"
# edPaget:
# name: "PI:NAME:<NAME>END_PI"
# twitter: "edpaget"
# title: counterpart "team.content.edPaget.title"
# bio: counterpart "team.content.edPaget.bio"
# image: "/assets/team/ed.png"
# location: "alumni"
grantMiller:
name: "PI:NAME:<NAME>END_PI"
twitter: "mrniaboc"
title: counterpart "team.content.grantMiller.title"
bio: counterpart "team.content.grantMiller.bio"
image: "/assets/team/grant.jpg"
location: "oxford"
hannahSewell:
name: "PI:NAME:<NAME>END_PI"
twitter: "hannahsewell2"
title: counterpart "team.content.hannahSewell.title"
bio: counterpart "team.content.hannahSewell.bio"
image: "/assets/team/hannah_s.jpg"
location: "oxford"
helenSpiers:
name: "PI:NAME:<NAME>END_PI"
twitter: "H_Spiers"
title: counterpart "team.content.helenSpiers.title"
bio: counterpart "team.content.helenSpiers.bio"
image: "/assets/team/helenspiers.jpg"
location: "oxford"
PI:NAME:<NAME>END_PI:
name: "PI:NAME:<NAME>END_PI"
title: counterpart "team.content.gregHines.title"
bio: counterpart "team.content.gregHines.bio"
image: "/assets/team/greg.jpg"
location: "alumni"
heathVanSingel:
name: "PI:NAME:<NAME>END_PI"
title: counterpart "team.content.heathVanSingel.title"
bio: counterpart "team.content.heathVanSingel.bio"
image: "/assets/team/heath.png"
location: "alumni"
hPI:NAME:<NAME>END_PIDickPI:NAME:<NAME>END_PIson:
name: "PI:NAME:<NAME>END_PI"
title: counterpart "team.content.hughDickinson.title"
bio: counterpart "team.content.hughDickinson.bio"
image: "/assets/team/hugh.jpg"
location: "minnesota"
jamesArtz:
name: "PI:NAME:<NAME>END_PI"
title: counterpart "team.content.jamesArtz.title"
bio: counterpart "team.content.jamesArtz.bio"
image: "/assets/team/james.jpg"
location: "chicago"
jenGupta:
name: "PI:NAME:<NAME>END_PI"
twitter: "jen_gupta"
title: counterpart "team.content.jenGupta.title"
bio: counterpart "team.content.jenGupta.bio"
image: "/assets/team/jen_gupta.jpg"
location: "portsmouth"
jimODonnell:
name: "PI:NAME:<NAME>END_PI"
twitter: "pekingspring"
title: counterpart "team.content.jimODonnell.title"
bio: counterpart "team.content.jimODonnell.bio"
image: "/assets/team/jim.jpg"
location: "oxford"
jPI:NAME:<NAME>END_PIMartPI:NAME:<NAME>END_PI:
name: "PI:NAME:<NAME>END_PI"
twitter: "Jordanwhitneym"
title: counterpart "team.content.jordanMartin.title"
bio: counterpart "team.content.jordanMartin.bio"
image: "/assets/team/jordan.jpg"
location: "alumni"
PI:NAME:<NAME>END_PI:
name: "PI:NAME:<NAME>END_PI"
title: counterpart "team.content.julieFeldt.title"
bio: counterpart "team.content.julieFeldt.bio"
image: "/assets/team/julie.png"
location: "chicago"
kPI:NAME:<NAME>END_PIMPI:NAME:<NAME>END_PI:
name: "PI:NAME:<NAME>END_PI"
twitter: "karenlmasters"
title: counterpart "team.content.karenMasters.title"
bio: counterpart "team.content.karenMasters.bio"
image: "/assets/team/karen.jpg"
location: "portsmouth"
kellyBPI:NAME:<NAME>END_PI:
name: "PI:NAME:<NAME>END_PI"
twitter: "BordenKelly"
title: counterpart "team.content.kellyBorden.title"
bio: counterpart "team.content.kellyBorden.bio"
image: "/assets/team/kelly.jpg"
location: "chicago"
PI:NAME:<NAME>END_PIWPI:NAME:<NAME>END_PI:
name: "PI:NAME:<NAME>END_PI"
twitter: "kwwillett"
title: counterpart "team.content.kyleWillett.title"
bio: counterpart "team.content.kyleWillett.bio"
image: "/assets/team/kyle.jpg"
location: "alumni"
lauraTrouille:
name: "PI:NAME:<NAME>END_PI"
twitter: "windycityastro"
title: counterpart "team.content.lauraTrouille.title"
bio: counterpart "team.content.lauraTrouille.bio"
image: "/assets/team/laura.jpg"
location: "chicago"
lauraWhyte:
name: "PI:NAME:<NAME>END_PI"
title: counterpart "team.content.lauraWhyte.title"
bio: counterpart "team.content.lauraWhyte.bio"
image: "/assets/team/laura_w.jpg"
location: "alumni"
lucyFortson:
name: "PI:NAME:<NAME>END_PI"
twitter: "lucyfortson"
title: counterpart "team.content.lucyFortson.title"
bio: counterpart "team.content.lucyFortson.bio"
image: "/assets/team/lucy.jpg"
location: "minnesota"
mariamSaeedi:
name: "PI:NAME:<NAME>END_PI"
twitter: "tweetsmariam"
title: counterpart "team.content.mariamSaeedi.title"
bio: counterpart "team.content.mariamSaeedi.bio"
image: "/assets/team/mariam_s.jpg"
location: "oxford"
markBouslog:
name: "PI:NAME:<NAME>END_PI"
title: counterpart "team.content.markBouslog.title"
bio: counterpart "team.content.markBouslog.bio"
image: "/assets/team/mark.jpg"
location: "chicago"
martenVeldthuis:
name: "PI:NAME:<NAME>END_PI"
twitter: "mveldth"
title: counterpart "team.content.martenVeldthuis.title"
bio: counterpart "team.content.martenVeldthuis.bio"
image: "/assets/team/marten.jpg"
location: "oxford"
megSchPI:NAME:<NAME>END_PI:
name: "PI:NAME:<NAME>END_PI"
twitter: "megschwamb"
title: counterpart "team.content.megSchwamb.title"
bio: counterpart "team.content.megSchwamb.bio"
image: "/assets/team/meg.jpg"
location: "hilo"
melanieBeck:
name: "PI:NAME:<NAME>END_PI"
twitter: "highzgal"
title: counterpart "team.content.melanieBeck.title"
bio: counterpart "team.content.melanieBeck.bio"
image: "/assets/team/melanie.jpg"
location: "minnesota"
PI:NAME:<NAME>END_PIPPI:NAME:<NAME>END_PI:
name: "PI:NAME:<NAME>END_PI"
twitter: "michael_parrish"
title: counterpart "team.content.michaelParrish.title"
bio: counterpart "team.content.michaelParrish.bio"
image: "/assets/team/michael.png"
location: "alumni"
noahMalmed:
name: "PI:NAME:<NAME>END_PI"
title: counterpart "team.content.noahMalmed.title"
bio: counterpart "team.content.noahMalmed.bio"
image: "/assets/team/noah.jpg"
location: "chicago"
perryRoper:
name: "PI:NAME:<NAME>END_PI"
title: counterpart "team.content.perryRoper.title"
bio: counterpart "team.content.perryRoper.bio"
image: "/assets/team/perry.jpg"
location: "alumni"
rebeccaSmethPI:NAME:<NAME>END_PI:
name: "PI:NAME:<NAME>END_PI"
twitter: "becky1505"
title: counterpart "team.content.rebeccaSmethurst.title"
bio: counterpart "team.content.rebeccaSmethurst.bio"
image: "/assets/team/becky.jpg"
location: "oxford"
robinSchaaf:
name: "PI:NAME:<NAME>END_PI"
title: counterpart "team.content.robinSchaaf.title"
bio: counterpart "team.content.robinSchaaf.bio"
image: "/assets/team/robin.jpg"
location: "alumni"
PI:NAME:<NAME>END_PI:
name: "PI:NAME:<NAME>END_PI"
title: counterpart "team.content.rogerHutchings.title"
bio: counterpart "team.content.rogerHutchings.bio"
image: "/assets/team/roger.jpg"
location: "oxford"
PI:NAME:<NAME>END_PI:
name: "PI:NAME:<NAME>END_PI"
title: counterpart "team.content.robertSimpson.title"
bio: counterpart "team.content.robertSimpson.bio"
image: "/assets/team/rob.jpg"
location: "alumni"
PI:NAME:<NAME>END_PIBPI:NAME:<NAME>END_PI:
name: "PI:NAME:<NAME>END_PI"
twitter: "snblickhan"
title: counterpart "team.content.samanthaBlickhan.title"
bio: counterpart "team.content.samanthaBlickhan.bio"
image: "/assets/team/sam.jpg"
location: "chicago"
sPI:NAME:<NAME>END_PI:
name: "PI:NAME:<NAME>END_PI"
twitter: "kruksandor"
title: counterpart "team.content.sandorKruk.title"
bio: counterpart "team.content.sandorKruk.bio"
image: "/assets/team/sandor.jpg"
location: "oxford"
sarahAllen:
name: "PI:NAME:<NAME>END_PI"
title: counterpart "team.content.sarahAllen.title"
bio: counterpart "team.content.sarahAllen.bio"
image: "/assets/team/sarah.jpg"
location: "chicago"
saschaIshikawa:
name: "PI:NAME:<NAME>END_PI"
twitter: "sascha_ishikawa"
title: counterpart "team.content.saschaIshikawa.title"
bio: counterpart "team.content.saschaIshikawa.bio"
image: "/assets/team/sascha.png"
location: "alumni"
shaunANoordin:
name: "PI:NAME:<NAME>END_PI"
title: counterpart "team.content.shaunANoordin.title"
bio: counterpart "team.content.shaunANoordin.bio"
image: "/assets/team/shaunanoordin.jpg"
location: "oxford"
simPI:NAME:<NAME>END_PIDuca:
name: "PI:NAME:<NAME>END_PI"
title: counterpart "team.content.simoneDuca.title"
bio: counterpart "team.content.simoneDuca.bio"
image: "/assets/team/simone.jpg"
location: "oxford"
PI:NAME:<NAME>END_PIuartLynn:
name: "PI:NAME:<NAME>END_PI"
title: counterpart "team.content.stuartLynn.title"
bio: counterpart "team.content.stuartLynn.bio"
image: "/assets/team/stuart.png"
location: "alumni"
PI:NAME:<NAME>END_PI:
name: "PI:NAME:<NAME>END_PI"
title: counterpart "team.content.steveRaden.title"
bio: counterpart "team.content.steveRaden.bio"
image: "/assets/team/steve.png"
location: "alumni"
PI:NAME:<NAME>END_PI:
name: "PI:NAME:<NAME>END_PI"
title: counterpart "team.content.veronicaMaidel.title"
bio: counterpart "team.content.veronicaMaidel.bio"
image: "/assets/team/veronica.jpg"
location: "alumni"
victoriaVanHPI:NAME:<NAME>END_PI:
name: "PI:NAME:<NAME>END_PI"
twitter: "VanHyningV"
title: counterpart "team.content.victoriaVanHyning.title"
bio: counterpart "team.content.victoriaVanHyning.bio"
image: "/assets/team/victoria.JPG"
location: "oxford"
willGranger:
name: "PI:NAME:<NAME>END_PI"
title: counterpart "team.content.willGranger.title"
bio: counterpart "team.content.willGranger.bio"
image: "/assets/team/will.jpg"
location: "chicago"
zachWolfenbarger:
name: "PI:NAME:<NAME>END_PI"
title: counterpart "team.content.zachWolfenbarger.title"
bio: counterpart "team.content.zachWolfenbarger.bio"
image: "/assets/team/zach.JPG"
location: "chicago"
module.exports = createReactClass
displayName: 'TeamPage'
getInitialState: ->
currentSort: 'showAll'
sumArray: (object) ->
array.reduce (x, y) -> x + y
getCounts: ->
counts = {}
for teamMember, details of teamMembers
if details.location of counts
counts[details.location] += 1
else
counts[details.location] = 1
allCount = 0
for key, value of counts
if key isnt "alumni"
allCount += value
counts["showAll"] = allCount
return counts
render: ->
sideBarNav = counterpart "team.nav"
<div className="team-page secondary-page-copy">
<aside className="secondary-page-side-bar">
<nav ref="sideBarNav">
{for navItem of sideBarNav
counts = @getCounts(navItem)
<button key={navItem} ref={navItem} className="secret-button nav-#{navItem} side-bar-button" style={fontWeight: 700 if @state.currentSort is navItem} onClick={@showPeopleList.bind(null, navItem)}><Translate content="team.nav.#{navItem}" /> ({counts[navItem]})</button>}
</nav>
</aside>
<section className="team-member-list">
<h2>{if @state.currentSort is 'showAll'
<Translate content="team.content.header.showAll" />
else
@state.currentSort
}</h2>
{for teamMember, details of teamMembers
if (@state.currentSort is details.location) or (@state.currentSort is 'showAll' and details.location isnt 'alumni')
imageSrc = details.image
<div key={teamMember} className="team-member">
<img src={imageSrc} alt="#{details.name}" />
<div className="team-member-details">
<h3>{details.name}, {details.title} {if details.twitter then <a href="http://twitter.com/#{details.twitter}" target="_blank"><i className="fa fa-twitter"></i></a> }</h3>
<p>{details.bio}</p>
</div>
</div>
}
</section>
</div>
showPeopleList: (navItem) ->
@setState currentSort: navItem
|
[
{
"context": "z: \"form-control\", group:\"details\"},\n {field: \"username\", type: 'text', label: \"User\", clazz: \"form-contr",
"end": 126,
"score": 0.9861356616020203,
"start": 118,
"tag": "USERNAME",
"value": "username"
},
{
"context": "\"},\n {field: \"username\", type: 'text', label: \"User\", clazz: \"form-control\", group:\"details\"},\n {f",
"end": 155,
"score": 0.8799170851707458,
"start": 151,
"tag": "USERNAME",
"value": "User"
},
{
"context": "\"},\n {field: \"password\", type: 'text', label: \"Password\", clazz: \"form-control\", group:\"details\"},\n {f",
"end": 343,
"score": 0.9910294413566589,
"start": 335,
"tag": "PASSWORD",
"value": "Password"
}
] | src/packages/carpool-admin/client/UsersAdmin.coffee | ArnoldasSid/vilnius-carpool | 11 | userForm = [
{field: "email", type: 'text', label: "Email", clazz: "form-control", group:"details"},
{field: "username", type: 'text', label: "User", clazz: "form-control", group:"details"},
{field: "name", type: 'text', label: "Name", clazz: "form-control", group:"details"},
{field: "password", type: 'text', label: "Password", clazz: "form-control", group:"details"},
{field: "roles", type: 'listedit', label: "Role", clazz: "form-control", group:"details"},
]
class @UsersAdminController extends AdminController
waitOn: ()->
[Meteor.subscribe("adminUserContacts")]
data: ()=>
d("Forms subscribtion ready "+@ready())
return unless @ready
# Each collection item map to form
forms = Meteor.users.find().map (item)->
formValues: createFormValues userForm,
username: item.username
name: item.profile?.name or "Anonymous"
roles: item.roles
email: item.emails?[0]?.address
, item._id, "#{item._id}-"
editMode: new ReactiveVar(false)
_id: item._id
# Add empty form for new items
forms.unshift
formValues: createFormValues(userForm, {})
editMode: new ReactiveVar(true)
result =
form: userForm
forms: forms
actions:
save: (event, template)->
values = getFormValues(@formValues, template, "#{@_id}-" if @_id)
values.profile = name: values.name
delete values.name
d "Saving user", values
if not @_id
Meteor.call "createAccount", values, (err, result)=>
if err then d "Account creating error", err
else
@editMode.set(false);
else
values._id = @_id
Meteor.call "updateAccount", values, (err, result)=>
if err then d "Account updating error", err
else
@editMode.set(false);
remove: (event, template)->
Meteor.call "deleteAccount", @_id, (err, result)=>
if err then d "Account removing error", err
| 95542 | userForm = [
{field: "email", type: 'text', label: "Email", clazz: "form-control", group:"details"},
{field: "username", type: 'text', label: "User", clazz: "form-control", group:"details"},
{field: "name", type: 'text', label: "Name", clazz: "form-control", group:"details"},
{field: "password", type: 'text', label: "<PASSWORD>", clazz: "form-control", group:"details"},
{field: "roles", type: 'listedit', label: "Role", clazz: "form-control", group:"details"},
]
class @UsersAdminController extends AdminController
waitOn: ()->
[Meteor.subscribe("adminUserContacts")]
data: ()=>
d("Forms subscribtion ready "+@ready())
return unless @ready
# Each collection item map to form
forms = Meteor.users.find().map (item)->
formValues: createFormValues userForm,
username: item.username
name: item.profile?.name or "Anonymous"
roles: item.roles
email: item.emails?[0]?.address
, item._id, "#{item._id}-"
editMode: new ReactiveVar(false)
_id: item._id
# Add empty form for new items
forms.unshift
formValues: createFormValues(userForm, {})
editMode: new ReactiveVar(true)
result =
form: userForm
forms: forms
actions:
save: (event, template)->
values = getFormValues(@formValues, template, "#{@_id}-" if @_id)
values.profile = name: values.name
delete values.name
d "Saving user", values
if not @_id
Meteor.call "createAccount", values, (err, result)=>
if err then d "Account creating error", err
else
@editMode.set(false);
else
values._id = @_id
Meteor.call "updateAccount", values, (err, result)=>
if err then d "Account updating error", err
else
@editMode.set(false);
remove: (event, template)->
Meteor.call "deleteAccount", @_id, (err, result)=>
if err then d "Account removing error", err
| true | userForm = [
{field: "email", type: 'text', label: "Email", clazz: "form-control", group:"details"},
{field: "username", type: 'text', label: "User", clazz: "form-control", group:"details"},
{field: "name", type: 'text', label: "Name", clazz: "form-control", group:"details"},
{field: "password", type: 'text', label: "PI:PASSWORD:<PASSWORD>END_PI", clazz: "form-control", group:"details"},
{field: "roles", type: 'listedit', label: "Role", clazz: "form-control", group:"details"},
]
class @UsersAdminController extends AdminController
waitOn: ()->
[Meteor.subscribe("adminUserContacts")]
data: ()=>
d("Forms subscribtion ready "+@ready())
return unless @ready
# Each collection item map to form
forms = Meteor.users.find().map (item)->
formValues: createFormValues userForm,
username: item.username
name: item.profile?.name or "Anonymous"
roles: item.roles
email: item.emails?[0]?.address
, item._id, "#{item._id}-"
editMode: new ReactiveVar(false)
_id: item._id
# Add empty form for new items
forms.unshift
formValues: createFormValues(userForm, {})
editMode: new ReactiveVar(true)
result =
form: userForm
forms: forms
actions:
save: (event, template)->
values = getFormValues(@formValues, template, "#{@_id}-" if @_id)
values.profile = name: values.name
delete values.name
d "Saving user", values
if not @_id
Meteor.call "createAccount", values, (err, result)=>
if err then d "Account creating error", err
else
@editMode.set(false);
else
values._id = @_id
Meteor.call "updateAccount", values, (err, result)=>
if err then d "Account updating error", err
else
@editMode.set(false);
remove: (event, template)->
Meteor.call "deleteAccount", @_id, (err, result)=>
if err then d "Account removing error", err
|
[
{
"context": "h at one point). \n keyTimeslot = [\"Y#{row.key.shift()}Q#{row.key.shift()}\"]\n ",
"end": 1105,
"score": 0.8464520573616028,
"start": 1099,
"tag": "KEY",
"value": "Y#{row"
},
{
"context": "e point). \n keyTimeslot = [\"Y#{row.key.shift()}Q#{row.key.shift()}\"]\n # The rest is WBS,",
"end": 1124,
"score": 0.8264829516410828,
"start": 1106,
"tag": "KEY",
"value": "key.shift()}Q#{row"
},
{
"context": " keyTimeslot = [\"Y#{row.key.shift()}Q#{row.key.shift()}\"]\n # The rest is WBS, the work bre",
"end": 1137,
"score": 0.8367111682891846,
"start": 1125,
"tag": "KEY",
"value": "key.shift()}"
},
{
"context": "h at one point). \n keyTimeslot = [\"Y#{row.key.shift()}Q#{row.key.shift()}\"]\n ",
"end": 5647,
"score": 0.6242822408676147,
"start": 5644,
"tag": "KEY",
"value": "Y#{"
},
{
"context": "int). \n keyTimeslot = [\"Y#{row.key.shift()}Q#{row.key.shift()}\"]\n # The rest is W",
"end": 5666,
"score": 0.7636646032333374,
"start": 5655,
"tag": "KEY",
"value": "shift()}Q#{"
},
{
"context": " keyTimeslot = [\"Y#{row.key.shift()}Q#{row.key.shift()}\"]\n # The rest is WBS, the work bre",
"end": 5682,
"score": 0.7585160136222839,
"start": 5674,
"tag": "KEY",
"value": "shift()}"
},
{
"context": "h at one point). \n keyTimeslot = [\"Y#{row.key.shift()}Q#{row.key.shift()}\"]\n ",
"end": 10988,
"score": 0.8867115378379822,
"start": 10985,
"tag": "KEY",
"value": "Y#{"
},
{
"context": "int). \n keyTimeslot = [\"Y#{row.key.shift()}Q#{row.key.shift()}\"]\n # The rest is W",
"end": 11007,
"score": 0.9029834270477295,
"start": 10996,
"tag": "KEY",
"value": "shift()}Q#{"
},
{
"context": " keyTimeslot = [\"Y#{row.key.shift()}Q#{row.key.shift()}\"]\n # The rest is WBS, the work bre",
"end": 11023,
"score": 0.8826444149017334,
"start": 11015,
"tag": "KEY",
"value": "shift()}"
}
] | lists/chart.coffee | IKS/Proggis | 2 | (head, req) ->
view = req.path.pop()
groupLevel = req.query.group_level
taskFilter = Number req.query.task_filter
roundNumber = (rnum, rlength) ->
Math.round(parseFloat(rnum) * Math.pow(10, rlength)) / Math.pow(10, rlength)
# We fill this structure for a stacked Jit Chart
# `values` is an array of columns `{label:` column label, `values:` numbers in the column`}`
# these columns are shown stacked on the chart.
# `label` is an array of row labels
chart = {}
switch view
# ######################################################################
# used for planned effort over time
when "EffortAllocTime"
chart = {values: [], label: []}
switch groupLevel
when "3"
labelPrefix = "WP"
when "4"
labelPrefix = "Task"
tree = {}
while row = getRow()
# row.key has two parts. The first and second are Year and Quarter
# (or month at one point).
keyTimeslot = ["Y#{row.key.shift()}Q#{row.key.shift()}"]
# The rest is WBS, the work breakdown structure.
keyWbs = row.key
if taskFilter and keyWbs[0] is taskFilter or not taskFilter
# the treeAddress consists of the timeslot (e.g. "Y2Q4")
# and the keyWbs (e.g. "2.3")
treeAddress = [keyTimeslot, keyWbs]
# Iterate on the tree to find the right place for the row.
# row.key
leaf = tree
for i, keyEl of treeAddress
leaf[keyEl] = {} unless leaf[keyEl] instanceof Object
leaf = leaf[keyEl]
leaf.value = 0 unless leaf.value
leaf.value += Number(row.value)
# Make dotted label-notation out of the comma-separated one
wbsLabel = (key) ->
"#{labelPrefix} #{key.replace ",", "."}"
# iterate through the tree
# First is the timeslots
for timeslotKey, timeslotValue of tree
# A column object has the label of the timeslot
column =
label: timeslotKey
values: []
chart.values.push column
for wbs, task of timeslotValue
# column.values are the actual numbers in a column.
column.values.push task.value
# stacked labels in `chart.label` consist of wbs labels
# (e.g. "WP 3" or "Task 2.4")
chart.label = []
for wbs, task of timeslotValue
chart.label.push wbsLabel wbs
# ######################################################################
# used for planned effort by partner
when "EffortAllocPartner"
chart = {values: [], label: []}
switch groupLevel
when "2"
labelPrefix = "WP"
when "3"
labelPrefix = "Task"
tree = {}
while row = getRow()
# row.key has two parts. The first and second are Year and Quarter
# (or month at one point).
keyPartner = row.key.shift()
# The rest is WBS, the work breakdown structure.
keyWbs = row.key
if taskFilter and keyWbs[0] is taskFilter or not taskFilter
# the treeAddress consists of the timeslot (e.g. "Y2Q4")
# and the keyWbs (e.g. "2.3")
treeAddress = [keyPartner, keyWbs]
# Iterate on the tree to find the right place for the row.
# row.key
leaf = tree
for i, keyEl of treeAddress
leaf[keyEl] = {} unless leaf[keyEl] instanceof Object
leaf = leaf[keyEl]
leaf.value = row.value
# send JSON.stringify tree
# Make dotted label-notation out of the comma-separated one
wbsLabel = (key) ->
"#{labelPrefix} #{key.replace ",", "."}"
# iterate through the tree
# First is the partners
for partnerKey, partnerValue of tree
# A column object has the label of the timeslot
column =
label: partnerKey
values: []
chart.values.push column
for wbs, task of partnerValue
# column.values are the actual numbers in a column.
column.values.push task.value
# stacked labels in `chart.label` consist of wbs labels
# (e.g. "WP 3" or "Task 2.4")
chart.label = []
for wbs, task of partnerValue
chart.label.push wbsLabel wbs
# ######################################################################
# used for monitoring effort over time
when "EffortTime"
chart = {values: [], label: []}
switch groupLevel
when "3"
labelPrefix = "WP"
when "4"
labelPrefix = "Task"
tree = {}
while row = getRow()
# row.key has two parts. The first and second are Year and Quarter
# (or month at one point).
keyTimeslot = ["Y#{row.key.shift()}Q#{row.key.shift()}"]
# The rest is WBS, the work breakdown structure.
keyWbs = row.key
if taskFilter and keyWbs[0] is taskFilter or not taskFilter
# the treeAddress consists of the timeslot (e.g. "Y2Q4")
# and the keyWbs (e.g. "2.3")
treeAddress = [keyTimeslot, keyWbs]
# Iterate on the tree to find the right place for the row.
# row.key
leaf = tree
for i, keyEl of treeAddress
leaf[keyEl] = {} unless leaf[keyEl] instanceof Object
leaf = leaf[keyEl]
leaf.value = row.value
# Make dotted label-notation out of the comma-separated one
wbsLabel = (key) ->
"#{labelPrefix} #{key.replace ",", "."}"
# iterate through the tree
# First is the timeslots
for timeslotKey, timeslotValue of tree
# A column object has the label of the timeslot
columnPlan =
label: "#{timeslotKey} planned"
values: []
chart.values.push columnPlan
columnSpent =
label: "#{timeslotKey} spent"
values: []
chart.values.push columnSpent
for wbs, task of timeslotValue
# column.values are the actual numbers in a column.
columnPlan.values.push task.value.planned
columnSpent.values.push roundNumber task.value.spent, 1
# stacked labels in `chart.label` consist of wbs labels
# (e.g. "WP 3" or "Task 2.4")
chart.label = []
for wbs, task of timeslotValue
chart.label.push wbsLabel wbs
# ######################################################################
# used for monitoring plan and spent efforts on the partners
when "EffortPartner"
chart = {values: [], label: []}
switch groupLevel
when "2"
labelPrefix = "WP"
when "3"
labelPrefix = "Task"
tree = {}
while row = getRow()
# row.key has two parts. The first and second are Year and Quarter
# (or month at one point).
keyPartner = row.key.shift()
# The rest is WBS, the work breakdown structure.
keyWbs = row.key
if taskFilter and keyWbs[0] is taskFilter or not taskFilter
# the treeAddress consists of the timeslot (e.g. "Y2Q4")
# and the keyWbs (e.g. "2.3")
treeAddress = [keyPartner, keyWbs]
# Iterate on the tree to find the right place for the row.
# row.key
leaf = tree
for i, keyEl of treeAddress
leaf[keyEl] = {} unless leaf[keyEl] instanceof Object
leaf = leaf[keyEl]
leaf.value = row.value
# send JSON.stringify tree
# Make dotted label-notation out of the comma-separated one
wbsLabel = (key) ->
"#{labelPrefix} #{key.replace ",", "."}"
# iterate through the tree
# First is the partners
for partnerKey, partnerValue of tree
# A column object has the label of the timeslot
columnPlan =
# column label
label: "#{partnerKey} planned"
values: []
chart.values.push columnPlan
columnSpent =
# column label
label: "#{partnerKey} spent"
values: []
chart.values.push columnSpent
for wbs, task of partnerValue
# column.values are the actual numbers in a column.
columnPlan.values.push task.value.planned
columnSpent.values.push roundNumber task.value.spent, 1
# stacked (row) labels in `chart.label` consist of wbs labels
# (e.g. "WP 3" or "Task 2.4")
chart.label = []
for wbs, task of partnerValue
chart.label.push wbsLabel wbs
# ######################################################################
# used for showing the project performance over the whole period of the
# project.
# The JSON format follows the flot.js plotter data format with
# data = [[x1, y1],[x2,y2]..] instead of just [y1, y2, ...] as it is
# needed for Jit charts.
when "ProjectOverTime"
chart = {values: []}
switch groupLevel
when "3"
labelPrefix = "WP"
when "4"
labelPrefix = "Task"
tree = {}
while row = getRow()
# row.key has two parts. The first and second are Year and Quarter
# (or month at one point).
keyTimeslot = ["Y#{row.key.shift()}Q#{row.key.shift()}"]
# The rest is WBS, the work breakdown structure.
keyWbs = row.key
if taskFilter and keyWbs[0] is taskFilter or not taskFilter
# the treeAddress consists of the timeslot (e.g. "Y2Q4")
# and the keyWbs (e.g. "2.3")
treeAddress = [keyTimeslot, keyWbs]
# Iterate on the tree to find the right place for the row.
# row.key
leaf = tree
for i, keyEl of treeAddress
leaf[keyEl] = {} unless leaf[keyEl] instanceof Object
leaf = leaf[keyEl]
leaf.value = row.value
# Make dotted label-notation out of the comma-separated one
wbsLabel = (key) ->
"#{labelPrefix} #{key.replace ",", "."}"
chart.values =
xaxis:
ticks: [[0, " "]]
yaxis:
[{
position: "right"
},{
position: "left"
}]
plan: [[0,0]]
spent: [[0,0]]
deliverablePlan: [[0,0]]
deliverableComplete: [[0,0]]
# one tick is a quarter
xtickDays: 365/4
i = 0
# iterate through the tree
# First is the timeslots
for timeslotKey, timeslotValue of tree
i++
chart.values.xaxis.ticks.push [i, timeslotKey]
plan = [i, 0]
chart.values.plan.push plan
spent = [i, 0]
chart.values.spent.push spent
deliverablePlan = [i, 0]
chart.values.deliverablePlan.push deliverablePlan
deliverableComplete = [i, 0]
chart.values.deliverableComplete.push deliverableComplete
for wbs, task of timeslotValue
# column.values are the actual numbers in a column.
plan[1] += task.value.planned
spent[1] += roundNumber task.value.spent, 1
deliverablePlan[1] += task.value.deliverables
deliverableComplete[1] += task.value.completed
# stacked labels in `chart.label` consist of wbs labels
# (e.g. "WP 3" or "Task 2.4")
# chart.label = []
# for wbs, task of timeslotValue
# chart.label.push wbsLabel wbs
getSum = (array) ->
sum = 0
for valArr in array
sum += valArr[1]
sum
accumulate = (array, sum) ->
acc = []
reached = 0
for valArr in array
reached += valArr[1]
acc.push [valArr[0], reached] if valArr[1] or not acc.length
acc
chart.values.plan = accumulate chart.values.plan, getSum chart.values.plan
chart.values.spent = accumulate chart.values.spent, getSum chart.values.plan
chart.values.deliverablePlan =
accumulate chart.values.deliverablePlan, getSum chart.values.deliverablePlan
chart.values.deliverableComplete =
accumulate chart.values.deliverableComplete, getSum chart.values.deliverablePlan
# Send the actual chart object to the client.
send JSON.stringify chart
| 36929 | (head, req) ->
view = req.path.pop()
groupLevel = req.query.group_level
taskFilter = Number req.query.task_filter
roundNumber = (rnum, rlength) ->
Math.round(parseFloat(rnum) * Math.pow(10, rlength)) / Math.pow(10, rlength)
# We fill this structure for a stacked Jit Chart
# `values` is an array of columns `{label:` column label, `values:` numbers in the column`}`
# these columns are shown stacked on the chart.
# `label` is an array of row labels
chart = {}
switch view
# ######################################################################
# used for planned effort over time
when "EffortAllocTime"
chart = {values: [], label: []}
switch groupLevel
when "3"
labelPrefix = "WP"
when "4"
labelPrefix = "Task"
tree = {}
while row = getRow()
# row.key has two parts. The first and second are Year and Quarter
# (or month at one point).
keyTimeslot = ["<KEY>.<KEY>.<KEY>"]
# The rest is WBS, the work breakdown structure.
keyWbs = row.key
if taskFilter and keyWbs[0] is taskFilter or not taskFilter
# the treeAddress consists of the timeslot (e.g. "Y2Q4")
# and the keyWbs (e.g. "2.3")
treeAddress = [keyTimeslot, keyWbs]
# Iterate on the tree to find the right place for the row.
# row.key
leaf = tree
for i, keyEl of treeAddress
leaf[keyEl] = {} unless leaf[keyEl] instanceof Object
leaf = leaf[keyEl]
leaf.value = 0 unless leaf.value
leaf.value += Number(row.value)
# Make dotted label-notation out of the comma-separated one
wbsLabel = (key) ->
"#{labelPrefix} #{key.replace ",", "."}"
# iterate through the tree
# First is the timeslots
for timeslotKey, timeslotValue of tree
# A column object has the label of the timeslot
column =
label: timeslotKey
values: []
chart.values.push column
for wbs, task of timeslotValue
# column.values are the actual numbers in a column.
column.values.push task.value
# stacked labels in `chart.label` consist of wbs labels
# (e.g. "WP 3" or "Task 2.4")
chart.label = []
for wbs, task of timeslotValue
chart.label.push wbsLabel wbs
# ######################################################################
# used for planned effort by partner
when "EffortAllocPartner"
chart = {values: [], label: []}
switch groupLevel
when "2"
labelPrefix = "WP"
when "3"
labelPrefix = "Task"
tree = {}
while row = getRow()
# row.key has two parts. The first and second are Year and Quarter
# (or month at one point).
keyPartner = row.key.shift()
# The rest is WBS, the work breakdown structure.
keyWbs = row.key
if taskFilter and keyWbs[0] is taskFilter or not taskFilter
# the treeAddress consists of the timeslot (e.g. "Y2Q4")
# and the keyWbs (e.g. "2.3")
treeAddress = [keyPartner, keyWbs]
# Iterate on the tree to find the right place for the row.
# row.key
leaf = tree
for i, keyEl of treeAddress
leaf[keyEl] = {} unless leaf[keyEl] instanceof Object
leaf = leaf[keyEl]
leaf.value = row.value
# send JSON.stringify tree
# Make dotted label-notation out of the comma-separated one
wbsLabel = (key) ->
"#{labelPrefix} #{key.replace ",", "."}"
# iterate through the tree
# First is the partners
for partnerKey, partnerValue of tree
# A column object has the label of the timeslot
column =
label: partnerKey
values: []
chart.values.push column
for wbs, task of partnerValue
# column.values are the actual numbers in a column.
column.values.push task.value
# stacked labels in `chart.label` consist of wbs labels
# (e.g. "WP 3" or "Task 2.4")
chart.label = []
for wbs, task of partnerValue
chart.label.push wbsLabel wbs
# ######################################################################
# used for monitoring effort over time
when "EffortTime"
chart = {values: [], label: []}
switch groupLevel
when "3"
labelPrefix = "WP"
when "4"
labelPrefix = "Task"
tree = {}
while row = getRow()
# row.key has two parts. The first and second are Year and Quarter
# (or month at one point).
keyTimeslot = ["<KEY>row.key.<KEY>row.key.<KEY>"]
# The rest is WBS, the work breakdown structure.
keyWbs = row.key
if taskFilter and keyWbs[0] is taskFilter or not taskFilter
# the treeAddress consists of the timeslot (e.g. "Y2Q4")
# and the keyWbs (e.g. "2.3")
treeAddress = [keyTimeslot, keyWbs]
# Iterate on the tree to find the right place for the row.
# row.key
leaf = tree
for i, keyEl of treeAddress
leaf[keyEl] = {} unless leaf[keyEl] instanceof Object
leaf = leaf[keyEl]
leaf.value = row.value
# Make dotted label-notation out of the comma-separated one
wbsLabel = (key) ->
"#{labelPrefix} #{key.replace ",", "."}"
# iterate through the tree
# First is the timeslots
for timeslotKey, timeslotValue of tree
# A column object has the label of the timeslot
columnPlan =
label: "#{timeslotKey} planned"
values: []
chart.values.push columnPlan
columnSpent =
label: "#{timeslotKey} spent"
values: []
chart.values.push columnSpent
for wbs, task of timeslotValue
# column.values are the actual numbers in a column.
columnPlan.values.push task.value.planned
columnSpent.values.push roundNumber task.value.spent, 1
# stacked labels in `chart.label` consist of wbs labels
# (e.g. "WP 3" or "Task 2.4")
chart.label = []
for wbs, task of timeslotValue
chart.label.push wbsLabel wbs
# ######################################################################
# used for monitoring plan and spent efforts on the partners
when "EffortPartner"
chart = {values: [], label: []}
switch groupLevel
when "2"
labelPrefix = "WP"
when "3"
labelPrefix = "Task"
tree = {}
while row = getRow()
# row.key has two parts. The first and second are Year and Quarter
# (or month at one point).
keyPartner = row.key.shift()
# The rest is WBS, the work breakdown structure.
keyWbs = row.key
if taskFilter and keyWbs[0] is taskFilter or not taskFilter
# the treeAddress consists of the timeslot (e.g. "Y2Q4")
# and the keyWbs (e.g. "2.3")
treeAddress = [keyPartner, keyWbs]
# Iterate on the tree to find the right place for the row.
# row.key
leaf = tree
for i, keyEl of treeAddress
leaf[keyEl] = {} unless leaf[keyEl] instanceof Object
leaf = leaf[keyEl]
leaf.value = row.value
# send JSON.stringify tree
# Make dotted label-notation out of the comma-separated one
wbsLabel = (key) ->
"#{labelPrefix} #{key.replace ",", "."}"
# iterate through the tree
# First is the partners
for partnerKey, partnerValue of tree
# A column object has the label of the timeslot
columnPlan =
# column label
label: "#{partnerKey} planned"
values: []
chart.values.push columnPlan
columnSpent =
# column label
label: "#{partnerKey} spent"
values: []
chart.values.push columnSpent
for wbs, task of partnerValue
# column.values are the actual numbers in a column.
columnPlan.values.push task.value.planned
columnSpent.values.push roundNumber task.value.spent, 1
# stacked (row) labels in `chart.label` consist of wbs labels
# (e.g. "WP 3" or "Task 2.4")
chart.label = []
for wbs, task of partnerValue
chart.label.push wbsLabel wbs
# ######################################################################
# used for showing the project performance over the whole period of the
# project.
# The JSON format follows the flot.js plotter data format with
# data = [[x1, y1],[x2,y2]..] instead of just [y1, y2, ...] as it is
# needed for Jit charts.
when "ProjectOverTime"
chart = {values: []}
switch groupLevel
when "3"
labelPrefix = "WP"
when "4"
labelPrefix = "Task"
tree = {}
while row = getRow()
# row.key has two parts. The first and second are Year and Quarter
# (or month at one point).
keyTimeslot = ["<KEY>row.key.<KEY>row.key.<KEY>"]
# The rest is WBS, the work breakdown structure.
keyWbs = row.key
if taskFilter and keyWbs[0] is taskFilter or not taskFilter
# the treeAddress consists of the timeslot (e.g. "Y2Q4")
# and the keyWbs (e.g. "2.3")
treeAddress = [keyTimeslot, keyWbs]
# Iterate on the tree to find the right place for the row.
# row.key
leaf = tree
for i, keyEl of treeAddress
leaf[keyEl] = {} unless leaf[keyEl] instanceof Object
leaf = leaf[keyEl]
leaf.value = row.value
# Make dotted label-notation out of the comma-separated one
wbsLabel = (key) ->
"#{labelPrefix} #{key.replace ",", "."}"
chart.values =
xaxis:
ticks: [[0, " "]]
yaxis:
[{
position: "right"
},{
position: "left"
}]
plan: [[0,0]]
spent: [[0,0]]
deliverablePlan: [[0,0]]
deliverableComplete: [[0,0]]
# one tick is a quarter
xtickDays: 365/4
i = 0
# iterate through the tree
# First is the timeslots
for timeslotKey, timeslotValue of tree
i++
chart.values.xaxis.ticks.push [i, timeslotKey]
plan = [i, 0]
chart.values.plan.push plan
spent = [i, 0]
chart.values.spent.push spent
deliverablePlan = [i, 0]
chart.values.deliverablePlan.push deliverablePlan
deliverableComplete = [i, 0]
chart.values.deliverableComplete.push deliverableComplete
for wbs, task of timeslotValue
# column.values are the actual numbers in a column.
plan[1] += task.value.planned
spent[1] += roundNumber task.value.spent, 1
deliverablePlan[1] += task.value.deliverables
deliverableComplete[1] += task.value.completed
# stacked labels in `chart.label` consist of wbs labels
# (e.g. "WP 3" or "Task 2.4")
# chart.label = []
# for wbs, task of timeslotValue
# chart.label.push wbsLabel wbs
getSum = (array) ->
sum = 0
for valArr in array
sum += valArr[1]
sum
accumulate = (array, sum) ->
acc = []
reached = 0
for valArr in array
reached += valArr[1]
acc.push [valArr[0], reached] if valArr[1] or not acc.length
acc
chart.values.plan = accumulate chart.values.plan, getSum chart.values.plan
chart.values.spent = accumulate chart.values.spent, getSum chart.values.plan
chart.values.deliverablePlan =
accumulate chart.values.deliverablePlan, getSum chart.values.deliverablePlan
chart.values.deliverableComplete =
accumulate chart.values.deliverableComplete, getSum chart.values.deliverablePlan
# Send the actual chart object to the client.
send JSON.stringify chart
| true | (head, req) ->
view = req.path.pop()
groupLevel = req.query.group_level
taskFilter = Number req.query.task_filter
roundNumber = (rnum, rlength) ->
Math.round(parseFloat(rnum) * Math.pow(10, rlength)) / Math.pow(10, rlength)
# We fill this structure for a stacked Jit Chart
# `values` is an array of columns `{label:` column label, `values:` numbers in the column`}`
# these columns are shown stacked on the chart.
# `label` is an array of row labels
chart = {}
switch view
# ######################################################################
# used for planned effort over time
when "EffortAllocTime"
chart = {values: [], label: []}
switch groupLevel
when "3"
labelPrefix = "WP"
when "4"
labelPrefix = "Task"
tree = {}
while row = getRow()
# row.key has two parts. The first and second are Year and Quarter
# (or month at one point).
keyTimeslot = ["PI:KEY:<KEY>END_PI.PI:KEY:<KEY>END_PI.PI:KEY:<KEY>END_PI"]
# The rest is WBS, the work breakdown structure.
keyWbs = row.key
if taskFilter and keyWbs[0] is taskFilter or not taskFilter
# the treeAddress consists of the timeslot (e.g. "Y2Q4")
# and the keyWbs (e.g. "2.3")
treeAddress = [keyTimeslot, keyWbs]
# Iterate on the tree to find the right place for the row.
# row.key
leaf = tree
for i, keyEl of treeAddress
leaf[keyEl] = {} unless leaf[keyEl] instanceof Object
leaf = leaf[keyEl]
leaf.value = 0 unless leaf.value
leaf.value += Number(row.value)
# Make dotted label-notation out of the comma-separated one
wbsLabel = (key) ->
"#{labelPrefix} #{key.replace ",", "."}"
# iterate through the tree
# First is the timeslots
for timeslotKey, timeslotValue of tree
# A column object has the label of the timeslot
column =
label: timeslotKey
values: []
chart.values.push column
for wbs, task of timeslotValue
# column.values are the actual numbers in a column.
column.values.push task.value
# stacked labels in `chart.label` consist of wbs labels
# (e.g. "WP 3" or "Task 2.4")
chart.label = []
for wbs, task of timeslotValue
chart.label.push wbsLabel wbs
# ######################################################################
# used for planned effort by partner
when "EffortAllocPartner"
chart = {values: [], label: []}
switch groupLevel
when "2"
labelPrefix = "WP"
when "3"
labelPrefix = "Task"
tree = {}
while row = getRow()
# row.key has two parts. The first and second are Year and Quarter
# (or month at one point).
keyPartner = row.key.shift()
# The rest is WBS, the work breakdown structure.
keyWbs = row.key
if taskFilter and keyWbs[0] is taskFilter or not taskFilter
# the treeAddress consists of the timeslot (e.g. "Y2Q4")
# and the keyWbs (e.g. "2.3")
treeAddress = [keyPartner, keyWbs]
# Iterate on the tree to find the right place for the row.
# row.key
leaf = tree
for i, keyEl of treeAddress
leaf[keyEl] = {} unless leaf[keyEl] instanceof Object
leaf = leaf[keyEl]
leaf.value = row.value
# send JSON.stringify tree
# Make dotted label-notation out of the comma-separated one
wbsLabel = (key) ->
"#{labelPrefix} #{key.replace ",", "."}"
# iterate through the tree
# First is the partners
for partnerKey, partnerValue of tree
# A column object has the label of the timeslot
column =
label: partnerKey
values: []
chart.values.push column
for wbs, task of partnerValue
# column.values are the actual numbers in a column.
column.values.push task.value
# stacked labels in `chart.label` consist of wbs labels
# (e.g. "WP 3" or "Task 2.4")
chart.label = []
for wbs, task of partnerValue
chart.label.push wbsLabel wbs
# ######################################################################
# used for monitoring effort over time
when "EffortTime"
chart = {values: [], label: []}
switch groupLevel
when "3"
labelPrefix = "WP"
when "4"
labelPrefix = "Task"
tree = {}
while row = getRow()
# row.key has two parts. The first and second are Year and Quarter
# (or month at one point).
keyTimeslot = ["PI:KEY:<KEY>END_PIrow.key.PI:KEY:<KEY>END_PIrow.key.PI:KEY:<KEY>END_PI"]
# The rest is WBS, the work breakdown structure.
keyWbs = row.key
if taskFilter and keyWbs[0] is taskFilter or not taskFilter
# the treeAddress consists of the timeslot (e.g. "Y2Q4")
# and the keyWbs (e.g. "2.3")
treeAddress = [keyTimeslot, keyWbs]
# Iterate on the tree to find the right place for the row.
# row.key
leaf = tree
for i, keyEl of treeAddress
leaf[keyEl] = {} unless leaf[keyEl] instanceof Object
leaf = leaf[keyEl]
leaf.value = row.value
# Make dotted label-notation out of the comma-separated one
wbsLabel = (key) ->
"#{labelPrefix} #{key.replace ",", "."}"
# iterate through the tree
# First is the timeslots
for timeslotKey, timeslotValue of tree
# A column object has the label of the timeslot
columnPlan =
label: "#{timeslotKey} planned"
values: []
chart.values.push columnPlan
columnSpent =
label: "#{timeslotKey} spent"
values: []
chart.values.push columnSpent
for wbs, task of timeslotValue
# column.values are the actual numbers in a column.
columnPlan.values.push task.value.planned
columnSpent.values.push roundNumber task.value.spent, 1
# stacked labels in `chart.label` consist of wbs labels
# (e.g. "WP 3" or "Task 2.4")
chart.label = []
for wbs, task of timeslotValue
chart.label.push wbsLabel wbs
# ######################################################################
# used for monitoring plan and spent efforts on the partners
when "EffortPartner"
chart = {values: [], label: []}
switch groupLevel
when "2"
labelPrefix = "WP"
when "3"
labelPrefix = "Task"
tree = {}
while row = getRow()
# row.key has two parts. The first and second are Year and Quarter
# (or month at one point).
keyPartner = row.key.shift()
# The rest is WBS, the work breakdown structure.
keyWbs = row.key
if taskFilter and keyWbs[0] is taskFilter or not taskFilter
# the treeAddress consists of the timeslot (e.g. "Y2Q4")
# and the keyWbs (e.g. "2.3")
treeAddress = [keyPartner, keyWbs]
# Iterate on the tree to find the right place for the row.
# row.key
leaf = tree
for i, keyEl of treeAddress
leaf[keyEl] = {} unless leaf[keyEl] instanceof Object
leaf = leaf[keyEl]
leaf.value = row.value
# send JSON.stringify tree
# Make dotted label-notation out of the comma-separated one
wbsLabel = (key) ->
"#{labelPrefix} #{key.replace ",", "."}"
# iterate through the tree
# First is the partners
for partnerKey, partnerValue of tree
# A column object has the label of the timeslot
columnPlan =
# column label
label: "#{partnerKey} planned"
values: []
chart.values.push columnPlan
columnSpent =
# column label
label: "#{partnerKey} spent"
values: []
chart.values.push columnSpent
for wbs, task of partnerValue
# column.values are the actual numbers in a column.
columnPlan.values.push task.value.planned
columnSpent.values.push roundNumber task.value.spent, 1
# stacked (row) labels in `chart.label` consist of wbs labels
# (e.g. "WP 3" or "Task 2.4")
chart.label = []
for wbs, task of partnerValue
chart.label.push wbsLabel wbs
# ######################################################################
# used for showing the project performance over the whole period of the
# project.
# The JSON format follows the flot.js plotter data format with
# data = [[x1, y1],[x2,y2]..] instead of just [y1, y2, ...] as it is
# needed for Jit charts.
when "ProjectOverTime"
chart = {values: []}
switch groupLevel
when "3"
labelPrefix = "WP"
when "4"
labelPrefix = "Task"
tree = {}
while row = getRow()
# row.key has two parts. The first and second are Year and Quarter
# (or month at one point).
keyTimeslot = ["PI:KEY:<KEY>END_PIrow.key.PI:KEY:<KEY>END_PIrow.key.PI:KEY:<KEY>END_PI"]
# The rest is WBS, the work breakdown structure.
keyWbs = row.key
if taskFilter and keyWbs[0] is taskFilter or not taskFilter
# the treeAddress consists of the timeslot (e.g. "Y2Q4")
# and the keyWbs (e.g. "2.3")
treeAddress = [keyTimeslot, keyWbs]
# Iterate on the tree to find the right place for the row.
# row.key
leaf = tree
for i, keyEl of treeAddress
leaf[keyEl] = {} unless leaf[keyEl] instanceof Object
leaf = leaf[keyEl]
leaf.value = row.value
# Make dotted label-notation out of the comma-separated one
wbsLabel = (key) ->
"#{labelPrefix} #{key.replace ",", "."}"
chart.values =
xaxis:
ticks: [[0, " "]]
yaxis:
[{
position: "right"
},{
position: "left"
}]
plan: [[0,0]]
spent: [[0,0]]
deliverablePlan: [[0,0]]
deliverableComplete: [[0,0]]
# one tick is a quarter
xtickDays: 365/4
i = 0
# iterate through the tree
# First is the timeslots
for timeslotKey, timeslotValue of tree
i++
chart.values.xaxis.ticks.push [i, timeslotKey]
plan = [i, 0]
chart.values.plan.push plan
spent = [i, 0]
chart.values.spent.push spent
deliverablePlan = [i, 0]
chart.values.deliverablePlan.push deliverablePlan
deliverableComplete = [i, 0]
chart.values.deliverableComplete.push deliverableComplete
for wbs, task of timeslotValue
# column.values are the actual numbers in a column.
plan[1] += task.value.planned
spent[1] += roundNumber task.value.spent, 1
deliverablePlan[1] += task.value.deliverables
deliverableComplete[1] += task.value.completed
# stacked labels in `chart.label` consist of wbs labels
# (e.g. "WP 3" or "Task 2.4")
# chart.label = []
# for wbs, task of timeslotValue
# chart.label.push wbsLabel wbs
getSum = (array) ->
sum = 0
for valArr in array
sum += valArr[1]
sum
accumulate = (array, sum) ->
acc = []
reached = 0
for valArr in array
reached += valArr[1]
acc.push [valArr[0], reached] if valArr[1] or not acc.length
acc
chart.values.plan = accumulate chart.values.plan, getSum chart.values.plan
chart.values.spent = accumulate chart.values.spent, getSum chart.values.plan
chart.values.deliverablePlan =
accumulate chart.values.deliverablePlan, getSum chart.values.deliverablePlan
chart.values.deliverableComplete =
accumulate chart.values.deliverableComplete, getSum chart.values.deliverablePlan
# Send the actual chart object to the client.
send JSON.stringify chart
|
[
{
"context": "###\n@author Martin Wawrusch (martin@wawrusch.com)\n###\n\nHoek = require 'hoek'\n",
"end": 27,
"score": 0.9998791813850403,
"start": 12,
"tag": "NAME",
"value": "Martin Wawrusch"
},
{
"context": "###\n@author Martin Wawrusch (martin@wawrusch.com)\n###\n\nHoek = require 'hoek'\ni18n = require './i18",
"end": 48,
"score": 0.9999284744262695,
"start": 29,
"tag": "EMAIL",
"value": "martin@wawrusch.com"
}
] | src/index.coffee | codedoctor/hapi-routes-oauth-management | 1 | ###
@author Martin Wawrusch (martin@wawrusch.com)
###
Hoek = require 'hoek'
i18n = require './i18n'
###
Main entry point for the plugin
@param [Plugin] plugin the HAPI plugin
@param [Object] options the plugin options
@option options [String|Function] _tenantId the account id to use, or an async function.
@option options [String] baseUrl the url to your API. For example https://api.mystuff.com
@option options [String] routesBaseName the name of the endpoints, defaults to role.
@option options [String] serverAdminScopeName the name of the serverAdmin scope, defaults to serverAdmin.
@param [Function] cb the callback invoked after completion
When passing a function to the _tenantId the signature needs to be as follows:
```coffeescript
fnAccountId = (request,cb) ->
_tenantId = null
# lookup _tenantId here ...
cb null, _tenantId
```
###
routesToExpose = [
require './routes-oauth-apps-get'
require './routes-oauth-apps-oauthappid-delete'
require './routes-oauth-apps-oauthappid-get'
require './routes-oauth-apps-oauthappid-patch'
require './routes-oauth-apps-post'
require './routes-oauth-scopes-get'
require './routes-oauth-scopes-oauthscopeid-delete'
require './routes-oauth-scopes-oauthscopeid-get'
require './routes-oauth-scopes-oauthscopeid-patch'
require './routes-oauth-scopes-post'
]
module.exports.register = (server, options = {}, cb) ->
defaults =
routesAppsBaseName: 'oauth-apps'
routesScopesBaseName: 'oauth-scopes'
serverAdminScopeName: 'server-admin'
routeTagsPublic: ['api','api-public']
routeTagsAdmin: ['api','api-admin']
options = Hoek.applyToDefaults defaults, options
r server,options for r in routesToExpose
server.expose 'i18n',i18n
cb()
###
@nodoc
###
module.exports.register.attributes =
pkg: require '../package.json'
| 10293 | ###
@author <NAME> (<EMAIL>)
###
Hoek = require 'hoek'
i18n = require './i18n'
###
Main entry point for the plugin
@param [Plugin] plugin the HAPI plugin
@param [Object] options the plugin options
@option options [String|Function] _tenantId the account id to use, or an async function.
@option options [String] baseUrl the url to your API. For example https://api.mystuff.com
@option options [String] routesBaseName the name of the endpoints, defaults to role.
@option options [String] serverAdminScopeName the name of the serverAdmin scope, defaults to serverAdmin.
@param [Function] cb the callback invoked after completion
When passing a function to the _tenantId the signature needs to be as follows:
```coffeescript
fnAccountId = (request,cb) ->
_tenantId = null
# lookup _tenantId here ...
cb null, _tenantId
```
###
routesToExpose = [
require './routes-oauth-apps-get'
require './routes-oauth-apps-oauthappid-delete'
require './routes-oauth-apps-oauthappid-get'
require './routes-oauth-apps-oauthappid-patch'
require './routes-oauth-apps-post'
require './routes-oauth-scopes-get'
require './routes-oauth-scopes-oauthscopeid-delete'
require './routes-oauth-scopes-oauthscopeid-get'
require './routes-oauth-scopes-oauthscopeid-patch'
require './routes-oauth-scopes-post'
]
module.exports.register = (server, options = {}, cb) ->
defaults =
routesAppsBaseName: 'oauth-apps'
routesScopesBaseName: 'oauth-scopes'
serverAdminScopeName: 'server-admin'
routeTagsPublic: ['api','api-public']
routeTagsAdmin: ['api','api-admin']
options = Hoek.applyToDefaults defaults, options
r server,options for r in routesToExpose
server.expose 'i18n',i18n
cb()
###
@nodoc
###
module.exports.register.attributes =
pkg: require '../package.json'
| true | ###
@author PI:NAME:<NAME>END_PI (PI:EMAIL:<EMAIL>END_PI)
###
Hoek = require 'hoek'
i18n = require './i18n'
###
Main entry point for the plugin
@param [Plugin] plugin the HAPI plugin
@param [Object] options the plugin options
@option options [String|Function] _tenantId the account id to use, or an async function.
@option options [String] baseUrl the url to your API. For example https://api.mystuff.com
@option options [String] routesBaseName the name of the endpoints, defaults to role.
@option options [String] serverAdminScopeName the name of the serverAdmin scope, defaults to serverAdmin.
@param [Function] cb the callback invoked after completion
When passing a function to the _tenantId the signature needs to be as follows:
```coffeescript
fnAccountId = (request,cb) ->
_tenantId = null
# lookup _tenantId here ...
cb null, _tenantId
```
###
routesToExpose = [
require './routes-oauth-apps-get'
require './routes-oauth-apps-oauthappid-delete'
require './routes-oauth-apps-oauthappid-get'
require './routes-oauth-apps-oauthappid-patch'
require './routes-oauth-apps-post'
require './routes-oauth-scopes-get'
require './routes-oauth-scopes-oauthscopeid-delete'
require './routes-oauth-scopes-oauthscopeid-get'
require './routes-oauth-scopes-oauthscopeid-patch'
require './routes-oauth-scopes-post'
]
module.exports.register = (server, options = {}, cb) ->
defaults =
routesAppsBaseName: 'oauth-apps'
routesScopesBaseName: 'oauth-scopes'
serverAdminScopeName: 'server-admin'
routeTagsPublic: ['api','api-public']
routeTagsAdmin: ['api','api-admin']
options = Hoek.applyToDefaults defaults, options
r server,options for r in routesToExpose
server.expose 'i18n',i18n
cb()
###
@nodoc
###
module.exports.register.attributes =
pkg: require '../package.json'
|
[
{
"context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public Li",
"end": 43,
"score": 0.9999130368232727,
"start": 29,
"tag": "EMAIL",
"value": "contact@ppy.sh"
}
] | resources/assets/coffee/react/contest-entry/uploader.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, form, input, i } from 'react-dom-factories'
el = React.createElement
export class Uploader extends React.Component
constructor: (props) ->
super props
@state =
state: ''
setOverlay: (state) ->
return if @props.disabled
@setState state: state
componentDidMount: =>
switch @props.contest.type
when 'art'
allowedExtensions = ['.jpg', '.jpeg', '.png']
maxSize = 4000000
when 'beatmap'
allowedExtensions = ['.osu', '.osz']
maxSize = 20000000
when 'music'
allowedExtensions = ['.mp3']
maxSize = 15000000
$dropzone = $('.js-contest-entry-upload--dropzone')
$uploadButton = $ '<input>',
class: 'js-contest-entry-upload fileupload__input'
type: 'file'
name: 'entry'
accept: allowedExtensions.join(',')
disabled: @props.disabled
$(@uploadButtonContainer).append($uploadButton)
$.subscribe 'dragenterGlobal.contest-upload', => @setOverlay('active')
$.subscribe 'dragendGlobal.contest-upload', => @setOverlay('hidden')
$(document).on 'dragenter.contest-upload', '.contest-userentry--uploader', => @setOverlay('hover')
$(document).on 'dragleave.contest-upload', '.contest-userentry--uploader', => @setOverlay('active')
@$uploadButton().fileupload
url: laroute.route 'contest-entries.store'
dataType: 'json'
dropZone: $dropzone
sequentialUploads: true
formData:
contest_id: @props.contest.id
add: (e, data) =>
return if @props.disabled
file = data.files[0]
extension = /(\.[^.]+)$/.exec(file.name)[1]
if !_.includes(allowedExtensions, extension)
osu.popup osu.trans("contest.entry.wrong_type.#{@props.contest.type}"), 'danger'
return
if file.size > maxSize
osu.popup osu.trans('contest.entry.too_big', limit: osu.formatBytes(maxSize, 0)), 'danger'
return
data.submit()
submit: ->
$.publish 'dragendGlobal'
done: (_e, data) ->
$.publish 'contest:entries:update', data: data.result
fail: osu.fileuploadFailCallback(@$uploadButton)
componentWillUnmount: =>
$.unsubscribe '.contest-upload'
$(document).off '.contest-upload'
@$uploadButton()
.fileupload 'destroy'
.remove()
render: =>
labelClass = [
'fileupload',
'contest-userentry',
'contest-userentry--uploader',
'disabled' if @props.disabled,
'contest-userentry--dragndrop-active' if @state.state == 'active',
'contest-userentry--dragndrop-hover' if @state.state == 'hover',
]
div className: "contest-userentry contest-userentry--new#{if @props.disabled then ' contest-userentry--disabled' else ''}",
div className: 'js-contest-entry-upload--dropzone',
el 'label',
className: labelClass.join(' ')
ref: (el) => @uploadButtonContainer = el
i className: 'fas fa-plus contest-userentry__icon'
div {}, osu.trans('contest.entry.drop_here')
$uploadButton: =>
$(@uploadButtonContainer).find('.js-contest-entry-upload')
| 162571 | # 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, form, input, i } from 'react-dom-factories'
el = React.createElement
export class Uploader extends React.Component
constructor: (props) ->
super props
@state =
state: ''
setOverlay: (state) ->
return if @props.disabled
@setState state: state
componentDidMount: =>
switch @props.contest.type
when 'art'
allowedExtensions = ['.jpg', '.jpeg', '.png']
maxSize = 4000000
when 'beatmap'
allowedExtensions = ['.osu', '.osz']
maxSize = 20000000
when 'music'
allowedExtensions = ['.mp3']
maxSize = 15000000
$dropzone = $('.js-contest-entry-upload--dropzone')
$uploadButton = $ '<input>',
class: 'js-contest-entry-upload fileupload__input'
type: 'file'
name: 'entry'
accept: allowedExtensions.join(',')
disabled: @props.disabled
$(@uploadButtonContainer).append($uploadButton)
$.subscribe 'dragenterGlobal.contest-upload', => @setOverlay('active')
$.subscribe 'dragendGlobal.contest-upload', => @setOverlay('hidden')
$(document).on 'dragenter.contest-upload', '.contest-userentry--uploader', => @setOverlay('hover')
$(document).on 'dragleave.contest-upload', '.contest-userentry--uploader', => @setOverlay('active')
@$uploadButton().fileupload
url: laroute.route 'contest-entries.store'
dataType: 'json'
dropZone: $dropzone
sequentialUploads: true
formData:
contest_id: @props.contest.id
add: (e, data) =>
return if @props.disabled
file = data.files[0]
extension = /(\.[^.]+)$/.exec(file.name)[1]
if !_.includes(allowedExtensions, extension)
osu.popup osu.trans("contest.entry.wrong_type.#{@props.contest.type}"), 'danger'
return
if file.size > maxSize
osu.popup osu.trans('contest.entry.too_big', limit: osu.formatBytes(maxSize, 0)), 'danger'
return
data.submit()
submit: ->
$.publish 'dragendGlobal'
done: (_e, data) ->
$.publish 'contest:entries:update', data: data.result
fail: osu.fileuploadFailCallback(@$uploadButton)
componentWillUnmount: =>
$.unsubscribe '.contest-upload'
$(document).off '.contest-upload'
@$uploadButton()
.fileupload 'destroy'
.remove()
render: =>
labelClass = [
'fileupload',
'contest-userentry',
'contest-userentry--uploader',
'disabled' if @props.disabled,
'contest-userentry--dragndrop-active' if @state.state == 'active',
'contest-userentry--dragndrop-hover' if @state.state == 'hover',
]
div className: "contest-userentry contest-userentry--new#{if @props.disabled then ' contest-userentry--disabled' else ''}",
div className: 'js-contest-entry-upload--dropzone',
el 'label',
className: labelClass.join(' ')
ref: (el) => @uploadButtonContainer = el
i className: 'fas fa-plus contest-userentry__icon'
div {}, osu.trans('contest.entry.drop_here')
$uploadButton: =>
$(@uploadButtonContainer).find('.js-contest-entry-upload')
| 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, form, input, i } from 'react-dom-factories'
el = React.createElement
export class Uploader extends React.Component
constructor: (props) ->
super props
@state =
state: ''
setOverlay: (state) ->
return if @props.disabled
@setState state: state
componentDidMount: =>
switch @props.contest.type
when 'art'
allowedExtensions = ['.jpg', '.jpeg', '.png']
maxSize = 4000000
when 'beatmap'
allowedExtensions = ['.osu', '.osz']
maxSize = 20000000
when 'music'
allowedExtensions = ['.mp3']
maxSize = 15000000
$dropzone = $('.js-contest-entry-upload--dropzone')
$uploadButton = $ '<input>',
class: 'js-contest-entry-upload fileupload__input'
type: 'file'
name: 'entry'
accept: allowedExtensions.join(',')
disabled: @props.disabled
$(@uploadButtonContainer).append($uploadButton)
$.subscribe 'dragenterGlobal.contest-upload', => @setOverlay('active')
$.subscribe 'dragendGlobal.contest-upload', => @setOverlay('hidden')
$(document).on 'dragenter.contest-upload', '.contest-userentry--uploader', => @setOverlay('hover')
$(document).on 'dragleave.contest-upload', '.contest-userentry--uploader', => @setOverlay('active')
@$uploadButton().fileupload
url: laroute.route 'contest-entries.store'
dataType: 'json'
dropZone: $dropzone
sequentialUploads: true
formData:
contest_id: @props.contest.id
add: (e, data) =>
return if @props.disabled
file = data.files[0]
extension = /(\.[^.]+)$/.exec(file.name)[1]
if !_.includes(allowedExtensions, extension)
osu.popup osu.trans("contest.entry.wrong_type.#{@props.contest.type}"), 'danger'
return
if file.size > maxSize
osu.popup osu.trans('contest.entry.too_big', limit: osu.formatBytes(maxSize, 0)), 'danger'
return
data.submit()
submit: ->
$.publish 'dragendGlobal'
done: (_e, data) ->
$.publish 'contest:entries:update', data: data.result
fail: osu.fileuploadFailCallback(@$uploadButton)
componentWillUnmount: =>
$.unsubscribe '.contest-upload'
$(document).off '.contest-upload'
@$uploadButton()
.fileupload 'destroy'
.remove()
render: =>
labelClass = [
'fileupload',
'contest-userentry',
'contest-userentry--uploader',
'disabled' if @props.disabled,
'contest-userentry--dragndrop-active' if @state.state == 'active',
'contest-userentry--dragndrop-hover' if @state.state == 'hover',
]
div className: "contest-userentry contest-userentry--new#{if @props.disabled then ' contest-userentry--disabled' else ''}",
div className: 'js-contest-entry-upload--dropzone',
el 'label',
className: labelClass.join(' ')
ref: (el) => @uploadButtonContainer = el
i className: 'fas fa-plus contest-userentry__icon'
div {}, osu.trans('contest.entry.drop_here')
$uploadButton: =>
$(@uploadButtonContainer).find('.js-contest-entry-upload')
|
[
{
"context": ":32 UTC 2015\"\ndate_output = \"#{date}\\n\"\n\nemail = \"user@example.com\"\noscrc_file = \"email = #{email}\"\n\n# helpers to sp",
"end": 659,
"score": 0.9999105334281921,
"start": 643,
"tag": "EMAIL",
"value": "user@example.com"
},
{
"context": "c file does not contain an email\", ->\n user = \"tester\"\n domain = \"example.com\"\n domain_output = \"",
"end": 2054,
"score": 0.9989878535270691,
"start": 2048,
"tag": "USERNAME",
"value": "tester"
},
{
"context": "mise\n\n afterEach ->\n process.env[\"USER\"] = @originalUser\n\n it \"uses the current user and the machine do",
"end": 2771,
"score": 0.9447400569915771,
"start": 2758,
"tag": "USERNAME",
"value": "@originalUser"
},
{
"context": "eader) ->\n expect(header_includes(header, \"tester@example.com\")).toBe(true)\n\n describe \"when the domain cannot",
"end": 2937,
"score": 0.9998766183853149,
"start": 2919,
"tag": "EMAIL",
"value": "tester@example.com"
},
{
"context": "en the domain cannot be obtained\", ->\n user = \"tester\"\n\n beforeEach ->\n @originalUser = process",
"end": 3023,
"score": 0.9990550875663757,
"start": 3017,
"tag": "USERNAME",
"value": "tester"
},
{
"context": "mise\n\n afterEach ->\n process.env[\"USER\"] = @originalUser\n\n it \"uses the 'localhost' fallback \", ->\n ",
"end": 3693,
"score": 0.7498390078544617,
"start": 3680,
"tag": "USERNAME",
"value": "@originalUser"
}
] | spec/changelog-entry-spec.coffee | lslezak/language-changes | 0 |
ChangelogEntry = require("../lib/changelog-entry")
child_process = require('child_process')
fs = require('fs')
# the provided waitsForPromise helper fails when the promise is resolved to a failure
# this is a complement helper for failed promises
# see https://goo.gl/VtFGVn
waitsForFailedPromise = (fn) ->
promise = fn()
waitsFor 'spec promise to resolve', 30000, (done) ->
promise.then(
(success) ->
jasmine.getEnv().currentSpec.fail("Expected promise to fail, but succeeded with: " + success)
done()
done
)
# mocked values
date = "Tue Dec 8 08:32:32 UTC 2015"
date_output = "#{date}\n"
email = "user@example.com"
oscrc_file = "email = #{email}"
# helpers to split the header line
separator = (header) ->
header.split("\n")[0]
authored = (header) ->
header.split("\n")[1]
header_includes = (header, data) ->
authored(header).indexOf(data) > -1
describe "Add a new changelog entry", ->
header_promise = null
describe "when .oscrc contains an email and the date command succeeds", ->
beforeEach ->
# read the date
spyOn(child_process, 'exec').andCallFake ->
child_process.exec.mostRecentCall.args[1](null, date_output, "")
# read the email from .oscrc
spyOn(fs, 'readFile').andCallFake ->
fs.readFile.mostRecentCall.args[2](null, oscrc_file)
header_promise = (new ChangelogEntry).header()
waitsForPromise -> header_promise
it "returns a defined value", ->
header_promise.then (header) ->
expect(header).not.toBeNull()
expect(header).toBeDefined()
it "contains a dash separator", ->
header_promise.then (header) ->
expect(separator(header)).toMatch(/^-{67}$/)
it "contains a date", ->
header_promise.then (header) ->
expect(header_includes(header, date)).toBe(true)
it "contains an email", ->
header_promise.then (header) ->
expect(header_includes(header, email)).toBe(true)
describe "when .oscrc file does not contain an email", ->
user = "tester"
domain = "example.com"
domain_output = "#{domain}\n"
beforeEach ->
@originalUser = process.env["USER"]
process.env["USER"] = user
spyOn(fs, 'readFile').andCallFake ->
fs.readFile.mostRecentCall.args[2](null, "")
spyOn(child_process, 'exec').andCallFake ->
args = child_process.exec.mostRecentCall.args
if args[0] is "dnsdomainname"
# fake dnsdomainname call
args[1](null, domain_output, "")
else
# fake date call
args[1](null, date_output, "")
header_promise = (new ChangelogEntry).header()
waitsForPromise ->
header_promise
afterEach ->
process.env["USER"] = @originalUser
it "uses the current user and the machine domain for email", ->
header_promise.then (header) ->
expect(header_includes(header, "tester@example.com")).toBe(true)
describe "when the domain cannot be obtained", ->
user = "tester"
beforeEach ->
@originalUser = process.env["USER"]
process.env["USER"] = user
spyOn(fs, 'readFile').andCallFake ->
fs.readFile.mostRecentCall.args[2](null, "")
spyOn(child_process, 'exec').andCallFake ->
args = child_process.exec.mostRecentCall.args
if args[0] is "dnsdomainname"
# fake dnsdomainname fail
args[1]("error: dnsdomainname failed", "", "")
else
# fake date call
args[1](null, date_output, "")
header_promise = (new ChangelogEntry).header()
waitsForPromise ->
header_promise
afterEach ->
process.env["USER"] = @originalUser
it "uses the 'localhost' fallback ", ->
header_promise.then (header) ->
expect(header_includes(header, "tester@localhost")).toBe(true)
describe "when the date command fails", ->
date_error = "date: command not found"
beforeEach ->
# read the date
spyOn(child_process, 'exec').andCallFake ->
child_process.exec.mostRecentCall.args[1](date_error, "", "")
# read the email from .oscrc
spyOn(fs, 'readFile').andCallFake ->
fs.readFile.mostRecentCall.args[2](null, oscrc_file)
header_promise = (new ChangelogEntry).header()
waitsForFailedPromise -> header_promise
it "resolves to an error", ->
header_promise.catch (error) ->
expect(error).toEqual(date_error)
| 76158 |
ChangelogEntry = require("../lib/changelog-entry")
child_process = require('child_process')
fs = require('fs')
# the provided waitsForPromise helper fails when the promise is resolved to a failure
# this is a complement helper for failed promises
# see https://goo.gl/VtFGVn
waitsForFailedPromise = (fn) ->
promise = fn()
waitsFor 'spec promise to resolve', 30000, (done) ->
promise.then(
(success) ->
jasmine.getEnv().currentSpec.fail("Expected promise to fail, but succeeded with: " + success)
done()
done
)
# mocked values
date = "Tue Dec 8 08:32:32 UTC 2015"
date_output = "#{date}\n"
email = "<EMAIL>"
oscrc_file = "email = #{email}"
# helpers to split the header line
separator = (header) ->
header.split("\n")[0]
authored = (header) ->
header.split("\n")[1]
header_includes = (header, data) ->
authored(header).indexOf(data) > -1
describe "Add a new changelog entry", ->
header_promise = null
describe "when .oscrc contains an email and the date command succeeds", ->
beforeEach ->
# read the date
spyOn(child_process, 'exec').andCallFake ->
child_process.exec.mostRecentCall.args[1](null, date_output, "")
# read the email from .oscrc
spyOn(fs, 'readFile').andCallFake ->
fs.readFile.mostRecentCall.args[2](null, oscrc_file)
header_promise = (new ChangelogEntry).header()
waitsForPromise -> header_promise
it "returns a defined value", ->
header_promise.then (header) ->
expect(header).not.toBeNull()
expect(header).toBeDefined()
it "contains a dash separator", ->
header_promise.then (header) ->
expect(separator(header)).toMatch(/^-{67}$/)
it "contains a date", ->
header_promise.then (header) ->
expect(header_includes(header, date)).toBe(true)
it "contains an email", ->
header_promise.then (header) ->
expect(header_includes(header, email)).toBe(true)
describe "when .oscrc file does not contain an email", ->
user = "tester"
domain = "example.com"
domain_output = "#{domain}\n"
beforeEach ->
@originalUser = process.env["USER"]
process.env["USER"] = user
spyOn(fs, 'readFile').andCallFake ->
fs.readFile.mostRecentCall.args[2](null, "")
spyOn(child_process, 'exec').andCallFake ->
args = child_process.exec.mostRecentCall.args
if args[0] is "dnsdomainname"
# fake dnsdomainname call
args[1](null, domain_output, "")
else
# fake date call
args[1](null, date_output, "")
header_promise = (new ChangelogEntry).header()
waitsForPromise ->
header_promise
afterEach ->
process.env["USER"] = @originalUser
it "uses the current user and the machine domain for email", ->
header_promise.then (header) ->
expect(header_includes(header, "<EMAIL>")).toBe(true)
describe "when the domain cannot be obtained", ->
user = "tester"
beforeEach ->
@originalUser = process.env["USER"]
process.env["USER"] = user
spyOn(fs, 'readFile').andCallFake ->
fs.readFile.mostRecentCall.args[2](null, "")
spyOn(child_process, 'exec').andCallFake ->
args = child_process.exec.mostRecentCall.args
if args[0] is "dnsdomainname"
# fake dnsdomainname fail
args[1]("error: dnsdomainname failed", "", "")
else
# fake date call
args[1](null, date_output, "")
header_promise = (new ChangelogEntry).header()
waitsForPromise ->
header_promise
afterEach ->
process.env["USER"] = @originalUser
it "uses the 'localhost' fallback ", ->
header_promise.then (header) ->
expect(header_includes(header, "tester@localhost")).toBe(true)
describe "when the date command fails", ->
date_error = "date: command not found"
beforeEach ->
# read the date
spyOn(child_process, 'exec').andCallFake ->
child_process.exec.mostRecentCall.args[1](date_error, "", "")
# read the email from .oscrc
spyOn(fs, 'readFile').andCallFake ->
fs.readFile.mostRecentCall.args[2](null, oscrc_file)
header_promise = (new ChangelogEntry).header()
waitsForFailedPromise -> header_promise
it "resolves to an error", ->
header_promise.catch (error) ->
expect(error).toEqual(date_error)
| true |
ChangelogEntry = require("../lib/changelog-entry")
child_process = require('child_process')
fs = require('fs')
# the provided waitsForPromise helper fails when the promise is resolved to a failure
# this is a complement helper for failed promises
# see https://goo.gl/VtFGVn
waitsForFailedPromise = (fn) ->
promise = fn()
waitsFor 'spec promise to resolve', 30000, (done) ->
promise.then(
(success) ->
jasmine.getEnv().currentSpec.fail("Expected promise to fail, but succeeded with: " + success)
done()
done
)
# mocked values
date = "Tue Dec 8 08:32:32 UTC 2015"
date_output = "#{date}\n"
email = "PI:EMAIL:<EMAIL>END_PI"
oscrc_file = "email = #{email}"
# helpers to split the header line
separator = (header) ->
header.split("\n")[0]
authored = (header) ->
header.split("\n")[1]
header_includes = (header, data) ->
authored(header).indexOf(data) > -1
describe "Add a new changelog entry", ->
header_promise = null
describe "when .oscrc contains an email and the date command succeeds", ->
beforeEach ->
# read the date
spyOn(child_process, 'exec').andCallFake ->
child_process.exec.mostRecentCall.args[1](null, date_output, "")
# read the email from .oscrc
spyOn(fs, 'readFile').andCallFake ->
fs.readFile.mostRecentCall.args[2](null, oscrc_file)
header_promise = (new ChangelogEntry).header()
waitsForPromise -> header_promise
it "returns a defined value", ->
header_promise.then (header) ->
expect(header).not.toBeNull()
expect(header).toBeDefined()
it "contains a dash separator", ->
header_promise.then (header) ->
expect(separator(header)).toMatch(/^-{67}$/)
it "contains a date", ->
header_promise.then (header) ->
expect(header_includes(header, date)).toBe(true)
it "contains an email", ->
header_promise.then (header) ->
expect(header_includes(header, email)).toBe(true)
describe "when .oscrc file does not contain an email", ->
user = "tester"
domain = "example.com"
domain_output = "#{domain}\n"
beforeEach ->
@originalUser = process.env["USER"]
process.env["USER"] = user
spyOn(fs, 'readFile').andCallFake ->
fs.readFile.mostRecentCall.args[2](null, "")
spyOn(child_process, 'exec').andCallFake ->
args = child_process.exec.mostRecentCall.args
if args[0] is "dnsdomainname"
# fake dnsdomainname call
args[1](null, domain_output, "")
else
# fake date call
args[1](null, date_output, "")
header_promise = (new ChangelogEntry).header()
waitsForPromise ->
header_promise
afterEach ->
process.env["USER"] = @originalUser
it "uses the current user and the machine domain for email", ->
header_promise.then (header) ->
expect(header_includes(header, "PI:EMAIL:<EMAIL>END_PI")).toBe(true)
describe "when the domain cannot be obtained", ->
user = "tester"
beforeEach ->
@originalUser = process.env["USER"]
process.env["USER"] = user
spyOn(fs, 'readFile').andCallFake ->
fs.readFile.mostRecentCall.args[2](null, "")
spyOn(child_process, 'exec').andCallFake ->
args = child_process.exec.mostRecentCall.args
if args[0] is "dnsdomainname"
# fake dnsdomainname fail
args[1]("error: dnsdomainname failed", "", "")
else
# fake date call
args[1](null, date_output, "")
header_promise = (new ChangelogEntry).header()
waitsForPromise ->
header_promise
afterEach ->
process.env["USER"] = @originalUser
it "uses the 'localhost' fallback ", ->
header_promise.then (header) ->
expect(header_includes(header, "tester@localhost")).toBe(true)
describe "when the date command fails", ->
date_error = "date: command not found"
beforeEach ->
# read the date
spyOn(child_process, 'exec').andCallFake ->
child_process.exec.mostRecentCall.args[1](date_error, "", "")
# read the email from .oscrc
spyOn(fs, 'readFile').andCallFake ->
fs.readFile.mostRecentCall.args[2](null, oscrc_file)
header_promise = (new ChangelogEntry).header()
waitsForFailedPromise -> header_promise
it "resolves to an error", ->
header_promise.catch (error) ->
expect(error).toEqual(date_error)
|
[
{
"context": "l: user.emailAddresses[0].address,\n name: user.name,\n role: request.session.passport.member.",
"end": 788,
"score": 0.9585224986076355,
"start": 779,
"tag": "NAME",
"value": "user.name"
}
] | app/controllers/data_controller.coffee | HoistRnD/data.hoi.io | 0 |
hoist = require 'hoist-core'
Model= hoist.data.Model
throat = require 'throat'
User=hoist.models.User
DataRuleCollection=hoist.models.DataRuleCollection
ruleRunner=hoist.data.ruleRunner
errors=require '../platform/errors'
_=require 'underscore'
q=hoist.q
class DataController
getCurrentUser:(request) ->
#no user logged in
return q.fcall(()->) unless (request.session &&
request.session.passport &&
request.session.passport.member)
return q.fcall(()->
return User.findByIdQ(request.session.passport.member.userId)
.then((user) ->
hoist.logger.debug 'there is a current user', JSON.stringify(user)
return {
_id: request.session.passport.member._id,
email: user.emailAddresses[0].address,
name: user.name,
role: request.session.passport.member.defaultRole
}))
runDataRules:(request,allDataRules) =>
#return an array of touples (entity and rule ids to apply)
rulesToRun = _.map(request.boundData.entities,(entity) ->
return {
entity:entity,
rules:_.chain(allDataRules.runLists)
#find run list for this entity or for all entities
.filter((runList) ->
return (
runList.model.toLowerCase() == entity._type.toLowerCase() ||
runList.model.toLowerCase() == 'all')
)
#apply the update rules
.map((runList) -> return runList.onUpdate)
.flatten().value()
})
loadUser = @getCurrentUser(request)
rulesRunFuncs = _.map(rulesToRun,(ruleToRun)=>
hoist.logger.debug 'running rules'
@validateEntity(request,loadUser,ruleToRun,allDataRules.rules))
return q.allSettled(rulesRunFuncs)
loadExistingEntity:(request,entity) ->
#no entity id so can't load anything existing
return q.fcall(()->) if !entity._id
return request.dataStore.get(entity._type, entity._id)
validateEntity:(request,loadUser,ruleListToRun,allRules) =>
#no rules to run so pass
return q.fcall(()->) if !ruleListToRun.rules
return q.fcall(()->) if ruleListToRun.rules.length<1
return q.all([@loadExistingEntity(request,ruleListToRun.entity),loadUser])
.spread((existingEntity,user)->
return q.all(_.chain(allRules)
.filter((rule) ->
#only run enabled rules and those listed to run against this entity
return rule.enabled &&_.some(ruleListToRun.rules, (id) ->
return id.equals(rule._id)
)
)
#run them in the order specified
.sortBy((rule) -> return rule.order)
.map(throat 2, (rule) ->
#run the rule
ruleFn = "function(model,existing,user){" + rule.rule + "}"
u = 'none'
if(user)
u = JSON.stringify(user)
hoist.logger.debug('running rule',rule.name,ruleFn,u)
return ruleRunner.run(
ruleFn, ruleListToRun.entity, existingEntity, user
)
.then((result) ->
if (!result)
error = new Error()
error.rule = rule.name
error.entity = JSON.stringify(ruleListToRun.entity)
throw error
)
).value())
)
applyDataRules:(request) =>
#if no data rules return nothing
application = request.application
environment = request.environment
return q.fcall(()->) if !environment.dataRules
return DataRuleCollection
.findByIdQ(environment.dataRules)
.then((dataRulesCollection)=>@runDataRules(request,dataRulesCollection))
checkValidationResults:(validationResults) ->
validationResults = validationResults || []
failedChecks = _.filter(validationResults, (validationResult) ->
return validationResult.state == 'rejected';
)
if (failedChecks && failedChecks.length > 0)
error = new errors.Data.RulesFailed("One or more data rules failed")
error.failures = _.chain(failedChecks).map((check) ->
return {
rule: check.reason.rule,
entity: check.reason.entity
})
.flatten().value()
throw error
saveEntities:(req) ->
return q.allSettled(
_.map(req.boundData.entities,(entity) ->
return req.dataStore.save(entity)
))
.then((results)->
return _.chain(results).map((result)->
return result.value
).flatten().value()
)
ping: (req, res) ->
res.send({
ok: true,
node: process.env.NODE_NAME,
port: process.env.PORT
})
post: (req, res) =>
member = req.session.passport.member
bucket = req.session.passport.bucket
environment = req.environment
application = req.application
hoist.auth.helpers.data.canWrite(member,environment,bucket)
.then (allowed) =>
throw new errors.request.Forbidden("User doesn't have permissions to write data") if !allowed
return @applyDataRules(req)
.then (results) =>
return @checkValidationResults(results)
.then () =>
return @saveEntities(req)
.then (savedEntities) ->
saveSuccessful = _.every(savedEntities,(entity)->return entity._saved)
statusCode = 200
statusCode = 403 if !saveSuccessful
if(savedEntities.length==1)
savedEntities = savedEntities[0]
res.send(statusCode,savedEntities)
.catch (err) ->
if (!err.resCode)
hoist.error(err, req, req.application)
err = new errors.server.ServerError()
response = {
message:err.message
}
if err.failures
response.failures = err.failures
res.send(err.resCode || 500, response)
.done()
get: (req, res) ->
member = req.session.passport.member
bucket = req.session.passport.bucket
environment = req.environment
hoist.auth.helpers.data.canRead(member,environment,bucket)
.then (allowed) ->
throw new errors.request.Forbidden("User doesn't have permissions to read data") if !allowed
query = {}
if(req.query.skip)
query.skip = req.query.skip
if(req.query.limit)
query.limit = req.query.limit
if(req.query.q)
query.q = JSON.parse(req.query.q)
if(req.query.sort)
query.sort = JSON.parse(req.query.sort)
return req.dataStore.get(req.dataParams._type,req.dataParams._id,query)
.then (entity) ->
if !entity
throw new errors.request.NotFound("Data item doesn't exist")
return
res.send(200,entity)
.catch (err) ->
if (!err.resCode)
hoist.error(err, req, req.application)
err = new errors.server.ServerError()
res.send(err.resCode || 500, err.message)
.done()
delete: (req, res) ->
member = req.session.passport.member
bucket = req.session.passport.bucket
environment = req.environment
application = req.application
hoist.auth.helpers.data.canDelete(member,environment,bucket)
.then (allowed) ->
throw new errors.request.Forbidden("User doesn't have permissions to delete data") if !allowed
req.dataStore.delete(req.dataParams._type, req.dataParams._id)
.then((numberOfRemovedDocs)->
if(numberOfRemovedDocs.length&&numberOfRemovedDocs.length>1)
numberOfRemovedDocs = numberOfRemovedDocs[0];
res.send({status:"ok",removed:numberOfRemovedDocs})
)
.catch((err) ->
if (!err.resCode)
hoist.error(err, req, req.application)
err = new errors.server.ServerError()
res.send(err.resCode || 500, err.message)
).done()
module.exports = new DataController()
| 112890 |
hoist = require 'hoist-core'
Model= hoist.data.Model
throat = require 'throat'
User=hoist.models.User
DataRuleCollection=hoist.models.DataRuleCollection
ruleRunner=hoist.data.ruleRunner
errors=require '../platform/errors'
_=require 'underscore'
q=hoist.q
class DataController
getCurrentUser:(request) ->
#no user logged in
return q.fcall(()->) unless (request.session &&
request.session.passport &&
request.session.passport.member)
return q.fcall(()->
return User.findByIdQ(request.session.passport.member.userId)
.then((user) ->
hoist.logger.debug 'there is a current user', JSON.stringify(user)
return {
_id: request.session.passport.member._id,
email: user.emailAddresses[0].address,
name: <NAME>,
role: request.session.passport.member.defaultRole
}))
runDataRules:(request,allDataRules) =>
#return an array of touples (entity and rule ids to apply)
rulesToRun = _.map(request.boundData.entities,(entity) ->
return {
entity:entity,
rules:_.chain(allDataRules.runLists)
#find run list for this entity or for all entities
.filter((runList) ->
return (
runList.model.toLowerCase() == entity._type.toLowerCase() ||
runList.model.toLowerCase() == 'all')
)
#apply the update rules
.map((runList) -> return runList.onUpdate)
.flatten().value()
})
loadUser = @getCurrentUser(request)
rulesRunFuncs = _.map(rulesToRun,(ruleToRun)=>
hoist.logger.debug 'running rules'
@validateEntity(request,loadUser,ruleToRun,allDataRules.rules))
return q.allSettled(rulesRunFuncs)
loadExistingEntity:(request,entity) ->
#no entity id so can't load anything existing
return q.fcall(()->) if !entity._id
return request.dataStore.get(entity._type, entity._id)
validateEntity:(request,loadUser,ruleListToRun,allRules) =>
#no rules to run so pass
return q.fcall(()->) if !ruleListToRun.rules
return q.fcall(()->) if ruleListToRun.rules.length<1
return q.all([@loadExistingEntity(request,ruleListToRun.entity),loadUser])
.spread((existingEntity,user)->
return q.all(_.chain(allRules)
.filter((rule) ->
#only run enabled rules and those listed to run against this entity
return rule.enabled &&_.some(ruleListToRun.rules, (id) ->
return id.equals(rule._id)
)
)
#run them in the order specified
.sortBy((rule) -> return rule.order)
.map(throat 2, (rule) ->
#run the rule
ruleFn = "function(model,existing,user){" + rule.rule + "}"
u = 'none'
if(user)
u = JSON.stringify(user)
hoist.logger.debug('running rule',rule.name,ruleFn,u)
return ruleRunner.run(
ruleFn, ruleListToRun.entity, existingEntity, user
)
.then((result) ->
if (!result)
error = new Error()
error.rule = rule.name
error.entity = JSON.stringify(ruleListToRun.entity)
throw error
)
).value())
)
applyDataRules:(request) =>
#if no data rules return nothing
application = request.application
environment = request.environment
return q.fcall(()->) if !environment.dataRules
return DataRuleCollection
.findByIdQ(environment.dataRules)
.then((dataRulesCollection)=>@runDataRules(request,dataRulesCollection))
checkValidationResults:(validationResults) ->
validationResults = validationResults || []
failedChecks = _.filter(validationResults, (validationResult) ->
return validationResult.state == 'rejected';
)
if (failedChecks && failedChecks.length > 0)
error = new errors.Data.RulesFailed("One or more data rules failed")
error.failures = _.chain(failedChecks).map((check) ->
return {
rule: check.reason.rule,
entity: check.reason.entity
})
.flatten().value()
throw error
saveEntities:(req) ->
return q.allSettled(
_.map(req.boundData.entities,(entity) ->
return req.dataStore.save(entity)
))
.then((results)->
return _.chain(results).map((result)->
return result.value
).flatten().value()
)
ping: (req, res) ->
res.send({
ok: true,
node: process.env.NODE_NAME,
port: process.env.PORT
})
post: (req, res) =>
member = req.session.passport.member
bucket = req.session.passport.bucket
environment = req.environment
application = req.application
hoist.auth.helpers.data.canWrite(member,environment,bucket)
.then (allowed) =>
throw new errors.request.Forbidden("User doesn't have permissions to write data") if !allowed
return @applyDataRules(req)
.then (results) =>
return @checkValidationResults(results)
.then () =>
return @saveEntities(req)
.then (savedEntities) ->
saveSuccessful = _.every(savedEntities,(entity)->return entity._saved)
statusCode = 200
statusCode = 403 if !saveSuccessful
if(savedEntities.length==1)
savedEntities = savedEntities[0]
res.send(statusCode,savedEntities)
.catch (err) ->
if (!err.resCode)
hoist.error(err, req, req.application)
err = new errors.server.ServerError()
response = {
message:err.message
}
if err.failures
response.failures = err.failures
res.send(err.resCode || 500, response)
.done()
get: (req, res) ->
member = req.session.passport.member
bucket = req.session.passport.bucket
environment = req.environment
hoist.auth.helpers.data.canRead(member,environment,bucket)
.then (allowed) ->
throw new errors.request.Forbidden("User doesn't have permissions to read data") if !allowed
query = {}
if(req.query.skip)
query.skip = req.query.skip
if(req.query.limit)
query.limit = req.query.limit
if(req.query.q)
query.q = JSON.parse(req.query.q)
if(req.query.sort)
query.sort = JSON.parse(req.query.sort)
return req.dataStore.get(req.dataParams._type,req.dataParams._id,query)
.then (entity) ->
if !entity
throw new errors.request.NotFound("Data item doesn't exist")
return
res.send(200,entity)
.catch (err) ->
if (!err.resCode)
hoist.error(err, req, req.application)
err = new errors.server.ServerError()
res.send(err.resCode || 500, err.message)
.done()
delete: (req, res) ->
member = req.session.passport.member
bucket = req.session.passport.bucket
environment = req.environment
application = req.application
hoist.auth.helpers.data.canDelete(member,environment,bucket)
.then (allowed) ->
throw new errors.request.Forbidden("User doesn't have permissions to delete data") if !allowed
req.dataStore.delete(req.dataParams._type, req.dataParams._id)
.then((numberOfRemovedDocs)->
if(numberOfRemovedDocs.length&&numberOfRemovedDocs.length>1)
numberOfRemovedDocs = numberOfRemovedDocs[0];
res.send({status:"ok",removed:numberOfRemovedDocs})
)
.catch((err) ->
if (!err.resCode)
hoist.error(err, req, req.application)
err = new errors.server.ServerError()
res.send(err.resCode || 500, err.message)
).done()
module.exports = new DataController()
| true |
hoist = require 'hoist-core'
Model= hoist.data.Model
throat = require 'throat'
User=hoist.models.User
DataRuleCollection=hoist.models.DataRuleCollection
ruleRunner=hoist.data.ruleRunner
errors=require '../platform/errors'
_=require 'underscore'
q=hoist.q
class DataController
getCurrentUser:(request) ->
#no user logged in
return q.fcall(()->) unless (request.session &&
request.session.passport &&
request.session.passport.member)
return q.fcall(()->
return User.findByIdQ(request.session.passport.member.userId)
.then((user) ->
hoist.logger.debug 'there is a current user', JSON.stringify(user)
return {
_id: request.session.passport.member._id,
email: user.emailAddresses[0].address,
name: PI:NAME:<NAME>END_PI,
role: request.session.passport.member.defaultRole
}))
runDataRules:(request,allDataRules) =>
#return an array of touples (entity and rule ids to apply)
rulesToRun = _.map(request.boundData.entities,(entity) ->
return {
entity:entity,
rules:_.chain(allDataRules.runLists)
#find run list for this entity or for all entities
.filter((runList) ->
return (
runList.model.toLowerCase() == entity._type.toLowerCase() ||
runList.model.toLowerCase() == 'all')
)
#apply the update rules
.map((runList) -> return runList.onUpdate)
.flatten().value()
})
loadUser = @getCurrentUser(request)
rulesRunFuncs = _.map(rulesToRun,(ruleToRun)=>
hoist.logger.debug 'running rules'
@validateEntity(request,loadUser,ruleToRun,allDataRules.rules))
return q.allSettled(rulesRunFuncs)
loadExistingEntity:(request,entity) ->
#no entity id so can't load anything existing
return q.fcall(()->) if !entity._id
return request.dataStore.get(entity._type, entity._id)
validateEntity:(request,loadUser,ruleListToRun,allRules) =>
#no rules to run so pass
return q.fcall(()->) if !ruleListToRun.rules
return q.fcall(()->) if ruleListToRun.rules.length<1
return q.all([@loadExistingEntity(request,ruleListToRun.entity),loadUser])
.spread((existingEntity,user)->
return q.all(_.chain(allRules)
.filter((rule) ->
#only run enabled rules and those listed to run against this entity
return rule.enabled &&_.some(ruleListToRun.rules, (id) ->
return id.equals(rule._id)
)
)
#run them in the order specified
.sortBy((rule) -> return rule.order)
.map(throat 2, (rule) ->
#run the rule
ruleFn = "function(model,existing,user){" + rule.rule + "}"
u = 'none'
if(user)
u = JSON.stringify(user)
hoist.logger.debug('running rule',rule.name,ruleFn,u)
return ruleRunner.run(
ruleFn, ruleListToRun.entity, existingEntity, user
)
.then((result) ->
if (!result)
error = new Error()
error.rule = rule.name
error.entity = JSON.stringify(ruleListToRun.entity)
throw error
)
).value())
)
applyDataRules:(request) =>
#if no data rules return nothing
application = request.application
environment = request.environment
return q.fcall(()->) if !environment.dataRules
return DataRuleCollection
.findByIdQ(environment.dataRules)
.then((dataRulesCollection)=>@runDataRules(request,dataRulesCollection))
checkValidationResults:(validationResults) ->
validationResults = validationResults || []
failedChecks = _.filter(validationResults, (validationResult) ->
return validationResult.state == 'rejected';
)
if (failedChecks && failedChecks.length > 0)
error = new errors.Data.RulesFailed("One or more data rules failed")
error.failures = _.chain(failedChecks).map((check) ->
return {
rule: check.reason.rule,
entity: check.reason.entity
})
.flatten().value()
throw error
saveEntities:(req) ->
return q.allSettled(
_.map(req.boundData.entities,(entity) ->
return req.dataStore.save(entity)
))
.then((results)->
return _.chain(results).map((result)->
return result.value
).flatten().value()
)
ping: (req, res) ->
res.send({
ok: true,
node: process.env.NODE_NAME,
port: process.env.PORT
})
post: (req, res) =>
member = req.session.passport.member
bucket = req.session.passport.bucket
environment = req.environment
application = req.application
hoist.auth.helpers.data.canWrite(member,environment,bucket)
.then (allowed) =>
throw new errors.request.Forbidden("User doesn't have permissions to write data") if !allowed
return @applyDataRules(req)
.then (results) =>
return @checkValidationResults(results)
.then () =>
return @saveEntities(req)
.then (savedEntities) ->
saveSuccessful = _.every(savedEntities,(entity)->return entity._saved)
statusCode = 200
statusCode = 403 if !saveSuccessful
if(savedEntities.length==1)
savedEntities = savedEntities[0]
res.send(statusCode,savedEntities)
.catch (err) ->
if (!err.resCode)
hoist.error(err, req, req.application)
err = new errors.server.ServerError()
response = {
message:err.message
}
if err.failures
response.failures = err.failures
res.send(err.resCode || 500, response)
.done()
get: (req, res) ->
member = req.session.passport.member
bucket = req.session.passport.bucket
environment = req.environment
hoist.auth.helpers.data.canRead(member,environment,bucket)
.then (allowed) ->
throw new errors.request.Forbidden("User doesn't have permissions to read data") if !allowed
query = {}
if(req.query.skip)
query.skip = req.query.skip
if(req.query.limit)
query.limit = req.query.limit
if(req.query.q)
query.q = JSON.parse(req.query.q)
if(req.query.sort)
query.sort = JSON.parse(req.query.sort)
return req.dataStore.get(req.dataParams._type,req.dataParams._id,query)
.then (entity) ->
if !entity
throw new errors.request.NotFound("Data item doesn't exist")
return
res.send(200,entity)
.catch (err) ->
if (!err.resCode)
hoist.error(err, req, req.application)
err = new errors.server.ServerError()
res.send(err.resCode || 500, err.message)
.done()
delete: (req, res) ->
member = req.session.passport.member
bucket = req.session.passport.bucket
environment = req.environment
application = req.application
hoist.auth.helpers.data.canDelete(member,environment,bucket)
.then (allowed) ->
throw new errors.request.Forbidden("User doesn't have permissions to delete data") if !allowed
req.dataStore.delete(req.dataParams._type, req.dataParams._id)
.then((numberOfRemovedDocs)->
if(numberOfRemovedDocs.length&&numberOfRemovedDocs.length>1)
numberOfRemovedDocs = numberOfRemovedDocs[0];
res.send({status:"ok",removed:numberOfRemovedDocs})
)
.catch((err) ->
if (!err.resCode)
hoist.error(err, req, req.application)
err = new errors.server.ServerError()
res.send(err.resCode || 500, err.message)
).done()
module.exports = new DataController()
|
[
{
"context": "weet Button Prototype for Twitter on Android\n# By: Jason Valenti\n# If you have any questions tweet me: @jval3nti\n\n",
"end": 67,
"score": 0.9998628497123718,
"start": 54,
"tag": "NAME",
"value": "Jason Valenti"
},
{
"context": "ason Valenti\n# If you have any questions tweet me: @jval3nti\n\n\n# Setting up my images as layers\ntimeline = new",
"end": 115,
"score": 0.999264657497406,
"start": 106,
"tag": "USERNAME",
"value": "@jval3nti"
}
] | framer/backup.coffee | doctoroakin/FramerJS-Tweet-Button | 0 | # Tweet Button Prototype for Twitter on Android
# By: Jason Valenti
# If you have any questions tweet me: @jval3nti
# Setting up my images as layers
timeline = new Layer
x:0, y:0, width:1080, height:1919, image:"images/TwitterTweet_2.png"
timeline.visible = true
tweetBR = new Layer
x:0, y:0, width:1080, height:1920, image:"images/tweetBR.png"
tweetBR.visible = false
#1040 is where the keyboard shoud go to
keyboard = new Layer
x:0, y:1940, width:1080, height:885, image:"images/keyboard.png"
cameraBar = new Layer
x:0, y:1940, width:1080, height:168, image:"images/camBar.png"
tweetButton = new Layer
x:790, y:1655, width:191, height:191, image:"images/NewTweet.png"
bird = new Layer
x:815, y:1700, width:130, height:100, image:"images/bird2.png"
bird.visible = true
back = new Layer
x:1, y:30, width:250, height:250, opacity:0, scale:0.5, borderRadius: 75, visible:true, backgroundColor:"#CCC"
#animations
keyboard.states.animationOptions = ({
time: .190,
curve: "ease-in-out"
})
cameraBar.states.animationOptions = ({
time: .190,
curve: "ease-in-out"
})
#The code that runs when you click on the Tweet Button (the blue circle with the bird in it)
tweetButton.on Events.Click, ->
timeline.states.switch("detail")
tweetBR.states.switch("detail")
bird.states.switch("detail")
tweetButton.states.switch("detail")
cameraBar.states.switch("detail")
keyboard.states.switch("detail")
# The code that runs when you click on the back button
back.on Events.Click, ->
keyboard.states.switch("hide")
cameraBar.states.switch("hide")
tweetBR.states.switch("hide")
timeline.states.switch("hide")
tweetButton.states.switch("hide")
bird.states.switch("hide")
#States
timeline.states.add (detail: {visible: false})
tweetBR.states.add (detail: {visible: true})
tweetButton.states.add (detail: {visible: false})
bird.states.add (detail: {visible: false})
keyboard.states.add (detail: {y:1040})
cameraBar.states.add (detail: {y:850})
keyboard.states.add (hide: {y:1940})
cameraBar.states.add (hide: {y:1940})
tweetBR.states.add (hide: {visible: false})
timeline.states.add (hide: {visible: true})
tweetButton.states.add (hide: {visible: true})
bird.states.add (hide: {visible: true}) | 206541 | # Tweet Button Prototype for Twitter on Android
# By: <NAME>
# If you have any questions tweet me: @jval3nti
# Setting up my images as layers
timeline = new Layer
x:0, y:0, width:1080, height:1919, image:"images/TwitterTweet_2.png"
timeline.visible = true
tweetBR = new Layer
x:0, y:0, width:1080, height:1920, image:"images/tweetBR.png"
tweetBR.visible = false
#1040 is where the keyboard shoud go to
keyboard = new Layer
x:0, y:1940, width:1080, height:885, image:"images/keyboard.png"
cameraBar = new Layer
x:0, y:1940, width:1080, height:168, image:"images/camBar.png"
tweetButton = new Layer
x:790, y:1655, width:191, height:191, image:"images/NewTweet.png"
bird = new Layer
x:815, y:1700, width:130, height:100, image:"images/bird2.png"
bird.visible = true
back = new Layer
x:1, y:30, width:250, height:250, opacity:0, scale:0.5, borderRadius: 75, visible:true, backgroundColor:"#CCC"
#animations
keyboard.states.animationOptions = ({
time: .190,
curve: "ease-in-out"
})
cameraBar.states.animationOptions = ({
time: .190,
curve: "ease-in-out"
})
#The code that runs when you click on the Tweet Button (the blue circle with the bird in it)
tweetButton.on Events.Click, ->
timeline.states.switch("detail")
tweetBR.states.switch("detail")
bird.states.switch("detail")
tweetButton.states.switch("detail")
cameraBar.states.switch("detail")
keyboard.states.switch("detail")
# The code that runs when you click on the back button
back.on Events.Click, ->
keyboard.states.switch("hide")
cameraBar.states.switch("hide")
tweetBR.states.switch("hide")
timeline.states.switch("hide")
tweetButton.states.switch("hide")
bird.states.switch("hide")
#States
timeline.states.add (detail: {visible: false})
tweetBR.states.add (detail: {visible: true})
tweetButton.states.add (detail: {visible: false})
bird.states.add (detail: {visible: false})
keyboard.states.add (detail: {y:1040})
cameraBar.states.add (detail: {y:850})
keyboard.states.add (hide: {y:1940})
cameraBar.states.add (hide: {y:1940})
tweetBR.states.add (hide: {visible: false})
timeline.states.add (hide: {visible: true})
tweetButton.states.add (hide: {visible: true})
bird.states.add (hide: {visible: true}) | true | # Tweet Button Prototype for Twitter on Android
# By: PI:NAME:<NAME>END_PI
# If you have any questions tweet me: @jval3nti
# Setting up my images as layers
timeline = new Layer
x:0, y:0, width:1080, height:1919, image:"images/TwitterTweet_2.png"
timeline.visible = true
tweetBR = new Layer
x:0, y:0, width:1080, height:1920, image:"images/tweetBR.png"
tweetBR.visible = false
#1040 is where the keyboard shoud go to
keyboard = new Layer
x:0, y:1940, width:1080, height:885, image:"images/keyboard.png"
cameraBar = new Layer
x:0, y:1940, width:1080, height:168, image:"images/camBar.png"
tweetButton = new Layer
x:790, y:1655, width:191, height:191, image:"images/NewTweet.png"
bird = new Layer
x:815, y:1700, width:130, height:100, image:"images/bird2.png"
bird.visible = true
back = new Layer
x:1, y:30, width:250, height:250, opacity:0, scale:0.5, borderRadius: 75, visible:true, backgroundColor:"#CCC"
#animations
keyboard.states.animationOptions = ({
time: .190,
curve: "ease-in-out"
})
cameraBar.states.animationOptions = ({
time: .190,
curve: "ease-in-out"
})
#The code that runs when you click on the Tweet Button (the blue circle with the bird in it)
tweetButton.on Events.Click, ->
timeline.states.switch("detail")
tweetBR.states.switch("detail")
bird.states.switch("detail")
tweetButton.states.switch("detail")
cameraBar.states.switch("detail")
keyboard.states.switch("detail")
# The code that runs when you click on the back button
back.on Events.Click, ->
keyboard.states.switch("hide")
cameraBar.states.switch("hide")
tweetBR.states.switch("hide")
timeline.states.switch("hide")
tweetButton.states.switch("hide")
bird.states.switch("hide")
#States
timeline.states.add (detail: {visible: false})
tweetBR.states.add (detail: {visible: true})
tweetButton.states.add (detail: {visible: false})
bird.states.add (detail: {visible: false})
keyboard.states.add (detail: {y:1040})
cameraBar.states.add (detail: {y:850})
keyboard.states.add (hide: {y:1940})
cameraBar.states.add (hide: {y:1940})
tweetBR.states.add (hide: {visible: false})
timeline.states.add (hide: {visible: true})
tweetButton.states.add (hide: {visible: true})
bird.states.add (hide: {visible: true}) |
[
{
"context": "ll/salt.netapi.rest_cherrypy.html>\n#\n# Author:\n# HenryCook <henry@havingatinker.uk>\n\n{spawn, exec} = requir",
"end": 544,
"score": 0.9991105198860168,
"start": 535,
"tag": "NAME",
"value": "HenryCook"
},
{
"context": "pi.rest_cherrypy.html>\n#\n# Author:\n# HenryCook <henry@havingatinker.uk>\n\n{spawn, exec} = require 'child_process'\nmodule",
"end": 568,
"score": 0.9999277591705322,
"start": 546,
"tag": "EMAIL",
"value": "henry@havingatinker.uk"
}
] | scripts/salt.coffee | HenryCook/hubot-scripts | 0 | # Description:
# Interacts with Salt minions
#
# Commands:
# hubot salt ping <host> - Salt Master pings the Salt minion.
# hubot salt puppet <host> - Runs Puppet on Salt minion.
#
# Configuration:
# SALT_API_ENDPOINT - The endpoint for Salt's REST API e.g. https://salt-master.foo.bar:8000
# SALT_API_USER - Salt API user
# SALT_API_PASSWORD - Salt API password
#
# Notes:
# Salt REST API needs to be up and running
# <https://docs.saltstack.com/en/latest/ref/netapi/all/salt.netapi.rest_cherrypy.html>
#
# Author:
# HenryCook <henry@havingatinker.uk>
{spawn, exec} = require 'child_process'
module.exports = (robot) ->
robot.respond /salt ping ([^ ]+)\s*(\w*)/i, (msg) ->
c = "/opt/hubot/bin/salt/salt_api.py --ping "+ msg.match[1]
exec c, (err, stdout, stderr) ->
msg.send stdout
msg.send stderr
msg.send err
robot.respond /salt puppet ([^ ]+)\s*(\w*)/i, (msg) ->
c = "/opt/hubot/bin/salt/salt_api.py --run-puppet "+ msg.match[1]
exec c, (err, stdout, stderr) ->
msg.send stdout
msg.send stderr
msg.send err
| 214289 | # Description:
# Interacts with Salt minions
#
# Commands:
# hubot salt ping <host> - Salt Master pings the Salt minion.
# hubot salt puppet <host> - Runs Puppet on Salt minion.
#
# Configuration:
# SALT_API_ENDPOINT - The endpoint for Salt's REST API e.g. https://salt-master.foo.bar:8000
# SALT_API_USER - Salt API user
# SALT_API_PASSWORD - Salt API password
#
# Notes:
# Salt REST API needs to be up and running
# <https://docs.saltstack.com/en/latest/ref/netapi/all/salt.netapi.rest_cherrypy.html>
#
# Author:
# <NAME> <<EMAIL>>
{spawn, exec} = require 'child_process'
module.exports = (robot) ->
robot.respond /salt ping ([^ ]+)\s*(\w*)/i, (msg) ->
c = "/opt/hubot/bin/salt/salt_api.py --ping "+ msg.match[1]
exec c, (err, stdout, stderr) ->
msg.send stdout
msg.send stderr
msg.send err
robot.respond /salt puppet ([^ ]+)\s*(\w*)/i, (msg) ->
c = "/opt/hubot/bin/salt/salt_api.py --run-puppet "+ msg.match[1]
exec c, (err, stdout, stderr) ->
msg.send stdout
msg.send stderr
msg.send err
| true | # Description:
# Interacts with Salt minions
#
# Commands:
# hubot salt ping <host> - Salt Master pings the Salt minion.
# hubot salt puppet <host> - Runs Puppet on Salt minion.
#
# Configuration:
# SALT_API_ENDPOINT - The endpoint for Salt's REST API e.g. https://salt-master.foo.bar:8000
# SALT_API_USER - Salt API user
# SALT_API_PASSWORD - Salt API password
#
# Notes:
# Salt REST API needs to be up and running
# <https://docs.saltstack.com/en/latest/ref/netapi/all/salt.netapi.rest_cherrypy.html>
#
# Author:
# PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
{spawn, exec} = require 'child_process'
module.exports = (robot) ->
robot.respond /salt ping ([^ ]+)\s*(\w*)/i, (msg) ->
c = "/opt/hubot/bin/salt/salt_api.py --ping "+ msg.match[1]
exec c, (err, stdout, stderr) ->
msg.send stdout
msg.send stderr
msg.send err
robot.respond /salt puppet ([^ ]+)\s*(\w*)/i, (msg) ->
c = "/opt/hubot/bin/salt/salt_api.py --run-puppet "+ msg.match[1]
exec c, (err, stdout, stderr) ->
msg.send stdout
msg.send stderr
msg.send err
|
[
{
"context": "#Language: European Portuguese\n#Translators: Tiago Silva\n\npt_PT =\n\n add: \"adicionar\"\n and: \"e\"\n back: \"",
"end": 56,
"score": 0.9998148679733276,
"start": 45,
"tag": "NAME",
"value": "Tiago Silva"
},
{
"context": "r\"\n and: \"e\"\n back: \"voltar\"\n changePassword: \"Alterar palavra-passe\"\n choosePassword: \"Escolha uma palavra-passe\"\n ",
"end": 154,
"score": 0.9889464378356934,
"start": 133,
"tag": "PASSWORD",
"value": "Alterar palavra-passe"
},
{
"context": "sword: \"Alterar palavra-passe\"\n choosePassword: \"Escolha uma palavra-passe\"\n clickAgree: \"Ao clicar em Registar, está a ace",
"end": 200,
"score": 0.9956070184707642,
"start": 175,
"tag": "PASSWORD",
"value": "Escolha uma palavra-passe"
},
{
"context": "ateAccount: \"Criar uma Conta\"\n currentPassword: \"Palavra-passe Atual\"\n dontHaveAnAccount: \"Não tem conta?\"\n email: \"",
"end": 366,
"score": 0.9976028203964233,
"start": 347,
"tag": "PASSWORD",
"value": "Palavra-passe Atual"
},
{
"context": "ara redefinir a palavra-passe\"\n forgotPassword: \"Esqueci-me da palavra-passe\"\n ifYouAlreadyHaveAnAccount: \"Se já tem uma cont",
"end": 572,
"score": 0.9980742931365967,
"start": 545,
"tag": "PASSWORD",
"value": "Esqueci-me da palavra-passe"
},
{
"context": "eAnAccount: \"Se já tem uma conta\"\n newPassword: \"Nova Palavra-passe\"\n newPasswordAgain: \"Nova Palavra-passe (novamen",
"end": 659,
"score": 0.9984001517295837,
"start": 641,
"tag": "PASSWORD",
"value": "Nova Palavra-passe"
},
{
"context": "ssword: \"Nova Palavra-passe\"\n newPasswordAgain: \"Nova Palavra-passe (novamente)\"\n optional: \"Opcional\"\n OR: \"OU\"\n ",
"end": 700,
"score": 0.969413161277771,
"start": 682,
"tag": "PASSWORD",
"value": "Nova Palavra-passe"
},
{
"context": "a-passe\"\n newPasswordAgain: \"Nova Palavra-passe (novamente)\"\n optional: \"Opcional\"\n OR: \"OU\"\n password: \"Pa",
"end": 711,
"score": 0.9075962901115417,
"start": 702,
"tag": "PASSWORD",
"value": "novamente"
},
{
"context": ")\"\n optional: \"Opcional\"\n OR: \"OU\"\n password: \"Palavra-passe\"\n passwordAgain: \"Palavra-passe (novamente)\"\n p",
"end": 774,
"score": 0.9986863136291504,
"start": 761,
"tag": "PASSWORD",
"value": "Palavra-passe"
},
{
"context": "OU\"\n password: \"Palavra-passe\"\n passwordAgain: \"Palavra-passe (novamente)\"\n privacyPolicy: \"Política de Privacidade\"\n remo",
"end": 818,
"score": 0.9952904582023621,
"start": 794,
"tag": "PASSWORD",
"value": "Palavra-passe (novamente"
},
{
"context": "cidade\"\n remove: \"remover\"\n resetYourPassword: \"Redefinir a palavra-passe\"\n setPassword: \"Definir Palavra-passe\"\n sign: \"",
"end": 931,
"score": 0.9973740577697754,
"start": 906,
"tag": "PASSWORD",
"value": "Redefinir a palavra-passe"
},
{
"context": "word: \"Redefinir a palavra-passe\"\n setPassword: \"Definir Palavra-passe\"\n sign: \"Iniciar\"\n signIn: \"Iniciar Sessão\"\n s",
"end": 970,
"score": 0.9928637146949768,
"start": 949,
"tag": "PASSWORD",
"value": "Definir Palavra-passe"
},
{
"context": "\"\n terms: \"Termos de Uso\"\n updateYourPassword: \"Alterar a palavra-passe\"\n username: \"Nome do ulilizador\"\n usernameOrEma",
"end": 1257,
"score": 0.9981791377067566,
"start": 1234,
"tag": "PASSWORD",
"value": "Alterar a palavra-passe"
},
{
"context": "rPassword: \"Alterar a palavra-passe\"\n username: \"Nome do ulilizador\"\n usernameOrEmail: \"Ulilizador ou e-mail\"\n with",
"end": 1290,
"score": 0.997607946395874,
"start": 1272,
"tag": "USERNAME",
"value": "Nome do ulilizador"
},
{
"context": "sername: \"Nome do ulilizador\"\n usernameOrEmail: \"Ulilizador ou e-mail\"\n with: \"com\"\n \"Send the verification",
"end": 1322,
"score": 0.9551365971565247,
"start": 1312,
"tag": "USERNAME",
"value": "Ulilizador"
},
{
"context": "rified: \"E-mail verificado\"\n passwordChanged: \"Palavra-passe alterada\"\n passwordReset: \"Palavra-passe redefinida\"\n\n\n",
"end": 2460,
"score": 0.9987188577651978,
"start": 2438,
"tag": "PASSWORD",
"value": "Palavra-passe alterada"
},
{
"context": "ged: \"Palavra-passe alterada\"\n passwordReset: \"Palavra-passe redefinida\"\n\n\n error:\n emailRequired: \"O e-mail é obriga",
"end": 2506,
"score": 0.9986143112182617,
"start": 2482,
"tag": "PASSWORD",
"value": "Palavra-passe redefinida"
},
{
"context": "-- accounts-password\n \"Incorrect password\": \"Palavra-passe incorreta\"\n \"Invalid email\": \"E-mail inválid",
"end": 4549,
"score": 0.8939935564994812,
"start": 4536,
"tag": "PASSWORD",
"value": "Palavra-passe"
},
{
"context": "ord\n \"Incorrect password\": \"Palavra-passe incorreta\"\n \"Invalid email\": \"E-mail inválido\"\n \"",
"end": 4559,
"score": 0.6703704595565796,
"start": 4553,
"tag": "PASSWORD",
"value": "orreta"
}
] | t9n/pt_PT.coffee | softwarerero/meteor-accounts-t9n | 80 | #Language: European Portuguese
#Translators: Tiago Silva
pt_PT =
add: "adicionar"
and: "e"
back: "voltar"
changePassword: "Alterar palavra-passe"
choosePassword: "Escolha uma palavra-passe"
clickAgree: "Ao clicar em Registar, está a aceitar os nossos"
configure: "Configurar"
createAccount: "Criar uma Conta"
currentPassword: "Palavra-passe Atual"
dontHaveAnAccount: "Não tem conta?"
email: "E-mail"
emailAddress: "Endereço de e-mail"
emailResetLink: "Enviar e-mail para redefinir a palavra-passe"
forgotPassword: "Esqueci-me da palavra-passe"
ifYouAlreadyHaveAnAccount: "Se já tem uma conta"
newPassword: "Nova Palavra-passe"
newPasswordAgain: "Nova Palavra-passe (novamente)"
optional: "Opcional"
OR: "OU"
password: "Palavra-passe"
passwordAgain: "Palavra-passe (novamente)"
privacyPolicy: "Política de Privacidade"
remove: "remover"
resetYourPassword: "Redefinir a palavra-passe"
setPassword: "Definir Palavra-passe"
sign: "Iniciar"
signIn: "Iniciar Sessão"
signin: "iniciar sessão"
signOut: "Sair"
signUp: "Criar conta"
signupCode: "Código de Registo"
signUpWithYourEmailAddress: "Registar com o endereço de e-mail"
terms: "Termos de Uso"
updateYourPassword: "Alterar a palavra-passe"
username: "Nome do ulilizador"
usernameOrEmail: "Ulilizador ou e-mail"
with: "com"
"Send the verification email again" : "Reenviar e-mail de verificação",
"Send email again" : "Reenviar e-mail"
"A new email has been sent to you. If the email doesn't show up in your inbox, be sure to check your spam folder.": "Se le ha enviado un nuevo correo electrónico. Si el correo electrónico no aparece en su bandeja de entrada, asegúrese de revisar su carpeta de correo no deseado."
"Already verified": "Ya verificado"
"At least 1 digit, 1 lowercase and 1 uppercase": "Al menos 1 dígito, 1 minúscula y 1 mayúscula"
"Invalid email": "Email inválido"
"Required Field": "Campo requerido"
"Send again": "Enviar de nuevo"
"Send email again": "Enviar correo de nuevo"
"Send the verification email again": "Enviar el correo electrónico de verificación de nuevo"
"Verification email lost?": "¿Perdió el correo electrónico de verificación?"
"Maximum allowed length: 6": "Longitud máxima permitida: 6"
"Minimum required length: 6": "Longitud mínima requerida: 6"
info:
emailSent: "E-mail enviado"
emailVerified: "E-mail verificado"
passwordChanged: "Palavra-passe alterada"
passwordReset: "Palavra-passe redefinida"
error:
emailRequired: "O e-mail é obrigatório."
minChar: "A palavra-passe tem de ter no mínimo 7 caracteres."
pwdsDontMatch: "As palavra-passes não coincidem"
pwOneDigit: "A palavra-passe tem de conter pelo menos um dígito."
pwOneLetter: "A palavra-passe tem de conter pelo menos uma letra."
signInRequired: "É necessário iniciar sessão para fazer isso."
signupCodeIncorrect: "Código de registo incorreto."
signupCodeRequired: "É necessário um código de registo."
usernameIsEmail: "O nome do utilizador não pode ser um endereço de e-mail."
usernameRequired: "O nome de usuário é obrigatório."
accounts:
#---- accounts-base
#"@" + domain + " email required"
#"A login handler should return a result or undefined"
"Email already exists.": "O e-mail já existe."
"Email doesn't match the criteria.": "E-mail inválido."
"Invalid login token": "Token de início de sessão inválido"
"Login forbidden": "Início de sessão impedido"
#"Service " + options.service + " already configured"
"Service unknown": "Serviço desconhecido"
"Unrecognized options for login request": "Pedido de início de sessão com opções não reconhecidas"
"User validation failed": "A validação do utilizador falhou"
"Username already exists.": "O nome do utilizador já existe."
"You are not logged in.": "Não tem sessão iniciada."
"You've been logged out by the server. Please log in again.": "Sessão terminada pelo servidor. Por favor, inicie sessão novamente."
"Your session has expired. Please log in again.": "A sua sessão expirou. Por favor, inicie sessão novamente."
#---- accounts-oauth
"No matching login attempt found": "Não foi encontrada nenhuma tentativa de início de sessão que coincida."
#---- accounts-password-client
"Password is old. Please reset your password.": "A palavra-passe é antiga. Por favor, redefina a sua palavra-passe."
#---- accounts-password
"Incorrect password": "Palavra-passe incorreta"
"Invalid email": "E-mail inválido"
"Must be logged in": "É necessário iniciar sessão"
"Need to set a username or email": "É necessário definir um nome de utilizador ou e-mail"
"old password format": "Formato de palavra-passe antigo"
"Password may not be empty": "A palavra-passe não pode estar em branco"
"Signups forbidden": "Criação de contas proibida"
"Token expired": "O token expirou"
"Token has invalid email address": "O token tem um endereço de e-mail inválido"
"User has no password set": "O utilizador não defeniu a palavra-passe"
"User not found": "Utilizador não encontrado"
"Verify email link expired": "O link de verificação de e-mail expirou"
"Verify email link is for unknown address": "O link de verificação de e-mail está definido para um endereço desconhecido"
#---- match
"Match failed": "Comparação falhou"
#---- Misc...
"Unknown error": "Erro desconhecido"
T9n?.map "pt_PT", pt_PT
T9n?.map "pt-PT", pt_PT
module?.exports = pt_PT
| 11018 | #Language: European Portuguese
#Translators: <NAME>
pt_PT =
add: "adicionar"
and: "e"
back: "voltar"
changePassword: "<PASSWORD>"
choosePassword: "<PASSWORD>"
clickAgree: "Ao clicar em Registar, está a aceitar os nossos"
configure: "Configurar"
createAccount: "Criar uma Conta"
currentPassword: "<PASSWORD>"
dontHaveAnAccount: "Não tem conta?"
email: "E-mail"
emailAddress: "Endereço de e-mail"
emailResetLink: "Enviar e-mail para redefinir a palavra-passe"
forgotPassword: "<PASSWORD>"
ifYouAlreadyHaveAnAccount: "Se já tem uma conta"
newPassword: "<PASSWORD>"
newPasswordAgain: "<PASSWORD> (<PASSWORD>)"
optional: "Opcional"
OR: "OU"
password: "<PASSWORD>"
passwordAgain: "<PASSWORD>)"
privacyPolicy: "Política de Privacidade"
remove: "remover"
resetYourPassword: "<PASSWORD>"
setPassword: "<PASSWORD>"
sign: "Iniciar"
signIn: "Iniciar Sessão"
signin: "iniciar sessão"
signOut: "Sair"
signUp: "Criar conta"
signupCode: "Código de Registo"
signUpWithYourEmailAddress: "Registar com o endereço de e-mail"
terms: "Termos de Uso"
updateYourPassword: "<PASSWORD>"
username: "Nome do ulilizador"
usernameOrEmail: "Ulilizador ou e-mail"
with: "com"
"Send the verification email again" : "Reenviar e-mail de verificação",
"Send email again" : "Reenviar e-mail"
"A new email has been sent to you. If the email doesn't show up in your inbox, be sure to check your spam folder.": "Se le ha enviado un nuevo correo electrónico. Si el correo electrónico no aparece en su bandeja de entrada, asegúrese de revisar su carpeta de correo no deseado."
"Already verified": "Ya verificado"
"At least 1 digit, 1 lowercase and 1 uppercase": "Al menos 1 dígito, 1 minúscula y 1 mayúscula"
"Invalid email": "Email inválido"
"Required Field": "Campo requerido"
"Send again": "Enviar de nuevo"
"Send email again": "Enviar correo de nuevo"
"Send the verification email again": "Enviar el correo electrónico de verificación de nuevo"
"Verification email lost?": "¿Perdió el correo electrónico de verificación?"
"Maximum allowed length: 6": "Longitud máxima permitida: 6"
"Minimum required length: 6": "Longitud mínima requerida: 6"
info:
emailSent: "E-mail enviado"
emailVerified: "E-mail verificado"
passwordChanged: "<PASSWORD>"
passwordReset: "<PASSWORD>"
error:
emailRequired: "O e-mail é obrigatório."
minChar: "A palavra-passe tem de ter no mínimo 7 caracteres."
pwdsDontMatch: "As palavra-passes não coincidem"
pwOneDigit: "A palavra-passe tem de conter pelo menos um dígito."
pwOneLetter: "A palavra-passe tem de conter pelo menos uma letra."
signInRequired: "É necessário iniciar sessão para fazer isso."
signupCodeIncorrect: "Código de registo incorreto."
signupCodeRequired: "É necessário um código de registo."
usernameIsEmail: "O nome do utilizador não pode ser um endereço de e-mail."
usernameRequired: "O nome de usuário é obrigatório."
accounts:
#---- accounts-base
#"@" + domain + " email required"
#"A login handler should return a result or undefined"
"Email already exists.": "O e-mail já existe."
"Email doesn't match the criteria.": "E-mail inválido."
"Invalid login token": "Token de início de sessão inválido"
"Login forbidden": "Início de sessão impedido"
#"Service " + options.service + " already configured"
"Service unknown": "Serviço desconhecido"
"Unrecognized options for login request": "Pedido de início de sessão com opções não reconhecidas"
"User validation failed": "A validação do utilizador falhou"
"Username already exists.": "O nome do utilizador já existe."
"You are not logged in.": "Não tem sessão iniciada."
"You've been logged out by the server. Please log in again.": "Sessão terminada pelo servidor. Por favor, inicie sessão novamente."
"Your session has expired. Please log in again.": "A sua sessão expirou. Por favor, inicie sessão novamente."
#---- accounts-oauth
"No matching login attempt found": "Não foi encontrada nenhuma tentativa de início de sessão que coincida."
#---- accounts-password-client
"Password is old. Please reset your password.": "A palavra-passe é antiga. Por favor, redefina a sua palavra-passe."
#---- accounts-password
"Incorrect password": "<PASSWORD> inc<PASSWORD>"
"Invalid email": "E-mail inválido"
"Must be logged in": "É necessário iniciar sessão"
"Need to set a username or email": "É necessário definir um nome de utilizador ou e-mail"
"old password format": "Formato de palavra-passe antigo"
"Password may not be empty": "A palavra-passe não pode estar em branco"
"Signups forbidden": "Criação de contas proibida"
"Token expired": "O token expirou"
"Token has invalid email address": "O token tem um endereço de e-mail inválido"
"User has no password set": "O utilizador não defeniu a palavra-passe"
"User not found": "Utilizador não encontrado"
"Verify email link expired": "O link de verificação de e-mail expirou"
"Verify email link is for unknown address": "O link de verificação de e-mail está definido para um endereço desconhecido"
#---- match
"Match failed": "Comparação falhou"
#---- Misc...
"Unknown error": "Erro desconhecido"
T9n?.map "pt_PT", pt_PT
T9n?.map "pt-PT", pt_PT
module?.exports = pt_PT
| true | #Language: European Portuguese
#Translators: PI:NAME:<NAME>END_PI
pt_PT =
add: "adicionar"
and: "e"
back: "voltar"
changePassword: "PI:PASSWORD:<PASSWORD>END_PI"
choosePassword: "PI:PASSWORD:<PASSWORD>END_PI"
clickAgree: "Ao clicar em Registar, está a aceitar os nossos"
configure: "Configurar"
createAccount: "Criar uma Conta"
currentPassword: "PI:PASSWORD:<PASSWORD>END_PI"
dontHaveAnAccount: "Não tem conta?"
email: "E-mail"
emailAddress: "Endereço de e-mail"
emailResetLink: "Enviar e-mail para redefinir a palavra-passe"
forgotPassword: "PI:PASSWORD:<PASSWORD>END_PI"
ifYouAlreadyHaveAnAccount: "Se já tem uma conta"
newPassword: "PI:PASSWORD:<PASSWORD>END_PI"
newPasswordAgain: "PI:PASSWORD:<PASSWORD>END_PI (PI:PASSWORD:<PASSWORD>END_PI)"
optional: "Opcional"
OR: "OU"
password: "PI:PASSWORD:<PASSWORD>END_PI"
passwordAgain: "PI:PASSWORD:<PASSWORD>END_PI)"
privacyPolicy: "Política de Privacidade"
remove: "remover"
resetYourPassword: "PI:PASSWORD:<PASSWORD>END_PI"
setPassword: "PI:PASSWORD:<PASSWORD>END_PI"
sign: "Iniciar"
signIn: "Iniciar Sessão"
signin: "iniciar sessão"
signOut: "Sair"
signUp: "Criar conta"
signupCode: "Código de Registo"
signUpWithYourEmailAddress: "Registar com o endereço de e-mail"
terms: "Termos de Uso"
updateYourPassword: "PI:PASSWORD:<PASSWORD>END_PI"
username: "Nome do ulilizador"
usernameOrEmail: "Ulilizador ou e-mail"
with: "com"
"Send the verification email again" : "Reenviar e-mail de verificação",
"Send email again" : "Reenviar e-mail"
"A new email has been sent to you. If the email doesn't show up in your inbox, be sure to check your spam folder.": "Se le ha enviado un nuevo correo electrónico. Si el correo electrónico no aparece en su bandeja de entrada, asegúrese de revisar su carpeta de correo no deseado."
"Already verified": "Ya verificado"
"At least 1 digit, 1 lowercase and 1 uppercase": "Al menos 1 dígito, 1 minúscula y 1 mayúscula"
"Invalid email": "Email inválido"
"Required Field": "Campo requerido"
"Send again": "Enviar de nuevo"
"Send email again": "Enviar correo de nuevo"
"Send the verification email again": "Enviar el correo electrónico de verificación de nuevo"
"Verification email lost?": "¿Perdió el correo electrónico de verificación?"
"Maximum allowed length: 6": "Longitud máxima permitida: 6"
"Minimum required length: 6": "Longitud mínima requerida: 6"
info:
emailSent: "E-mail enviado"
emailVerified: "E-mail verificado"
passwordChanged: "PI:PASSWORD:<PASSWORD>END_PI"
passwordReset: "PI:PASSWORD:<PASSWORD>END_PI"
error:
emailRequired: "O e-mail é obrigatório."
minChar: "A palavra-passe tem de ter no mínimo 7 caracteres."
pwdsDontMatch: "As palavra-passes não coincidem"
pwOneDigit: "A palavra-passe tem de conter pelo menos um dígito."
pwOneLetter: "A palavra-passe tem de conter pelo menos uma letra."
signInRequired: "É necessário iniciar sessão para fazer isso."
signupCodeIncorrect: "Código de registo incorreto."
signupCodeRequired: "É necessário um código de registo."
usernameIsEmail: "O nome do utilizador não pode ser um endereço de e-mail."
usernameRequired: "O nome de usuário é obrigatório."
accounts:
#---- accounts-base
#"@" + domain + " email required"
#"A login handler should return a result or undefined"
"Email already exists.": "O e-mail já existe."
"Email doesn't match the criteria.": "E-mail inválido."
"Invalid login token": "Token de início de sessão inválido"
"Login forbidden": "Início de sessão impedido"
#"Service " + options.service + " already configured"
"Service unknown": "Serviço desconhecido"
"Unrecognized options for login request": "Pedido de início de sessão com opções não reconhecidas"
"User validation failed": "A validação do utilizador falhou"
"Username already exists.": "O nome do utilizador já existe."
"You are not logged in.": "Não tem sessão iniciada."
"You've been logged out by the server. Please log in again.": "Sessão terminada pelo servidor. Por favor, inicie sessão novamente."
"Your session has expired. Please log in again.": "A sua sessão expirou. Por favor, inicie sessão novamente."
#---- accounts-oauth
"No matching login attempt found": "Não foi encontrada nenhuma tentativa de início de sessão que coincida."
#---- accounts-password-client
"Password is old. Please reset your password.": "A palavra-passe é antiga. Por favor, redefina a sua palavra-passe."
#---- accounts-password
"Incorrect password": "PI:PASSWORD:<PASSWORD>END_PI incPI:PASSWORD:<PASSWORD>END_PI"
"Invalid email": "E-mail inválido"
"Must be logged in": "É necessário iniciar sessão"
"Need to set a username or email": "É necessário definir um nome de utilizador ou e-mail"
"old password format": "Formato de palavra-passe antigo"
"Password may not be empty": "A palavra-passe não pode estar em branco"
"Signups forbidden": "Criação de contas proibida"
"Token expired": "O token expirou"
"Token has invalid email address": "O token tem um endereço de e-mail inválido"
"User has no password set": "O utilizador não defeniu a palavra-passe"
"User not found": "Utilizador não encontrado"
"Verify email link expired": "O link de verificação de e-mail expirou"
"Verify email link is for unknown address": "O link de verificação de e-mail está definido para um endereço desconhecido"
#---- match
"Match failed": "Comparação falhou"
#---- Misc...
"Unknown error": "Erro desconhecido"
T9n?.map "pt_PT", pt_PT
T9n?.map "pt-PT", pt_PT
module?.exports = pt_PT
|
[
{
"context": "& user.email == req.body.email && user.password == req.body.password\n\t\t\t\t\treturn res.json {\n\t\t\t\t\t\temail: user.email,\n\t",
"end": 3011,
"score": 0.6872391700744629,
"start": 2994,
"tag": "PASSWORD",
"value": "req.body.password"
}
] | test/acceptance/coffee/helpers/MockV1Api.coffee | shyoshyo/web-sharelatex | 1 | express = require("express")
app = express()
bodyParser = require('body-parser')
sinon = require 'sinon'
app.use(bodyParser.json())
v1Id = 1000
module.exports = MockV1Api =
nextV1Id: -> v1Id++
users: { }
setUser: (id, user) ->
@users[id] = user
exportId: null
exportParams: null
setExportId: (id) ->
@exportId = id
getLastExportParams: () ->
@exportParams
clearExportParams: () ->
@exportParams = null
syncUserFeatures: sinon.stub()
affiliations: []
updateEmail: sinon.stub()
existingEmails: []
brands: {}
brand_variations: {}
validation_clients: {}
setAffiliations: (affiliations) -> @affiliations = affiliations
doc_exported: {}
setDocExported: (token, info) -> @doc_exported[token] = info
run: () ->
app.get "/api/v1/sharelatex/users/:v1_user_id/plan_code", (req, res, next) =>
user = @users[req.params.v1_user_id]
if user
res.json user
else
res.sendStatus 404
app.get "/api/v1/sharelatex/users/:v1_user_id/subscriptions", (req, res, next) =>
user = @users[req.params.v1_user_id]
if user?.subscription?
res.json user.subscription
else
res.sendStatus 404
app.get "/api/v1/sharelatex/users/:v1_user_id/subscription_status", (req, res, next) =>
user = @users[req.params.v1_user_id]
if user?.subscription_status?
res.json user.subscription_status
else
res.sendStatus 404
app.delete "/api/v1/sharelatex/users/:v1_user_id/subscription", (req, res, next) =>
user = @users[req.params.v1_user_id]
if user?
user.canceled = true
res.sendStatus 200
else
res.sendStatus 404
app.post "/api/v1/sharelatex/users/:v1_user_id/sync", (req, res, next) =>
@syncUserFeatures(req.params.v1_user_id)
res.sendStatus 200
app.post "/api/v1/sharelatex/exports", (req, res, next) =>
@exportParams = Object.assign({}, req.body)
res.json exportId: @exportId
app.get "/api/v2/users/:userId/affiliations", (req, res, next) =>
res.json @affiliations
app.post "/api/v2/users/:userId/affiliations", (req, res, next) =>
res.sendStatus 201
app.delete "/api/v2/users/:userId/affiliations/:email", (req, res, next) =>
res.sendStatus 204
app.get "/api/v2/brands/:slug", (req, res, next) =>
if brand = @brands[req.params.slug]
res.json brand
else
res.sendStatus 404
app.get '/universities/list', (req, res, next) ->
res.json []
app.get '/universities/list/:id', (req, res, next) ->
res.json {
id: parseInt(req.params.id)
name: "Institution #{req.params.id}"
}
app.get '/university/domains', (req, res, next) ->
res.json []
app.put '/api/v1/sharelatex/users/:id/email', (req, res, next) =>
{ email } = req.body?.user
if email in @existingEmails
return res.sendStatus 409
else
@updateEmail parseInt(req.params.id), email
return res.sendStatus 200
app.post "/api/v1/sharelatex/login", (req, res, next) =>
for id, user of @users
if user? && user.email == req.body.email && user.password == req.body.password
return res.json {
email: user.email,
valid: true,
user_profile: user.profile
}
return res.status(403).json {
email: req.body.email,
valid: false
}
app.get "/api/v2/partners/:partner/conversions/:id", (req, res, next) =>
partner = @validation_clients[req.params.partner]
conversion = partner?.conversions?[req.params.id]
if conversion?
res.status(200).json {input_file_uri: conversion, brand_variation_id: partner.brand_variation_id}
else
res.status(404).json {}
app.get "/api/v2/brand_variations/:id", (req, res, next) =>
variation = @brand_variations[req.params.id]
if variation?
res.status(200).json variation
else
res.status(404).json {}
app.get '/api/v1/sharelatex/docs/:token/is_published', (req, res, next) =>
res.json { allow: true }
app.get '/api/v1/sharelatex/users/:user_id/docs/:token/info', (req, res, next) =>
res.json {
exists: true,
exported: false
}
app.get '/api/v1/sharelatex/docs/:token/exported_to_v2', (req, res, next) =>
return res.json @doc_exported[req.params.token] if @doc_exported[req.params.token]?
res.json { exporting: false, exported: false }
app.get '/api/v1/sharelatex/docs/read_token/:token/exists', (req, res, next) =>
res.json { exists: false }
app.listen 5000, (error) ->
throw error if error?
.on "error", (error) ->
console.error "error starting MockV1Api:", error.message
process.exit(1)
MockV1Api.run()
| 190212 | express = require("express")
app = express()
bodyParser = require('body-parser')
sinon = require 'sinon'
app.use(bodyParser.json())
v1Id = 1000
module.exports = MockV1Api =
nextV1Id: -> v1Id++
users: { }
setUser: (id, user) ->
@users[id] = user
exportId: null
exportParams: null
setExportId: (id) ->
@exportId = id
getLastExportParams: () ->
@exportParams
clearExportParams: () ->
@exportParams = null
syncUserFeatures: sinon.stub()
affiliations: []
updateEmail: sinon.stub()
existingEmails: []
brands: {}
brand_variations: {}
validation_clients: {}
setAffiliations: (affiliations) -> @affiliations = affiliations
doc_exported: {}
setDocExported: (token, info) -> @doc_exported[token] = info
run: () ->
app.get "/api/v1/sharelatex/users/:v1_user_id/plan_code", (req, res, next) =>
user = @users[req.params.v1_user_id]
if user
res.json user
else
res.sendStatus 404
app.get "/api/v1/sharelatex/users/:v1_user_id/subscriptions", (req, res, next) =>
user = @users[req.params.v1_user_id]
if user?.subscription?
res.json user.subscription
else
res.sendStatus 404
app.get "/api/v1/sharelatex/users/:v1_user_id/subscription_status", (req, res, next) =>
user = @users[req.params.v1_user_id]
if user?.subscription_status?
res.json user.subscription_status
else
res.sendStatus 404
app.delete "/api/v1/sharelatex/users/:v1_user_id/subscription", (req, res, next) =>
user = @users[req.params.v1_user_id]
if user?
user.canceled = true
res.sendStatus 200
else
res.sendStatus 404
app.post "/api/v1/sharelatex/users/:v1_user_id/sync", (req, res, next) =>
@syncUserFeatures(req.params.v1_user_id)
res.sendStatus 200
app.post "/api/v1/sharelatex/exports", (req, res, next) =>
@exportParams = Object.assign({}, req.body)
res.json exportId: @exportId
app.get "/api/v2/users/:userId/affiliations", (req, res, next) =>
res.json @affiliations
app.post "/api/v2/users/:userId/affiliations", (req, res, next) =>
res.sendStatus 201
app.delete "/api/v2/users/:userId/affiliations/:email", (req, res, next) =>
res.sendStatus 204
app.get "/api/v2/brands/:slug", (req, res, next) =>
if brand = @brands[req.params.slug]
res.json brand
else
res.sendStatus 404
app.get '/universities/list', (req, res, next) ->
res.json []
app.get '/universities/list/:id', (req, res, next) ->
res.json {
id: parseInt(req.params.id)
name: "Institution #{req.params.id}"
}
app.get '/university/domains', (req, res, next) ->
res.json []
app.put '/api/v1/sharelatex/users/:id/email', (req, res, next) =>
{ email } = req.body?.user
if email in @existingEmails
return res.sendStatus 409
else
@updateEmail parseInt(req.params.id), email
return res.sendStatus 200
app.post "/api/v1/sharelatex/login", (req, res, next) =>
for id, user of @users
if user? && user.email == req.body.email && user.password == <PASSWORD>
return res.json {
email: user.email,
valid: true,
user_profile: user.profile
}
return res.status(403).json {
email: req.body.email,
valid: false
}
app.get "/api/v2/partners/:partner/conversions/:id", (req, res, next) =>
partner = @validation_clients[req.params.partner]
conversion = partner?.conversions?[req.params.id]
if conversion?
res.status(200).json {input_file_uri: conversion, brand_variation_id: partner.brand_variation_id}
else
res.status(404).json {}
app.get "/api/v2/brand_variations/:id", (req, res, next) =>
variation = @brand_variations[req.params.id]
if variation?
res.status(200).json variation
else
res.status(404).json {}
app.get '/api/v1/sharelatex/docs/:token/is_published', (req, res, next) =>
res.json { allow: true }
app.get '/api/v1/sharelatex/users/:user_id/docs/:token/info', (req, res, next) =>
res.json {
exists: true,
exported: false
}
app.get '/api/v1/sharelatex/docs/:token/exported_to_v2', (req, res, next) =>
return res.json @doc_exported[req.params.token] if @doc_exported[req.params.token]?
res.json { exporting: false, exported: false }
app.get '/api/v1/sharelatex/docs/read_token/:token/exists', (req, res, next) =>
res.json { exists: false }
app.listen 5000, (error) ->
throw error if error?
.on "error", (error) ->
console.error "error starting MockV1Api:", error.message
process.exit(1)
MockV1Api.run()
| true | express = require("express")
app = express()
bodyParser = require('body-parser')
sinon = require 'sinon'
app.use(bodyParser.json())
v1Id = 1000
module.exports = MockV1Api =
nextV1Id: -> v1Id++
users: { }
setUser: (id, user) ->
@users[id] = user
exportId: null
exportParams: null
setExportId: (id) ->
@exportId = id
getLastExportParams: () ->
@exportParams
clearExportParams: () ->
@exportParams = null
syncUserFeatures: sinon.stub()
affiliations: []
updateEmail: sinon.stub()
existingEmails: []
brands: {}
brand_variations: {}
validation_clients: {}
setAffiliations: (affiliations) -> @affiliations = affiliations
doc_exported: {}
setDocExported: (token, info) -> @doc_exported[token] = info
run: () ->
app.get "/api/v1/sharelatex/users/:v1_user_id/plan_code", (req, res, next) =>
user = @users[req.params.v1_user_id]
if user
res.json user
else
res.sendStatus 404
app.get "/api/v1/sharelatex/users/:v1_user_id/subscriptions", (req, res, next) =>
user = @users[req.params.v1_user_id]
if user?.subscription?
res.json user.subscription
else
res.sendStatus 404
app.get "/api/v1/sharelatex/users/:v1_user_id/subscription_status", (req, res, next) =>
user = @users[req.params.v1_user_id]
if user?.subscription_status?
res.json user.subscription_status
else
res.sendStatus 404
app.delete "/api/v1/sharelatex/users/:v1_user_id/subscription", (req, res, next) =>
user = @users[req.params.v1_user_id]
if user?
user.canceled = true
res.sendStatus 200
else
res.sendStatus 404
app.post "/api/v1/sharelatex/users/:v1_user_id/sync", (req, res, next) =>
@syncUserFeatures(req.params.v1_user_id)
res.sendStatus 200
app.post "/api/v1/sharelatex/exports", (req, res, next) =>
@exportParams = Object.assign({}, req.body)
res.json exportId: @exportId
app.get "/api/v2/users/:userId/affiliations", (req, res, next) =>
res.json @affiliations
app.post "/api/v2/users/:userId/affiliations", (req, res, next) =>
res.sendStatus 201
app.delete "/api/v2/users/:userId/affiliations/:email", (req, res, next) =>
res.sendStatus 204
app.get "/api/v2/brands/:slug", (req, res, next) =>
if brand = @brands[req.params.slug]
res.json brand
else
res.sendStatus 404
app.get '/universities/list', (req, res, next) ->
res.json []
app.get '/universities/list/:id', (req, res, next) ->
res.json {
id: parseInt(req.params.id)
name: "Institution #{req.params.id}"
}
app.get '/university/domains', (req, res, next) ->
res.json []
app.put '/api/v1/sharelatex/users/:id/email', (req, res, next) =>
{ email } = req.body?.user
if email in @existingEmails
return res.sendStatus 409
else
@updateEmail parseInt(req.params.id), email
return res.sendStatus 200
app.post "/api/v1/sharelatex/login", (req, res, next) =>
for id, user of @users
if user? && user.email == req.body.email && user.password == PI:PASSWORD:<PASSWORD>END_PI
return res.json {
email: user.email,
valid: true,
user_profile: user.profile
}
return res.status(403).json {
email: req.body.email,
valid: false
}
app.get "/api/v2/partners/:partner/conversions/:id", (req, res, next) =>
partner = @validation_clients[req.params.partner]
conversion = partner?.conversions?[req.params.id]
if conversion?
res.status(200).json {input_file_uri: conversion, brand_variation_id: partner.brand_variation_id}
else
res.status(404).json {}
app.get "/api/v2/brand_variations/:id", (req, res, next) =>
variation = @brand_variations[req.params.id]
if variation?
res.status(200).json variation
else
res.status(404).json {}
app.get '/api/v1/sharelatex/docs/:token/is_published', (req, res, next) =>
res.json { allow: true }
app.get '/api/v1/sharelatex/users/:user_id/docs/:token/info', (req, res, next) =>
res.json {
exists: true,
exported: false
}
app.get '/api/v1/sharelatex/docs/:token/exported_to_v2', (req, res, next) =>
return res.json @doc_exported[req.params.token] if @doc_exported[req.params.token]?
res.json { exporting: false, exported: false }
app.get '/api/v1/sharelatex/docs/read_token/:token/exists', (req, res, next) =>
res.json { exists: false }
app.listen 5000, (error) ->
throw error if error?
.on "error", (error) ->
console.error "error starting MockV1Api:", error.message
process.exit(1)
MockV1Api.run()
|
[
{
"context": "sion.envArrayToObject([\n\t\t\t'key1= test',\n\t\t\t'key2=test\\ntest',\n\t\t\t'key3=test ',\n\t\t\t'key4= test '\n\t\t\t'key5=test",
"end": 1095,
"score": 0.939504861831665,
"start": 1085,
"tag": "KEY",
"value": "test\\ntest"
},
{
"context": "test',\n\t\t\t'key3=test ',\n\t\t\t'key4= test '\n\t\t\t'key5=test\\r\\ntest',\n\t\t])).to.deep.equal({\n\t\t\tkey1: ' test',\n\t\t\tkey2",
"end": 1153,
"score": 0.9947777390480042,
"start": 1141,
"tag": "KEY",
"value": "test\\r\\ntest"
},
{
"context": "\t\t])).to.deep.equal({\n\t\t\tkey1: ' test',\n\t\t\tkey2: 'test\\ntest',\n\t\t\tkey3: 'test ',\n\t\t\tkey4: ' test ',\n\t\t\tkey5: '",
"end": 1216,
"score": 0.9976356029510498,
"start": 1206,
"tag": "KEY",
"value": "test\\ntest"
},
{
"context": "\t\tkey1: ' test',\n\t\t\tkey2: 'test\\ntest',\n\t\t\tkey3: 'test ',\n\t\t\tkey4: ' test ',\n\t\t\tkey5: 'test\\r\\ntest'\n\t\t}",
"end": 1233,
"score": 0.5508555173873901,
"start": 1229,
"tag": "KEY",
"value": "test"
},
{
"context": "\t\tkey2: 'test\\ntest',\n\t\t\tkey3: 'test ',\n\t\t\tkey4: ' test ',\n\t\t\tkey5: 'test\\r\\ntest'\n\t\t})\n",
"end": 1252,
"score": 0.5043626427650452,
"start": 1248,
"tag": "KEY",
"value": "test"
},
{
"context": "',\n\t\t\tkey3: 'test ',\n\t\t\tkey4: ' test ',\n\t\t\tkey5: 'test\\r\\ntest'\n\t\t})\n",
"end": 1278,
"score": 0.998923122882843,
"start": 1266,
"tag": "KEY",
"value": "test\\r\\ntest"
}
] | test/15-conversions.spec.coffee | metamorfoso/balena-supervisor | 0 | { expect } = require './lib/chai-config'
conversion = require '../src/lib/conversions'
describe 'conversions', ->
describe 'envArrayToObject', ->
it 'should convert an env array to an object', ->
expect(conversion.envArrayToObject([
'key=value'
'test1=test2'
'k=v'
'equalsvalue=thisvaluehasan=char'
'asd='
'number=123'
])).to.deep.equal({
key: 'value'
test1: 'test2'
k: 'v'
equalsvalue: 'thisvaluehasan=char'
asd: ''
number: '123'
})
it 'should ignore invalid env array entries', ->
expect(conversion.envArrayToObject([
'key1',
'key1=value1'
])).to.deep.equal({
key1: 'value1'
})
it 'should return an empty object with an empty input', ->
expect(conversion.envArrayToObject(null)).to.deep.equal({})
expect(conversion.envArrayToObject('')).to.deep.equal({})
expect(conversion.envArrayToObject([])).to.deep.equal({})
expect(conversion.envArrayToObject(1)).to.deep.equal({})
it 'should correctly handle whitespace', ->
expect(conversion.envArrayToObject([
'key1= test',
'key2=test\ntest',
'key3=test ',
'key4= test '
'key5=test\r\ntest',
])).to.deep.equal({
key1: ' test',
key2: 'test\ntest',
key3: 'test ',
key4: ' test ',
key5: 'test\r\ntest'
})
| 124857 | { expect } = require './lib/chai-config'
conversion = require '../src/lib/conversions'
describe 'conversions', ->
describe 'envArrayToObject', ->
it 'should convert an env array to an object', ->
expect(conversion.envArrayToObject([
'key=value'
'test1=test2'
'k=v'
'equalsvalue=thisvaluehasan=char'
'asd='
'number=123'
])).to.deep.equal({
key: 'value'
test1: 'test2'
k: 'v'
equalsvalue: 'thisvaluehasan=char'
asd: ''
number: '123'
})
it 'should ignore invalid env array entries', ->
expect(conversion.envArrayToObject([
'key1',
'key1=value1'
])).to.deep.equal({
key1: 'value1'
})
it 'should return an empty object with an empty input', ->
expect(conversion.envArrayToObject(null)).to.deep.equal({})
expect(conversion.envArrayToObject('')).to.deep.equal({})
expect(conversion.envArrayToObject([])).to.deep.equal({})
expect(conversion.envArrayToObject(1)).to.deep.equal({})
it 'should correctly handle whitespace', ->
expect(conversion.envArrayToObject([
'key1= test',
'key2=<KEY>',
'key3=test ',
'key4= test '
'key5=<KEY>',
])).to.deep.equal({
key1: ' test',
key2: '<KEY>',
key3: '<KEY> ',
key4: ' <KEY> ',
key5: '<KEY>'
})
| true | { expect } = require './lib/chai-config'
conversion = require '../src/lib/conversions'
describe 'conversions', ->
describe 'envArrayToObject', ->
it 'should convert an env array to an object', ->
expect(conversion.envArrayToObject([
'key=value'
'test1=test2'
'k=v'
'equalsvalue=thisvaluehasan=char'
'asd='
'number=123'
])).to.deep.equal({
key: 'value'
test1: 'test2'
k: 'v'
equalsvalue: 'thisvaluehasan=char'
asd: ''
number: '123'
})
it 'should ignore invalid env array entries', ->
expect(conversion.envArrayToObject([
'key1',
'key1=value1'
])).to.deep.equal({
key1: 'value1'
})
it 'should return an empty object with an empty input', ->
expect(conversion.envArrayToObject(null)).to.deep.equal({})
expect(conversion.envArrayToObject('')).to.deep.equal({})
expect(conversion.envArrayToObject([])).to.deep.equal({})
expect(conversion.envArrayToObject(1)).to.deep.equal({})
it 'should correctly handle whitespace', ->
expect(conversion.envArrayToObject([
'key1= test',
'key2=PI:KEY:<KEY>END_PI',
'key3=test ',
'key4= test '
'key5=PI:KEY:<KEY>END_PI',
])).to.deep.equal({
key1: ' test',
key2: 'PI:KEY:<KEY>END_PI',
key3: 'PI:KEY:<KEY>END_PI ',
key4: ' PI:KEY:<KEY>END_PI ',
key5: 'PI:KEY:<KEY>END_PI'
})
|
[
{
"context": "ist` module unit tests\n#\n# Copyright (C) 2011-2013 Nikolay Nemshilov\n#\n{Test,should} = require('lovely')\n\nTest.set \"/n",
"end": 82,
"score": 0.9998832941055298,
"start": 65,
"tag": "NAME",
"value": "Nikolay Nemshilov"
}
] | stl/dom/test/node_list_test.coffee | lovely-io/lovely.io-stl | 2 | #
# The `NodeList` module unit tests
#
# Copyright (C) 2011-2013 Nikolay Nemshilov
#
{Test,should} = require('lovely')
Test.set "/node_list.html", """
<html>
<head>
<script src="/core.js"></script>
<script src="/dom.js"></script>
</head>
<body>
<div id="one"></div>
<div id="two"></div>
<div id="three"></div>
</body>
</html>
"""
describe 'NodeList', ->
NodeList = $ = window = document = null
before Test.load "/node_list.html", (dom, win)->
$ = dom
NodeList = $.NodeList
window = win
document = win.document
describe "\b#constructor", ->
it "should accept a list of raw dom-elements as an argument", ->
element1 = document.getElementById('one')
element2 = document.getElementById('two')
search = new NodeList([element1, element2])
search.should.be.instanceOf NodeList
search.should.have.length 2
search[0].should.be.instanceOf $.Element
search[1].should.be.instanceOf $.Element
search[0]._.should.equal element1
search[1]._.should.equal element2
it "should make an empty list when called without arguments", ->
list = new NodeList()
list.length.should.equal 0
(list[0] is undefined).should.be.true
describe "DOM methods", ->
list = null
before ->
list = new $.NodeList([
document.getElementById('one'),
document.getElementById('two'),
document.getElementById('three')])
it "should call the setter methods on every item on the list", ->
list.setClass('test')
list.map('getClass').toArray().should.eql ['test', 'test', 'test']
it "should return search itself back to the code by default", ->
list.addClass('test').should.equal list
it "should return the result of the first element when calls a getter method", ->
list.attr('id').should.eql 'one'
it "should return 'null' back when the NodeList is empty", ->
(new $.NodeList([]).addClass('test') is null).should.be.true
describe "\b#exists()", ->
it "should return 'false' for empty lists", ->
list = new NodeList([])
list.exists().should.be.false
it "should return 'true' for non-empty lists", ->
list = new NodeList([document.getElementById('one')])
list.exists().should.be.true
| 38642 | #
# The `NodeList` module unit tests
#
# Copyright (C) 2011-2013 <NAME>
#
{Test,should} = require('lovely')
Test.set "/node_list.html", """
<html>
<head>
<script src="/core.js"></script>
<script src="/dom.js"></script>
</head>
<body>
<div id="one"></div>
<div id="two"></div>
<div id="three"></div>
</body>
</html>
"""
describe 'NodeList', ->
NodeList = $ = window = document = null
before Test.load "/node_list.html", (dom, win)->
$ = dom
NodeList = $.NodeList
window = win
document = win.document
describe "\b#constructor", ->
it "should accept a list of raw dom-elements as an argument", ->
element1 = document.getElementById('one')
element2 = document.getElementById('two')
search = new NodeList([element1, element2])
search.should.be.instanceOf NodeList
search.should.have.length 2
search[0].should.be.instanceOf $.Element
search[1].should.be.instanceOf $.Element
search[0]._.should.equal element1
search[1]._.should.equal element2
it "should make an empty list when called without arguments", ->
list = new NodeList()
list.length.should.equal 0
(list[0] is undefined).should.be.true
describe "DOM methods", ->
list = null
before ->
list = new $.NodeList([
document.getElementById('one'),
document.getElementById('two'),
document.getElementById('three')])
it "should call the setter methods on every item on the list", ->
list.setClass('test')
list.map('getClass').toArray().should.eql ['test', 'test', 'test']
it "should return search itself back to the code by default", ->
list.addClass('test').should.equal list
it "should return the result of the first element when calls a getter method", ->
list.attr('id').should.eql 'one'
it "should return 'null' back when the NodeList is empty", ->
(new $.NodeList([]).addClass('test') is null).should.be.true
describe "\b#exists()", ->
it "should return 'false' for empty lists", ->
list = new NodeList([])
list.exists().should.be.false
it "should return 'true' for non-empty lists", ->
list = new NodeList([document.getElementById('one')])
list.exists().should.be.true
| true | #
# The `NodeList` module unit tests
#
# Copyright (C) 2011-2013 PI:NAME:<NAME>END_PI
#
{Test,should} = require('lovely')
Test.set "/node_list.html", """
<html>
<head>
<script src="/core.js"></script>
<script src="/dom.js"></script>
</head>
<body>
<div id="one"></div>
<div id="two"></div>
<div id="three"></div>
</body>
</html>
"""
describe 'NodeList', ->
NodeList = $ = window = document = null
before Test.load "/node_list.html", (dom, win)->
$ = dom
NodeList = $.NodeList
window = win
document = win.document
describe "\b#constructor", ->
it "should accept a list of raw dom-elements as an argument", ->
element1 = document.getElementById('one')
element2 = document.getElementById('two')
search = new NodeList([element1, element2])
search.should.be.instanceOf NodeList
search.should.have.length 2
search[0].should.be.instanceOf $.Element
search[1].should.be.instanceOf $.Element
search[0]._.should.equal element1
search[1]._.should.equal element2
it "should make an empty list when called without arguments", ->
list = new NodeList()
list.length.should.equal 0
(list[0] is undefined).should.be.true
describe "DOM methods", ->
list = null
before ->
list = new $.NodeList([
document.getElementById('one'),
document.getElementById('two'),
document.getElementById('three')])
it "should call the setter methods on every item on the list", ->
list.setClass('test')
list.map('getClass').toArray().should.eql ['test', 'test', 'test']
it "should return search itself back to the code by default", ->
list.addClass('test').should.equal list
it "should return the result of the first element when calls a getter method", ->
list.attr('id').should.eql 'one'
it "should return 'null' back when the NodeList is empty", ->
(new $.NodeList([]).addClass('test') is null).should.be.true
describe "\b#exists()", ->
it "should return 'false' for empty lists", ->
list = new NodeList([])
list.exists().should.be.false
it "should return 'true' for non-empty lists", ->
list = new NodeList([document.getElementById('one')])
list.exists().should.be.true
|
[
{
"context": "dn'\n\npayload = {\n \"headers\": {\n \"x-real-ip\": \"42.121.112.219\",\n \"x-forwarded-for\": \"42.121.112.219\",\n \"h",
"end": 210,
"score": 0.9997230172157288,
"start": 196,
"tag": "IP_ADDRESS",
"value": "42.121.112.219"
},
{
"context": "al-ip\": \"42.121.112.219\",\n \"x-forwarded-for\": \"42.121.112.219\",\n \"host\": \"talk.ai\",\n \"x-nginx-proxy\": \"tr",
"end": 251,
"score": 0.9997190237045288,
"start": 237,
"tag": "IP_ADDRESS",
"value": "42.121.112.219"
},
{
"context": ":48+08:00\",\n \"url\": \"https://code.csdn.net/white715/webcnn/commit/59acbad155b77f3d03412094aab3877a1ff",
"end": 788,
"score": 0.9943603277206421,
"start": 780,
"tag": "USERNAME",
"value": "white715"
},
{
"context": "1ff2887c\",\n \"author\": {\n \"name\": \"lee715\",\n \"email\": \"li.l@huiyi-tech.com\"\n ",
"end": 891,
"score": 0.99936842918396,
"start": 885,
"tag": "USERNAME",
"value": "lee715"
},
{
"context": "{\n \"name\": \"lee715\",\n \"email\": \"li.l@huiyi-tech.com\"\n }\n },\n {\n \"id\": \"e32a60",
"end": 933,
"score": 0.9999035000801086,
"start": 914,
"tag": "EMAIL",
"value": "li.l@huiyi-tech.com"
},
{
"context": "ch.com\"\n }\n },\n {\n \"id\": \"e32a60eccbb10f434ed498c0a9b77f366e91a8dc\",\n \"mess",
"end": 983,
"score": 0.4548574388027191,
"start": 977,
"tag": "PASSWORD",
"value": "e32a60"
},
{
"context": " }\n },\n {\n \"id\": \"e32a60eccbb10f434ed498c0a9b77f366e91a8dc\",\n \"message\": \"b\\n\",\n ",
"end": 999,
"score": 0.4743441641330719,
"start": 988,
"tag": "PASSWORD",
"value": "10f434ed498"
},
{
"context": " },\n {\n \"id\": \"e32a60eccbb10f434ed498c0a9b77f366e91a8dc\",\n \"message\": \"b\\n\",\n ",
"end": 1002,
"score": 0.439108669757843,
"start": 1000,
"tag": "PASSWORD",
"value": "0a"
},
{
"context": " {\n \"id\": \"e32a60eccbb10f434ed498c0a9b77f366e91a8dc\",\n \"message\": \"b\\n\",\n \"timestamp\": ",
"end": 1017,
"score": 0.4748977720737457,
"start": 1004,
"tag": "PASSWORD",
"value": "77f366e91a8dc"
},
{
"context": "6e91a8dc\",\n \"author\": {\n \"name\": \"lee715\",\n \"email\": \"li.l@huiyi-tech.com\"\n ",
"end": 1245,
"score": 0.9996631145477295,
"start": 1239,
"tag": "USERNAME",
"value": "lee715"
},
{
"context": "{\n \"name\": \"lee715\",\n \"email\": \"li.l@huiyi-tech.com\"\n }\n }\n ],\n \"user_id\": 134214,\n",
"end": 1287,
"score": 0.9999265074729919,
"start": 1268,
"tag": "EMAIL",
"value": "li.l@huiyi-tech.com"
},
{
"context": "}\n ],\n \"user_id\": 134214,\n \"user_name\": \"white715\",\n \"repository\": {\n \"name\": \"webcnn\",\n ",
"end": 1363,
"score": 0.9988526105880737,
"start": 1355,
"tag": "USERNAME",
"value": "white715"
},
{
"context": "ository\": {\n \"name\": \"webcnn\",\n \"url\": \"git@code.csdn.net:white715/webcnn.git\",\n \"description\": \"webcn",
"end": 1441,
"score": 0.9999096393585205,
"start": 1424,
"tag": "EMAIL",
"value": "git@code.csdn.net"
},
{
"context": "ata.redirectUrl.should.eql 'https://code.csdn.net/white715/webcnn'\n",
"end": 2592,
"score": 0.9979342222213745,
"start": 2584,
"tag": "USERNAME",
"value": "white715"
}
] | test/services/csdn.coffee | jianliaoim/talk-services | 40 | should = require 'should'
requireDir = require 'require-dir'
loader = require '../../src/loader'
{req} = require '../util'
$csdn = loader.load 'csdn'
payload = {
"headers": {
"x-real-ip": "42.121.112.219",
"x-forwarded-for": "42.121.112.219",
"host": "talk.ai",
"x-nginx-proxy": "true",
"connection": "Upgrade",
"content-length": "1128",
"content-type": "application/json"
},
"query": {},
"body": {
"before": "5dff974d0fb8cbfd8d8c063050866e0e6593ea70",
"after": "59acbad155b77f3d03412094aab3877a1ff2887c",
"ref": "refs/heads/master",
"commits": [
{
"id": "59acbad155b77f3d03412094aab3877a1ff2887c",
"message": "c\n",
"timestamp": "2015-06-30T11:24:48+08:00",
"url": "https://code.csdn.net/white715/webcnn/commit/59acbad155b77f3d03412094aab3877a1ff2887c",
"author": {
"name": "lee715",
"email": "li.l@huiyi-tech.com"
}
},
{
"id": "e32a60eccbb10f434ed498c0a9b77f366e91a8dc",
"message": "b\n",
"timestamp": "2015-06-30T11:24:41+08:00",
"url": "https://code.csdn.net/white715/webcnn/commit/e32a60eccbb10f434ed498c0a9b77f366e91a8dc",
"author": {
"name": "lee715",
"email": "li.l@huiyi-tech.com"
}
}
],
"user_id": 134214,
"user_name": "white715",
"repository": {
"name": "webcnn",
"url": "git@code.csdn.net:white715/webcnn.git",
"description": "webcnn",
"homepage": "https://code.csdn.net/white715/webcnn"
},
"total_commits_count": 2
}
}
testWebhook = (payload) ->
# Overwrite the sendMessage function of coding
req.body = payload.body
$csdn.then (csdn) -> csdn.receiveEvent 'service.webhook', req
describe 'Csdn#Webhook', ->
req.integration =
_id: '552cc903022844e6d8afb3b4'
category: 'coding'
it 'receive zen', ->
testWebhook {}
.then (message) -> should(message).be.empty
it 'receive push', ->
testWebhook payload
.then (message) ->
message.attachments[0].data.title.should.eql '[webcnn] 提交了新的代码'
message.attachments[0].data.text.should.eql [
'<a href="https://code.csdn.net/white715/webcnn/commit/59acbad155b77f3d03412094aab3877a1ff2887c" target="_blank">'
'<code>59acba:</code></a> c\n<br>'
'<a href="https://code.csdn.net/white715/webcnn/commit/e32a60eccbb10f434ed498c0a9b77f366e91a8dc" target="_blank">'
'<code>e32a60:</code></a> b\n<br>'
].join ''
message.attachments[0].data.redirectUrl.should.eql 'https://code.csdn.net/white715/webcnn'
| 140045 | should = require 'should'
requireDir = require 'require-dir'
loader = require '../../src/loader'
{req} = require '../util'
$csdn = loader.load 'csdn'
payload = {
"headers": {
"x-real-ip": "172.16.31.10",
"x-forwarded-for": "172.16.31.10",
"host": "talk.ai",
"x-nginx-proxy": "true",
"connection": "Upgrade",
"content-length": "1128",
"content-type": "application/json"
},
"query": {},
"body": {
"before": "5dff974d0fb8cbfd8d8c063050866e0e6593ea70",
"after": "59acbad155b77f3d03412094aab3877a1ff2887c",
"ref": "refs/heads/master",
"commits": [
{
"id": "59acbad155b77f3d03412094aab3877a1ff2887c",
"message": "c\n",
"timestamp": "2015-06-30T11:24:48+08:00",
"url": "https://code.csdn.net/white715/webcnn/commit/59acbad155b77f3d03412094aab3877a1ff2887c",
"author": {
"name": "lee715",
"email": "<EMAIL>"
}
},
{
"id": "<PASSWORD>eccbb<PASSWORD>c<PASSWORD>9b<PASSWORD>",
"message": "b\n",
"timestamp": "2015-06-30T11:24:41+08:00",
"url": "https://code.csdn.net/white715/webcnn/commit/e32a60eccbb10f434ed498c0a9b77f366e91a8dc",
"author": {
"name": "lee715",
"email": "<EMAIL>"
}
}
],
"user_id": 134214,
"user_name": "white715",
"repository": {
"name": "webcnn",
"url": "<EMAIL>:white715/webcnn.git",
"description": "webcnn",
"homepage": "https://code.csdn.net/white715/webcnn"
},
"total_commits_count": 2
}
}
testWebhook = (payload) ->
# Overwrite the sendMessage function of coding
req.body = payload.body
$csdn.then (csdn) -> csdn.receiveEvent 'service.webhook', req
describe 'Csdn#Webhook', ->
req.integration =
_id: '552cc903022844e6d8afb3b4'
category: 'coding'
it 'receive zen', ->
testWebhook {}
.then (message) -> should(message).be.empty
it 'receive push', ->
testWebhook payload
.then (message) ->
message.attachments[0].data.title.should.eql '[webcnn] 提交了新的代码'
message.attachments[0].data.text.should.eql [
'<a href="https://code.csdn.net/white715/webcnn/commit/59acbad155b77f3d03412094aab3877a1ff2887c" target="_blank">'
'<code>59acba:</code></a> c\n<br>'
'<a href="https://code.csdn.net/white715/webcnn/commit/e32a60eccbb10f434ed498c0a9b77f366e91a8dc" target="_blank">'
'<code>e32a60:</code></a> b\n<br>'
].join ''
message.attachments[0].data.redirectUrl.should.eql 'https://code.csdn.net/white715/webcnn'
| true | should = require 'should'
requireDir = require 'require-dir'
loader = require '../../src/loader'
{req} = require '../util'
$csdn = loader.load 'csdn'
payload = {
"headers": {
"x-real-ip": "PI:IP_ADDRESS:172.16.31.10END_PI",
"x-forwarded-for": "PI:IP_ADDRESS:172.16.31.10END_PI",
"host": "talk.ai",
"x-nginx-proxy": "true",
"connection": "Upgrade",
"content-length": "1128",
"content-type": "application/json"
},
"query": {},
"body": {
"before": "5dff974d0fb8cbfd8d8c063050866e0e6593ea70",
"after": "59acbad155b77f3d03412094aab3877a1ff2887c",
"ref": "refs/heads/master",
"commits": [
{
"id": "59acbad155b77f3d03412094aab3877a1ff2887c",
"message": "c\n",
"timestamp": "2015-06-30T11:24:48+08:00",
"url": "https://code.csdn.net/white715/webcnn/commit/59acbad155b77f3d03412094aab3877a1ff2887c",
"author": {
"name": "lee715",
"email": "PI:EMAIL:<EMAIL>END_PI"
}
},
{
"id": "PI:PASSWORD:<PASSWORD>END_PIeccbbPI:PASSWORD:<PASSWORD>END_PIcPI:PASSWORD:<PASSWORD>END_PI9bPI:PASSWORD:<PASSWORD>END_PI",
"message": "b\n",
"timestamp": "2015-06-30T11:24:41+08:00",
"url": "https://code.csdn.net/white715/webcnn/commit/e32a60eccbb10f434ed498c0a9b77f366e91a8dc",
"author": {
"name": "lee715",
"email": "PI:EMAIL:<EMAIL>END_PI"
}
}
],
"user_id": 134214,
"user_name": "white715",
"repository": {
"name": "webcnn",
"url": "PI:EMAIL:<EMAIL>END_PI:white715/webcnn.git",
"description": "webcnn",
"homepage": "https://code.csdn.net/white715/webcnn"
},
"total_commits_count": 2
}
}
testWebhook = (payload) ->
# Overwrite the sendMessage function of coding
req.body = payload.body
$csdn.then (csdn) -> csdn.receiveEvent 'service.webhook', req
describe 'Csdn#Webhook', ->
req.integration =
_id: '552cc903022844e6d8afb3b4'
category: 'coding'
it 'receive zen', ->
testWebhook {}
.then (message) -> should(message).be.empty
it 'receive push', ->
testWebhook payload
.then (message) ->
message.attachments[0].data.title.should.eql '[webcnn] 提交了新的代码'
message.attachments[0].data.text.should.eql [
'<a href="https://code.csdn.net/white715/webcnn/commit/59acbad155b77f3d03412094aab3877a1ff2887c" target="_blank">'
'<code>59acba:</code></a> c\n<br>'
'<a href="https://code.csdn.net/white715/webcnn/commit/e32a60eccbb10f434ed498c0a9b77f366e91a8dc" target="_blank">'
'<code>e32a60:</code></a> b\n<br>'
].join ''
message.attachments[0].data.redirectUrl.should.eql 'https://code.csdn.net/white715/webcnn'
|
[
{
"context": "###\n- Author : Iain M Hamilton - <iain@beakable.com> - http://www.beakable.com\n ",
"end": 30,
"score": 0.9998841881752014,
"start": 15,
"tag": "NAME",
"value": "Iain M Hamilton"
},
{
"context": "###\n- Author : Iain M Hamilton - <iain@beakable.com> - http://www.beakable.com\n Twitter: @beakable\n#",
"end": 51,
"score": 0.9999306201934814,
"start": 34,
"tag": "EMAIL",
"value": "iain@beakable.com"
},
{
"context": "beakable.com> - http://www.beakable.com\n Twitter: @beakable\n###\n\n###* jsiso/utils simple common functions use",
"end": 99,
"score": 0.9869592785835266,
"start": 90,
"tag": "USERNAME",
"value": "@beakable"
}
] | jsiso/utils.coffee | WahlbergRu/Go-In-Shadow | 0 | ###
- Author : Iain M Hamilton - <iain@beakable.com> - http://www.beakable.com
Twitter: @beakable
###
###* jsiso/utils simple common functions used throughout JsIso *###
define ->
{
roundTo: (num, dec) ->
Math.round(num * 10 ** dec) / 10 ** dec
rand: (l, u) ->
Math.floor Math.random() * (u - l + 1) + l
remove: (from, to) ->
rest = @slice((to or from) + 1 or @length)
@length = if from < 0 then @length + from else from
@push.apply this, rest
range: (from, to) ->
{
from: from
to: to
}
flipTwoDArray: (arrayLayout, direction) ->
tempArray = []
tempLine = []
i = undefined
j = undefined
if direction == 'horizontal'
i = arrayLayout.length - 1
while i >= 0
j = 0
while j < arrayLayout[i].length
tempLine.push arrayLayout[i][j]
j++
tempArray.push tempLine
tempLine = []
i--
return tempArray
else if direction == 'vertical'
i = 0
while i < arrayLayout.length
j = arrayLayout[i].length - 1
while j >= 0
tempLine.push arrayLayout[i][j]
j--
tempArray.push tempLine
tempLine = []
i++
return tempArray
rotateTwoDArray: (arrayLayout, direction) ->
tempArray = []
tempLine = []
i = undefined
j = undefined
w = arrayLayout.length
h = if arrayLayout[0] then arrayLayout[0].length else 0
if direction == 'left'
i = 0
while i < h
j = 0
while j < w
if !tempArray[i]
tempArray[i] = []
tempArray[i][j] = arrayLayout[w - j - 1][i]
j++
i++
return tempArray
else if direction == 'right'
i = 0
while i < h
j = 0
while j < w
if !tempArray[i]
tempArray[i] = []
tempArray[i][j] = arrayLayout[j][h - i - 1]
j++
i++
return tempArray
lineSplit: (ctx, text, width) ->
textLines = []
elements = ''
line = ''
tempLine = ''
lastword = null
if ctx.measureText(text).width > width
elements = text.split(' ')
i = 0
while i < elements.length
tempLine += elements[i] + ' '
if ctx.measureText(tempLine).width < width
line += elements[i] + ' '
lastword = elements[i]
else
if lastword and lastword != elements[i]
# Prevent getitng locked in a large word
i--
textLines.push line
else
textLines.push tempLine
line = ''
tempLine = ''
i++
else
textLines[0] = text
if line != ''
textLines.push line
textLines
}
| 149148 | ###
- Author : <NAME> - <<EMAIL>> - http://www.beakable.com
Twitter: @beakable
###
###* jsiso/utils simple common functions used throughout JsIso *###
define ->
{
roundTo: (num, dec) ->
Math.round(num * 10 ** dec) / 10 ** dec
rand: (l, u) ->
Math.floor Math.random() * (u - l + 1) + l
remove: (from, to) ->
rest = @slice((to or from) + 1 or @length)
@length = if from < 0 then @length + from else from
@push.apply this, rest
range: (from, to) ->
{
from: from
to: to
}
flipTwoDArray: (arrayLayout, direction) ->
tempArray = []
tempLine = []
i = undefined
j = undefined
if direction == 'horizontal'
i = arrayLayout.length - 1
while i >= 0
j = 0
while j < arrayLayout[i].length
tempLine.push arrayLayout[i][j]
j++
tempArray.push tempLine
tempLine = []
i--
return tempArray
else if direction == 'vertical'
i = 0
while i < arrayLayout.length
j = arrayLayout[i].length - 1
while j >= 0
tempLine.push arrayLayout[i][j]
j--
tempArray.push tempLine
tempLine = []
i++
return tempArray
rotateTwoDArray: (arrayLayout, direction) ->
tempArray = []
tempLine = []
i = undefined
j = undefined
w = arrayLayout.length
h = if arrayLayout[0] then arrayLayout[0].length else 0
if direction == 'left'
i = 0
while i < h
j = 0
while j < w
if !tempArray[i]
tempArray[i] = []
tempArray[i][j] = arrayLayout[w - j - 1][i]
j++
i++
return tempArray
else if direction == 'right'
i = 0
while i < h
j = 0
while j < w
if !tempArray[i]
tempArray[i] = []
tempArray[i][j] = arrayLayout[j][h - i - 1]
j++
i++
return tempArray
lineSplit: (ctx, text, width) ->
textLines = []
elements = ''
line = ''
tempLine = ''
lastword = null
if ctx.measureText(text).width > width
elements = text.split(' ')
i = 0
while i < elements.length
tempLine += elements[i] + ' '
if ctx.measureText(tempLine).width < width
line += elements[i] + ' '
lastword = elements[i]
else
if lastword and lastword != elements[i]
# Prevent getitng locked in a large word
i--
textLines.push line
else
textLines.push tempLine
line = ''
tempLine = ''
i++
else
textLines[0] = text
if line != ''
textLines.push line
textLines
}
| true | ###
- Author : PI:NAME:<NAME>END_PI - <PI:EMAIL:<EMAIL>END_PI> - http://www.beakable.com
Twitter: @beakable
###
###* jsiso/utils simple common functions used throughout JsIso *###
define ->
{
roundTo: (num, dec) ->
Math.round(num * 10 ** dec) / 10 ** dec
rand: (l, u) ->
Math.floor Math.random() * (u - l + 1) + l
remove: (from, to) ->
rest = @slice((to or from) + 1 or @length)
@length = if from < 0 then @length + from else from
@push.apply this, rest
range: (from, to) ->
{
from: from
to: to
}
flipTwoDArray: (arrayLayout, direction) ->
tempArray = []
tempLine = []
i = undefined
j = undefined
if direction == 'horizontal'
i = arrayLayout.length - 1
while i >= 0
j = 0
while j < arrayLayout[i].length
tempLine.push arrayLayout[i][j]
j++
tempArray.push tempLine
tempLine = []
i--
return tempArray
else if direction == 'vertical'
i = 0
while i < arrayLayout.length
j = arrayLayout[i].length - 1
while j >= 0
tempLine.push arrayLayout[i][j]
j--
tempArray.push tempLine
tempLine = []
i++
return tempArray
rotateTwoDArray: (arrayLayout, direction) ->
tempArray = []
tempLine = []
i = undefined
j = undefined
w = arrayLayout.length
h = if arrayLayout[0] then arrayLayout[0].length else 0
if direction == 'left'
i = 0
while i < h
j = 0
while j < w
if !tempArray[i]
tempArray[i] = []
tempArray[i][j] = arrayLayout[w - j - 1][i]
j++
i++
return tempArray
else if direction == 'right'
i = 0
while i < h
j = 0
while j < w
if !tempArray[i]
tempArray[i] = []
tempArray[i][j] = arrayLayout[j][h - i - 1]
j++
i++
return tempArray
lineSplit: (ctx, text, width) ->
textLines = []
elements = ''
line = ''
tempLine = ''
lastword = null
if ctx.measureText(text).width > width
elements = text.split(' ')
i = 0
while i < elements.length
tempLine += elements[i] + ' '
if ctx.measureText(tempLine).width < width
line += elements[i] + ' '
lastword = elements[i]
else
if lastword and lastword != elements[i]
# Prevent getitng locked in a large word
i--
textLines.push line
else
textLines.push tempLine
line = ''
tempLine = ''
i++
else
textLines[0] = text
if line != ''
textLines.push line
textLines
}
|
[
{
"context": "parsed_parent_key'\n bucket_key: 'BUCKET.key'\n\n link_generator: Drug.getDru",
"end": 10583,
"score": 0.6168470978736877,
"start": 10577,
"tag": "KEY",
"value": "BUCKET"
},
{
"context": "template_data:\n bucket_key: 'BUCKET.key'\n link_generator: Target.g",
"end": 13942,
"score": 0.5101523399353027,
"start": 13936,
"tag": "KEY",
"value": "BUCKET"
}
] | src/glados/static/coffee/MainPageApp.coffee | BNext-IQT/glados-frontend-chembl-main-interface | 33 | # Class in charge of rendering the index page of the ChEMBL web ui
class MainPageApp
# ----------------------------------------------------------------------------------------------------------------------
# Initialization
# ----------------------------------------------------------------------------------------------------------------------
@init = ->
glados.apps.Main.MainGladosApp.hideMainSplashScreen()
new glados.views.MainPage.VisualisationsWithCaptionsView
el: $('.BCK-visualisations-with-captions')
@initAssociatedResources()
@initDatabaseSummary()
@initTweets()
@initBlogEntries()
@initGithubDetails()
# ----------------------------------------------------------------------------------------------------------------------
# Init functions
# ----------------------------------------------------------------------------------------------------------------------
@initTargetClassificationSunburst = ($browseButtonContainer) ->
config =
browse_all_link: "#{glados.Settings.GLADOS_BASE_URL_FULL}/g/#browse/targets"
browse_button: true
browse_button_container: $browseButtonContainer
entity_name_plural: Target.prototype.entityNamePlural
view = new glados.views.MainPage.TargetClassificationsSunburstsView
el: $('#BCK-protein-classification-zoomburst')
config: config
return view
@initAssayClassificationSunburst = ($browseButtonContainer) ->
config =
browse_all_link: "#{glados.Settings.GLADOS_BASE_URL_FULL}/g/#browse/assays"
browse_button: true
browse_button_container: $browseButtonContainer
entity_name_plural: Assay.prototype.entityNamePlural
view = new glados.views.MainPage.AssayClassificationsSunburstsView
el: $('#BCK-assay-classification-zoomburst')
config: config
return view
@initBrowseEntities = ->
return new glados.views.MainPage.BrowseEntitiesAsCirclesView
el: $('#BrowseEntitiesAsCircles')
@initBrowseCovidEntities = ->
return new glados.views.MainPage.BrowseCovidEntitiesAsCirclesView
el: $('#BrowseCovidEntitiesAsCircles')
@initMaxPhaseForDisease = ->
maxPhaseForDisease = MainPageApp.getMaxPhaseForDiseaseAgg()
maxPhaseProp = glados.models.visualisation.PropertiesFactory.getPropertyConfigFor('Compound', 'MAX_PHASE', true)
diseaseClassProp = glados.models.visualisation.PropertiesFactory.getPropertyConfigFor('Compound', 'DISEASE')
pieConfig =
side_legend: true
x_axis_prop_name: 'maxPhaseForDisease'
split_series_prop_name: 'split_series_agg'
title: 'Max Phase for Disease'
max_categories: 5
stacked_donut: true
stacked_levels: 2
hide_title: true
properties:
max_phase: maxPhaseProp
disease_class: diseaseClassProp
initial_property_x: 'max_phase'
initial_property_z: 'disease_class'
title_link_url: Drug.getDrugsListURL()
config =
pie_config: pieConfig
is_outside_an_entity_report_card: true
disable_embedding: true
embed_url: "#{glados.Settings.GLADOS_BASE_URL_FULL}embed/#max_phase_for_disease"
view_name: 'Visualisation-DrugsByMaxPhaseAndDisease'
view_type: glados.views.base.TrackView.viewTypes.VISUALISATION
link_to_all:
link_text: 'See all drug Compounds in ChEMBL'
url: Drug.getDrugsListURL()
view = new glados.views.ReportCards.PieInCardView
el: $('#MaxPhaseForDisease')
model: maxPhaseForDisease
config: config
report_card_app: @
maxPhaseForDisease.fetch()
return view
@initFirstApprovalByMoleculeType = ->
drugsByMoleculeTypeAgg = MainPageApp.getFirstApprovalPercentage()
approvalDateProp = glados.models.visualisation.PropertiesFactory.getPropertyConfigFor('Compound', 'FIRST_APPROVAL')
moleculeTypeProp = glados.models.visualisation.PropertiesFactory.getPropertyConfigFor('Compound', 'MOLECULE_TYPE', true)
barsColourScale = moleculeTypeProp.colourScale
histogramConfig =
bars_colour_scale: barsColourScale
stacked_histogram: true
sort_by_key: false
rotate_x_axis_if_needed: true
hide_x_axis_title: true
legend_vertical: true
big_size: true
paint_axes_selectors: true
properties:
year: approvalDateProp
molecule_type: moleculeTypeProp
initial_property_x: 'year'
initial_property_z: 'molecule_type'
x_axis_options: ['count']
x_axis_min_columns: 1
x_axis_max_columns: 40
x_axis_initial_num_columns: 40
x_axis_prop_name: 'firstApprovalByMoleculeType'
y_scale_mode: 'percentage'
title: 'Drugs By Molecule Type and First Approval'
title_link_url: Drug.getDrugsListURL('_exists_:first_approval')
config =
histogram_config: histogramConfig
disable_embedding: true
is_outside_an_entity_report_card: true
view_name: 'Visualisation-DrugsByMoleculeTypeAndFirstApproval'
view_type: glados.views.base.TrackView.viewTypes.VISUALISATION
# embed_url: "#{glados.Settings.GLADOS_BASE_URL_FULL}embed/#documents_by_year_histogram"
view = new glados.views.ReportCards.HistogramInCardView
el: $('#BCK-FirstApprovalHistogram')
model: drugsByMoleculeTypeAgg
config: config
report_card_app: @
drugsByMoleculeTypeAgg.fetch()
return view
@initDrugsPerUsanYear = ->
allDrugsByYear = glados.apps.VisualisePageApp.getYearByMaxPhaseAgg()
usanYearProp = glados.models.visualisation.PropertiesFactory.getPropertyConfigFor('Compound', 'USAN_YEAR')
maxPhaseProp = glados.models.visualisation.PropertiesFactory.getPropertyConfigFor('Compound', 'MAX_PHASE', true)
barsColourScale = maxPhaseProp.colourScale
histogramConfig =
bars_colour_scale: barsColourScale
stacked_histogram: true
sort_by_key: true
rotate_x_axis_if_needed: false
hide_x_axis_title: true
y_scale_mode: 'normal'
legend_vertical: true
big_size: true
paint_axes_selectors: true
properties:
year: usanYearProp
max_phase: maxPhaseProp
initial_property_x: 'year'
initial_property_z: 'max_phase'
x_axis_options: ['count']
x_axis_min_columns: 1
x_axis_max_columns: 40
x_axis_initial_num_columns: 40
x_axis_prop_name: 'yearByMaxPhase'
title: 'Drugs by Usan Year'
title_link_url: Drug.getDrugsListURL('_metadata.compound_records.src_id:13 AND _exists_:usan_year')
config =
histogram_config: histogramConfig
is_outside_an_entity_report_card: true
disable_embedding: true
view_name: 'Visualisation-DrugsByUsanYear'
view_type: glados.views.base.TrackView.viewTypes.VISUALISATION
# embed_url: "#{glados.Settings.GLADOS_BASE_URL_FULL}embed/#documents_by_year_histogram"
view = new glados.views.ReportCards.HistogramInCardView
el: $('#PapersPerYearHistogram')
model: allDrugsByYear
config: config
report_card_app: @
allDrugsByYear.fetch()
return view
@initTargetsVisualisation = ($browseButtonContainer) ->
targetHierarchyAgg = MainPageApp.getTargetsOrganismTreeAgg()
config =
is_outside_an_entity_report_card: true
disable_embedding: true
embed_url: "#{glados.Settings.GLADOS_BASE_URL_FULL}embed/#targets_by_protein_class"
view_class: BrowseTargetAsCirclesView
view_name: 'Visualisation-TargetBrowserAsCircles'
view_type: glados.views.base.TrackView.viewTypes.VISUALISATION
view_config:
browse_button_container: $browseButtonContainer
view = new glados.views.ReportCards.VisualisationInCardView
el: $('#BCK-TargetBrowserAsCircles')
model: targetHierarchyAgg
config: config
report_card_app: @
targetHierarchyAgg.fetch()
return view
@initDatabaseSummary = ->
databaseInfo = new glados.models.MainPage.DatabaseSummaryInfo()
new glados.views.MainPage.DatabaseSummaryView
model: databaseInfo
el: $('.BCK-Database-summary-info')
databaseInfo.fetch()
@initAssociatedResources = ->
new glados.views.MainPage.AssociatedResourcesView
el: $('.BCK-Associated-resources')
@initTweets = ->
tweetsList = glados.models.paginatedCollections.PaginatedCollectionFactory.getNewTweetsList()
tweetsList.initURL()
$tweetsElem = $('.BCK-Tweets-container')
glados.views.PaginatedViews.PaginatedViewFactory.getNewInfinitePaginatedView(tweetsList, $tweetsElem, 'do-repaint')
tweetsList.fetch()
@initBlogEntries = ->
blogEntriesList = glados.models.paginatedCollections.PaginatedCollectionFactory.getNewBlogEntriesList()
blogEntriesList.initURL()
$blogEntriesElem = $('.BCK-Blog-Entries-container')
glados.views.PaginatedViews.PaginatedViewFactory.getNewInfinitePaginatedView(blogEntriesList, $blogEntriesElem, 'do-repaint')
blogEntriesList.fetch()
@initGithubDetails = ->
new glados.views.MainPage.GitHubDetailsView
el: $('.BCK-github-details')
# ----------------------------------------------------------------------------------------------------------------------
# Aggregations
# ----------------------------------------------------------------------------------------------------------------------
@getFirstApprovalPercentage = (defaultInterval = 1) ->
queryConfig =
type: glados.models.Aggregations.Aggregation.QueryTypes.QUERY_STRING
query_string_template: '_metadata.drug.is_drug:true'
template_data: {}
aggsConfig =
aggs:
firstApprovalByMoleculeType:
type: glados.models.Aggregations.Aggregation.AggTypes.HISTOGRAM
field: 'first_approval'
default_interval_size: defaultInterval
min_interval_size: 1
max_interval_size: 10
bucket_key_parse_function: (key) -> key.replace(/\.0/i, '')
bucket_sort_compare_function: (bucketA, bucketB) ->
yearA = parseFloat(bucketA.key)
yearB = parseFloat(bucketB.key)
if yearA < yearB
return -1
else if yearA > yearB
return 1
return 0
aggs:
molecule_type:
type: glados.models.Aggregations.Aggregation.AggTypes.TERMS
field: 'molecule_type'
size: 10
bucket_links:
bucket_filter_template: 'first_approval:{{year}} AND molecule_type:"{{bucket_key}}"'
template_data:
year: 'BUCKET.parsed_parent_key'
bucket_key: 'BUCKET.key'
link_generator: Drug.getDrugsListURL
moleculeTypeByYear = new glados.models.Aggregations.Aggregation
index_url: glados.models.Aggregations.Aggregation.COMPOUND_INDEX_URL
query_config: queryConfig
aggs_config: aggsConfig
return moleculeTypeByYear
@getMaxPhaseForDiseaseAgg = () ->
queryConfig =
type: glados.models.Aggregations.Aggregation.QueryTypes.QUERY_STRING
query_string_template: '_metadata.drug.is_drug:true'
template_data: {}
aggsConfig =
aggs:
maxPhaseForDisease:
type: glados.models.Aggregations.Aggregation.AggTypes.TERMS
field: 'max_phase'
size: 5
bucket_links:
bucket_filter_template: '_metadata.drug.is_drug:true AND ' +
'max_phase:{{bucket_key}}'
template_data:
bucket_key: 'BUCKET.key'
link_generator: Compound.getCompoundsListURL
aggs:
split_series_agg:
type: glados.models.Aggregations.Aggregation.AggTypes.TERMS
field: '_metadata.drug_indications.efo_term'
size: 12
bucket_links:
bucket_filter_template: '_metadata.drug.is_drug:true AND ' +
'max_phase :{{max_phase}} AND _metadata.drug_indications.efo_term:("{{bucket_key}}"' +
'{{#each extra_buckets}} OR "{{this}}"{{/each}})'
template_data:
max_phase: 'BUCKET.parent_key'
bucket_key: 'BUCKET.key'
extra_buckets: 'EXTRA_BUCKETS.key'
link_generator: Compound.getCompoundsListURL
MaxPhaseForDisease = new glados.models.Aggregations.Aggregation
index_url: glados.models.Aggregations.Aggregation.COMPOUND_INDEX_URL
query_config: queryConfig
aggs_config: aggsConfig
return MaxPhaseForDisease
@getTargetsOrganismTreeAgg = ->
queryConfig =
type: glados.models.Aggregations.Aggregation.QueryTypes.QUERY_STRING
query_string_template: '*'
template_data: {}
aggsConfig =
aggs:
children:
type: glados.models.Aggregations.Aggregation.AggTypes.TERMS
field: '_metadata.organism_taxonomy.l1'
size: 50
bucket_links:
bucket_filter_template: '_metadata.organism_taxonomy.l1:("{{bucket_key}}")'
template_data:
bucket_key: 'BUCKET.key'
link_generator: Target.getTargetsListURL
aggs:
children:
type: glados.models.Aggregations.Aggregation.AggTypes.TERMS
field: '_metadata.organism_taxonomy.l2'
size: 50
bucket_links:
bucket_filter_template: '_metadata.organism_taxonomy.l2:("{{bucket_key}}")'
template_data:
bucket_key: 'BUCKET.key'
link_generator: Target.getTargetsListURL
aggs:
children:
type: glados.models.Aggregations.Aggregation.AggTypes.TERMS
field: '_metadata.organism_taxonomy.l3'
size: 50
bucket_links:
bucket_filter_template: '_metadata.organism_taxonomy.l3:("{{bucket_key}}")'
template_data:
bucket_key: 'BUCKET.key'
link_generator: Target.getTargetsListURL
organismTreeAgg = new glados.models.Aggregations.Aggregation
index_url: glados.models.Aggregations.Aggregation.TARGET_INDEX_URL
query_config: queryConfig
aggs_config: aggsConfig
return organismTreeAgg
| 23624 | # Class in charge of rendering the index page of the ChEMBL web ui
class MainPageApp
# ----------------------------------------------------------------------------------------------------------------------
# Initialization
# ----------------------------------------------------------------------------------------------------------------------
@init = ->
glados.apps.Main.MainGladosApp.hideMainSplashScreen()
new glados.views.MainPage.VisualisationsWithCaptionsView
el: $('.BCK-visualisations-with-captions')
@initAssociatedResources()
@initDatabaseSummary()
@initTweets()
@initBlogEntries()
@initGithubDetails()
# ----------------------------------------------------------------------------------------------------------------------
# Init functions
# ----------------------------------------------------------------------------------------------------------------------
@initTargetClassificationSunburst = ($browseButtonContainer) ->
config =
browse_all_link: "#{glados.Settings.GLADOS_BASE_URL_FULL}/g/#browse/targets"
browse_button: true
browse_button_container: $browseButtonContainer
entity_name_plural: Target.prototype.entityNamePlural
view = new glados.views.MainPage.TargetClassificationsSunburstsView
el: $('#BCK-protein-classification-zoomburst')
config: config
return view
@initAssayClassificationSunburst = ($browseButtonContainer) ->
config =
browse_all_link: "#{glados.Settings.GLADOS_BASE_URL_FULL}/g/#browse/assays"
browse_button: true
browse_button_container: $browseButtonContainer
entity_name_plural: Assay.prototype.entityNamePlural
view = new glados.views.MainPage.AssayClassificationsSunburstsView
el: $('#BCK-assay-classification-zoomburst')
config: config
return view
@initBrowseEntities = ->
return new glados.views.MainPage.BrowseEntitiesAsCirclesView
el: $('#BrowseEntitiesAsCircles')
@initBrowseCovidEntities = ->
return new glados.views.MainPage.BrowseCovidEntitiesAsCirclesView
el: $('#BrowseCovidEntitiesAsCircles')
@initMaxPhaseForDisease = ->
maxPhaseForDisease = MainPageApp.getMaxPhaseForDiseaseAgg()
maxPhaseProp = glados.models.visualisation.PropertiesFactory.getPropertyConfigFor('Compound', 'MAX_PHASE', true)
diseaseClassProp = glados.models.visualisation.PropertiesFactory.getPropertyConfigFor('Compound', 'DISEASE')
pieConfig =
side_legend: true
x_axis_prop_name: 'maxPhaseForDisease'
split_series_prop_name: 'split_series_agg'
title: 'Max Phase for Disease'
max_categories: 5
stacked_donut: true
stacked_levels: 2
hide_title: true
properties:
max_phase: maxPhaseProp
disease_class: diseaseClassProp
initial_property_x: 'max_phase'
initial_property_z: 'disease_class'
title_link_url: Drug.getDrugsListURL()
config =
pie_config: pieConfig
is_outside_an_entity_report_card: true
disable_embedding: true
embed_url: "#{glados.Settings.GLADOS_BASE_URL_FULL}embed/#max_phase_for_disease"
view_name: 'Visualisation-DrugsByMaxPhaseAndDisease'
view_type: glados.views.base.TrackView.viewTypes.VISUALISATION
link_to_all:
link_text: 'See all drug Compounds in ChEMBL'
url: Drug.getDrugsListURL()
view = new glados.views.ReportCards.PieInCardView
el: $('#MaxPhaseForDisease')
model: maxPhaseForDisease
config: config
report_card_app: @
maxPhaseForDisease.fetch()
return view
@initFirstApprovalByMoleculeType = ->
drugsByMoleculeTypeAgg = MainPageApp.getFirstApprovalPercentage()
approvalDateProp = glados.models.visualisation.PropertiesFactory.getPropertyConfigFor('Compound', 'FIRST_APPROVAL')
moleculeTypeProp = glados.models.visualisation.PropertiesFactory.getPropertyConfigFor('Compound', 'MOLECULE_TYPE', true)
barsColourScale = moleculeTypeProp.colourScale
histogramConfig =
bars_colour_scale: barsColourScale
stacked_histogram: true
sort_by_key: false
rotate_x_axis_if_needed: true
hide_x_axis_title: true
legend_vertical: true
big_size: true
paint_axes_selectors: true
properties:
year: approvalDateProp
molecule_type: moleculeTypeProp
initial_property_x: 'year'
initial_property_z: 'molecule_type'
x_axis_options: ['count']
x_axis_min_columns: 1
x_axis_max_columns: 40
x_axis_initial_num_columns: 40
x_axis_prop_name: 'firstApprovalByMoleculeType'
y_scale_mode: 'percentage'
title: 'Drugs By Molecule Type and First Approval'
title_link_url: Drug.getDrugsListURL('_exists_:first_approval')
config =
histogram_config: histogramConfig
disable_embedding: true
is_outside_an_entity_report_card: true
view_name: 'Visualisation-DrugsByMoleculeTypeAndFirstApproval'
view_type: glados.views.base.TrackView.viewTypes.VISUALISATION
# embed_url: "#{glados.Settings.GLADOS_BASE_URL_FULL}embed/#documents_by_year_histogram"
view = new glados.views.ReportCards.HistogramInCardView
el: $('#BCK-FirstApprovalHistogram')
model: drugsByMoleculeTypeAgg
config: config
report_card_app: @
drugsByMoleculeTypeAgg.fetch()
return view
@initDrugsPerUsanYear = ->
allDrugsByYear = glados.apps.VisualisePageApp.getYearByMaxPhaseAgg()
usanYearProp = glados.models.visualisation.PropertiesFactory.getPropertyConfigFor('Compound', 'USAN_YEAR')
maxPhaseProp = glados.models.visualisation.PropertiesFactory.getPropertyConfigFor('Compound', 'MAX_PHASE', true)
barsColourScale = maxPhaseProp.colourScale
histogramConfig =
bars_colour_scale: barsColourScale
stacked_histogram: true
sort_by_key: true
rotate_x_axis_if_needed: false
hide_x_axis_title: true
y_scale_mode: 'normal'
legend_vertical: true
big_size: true
paint_axes_selectors: true
properties:
year: usanYearProp
max_phase: maxPhaseProp
initial_property_x: 'year'
initial_property_z: 'max_phase'
x_axis_options: ['count']
x_axis_min_columns: 1
x_axis_max_columns: 40
x_axis_initial_num_columns: 40
x_axis_prop_name: 'yearByMaxPhase'
title: 'Drugs by Usan Year'
title_link_url: Drug.getDrugsListURL('_metadata.compound_records.src_id:13 AND _exists_:usan_year')
config =
histogram_config: histogramConfig
is_outside_an_entity_report_card: true
disable_embedding: true
view_name: 'Visualisation-DrugsByUsanYear'
view_type: glados.views.base.TrackView.viewTypes.VISUALISATION
# embed_url: "#{glados.Settings.GLADOS_BASE_URL_FULL}embed/#documents_by_year_histogram"
view = new glados.views.ReportCards.HistogramInCardView
el: $('#PapersPerYearHistogram')
model: allDrugsByYear
config: config
report_card_app: @
allDrugsByYear.fetch()
return view
@initTargetsVisualisation = ($browseButtonContainer) ->
targetHierarchyAgg = MainPageApp.getTargetsOrganismTreeAgg()
config =
is_outside_an_entity_report_card: true
disable_embedding: true
embed_url: "#{glados.Settings.GLADOS_BASE_URL_FULL}embed/#targets_by_protein_class"
view_class: BrowseTargetAsCirclesView
view_name: 'Visualisation-TargetBrowserAsCircles'
view_type: glados.views.base.TrackView.viewTypes.VISUALISATION
view_config:
browse_button_container: $browseButtonContainer
view = new glados.views.ReportCards.VisualisationInCardView
el: $('#BCK-TargetBrowserAsCircles')
model: targetHierarchyAgg
config: config
report_card_app: @
targetHierarchyAgg.fetch()
return view
@initDatabaseSummary = ->
databaseInfo = new glados.models.MainPage.DatabaseSummaryInfo()
new glados.views.MainPage.DatabaseSummaryView
model: databaseInfo
el: $('.BCK-Database-summary-info')
databaseInfo.fetch()
@initAssociatedResources = ->
new glados.views.MainPage.AssociatedResourcesView
el: $('.BCK-Associated-resources')
@initTweets = ->
tweetsList = glados.models.paginatedCollections.PaginatedCollectionFactory.getNewTweetsList()
tweetsList.initURL()
$tweetsElem = $('.BCK-Tweets-container')
glados.views.PaginatedViews.PaginatedViewFactory.getNewInfinitePaginatedView(tweetsList, $tweetsElem, 'do-repaint')
tweetsList.fetch()
@initBlogEntries = ->
blogEntriesList = glados.models.paginatedCollections.PaginatedCollectionFactory.getNewBlogEntriesList()
blogEntriesList.initURL()
$blogEntriesElem = $('.BCK-Blog-Entries-container')
glados.views.PaginatedViews.PaginatedViewFactory.getNewInfinitePaginatedView(blogEntriesList, $blogEntriesElem, 'do-repaint')
blogEntriesList.fetch()
@initGithubDetails = ->
new glados.views.MainPage.GitHubDetailsView
el: $('.BCK-github-details')
# ----------------------------------------------------------------------------------------------------------------------
# Aggregations
# ----------------------------------------------------------------------------------------------------------------------
@getFirstApprovalPercentage = (defaultInterval = 1) ->
queryConfig =
type: glados.models.Aggregations.Aggregation.QueryTypes.QUERY_STRING
query_string_template: '_metadata.drug.is_drug:true'
template_data: {}
aggsConfig =
aggs:
firstApprovalByMoleculeType:
type: glados.models.Aggregations.Aggregation.AggTypes.HISTOGRAM
field: 'first_approval'
default_interval_size: defaultInterval
min_interval_size: 1
max_interval_size: 10
bucket_key_parse_function: (key) -> key.replace(/\.0/i, '')
bucket_sort_compare_function: (bucketA, bucketB) ->
yearA = parseFloat(bucketA.key)
yearB = parseFloat(bucketB.key)
if yearA < yearB
return -1
else if yearA > yearB
return 1
return 0
aggs:
molecule_type:
type: glados.models.Aggregations.Aggregation.AggTypes.TERMS
field: 'molecule_type'
size: 10
bucket_links:
bucket_filter_template: 'first_approval:{{year}} AND molecule_type:"{{bucket_key}}"'
template_data:
year: 'BUCKET.parsed_parent_key'
bucket_key: '<KEY>.key'
link_generator: Drug.getDrugsListURL
moleculeTypeByYear = new glados.models.Aggregations.Aggregation
index_url: glados.models.Aggregations.Aggregation.COMPOUND_INDEX_URL
query_config: queryConfig
aggs_config: aggsConfig
return moleculeTypeByYear
@getMaxPhaseForDiseaseAgg = () ->
queryConfig =
type: glados.models.Aggregations.Aggregation.QueryTypes.QUERY_STRING
query_string_template: '_metadata.drug.is_drug:true'
template_data: {}
aggsConfig =
aggs:
maxPhaseForDisease:
type: glados.models.Aggregations.Aggregation.AggTypes.TERMS
field: 'max_phase'
size: 5
bucket_links:
bucket_filter_template: '_metadata.drug.is_drug:true AND ' +
'max_phase:{{bucket_key}}'
template_data:
bucket_key: 'BUCKET.key'
link_generator: Compound.getCompoundsListURL
aggs:
split_series_agg:
type: glados.models.Aggregations.Aggregation.AggTypes.TERMS
field: '_metadata.drug_indications.efo_term'
size: 12
bucket_links:
bucket_filter_template: '_metadata.drug.is_drug:true AND ' +
'max_phase :{{max_phase}} AND _metadata.drug_indications.efo_term:("{{bucket_key}}"' +
'{{#each extra_buckets}} OR "{{this}}"{{/each}})'
template_data:
max_phase: 'BUCKET.parent_key'
bucket_key: 'BUCKET.key'
extra_buckets: 'EXTRA_BUCKETS.key'
link_generator: Compound.getCompoundsListURL
MaxPhaseForDisease = new glados.models.Aggregations.Aggregation
index_url: glados.models.Aggregations.Aggregation.COMPOUND_INDEX_URL
query_config: queryConfig
aggs_config: aggsConfig
return MaxPhaseForDisease
@getTargetsOrganismTreeAgg = ->
queryConfig =
type: glados.models.Aggregations.Aggregation.QueryTypes.QUERY_STRING
query_string_template: '*'
template_data: {}
aggsConfig =
aggs:
children:
type: glados.models.Aggregations.Aggregation.AggTypes.TERMS
field: '_metadata.organism_taxonomy.l1'
size: 50
bucket_links:
bucket_filter_template: '_metadata.organism_taxonomy.l1:("{{bucket_key}}")'
template_data:
bucket_key: 'BUCKET.key'
link_generator: Target.getTargetsListURL
aggs:
children:
type: glados.models.Aggregations.Aggregation.AggTypes.TERMS
field: '_metadata.organism_taxonomy.l2'
size: 50
bucket_links:
bucket_filter_template: '_metadata.organism_taxonomy.l2:("{{bucket_key}}")'
template_data:
bucket_key: 'BUCKET.key'
link_generator: Target.getTargetsListURL
aggs:
children:
type: glados.models.Aggregations.Aggregation.AggTypes.TERMS
field: '_metadata.organism_taxonomy.l3'
size: 50
bucket_links:
bucket_filter_template: '_metadata.organism_taxonomy.l3:("{{bucket_key}}")'
template_data:
bucket_key: '<KEY>.key'
link_generator: Target.getTargetsListURL
organismTreeAgg = new glados.models.Aggregations.Aggregation
index_url: glados.models.Aggregations.Aggregation.TARGET_INDEX_URL
query_config: queryConfig
aggs_config: aggsConfig
return organismTreeAgg
| true | # Class in charge of rendering the index page of the ChEMBL web ui
class MainPageApp
# ----------------------------------------------------------------------------------------------------------------------
# Initialization
# ----------------------------------------------------------------------------------------------------------------------
@init = ->
glados.apps.Main.MainGladosApp.hideMainSplashScreen()
new glados.views.MainPage.VisualisationsWithCaptionsView
el: $('.BCK-visualisations-with-captions')
@initAssociatedResources()
@initDatabaseSummary()
@initTweets()
@initBlogEntries()
@initGithubDetails()
# ----------------------------------------------------------------------------------------------------------------------
# Init functions
# ----------------------------------------------------------------------------------------------------------------------
@initTargetClassificationSunburst = ($browseButtonContainer) ->
config =
browse_all_link: "#{glados.Settings.GLADOS_BASE_URL_FULL}/g/#browse/targets"
browse_button: true
browse_button_container: $browseButtonContainer
entity_name_plural: Target.prototype.entityNamePlural
view = new glados.views.MainPage.TargetClassificationsSunburstsView
el: $('#BCK-protein-classification-zoomburst')
config: config
return view
@initAssayClassificationSunburst = ($browseButtonContainer) ->
config =
browse_all_link: "#{glados.Settings.GLADOS_BASE_URL_FULL}/g/#browse/assays"
browse_button: true
browse_button_container: $browseButtonContainer
entity_name_plural: Assay.prototype.entityNamePlural
view = new glados.views.MainPage.AssayClassificationsSunburstsView
el: $('#BCK-assay-classification-zoomburst')
config: config
return view
@initBrowseEntities = ->
return new glados.views.MainPage.BrowseEntitiesAsCirclesView
el: $('#BrowseEntitiesAsCircles')
@initBrowseCovidEntities = ->
return new glados.views.MainPage.BrowseCovidEntitiesAsCirclesView
el: $('#BrowseCovidEntitiesAsCircles')
@initMaxPhaseForDisease = ->
maxPhaseForDisease = MainPageApp.getMaxPhaseForDiseaseAgg()
maxPhaseProp = glados.models.visualisation.PropertiesFactory.getPropertyConfigFor('Compound', 'MAX_PHASE', true)
diseaseClassProp = glados.models.visualisation.PropertiesFactory.getPropertyConfigFor('Compound', 'DISEASE')
pieConfig =
side_legend: true
x_axis_prop_name: 'maxPhaseForDisease'
split_series_prop_name: 'split_series_agg'
title: 'Max Phase for Disease'
max_categories: 5
stacked_donut: true
stacked_levels: 2
hide_title: true
properties:
max_phase: maxPhaseProp
disease_class: diseaseClassProp
initial_property_x: 'max_phase'
initial_property_z: 'disease_class'
title_link_url: Drug.getDrugsListURL()
config =
pie_config: pieConfig
is_outside_an_entity_report_card: true
disable_embedding: true
embed_url: "#{glados.Settings.GLADOS_BASE_URL_FULL}embed/#max_phase_for_disease"
view_name: 'Visualisation-DrugsByMaxPhaseAndDisease'
view_type: glados.views.base.TrackView.viewTypes.VISUALISATION
link_to_all:
link_text: 'See all drug Compounds in ChEMBL'
url: Drug.getDrugsListURL()
view = new glados.views.ReportCards.PieInCardView
el: $('#MaxPhaseForDisease')
model: maxPhaseForDisease
config: config
report_card_app: @
maxPhaseForDisease.fetch()
return view
@initFirstApprovalByMoleculeType = ->
drugsByMoleculeTypeAgg = MainPageApp.getFirstApprovalPercentage()
approvalDateProp = glados.models.visualisation.PropertiesFactory.getPropertyConfigFor('Compound', 'FIRST_APPROVAL')
moleculeTypeProp = glados.models.visualisation.PropertiesFactory.getPropertyConfigFor('Compound', 'MOLECULE_TYPE', true)
barsColourScale = moleculeTypeProp.colourScale
histogramConfig =
bars_colour_scale: barsColourScale
stacked_histogram: true
sort_by_key: false
rotate_x_axis_if_needed: true
hide_x_axis_title: true
legend_vertical: true
big_size: true
paint_axes_selectors: true
properties:
year: approvalDateProp
molecule_type: moleculeTypeProp
initial_property_x: 'year'
initial_property_z: 'molecule_type'
x_axis_options: ['count']
x_axis_min_columns: 1
x_axis_max_columns: 40
x_axis_initial_num_columns: 40
x_axis_prop_name: 'firstApprovalByMoleculeType'
y_scale_mode: 'percentage'
title: 'Drugs By Molecule Type and First Approval'
title_link_url: Drug.getDrugsListURL('_exists_:first_approval')
config =
histogram_config: histogramConfig
disable_embedding: true
is_outside_an_entity_report_card: true
view_name: 'Visualisation-DrugsByMoleculeTypeAndFirstApproval'
view_type: glados.views.base.TrackView.viewTypes.VISUALISATION
# embed_url: "#{glados.Settings.GLADOS_BASE_URL_FULL}embed/#documents_by_year_histogram"
view = new glados.views.ReportCards.HistogramInCardView
el: $('#BCK-FirstApprovalHistogram')
model: drugsByMoleculeTypeAgg
config: config
report_card_app: @
drugsByMoleculeTypeAgg.fetch()
return view
@initDrugsPerUsanYear = ->
allDrugsByYear = glados.apps.VisualisePageApp.getYearByMaxPhaseAgg()
usanYearProp = glados.models.visualisation.PropertiesFactory.getPropertyConfigFor('Compound', 'USAN_YEAR')
maxPhaseProp = glados.models.visualisation.PropertiesFactory.getPropertyConfigFor('Compound', 'MAX_PHASE', true)
barsColourScale = maxPhaseProp.colourScale
histogramConfig =
bars_colour_scale: barsColourScale
stacked_histogram: true
sort_by_key: true
rotate_x_axis_if_needed: false
hide_x_axis_title: true
y_scale_mode: 'normal'
legend_vertical: true
big_size: true
paint_axes_selectors: true
properties:
year: usanYearProp
max_phase: maxPhaseProp
initial_property_x: 'year'
initial_property_z: 'max_phase'
x_axis_options: ['count']
x_axis_min_columns: 1
x_axis_max_columns: 40
x_axis_initial_num_columns: 40
x_axis_prop_name: 'yearByMaxPhase'
title: 'Drugs by Usan Year'
title_link_url: Drug.getDrugsListURL('_metadata.compound_records.src_id:13 AND _exists_:usan_year')
config =
histogram_config: histogramConfig
is_outside_an_entity_report_card: true
disable_embedding: true
view_name: 'Visualisation-DrugsByUsanYear'
view_type: glados.views.base.TrackView.viewTypes.VISUALISATION
# embed_url: "#{glados.Settings.GLADOS_BASE_URL_FULL}embed/#documents_by_year_histogram"
view = new glados.views.ReportCards.HistogramInCardView
el: $('#PapersPerYearHistogram')
model: allDrugsByYear
config: config
report_card_app: @
allDrugsByYear.fetch()
return view
@initTargetsVisualisation = ($browseButtonContainer) ->
targetHierarchyAgg = MainPageApp.getTargetsOrganismTreeAgg()
config =
is_outside_an_entity_report_card: true
disable_embedding: true
embed_url: "#{glados.Settings.GLADOS_BASE_URL_FULL}embed/#targets_by_protein_class"
view_class: BrowseTargetAsCirclesView
view_name: 'Visualisation-TargetBrowserAsCircles'
view_type: glados.views.base.TrackView.viewTypes.VISUALISATION
view_config:
browse_button_container: $browseButtonContainer
view = new glados.views.ReportCards.VisualisationInCardView
el: $('#BCK-TargetBrowserAsCircles')
model: targetHierarchyAgg
config: config
report_card_app: @
targetHierarchyAgg.fetch()
return view
@initDatabaseSummary = ->
databaseInfo = new glados.models.MainPage.DatabaseSummaryInfo()
new glados.views.MainPage.DatabaseSummaryView
model: databaseInfo
el: $('.BCK-Database-summary-info')
databaseInfo.fetch()
@initAssociatedResources = ->
new glados.views.MainPage.AssociatedResourcesView
el: $('.BCK-Associated-resources')
@initTweets = ->
tweetsList = glados.models.paginatedCollections.PaginatedCollectionFactory.getNewTweetsList()
tweetsList.initURL()
$tweetsElem = $('.BCK-Tweets-container')
glados.views.PaginatedViews.PaginatedViewFactory.getNewInfinitePaginatedView(tweetsList, $tweetsElem, 'do-repaint')
tweetsList.fetch()
@initBlogEntries = ->
blogEntriesList = glados.models.paginatedCollections.PaginatedCollectionFactory.getNewBlogEntriesList()
blogEntriesList.initURL()
$blogEntriesElem = $('.BCK-Blog-Entries-container')
glados.views.PaginatedViews.PaginatedViewFactory.getNewInfinitePaginatedView(blogEntriesList, $blogEntriesElem, 'do-repaint')
blogEntriesList.fetch()
@initGithubDetails = ->
new glados.views.MainPage.GitHubDetailsView
el: $('.BCK-github-details')
# ----------------------------------------------------------------------------------------------------------------------
# Aggregations
# ----------------------------------------------------------------------------------------------------------------------
@getFirstApprovalPercentage = (defaultInterval = 1) ->
queryConfig =
type: glados.models.Aggregations.Aggregation.QueryTypes.QUERY_STRING
query_string_template: '_metadata.drug.is_drug:true'
template_data: {}
aggsConfig =
aggs:
firstApprovalByMoleculeType:
type: glados.models.Aggregations.Aggregation.AggTypes.HISTOGRAM
field: 'first_approval'
default_interval_size: defaultInterval
min_interval_size: 1
max_interval_size: 10
bucket_key_parse_function: (key) -> key.replace(/\.0/i, '')
bucket_sort_compare_function: (bucketA, bucketB) ->
yearA = parseFloat(bucketA.key)
yearB = parseFloat(bucketB.key)
if yearA < yearB
return -1
else if yearA > yearB
return 1
return 0
aggs:
molecule_type:
type: glados.models.Aggregations.Aggregation.AggTypes.TERMS
field: 'molecule_type'
size: 10
bucket_links:
bucket_filter_template: 'first_approval:{{year}} AND molecule_type:"{{bucket_key}}"'
template_data:
year: 'BUCKET.parsed_parent_key'
bucket_key: 'PI:KEY:<KEY>END_PI.key'
link_generator: Drug.getDrugsListURL
moleculeTypeByYear = new glados.models.Aggregations.Aggregation
index_url: glados.models.Aggregations.Aggregation.COMPOUND_INDEX_URL
query_config: queryConfig
aggs_config: aggsConfig
return moleculeTypeByYear
@getMaxPhaseForDiseaseAgg = () ->
queryConfig =
type: glados.models.Aggregations.Aggregation.QueryTypes.QUERY_STRING
query_string_template: '_metadata.drug.is_drug:true'
template_data: {}
aggsConfig =
aggs:
maxPhaseForDisease:
type: glados.models.Aggregations.Aggregation.AggTypes.TERMS
field: 'max_phase'
size: 5
bucket_links:
bucket_filter_template: '_metadata.drug.is_drug:true AND ' +
'max_phase:{{bucket_key}}'
template_data:
bucket_key: 'BUCKET.key'
link_generator: Compound.getCompoundsListURL
aggs:
split_series_agg:
type: glados.models.Aggregations.Aggregation.AggTypes.TERMS
field: '_metadata.drug_indications.efo_term'
size: 12
bucket_links:
bucket_filter_template: '_metadata.drug.is_drug:true AND ' +
'max_phase :{{max_phase}} AND _metadata.drug_indications.efo_term:("{{bucket_key}}"' +
'{{#each extra_buckets}} OR "{{this}}"{{/each}})'
template_data:
max_phase: 'BUCKET.parent_key'
bucket_key: 'BUCKET.key'
extra_buckets: 'EXTRA_BUCKETS.key'
link_generator: Compound.getCompoundsListURL
MaxPhaseForDisease = new glados.models.Aggregations.Aggregation
index_url: glados.models.Aggregations.Aggregation.COMPOUND_INDEX_URL
query_config: queryConfig
aggs_config: aggsConfig
return MaxPhaseForDisease
@getTargetsOrganismTreeAgg = ->
queryConfig =
type: glados.models.Aggregations.Aggregation.QueryTypes.QUERY_STRING
query_string_template: '*'
template_data: {}
aggsConfig =
aggs:
children:
type: glados.models.Aggregations.Aggregation.AggTypes.TERMS
field: '_metadata.organism_taxonomy.l1'
size: 50
bucket_links:
bucket_filter_template: '_metadata.organism_taxonomy.l1:("{{bucket_key}}")'
template_data:
bucket_key: 'BUCKET.key'
link_generator: Target.getTargetsListURL
aggs:
children:
type: glados.models.Aggregations.Aggregation.AggTypes.TERMS
field: '_metadata.organism_taxonomy.l2'
size: 50
bucket_links:
bucket_filter_template: '_metadata.organism_taxonomy.l2:("{{bucket_key}}")'
template_data:
bucket_key: 'BUCKET.key'
link_generator: Target.getTargetsListURL
aggs:
children:
type: glados.models.Aggregations.Aggregation.AggTypes.TERMS
field: '_metadata.organism_taxonomy.l3'
size: 50
bucket_links:
bucket_filter_template: '_metadata.organism_taxonomy.l3:("{{bucket_key}}")'
template_data:
bucket_key: 'PI:KEY:<KEY>END_PI.key'
link_generator: Target.getTargetsListURL
organismTreeAgg = new glados.models.Aggregations.Aggregation
index_url: glados.models.Aggregations.Aggregation.TARGET_INDEX_URL
query_config: queryConfig
aggs_config: aggsConfig
return organismTreeAgg
|
[
{
"context": "wn extends Region\n\n constructor: ->\n\n @name = \"Maeles Town\"\n @desc = \"Strength boost and artisan sh",
"end": 302,
"score": 0.5217328071594238,
"start": 300,
"tag": "NAME",
"value": "ae"
}
] | src/character/regions/MaelesTown.coffee | sadbear-/IdleLands | 0 |
Region = require "../base/Region"
`/**
* This region gives you strength and makes shops have better results.
*
* @name Maeles Town
* @effect +5% STR
* @effect Shop quality boost
* @category Norkos
* @package World Regions
*/`
class MaelesTown extends Region
constructor: ->
@name = "Maeles Town"
@desc = "Strength boost and artisan shops"
@strPercent: -> 5
@shopMult: -> 2
@shopSlots: -> 2
@shopQuality: -> 1.5
module.exports = exports = MaelesTown | 211962 |
Region = require "../base/Region"
`/**
* This region gives you strength and makes shops have better results.
*
* @name Maeles Town
* @effect +5% STR
* @effect Shop quality boost
* @category Norkos
* @package World Regions
*/`
class MaelesTown extends Region
constructor: ->
@name = "M<NAME>les Town"
@desc = "Strength boost and artisan shops"
@strPercent: -> 5
@shopMult: -> 2
@shopSlots: -> 2
@shopQuality: -> 1.5
module.exports = exports = MaelesTown | true |
Region = require "../base/Region"
`/**
* This region gives you strength and makes shops have better results.
*
* @name Maeles Town
* @effect +5% STR
* @effect Shop quality boost
* @category Norkos
* @package World Regions
*/`
class MaelesTown extends Region
constructor: ->
@name = "MPI:NAME:<NAME>END_PIles Town"
@desc = "Strength boost and artisan shops"
@strPercent: -> 5
@shopMult: -> 2
@shopSlots: -> 2
@shopQuality: -> 1.5
module.exports = exports = MaelesTown |
[
{
"context": " 'http'\n uuid: 'tentacle-uuid'\n token: 'tentacle-token'\n\n afterEach 'tear down meshblu', (done) ->\n ",
"end": 525,
"score": 0.9589356184005737,
"start": 511,
"tag": "PASSWORD",
"value": "tentacle-token"
},
{
"context": "etup message', ->\n spaceshipMessage = name: \"speedy\", size: 5\n\n @message = TestHelper.messageToP",
"end": 982,
"score": 0.9900431632995605,
"start": 976,
"tag": "NAME",
"value": "speedy"
},
{
"context": " object', ->\n message =\n data: name: \"speedy\", size: 5\n devices: ['t100']\n metad",
"end": 1426,
"score": 0.9921687245368958,
"start": 1420,
"tag": "NAME",
"value": "speedy"
}
] | test/message-to-protobuf-spec.coffee | redaphid/meshblu-message-transformer-protobuf | 0 | shmock = require 'shmock'
enableDestroy = require 'server-destroy'
TestHelper = require './helpers'
MessageTransformer = require '..'
spaceshipSchema = require './data/spaceship-schema.json'
describe 'MessageToProtobuf', ->
beforeEach 'setup meshblu', (done) ->
@meshblu = shmock done
enableDestroy @meshblu
@meshbluConfig =
server: 'localhost'
port: @meshblu.address().port
protocol: 'http'
uuid: 'tentacle-uuid'
token: 'tentacle-token'
afterEach 'tear down meshblu', (done) ->
@meshblu.destroy done
beforeEach ->
@sut = new MessageTransformer
context 'when given a tentacle message', ->
beforeEach 'meshblu', ->
device =
schemas:
version: "1.0.0"
message:
spaceship: spaceshipSchema
@meshblu.get('/v2/devices/tentacle-uuid').reply 200, device
beforeEach 'setup message', ->
spaceshipMessage = name: "speedy", size: 5
@message = TestHelper.messageToProtobuf
devices: ['t100']
type: 'spaceship'
data: TestHelper.encode
message: spaceshipMessage
protoPath: './test/data/spaceship.proto'
type: 'spaceship'
beforeEach (done) ->
@sut.toJSON {@message, @meshbluConfig}, (error, @response) => done()
it 'should create a json object', ->
message =
data: name: "speedy", size: 5
devices: ['t100']
metadata: messageType: 'spaceship'
expect(@response).to.deep.equal(message)
| 208148 | shmock = require 'shmock'
enableDestroy = require 'server-destroy'
TestHelper = require './helpers'
MessageTransformer = require '..'
spaceshipSchema = require './data/spaceship-schema.json'
describe 'MessageToProtobuf', ->
beforeEach 'setup meshblu', (done) ->
@meshblu = shmock done
enableDestroy @meshblu
@meshbluConfig =
server: 'localhost'
port: @meshblu.address().port
protocol: 'http'
uuid: 'tentacle-uuid'
token: '<PASSWORD>'
afterEach 'tear down meshblu', (done) ->
@meshblu.destroy done
beforeEach ->
@sut = new MessageTransformer
context 'when given a tentacle message', ->
beforeEach 'meshblu', ->
device =
schemas:
version: "1.0.0"
message:
spaceship: spaceshipSchema
@meshblu.get('/v2/devices/tentacle-uuid').reply 200, device
beforeEach 'setup message', ->
spaceshipMessage = name: "<NAME>", size: 5
@message = TestHelper.messageToProtobuf
devices: ['t100']
type: 'spaceship'
data: TestHelper.encode
message: spaceshipMessage
protoPath: './test/data/spaceship.proto'
type: 'spaceship'
beforeEach (done) ->
@sut.toJSON {@message, @meshbluConfig}, (error, @response) => done()
it 'should create a json object', ->
message =
data: name: "<NAME>", size: 5
devices: ['t100']
metadata: messageType: 'spaceship'
expect(@response).to.deep.equal(message)
| true | shmock = require 'shmock'
enableDestroy = require 'server-destroy'
TestHelper = require './helpers'
MessageTransformer = require '..'
spaceshipSchema = require './data/spaceship-schema.json'
describe 'MessageToProtobuf', ->
beforeEach 'setup meshblu', (done) ->
@meshblu = shmock done
enableDestroy @meshblu
@meshbluConfig =
server: 'localhost'
port: @meshblu.address().port
protocol: 'http'
uuid: 'tentacle-uuid'
token: 'PI:PASSWORD:<PASSWORD>END_PI'
afterEach 'tear down meshblu', (done) ->
@meshblu.destroy done
beforeEach ->
@sut = new MessageTransformer
context 'when given a tentacle message', ->
beforeEach 'meshblu', ->
device =
schemas:
version: "1.0.0"
message:
spaceship: spaceshipSchema
@meshblu.get('/v2/devices/tentacle-uuid').reply 200, device
beforeEach 'setup message', ->
spaceshipMessage = name: "PI:NAME:<NAME>END_PI", size: 5
@message = TestHelper.messageToProtobuf
devices: ['t100']
type: 'spaceship'
data: TestHelper.encode
message: spaceshipMessage
protoPath: './test/data/spaceship.proto'
type: 'spaceship'
beforeEach (done) ->
@sut.toJSON {@message, @meshbluConfig}, (error, @response) => done()
it 'should create a json object', ->
message =
data: name: "PI:NAME:<NAME>END_PI", size: 5
devices: ['t100']
metadata: messageType: 'spaceship'
expect(@response).to.deep.equal(message)
|
[
{
"context": "\tPerson:\n\t\n\t\tclass Person\n\t\t\n\t\t\tconstructor: ( id, firstName, lastName, phoneNumber, emailAddress, photoURL, c",
"end": 866,
"score": 0.9909998774528503,
"start": 857,
"tag": "NAME",
"value": "firstName"
},
{
"context": "\t\tclass Person\n\t\t\n\t\t\tconstructor: ( id, firstName, lastName, phoneNumber, emailAddress, photoURL, coach, perm",
"end": 876,
"score": 0.9892180562019348,
"start": 868,
"tag": "NAME",
"value": "lastName"
},
{
"context": "o.observable( id )\n\t\t\t\t@firstName = ko.observable( firstName )\n\t\t\t\t@lastName = ko.observable( lastName )\n\t\t\t\t@",
"end": 1010,
"score": 0.9623814821243286,
"start": 1001,
"tag": "NAME",
"value": "firstName"
},
{
"context": "rvable( firstName )\n\t\t\t\t@lastName = ko.observable( lastName )\n\t\t\t\t@phoneNumber = ko.observable( phoneNumber )",
"end": 1052,
"score": 0.9777478575706482,
"start": 1044,
"tag": "NAME",
"value": "lastName"
}
] | src/main/coffee/mygps/mygps/model/Person.coffee | vandsonlima/SSP | 17 | #
# Licensed to Apereo under one or more contributor license
# agreements. See the NOTICE file distributed with this work
# for additional information regarding copyright ownership.
# Apereo licenses this file to you under the Apache License,
# Version 2.0 (the "License"); you may not use this file
# except in compliance with the License. You may obtain a
# copy of the License at the following location:
#
# 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.
#
namespace 'mygps.model'
Person:
class Person
constructor: ( id, firstName, lastName, phoneNumber, emailAddress, photoURL, coach, permissions ) ->
@id = ko.observable( id )
@firstName = ko.observable( firstName )
@lastName = ko.observable( lastName )
@phoneNumber = ko.observable( phoneNumber )
@photoURL = ko.observable( photoURL )
@coach = ko.observable( coach )
@permissions = ko.observable( permissions )
@createFromTransferObject: ( personTO ) ->
if personTO.coach?
coach = mygps.model.Person.createFromTransferObject( personTO.coach )
return new Person( personTO.id, personTO.firstName, personTO.lastName, personTO.phoneNumber, personTO.emailAddress, personTO.photoURL, coach, personTO.permissions ) | 127532 | #
# Licensed to Apereo under one or more contributor license
# agreements. See the NOTICE file distributed with this work
# for additional information regarding copyright ownership.
# Apereo licenses this file to you under the Apache License,
# Version 2.0 (the "License"); you may not use this file
# except in compliance with the License. You may obtain a
# copy of the License at the following location:
#
# 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.
#
namespace 'mygps.model'
Person:
class Person
constructor: ( id, <NAME>, <NAME>, phoneNumber, emailAddress, photoURL, coach, permissions ) ->
@id = ko.observable( id )
@firstName = ko.observable( <NAME> )
@lastName = ko.observable( <NAME> )
@phoneNumber = ko.observable( phoneNumber )
@photoURL = ko.observable( photoURL )
@coach = ko.observable( coach )
@permissions = ko.observable( permissions )
@createFromTransferObject: ( personTO ) ->
if personTO.coach?
coach = mygps.model.Person.createFromTransferObject( personTO.coach )
return new Person( personTO.id, personTO.firstName, personTO.lastName, personTO.phoneNumber, personTO.emailAddress, personTO.photoURL, coach, personTO.permissions ) | true | #
# Licensed to Apereo under one or more contributor license
# agreements. See the NOTICE file distributed with this work
# for additional information regarding copyright ownership.
# Apereo licenses this file to you under the Apache License,
# Version 2.0 (the "License"); you may not use this file
# except in compliance with the License. You may obtain a
# copy of the License at the following location:
#
# 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.
#
namespace 'mygps.model'
Person:
class Person
constructor: ( id, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, phoneNumber, emailAddress, photoURL, coach, permissions ) ->
@id = ko.observable( id )
@firstName = ko.observable( PI:NAME:<NAME>END_PI )
@lastName = ko.observable( PI:NAME:<NAME>END_PI )
@phoneNumber = ko.observable( phoneNumber )
@photoURL = ko.observable( photoURL )
@coach = ko.observable( coach )
@permissions = ko.observable( permissions )
@createFromTransferObject: ( personTO ) ->
if personTO.coach?
coach = mygps.model.Person.createFromTransferObject( personTO.coach )
return new Person( personTO.id, personTO.firstName, personTO.lastName, personTO.phoneNumber, personTO.emailAddress, personTO.photoURL, coach, personTO.permissions ) |
[
{
"context": "e: third\n the_field: rest\n\ncontenders: [\n \"Michael Phelps\"\n \"Liu Xiang\"\n \"Yao Ming\"\n \"Allyson Felix\"\n \"",
"end": 301,
"score": 0.999873697757721,
"start": 287,
"tag": "NAME",
"value": "Michael Phelps"
},
{
"context": "field: rest\n\ncontenders: [\n \"Michael Phelps\"\n \"Liu Xiang\"\n \"Yao Ming\"\n \"Allyson Felix\"\n \"Shawn Johnson\"",
"end": 315,
"score": 0.9998378157615662,
"start": 306,
"tag": "NAME",
"value": "Liu Xiang"
},
{
"context": "contenders: [\n \"Michael Phelps\"\n \"Liu Xiang\"\n \"Yao Ming\"\n \"Allyson Felix\"\n \"Shawn Johnson\"\n \"Roman Seb",
"end": 328,
"score": 0.9998539686203003,
"start": 320,
"tag": "NAME",
"value": "Yao Ming"
},
{
"context": "\n \"Michael Phelps\"\n \"Liu Xiang\"\n \"Yao Ming\"\n \"Allyson Felix\"\n \"Shawn Johnson\"\n \"Roman Sebrle\"\n \"Guo Jingji",
"end": 346,
"score": 0.9998763203620911,
"start": 333,
"tag": "NAME",
"value": "Allyson Felix"
},
{
"context": "\"\n \"Liu Xiang\"\n \"Yao Ming\"\n \"Allyson Felix\"\n \"Shawn Johnson\"\n \"Roman Sebrle\"\n \"Guo Jingjing\"\n \"Tyson Gay\"\n",
"end": 364,
"score": 0.9998675584793091,
"start": 351,
"tag": "NAME",
"value": "Shawn Johnson"
},
{
"context": "\"Yao Ming\"\n \"Allyson Felix\"\n \"Shawn Johnson\"\n \"Roman Sebrle\"\n \"Guo Jingjing\"\n \"Tyson Gay\"\n \"Asafa Powell\"\n",
"end": 381,
"score": 0.999865710735321,
"start": 369,
"tag": "NAME",
"value": "Roman Sebrle"
},
{
"context": "yson Felix\"\n \"Shawn Johnson\"\n \"Roman Sebrle\"\n \"Guo Jingjing\"\n \"Tyson Gay\"\n \"Asafa Powell\"\n \"Usain Bolt\"\n]\n",
"end": 398,
"score": 0.9998685717582703,
"start": 386,
"tag": "NAME",
"value": "Guo Jingjing"
},
{
"context": "awn Johnson\"\n \"Roman Sebrle\"\n \"Guo Jingjing\"\n \"Tyson Gay\"\n \"Asafa Powell\"\n \"Usain Bolt\"\n]\n\nmedalists(\"Mi",
"end": 412,
"score": 0.9998701810836792,
"start": 403,
"tag": "NAME",
"value": "Tyson Gay"
},
{
"context": " \"Roman Sebrle\"\n \"Guo Jingjing\"\n \"Tyson Gay\"\n \"Asafa Powell\"\n \"Usain Bolt\"\n]\n\nmedalists(\"Mighty Mouse\", cont",
"end": 429,
"score": 0.9998720288276672,
"start": 417,
"tag": "NAME",
"value": "Asafa Powell"
},
{
"context": " \"Guo Jingjing\"\n \"Tyson Gay\"\n \"Asafa Powell\"\n \"Usain Bolt\"\n]\n\nmedalists(\"Mighty Mouse\", contenders...)\n\npri",
"end": 444,
"score": 0.9998553991317749,
"start": 434,
"tag": "NAME",
"value": "Usain Bolt"
},
{
"context": ")\n\nprint(gold is \"Mighty Mouse\")\nprint(silver is \"Michael Phelps\")\nprint(bronze is \"Liu Xiang\")\nprint(the_field.le",
"end": 552,
"score": 0.9997353553771973,
"start": 538,
"tag": "NAME",
"value": "Michael Phelps"
}
] | test/fixtures/execution/test_splats.coffee | tlrobinson/coffee-script | 1 | func: first, second, rest... =>
rest.join(' ')
result: func(1, 2, 3, 4, 5)
print(result is "3 4 5")
gold: silver: bronze: the_field: null
medalists: first, second, third, rest... =>
gold: first
silver: second
bronze: third
the_field: rest
contenders: [
"Michael Phelps"
"Liu Xiang"
"Yao Ming"
"Allyson Felix"
"Shawn Johnson"
"Roman Sebrle"
"Guo Jingjing"
"Tyson Gay"
"Asafa Powell"
"Usain Bolt"
]
medalists("Mighty Mouse", contenders...)
print(gold is "Mighty Mouse")
print(silver is "Michael Phelps")
print(bronze is "Liu Xiang")
print(the_field.length is 8) | 131898 | func: first, second, rest... =>
rest.join(' ')
result: func(1, 2, 3, 4, 5)
print(result is "3 4 5")
gold: silver: bronze: the_field: null
medalists: first, second, third, rest... =>
gold: first
silver: second
bronze: third
the_field: rest
contenders: [
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
]
medalists("Mighty Mouse", contenders...)
print(gold is "Mighty Mouse")
print(silver is "<NAME>")
print(bronze is "Liu Xiang")
print(the_field.length is 8) | true | func: first, second, rest... =>
rest.join(' ')
result: func(1, 2, 3, 4, 5)
print(result is "3 4 5")
gold: silver: bronze: the_field: null
medalists: first, second, third, rest... =>
gold: first
silver: second
bronze: third
the_field: rest
contenders: [
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
]
medalists("Mighty Mouse", contenders...)
print(gold is "Mighty Mouse")
print(silver is "PI:NAME:<NAME>END_PI")
print(bronze is "Liu Xiang")
print(the_field.length is 8) |
[
{
"context": "\n\n \"comment\" : \"comments\"\n \"foobar\" : \"foobars\"\n \"newsletter\" : \"newsletters\"\n\n \"old_news\" ",
"end": 1498,
"score": 0.9904502034187317,
"start": 1491,
"tag": "NAME",
"value": "foobars"
},
{
"context": ": 'Actionwebservice'\n \"david's code\" : \"David's Code\"\n \"David's code\" : \"David's Code",
"end": 3742,
"score": 0.8059004545211792,
"start": 3737,
"tag": "NAME",
"value": "David"
},
{
"context": "ce'\n \"david's code\" : \"David's Code\"\n \"David's code\" : \"David's Code\"\n \"david's Code",
"end": 3759,
"score": 0.7414395213127136,
"start": 3754,
"tag": "NAME",
"value": "David"
},
{
"context": " : \"David's Code\"\n \"David's code\" : \"David's Code\"\n \"david's Code\" : \"David's Code",
"end": 3785,
"score": 0.8368854522705078,
"start": 3780,
"tag": "NAME",
"value": "David"
},
{
"context": "de\"\n \"David's code\" : \"David's Code\"\n \"david's Code\" : \"David's Code\"\n \"sgt. pepper'",
"end": 3802,
"score": 0.6278504729270935,
"start": 3797,
"tag": "NAME",
"value": "david"
},
{
"context": " : \"David's Code\"\n \"david's Code\" : \"David's Code\"\n \"sgt. pepper's\" : \"Sgt. Pepper'",
"end": 3828,
"score": 0.8496566414833069,
"start": 3823,
"tag": "NAME",
"value": "David"
},
{
"context": "There\"\n \"¿por qué?\" : '¿Por Qué?'\n \"Fred’s\" : \"Fred’s\"\n \"Fred`s\" ",
"end": 4032,
"score": 0.7683212757110596,
"start": 4028,
"tag": "NAME",
"value": "Fred"
},
{
"context": " : '¿Por Qué?'\n \"Fred’s\" : \"Fred’s\"\n \"Fred`s\" : \"Fred`s\"\n\nirregula",
"end": 4058,
"score": 0.7866166234016418,
"start": 4054,
"tag": "NAME",
"value": "Fred"
},
{
"context": "Por Qué?'\n \"Fred’s\" : \"Fred’s\"\n \"Fred`s\" : \"Fred`s\"\n\nirregularities =",
"end": 4066,
"score": 0.5531665682792664,
"start": 4065,
"tag": "NAME",
"value": "F"
},
{
"context": " : \"Fred’s\"\n \"Fred`s\" : \"Fred`s\"\n\nirregularities =\n 'person' : 'people',\n 'ma",
"end": 4095,
"score": 0.7310345768928528,
"start": 4091,
"tag": "NAME",
"value": "Fred"
}
] | node_modules/underscore.inflections/test/inflections_test.coffee | npupillo/json-server | 1 | root = exports ? @
_ = root._ or require 'underscore'
if typeof exports isnt "undefined"
_.mixin require '../src/underscore.inflections'
defaultUncountables = [
'equipment', 'information', 'rice', 'money', 'species', 'series',
'fish', 'sheep', 'jeans', 'moose', 'deer', 'news'
]
singularToPlural =
"search" : "searches"
"switch" : "switches"
"fix" : "fixes"
"box" : "boxes"
"process" : "processes"
"address" : "addresses"
"case" : "cases"
"stack" : "stacks"
"wish" : "wishes"
"fish" : "fish"
"jeans" : "jeans"
"funky jeans" : "funky jeans"
"my money" : "my money"
"category" : "categories"
"query" : "queries"
"ability" : "abilities"
"agency" : "agencies"
"movie" : "movies"
"archive" : "archives"
"index" : "indices"
"wife" : "wives"
"safe" : "saves"
"half" : "halves"
"move" : "moves"
"salesperson" : "salespeople"
"person" : "people"
"spokesman" : "spokesmen"
"man" : "men"
"woman" : "women"
"basis" : "bases"
"diagnosis" : "diagnoses"
"diagnosis_a" : "diagnosis_as"
"datum" : "data"
"medium" : "media"
"stadium" : "stadia"
"analysis" : "analyses"
"node_child" : "node_children"
"child" : "children"
"experience" : "experiences"
"day" : "days"
"comment" : "comments"
"foobar" : "foobars"
"newsletter" : "newsletters"
"old_news" : "old_news"
"news" : "news"
"series" : "series"
"species" : "species"
"quiz" : "quizzes"
"perspective" : "perspectives"
"ox" : "oxen"
"photo" : "photos"
"buffalo" : "buffaloes"
"tomato" : "tomatoes"
"dwarf" : "dwarves"
"elf" : "elves"
"information" : "information"
"equipment" : "equipment"
"bus" : "buses"
"status" : "statuses"
"status_code" : "status_codes"
"mouse" : "mice"
"louse" : "lice"
"house" : "houses"
"octopus" : "octopi"
"virus" : "viri"
"alias" : "aliases"
"portfolio" : "portfolios"
"vertex" : "vertices"
"matrix" : "matrices"
"matrix_fu" : "matrix_fus"
"axis" : "axes"
"taxi" : "taxis"
"testis" : "testes"
"crisis" : "crises"
"rice" : "rice"
"shoe" : "shoes"
"horse" : "horses"
"prize" : "prizes"
"edge" : "edges"
"cow" : "kine"
"database" : "databases"
camelToUnderscore =
"Product" : "product"
"SpecialGuest" : "special_guest"
"ApplicationController" : "application_controller"
"Area51Controller" : "area51_controller"
camelToUnderscoreWithoutReverse =
"HTMLTidy" : "html_tidy"
"HTMLTidyGenerator" : "html_tidy_generator"
"FreeBSD" : "free_bsd"
"HTML" : "html"
underscoreToLowerCamel =
"product" : "product"
"special_guest" : "specialGuest"
"application_controller" : "applicationController"
"area51_controller" : "area51Controller"
underscoreToHuman =
"employee_salary" : "Employee salary"
"employee_id" : "Employee"
"underground" : "Underground"
mixtureToTitleCase =
'active_record' : 'Active Record'
'ActiveRecord' : 'Active Record'
'action web service' : 'Action Web Service'
'Action Web Service' : 'Action Web Service'
'Action web service' : 'Action Web Service'
'actionwebservice' : 'Actionwebservice'
'Actionwebservice' : 'Actionwebservice'
"david's code" : "David's Code"
"David's code" : "David's Code"
"david's Code" : "David's Code"
"sgt. pepper's" : "Sgt. Pepper's"
"i've just seen a face" : "I've Just Seen A Face"
"maybe you'll be there" : "Maybe You'll Be There"
"¿por qué?" : '¿Por Qué?'
"Fred’s" : "Fred’s"
"Fred`s" : "Fred`s"
irregularities =
'person' : 'people',
'man' : 'men',
'child' : 'children',
'sex' : 'sexes',
'move' : 'moves',
'misc.' : 'misc.',
describe 'underscore.inflections', ->
describe 'singularize', ->
_.each singularToPlural, (value, key, list) ->
it "should properly singularize #{value}", ->
_.singularize(value).should.equal key
_.each singularToPlural, (value, key, list) ->
it "should properly singularize #{key}", ->
_.singularize(key).should.equal key
it "should inflect an empty string", ->
_.pluralize("").should.equal ""
describe 'pluralize', ->
_.each singularToPlural, (value, key, list) ->
it "should properly pluralize #{key}", ->
_.pluralize(key).should.equal value
_.each singularToPlural, (value, key, list) ->
it "should properly pluralize #{value}", ->
_.pluralize(value).should.equal value
it "should inflect an empty string", ->
_.pluralize("").should.equal ""
it "should inflect with a count", ->
_.pluralize("count", 1).should.equal "1 count"
_.pluralize("count", 2).should.equal "2 counts"
_.pluralize("count", '1').should.equal "1 count"
_.pluralize("count", '2').should.equal "2 counts"
_.pluralize("count", '1,066').should.equal "1,066 counts"
_.pluralize("count", '1.25').should.equal "1.25 counts"
_.pluralize("count", '1.0').should.equal "1.0 count"
_.pluralize("count", '1.00').should.equal "1.00 count"
_.pluralize("count", 0, plural: "counters").should.equal "0 counters"
_.pluralize("count", null, plural: "counters").should.equal "0 counters"
_.pluralize("person", 2).should.equal "2 people"
_.pluralize("buffalo", 10).should.equal "10 buffaloes"
_.pluralize("berry", 1).should.equal "1 berry"
_.pluralize("berry", 12).should.equal "12 berries"
it "should inflect with count, but not show number", ->
_.pluralize("count", 1, showNumber: false).should.equal "count"
_.pluralize("count", 2, showNumber: false).should.equal "counts"
_.pluralize("count", '1', showNumber: false).should.equal "count"
_.pluralize("count", '2', showNumber: false).should.equal "counts"
_.pluralize("count", '1,066', showNumber: false).should.equal "counts"
_.pluralize("count", '1.25', showNumber: false).should.equal "counts"
_.pluralize("count", '1.0', showNumber: false).should.equal "count"
_.pluralize("count", '1.00', showNumber: false).should.equal "count"
_.pluralize("count", 0, plural: "counters", showNumber: false).should.equal "counters"
_.pluralize("count", null, plural: "counters", showNumber: false).should.equal "counters"
_.pluralize("person", 2, showNumber: false).should.equal "people"
_.pluralize("buffalo", 10, showNumber: false).should.equal "buffaloes"
_.pluralize("berry", 1, showNumber: false).should.equal "berry"
_.pluralize("berry", 12, showNumber: false).should.equal "berries"
describe 'uncountable', ->
_.each defaultUncountables, (word) ->
it "should test uncountability of #{word} with pluralize", ->
_.pluralize(word).should.equal word
it "should test uncountability of #{word} with pluralize", ->
_.singularize(word).should.equal word
it "should test uncountability of #{word} with pluralize", ->
_.singularize(word).should.equal _.pluralize(word)
describe 'irregulars', ->
_.each irregularities, (value, key) ->
it "should test irregularity between #{key} and #{value}", ->
_.irregular key, value
_.singularize(value).should.equal key
_.pluralize(key).should.equal value
it "should test pluralize of irregularity #{value} should be the same", ->
_.irregular key, value
_.pluralize(value).should.equal value
describe 'overwriting', ->
it "should override and switch back", ->
_.singularize("series").should.equal "series"
_.singular("series", "serie")
_.singularize("series").should.equal "serie"
_.uncountable "series"
describe 'clear', ->
it "should test clearing rules"
describe 'camelize', ->
it "should propertly camelize", ->
_.each camelToUnderscore, (value, key, list) ->
_.camelize(value).should.equal key
it "should downcase the first character if passed false as a second argument", ->
_.camelize('Capital', false).should.equal 'capital'
it "should remove underscores", ->
_.camelize('Camel_Case').should.equal 'CamelCase'
describe 'acronyms', ->
before ->
_.acronym('API')
_.acronym('HTML')
_.acronym('HTTP')
_.acronym('RESTful')
_.acronym('W3C')
_.acronym('PhD')
_.acronym('RoR')
_.acronym('SSL')
# camelize underscore humanize titleize
_.each [
["API", "api", "API", "API"],
["APIController", "api_controller", "API controller", "API Controller"],
["HTTPAPI", "http_api", "HTTP API", "HTTP API"],
["SSLError", "ssl_error", "SSL error", "SSL Error"],
["RESTful", "restful", "RESTful", "RESTful"],
["RESTfulController", "restful_controller", "RESTful controller", "RESTful Controller"],
["IHeartW3C", "i_heart_w3c", "I heart W3C", "I Heart W3C"],
["PhDRequired", "phd_required", "PhD required", "PhD Required"],
["IRoRU", "i_ror_u", "I RoR u", "I RoR U"],
["RESTfulHTTPAPI", "restful_http_api", "RESTful HTTP API", "RESTful HTTP API"],
# misdirection
["Capistrano", "capistrano", "Capistrano", "Capistrano"],
["CapiController", "capi_controller", "Capi controller", "Capi Controller"],
["HttpsApis", "https_apis", "Https apis", "Https Apis"],
["Html5", "html5", "Html5", "Html5"],
["Restfully", "restfully", "Restfully", "Restfully"],
["RoRails", "ro_rails", "Ro rails", "Ro Rails"]
], (t) ->
camel = t[0]
under = t[1]
human = t[2]
title = t[3]
it 'should camelize as underscored', ->
_.camelize(under).should.equal camel
it 'should not change already camel cased', ->
_.camelize(camel).should.equal camel
it 'should not modify already underscored', ->
_.underscore(under).should.equal under
it 'should underscore camel cased', ->
_.underscore(camel).should.equal under
it 'titleizes underscored text as expected', ->
_.titleize(under).should.equal title
it 'titleizes camelcase text as expected', ->
_.titleize(camel).should.equal title
it 'should humanize as expected', ->
_.humanize(under).should.equal human
describe 'RESTfulHTTPAPI', ->
it 'does its thing', ->
_.underscore('RESTfulHTTPAPI').should.equal 'restful_http_api'
describe 'acronym override', ->
before ->
_.acronym('API')
_.acronym('LegacyApi')
it 'honors new acronym', ->
_.camelize('legacyapi').should.equal 'LegacyApi'
it 'does not match with underscore', ->
_.camelize('legacy_api').should.equal 'LegacyAPI'
it 'matches when delimited in a longer string', ->
_.camelize('some_legacyapi').should.equal 'SomeLegacyApi'
it 'does not match when not delimited', ->
_.camelize('nonlegacyapi').should.equal 'Nonlegacyapi'
describe 'acronym camelize lower', ->
before ->
_.acronym('API')
_.acronym('HTML')
it 'does not camelize first letter', ->
_.camelize('html_api', false).should.equal 'htmlAPI'
_.camelize('htmlAPI', false).should.equal 'htmlAPI'
_.camelize('HTMLAPI', false).should.equal 'htmlAPI'
describe 'underscore acronym sequence', ->
before ->
_.acronym('API')
_.acronym('JSON')
_.acronym('HTML')
it 'deliniates on acronym boundaries', ->
_.underscore('JSONHTMLAPI').should.equal 'json_html_api'
describe 'underscore', ->
_.each camelToUnderscore, (underscore, camel) ->
it 'should underscore as expected', ->
_.underscore(camel).should.equal underscore
_.each camelToUnderscoreWithoutReverse, (underscore, camel) ->
it 'should underscore without reverse as expected', ->
_.underscore(camel).should.equal underscore
describe 'humanize', ->
_.each underscoreToHuman, (human, underscore) ->
it 'should humanize as expected', ->
_.humanize(underscore).should.equal human
describe 'humanize by rule', ->
before ->
_.human /_cnt$/i, '_count'
_.human /^prefix/i, ''
it 'applies the custom rules', ->
_.humanize('jargon_cnt').should.equal 'Jargon count'
_.humanize('prefix_request').should.equal 'Request'
describe 'humanize by string', ->
before ->
_.human 'col_rpted_bugs', 'Reported bugs'
it 'performs the string replacement', ->
_.humanize('col_rpted_bugs').should.equal 'Reported bugs'
_.humanize('COL_rpted_bugs').should.equal 'Col rpted bugs'
describe 'titleize', ->
_.each mixtureToTitleCase, (titleized, before) ->
it "titleizes #{before}", ->
_.titleize(before).should.equal titleized
| 181069 | root = exports ? @
_ = root._ or require 'underscore'
if typeof exports isnt "undefined"
_.mixin require '../src/underscore.inflections'
defaultUncountables = [
'equipment', 'information', 'rice', 'money', 'species', 'series',
'fish', 'sheep', 'jeans', 'moose', 'deer', 'news'
]
singularToPlural =
"search" : "searches"
"switch" : "switches"
"fix" : "fixes"
"box" : "boxes"
"process" : "processes"
"address" : "addresses"
"case" : "cases"
"stack" : "stacks"
"wish" : "wishes"
"fish" : "fish"
"jeans" : "jeans"
"funky jeans" : "funky jeans"
"my money" : "my money"
"category" : "categories"
"query" : "queries"
"ability" : "abilities"
"agency" : "agencies"
"movie" : "movies"
"archive" : "archives"
"index" : "indices"
"wife" : "wives"
"safe" : "saves"
"half" : "halves"
"move" : "moves"
"salesperson" : "salespeople"
"person" : "people"
"spokesman" : "spokesmen"
"man" : "men"
"woman" : "women"
"basis" : "bases"
"diagnosis" : "diagnoses"
"diagnosis_a" : "diagnosis_as"
"datum" : "data"
"medium" : "media"
"stadium" : "stadia"
"analysis" : "analyses"
"node_child" : "node_children"
"child" : "children"
"experience" : "experiences"
"day" : "days"
"comment" : "comments"
"foobar" : "<NAME>"
"newsletter" : "newsletters"
"old_news" : "old_news"
"news" : "news"
"series" : "series"
"species" : "species"
"quiz" : "quizzes"
"perspective" : "perspectives"
"ox" : "oxen"
"photo" : "photos"
"buffalo" : "buffaloes"
"tomato" : "tomatoes"
"dwarf" : "dwarves"
"elf" : "elves"
"information" : "information"
"equipment" : "equipment"
"bus" : "buses"
"status" : "statuses"
"status_code" : "status_codes"
"mouse" : "mice"
"louse" : "lice"
"house" : "houses"
"octopus" : "octopi"
"virus" : "viri"
"alias" : "aliases"
"portfolio" : "portfolios"
"vertex" : "vertices"
"matrix" : "matrices"
"matrix_fu" : "matrix_fus"
"axis" : "axes"
"taxi" : "taxis"
"testis" : "testes"
"crisis" : "crises"
"rice" : "rice"
"shoe" : "shoes"
"horse" : "horses"
"prize" : "prizes"
"edge" : "edges"
"cow" : "kine"
"database" : "databases"
camelToUnderscore =
"Product" : "product"
"SpecialGuest" : "special_guest"
"ApplicationController" : "application_controller"
"Area51Controller" : "area51_controller"
camelToUnderscoreWithoutReverse =
"HTMLTidy" : "html_tidy"
"HTMLTidyGenerator" : "html_tidy_generator"
"FreeBSD" : "free_bsd"
"HTML" : "html"
underscoreToLowerCamel =
"product" : "product"
"special_guest" : "specialGuest"
"application_controller" : "applicationController"
"area51_controller" : "area51Controller"
underscoreToHuman =
"employee_salary" : "Employee salary"
"employee_id" : "Employee"
"underground" : "Underground"
mixtureToTitleCase =
'active_record' : 'Active Record'
'ActiveRecord' : 'Active Record'
'action web service' : 'Action Web Service'
'Action Web Service' : 'Action Web Service'
'Action web service' : 'Action Web Service'
'actionwebservice' : 'Actionwebservice'
'Actionwebservice' : 'Actionwebservice'
"david's code" : "<NAME>'s Code"
"<NAME>'s code" : "<NAME>'s Code"
"<NAME>'s Code" : "<NAME>'s Code"
"sgt. pepper's" : "Sgt. Pepper's"
"i've just seen a face" : "I've Just Seen A Face"
"maybe you'll be there" : "Maybe You'll Be There"
"¿por qué?" : '¿Por Qué?'
"<NAME>’s" : "<NAME>’s"
"<NAME>red`s" : "<NAME>`s"
irregularities =
'person' : 'people',
'man' : 'men',
'child' : 'children',
'sex' : 'sexes',
'move' : 'moves',
'misc.' : 'misc.',
describe 'underscore.inflections', ->
describe 'singularize', ->
_.each singularToPlural, (value, key, list) ->
it "should properly singularize #{value}", ->
_.singularize(value).should.equal key
_.each singularToPlural, (value, key, list) ->
it "should properly singularize #{key}", ->
_.singularize(key).should.equal key
it "should inflect an empty string", ->
_.pluralize("").should.equal ""
describe 'pluralize', ->
_.each singularToPlural, (value, key, list) ->
it "should properly pluralize #{key}", ->
_.pluralize(key).should.equal value
_.each singularToPlural, (value, key, list) ->
it "should properly pluralize #{value}", ->
_.pluralize(value).should.equal value
it "should inflect an empty string", ->
_.pluralize("").should.equal ""
it "should inflect with a count", ->
_.pluralize("count", 1).should.equal "1 count"
_.pluralize("count", 2).should.equal "2 counts"
_.pluralize("count", '1').should.equal "1 count"
_.pluralize("count", '2').should.equal "2 counts"
_.pluralize("count", '1,066').should.equal "1,066 counts"
_.pluralize("count", '1.25').should.equal "1.25 counts"
_.pluralize("count", '1.0').should.equal "1.0 count"
_.pluralize("count", '1.00').should.equal "1.00 count"
_.pluralize("count", 0, plural: "counters").should.equal "0 counters"
_.pluralize("count", null, plural: "counters").should.equal "0 counters"
_.pluralize("person", 2).should.equal "2 people"
_.pluralize("buffalo", 10).should.equal "10 buffaloes"
_.pluralize("berry", 1).should.equal "1 berry"
_.pluralize("berry", 12).should.equal "12 berries"
it "should inflect with count, but not show number", ->
_.pluralize("count", 1, showNumber: false).should.equal "count"
_.pluralize("count", 2, showNumber: false).should.equal "counts"
_.pluralize("count", '1', showNumber: false).should.equal "count"
_.pluralize("count", '2', showNumber: false).should.equal "counts"
_.pluralize("count", '1,066', showNumber: false).should.equal "counts"
_.pluralize("count", '1.25', showNumber: false).should.equal "counts"
_.pluralize("count", '1.0', showNumber: false).should.equal "count"
_.pluralize("count", '1.00', showNumber: false).should.equal "count"
_.pluralize("count", 0, plural: "counters", showNumber: false).should.equal "counters"
_.pluralize("count", null, plural: "counters", showNumber: false).should.equal "counters"
_.pluralize("person", 2, showNumber: false).should.equal "people"
_.pluralize("buffalo", 10, showNumber: false).should.equal "buffaloes"
_.pluralize("berry", 1, showNumber: false).should.equal "berry"
_.pluralize("berry", 12, showNumber: false).should.equal "berries"
describe 'uncountable', ->
_.each defaultUncountables, (word) ->
it "should test uncountability of #{word} with pluralize", ->
_.pluralize(word).should.equal word
it "should test uncountability of #{word} with pluralize", ->
_.singularize(word).should.equal word
it "should test uncountability of #{word} with pluralize", ->
_.singularize(word).should.equal _.pluralize(word)
describe 'irregulars', ->
_.each irregularities, (value, key) ->
it "should test irregularity between #{key} and #{value}", ->
_.irregular key, value
_.singularize(value).should.equal key
_.pluralize(key).should.equal value
it "should test pluralize of irregularity #{value} should be the same", ->
_.irregular key, value
_.pluralize(value).should.equal value
describe 'overwriting', ->
it "should override and switch back", ->
_.singularize("series").should.equal "series"
_.singular("series", "serie")
_.singularize("series").should.equal "serie"
_.uncountable "series"
describe 'clear', ->
it "should test clearing rules"
describe 'camelize', ->
it "should propertly camelize", ->
_.each camelToUnderscore, (value, key, list) ->
_.camelize(value).should.equal key
it "should downcase the first character if passed false as a second argument", ->
_.camelize('Capital', false).should.equal 'capital'
it "should remove underscores", ->
_.camelize('Camel_Case').should.equal 'CamelCase'
describe 'acronyms', ->
before ->
_.acronym('API')
_.acronym('HTML')
_.acronym('HTTP')
_.acronym('RESTful')
_.acronym('W3C')
_.acronym('PhD')
_.acronym('RoR')
_.acronym('SSL')
# camelize underscore humanize titleize
_.each [
["API", "api", "API", "API"],
["APIController", "api_controller", "API controller", "API Controller"],
["HTTPAPI", "http_api", "HTTP API", "HTTP API"],
["SSLError", "ssl_error", "SSL error", "SSL Error"],
["RESTful", "restful", "RESTful", "RESTful"],
["RESTfulController", "restful_controller", "RESTful controller", "RESTful Controller"],
["IHeartW3C", "i_heart_w3c", "I heart W3C", "I Heart W3C"],
["PhDRequired", "phd_required", "PhD required", "PhD Required"],
["IRoRU", "i_ror_u", "I RoR u", "I RoR U"],
["RESTfulHTTPAPI", "restful_http_api", "RESTful HTTP API", "RESTful HTTP API"],
# misdirection
["Capistrano", "capistrano", "Capistrano", "Capistrano"],
["CapiController", "capi_controller", "Capi controller", "Capi Controller"],
["HttpsApis", "https_apis", "Https apis", "Https Apis"],
["Html5", "html5", "Html5", "Html5"],
["Restfully", "restfully", "Restfully", "Restfully"],
["RoRails", "ro_rails", "Ro rails", "Ro Rails"]
], (t) ->
camel = t[0]
under = t[1]
human = t[2]
title = t[3]
it 'should camelize as underscored', ->
_.camelize(under).should.equal camel
it 'should not change already camel cased', ->
_.camelize(camel).should.equal camel
it 'should not modify already underscored', ->
_.underscore(under).should.equal under
it 'should underscore camel cased', ->
_.underscore(camel).should.equal under
it 'titleizes underscored text as expected', ->
_.titleize(under).should.equal title
it 'titleizes camelcase text as expected', ->
_.titleize(camel).should.equal title
it 'should humanize as expected', ->
_.humanize(under).should.equal human
describe 'RESTfulHTTPAPI', ->
it 'does its thing', ->
_.underscore('RESTfulHTTPAPI').should.equal 'restful_http_api'
describe 'acronym override', ->
before ->
_.acronym('API')
_.acronym('LegacyApi')
it 'honors new acronym', ->
_.camelize('legacyapi').should.equal 'LegacyApi'
it 'does not match with underscore', ->
_.camelize('legacy_api').should.equal 'LegacyAPI'
it 'matches when delimited in a longer string', ->
_.camelize('some_legacyapi').should.equal 'SomeLegacyApi'
it 'does not match when not delimited', ->
_.camelize('nonlegacyapi').should.equal 'Nonlegacyapi'
describe 'acronym camelize lower', ->
before ->
_.acronym('API')
_.acronym('HTML')
it 'does not camelize first letter', ->
_.camelize('html_api', false).should.equal 'htmlAPI'
_.camelize('htmlAPI', false).should.equal 'htmlAPI'
_.camelize('HTMLAPI', false).should.equal 'htmlAPI'
describe 'underscore acronym sequence', ->
before ->
_.acronym('API')
_.acronym('JSON')
_.acronym('HTML')
it 'deliniates on acronym boundaries', ->
_.underscore('JSONHTMLAPI').should.equal 'json_html_api'
describe 'underscore', ->
_.each camelToUnderscore, (underscore, camel) ->
it 'should underscore as expected', ->
_.underscore(camel).should.equal underscore
_.each camelToUnderscoreWithoutReverse, (underscore, camel) ->
it 'should underscore without reverse as expected', ->
_.underscore(camel).should.equal underscore
describe 'humanize', ->
_.each underscoreToHuman, (human, underscore) ->
it 'should humanize as expected', ->
_.humanize(underscore).should.equal human
describe 'humanize by rule', ->
before ->
_.human /_cnt$/i, '_count'
_.human /^prefix/i, ''
it 'applies the custom rules', ->
_.humanize('jargon_cnt').should.equal 'Jargon count'
_.humanize('prefix_request').should.equal 'Request'
describe 'humanize by string', ->
before ->
_.human 'col_rpted_bugs', 'Reported bugs'
it 'performs the string replacement', ->
_.humanize('col_rpted_bugs').should.equal 'Reported bugs'
_.humanize('COL_rpted_bugs').should.equal 'Col rpted bugs'
describe 'titleize', ->
_.each mixtureToTitleCase, (titleized, before) ->
it "titleizes #{before}", ->
_.titleize(before).should.equal titleized
| true | root = exports ? @
_ = root._ or require 'underscore'
if typeof exports isnt "undefined"
_.mixin require '../src/underscore.inflections'
defaultUncountables = [
'equipment', 'information', 'rice', 'money', 'species', 'series',
'fish', 'sheep', 'jeans', 'moose', 'deer', 'news'
]
singularToPlural =
"search" : "searches"
"switch" : "switches"
"fix" : "fixes"
"box" : "boxes"
"process" : "processes"
"address" : "addresses"
"case" : "cases"
"stack" : "stacks"
"wish" : "wishes"
"fish" : "fish"
"jeans" : "jeans"
"funky jeans" : "funky jeans"
"my money" : "my money"
"category" : "categories"
"query" : "queries"
"ability" : "abilities"
"agency" : "agencies"
"movie" : "movies"
"archive" : "archives"
"index" : "indices"
"wife" : "wives"
"safe" : "saves"
"half" : "halves"
"move" : "moves"
"salesperson" : "salespeople"
"person" : "people"
"spokesman" : "spokesmen"
"man" : "men"
"woman" : "women"
"basis" : "bases"
"diagnosis" : "diagnoses"
"diagnosis_a" : "diagnosis_as"
"datum" : "data"
"medium" : "media"
"stadium" : "stadia"
"analysis" : "analyses"
"node_child" : "node_children"
"child" : "children"
"experience" : "experiences"
"day" : "days"
"comment" : "comments"
"foobar" : "PI:NAME:<NAME>END_PI"
"newsletter" : "newsletters"
"old_news" : "old_news"
"news" : "news"
"series" : "series"
"species" : "species"
"quiz" : "quizzes"
"perspective" : "perspectives"
"ox" : "oxen"
"photo" : "photos"
"buffalo" : "buffaloes"
"tomato" : "tomatoes"
"dwarf" : "dwarves"
"elf" : "elves"
"information" : "information"
"equipment" : "equipment"
"bus" : "buses"
"status" : "statuses"
"status_code" : "status_codes"
"mouse" : "mice"
"louse" : "lice"
"house" : "houses"
"octopus" : "octopi"
"virus" : "viri"
"alias" : "aliases"
"portfolio" : "portfolios"
"vertex" : "vertices"
"matrix" : "matrices"
"matrix_fu" : "matrix_fus"
"axis" : "axes"
"taxi" : "taxis"
"testis" : "testes"
"crisis" : "crises"
"rice" : "rice"
"shoe" : "shoes"
"horse" : "horses"
"prize" : "prizes"
"edge" : "edges"
"cow" : "kine"
"database" : "databases"
camelToUnderscore =
"Product" : "product"
"SpecialGuest" : "special_guest"
"ApplicationController" : "application_controller"
"Area51Controller" : "area51_controller"
camelToUnderscoreWithoutReverse =
"HTMLTidy" : "html_tidy"
"HTMLTidyGenerator" : "html_tidy_generator"
"FreeBSD" : "free_bsd"
"HTML" : "html"
underscoreToLowerCamel =
"product" : "product"
"special_guest" : "specialGuest"
"application_controller" : "applicationController"
"area51_controller" : "area51Controller"
underscoreToHuman =
"employee_salary" : "Employee salary"
"employee_id" : "Employee"
"underground" : "Underground"
mixtureToTitleCase =
'active_record' : 'Active Record'
'ActiveRecord' : 'Active Record'
'action web service' : 'Action Web Service'
'Action Web Service' : 'Action Web Service'
'Action web service' : 'Action Web Service'
'actionwebservice' : 'Actionwebservice'
'Actionwebservice' : 'Actionwebservice'
"david's code" : "PI:NAME:<NAME>END_PI's Code"
"PI:NAME:<NAME>END_PI's code" : "PI:NAME:<NAME>END_PI's Code"
"PI:NAME:<NAME>END_PI's Code" : "PI:NAME:<NAME>END_PI's Code"
"sgt. pepper's" : "Sgt. Pepper's"
"i've just seen a face" : "I've Just Seen A Face"
"maybe you'll be there" : "Maybe You'll Be There"
"¿por qué?" : '¿Por Qué?'
"PI:NAME:<NAME>END_PI’s" : "PI:NAME:<NAME>END_PI’s"
"PI:NAME:<NAME>END_PIred`s" : "PI:NAME:<NAME>END_PI`s"
irregularities =
'person' : 'people',
'man' : 'men',
'child' : 'children',
'sex' : 'sexes',
'move' : 'moves',
'misc.' : 'misc.',
describe 'underscore.inflections', ->
describe 'singularize', ->
_.each singularToPlural, (value, key, list) ->
it "should properly singularize #{value}", ->
_.singularize(value).should.equal key
_.each singularToPlural, (value, key, list) ->
it "should properly singularize #{key}", ->
_.singularize(key).should.equal key
it "should inflect an empty string", ->
_.pluralize("").should.equal ""
describe 'pluralize', ->
_.each singularToPlural, (value, key, list) ->
it "should properly pluralize #{key}", ->
_.pluralize(key).should.equal value
_.each singularToPlural, (value, key, list) ->
it "should properly pluralize #{value}", ->
_.pluralize(value).should.equal value
it "should inflect an empty string", ->
_.pluralize("").should.equal ""
it "should inflect with a count", ->
_.pluralize("count", 1).should.equal "1 count"
_.pluralize("count", 2).should.equal "2 counts"
_.pluralize("count", '1').should.equal "1 count"
_.pluralize("count", '2').should.equal "2 counts"
_.pluralize("count", '1,066').should.equal "1,066 counts"
_.pluralize("count", '1.25').should.equal "1.25 counts"
_.pluralize("count", '1.0').should.equal "1.0 count"
_.pluralize("count", '1.00').should.equal "1.00 count"
_.pluralize("count", 0, plural: "counters").should.equal "0 counters"
_.pluralize("count", null, plural: "counters").should.equal "0 counters"
_.pluralize("person", 2).should.equal "2 people"
_.pluralize("buffalo", 10).should.equal "10 buffaloes"
_.pluralize("berry", 1).should.equal "1 berry"
_.pluralize("berry", 12).should.equal "12 berries"
it "should inflect with count, but not show number", ->
_.pluralize("count", 1, showNumber: false).should.equal "count"
_.pluralize("count", 2, showNumber: false).should.equal "counts"
_.pluralize("count", '1', showNumber: false).should.equal "count"
_.pluralize("count", '2', showNumber: false).should.equal "counts"
_.pluralize("count", '1,066', showNumber: false).should.equal "counts"
_.pluralize("count", '1.25', showNumber: false).should.equal "counts"
_.pluralize("count", '1.0', showNumber: false).should.equal "count"
_.pluralize("count", '1.00', showNumber: false).should.equal "count"
_.pluralize("count", 0, plural: "counters", showNumber: false).should.equal "counters"
_.pluralize("count", null, plural: "counters", showNumber: false).should.equal "counters"
_.pluralize("person", 2, showNumber: false).should.equal "people"
_.pluralize("buffalo", 10, showNumber: false).should.equal "buffaloes"
_.pluralize("berry", 1, showNumber: false).should.equal "berry"
_.pluralize("berry", 12, showNumber: false).should.equal "berries"
describe 'uncountable', ->
_.each defaultUncountables, (word) ->
it "should test uncountability of #{word} with pluralize", ->
_.pluralize(word).should.equal word
it "should test uncountability of #{word} with pluralize", ->
_.singularize(word).should.equal word
it "should test uncountability of #{word} with pluralize", ->
_.singularize(word).should.equal _.pluralize(word)
describe 'irregulars', ->
_.each irregularities, (value, key) ->
it "should test irregularity between #{key} and #{value}", ->
_.irregular key, value
_.singularize(value).should.equal key
_.pluralize(key).should.equal value
it "should test pluralize of irregularity #{value} should be the same", ->
_.irregular key, value
_.pluralize(value).should.equal value
describe 'overwriting', ->
it "should override and switch back", ->
_.singularize("series").should.equal "series"
_.singular("series", "serie")
_.singularize("series").should.equal "serie"
_.uncountable "series"
describe 'clear', ->
it "should test clearing rules"
describe 'camelize', ->
it "should propertly camelize", ->
_.each camelToUnderscore, (value, key, list) ->
_.camelize(value).should.equal key
it "should downcase the first character if passed false as a second argument", ->
_.camelize('Capital', false).should.equal 'capital'
it "should remove underscores", ->
_.camelize('Camel_Case').should.equal 'CamelCase'
describe 'acronyms', ->
before ->
_.acronym('API')
_.acronym('HTML')
_.acronym('HTTP')
_.acronym('RESTful')
_.acronym('W3C')
_.acronym('PhD')
_.acronym('RoR')
_.acronym('SSL')
# camelize underscore humanize titleize
_.each [
["API", "api", "API", "API"],
["APIController", "api_controller", "API controller", "API Controller"],
["HTTPAPI", "http_api", "HTTP API", "HTTP API"],
["SSLError", "ssl_error", "SSL error", "SSL Error"],
["RESTful", "restful", "RESTful", "RESTful"],
["RESTfulController", "restful_controller", "RESTful controller", "RESTful Controller"],
["IHeartW3C", "i_heart_w3c", "I heart W3C", "I Heart W3C"],
["PhDRequired", "phd_required", "PhD required", "PhD Required"],
["IRoRU", "i_ror_u", "I RoR u", "I RoR U"],
["RESTfulHTTPAPI", "restful_http_api", "RESTful HTTP API", "RESTful HTTP API"],
# misdirection
["Capistrano", "capistrano", "Capistrano", "Capistrano"],
["CapiController", "capi_controller", "Capi controller", "Capi Controller"],
["HttpsApis", "https_apis", "Https apis", "Https Apis"],
["Html5", "html5", "Html5", "Html5"],
["Restfully", "restfully", "Restfully", "Restfully"],
["RoRails", "ro_rails", "Ro rails", "Ro Rails"]
], (t) ->
camel = t[0]
under = t[1]
human = t[2]
title = t[3]
it 'should camelize as underscored', ->
_.camelize(under).should.equal camel
it 'should not change already camel cased', ->
_.camelize(camel).should.equal camel
it 'should not modify already underscored', ->
_.underscore(under).should.equal under
it 'should underscore camel cased', ->
_.underscore(camel).should.equal under
it 'titleizes underscored text as expected', ->
_.titleize(under).should.equal title
it 'titleizes camelcase text as expected', ->
_.titleize(camel).should.equal title
it 'should humanize as expected', ->
_.humanize(under).should.equal human
describe 'RESTfulHTTPAPI', ->
it 'does its thing', ->
_.underscore('RESTfulHTTPAPI').should.equal 'restful_http_api'
describe 'acronym override', ->
before ->
_.acronym('API')
_.acronym('LegacyApi')
it 'honors new acronym', ->
_.camelize('legacyapi').should.equal 'LegacyApi'
it 'does not match with underscore', ->
_.camelize('legacy_api').should.equal 'LegacyAPI'
it 'matches when delimited in a longer string', ->
_.camelize('some_legacyapi').should.equal 'SomeLegacyApi'
it 'does not match when not delimited', ->
_.camelize('nonlegacyapi').should.equal 'Nonlegacyapi'
describe 'acronym camelize lower', ->
before ->
_.acronym('API')
_.acronym('HTML')
it 'does not camelize first letter', ->
_.camelize('html_api', false).should.equal 'htmlAPI'
_.camelize('htmlAPI', false).should.equal 'htmlAPI'
_.camelize('HTMLAPI', false).should.equal 'htmlAPI'
describe 'underscore acronym sequence', ->
before ->
_.acronym('API')
_.acronym('JSON')
_.acronym('HTML')
it 'deliniates on acronym boundaries', ->
_.underscore('JSONHTMLAPI').should.equal 'json_html_api'
describe 'underscore', ->
_.each camelToUnderscore, (underscore, camel) ->
it 'should underscore as expected', ->
_.underscore(camel).should.equal underscore
_.each camelToUnderscoreWithoutReverse, (underscore, camel) ->
it 'should underscore without reverse as expected', ->
_.underscore(camel).should.equal underscore
describe 'humanize', ->
_.each underscoreToHuman, (human, underscore) ->
it 'should humanize as expected', ->
_.humanize(underscore).should.equal human
describe 'humanize by rule', ->
before ->
_.human /_cnt$/i, '_count'
_.human /^prefix/i, ''
it 'applies the custom rules', ->
_.humanize('jargon_cnt').should.equal 'Jargon count'
_.humanize('prefix_request').should.equal 'Request'
describe 'humanize by string', ->
before ->
_.human 'col_rpted_bugs', 'Reported bugs'
it 'performs the string replacement', ->
_.humanize('col_rpted_bugs').should.equal 'Reported bugs'
_.humanize('COL_rpted_bugs').should.equal 'Col rpted bugs'
describe 'titleize', ->
_.each mixtureToTitleCase, (titleized, before) ->
it "titleizes #{before}", ->
_.titleize(before).should.equal titleized
|
[
{
"context": "://www.tcs.de\n# a little tool based on the work of Lee Machin used to capture image of your webcam right in you",
"end": 127,
"score": 0.9997201561927795,
"start": 117,
"tag": "NAME",
"value": "Lee Machin"
}
] | src/static/js/cheesecake.coffee | exinferis/cheeseCake | 0 | # # CheeseCake
# Team Centric Software GmbH, Exinferis 2012
# http://www.tcs.de
# a little tool based on the work of Lee Machin used to capture image of your webcam right in your browser
# and uploading them to s3 directly using a node.js based service for generating the s3 Signature and Policy.
# Will not work on anything else than the newest browsers.
class CheeseCake
constructor: ( @options ) ->
# extracting options or settings default values
@el = @options.el or $( "document" )
@format = @options.format or "image/jpeg"
@ext = @options.ext or "jpg"
@s3provider = @options.s3provider or ""
@cheese = new SayCheese( @el )
@images = {}
@cheese.on( "start", @initUI )
@cheese.on( "snapshot", @_snapShotHandler )
$( ".action-takepicture" ).on( "click", @takeSnapShot )
$( ".action-reset" ).on( "click", @reset )
@cheese.start()
return
# ### initUI
# shows th ui after cheese has been initialized and the webcam access has been allowed
initUI: =>
$( ".action-takepicture" ).fadeIn()
return
# ### takeSnapShot
# taking a snapshot using the webcam and publishing a corresponding event
takeSnapShot: =>
@cheese.takeSnapshot( )
return
# ### _snapShotHandler
# decides what to do with a previous taken snapshot
_snapShotHandler: ( snapshot ) =>
_id = _.uniqueId( "canvas_" )
_data = snapshot.toDataURL( @format )
@images[ _id ] = @dataURItoBlob( _data )
# removing an old image from the ui and the images object
if $( "#previewimages .thumbnail" ).length is 4
_toRemoveid = $( "#previewimages .thumblistitem:first" ).attr( "id" )
@images = _.omit( @images, _toRemoveid )
$( "#previewimages .thumblistitem:first" ).remove()
$( "#previewimages" ).append( "<li class='thumblistitem' id='thumb_#{_id}'><span class='thumbnail' id='#{_id}'><span class='marker hide'></span></span></li>" )
$( "##{_id}" ).append( snapshot )
$( "##{_id}").on( "click", @_createUploadForm )
return
# transforms a data uri from the canvas object to a JS blob object
dataURItoBlob: (dataURI) =>
binary = atob(dataURI.split(",")[1])
array = []
i = 0
while i < binary.length
array.push binary.charCodeAt(i)
i++
return new Blob( [new Uint8Array(array)],
type: "image/jpeg"
)
# ### _requestCredentials
# requesting the upload credentials
_requestCredentials: ( mimetype, file, cb )=>
$.ajax(
type: "POST"
url: "#{@s3provider}/credentials"
data:
mimetype: mimetype
file: file
success: ( res )=>
cb( res )
return
error: ( err ) =>
alert( "An error occurred receiving the S3 credentials from the server." )
return
)
return
_createUploadForm: ( event ) =>
# getting the id and anttaching the ajax loader to it
_id = $( event.currentTarget ).attr( "id" )
$( "##{_id}" ).append( "<span class='ajaxloader'></span>")
$( ".action-takepicture" ).fadeOut()
if @images[_id]?
_fName = "pic_#{moment().valueOf().toString( 16 )}#{randomnumber=Math.floor(Math.random()*10000000).toString(6)}"
@_requestCredentials( @format, _fName, ( res ) =>
# building html5 / formdata object for use with xhr transport
formData = new FormData
formData.append( "key", "#{res.FileDescriptor}.#{@ext}" )
formData.append( "acl", "public-read" )
formData.append( "Content-Disposition", "" )
formData.append( "Content-Type", res.ContentType )
formData.append( "success_action_status", res.ActionStatus )
formData.append( "AWSAccessKeyId", res.Key )
formData.append( "Policy", res.PolicyBase64 )
formData.append( "Signature", res.Signature )
formData.append( "file", @images[_id] )
try
xhr = new XMLHttpRequest
xhr.onreadystatechange = =>
#xhr request has finished - one way or another
if xhr.readyState is 4
if xhr.status is 200 or xhr.status is 201
@_uploadFinished( _id, "http://#{res.Bucket}.s3.amazonaws.com/#{res.FileDescriptor}.#{@ext}" )
else
@_uploadError( _id, xhr.status )
return
xhr.onprogress = ( progress ) =>
# do something fancy here - maybe an animated progress bar?
return
xhr.open "POST", "http://#{res.Bucket}.s3.amazonaws.com", true
xhr.send formData
catch e
@_uploadError( _id, e )
return
)
return
# ### _uploadFinished
_uploadFinished: ( id, link ) =>
@_setUploadedVisible( id )
$( "##{id}" ).find( ".marker" ).css( "background-position": "left bottom", "display": "block" )
$( "#thumb_#{id}" ).append( "<div class='alert alert-success'>Your picture has been uploaded like a boss! <a href='#{link}' target='blank'>Link</a></div>" )
return
# ### _uploadError
# handling the (hopefully rare) event of an error during the XHR transport
_uploadError: ( id, e )=>
@_setUploadedVisible( id )
$( "##{id}" ).find( ".marker" ).css( "background-position": "right bottom", "display": "block" )
$( "#thumb_#{id}" ).append( "<div class='alert alert-error'>An error occurred while uploading the file.</div>" )
return
# ### _setUploadedVisible
# emphasizes an element as the currently uploaded / uploading element by fading out the others
_setUploadedVisible: ( id )=>
$( ".thumblistitem" ).not( "#thumb_#{id}" ).fadeTo( 500, 0.5 )
$( "#previewimages .thumbnail" ).off()
$( "##{id}" ).find( ".ajaxloader" ).remove()
$( ".action-reset" ).fadeIn()
return
# ### reset
# resets the app, deleting all canvas objects, flushing the images
reset: =>
@images = {}
$( "#previewimages" ).empty()
$( ".action-reset" ).fadeOut( ->
$( ".action-takepicture" ).fadeIn()
)
return
window.CheeseCake = CheeseCake | 89225 | # # CheeseCake
# Team Centric Software GmbH, Exinferis 2012
# http://www.tcs.de
# a little tool based on the work of <NAME> used to capture image of your webcam right in your browser
# and uploading them to s3 directly using a node.js based service for generating the s3 Signature and Policy.
# Will not work on anything else than the newest browsers.
class CheeseCake
constructor: ( @options ) ->
# extracting options or settings default values
@el = @options.el or $( "document" )
@format = @options.format or "image/jpeg"
@ext = @options.ext or "jpg"
@s3provider = @options.s3provider or ""
@cheese = new SayCheese( @el )
@images = {}
@cheese.on( "start", @initUI )
@cheese.on( "snapshot", @_snapShotHandler )
$( ".action-takepicture" ).on( "click", @takeSnapShot )
$( ".action-reset" ).on( "click", @reset )
@cheese.start()
return
# ### initUI
# shows th ui after cheese has been initialized and the webcam access has been allowed
initUI: =>
$( ".action-takepicture" ).fadeIn()
return
# ### takeSnapShot
# taking a snapshot using the webcam and publishing a corresponding event
takeSnapShot: =>
@cheese.takeSnapshot( )
return
# ### _snapShotHandler
# decides what to do with a previous taken snapshot
_snapShotHandler: ( snapshot ) =>
_id = _.uniqueId( "canvas_" )
_data = snapshot.toDataURL( @format )
@images[ _id ] = @dataURItoBlob( _data )
# removing an old image from the ui and the images object
if $( "#previewimages .thumbnail" ).length is 4
_toRemoveid = $( "#previewimages .thumblistitem:first" ).attr( "id" )
@images = _.omit( @images, _toRemoveid )
$( "#previewimages .thumblistitem:first" ).remove()
$( "#previewimages" ).append( "<li class='thumblistitem' id='thumb_#{_id}'><span class='thumbnail' id='#{_id}'><span class='marker hide'></span></span></li>" )
$( "##{_id}" ).append( snapshot )
$( "##{_id}").on( "click", @_createUploadForm )
return
# transforms a data uri from the canvas object to a JS blob object
dataURItoBlob: (dataURI) =>
binary = atob(dataURI.split(",")[1])
array = []
i = 0
while i < binary.length
array.push binary.charCodeAt(i)
i++
return new Blob( [new Uint8Array(array)],
type: "image/jpeg"
)
# ### _requestCredentials
# requesting the upload credentials
_requestCredentials: ( mimetype, file, cb )=>
$.ajax(
type: "POST"
url: "#{@s3provider}/credentials"
data:
mimetype: mimetype
file: file
success: ( res )=>
cb( res )
return
error: ( err ) =>
alert( "An error occurred receiving the S3 credentials from the server." )
return
)
return
_createUploadForm: ( event ) =>
# getting the id and anttaching the ajax loader to it
_id = $( event.currentTarget ).attr( "id" )
$( "##{_id}" ).append( "<span class='ajaxloader'></span>")
$( ".action-takepicture" ).fadeOut()
if @images[_id]?
_fName = "pic_#{moment().valueOf().toString( 16 )}#{randomnumber=Math.floor(Math.random()*10000000).toString(6)}"
@_requestCredentials( @format, _fName, ( res ) =>
# building html5 / formdata object for use with xhr transport
formData = new FormData
formData.append( "key", "#{res.FileDescriptor}.#{@ext}" )
formData.append( "acl", "public-read" )
formData.append( "Content-Disposition", "" )
formData.append( "Content-Type", res.ContentType )
formData.append( "success_action_status", res.ActionStatus )
formData.append( "AWSAccessKeyId", res.Key )
formData.append( "Policy", res.PolicyBase64 )
formData.append( "Signature", res.Signature )
formData.append( "file", @images[_id] )
try
xhr = new XMLHttpRequest
xhr.onreadystatechange = =>
#xhr request has finished - one way or another
if xhr.readyState is 4
if xhr.status is 200 or xhr.status is 201
@_uploadFinished( _id, "http://#{res.Bucket}.s3.amazonaws.com/#{res.FileDescriptor}.#{@ext}" )
else
@_uploadError( _id, xhr.status )
return
xhr.onprogress = ( progress ) =>
# do something fancy here - maybe an animated progress bar?
return
xhr.open "POST", "http://#{res.Bucket}.s3.amazonaws.com", true
xhr.send formData
catch e
@_uploadError( _id, e )
return
)
return
# ### _uploadFinished
_uploadFinished: ( id, link ) =>
@_setUploadedVisible( id )
$( "##{id}" ).find( ".marker" ).css( "background-position": "left bottom", "display": "block" )
$( "#thumb_#{id}" ).append( "<div class='alert alert-success'>Your picture has been uploaded like a boss! <a href='#{link}' target='blank'>Link</a></div>" )
return
# ### _uploadError
# handling the (hopefully rare) event of an error during the XHR transport
_uploadError: ( id, e )=>
@_setUploadedVisible( id )
$( "##{id}" ).find( ".marker" ).css( "background-position": "right bottom", "display": "block" )
$( "#thumb_#{id}" ).append( "<div class='alert alert-error'>An error occurred while uploading the file.</div>" )
return
# ### _setUploadedVisible
# emphasizes an element as the currently uploaded / uploading element by fading out the others
_setUploadedVisible: ( id )=>
$( ".thumblistitem" ).not( "#thumb_#{id}" ).fadeTo( 500, 0.5 )
$( "#previewimages .thumbnail" ).off()
$( "##{id}" ).find( ".ajaxloader" ).remove()
$( ".action-reset" ).fadeIn()
return
# ### reset
# resets the app, deleting all canvas objects, flushing the images
reset: =>
@images = {}
$( "#previewimages" ).empty()
$( ".action-reset" ).fadeOut( ->
$( ".action-takepicture" ).fadeIn()
)
return
window.CheeseCake = CheeseCake | true | # # CheeseCake
# Team Centric Software GmbH, Exinferis 2012
# http://www.tcs.de
# a little tool based on the work of PI:NAME:<NAME>END_PI used to capture image of your webcam right in your browser
# and uploading them to s3 directly using a node.js based service for generating the s3 Signature and Policy.
# Will not work on anything else than the newest browsers.
class CheeseCake
constructor: ( @options ) ->
# extracting options or settings default values
@el = @options.el or $( "document" )
@format = @options.format or "image/jpeg"
@ext = @options.ext or "jpg"
@s3provider = @options.s3provider or ""
@cheese = new SayCheese( @el )
@images = {}
@cheese.on( "start", @initUI )
@cheese.on( "snapshot", @_snapShotHandler )
$( ".action-takepicture" ).on( "click", @takeSnapShot )
$( ".action-reset" ).on( "click", @reset )
@cheese.start()
return
# ### initUI
# shows th ui after cheese has been initialized and the webcam access has been allowed
initUI: =>
$( ".action-takepicture" ).fadeIn()
return
# ### takeSnapShot
# taking a snapshot using the webcam and publishing a corresponding event
takeSnapShot: =>
@cheese.takeSnapshot( )
return
# ### _snapShotHandler
# decides what to do with a previous taken snapshot
_snapShotHandler: ( snapshot ) =>
_id = _.uniqueId( "canvas_" )
_data = snapshot.toDataURL( @format )
@images[ _id ] = @dataURItoBlob( _data )
# removing an old image from the ui and the images object
if $( "#previewimages .thumbnail" ).length is 4
_toRemoveid = $( "#previewimages .thumblistitem:first" ).attr( "id" )
@images = _.omit( @images, _toRemoveid )
$( "#previewimages .thumblistitem:first" ).remove()
$( "#previewimages" ).append( "<li class='thumblistitem' id='thumb_#{_id}'><span class='thumbnail' id='#{_id}'><span class='marker hide'></span></span></li>" )
$( "##{_id}" ).append( snapshot )
$( "##{_id}").on( "click", @_createUploadForm )
return
# transforms a data uri from the canvas object to a JS blob object
dataURItoBlob: (dataURI) =>
binary = atob(dataURI.split(",")[1])
array = []
i = 0
while i < binary.length
array.push binary.charCodeAt(i)
i++
return new Blob( [new Uint8Array(array)],
type: "image/jpeg"
)
# ### _requestCredentials
# requesting the upload credentials
_requestCredentials: ( mimetype, file, cb )=>
$.ajax(
type: "POST"
url: "#{@s3provider}/credentials"
data:
mimetype: mimetype
file: file
success: ( res )=>
cb( res )
return
error: ( err ) =>
alert( "An error occurred receiving the S3 credentials from the server." )
return
)
return
_createUploadForm: ( event ) =>
# getting the id and anttaching the ajax loader to it
_id = $( event.currentTarget ).attr( "id" )
$( "##{_id}" ).append( "<span class='ajaxloader'></span>")
$( ".action-takepicture" ).fadeOut()
if @images[_id]?
_fName = "pic_#{moment().valueOf().toString( 16 )}#{randomnumber=Math.floor(Math.random()*10000000).toString(6)}"
@_requestCredentials( @format, _fName, ( res ) =>
# building html5 / formdata object for use with xhr transport
formData = new FormData
formData.append( "key", "#{res.FileDescriptor}.#{@ext}" )
formData.append( "acl", "public-read" )
formData.append( "Content-Disposition", "" )
formData.append( "Content-Type", res.ContentType )
formData.append( "success_action_status", res.ActionStatus )
formData.append( "AWSAccessKeyId", res.Key )
formData.append( "Policy", res.PolicyBase64 )
formData.append( "Signature", res.Signature )
formData.append( "file", @images[_id] )
try
xhr = new XMLHttpRequest
xhr.onreadystatechange = =>
#xhr request has finished - one way or another
if xhr.readyState is 4
if xhr.status is 200 or xhr.status is 201
@_uploadFinished( _id, "http://#{res.Bucket}.s3.amazonaws.com/#{res.FileDescriptor}.#{@ext}" )
else
@_uploadError( _id, xhr.status )
return
xhr.onprogress = ( progress ) =>
# do something fancy here - maybe an animated progress bar?
return
xhr.open "POST", "http://#{res.Bucket}.s3.amazonaws.com", true
xhr.send formData
catch e
@_uploadError( _id, e )
return
)
return
# ### _uploadFinished
_uploadFinished: ( id, link ) =>
@_setUploadedVisible( id )
$( "##{id}" ).find( ".marker" ).css( "background-position": "left bottom", "display": "block" )
$( "#thumb_#{id}" ).append( "<div class='alert alert-success'>Your picture has been uploaded like a boss! <a href='#{link}' target='blank'>Link</a></div>" )
return
# ### _uploadError
# handling the (hopefully rare) event of an error during the XHR transport
_uploadError: ( id, e )=>
@_setUploadedVisible( id )
$( "##{id}" ).find( ".marker" ).css( "background-position": "right bottom", "display": "block" )
$( "#thumb_#{id}" ).append( "<div class='alert alert-error'>An error occurred while uploading the file.</div>" )
return
# ### _setUploadedVisible
# emphasizes an element as the currently uploaded / uploading element by fading out the others
_setUploadedVisible: ( id )=>
$( ".thumblistitem" ).not( "#thumb_#{id}" ).fadeTo( 500, 0.5 )
$( "#previewimages .thumbnail" ).off()
$( "##{id}" ).find( ".ajaxloader" ).remove()
$( ".action-reset" ).fadeIn()
return
# ### reset
# resets the app, deleting all canvas objects, flushing the images
reset: =>
@images = {}
$( "#previewimages" ).empty()
$( ".action-reset" ).fadeOut( ->
$( ".action-takepicture" ).fadeIn()
)
return
window.CheeseCake = CheeseCake |
[
{
"context": "already taken.')\n else\n password = hash password\n db.run \"INSERT INTO Users (Username, Pa",
"end": 768,
"score": 0.95660400390625,
"start": 755,
"tag": "PASSWORD",
"value": "hash password"
},
{
"context": "password ]\n return done null, { Username: username, Password: password }\n )\n passport.use 'local-l",
"end": 914,
"score": 0.9554336667060852,
"start": 906,
"tag": "USERNAME",
"value": "username"
},
{
"context": " return done null, { Username: username, Password: password }\n )\n passport.use 'local-login', new LocalStra",
"end": 934,
"score": 0.9979374408721924,
"start": 926,
"tag": "PASSWORD",
"value": "password"
}
] | src/passport.coffee | MWPuppire/auth | 0 | LocalStrategy = require('passport-local').Strategy
crypto = require 'crypto'
hash = (str) ->
crypto.createHash('sha256').update(str).digest 'hex'
module.exports = (passport, db) ->
passport.serializeUser (user, done) ->
done null, user
passport.deserializeUser (user, done) ->
done null, user
passport.use 'local-signup', new LocalStrategy({
passReqToCallback: true
}, (req, username, password, done) ->
process.nextTick () ->
db.get "SELECT 1 FROM Users WHERE Username=? LIMIT 1;", [ username ], (err, exists) ->
if err
return done err
if exists
return done null, false, req.flash('signupMessage', 'That username is already taken.')
else
password = hash password
db.run "INSERT INTO Users (Username, Password) VALUES (?, ?);", [ username, password ]
return done null, { Username: username, Password: password }
)
passport.use 'local-login', new LocalStrategy({
passReqToCallback: true
}, (req, username, password, done) ->
db.get "SELECT * FROM Users WHERE Username=? LIMIT 1;", [ username ], (err, user) ->
if err
return done err
if not user
return done null, false, req.flash('loginMessage', 'Username not found.')
if hash(password) != user.Password
return done null, false, req.flash('loginMessage', 'Wrong password.')
return done null, user
)
| 210897 | LocalStrategy = require('passport-local').Strategy
crypto = require 'crypto'
hash = (str) ->
crypto.createHash('sha256').update(str).digest 'hex'
module.exports = (passport, db) ->
passport.serializeUser (user, done) ->
done null, user
passport.deserializeUser (user, done) ->
done null, user
passport.use 'local-signup', new LocalStrategy({
passReqToCallback: true
}, (req, username, password, done) ->
process.nextTick () ->
db.get "SELECT 1 FROM Users WHERE Username=? LIMIT 1;", [ username ], (err, exists) ->
if err
return done err
if exists
return done null, false, req.flash('signupMessage', 'That username is already taken.')
else
password = <PASSWORD>
db.run "INSERT INTO Users (Username, Password) VALUES (?, ?);", [ username, password ]
return done null, { Username: username, Password: <PASSWORD> }
)
passport.use 'local-login', new LocalStrategy({
passReqToCallback: true
}, (req, username, password, done) ->
db.get "SELECT * FROM Users WHERE Username=? LIMIT 1;", [ username ], (err, user) ->
if err
return done err
if not user
return done null, false, req.flash('loginMessage', 'Username not found.')
if hash(password) != user.Password
return done null, false, req.flash('loginMessage', 'Wrong password.')
return done null, user
)
| true | LocalStrategy = require('passport-local').Strategy
crypto = require 'crypto'
hash = (str) ->
crypto.createHash('sha256').update(str).digest 'hex'
module.exports = (passport, db) ->
passport.serializeUser (user, done) ->
done null, user
passport.deserializeUser (user, done) ->
done null, user
passport.use 'local-signup', new LocalStrategy({
passReqToCallback: true
}, (req, username, password, done) ->
process.nextTick () ->
db.get "SELECT 1 FROM Users WHERE Username=? LIMIT 1;", [ username ], (err, exists) ->
if err
return done err
if exists
return done null, false, req.flash('signupMessage', 'That username is already taken.')
else
password = PI:PASSWORD:<PASSWORD>END_PI
db.run "INSERT INTO Users (Username, Password) VALUES (?, ?);", [ username, password ]
return done null, { Username: username, Password: PI:PASSWORD:<PASSWORD>END_PI }
)
passport.use 'local-login', new LocalStrategy({
passReqToCallback: true
}, (req, username, password, done) ->
db.get "SELECT * FROM Users WHERE Username=? LIMIT 1;", [ username ], (err, user) ->
if err
return done err
if not user
return done null, false, req.flash('loginMessage', 'Username not found.')
if hash(password) != user.Password
return done null, false, req.flash('loginMessage', 'Wrong password.')
return done null, user
)
|
[
{
"context": " nickname :\n label : 'Nickname'\n cssClass : 'custom-link-view'\n ",
"end": 6454,
"score": 0.8320363163948059,
"start": 6446,
"tag": "NAME",
"value": "Nickname"
}
] | client/app/lib/providers/machinesettingsgeneralview.coffee | ezgikaysi/koding | 1 | kd = require 'kd'
KDView = kd.View
Encoder = require 'htmlencode'
Machine = require './machine'
isKoding = require 'app/util/isKoding'
showError = require 'app/util/showError'
selectText = require 'app/util/selectText'
KodingSwitch = require '../commonviews/kodingswitch'
KDLoaderView = kd.LoaderView
CustomLinkView = require '../customlinkview'
CopyTooltipView = require 'app/components/common/copytooltipview'
KDHitEnterInputView = kd.HitEnterInputView
KDFormViewWithFields = kd.FormViewWithFields
ComputeErrorUsageModal = require './computeerrorusagemodal'
StackTemplateReadmeModal = require 'app/stacks/stacktemplatereadmemodal'
StackTemplateContentModal = require 'app/stacks/stacktemplatecontentmodal'
module.exports = class MachineSettingsGeneralView extends KDView
{ Running, Starting } = Machine.State
constructor: (options, data) ->
super options, data
@machine = @getData()
@createForm()
@fetchMachineState()
@bindViewEvents()
handleMachineStateChanged: (state) ->
method = if state then 'start' else 'stop'
kd.singletons.computeController[method] @machine
@emit 'ModalDestroyRequested'
handleAlwaysOnStateChanged: (state) ->
{ alwaysOn } = @form.inputs
{ computeController } = kd.singletons
computeController.fetchUserPlan (plan) =>
computeController.setAlwaysOn @machine, state, (err) =>
return unless err
if err.name is 'UsageLimitReached' and plan isnt 'hobbyist'
@emit 'ModalDestroyRequested'
kd.utils.defer -> new ComputeErrorUsageModal { plan }
else
showError err
alwaysOn.setOff no
handleNicknameUpdate: ->
{ nickEdit, nickname } = @form.inputs
newLabel = nickEdit.getValue()
if kd.utils.slugify(newLabel) is ''
return showError 'Nickname cannot be empty.'
@machine.setLabel newLabel, (err, newSlug) =>
return if showError err
label = Encoder.XSSEncode newLabel
nickname.updatePartial "<span class='edit'>update</span> #{label}"
nickEdit.hide()
nickname.show()
@machine.emit 'MachineLabelUpdated', newLabel, newSlug
# @emit 'ModalDestroyRequested'
fetchMachineState: ->
machineId = @machine._id
currentState = @machine.status.state
{ statusToggle, statusLoader } = @form.inputs
statusToggle.hide()
kd.singletons.computeController.getKloud()
.info { machineId, currentState }
.then (response) ->
if response.State is Running
then statusToggle.setOn no
else statusToggle.setOff no
statusToggle.show()
statusLoader.hide()
.catch (err) ->
kd.warn 'Failed to fetch info for machine settings:', err
statusLoader.hide()
statusToggle.setOff no
statusToggle.show()
bindViewEvents: ->
{ hasClass } = kd.dom
{ computeController } = kd.singletons
{ nickname, nickEdit, buildlogs, publicIp, stackInfo } = @form.inputs
nickname.on 'click', (e) =>
return unless e.target.tagName is 'SPAN'
nickname.hide()
kd.singletons.windowController.addLayer nickEdit
nickEdit.once 'ReceivedClickElsewhere', ->
nickEdit.hide()
nickname.show()
nickEdit.setValue Encoder.htmlDecode @machine.label
nickEdit.show()
kd.utils.defer -> nickEdit.setFocus()
buildlogs.on 'click', (e) =>
return unless @machine.isRunning()
return unless e.target.tagName is 'SPAN'
buildlogs.updatePartial 'loading...'
computeController.showBuildLogs @machine
kd.utils.wait 1000, @lazyBound 'emit', 'ModalDestroyRequested'
publicIp.on 'click', ->
selectText publicIp.getElement()
publicIp.showTooltip()
stackInfoProcess = no
stackInfo.on 'click', (event) =>
return if stackInfoProcess
{ target } = event
if hasClass target, 'permission'
return computeController.fixMachinePermissions @machine
@getStackTemplate (err, template) ->
stackInfoProcess = no
return unless template
if hasClass target, 'readme'
new StackTemplateReadmeModal {}, template
else if hasClass target, 'template'
new StackTemplateContentModal {}, template
getStackTemplate: (callback) ->
{ computeController } = kd.singletons
{ templateId } = @machine.jMachine.generatedFrom
computeController.fetchBaseStackTemplate { baseStackId : templateId }, (err, template) ->
callback err, template
createForm: ->
isAws = @machine.provider is 'aws'
running = @machine.status.state in [ Running, Starting ]
accessUri = "http://#{@machine.domain}"
isManaged = @machine.isManaged()
logsMessage = if @machine.isRunning() \
then "<span class='link-view'>show logs</span>"
else 'Please turn on the machine to see logs'
publicIpView = new KDView
partial : @machine.ipAddress or 'N/A'
fixPermissionLink = if running and @machine.getOldOwner()
then "<span class='link-view permission'>fix permissions</span>" else ''
@addSubView @form = new KDFormViewWithFields
cssClass : 'AppModal-form'
fields :
statusToggle :
cssClass : if isManaged then 'hidden'
label : 'On/Off'
defaultValue : running
itemClass : KodingSwitch
disabled : @machine.isPermanent()
callback : @bound 'handleMachineStateChanged'
nextElement :
statusLoader:
itemClass : KDLoaderView
cssClass : 'in-progress'
size :
width : 16
height : 16
loaderOptions :
color : '#333333'
showLoader: yes
alwaysOn :
label : 'Keep VM always on'
defaultValue : @machine.alwaysOn
itemClass : KodingSwitch
cssClass : if isManaged then 'statustoggle hidden' else 'statustoggle'
disabled : @machine.isPermanent()
callback : @bound 'handleAlwaysOnStateChanged'
nickname :
label : 'Nickname'
cssClass : 'custom-link-view'
itemClass : KDView
partial : "<span class='edit'>update</span> #{@machine.label}"
nextElement :
nickEdit :
itemClass : KDHitEnterInputView
type : 'text'
cssClass : 'hidden'
attributes: { spellcheck: false }
callback : => @handleNicknameUpdate() # bound won't work.
publicIp :
label : 'Public IP'
itemClass : CopyTooltipView
childView : publicIpView
cssClass : if running then 'custom-link-view' else 'hidden'
accessUri :
label : 'Assigned URL'
cssClass : if isManaged or isAws then 'assigned-url hidden' else 'assigned-url'
itemClass : CustomLinkView
title : @machine.domain
href : accessUri
target : '_blank'
buildlogs :
label : 'Build logs'
cssClass : if isAws then 'custom-link-view' else 'hidden'
itemClass : KDView
partial : logsMessage
stackInfo :
label : 'Stack information'
cssClass : if isKoding() then 'hidden' else 'custom-link-view stack-information'
itemClass : KDView
partial : """
<span class="link-view template">show template</span>
<span class="link-view readme">show readme</span>
#{fixPermissionLink}
"""
| 4268 | kd = require 'kd'
KDView = kd.View
Encoder = require 'htmlencode'
Machine = require './machine'
isKoding = require 'app/util/isKoding'
showError = require 'app/util/showError'
selectText = require 'app/util/selectText'
KodingSwitch = require '../commonviews/kodingswitch'
KDLoaderView = kd.LoaderView
CustomLinkView = require '../customlinkview'
CopyTooltipView = require 'app/components/common/copytooltipview'
KDHitEnterInputView = kd.HitEnterInputView
KDFormViewWithFields = kd.FormViewWithFields
ComputeErrorUsageModal = require './computeerrorusagemodal'
StackTemplateReadmeModal = require 'app/stacks/stacktemplatereadmemodal'
StackTemplateContentModal = require 'app/stacks/stacktemplatecontentmodal'
module.exports = class MachineSettingsGeneralView extends KDView
{ Running, Starting } = Machine.State
constructor: (options, data) ->
super options, data
@machine = @getData()
@createForm()
@fetchMachineState()
@bindViewEvents()
handleMachineStateChanged: (state) ->
method = if state then 'start' else 'stop'
kd.singletons.computeController[method] @machine
@emit 'ModalDestroyRequested'
handleAlwaysOnStateChanged: (state) ->
{ alwaysOn } = @form.inputs
{ computeController } = kd.singletons
computeController.fetchUserPlan (plan) =>
computeController.setAlwaysOn @machine, state, (err) =>
return unless err
if err.name is 'UsageLimitReached' and plan isnt 'hobbyist'
@emit 'ModalDestroyRequested'
kd.utils.defer -> new ComputeErrorUsageModal { plan }
else
showError err
alwaysOn.setOff no
handleNicknameUpdate: ->
{ nickEdit, nickname } = @form.inputs
newLabel = nickEdit.getValue()
if kd.utils.slugify(newLabel) is ''
return showError 'Nickname cannot be empty.'
@machine.setLabel newLabel, (err, newSlug) =>
return if showError err
label = Encoder.XSSEncode newLabel
nickname.updatePartial "<span class='edit'>update</span> #{label}"
nickEdit.hide()
nickname.show()
@machine.emit 'MachineLabelUpdated', newLabel, newSlug
# @emit 'ModalDestroyRequested'
fetchMachineState: ->
machineId = @machine._id
currentState = @machine.status.state
{ statusToggle, statusLoader } = @form.inputs
statusToggle.hide()
kd.singletons.computeController.getKloud()
.info { machineId, currentState }
.then (response) ->
if response.State is Running
then statusToggle.setOn no
else statusToggle.setOff no
statusToggle.show()
statusLoader.hide()
.catch (err) ->
kd.warn 'Failed to fetch info for machine settings:', err
statusLoader.hide()
statusToggle.setOff no
statusToggle.show()
bindViewEvents: ->
{ hasClass } = kd.dom
{ computeController } = kd.singletons
{ nickname, nickEdit, buildlogs, publicIp, stackInfo } = @form.inputs
nickname.on 'click', (e) =>
return unless e.target.tagName is 'SPAN'
nickname.hide()
kd.singletons.windowController.addLayer nickEdit
nickEdit.once 'ReceivedClickElsewhere', ->
nickEdit.hide()
nickname.show()
nickEdit.setValue Encoder.htmlDecode @machine.label
nickEdit.show()
kd.utils.defer -> nickEdit.setFocus()
buildlogs.on 'click', (e) =>
return unless @machine.isRunning()
return unless e.target.tagName is 'SPAN'
buildlogs.updatePartial 'loading...'
computeController.showBuildLogs @machine
kd.utils.wait 1000, @lazyBound 'emit', 'ModalDestroyRequested'
publicIp.on 'click', ->
selectText publicIp.getElement()
publicIp.showTooltip()
stackInfoProcess = no
stackInfo.on 'click', (event) =>
return if stackInfoProcess
{ target } = event
if hasClass target, 'permission'
return computeController.fixMachinePermissions @machine
@getStackTemplate (err, template) ->
stackInfoProcess = no
return unless template
if hasClass target, 'readme'
new StackTemplateReadmeModal {}, template
else if hasClass target, 'template'
new StackTemplateContentModal {}, template
getStackTemplate: (callback) ->
{ computeController } = kd.singletons
{ templateId } = @machine.jMachine.generatedFrom
computeController.fetchBaseStackTemplate { baseStackId : templateId }, (err, template) ->
callback err, template
createForm: ->
isAws = @machine.provider is 'aws'
running = @machine.status.state in [ Running, Starting ]
accessUri = "http://#{@machine.domain}"
isManaged = @machine.isManaged()
logsMessage = if @machine.isRunning() \
then "<span class='link-view'>show logs</span>"
else 'Please turn on the machine to see logs'
publicIpView = new KDView
partial : @machine.ipAddress or 'N/A'
fixPermissionLink = if running and @machine.getOldOwner()
then "<span class='link-view permission'>fix permissions</span>" else ''
@addSubView @form = new KDFormViewWithFields
cssClass : 'AppModal-form'
fields :
statusToggle :
cssClass : if isManaged then 'hidden'
label : 'On/Off'
defaultValue : running
itemClass : KodingSwitch
disabled : @machine.isPermanent()
callback : @bound 'handleMachineStateChanged'
nextElement :
statusLoader:
itemClass : KDLoaderView
cssClass : 'in-progress'
size :
width : 16
height : 16
loaderOptions :
color : '#333333'
showLoader: yes
alwaysOn :
label : 'Keep VM always on'
defaultValue : @machine.alwaysOn
itemClass : KodingSwitch
cssClass : if isManaged then 'statustoggle hidden' else 'statustoggle'
disabled : @machine.isPermanent()
callback : @bound 'handleAlwaysOnStateChanged'
nickname :
label : '<NAME>'
cssClass : 'custom-link-view'
itemClass : KDView
partial : "<span class='edit'>update</span> #{@machine.label}"
nextElement :
nickEdit :
itemClass : KDHitEnterInputView
type : 'text'
cssClass : 'hidden'
attributes: { spellcheck: false }
callback : => @handleNicknameUpdate() # bound won't work.
publicIp :
label : 'Public IP'
itemClass : CopyTooltipView
childView : publicIpView
cssClass : if running then 'custom-link-view' else 'hidden'
accessUri :
label : 'Assigned URL'
cssClass : if isManaged or isAws then 'assigned-url hidden' else 'assigned-url'
itemClass : CustomLinkView
title : @machine.domain
href : accessUri
target : '_blank'
buildlogs :
label : 'Build logs'
cssClass : if isAws then 'custom-link-view' else 'hidden'
itemClass : KDView
partial : logsMessage
stackInfo :
label : 'Stack information'
cssClass : if isKoding() then 'hidden' else 'custom-link-view stack-information'
itemClass : KDView
partial : """
<span class="link-view template">show template</span>
<span class="link-view readme">show readme</span>
#{fixPermissionLink}
"""
| true | kd = require 'kd'
KDView = kd.View
Encoder = require 'htmlencode'
Machine = require './machine'
isKoding = require 'app/util/isKoding'
showError = require 'app/util/showError'
selectText = require 'app/util/selectText'
KodingSwitch = require '../commonviews/kodingswitch'
KDLoaderView = kd.LoaderView
CustomLinkView = require '../customlinkview'
CopyTooltipView = require 'app/components/common/copytooltipview'
KDHitEnterInputView = kd.HitEnterInputView
KDFormViewWithFields = kd.FormViewWithFields
ComputeErrorUsageModal = require './computeerrorusagemodal'
StackTemplateReadmeModal = require 'app/stacks/stacktemplatereadmemodal'
StackTemplateContentModal = require 'app/stacks/stacktemplatecontentmodal'
module.exports = class MachineSettingsGeneralView extends KDView
{ Running, Starting } = Machine.State
constructor: (options, data) ->
super options, data
@machine = @getData()
@createForm()
@fetchMachineState()
@bindViewEvents()
handleMachineStateChanged: (state) ->
method = if state then 'start' else 'stop'
kd.singletons.computeController[method] @machine
@emit 'ModalDestroyRequested'
handleAlwaysOnStateChanged: (state) ->
{ alwaysOn } = @form.inputs
{ computeController } = kd.singletons
computeController.fetchUserPlan (plan) =>
computeController.setAlwaysOn @machine, state, (err) =>
return unless err
if err.name is 'UsageLimitReached' and plan isnt 'hobbyist'
@emit 'ModalDestroyRequested'
kd.utils.defer -> new ComputeErrorUsageModal { plan }
else
showError err
alwaysOn.setOff no
handleNicknameUpdate: ->
{ nickEdit, nickname } = @form.inputs
newLabel = nickEdit.getValue()
if kd.utils.slugify(newLabel) is ''
return showError 'Nickname cannot be empty.'
@machine.setLabel newLabel, (err, newSlug) =>
return if showError err
label = Encoder.XSSEncode newLabel
nickname.updatePartial "<span class='edit'>update</span> #{label}"
nickEdit.hide()
nickname.show()
@machine.emit 'MachineLabelUpdated', newLabel, newSlug
# @emit 'ModalDestroyRequested'
fetchMachineState: ->
machineId = @machine._id
currentState = @machine.status.state
{ statusToggle, statusLoader } = @form.inputs
statusToggle.hide()
kd.singletons.computeController.getKloud()
.info { machineId, currentState }
.then (response) ->
if response.State is Running
then statusToggle.setOn no
else statusToggle.setOff no
statusToggle.show()
statusLoader.hide()
.catch (err) ->
kd.warn 'Failed to fetch info for machine settings:', err
statusLoader.hide()
statusToggle.setOff no
statusToggle.show()
bindViewEvents: ->
{ hasClass } = kd.dom
{ computeController } = kd.singletons
{ nickname, nickEdit, buildlogs, publicIp, stackInfo } = @form.inputs
nickname.on 'click', (e) =>
return unless e.target.tagName is 'SPAN'
nickname.hide()
kd.singletons.windowController.addLayer nickEdit
nickEdit.once 'ReceivedClickElsewhere', ->
nickEdit.hide()
nickname.show()
nickEdit.setValue Encoder.htmlDecode @machine.label
nickEdit.show()
kd.utils.defer -> nickEdit.setFocus()
buildlogs.on 'click', (e) =>
return unless @machine.isRunning()
return unless e.target.tagName is 'SPAN'
buildlogs.updatePartial 'loading...'
computeController.showBuildLogs @machine
kd.utils.wait 1000, @lazyBound 'emit', 'ModalDestroyRequested'
publicIp.on 'click', ->
selectText publicIp.getElement()
publicIp.showTooltip()
stackInfoProcess = no
stackInfo.on 'click', (event) =>
return if stackInfoProcess
{ target } = event
if hasClass target, 'permission'
return computeController.fixMachinePermissions @machine
@getStackTemplate (err, template) ->
stackInfoProcess = no
return unless template
if hasClass target, 'readme'
new StackTemplateReadmeModal {}, template
else if hasClass target, 'template'
new StackTemplateContentModal {}, template
getStackTemplate: (callback) ->
{ computeController } = kd.singletons
{ templateId } = @machine.jMachine.generatedFrom
computeController.fetchBaseStackTemplate { baseStackId : templateId }, (err, template) ->
callback err, template
createForm: ->
isAws = @machine.provider is 'aws'
running = @machine.status.state in [ Running, Starting ]
accessUri = "http://#{@machine.domain}"
isManaged = @machine.isManaged()
logsMessage = if @machine.isRunning() \
then "<span class='link-view'>show logs</span>"
else 'Please turn on the machine to see logs'
publicIpView = new KDView
partial : @machine.ipAddress or 'N/A'
fixPermissionLink = if running and @machine.getOldOwner()
then "<span class='link-view permission'>fix permissions</span>" else ''
@addSubView @form = new KDFormViewWithFields
cssClass : 'AppModal-form'
fields :
statusToggle :
cssClass : if isManaged then 'hidden'
label : 'On/Off'
defaultValue : running
itemClass : KodingSwitch
disabled : @machine.isPermanent()
callback : @bound 'handleMachineStateChanged'
nextElement :
statusLoader:
itemClass : KDLoaderView
cssClass : 'in-progress'
size :
width : 16
height : 16
loaderOptions :
color : '#333333'
showLoader: yes
alwaysOn :
label : 'Keep VM always on'
defaultValue : @machine.alwaysOn
itemClass : KodingSwitch
cssClass : if isManaged then 'statustoggle hidden' else 'statustoggle'
disabled : @machine.isPermanent()
callback : @bound 'handleAlwaysOnStateChanged'
nickname :
label : 'PI:NAME:<NAME>END_PI'
cssClass : 'custom-link-view'
itemClass : KDView
partial : "<span class='edit'>update</span> #{@machine.label}"
nextElement :
nickEdit :
itemClass : KDHitEnterInputView
type : 'text'
cssClass : 'hidden'
attributes: { spellcheck: false }
callback : => @handleNicknameUpdate() # bound won't work.
publicIp :
label : 'Public IP'
itemClass : CopyTooltipView
childView : publicIpView
cssClass : if running then 'custom-link-view' else 'hidden'
accessUri :
label : 'Assigned URL'
cssClass : if isManaged or isAws then 'assigned-url hidden' else 'assigned-url'
itemClass : CustomLinkView
title : @machine.domain
href : accessUri
target : '_blank'
buildlogs :
label : 'Build logs'
cssClass : if isAws then 'custom-link-view' else 'hidden'
itemClass : KDView
partial : logsMessage
stackInfo :
label : 'Stack information'
cssClass : if isKoding() then 'hidden' else 'custom-link-view stack-information'
itemClass : KDView
partial : """
<span class="link-view template">show template</span>
<span class="link-view readme">show readme</span>
#{fixPermissionLink}
"""
|
[
{
"context": "Formbuilder.registerField 'textarea',\n\n name: 'Long Answer'\n\n order: 5\n\n view: \"\"\"\n <textarea class='rf",
"end": 59,
"score": 0.8853768110275269,
"start": 48,
"tag": "NAME",
"value": "Long Answer"
}
] | src/scripts/fields/textarea.coffee | ahashmi929/formbuilder | 0 | Formbuilder.registerField 'textarea',
name: 'Long Answer'
order: 5
view: """
<textarea class='rf-size-<%= rf.get(Formbuilder.options.mappings.SIZE) %>'></textarea>
"""
edit: """
<%= Formbuilder.templates['edit/populate_from']({ rf: rf }) %>
"""
addButton: """
<span class="fa fa-paragraph"></span> Paragraph
"""
defaultAttributes: (attrs) ->
attrs.options.size = 'small'
attrs
| 168763 | Formbuilder.registerField 'textarea',
name: '<NAME>'
order: 5
view: """
<textarea class='rf-size-<%= rf.get(Formbuilder.options.mappings.SIZE) %>'></textarea>
"""
edit: """
<%= Formbuilder.templates['edit/populate_from']({ rf: rf }) %>
"""
addButton: """
<span class="fa fa-paragraph"></span> Paragraph
"""
defaultAttributes: (attrs) ->
attrs.options.size = 'small'
attrs
| true | Formbuilder.registerField 'textarea',
name: 'PI:NAME:<NAME>END_PI'
order: 5
view: """
<textarea class='rf-size-<%= rf.get(Formbuilder.options.mappings.SIZE) %>'></textarea>
"""
edit: """
<%= Formbuilder.templates['edit/populate_from']({ rf: rf }) %>
"""
addButton: """
<span class="fa fa-paragraph"></span> Paragraph
"""
defaultAttributes: (attrs) ->
attrs.options.size = 'small'
attrs
|
[
{
"context": ": window.current_url()\n name: name\n caption: window.current_level_name()\n ",
"end": 2753,
"score": 0.9952427744865417,
"start": 2749,
"tag": "NAME",
"value": "name"
}
] | app/assets/javascripts/packs/show-facebook.js.coffee | MichaelHoste/sokoban | 1 | $ ->
# connect to facebook
window.fbAsyncInit = ->
FB.init(
appId: $('meta[property="fb:app_id"]').attr('content')
channelUrl: '//sokoban-game.com/channel.html'
status: true
xfbml: true
cookie: true
frictionlessRequests: true
)
window.current_level_id = ->
$('#levels').find('.is-selected').attr('data-level-id')
window.current_level_name = ->
$('#levels').find('.is-selected').attr('data-level-name')
window.current_level_thumb = ->
$('#levels').find('.is-selected').attr('data-level-thumb')
window.current_url = ->
pack_slug = $('#packs').attr('data-pack-slug')
level_slug = $('#levels').find('.is-selected').attr('data-level-slug')
"https://sokoban-game.com/packs/#{pack_slug}/levels/#{level_slug}"
update_send_invitations_at = ->
current_user_id = $("#user-infos").attr('data-id')
$.post("/users/#{current_user_id}/update_send_invitations_at",
authenticity_token: window.authenticity_token()
)
post_to_fb = (options) ->
FB.ui(options, (request) ->
if request != null and request != undefined # if not click on cancel
update_send_invitations_at()
)
# TODO : send doesn't use "name", "description" and "picture" anymore and only use
# the informations on OpenGraph
window.facebook_send = (description, to = "", name = window.current_level_name()) ->
options =
method: 'send'
link: window.current_url()
redirect_uri: window.current_url()
name: name
description: description
to: to
picture: window.current_level_thumb()
post_to_fb(options)
# iteration > 0 if must be called recursively by batch of 50 friends (in the DOM)
window.facebook_app_request = (title, message, to, filters = [], data = "", iteration = 0) ->
options =
method: 'apprequests'
redirect_uri: window.current_url()
title: title
message: message
to: if iteration == 0 then to else $("#fb-friends .batch-#{iteration}").html()
filters: filters
data: data
if iteration == 0 or not $("#fb-friends .batch-#{iteration+1}").length
post_to_fb(options)
else
FB.ui(options, (request) ->
if request != null # if click on cancel, no more recursive calls
update_send_invitations_at()
window.facebook_app_request(title, message, to, filters, data, iteration + 1)
)
window.facebook_feed = (name, description, to = "") ->
options =
method: 'feed'
redirect_uri: window.current_url()
picture: window.current_level_thumb()
link: window.current_url()
name: name
caption: window.current_level_name()
description: description
to: to
post_to_fb(options)
window.facebook_send_invitation_message = (to = "") ->
window.facebook_send('Can you solve this Sokoban level?', to)
window.facebook_send_custom_invitation_message = ->
current_user_id = $("#user-infos").attr('data-id')
$.get("/users/#{current_user_id}/custom_invitation").success((data, status, xhr) ->
if data.f_id
window.facebook_send(data.description, data.f_id, data.name)
)
window.facebook_send_to_feed = (to = "", pushes = -1, moves = -1) ->
current_level_solved = $('#levels li.is-selected .s-icon-star').length
if current_level_solved
if pushes != -1 and moves != -1
description = "I just solved this Sokoban level with #{pushes} pushes and #{moves} moves and I bet that you can't!"
else
description = "I just solved this Sokoban level and I bet that you can't!"
else
description = "I can't solve this Sokoban level, can you help me?"
window.facebook_feed("Can you solve this Sokoban level?", description, to)
window.facebook_send_to_feed_in_ladder = (to, brag, pushes = -1, moves = -1) ->
if brag
title = "Can you solve this Sokoban level?"
if pushes != -1 and moves != -1
description = "I just beat your score on that Sokoban level! Can you do better than #{pushes} pushes and #{moves} moves?"
else
description = "I just beat your score on that Sokoban level! Can you do better?"
else
title = "Nice Job!"
description = "I can't solve this Sokoban level with so few pushes and moves as you!"
window.facebook_feed(title, description, to)
window.facebook_send_app_request = (to = '', filters = ['app_non_users']) ->
total_success = $('#user-infos').attr('data-global-success')
if total_success != '' and parseInt(total_success) <= 5
message = "Can you solve as many Sokoban levels as me?"
else
message = "I already solved #{total_success} Sokoban levels, can you beat me?"
window.facebook_app_request("Play Sokoban with me!", message, to, filters)
window.facebook_send_recursive_app_request = ->
total_success = $('#user-infos').attr('data-global-success')
if total_success != '' and parseInt(total_success) <= 5
message = "Can you solve as many Sokoban levels as me?"
else
message = "I already solved #{total_success} Sokoban levels, can you beat me?"
window.facebook_app_request('Play Sokoban with me!' , message, '', '', '', 1)
window.facebook_send_app_request_to_challenge_users = ->
f_ids = $('#invitations').find('.invite-item').map( ->
$(this).attr('data-f_id')
).get().join()
window.facebook_send_app_request(f_ids, [])
window.fbAsyncInit()
| 157368 | $ ->
# connect to facebook
window.fbAsyncInit = ->
FB.init(
appId: $('meta[property="fb:app_id"]').attr('content')
channelUrl: '//sokoban-game.com/channel.html'
status: true
xfbml: true
cookie: true
frictionlessRequests: true
)
window.current_level_id = ->
$('#levels').find('.is-selected').attr('data-level-id')
window.current_level_name = ->
$('#levels').find('.is-selected').attr('data-level-name')
window.current_level_thumb = ->
$('#levels').find('.is-selected').attr('data-level-thumb')
window.current_url = ->
pack_slug = $('#packs').attr('data-pack-slug')
level_slug = $('#levels').find('.is-selected').attr('data-level-slug')
"https://sokoban-game.com/packs/#{pack_slug}/levels/#{level_slug}"
update_send_invitations_at = ->
current_user_id = $("#user-infos").attr('data-id')
$.post("/users/#{current_user_id}/update_send_invitations_at",
authenticity_token: window.authenticity_token()
)
post_to_fb = (options) ->
FB.ui(options, (request) ->
if request != null and request != undefined # if not click on cancel
update_send_invitations_at()
)
# TODO : send doesn't use "name", "description" and "picture" anymore and only use
# the informations on OpenGraph
window.facebook_send = (description, to = "", name = window.current_level_name()) ->
options =
method: 'send'
link: window.current_url()
redirect_uri: window.current_url()
name: name
description: description
to: to
picture: window.current_level_thumb()
post_to_fb(options)
# iteration > 0 if must be called recursively by batch of 50 friends (in the DOM)
window.facebook_app_request = (title, message, to, filters = [], data = "", iteration = 0) ->
options =
method: 'apprequests'
redirect_uri: window.current_url()
title: title
message: message
to: if iteration == 0 then to else $("#fb-friends .batch-#{iteration}").html()
filters: filters
data: data
if iteration == 0 or not $("#fb-friends .batch-#{iteration+1}").length
post_to_fb(options)
else
FB.ui(options, (request) ->
if request != null # if click on cancel, no more recursive calls
update_send_invitations_at()
window.facebook_app_request(title, message, to, filters, data, iteration + 1)
)
window.facebook_feed = (name, description, to = "") ->
options =
method: 'feed'
redirect_uri: window.current_url()
picture: window.current_level_thumb()
link: window.current_url()
name: <NAME>
caption: window.current_level_name()
description: description
to: to
post_to_fb(options)
window.facebook_send_invitation_message = (to = "") ->
window.facebook_send('Can you solve this Sokoban level?', to)
window.facebook_send_custom_invitation_message = ->
current_user_id = $("#user-infos").attr('data-id')
$.get("/users/#{current_user_id}/custom_invitation").success((data, status, xhr) ->
if data.f_id
window.facebook_send(data.description, data.f_id, data.name)
)
window.facebook_send_to_feed = (to = "", pushes = -1, moves = -1) ->
current_level_solved = $('#levels li.is-selected .s-icon-star').length
if current_level_solved
if pushes != -1 and moves != -1
description = "I just solved this Sokoban level with #{pushes} pushes and #{moves} moves and I bet that you can't!"
else
description = "I just solved this Sokoban level and I bet that you can't!"
else
description = "I can't solve this Sokoban level, can you help me?"
window.facebook_feed("Can you solve this Sokoban level?", description, to)
window.facebook_send_to_feed_in_ladder = (to, brag, pushes = -1, moves = -1) ->
if brag
title = "Can you solve this Sokoban level?"
if pushes != -1 and moves != -1
description = "I just beat your score on that Sokoban level! Can you do better than #{pushes} pushes and #{moves} moves?"
else
description = "I just beat your score on that Sokoban level! Can you do better?"
else
title = "Nice Job!"
description = "I can't solve this Sokoban level with so few pushes and moves as you!"
window.facebook_feed(title, description, to)
window.facebook_send_app_request = (to = '', filters = ['app_non_users']) ->
total_success = $('#user-infos').attr('data-global-success')
if total_success != '' and parseInt(total_success) <= 5
message = "Can you solve as many Sokoban levels as me?"
else
message = "I already solved #{total_success} Sokoban levels, can you beat me?"
window.facebook_app_request("Play Sokoban with me!", message, to, filters)
window.facebook_send_recursive_app_request = ->
total_success = $('#user-infos').attr('data-global-success')
if total_success != '' and parseInt(total_success) <= 5
message = "Can you solve as many Sokoban levels as me?"
else
message = "I already solved #{total_success} Sokoban levels, can you beat me?"
window.facebook_app_request('Play Sokoban with me!' , message, '', '', '', 1)
window.facebook_send_app_request_to_challenge_users = ->
f_ids = $('#invitations').find('.invite-item').map( ->
$(this).attr('data-f_id')
).get().join()
window.facebook_send_app_request(f_ids, [])
window.fbAsyncInit()
| true | $ ->
# connect to facebook
window.fbAsyncInit = ->
FB.init(
appId: $('meta[property="fb:app_id"]').attr('content')
channelUrl: '//sokoban-game.com/channel.html'
status: true
xfbml: true
cookie: true
frictionlessRequests: true
)
window.current_level_id = ->
$('#levels').find('.is-selected').attr('data-level-id')
window.current_level_name = ->
$('#levels').find('.is-selected').attr('data-level-name')
window.current_level_thumb = ->
$('#levels').find('.is-selected').attr('data-level-thumb')
window.current_url = ->
pack_slug = $('#packs').attr('data-pack-slug')
level_slug = $('#levels').find('.is-selected').attr('data-level-slug')
"https://sokoban-game.com/packs/#{pack_slug}/levels/#{level_slug}"
update_send_invitations_at = ->
current_user_id = $("#user-infos").attr('data-id')
$.post("/users/#{current_user_id}/update_send_invitations_at",
authenticity_token: window.authenticity_token()
)
post_to_fb = (options) ->
FB.ui(options, (request) ->
if request != null and request != undefined # if not click on cancel
update_send_invitations_at()
)
# TODO : send doesn't use "name", "description" and "picture" anymore and only use
# the informations on OpenGraph
window.facebook_send = (description, to = "", name = window.current_level_name()) ->
options =
method: 'send'
link: window.current_url()
redirect_uri: window.current_url()
name: name
description: description
to: to
picture: window.current_level_thumb()
post_to_fb(options)
# iteration > 0 if must be called recursively by batch of 50 friends (in the DOM)
window.facebook_app_request = (title, message, to, filters = [], data = "", iteration = 0) ->
options =
method: 'apprequests'
redirect_uri: window.current_url()
title: title
message: message
to: if iteration == 0 then to else $("#fb-friends .batch-#{iteration}").html()
filters: filters
data: data
if iteration == 0 or not $("#fb-friends .batch-#{iteration+1}").length
post_to_fb(options)
else
FB.ui(options, (request) ->
if request != null # if click on cancel, no more recursive calls
update_send_invitations_at()
window.facebook_app_request(title, message, to, filters, data, iteration + 1)
)
window.facebook_feed = (name, description, to = "") ->
options =
method: 'feed'
redirect_uri: window.current_url()
picture: window.current_level_thumb()
link: window.current_url()
name: PI:NAME:<NAME>END_PI
caption: window.current_level_name()
description: description
to: to
post_to_fb(options)
window.facebook_send_invitation_message = (to = "") ->
window.facebook_send('Can you solve this Sokoban level?', to)
window.facebook_send_custom_invitation_message = ->
current_user_id = $("#user-infos").attr('data-id')
$.get("/users/#{current_user_id}/custom_invitation").success((data, status, xhr) ->
if data.f_id
window.facebook_send(data.description, data.f_id, data.name)
)
window.facebook_send_to_feed = (to = "", pushes = -1, moves = -1) ->
current_level_solved = $('#levels li.is-selected .s-icon-star').length
if current_level_solved
if pushes != -1 and moves != -1
description = "I just solved this Sokoban level with #{pushes} pushes and #{moves} moves and I bet that you can't!"
else
description = "I just solved this Sokoban level and I bet that you can't!"
else
description = "I can't solve this Sokoban level, can you help me?"
window.facebook_feed("Can you solve this Sokoban level?", description, to)
window.facebook_send_to_feed_in_ladder = (to, brag, pushes = -1, moves = -1) ->
if brag
title = "Can you solve this Sokoban level?"
if pushes != -1 and moves != -1
description = "I just beat your score on that Sokoban level! Can you do better than #{pushes} pushes and #{moves} moves?"
else
description = "I just beat your score on that Sokoban level! Can you do better?"
else
title = "Nice Job!"
description = "I can't solve this Sokoban level with so few pushes and moves as you!"
window.facebook_feed(title, description, to)
window.facebook_send_app_request = (to = '', filters = ['app_non_users']) ->
total_success = $('#user-infos').attr('data-global-success')
if total_success != '' and parseInt(total_success) <= 5
message = "Can you solve as many Sokoban levels as me?"
else
message = "I already solved #{total_success} Sokoban levels, can you beat me?"
window.facebook_app_request("Play Sokoban with me!", message, to, filters)
window.facebook_send_recursive_app_request = ->
total_success = $('#user-infos').attr('data-global-success')
if total_success != '' and parseInt(total_success) <= 5
message = "Can you solve as many Sokoban levels as me?"
else
message = "I already solved #{total_success} Sokoban levels, can you beat me?"
window.facebook_app_request('Play Sokoban with me!' , message, '', '', '', 1)
window.facebook_send_app_request_to_challenge_users = ->
f_ids = $('#invitations').find('.invite-item').map( ->
$(this).attr('data-f_id')
).get().join()
window.facebook_send_app_request(f_ids, [])
window.fbAsyncInit()
|
[
{
"context": "###\njQuery Gridly\nCopyright 2013 Kevin Sylvestre\n1.2.3\n###\n\n\"use strict\"\n\n$ = jQuery\n\nclass Animat",
"end": 48,
"score": 0.9998623132705688,
"start": 33,
"tag": "NAME",
"value": "Kevin Sylvestre"
}
] | javascripts/jquery.gridly.coffee | jiji262/jquery-gridly | 2 | ###
jQuery Gridly
Copyright 2013 Kevin Sylvestre
1.2.3
###
"use strict"
$ = jQuery
class Animation
@transitions:
"webkitTransition": "webkitTransitionEnd"
"mozTransition": "mozTransitionEnd"
"oTransition": "oTransitionEnd"
"transition": "transitionend"
@transition: ($el) ->
el = $el[0]
return result for type, result of @transitions when el.style[type]?
@execute: ($el, callback) ->
transition = @transition($el)
if transition? then $el.one(transition, callback) else callback()
class Draggable
constructor: ($container, selector, callbacks) ->
@$container = $container
@selector = selector
@callbacks = callbacks
@toggle()
bind: (method = 'on') =>
$(document)[method] 'mousemove touchmove', @moved
$(document)[method] 'mouseup touchend touchcancel', @ended
toggle: (method = 'on') =>
@$container[method] 'mousedown touchstart', @selector, @began
@$container[method] 'click', @selector, @click
on: =>
@toggle('on')
off: =>
@toggle('off')
coordinate: (event) =>
switch event.type
when 'touchstart','touchmove','touchend','touchcancel' then event.originalEvent.touches[0]
else event
began: (event) =>
return if @$target
event.preventDefault()
event.stopPropagation()
@bind('on')
@$target = $(event.target).closest(@$container.find(@selector))
@$target.addClass('dragging')
@origin =
x: @coordinate(event).pageX - @$target.position().left
y: @coordinate(event).pageY - @$target.position().top
@callbacks?.began?(event)
ended: (event) =>
return unless @$target?
event.preventDefault()
event.stopPropagation()
@bind('off')
@$target.removeClass('dragging')
delete @$target
delete @origin
@callbacks?.ended?(event)
moved: (event) =>
return unless @$target?
event.preventDefault()
event.stopPropagation()
@$target.css
left: @coordinate(event).pageX - @origin.x
top: @coordinate(event).pageY - @origin.y
@dragged = @$target
@callbacks?.moved?(event)
click: (event) =>
return unless @dragged
event.preventDefault()
event.stopPropagation()
delete @dragged
class Gridly
@settings:
base: 60
gutter: 20
columns: 12
draggable:
zIndex: 800
selector : '> *'
@gridly: ($el, options = {}) ->
data = $el.data('_gridly')
unless data
data = new Gridly($el, options)
$el.data('_gridly', data)
return data
constructor: ($el, settings = {}) ->
@$el = $el
@settings = $.extend {}, Gridly.settings, settings
@ordinalize(@$('> *'))
@draggable() unless @settings.draggable is false
return @
ordinalize: ($elements) =>
for i in [0 .. $elements.length]
$element = $($elements[i])
$element.data('position', i)
reordinalize: ($element, position) =>
$element.data('position', position)
$: (selector) =>
@$el.find(selector)
compare: (d, s) =>
return +1 if d.y > s.y + s.h
return -1 if s.y > d.y + d.h
return +1 if (d.x + (d.w / 2)) > (s.x + (s.w / 2))
return -1 if (s.x + (s.w / 2)) > (d.x + (d.w / 2))
return 0
draggable: (method) =>
@_draggable ?= new Draggable @$el, @settings.draggable.selector,
began: @draggingBegan
ended: @draggingEnded
moved: @draggingMoved
@_draggable[method]() if method?
$sorted: ($elements) =>
($elements || @$('> *')).sort (a,b) ->
$a = $(a)
$b = $(b)
aPosition = $a.data('position')
bPosition = $b.data('position')
aPositionInt = parseInt(aPosition)
bPositionInt = parseInt(bPosition)
return -1 if aPosition? and not bPosition?
return +1 if bPosition? and not aPosition?
return -1 if not aPosition and not bPosition and $a.index() < $b.index()
return +1 if not bPosition and not aPosition and $b.index() < $a.index()
return -1 if aPositionInt < bPositionInt
return +1 if bPositionInt < aPositionInt
return 0
draggingBegan: (event) =>
$elements = @$sorted()
@ordinalize($elements)
setTimeout @layout, 0
@settings?.callbacks?.reordering?($elements)
draggingEnded: (event) =>
$elements = @$sorted()
@ordinalize($elements)
setTimeout @layout, 0
@settings?.callbacks?.reordered?($elements)
draggingMoved: (event) =>
$dragging = $(event.target).closest(@$(@settings.draggable.selector))
$elements = @$sorted(@$(@settings.draggable.selector))
positions = @structure($elements).positions
original = index = $dragging.data('position')
for element in positions.filter((position) -> position.$element.is($dragging))
element.x = $dragging.position().left
element.y = $dragging.position().top
element.w = $dragging.data('width') || $dragging.width()
element.h = $dragging.data('height') || $dragging.height()
positions.sort @compare
$elements = positions.map (position) -> position.$element
$elements = (@settings.callbacks?.optimize || @optimize)($elements)
for i in [0...$elements.length]
@reordinalize($($elements[i]), i)
@layout()
size: ($element) =>
(($element.data('width') || $element.width()) + @settings.gutter) / (@settings.base + @settings.gutter)
position: ($element, columns) =>
size = @size($element)
height = Infinity
column = 0
for i in [0 ... (columns.length - size)]
max = Math.max columns[i ... (i + size)]...
if max < height
height = max
column = i
for i in [column ... column + size]
columns[i] = height + ($element.data('height') || $element.height()) + @settings.gutter
x: (column * (@settings.base + @settings.gutter))
y: height
structure: ($elements = @$sorted()) =>
positions = []
columns = (0 for i in [0 .. @settings.columns])
for index in [0 ... $elements.length]
$element = $($elements[index])
position = @position($element, columns)
positions.push
x: position.x
y: position.y
w: $element.data('width') || $element.width()
h: $element.data('height') || $element.height()
$element: $element
height: Math.max columns...
positions: positions
layout: =>
$elements = (@settings.callbacks?.optimize || @optimize)(@$sorted())
structure = @structure($elements)
for index in [0 ... $elements.length]
$element = $($elements[index])
position = structure.positions[index]
continue if $element.is('.dragging')
$element.css
position: 'absolute'
left: position.x
top: position.y
@$el.css
height: structure.height
optimize: (originals) =>
results = []
columns = 0
while originals.length > 0
columns = 0 if columns is @settings.columns
index = 0
for index in [0...originals.length]
break if columns + @size($(originals[index])) <= @settings.columns
if index is originals.length
index = 0
columns = 0
columns += @size($(originals[index]))
# Move from originals into results
results.push(originals.splice(index,1)[0])
return results
$.fn.extend
gridly: (option = {}, parameters...) ->
@each ->
$this = $(@)
options = $.extend {}, $.fn.gridly.defaults, typeof option is "object" and option
action = if typeof option is "string" then option else option.action
action ?= "layout"
Gridly.gridly($this, options)[action](parameters)
| 44401 | ###
jQuery Gridly
Copyright 2013 <NAME>
1.2.3
###
"use strict"
$ = jQuery
class Animation
@transitions:
"webkitTransition": "webkitTransitionEnd"
"mozTransition": "mozTransitionEnd"
"oTransition": "oTransitionEnd"
"transition": "transitionend"
@transition: ($el) ->
el = $el[0]
return result for type, result of @transitions when el.style[type]?
@execute: ($el, callback) ->
transition = @transition($el)
if transition? then $el.one(transition, callback) else callback()
class Draggable
constructor: ($container, selector, callbacks) ->
@$container = $container
@selector = selector
@callbacks = callbacks
@toggle()
bind: (method = 'on') =>
$(document)[method] 'mousemove touchmove', @moved
$(document)[method] 'mouseup touchend touchcancel', @ended
toggle: (method = 'on') =>
@$container[method] 'mousedown touchstart', @selector, @began
@$container[method] 'click', @selector, @click
on: =>
@toggle('on')
off: =>
@toggle('off')
coordinate: (event) =>
switch event.type
when 'touchstart','touchmove','touchend','touchcancel' then event.originalEvent.touches[0]
else event
began: (event) =>
return if @$target
event.preventDefault()
event.stopPropagation()
@bind('on')
@$target = $(event.target).closest(@$container.find(@selector))
@$target.addClass('dragging')
@origin =
x: @coordinate(event).pageX - @$target.position().left
y: @coordinate(event).pageY - @$target.position().top
@callbacks?.began?(event)
ended: (event) =>
return unless @$target?
event.preventDefault()
event.stopPropagation()
@bind('off')
@$target.removeClass('dragging')
delete @$target
delete @origin
@callbacks?.ended?(event)
moved: (event) =>
return unless @$target?
event.preventDefault()
event.stopPropagation()
@$target.css
left: @coordinate(event).pageX - @origin.x
top: @coordinate(event).pageY - @origin.y
@dragged = @$target
@callbacks?.moved?(event)
click: (event) =>
return unless @dragged
event.preventDefault()
event.stopPropagation()
delete @dragged
class Gridly
@settings:
base: 60
gutter: 20
columns: 12
draggable:
zIndex: 800
selector : '> *'
@gridly: ($el, options = {}) ->
data = $el.data('_gridly')
unless data
data = new Gridly($el, options)
$el.data('_gridly', data)
return data
constructor: ($el, settings = {}) ->
@$el = $el
@settings = $.extend {}, Gridly.settings, settings
@ordinalize(@$('> *'))
@draggable() unless @settings.draggable is false
return @
ordinalize: ($elements) =>
for i in [0 .. $elements.length]
$element = $($elements[i])
$element.data('position', i)
reordinalize: ($element, position) =>
$element.data('position', position)
$: (selector) =>
@$el.find(selector)
compare: (d, s) =>
return +1 if d.y > s.y + s.h
return -1 if s.y > d.y + d.h
return +1 if (d.x + (d.w / 2)) > (s.x + (s.w / 2))
return -1 if (s.x + (s.w / 2)) > (d.x + (d.w / 2))
return 0
draggable: (method) =>
@_draggable ?= new Draggable @$el, @settings.draggable.selector,
began: @draggingBegan
ended: @draggingEnded
moved: @draggingMoved
@_draggable[method]() if method?
$sorted: ($elements) =>
($elements || @$('> *')).sort (a,b) ->
$a = $(a)
$b = $(b)
aPosition = $a.data('position')
bPosition = $b.data('position')
aPositionInt = parseInt(aPosition)
bPositionInt = parseInt(bPosition)
return -1 if aPosition? and not bPosition?
return +1 if bPosition? and not aPosition?
return -1 if not aPosition and not bPosition and $a.index() < $b.index()
return +1 if not bPosition and not aPosition and $b.index() < $a.index()
return -1 if aPositionInt < bPositionInt
return +1 if bPositionInt < aPositionInt
return 0
draggingBegan: (event) =>
$elements = @$sorted()
@ordinalize($elements)
setTimeout @layout, 0
@settings?.callbacks?.reordering?($elements)
draggingEnded: (event) =>
$elements = @$sorted()
@ordinalize($elements)
setTimeout @layout, 0
@settings?.callbacks?.reordered?($elements)
draggingMoved: (event) =>
$dragging = $(event.target).closest(@$(@settings.draggable.selector))
$elements = @$sorted(@$(@settings.draggable.selector))
positions = @structure($elements).positions
original = index = $dragging.data('position')
for element in positions.filter((position) -> position.$element.is($dragging))
element.x = $dragging.position().left
element.y = $dragging.position().top
element.w = $dragging.data('width') || $dragging.width()
element.h = $dragging.data('height') || $dragging.height()
positions.sort @compare
$elements = positions.map (position) -> position.$element
$elements = (@settings.callbacks?.optimize || @optimize)($elements)
for i in [0...$elements.length]
@reordinalize($($elements[i]), i)
@layout()
size: ($element) =>
(($element.data('width') || $element.width()) + @settings.gutter) / (@settings.base + @settings.gutter)
position: ($element, columns) =>
size = @size($element)
height = Infinity
column = 0
for i in [0 ... (columns.length - size)]
max = Math.max columns[i ... (i + size)]...
if max < height
height = max
column = i
for i in [column ... column + size]
columns[i] = height + ($element.data('height') || $element.height()) + @settings.gutter
x: (column * (@settings.base + @settings.gutter))
y: height
structure: ($elements = @$sorted()) =>
positions = []
columns = (0 for i in [0 .. @settings.columns])
for index in [0 ... $elements.length]
$element = $($elements[index])
position = @position($element, columns)
positions.push
x: position.x
y: position.y
w: $element.data('width') || $element.width()
h: $element.data('height') || $element.height()
$element: $element
height: Math.max columns...
positions: positions
layout: =>
$elements = (@settings.callbacks?.optimize || @optimize)(@$sorted())
structure = @structure($elements)
for index in [0 ... $elements.length]
$element = $($elements[index])
position = structure.positions[index]
continue if $element.is('.dragging')
$element.css
position: 'absolute'
left: position.x
top: position.y
@$el.css
height: structure.height
optimize: (originals) =>
results = []
columns = 0
while originals.length > 0
columns = 0 if columns is @settings.columns
index = 0
for index in [0...originals.length]
break if columns + @size($(originals[index])) <= @settings.columns
if index is originals.length
index = 0
columns = 0
columns += @size($(originals[index]))
# Move from originals into results
results.push(originals.splice(index,1)[0])
return results
$.fn.extend
gridly: (option = {}, parameters...) ->
@each ->
$this = $(@)
options = $.extend {}, $.fn.gridly.defaults, typeof option is "object" and option
action = if typeof option is "string" then option else option.action
action ?= "layout"
Gridly.gridly($this, options)[action](parameters)
| true | ###
jQuery Gridly
Copyright 2013 PI:NAME:<NAME>END_PI
1.2.3
###
"use strict"
$ = jQuery
class Animation
@transitions:
"webkitTransition": "webkitTransitionEnd"
"mozTransition": "mozTransitionEnd"
"oTransition": "oTransitionEnd"
"transition": "transitionend"
@transition: ($el) ->
el = $el[0]
return result for type, result of @transitions when el.style[type]?
@execute: ($el, callback) ->
transition = @transition($el)
if transition? then $el.one(transition, callback) else callback()
class Draggable
constructor: ($container, selector, callbacks) ->
@$container = $container
@selector = selector
@callbacks = callbacks
@toggle()
bind: (method = 'on') =>
$(document)[method] 'mousemove touchmove', @moved
$(document)[method] 'mouseup touchend touchcancel', @ended
toggle: (method = 'on') =>
@$container[method] 'mousedown touchstart', @selector, @began
@$container[method] 'click', @selector, @click
on: =>
@toggle('on')
off: =>
@toggle('off')
coordinate: (event) =>
switch event.type
when 'touchstart','touchmove','touchend','touchcancel' then event.originalEvent.touches[0]
else event
began: (event) =>
return if @$target
event.preventDefault()
event.stopPropagation()
@bind('on')
@$target = $(event.target).closest(@$container.find(@selector))
@$target.addClass('dragging')
@origin =
x: @coordinate(event).pageX - @$target.position().left
y: @coordinate(event).pageY - @$target.position().top
@callbacks?.began?(event)
ended: (event) =>
return unless @$target?
event.preventDefault()
event.stopPropagation()
@bind('off')
@$target.removeClass('dragging')
delete @$target
delete @origin
@callbacks?.ended?(event)
moved: (event) =>
return unless @$target?
event.preventDefault()
event.stopPropagation()
@$target.css
left: @coordinate(event).pageX - @origin.x
top: @coordinate(event).pageY - @origin.y
@dragged = @$target
@callbacks?.moved?(event)
click: (event) =>
return unless @dragged
event.preventDefault()
event.stopPropagation()
delete @dragged
class Gridly
@settings:
base: 60
gutter: 20
columns: 12
draggable:
zIndex: 800
selector : '> *'
@gridly: ($el, options = {}) ->
data = $el.data('_gridly')
unless data
data = new Gridly($el, options)
$el.data('_gridly', data)
return data
constructor: ($el, settings = {}) ->
@$el = $el
@settings = $.extend {}, Gridly.settings, settings
@ordinalize(@$('> *'))
@draggable() unless @settings.draggable is false
return @
ordinalize: ($elements) =>
for i in [0 .. $elements.length]
$element = $($elements[i])
$element.data('position', i)
reordinalize: ($element, position) =>
$element.data('position', position)
$: (selector) =>
@$el.find(selector)
compare: (d, s) =>
return +1 if d.y > s.y + s.h
return -1 if s.y > d.y + d.h
return +1 if (d.x + (d.w / 2)) > (s.x + (s.w / 2))
return -1 if (s.x + (s.w / 2)) > (d.x + (d.w / 2))
return 0
draggable: (method) =>
@_draggable ?= new Draggable @$el, @settings.draggable.selector,
began: @draggingBegan
ended: @draggingEnded
moved: @draggingMoved
@_draggable[method]() if method?
$sorted: ($elements) =>
($elements || @$('> *')).sort (a,b) ->
$a = $(a)
$b = $(b)
aPosition = $a.data('position')
bPosition = $b.data('position')
aPositionInt = parseInt(aPosition)
bPositionInt = parseInt(bPosition)
return -1 if aPosition? and not bPosition?
return +1 if bPosition? and not aPosition?
return -1 if not aPosition and not bPosition and $a.index() < $b.index()
return +1 if not bPosition and not aPosition and $b.index() < $a.index()
return -1 if aPositionInt < bPositionInt
return +1 if bPositionInt < aPositionInt
return 0
draggingBegan: (event) =>
$elements = @$sorted()
@ordinalize($elements)
setTimeout @layout, 0
@settings?.callbacks?.reordering?($elements)
draggingEnded: (event) =>
$elements = @$sorted()
@ordinalize($elements)
setTimeout @layout, 0
@settings?.callbacks?.reordered?($elements)
draggingMoved: (event) =>
$dragging = $(event.target).closest(@$(@settings.draggable.selector))
$elements = @$sorted(@$(@settings.draggable.selector))
positions = @structure($elements).positions
original = index = $dragging.data('position')
for element in positions.filter((position) -> position.$element.is($dragging))
element.x = $dragging.position().left
element.y = $dragging.position().top
element.w = $dragging.data('width') || $dragging.width()
element.h = $dragging.data('height') || $dragging.height()
positions.sort @compare
$elements = positions.map (position) -> position.$element
$elements = (@settings.callbacks?.optimize || @optimize)($elements)
for i in [0...$elements.length]
@reordinalize($($elements[i]), i)
@layout()
size: ($element) =>
(($element.data('width') || $element.width()) + @settings.gutter) / (@settings.base + @settings.gutter)
position: ($element, columns) =>
size = @size($element)
height = Infinity
column = 0
for i in [0 ... (columns.length - size)]
max = Math.max columns[i ... (i + size)]...
if max < height
height = max
column = i
for i in [column ... column + size]
columns[i] = height + ($element.data('height') || $element.height()) + @settings.gutter
x: (column * (@settings.base + @settings.gutter))
y: height
structure: ($elements = @$sorted()) =>
positions = []
columns = (0 for i in [0 .. @settings.columns])
for index in [0 ... $elements.length]
$element = $($elements[index])
position = @position($element, columns)
positions.push
x: position.x
y: position.y
w: $element.data('width') || $element.width()
h: $element.data('height') || $element.height()
$element: $element
height: Math.max columns...
positions: positions
layout: =>
$elements = (@settings.callbacks?.optimize || @optimize)(@$sorted())
structure = @structure($elements)
for index in [0 ... $elements.length]
$element = $($elements[index])
position = structure.positions[index]
continue if $element.is('.dragging')
$element.css
position: 'absolute'
left: position.x
top: position.y
@$el.css
height: structure.height
optimize: (originals) =>
results = []
columns = 0
while originals.length > 0
columns = 0 if columns is @settings.columns
index = 0
for index in [0...originals.length]
break if columns + @size($(originals[index])) <= @settings.columns
if index is originals.length
index = 0
columns = 0
columns += @size($(originals[index]))
# Move from originals into results
results.push(originals.splice(index,1)[0])
return results
$.fn.extend
gridly: (option = {}, parameters...) ->
@each ->
$this = $(@)
options = $.extend {}, $.fn.gridly.defaults, typeof option is "object" and option
action = if typeof option is "string" then option else option.action
action ?= "layout"
Gridly.gridly($this, options)[action](parameters)
|
[
{
"context": "').notEmpty().isEmail()\n req.assert('password', 'Password cannot be blank.').notEmpty()\n redirect = req.param('redir",
"end": 1048,
"score": 0.5888108015060425,
"start": 1030,
"tag": "PASSWORD",
"value": "Password cannot be"
},
{
"context": ".user.id).then (user) ->\n user.compare_password old_password, (err, is_match) ->\n is_null = user",
"end": 2323,
"score": 0.6269378662109375,
"start": 2320,
"tag": "PASSWORD",
"value": "old"
},
{
"context": "word incorrect')\n\n user.hash_and_set_password new_password, (err) ->\n if err?\n return fail(\"",
"end": 2534,
"score": 0.8239685893058777,
"start": 2522,
"tag": "PASSWORD",
"value": "new_password"
}
] | src/controllers/user_controller.coffee | dwetterau/delta | 0 | passport = require 'passport'
models = require '../models'
exports.post_user_create = (req, res) ->
req.assert('email', 'Email is not valid.').isEmail()
req.assert('password', 'Password must be at least 4 characters long.').len(4)
req.assert('confirm_password', 'Passwords do not match.').equals(req.body.password)
errors = req.validationErrors()
fail = (error) ->
res.send {ok: false, error: error}
if errors
return fail errors
email = req.body.email
password = req.body.password
new_user = models.User.build({email})
new_user.hash_and_set_password password, (err) ->
if err?
return fail "Unable to create account at this time"
else
new_user.save().then ->
req.logIn new_user, (err) ->
res.send {ok: true, body: {user: new_user.to_json(), redirect_url: '/'}}
.catch ->
return fail 'Email already in use!'
exports.post_user_login = (req, res, next) ->
req.assert('email', 'Email is not valid.').notEmpty().isEmail()
req.assert('password', 'Password cannot be blank.').notEmpty()
redirect = req.param('redirect')
redirect_url = decodeURIComponent(redirect) || "/"
errors = req.validationErrors()
if errors?
return res.send {ok: false, error: errors}
passport.authenticate('local', (err, user, info) ->
if err?
return next(err)
if not user
return res.send {ok: false, error: 'Could not find user.'}
req.logIn user, (err) ->
if err?
return next err
res.send {ok: true, body: {redirect_url, user: user.toJSON()}}
)(req, res, next)
exports.get_user_logout = (req, res) ->
req.logout()
res.send {ok: true, body: {redirect_url: '/'}}
exports.post_change_password = (req, res) ->
req.assert('old_password', 'Old password must be at least 4 characters long.')
req.assert('new_password', 'New password must be at least 4 characters long.').len(4)
req.assert('confirm_password', 'Passwords do not match.').equals(req.param('new_password'))
errors = req.validationErrors()
if errors
return res.send {ok: false, error: errors}
old_password = req.param('old_password')
new_password = req.param('new_password')
fail = (message) ->
return res.send {ok: false, error: message}
models.User.find(req.user.id).then (user) ->
user.compare_password old_password, (err, is_match) ->
is_null = user.password is null
if not is_null and (not is_match or err)
return fail('Current password incorrect')
user.hash_and_set_password new_password, (err) ->
if err?
return fail("Failed to set new password")
user.save().then () ->
res.send {ok: true}
.catch fail
.catch fail
| 154279 | passport = require 'passport'
models = require '../models'
exports.post_user_create = (req, res) ->
req.assert('email', 'Email is not valid.').isEmail()
req.assert('password', 'Password must be at least 4 characters long.').len(4)
req.assert('confirm_password', 'Passwords do not match.').equals(req.body.password)
errors = req.validationErrors()
fail = (error) ->
res.send {ok: false, error: error}
if errors
return fail errors
email = req.body.email
password = req.body.password
new_user = models.User.build({email})
new_user.hash_and_set_password password, (err) ->
if err?
return fail "Unable to create account at this time"
else
new_user.save().then ->
req.logIn new_user, (err) ->
res.send {ok: true, body: {user: new_user.to_json(), redirect_url: '/'}}
.catch ->
return fail 'Email already in use!'
exports.post_user_login = (req, res, next) ->
req.assert('email', 'Email is not valid.').notEmpty().isEmail()
req.assert('password', '<PASSWORD> blank.').notEmpty()
redirect = req.param('redirect')
redirect_url = decodeURIComponent(redirect) || "/"
errors = req.validationErrors()
if errors?
return res.send {ok: false, error: errors}
passport.authenticate('local', (err, user, info) ->
if err?
return next(err)
if not user
return res.send {ok: false, error: 'Could not find user.'}
req.logIn user, (err) ->
if err?
return next err
res.send {ok: true, body: {redirect_url, user: user.toJSON()}}
)(req, res, next)
exports.get_user_logout = (req, res) ->
req.logout()
res.send {ok: true, body: {redirect_url: '/'}}
exports.post_change_password = (req, res) ->
req.assert('old_password', 'Old password must be at least 4 characters long.')
req.assert('new_password', 'New password must be at least 4 characters long.').len(4)
req.assert('confirm_password', 'Passwords do not match.').equals(req.param('new_password'))
errors = req.validationErrors()
if errors
return res.send {ok: false, error: errors}
old_password = req.param('old_password')
new_password = req.param('new_password')
fail = (message) ->
return res.send {ok: false, error: message}
models.User.find(req.user.id).then (user) ->
user.compare_password <PASSWORD>_password, (err, is_match) ->
is_null = user.password is null
if not is_null and (not is_match or err)
return fail('Current password incorrect')
user.hash_and_set_password <PASSWORD>, (err) ->
if err?
return fail("Failed to set new password")
user.save().then () ->
res.send {ok: true}
.catch fail
.catch fail
| true | passport = require 'passport'
models = require '../models'
exports.post_user_create = (req, res) ->
req.assert('email', 'Email is not valid.').isEmail()
req.assert('password', 'Password must be at least 4 characters long.').len(4)
req.assert('confirm_password', 'Passwords do not match.').equals(req.body.password)
errors = req.validationErrors()
fail = (error) ->
res.send {ok: false, error: error}
if errors
return fail errors
email = req.body.email
password = req.body.password
new_user = models.User.build({email})
new_user.hash_and_set_password password, (err) ->
if err?
return fail "Unable to create account at this time"
else
new_user.save().then ->
req.logIn new_user, (err) ->
res.send {ok: true, body: {user: new_user.to_json(), redirect_url: '/'}}
.catch ->
return fail 'Email already in use!'
exports.post_user_login = (req, res, next) ->
req.assert('email', 'Email is not valid.').notEmpty().isEmail()
req.assert('password', 'PI:PASSWORD:<PASSWORD>END_PI blank.').notEmpty()
redirect = req.param('redirect')
redirect_url = decodeURIComponent(redirect) || "/"
errors = req.validationErrors()
if errors?
return res.send {ok: false, error: errors}
passport.authenticate('local', (err, user, info) ->
if err?
return next(err)
if not user
return res.send {ok: false, error: 'Could not find user.'}
req.logIn user, (err) ->
if err?
return next err
res.send {ok: true, body: {redirect_url, user: user.toJSON()}}
)(req, res, next)
exports.get_user_logout = (req, res) ->
req.logout()
res.send {ok: true, body: {redirect_url: '/'}}
exports.post_change_password = (req, res) ->
req.assert('old_password', 'Old password must be at least 4 characters long.')
req.assert('new_password', 'New password must be at least 4 characters long.').len(4)
req.assert('confirm_password', 'Passwords do not match.').equals(req.param('new_password'))
errors = req.validationErrors()
if errors
return res.send {ok: false, error: errors}
old_password = req.param('old_password')
new_password = req.param('new_password')
fail = (message) ->
return res.send {ok: false, error: message}
models.User.find(req.user.id).then (user) ->
user.compare_password PI:PASSWORD:<PASSWORD>END_PI_password, (err, is_match) ->
is_null = user.password is null
if not is_null and (not is_match or err)
return fail('Current password incorrect')
user.hash_and_set_password PI:PASSWORD:<PASSWORD>END_PI, (err) ->
if err?
return fail("Failed to set new password")
user.save().then () ->
res.send {ok: true}
.catch fail
.catch fail
|
[
{
"context": "ngs.findOne({space: Session.get(\"spaceId\"), key: \"contacts_hidden_users\"})\n\t\t\t\t\t\treturn setting?.values || []\n\t\t\t\toptiona",
"end": 279,
"score": 0.7541078329086304,
"start": 258,
"tag": "KEY",
"value": "contacts_hidden_users"
}
] | creator/packages/steedos-creator/client/views/contacts_settings_hidden_modal.coffee | yicone/steedos-platform | 42 | Template.contacts_settings_hidden_modal.helpers
users_schema: ()->
fields =
hidden_users:
autoform:
type: 'selectuser'
multiple: true
defaultValue: ()->
setting = db.space_settings.findOne({space: Session.get("spaceId"), key: "contacts_hidden_users"})
return setting?.values || []
optional: false
type: [ String ]
label: ''
return new SimpleSchema(fields)
Template.contacts_settings_hidden_modal.events
'click #contacts_settings_hidden_modal_ok': (event, template)->
Meteor.call("set_space_settings", Session.get("spaceId"), "contacts_hidden_users", AutoForm.getFieldValue("hidden_users","contacts_settings_hidden_users"), true, ()->
Modal.hide(template);
toastr.success(t("saved_successfully"))
) | 71509 | Template.contacts_settings_hidden_modal.helpers
users_schema: ()->
fields =
hidden_users:
autoform:
type: 'selectuser'
multiple: true
defaultValue: ()->
setting = db.space_settings.findOne({space: Session.get("spaceId"), key: "<KEY>"})
return setting?.values || []
optional: false
type: [ String ]
label: ''
return new SimpleSchema(fields)
Template.contacts_settings_hidden_modal.events
'click #contacts_settings_hidden_modal_ok': (event, template)->
Meteor.call("set_space_settings", Session.get("spaceId"), "contacts_hidden_users", AutoForm.getFieldValue("hidden_users","contacts_settings_hidden_users"), true, ()->
Modal.hide(template);
toastr.success(t("saved_successfully"))
) | true | Template.contacts_settings_hidden_modal.helpers
users_schema: ()->
fields =
hidden_users:
autoform:
type: 'selectuser'
multiple: true
defaultValue: ()->
setting = db.space_settings.findOne({space: Session.get("spaceId"), key: "PI:KEY:<KEY>END_PI"})
return setting?.values || []
optional: false
type: [ String ]
label: ''
return new SimpleSchema(fields)
Template.contacts_settings_hidden_modal.events
'click #contacts_settings_hidden_modal_ok': (event, template)->
Meteor.call("set_space_settings", Session.get("spaceId"), "contacts_hidden_users", AutoForm.getFieldValue("hidden_users","contacts_settings_hidden_users"), true, ()->
Modal.hide(template);
toastr.success(t("saved_successfully"))
) |
[
{
"context": " host: \"web-prod.in.koding.com\",\n# login: \"guest\",\n# password: \"x1srTA7!%Vb}$n|S\"\n# }\noption",
"end": 98,
"score": 0.9882626533508301,
"start": 93,
"tag": "USERNAME",
"value": "guest"
},
{
"context": "ding.com\",\n# login: \"guest\",\n# password: \"x1srTA7!%Vb}$n|S\"\n# }\noptions = {host: \"localhost\"}\ndestination ",
"end": 134,
"score": 0.9994315505027771,
"start": 118,
"tag": "PASSWORD",
"value": "x1srTA7!%Vb}$n|S"
}
] | node_modules_koding/broker/examples/exchange2exchange.coffee | ezgikaysi/koding | 1 | Broker = require "broker"
# options = {
# host: "web-prod.in.koding.com",
# login: "guest",
# password: "x1srTA7!%Vb}$n|S"
# }
options = {host: "localhost"}
destination = "destinationExchange"
source = "sourceExchange"
broker = new Broker options
broker.bindExchange destination, source, "test"
| 144458 | Broker = require "broker"
# options = {
# host: "web-prod.in.koding.com",
# login: "guest",
# password: "<PASSWORD>"
# }
options = {host: "localhost"}
destination = "destinationExchange"
source = "sourceExchange"
broker = new Broker options
broker.bindExchange destination, source, "test"
| true | Broker = require "broker"
# options = {
# host: "web-prod.in.koding.com",
# login: "guest",
# password: "PI:PASSWORD:<PASSWORD>END_PI"
# }
options = {host: "localhost"}
destination = "destinationExchange"
source = "sourceExchange"
broker = new Broker options
broker.bindExchange destination, source, "test"
|
[
{
"context": "cs/#info.info\n\nFramer.Info =\n\ttitle: \"\"\n\tauthor: \"Tony\"\n\ttwitter: \"\"\n\tdescription: \"\"\n\n\n# Elements setup",
"end": 146,
"score": 0.9994388818740845,
"start": 142,
"tag": "NAME",
"value": "Tony"
}
] | 74newuber.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: ""
# Elements setup
bg = new BackgroundLayer
backgroundColor: "gray"
mapClip = new Layer
width: Screen.width * 1.5
height: Screen.width * 1.5
x: Align.center
y: Align.center
borderRadius: "50%"
backgroundColor: "lightblue"
scale: 0.15
rotation: -30
clip: true
map = new Layer
width: Screen.width * 1.5
height: Screen.height * 1.5
x: Align.center
y: Align.center
backgroundColor: "#DDE2E3"
parent: mapClip
scale: 0.57
for i in [0 ... 19]
street = new Layer
parent: map
height: 6
width: map.width
x: 0
y: i * 200
backgroundColor: "white"
avenue = new Layer
parent: map
height: map.height
width: 2
y: 0
x: i * 60
backgroundColor: "white"
menu = new Layer
width: 35
height: 21
backgroundColor: "none"
x: 65
y: 70
menuBar1 = new Layer
width: menu.width
height: 2
backgroundColor: "black"
parent: menu
menuBar2 = new Layer
width: menu.width
height: 2
midY: menu.height / 2
backgroundColor: "black"
parent: menu
menuBar3 = new Layer
width: menu.width
height: 2
maxY: menu.height
backgroundColor: "black"
parent: menu
messageCard = new Layer
width: Screen.width * 0.95
height: Screen.height / 2.5
backgroundColor: "#3d9fc6"
x: Align.center
borderRadius: 6
maxY: Screen.height + 410
shadowY: -10
shadowBlur: 80
shadowSpread: 50
shadowColor: "#DDE2E3"
html: "Meet your new Uber app"
style:
fontFamily: "Roboto"
fontSize: "1.55rem"
padding: "1.7rem 0 0 2rem"
color: "rgba(255,255,255,0.5)"
frequentAddress1 = new Layer
borderRadius: "50%"
backgroundColor: "white"
size: 110
y: Screen.height * 0.7
shadowY: 25
shadowBlur: 45
shadowColor: "rgba(0,0,0,0.22)"
frequentAddress2 = frequentAddress1.copy()
frequentAddress3 = frequentAddress1.copy()
frequentAddress1.x = Align.center(-frequentAddress1.width * 1.7)
frequentAddress2.x = Align.center
frequentAddress3.x = Align.center(frequentAddress1.width * 1.7)
frequentAText1 = new Layer
html: "636 2nd Ave"
backgroundColor: "none"
color: "#333"
parent: frequentAddress1
width: frequentAddress1.width * 1.4
midX: frequentAddress1.width / 2
y: frequentAddress1.height + 35
style:
textAlign: "center"
fontFamily: "Roboto"
fontSize: "1.6rem"
frequentShape1 = new Layer
size: 35
borderWidth: 4
backgroundColor: ""
borderColor: "black"
parent: frequentAddress1
midX: frequentAddress1.width / 2
midY: frequentAddress1.height / 2
frequentAText2 = new Layer
html: "153 Kearny Street"
color: "#333"
parent: frequentAddress2
backgroundColor: "none"
width: frequentAddress2.width * 1.4
midX: frequentAddress2.width / 2
y: frequentAddress1.height + 35
style:
textAlign: "center"
fontFamily: "Roboto"
fontSize: "1.6rem"
frequentShape2 = frequentShape1.copy()
frequentShape2.props =
parent: frequentAddress2
width: 55
midX: frequentAddress2.width / 2
midY: frequentAddress2.height / 2 + 10
borderRadius: 5
height: 15
frequentAText2 = new Layer
html: "1455 Market Street"
color: "#333"
parent: frequentAddress3
backgroundColor: "none"
width: frequentAddress3.width * 1.4
midX: frequentAddress3.width / 2
y: frequentAddress1.height + 35
style:
textAlign: "center"
fontFamily: "Roboto"
fontSize: "1.6rem"
frequentShape3 = frequentShape1.copy()
frequentShape3.props =
parent: frequentAddress3
size: 30
midX: frequentAddress3.width / 2
midY: frequentAddress3.height / 2
borderRadius: "50%"
currentLocationCirlce1 = new Layer
size: 100
borderRadius: "50%"
borderColor: "#3Fa0c6"
borderWidth: 2
backgroundColor: ""
opacity: 0.5
x: Align.center
y: Align.center
scale: 0
currentLocationCirlce2 = new Layer
size: 100
borderRadius: "50%"
backgroundColor: "#3Fa0c6"
opacity: 0.16
x: Align.center
y: Align.center
scale: 0
splashScreen = new Layer
width: Screen.width
height: Screen.height
backgroundColor: "black"
splashCircle = new Layer
size: 140
borderRadius: "50%"
backgroundColor: "white"
parent: splashScreen
midX: Screen.width / 2
midY: Screen.height / 2
splashSymbol = new Layer
size: 40
midX: Screen.width / 2
midY: Screen.height / 2
backgroundColor: "black"
shadowBlur: 50
shadowY: Screen.height / 2
shadowColor: "rgba(0,0,0,0.3)"
splashLine = new Layer
maxX: Screen.width / 2
midY: Screen.height / 2
height: 10
backgroundColor: "black"
searchBar = new Layer
width: Screen.width / 1.2
height: 105
x: Align.center
y: Screen.height * 0.14
backgroundColor: "white"
borderRadius: 5
shadowY: 50
shadowBlur: 55
shadowSpread: 0
shadowColor: "rgba(0,0,0,0.22)"
html: "Where to?"
color: "#555"
style:
fontSize: "2.4rem"
padding: "2.5rem"
paddingLeft: "5rem"
fontWeight: 300
fontFamily: "Roboto"
searchBarDot = new Layer
parent: searchBar
size: 12
y: Align.center
backgroundColor: "black"
x: 40
addressDot1 = new Layer
size: 19
borderRadius: "50%"
backgroundColor: "black"
midY: frequentAddress1.midY
x: Screen.width * 1.2
addressDot2 = addressDot1.copy()
addressDot3 = addressDot1.copy()
# States & Animation
fadeTime = 0.5
# Circle drop animation
circleDrop1 = new Animation
layer: currentLocationCirlce1
properties: scale: 3, opacity: 0
time: fadeTime * 2
circleDrop2 = new Animation
layer: currentLocationCirlce2
properties: scale: 2
time: fadeTime * 1.8
curve: "ease-in-out"
# Slide in dots animation
slide1 = new Animation
layer: addressDot1
properties: midX: frequentAddress1.midX
time: fadeTime * 2
slide2 = new Animation
layer: addressDot2
properties: midX: frequentAddress2.midX
time: fadeTime * 2
delay: fadeTime / 2
slide3 = new Animation
layer: addressDot3
properties: midX: frequentAddress3.midX
time: fadeTime * 2
delay: fadeTime
dotExpand1 = () =>
addressDot1.animate
properties: scale: 7.2, opacity: 0
time: fadeTime
frequentAddress1.states.switch("default")
dotExpand2 = () =>
addressDot2.animate
properties: scale: 7.2, opacity: 0
time: fadeTime
frequentAddress2.states.switch("default")
dotExpand3 = () =>
addressDot3.animate
properties: scale: 7.2, opacity: 0
time: fadeTime
frequentAddress3.states.switch("default")
# Splash Screen
splashScreen.states.add
on:
opacity: 0
splashScreen.states.animationOptions =
time: fadeTime * 5.5
splashCircle.states.add
on:
scale: 4
opacity: 0
splashCircle.states.animationOptions =
curve: "spring(64, 10, 0)"
splashLine.states.add
on:
scaleY: 0
splashLine.states.animationOptions =
time: fadeTime * 0.7
splashSymbol.states.add
on:
scale: 0.6
backgroundColor: "#3Fa0c6"
borderRadius: "50%"
shadowY: 10
splashSymbol.states.animationOptions =
time: fadeTime * 4
# Map Clip
mapClip.states.add
on:
scale: 2.5
rotation: 20
mapClip.states.animationOptions =
time: fadeTime * 4.5
delay: 0.1
curve: "spring(20, 20, 0)"
# Search Bar
searchBar.states.add
hide:
y: - 300
scale: 0.6
shadowY: -100
shadowColor: ""
searchBar.states.animationOptions =
time: fadeTime * 4.2
# frequent address
frequentAddress1.states.add
hide:
scale: 0
opacity: 0
frequentAddress1.states.animationOptions =
time: fadeTime
curve: "ease-in-out"
frequentAddress2.states.add
hide:
scale: 0
opacity: 0
frequentAddress2.states.animationOptions =
time: fadeTime
curve: "ease-in-out"
frequentAddress3.states.add
hide:
scale: 0
opacity: 0
frequentAddress3.states.animationOptions =
time: fadeTime
curve: "ease-in-out"
# message card
messageCard.states.add
hide:
y: Screen.height * 1.2
messageCard.states.animationOptions =
time: fadeTime * 2
# Menu
menu.states.add
hide:
opacity: 0
menu.states.animationOptions =
time: fadeTime * 6
# Events
searchBar.states.switchInstant("hide")
messageCard.states.switchInstant("hide")
menu.states.switchInstant("hide")
frequentAddress1.states.switchInstant("hide")
frequentAddress2.states.switchInstant("hide")
frequentAddress3.states.switchInstant("hide")
splashScreen.onClick ->
Utils.delay 0.3, =>
splashScreen.states.switch("on")
splashCircle.states.switch("on")
splashLine.states.switch("on")
splashSymbol.states.switch("on")
mapClip.states.switch("on")
Utils.delay fadeTime * 0.9, =>
searchBar.states.switch("default")
Utils.delay fadeTime * 1.5, =>
slide1.start()
slide2.start()
slide3.start()
slide1.on(Events.AnimationEnd, dotExpand1)
slide2.on(Events.AnimationEnd, dotExpand2)
slide3.on(Events.AnimationEnd, dotExpand3)
Utils.delay fadeTime * 3.2, =>
circleDrop1.start()
circleDrop1.on(Events.AnimationEnd, circleDrop2.start)
messageCard.states.switch("default")
menu.states.switch("default")
| 500 | # 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: ""
# Elements setup
bg = new BackgroundLayer
backgroundColor: "gray"
mapClip = new Layer
width: Screen.width * 1.5
height: Screen.width * 1.5
x: Align.center
y: Align.center
borderRadius: "50%"
backgroundColor: "lightblue"
scale: 0.15
rotation: -30
clip: true
map = new Layer
width: Screen.width * 1.5
height: Screen.height * 1.5
x: Align.center
y: Align.center
backgroundColor: "#DDE2E3"
parent: mapClip
scale: 0.57
for i in [0 ... 19]
street = new Layer
parent: map
height: 6
width: map.width
x: 0
y: i * 200
backgroundColor: "white"
avenue = new Layer
parent: map
height: map.height
width: 2
y: 0
x: i * 60
backgroundColor: "white"
menu = new Layer
width: 35
height: 21
backgroundColor: "none"
x: 65
y: 70
menuBar1 = new Layer
width: menu.width
height: 2
backgroundColor: "black"
parent: menu
menuBar2 = new Layer
width: menu.width
height: 2
midY: menu.height / 2
backgroundColor: "black"
parent: menu
menuBar3 = new Layer
width: menu.width
height: 2
maxY: menu.height
backgroundColor: "black"
parent: menu
messageCard = new Layer
width: Screen.width * 0.95
height: Screen.height / 2.5
backgroundColor: "#3d9fc6"
x: Align.center
borderRadius: 6
maxY: Screen.height + 410
shadowY: -10
shadowBlur: 80
shadowSpread: 50
shadowColor: "#DDE2E3"
html: "Meet your new Uber app"
style:
fontFamily: "Roboto"
fontSize: "1.55rem"
padding: "1.7rem 0 0 2rem"
color: "rgba(255,255,255,0.5)"
frequentAddress1 = new Layer
borderRadius: "50%"
backgroundColor: "white"
size: 110
y: Screen.height * 0.7
shadowY: 25
shadowBlur: 45
shadowColor: "rgba(0,0,0,0.22)"
frequentAddress2 = frequentAddress1.copy()
frequentAddress3 = frequentAddress1.copy()
frequentAddress1.x = Align.center(-frequentAddress1.width * 1.7)
frequentAddress2.x = Align.center
frequentAddress3.x = Align.center(frequentAddress1.width * 1.7)
frequentAText1 = new Layer
html: "636 2nd Ave"
backgroundColor: "none"
color: "#333"
parent: frequentAddress1
width: frequentAddress1.width * 1.4
midX: frequentAddress1.width / 2
y: frequentAddress1.height + 35
style:
textAlign: "center"
fontFamily: "Roboto"
fontSize: "1.6rem"
frequentShape1 = new Layer
size: 35
borderWidth: 4
backgroundColor: ""
borderColor: "black"
parent: frequentAddress1
midX: frequentAddress1.width / 2
midY: frequentAddress1.height / 2
frequentAText2 = new Layer
html: "153 Kearny Street"
color: "#333"
parent: frequentAddress2
backgroundColor: "none"
width: frequentAddress2.width * 1.4
midX: frequentAddress2.width / 2
y: frequentAddress1.height + 35
style:
textAlign: "center"
fontFamily: "Roboto"
fontSize: "1.6rem"
frequentShape2 = frequentShape1.copy()
frequentShape2.props =
parent: frequentAddress2
width: 55
midX: frequentAddress2.width / 2
midY: frequentAddress2.height / 2 + 10
borderRadius: 5
height: 15
frequentAText2 = new Layer
html: "1455 Market Street"
color: "#333"
parent: frequentAddress3
backgroundColor: "none"
width: frequentAddress3.width * 1.4
midX: frequentAddress3.width / 2
y: frequentAddress1.height + 35
style:
textAlign: "center"
fontFamily: "Roboto"
fontSize: "1.6rem"
frequentShape3 = frequentShape1.copy()
frequentShape3.props =
parent: frequentAddress3
size: 30
midX: frequentAddress3.width / 2
midY: frequentAddress3.height / 2
borderRadius: "50%"
currentLocationCirlce1 = new Layer
size: 100
borderRadius: "50%"
borderColor: "#3Fa0c6"
borderWidth: 2
backgroundColor: ""
opacity: 0.5
x: Align.center
y: Align.center
scale: 0
currentLocationCirlce2 = new Layer
size: 100
borderRadius: "50%"
backgroundColor: "#3Fa0c6"
opacity: 0.16
x: Align.center
y: Align.center
scale: 0
splashScreen = new Layer
width: Screen.width
height: Screen.height
backgroundColor: "black"
splashCircle = new Layer
size: 140
borderRadius: "50%"
backgroundColor: "white"
parent: splashScreen
midX: Screen.width / 2
midY: Screen.height / 2
splashSymbol = new Layer
size: 40
midX: Screen.width / 2
midY: Screen.height / 2
backgroundColor: "black"
shadowBlur: 50
shadowY: Screen.height / 2
shadowColor: "rgba(0,0,0,0.3)"
splashLine = new Layer
maxX: Screen.width / 2
midY: Screen.height / 2
height: 10
backgroundColor: "black"
searchBar = new Layer
width: Screen.width / 1.2
height: 105
x: Align.center
y: Screen.height * 0.14
backgroundColor: "white"
borderRadius: 5
shadowY: 50
shadowBlur: 55
shadowSpread: 0
shadowColor: "rgba(0,0,0,0.22)"
html: "Where to?"
color: "#555"
style:
fontSize: "2.4rem"
padding: "2.5rem"
paddingLeft: "5rem"
fontWeight: 300
fontFamily: "Roboto"
searchBarDot = new Layer
parent: searchBar
size: 12
y: Align.center
backgroundColor: "black"
x: 40
addressDot1 = new Layer
size: 19
borderRadius: "50%"
backgroundColor: "black"
midY: frequentAddress1.midY
x: Screen.width * 1.2
addressDot2 = addressDot1.copy()
addressDot3 = addressDot1.copy()
# States & Animation
fadeTime = 0.5
# Circle drop animation
circleDrop1 = new Animation
layer: currentLocationCirlce1
properties: scale: 3, opacity: 0
time: fadeTime * 2
circleDrop2 = new Animation
layer: currentLocationCirlce2
properties: scale: 2
time: fadeTime * 1.8
curve: "ease-in-out"
# Slide in dots animation
slide1 = new Animation
layer: addressDot1
properties: midX: frequentAddress1.midX
time: fadeTime * 2
slide2 = new Animation
layer: addressDot2
properties: midX: frequentAddress2.midX
time: fadeTime * 2
delay: fadeTime / 2
slide3 = new Animation
layer: addressDot3
properties: midX: frequentAddress3.midX
time: fadeTime * 2
delay: fadeTime
dotExpand1 = () =>
addressDot1.animate
properties: scale: 7.2, opacity: 0
time: fadeTime
frequentAddress1.states.switch("default")
dotExpand2 = () =>
addressDot2.animate
properties: scale: 7.2, opacity: 0
time: fadeTime
frequentAddress2.states.switch("default")
dotExpand3 = () =>
addressDot3.animate
properties: scale: 7.2, opacity: 0
time: fadeTime
frequentAddress3.states.switch("default")
# Splash Screen
splashScreen.states.add
on:
opacity: 0
splashScreen.states.animationOptions =
time: fadeTime * 5.5
splashCircle.states.add
on:
scale: 4
opacity: 0
splashCircle.states.animationOptions =
curve: "spring(64, 10, 0)"
splashLine.states.add
on:
scaleY: 0
splashLine.states.animationOptions =
time: fadeTime * 0.7
splashSymbol.states.add
on:
scale: 0.6
backgroundColor: "#3Fa0c6"
borderRadius: "50%"
shadowY: 10
splashSymbol.states.animationOptions =
time: fadeTime * 4
# Map Clip
mapClip.states.add
on:
scale: 2.5
rotation: 20
mapClip.states.animationOptions =
time: fadeTime * 4.5
delay: 0.1
curve: "spring(20, 20, 0)"
# Search Bar
searchBar.states.add
hide:
y: - 300
scale: 0.6
shadowY: -100
shadowColor: ""
searchBar.states.animationOptions =
time: fadeTime * 4.2
# frequent address
frequentAddress1.states.add
hide:
scale: 0
opacity: 0
frequentAddress1.states.animationOptions =
time: fadeTime
curve: "ease-in-out"
frequentAddress2.states.add
hide:
scale: 0
opacity: 0
frequentAddress2.states.animationOptions =
time: fadeTime
curve: "ease-in-out"
frequentAddress3.states.add
hide:
scale: 0
opacity: 0
frequentAddress3.states.animationOptions =
time: fadeTime
curve: "ease-in-out"
# message card
messageCard.states.add
hide:
y: Screen.height * 1.2
messageCard.states.animationOptions =
time: fadeTime * 2
# Menu
menu.states.add
hide:
opacity: 0
menu.states.animationOptions =
time: fadeTime * 6
# Events
searchBar.states.switchInstant("hide")
messageCard.states.switchInstant("hide")
menu.states.switchInstant("hide")
frequentAddress1.states.switchInstant("hide")
frequentAddress2.states.switchInstant("hide")
frequentAddress3.states.switchInstant("hide")
splashScreen.onClick ->
Utils.delay 0.3, =>
splashScreen.states.switch("on")
splashCircle.states.switch("on")
splashLine.states.switch("on")
splashSymbol.states.switch("on")
mapClip.states.switch("on")
Utils.delay fadeTime * 0.9, =>
searchBar.states.switch("default")
Utils.delay fadeTime * 1.5, =>
slide1.start()
slide2.start()
slide3.start()
slide1.on(Events.AnimationEnd, dotExpand1)
slide2.on(Events.AnimationEnd, dotExpand2)
slide3.on(Events.AnimationEnd, dotExpand3)
Utils.delay fadeTime * 3.2, =>
circleDrop1.start()
circleDrop1.on(Events.AnimationEnd, circleDrop2.start)
messageCard.states.switch("default")
menu.states.switch("default")
| 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: ""
# Elements setup
bg = new BackgroundLayer
backgroundColor: "gray"
mapClip = new Layer
width: Screen.width * 1.5
height: Screen.width * 1.5
x: Align.center
y: Align.center
borderRadius: "50%"
backgroundColor: "lightblue"
scale: 0.15
rotation: -30
clip: true
map = new Layer
width: Screen.width * 1.5
height: Screen.height * 1.5
x: Align.center
y: Align.center
backgroundColor: "#DDE2E3"
parent: mapClip
scale: 0.57
for i in [0 ... 19]
street = new Layer
parent: map
height: 6
width: map.width
x: 0
y: i * 200
backgroundColor: "white"
avenue = new Layer
parent: map
height: map.height
width: 2
y: 0
x: i * 60
backgroundColor: "white"
menu = new Layer
width: 35
height: 21
backgroundColor: "none"
x: 65
y: 70
menuBar1 = new Layer
width: menu.width
height: 2
backgroundColor: "black"
parent: menu
menuBar2 = new Layer
width: menu.width
height: 2
midY: menu.height / 2
backgroundColor: "black"
parent: menu
menuBar3 = new Layer
width: menu.width
height: 2
maxY: menu.height
backgroundColor: "black"
parent: menu
messageCard = new Layer
width: Screen.width * 0.95
height: Screen.height / 2.5
backgroundColor: "#3d9fc6"
x: Align.center
borderRadius: 6
maxY: Screen.height + 410
shadowY: -10
shadowBlur: 80
shadowSpread: 50
shadowColor: "#DDE2E3"
html: "Meet your new Uber app"
style:
fontFamily: "Roboto"
fontSize: "1.55rem"
padding: "1.7rem 0 0 2rem"
color: "rgba(255,255,255,0.5)"
frequentAddress1 = new Layer
borderRadius: "50%"
backgroundColor: "white"
size: 110
y: Screen.height * 0.7
shadowY: 25
shadowBlur: 45
shadowColor: "rgba(0,0,0,0.22)"
frequentAddress2 = frequentAddress1.copy()
frequentAddress3 = frequentAddress1.copy()
frequentAddress1.x = Align.center(-frequentAddress1.width * 1.7)
frequentAddress2.x = Align.center
frequentAddress3.x = Align.center(frequentAddress1.width * 1.7)
frequentAText1 = new Layer
html: "636 2nd Ave"
backgroundColor: "none"
color: "#333"
parent: frequentAddress1
width: frequentAddress1.width * 1.4
midX: frequentAddress1.width / 2
y: frequentAddress1.height + 35
style:
textAlign: "center"
fontFamily: "Roboto"
fontSize: "1.6rem"
frequentShape1 = new Layer
size: 35
borderWidth: 4
backgroundColor: ""
borderColor: "black"
parent: frequentAddress1
midX: frequentAddress1.width / 2
midY: frequentAddress1.height / 2
frequentAText2 = new Layer
html: "153 Kearny Street"
color: "#333"
parent: frequentAddress2
backgroundColor: "none"
width: frequentAddress2.width * 1.4
midX: frequentAddress2.width / 2
y: frequentAddress1.height + 35
style:
textAlign: "center"
fontFamily: "Roboto"
fontSize: "1.6rem"
frequentShape2 = frequentShape1.copy()
frequentShape2.props =
parent: frequentAddress2
width: 55
midX: frequentAddress2.width / 2
midY: frequentAddress2.height / 2 + 10
borderRadius: 5
height: 15
frequentAText2 = new Layer
html: "1455 Market Street"
color: "#333"
parent: frequentAddress3
backgroundColor: "none"
width: frequentAddress3.width * 1.4
midX: frequentAddress3.width / 2
y: frequentAddress1.height + 35
style:
textAlign: "center"
fontFamily: "Roboto"
fontSize: "1.6rem"
frequentShape3 = frequentShape1.copy()
frequentShape3.props =
parent: frequentAddress3
size: 30
midX: frequentAddress3.width / 2
midY: frequentAddress3.height / 2
borderRadius: "50%"
currentLocationCirlce1 = new Layer
size: 100
borderRadius: "50%"
borderColor: "#3Fa0c6"
borderWidth: 2
backgroundColor: ""
opacity: 0.5
x: Align.center
y: Align.center
scale: 0
currentLocationCirlce2 = new Layer
size: 100
borderRadius: "50%"
backgroundColor: "#3Fa0c6"
opacity: 0.16
x: Align.center
y: Align.center
scale: 0
splashScreen = new Layer
width: Screen.width
height: Screen.height
backgroundColor: "black"
splashCircle = new Layer
size: 140
borderRadius: "50%"
backgroundColor: "white"
parent: splashScreen
midX: Screen.width / 2
midY: Screen.height / 2
splashSymbol = new Layer
size: 40
midX: Screen.width / 2
midY: Screen.height / 2
backgroundColor: "black"
shadowBlur: 50
shadowY: Screen.height / 2
shadowColor: "rgba(0,0,0,0.3)"
splashLine = new Layer
maxX: Screen.width / 2
midY: Screen.height / 2
height: 10
backgroundColor: "black"
searchBar = new Layer
width: Screen.width / 1.2
height: 105
x: Align.center
y: Screen.height * 0.14
backgroundColor: "white"
borderRadius: 5
shadowY: 50
shadowBlur: 55
shadowSpread: 0
shadowColor: "rgba(0,0,0,0.22)"
html: "Where to?"
color: "#555"
style:
fontSize: "2.4rem"
padding: "2.5rem"
paddingLeft: "5rem"
fontWeight: 300
fontFamily: "Roboto"
searchBarDot = new Layer
parent: searchBar
size: 12
y: Align.center
backgroundColor: "black"
x: 40
addressDot1 = new Layer
size: 19
borderRadius: "50%"
backgroundColor: "black"
midY: frequentAddress1.midY
x: Screen.width * 1.2
addressDot2 = addressDot1.copy()
addressDot3 = addressDot1.copy()
# States & Animation
fadeTime = 0.5
# Circle drop animation
circleDrop1 = new Animation
layer: currentLocationCirlce1
properties: scale: 3, opacity: 0
time: fadeTime * 2
circleDrop2 = new Animation
layer: currentLocationCirlce2
properties: scale: 2
time: fadeTime * 1.8
curve: "ease-in-out"
# Slide in dots animation
slide1 = new Animation
layer: addressDot1
properties: midX: frequentAddress1.midX
time: fadeTime * 2
slide2 = new Animation
layer: addressDot2
properties: midX: frequentAddress2.midX
time: fadeTime * 2
delay: fadeTime / 2
slide3 = new Animation
layer: addressDot3
properties: midX: frequentAddress3.midX
time: fadeTime * 2
delay: fadeTime
dotExpand1 = () =>
addressDot1.animate
properties: scale: 7.2, opacity: 0
time: fadeTime
frequentAddress1.states.switch("default")
dotExpand2 = () =>
addressDot2.animate
properties: scale: 7.2, opacity: 0
time: fadeTime
frequentAddress2.states.switch("default")
dotExpand3 = () =>
addressDot3.animate
properties: scale: 7.2, opacity: 0
time: fadeTime
frequentAddress3.states.switch("default")
# Splash Screen
splashScreen.states.add
on:
opacity: 0
splashScreen.states.animationOptions =
time: fadeTime * 5.5
splashCircle.states.add
on:
scale: 4
opacity: 0
splashCircle.states.animationOptions =
curve: "spring(64, 10, 0)"
splashLine.states.add
on:
scaleY: 0
splashLine.states.animationOptions =
time: fadeTime * 0.7
splashSymbol.states.add
on:
scale: 0.6
backgroundColor: "#3Fa0c6"
borderRadius: "50%"
shadowY: 10
splashSymbol.states.animationOptions =
time: fadeTime * 4
# Map Clip
mapClip.states.add
on:
scale: 2.5
rotation: 20
mapClip.states.animationOptions =
time: fadeTime * 4.5
delay: 0.1
curve: "spring(20, 20, 0)"
# Search Bar
searchBar.states.add
hide:
y: - 300
scale: 0.6
shadowY: -100
shadowColor: ""
searchBar.states.animationOptions =
time: fadeTime * 4.2
# frequent address
frequentAddress1.states.add
hide:
scale: 0
opacity: 0
frequentAddress1.states.animationOptions =
time: fadeTime
curve: "ease-in-out"
frequentAddress2.states.add
hide:
scale: 0
opacity: 0
frequentAddress2.states.animationOptions =
time: fadeTime
curve: "ease-in-out"
frequentAddress3.states.add
hide:
scale: 0
opacity: 0
frequentAddress3.states.animationOptions =
time: fadeTime
curve: "ease-in-out"
# message card
messageCard.states.add
hide:
y: Screen.height * 1.2
messageCard.states.animationOptions =
time: fadeTime * 2
# Menu
menu.states.add
hide:
opacity: 0
menu.states.animationOptions =
time: fadeTime * 6
# Events
searchBar.states.switchInstant("hide")
messageCard.states.switchInstant("hide")
menu.states.switchInstant("hide")
frequentAddress1.states.switchInstant("hide")
frequentAddress2.states.switchInstant("hide")
frequentAddress3.states.switchInstant("hide")
splashScreen.onClick ->
Utils.delay 0.3, =>
splashScreen.states.switch("on")
splashCircle.states.switch("on")
splashLine.states.switch("on")
splashSymbol.states.switch("on")
mapClip.states.switch("on")
Utils.delay fadeTime * 0.9, =>
searchBar.states.switch("default")
Utils.delay fadeTime * 1.5, =>
slide1.start()
slide2.start()
slide3.start()
slide1.on(Events.AnimationEnd, dotExpand1)
slide2.on(Events.AnimationEnd, dotExpand2)
slide3.on(Events.AnimationEnd, dotExpand3)
Utils.delay fadeTime * 3.2, =>
circleDrop1.start()
circleDrop1.on(Events.AnimationEnd, circleDrop2.start)
messageCard.states.switch("default")
menu.states.switch("default")
|
[
{
"context": "ge-section-subheading').text().should.containEql 'Pablo Picasso'\n",
"end": 1657,
"score": 0.9997685551643372,
"start": 1644,
"tag": "NAME",
"value": "Pablo Picasso"
}
] | src/desktop/apps/fair/test/client/overview.coffee | kanaabe/force | 1 | _ = require 'underscore'
sd = require('sharify').data
benv = require 'benv'
Backbone = require 'backbone'
sinon = require 'sinon'
moment = require 'moment'
{ resolve } = require 'path'
{ fabricate } = require 'antigravity'
Fair = require '../../../../models/fair.coffee'
xdescribe 'ForYouView', ->
before (done) ->
benv.setup =>
sd.API_URL = 'localhost:3003'
sd.CURRENT_PATH = ""
sd.CURRENT_USER = "hello"
sd.NODE_ENV = "test"
benv.expose { $: benv.require 'jquery' }
sinon.stub Backbone, 'sync'
@OverviewView = require '../../client/overview.coffee'
Backbone.$ = $
@fair = new Fair fabricate 'fair'
done()
after ->
benv.teardown()
Backbone.sync.restore()
sd.CURRENT_USER = undefined
describe '#initialize', ->
it "renders personalized artist list", ->
view = new @OverviewView
el: $("""<div>
<div class='clock'></div>
<div class='container-left'><div class='large-section-subheading'></div></div>
</div>""")
fair: @fair
model: @model
Backbone.sync.args[0][2].success { time: moment().subtract('minutes', 2).format("YYYY-MM-DD HH:mm:ss ZZ") }
Backbone.sync.args[1][2].success [{artist: fabricate('artist')}]
Backbone.sync.args[2][2].success []
view.$el.html().should.not.containEql 'undefined'
view.$el.html().should.not.containEql "\#{"
view.$el.html().should.not.containEql "NaN"
view.$('.container-left .large-section-subheading').length.should.equal 1
view.$('.container-left .large-section-subheading').text().should.containEql 'Pablo Picasso'
| 140367 | _ = require 'underscore'
sd = require('sharify').data
benv = require 'benv'
Backbone = require 'backbone'
sinon = require 'sinon'
moment = require 'moment'
{ resolve } = require 'path'
{ fabricate } = require 'antigravity'
Fair = require '../../../../models/fair.coffee'
xdescribe 'ForYouView', ->
before (done) ->
benv.setup =>
sd.API_URL = 'localhost:3003'
sd.CURRENT_PATH = ""
sd.CURRENT_USER = "hello"
sd.NODE_ENV = "test"
benv.expose { $: benv.require 'jquery' }
sinon.stub Backbone, 'sync'
@OverviewView = require '../../client/overview.coffee'
Backbone.$ = $
@fair = new Fair fabricate 'fair'
done()
after ->
benv.teardown()
Backbone.sync.restore()
sd.CURRENT_USER = undefined
describe '#initialize', ->
it "renders personalized artist list", ->
view = new @OverviewView
el: $("""<div>
<div class='clock'></div>
<div class='container-left'><div class='large-section-subheading'></div></div>
</div>""")
fair: @fair
model: @model
Backbone.sync.args[0][2].success { time: moment().subtract('minutes', 2).format("YYYY-MM-DD HH:mm:ss ZZ") }
Backbone.sync.args[1][2].success [{artist: fabricate('artist')}]
Backbone.sync.args[2][2].success []
view.$el.html().should.not.containEql 'undefined'
view.$el.html().should.not.containEql "\#{"
view.$el.html().should.not.containEql "NaN"
view.$('.container-left .large-section-subheading').length.should.equal 1
view.$('.container-left .large-section-subheading').text().should.containEql '<NAME>'
| true | _ = require 'underscore'
sd = require('sharify').data
benv = require 'benv'
Backbone = require 'backbone'
sinon = require 'sinon'
moment = require 'moment'
{ resolve } = require 'path'
{ fabricate } = require 'antigravity'
Fair = require '../../../../models/fair.coffee'
xdescribe 'ForYouView', ->
before (done) ->
benv.setup =>
sd.API_URL = 'localhost:3003'
sd.CURRENT_PATH = ""
sd.CURRENT_USER = "hello"
sd.NODE_ENV = "test"
benv.expose { $: benv.require 'jquery' }
sinon.stub Backbone, 'sync'
@OverviewView = require '../../client/overview.coffee'
Backbone.$ = $
@fair = new Fair fabricate 'fair'
done()
after ->
benv.teardown()
Backbone.sync.restore()
sd.CURRENT_USER = undefined
describe '#initialize', ->
it "renders personalized artist list", ->
view = new @OverviewView
el: $("""<div>
<div class='clock'></div>
<div class='container-left'><div class='large-section-subheading'></div></div>
</div>""")
fair: @fair
model: @model
Backbone.sync.args[0][2].success { time: moment().subtract('minutes', 2).format("YYYY-MM-DD HH:mm:ss ZZ") }
Backbone.sync.args[1][2].success [{artist: fabricate('artist')}]
Backbone.sync.args[2][2].success []
view.$el.html().should.not.containEql 'undefined'
view.$el.html().should.not.containEql "\#{"
view.$el.html().should.not.containEql "NaN"
view.$('.container-left .large-section-subheading').length.should.equal 1
view.$('.container-left .large-section-subheading').text().should.containEql 'PI:NAME:<NAME>END_PI'
|
[
{
"context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission",
"end": 18,
"score": 0.9995357394218445,
"start": 12,
"tag": "NAME",
"value": "Joyent"
}
] | test/simple/test-beforeexit-event.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.
tryImmediate = ->
console.log "set immediate"
setImmediate ->
revivals++
process.once "beforeExit", tryTimer
return
return
tryTimer = ->
console.log "set a timeout"
setTimeout (->
console.log "timeout cb, do another once beforeExit"
revivals++
process.once "beforeExit", tryListen
return
), 1
return
tryListen = ->
console.log "create a server"
net.createServer().listen(0).on "listening", ->
revivals++
@close()
return
return
assert = require("assert")
net = require("net")
util = require("util")
revivals = 0
deaths = 0
process.on "beforeExit", ->
deaths++
return
process.once "beforeExit", tryImmediate
process.on "exit", ->
assert.equal 4, deaths
assert.equal 3, revivals
return
| 52981 | # 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.
tryImmediate = ->
console.log "set immediate"
setImmediate ->
revivals++
process.once "beforeExit", tryTimer
return
return
tryTimer = ->
console.log "set a timeout"
setTimeout (->
console.log "timeout cb, do another once beforeExit"
revivals++
process.once "beforeExit", tryListen
return
), 1
return
tryListen = ->
console.log "create a server"
net.createServer().listen(0).on "listening", ->
revivals++
@close()
return
return
assert = require("assert")
net = require("net")
util = require("util")
revivals = 0
deaths = 0
process.on "beforeExit", ->
deaths++
return
process.once "beforeExit", tryImmediate
process.on "exit", ->
assert.equal 4, deaths
assert.equal 3, revivals
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.
tryImmediate = ->
console.log "set immediate"
setImmediate ->
revivals++
process.once "beforeExit", tryTimer
return
return
tryTimer = ->
console.log "set a timeout"
setTimeout (->
console.log "timeout cb, do another once beforeExit"
revivals++
process.once "beforeExit", tryListen
return
), 1
return
tryListen = ->
console.log "create a server"
net.createServer().listen(0).on "listening", ->
revivals++
@close()
return
return
assert = require("assert")
net = require("net")
util = require("util")
revivals = 0
deaths = 0
process.on "beforeExit", ->
deaths++
return
process.once "beforeExit", tryImmediate
process.on "exit", ->
assert.equal 4, deaths
assert.equal 3, revivals
return
|
[
{
"context": "Scratch way\nopen-source under the MIT license, (c) Ethan Arterberry, 2015\n\n<broadcast.coffee>\nwritten in CoffeeScript",
"end": 122,
"score": 0.9998762011528015,
"start": 106,
"tag": "NAME",
"value": "Ethan Arterberry"
}
] | broadcast.coffee | sargeant45/broadcast | 0 | ###
broadcast 1.2
JavaScript function passing done the Scratch way
open-source under the MIT license, (c) Ethan Arterberry, 2015
<broadcast.coffee>
written in CoffeeScript, JavaScript done right
###
class Broadcast
constructor: ->
@broadcasts = {}
console?.log "New Broadcast class created."
create: (id, execute) ->
if id && execute
@broadcasts[id] = []
@broadcasts[id].push(item) for item in execute
console?.log "Broadcast with ID \"#{id}\" has been set up to execute functions:\n\t%s\nwhen called.", execute.toString().replace(/\n/g, "\n\t")
else
console?.error "Please pass all parameters (id, execute) to Broadcast::create."
shout: (id, sync, _callback) ->
if !id
throw "You did not specify a Broadcast ID."
if !sync
throw "You did not specify a sync type."
switch sync
when "async"
###@cc_on
// conditional IE < 9 only fix for setTimeout params
@if (@_jscript_version <= 9)
(function(f){
window.setTimeout =f(window.setTimeout);
window.setInterval =f(window.setInterval);
})(function(f){return function(c,t){var a=[].slice.call(arguments,2);return f(function(){c.apply(this,a)},t)}});
@end
@
###
setTimeout(->
if _callback then _callback()
, 0, item)
for item in @broadcasts[id]
setTimeout((item) ->
item()
, 0, item)
when "sync"
for item in @broadcasts[id]
item()
if _callback then _callback()
else
throw "'sync' can only be 'async' or 'sync'."
modify: (id, execute, newid) ->
if id
if execute
oldexecute = (broadcasts) -> broadcasts[id]
@broadcasts[id] = execute
console?.log "Broadcast with ID \"#{id}\" has been modified to execute code:\n\t%s\ninstead of functions:\n[%s]\nwhen called.", execute.toString().replace(/\n/g, "\n\t"), oldexecute(@broadcasts).toString().replace(/\n/g, "\n\t")
if newid
@broadcasts[newid] = @broadcasts[id]
delete @broadcasts[id]
console?.log "Broadcast with ID \"#{id}\" has been renamed to \"#{newid}\"."
else
console?.error "Please pass the \"id\" parameter to Broadcast::modify."
add: (id, execute) ->
if id && execute
@broadcasts[id].push(item) for item in execute
console?.log "Broadcast with ID \"#{id}\" has been set up to execute newly added code:\n\t%s\nwhen called.", execute.toString().replace(/\n/g, "\n\t")
else
console?.error "Please pass all parameters (id, execute) to Broadcast::add." | 113838 | ###
broadcast 1.2
JavaScript function passing done the Scratch way
open-source under the MIT license, (c) <NAME>, 2015
<broadcast.coffee>
written in CoffeeScript, JavaScript done right
###
class Broadcast
constructor: ->
@broadcasts = {}
console?.log "New Broadcast class created."
create: (id, execute) ->
if id && execute
@broadcasts[id] = []
@broadcasts[id].push(item) for item in execute
console?.log "Broadcast with ID \"#{id}\" has been set up to execute functions:\n\t%s\nwhen called.", execute.toString().replace(/\n/g, "\n\t")
else
console?.error "Please pass all parameters (id, execute) to Broadcast::create."
shout: (id, sync, _callback) ->
if !id
throw "You did not specify a Broadcast ID."
if !sync
throw "You did not specify a sync type."
switch sync
when "async"
###@cc_on
// conditional IE < 9 only fix for setTimeout params
@if (@_jscript_version <= 9)
(function(f){
window.setTimeout =f(window.setTimeout);
window.setInterval =f(window.setInterval);
})(function(f){return function(c,t){var a=[].slice.call(arguments,2);return f(function(){c.apply(this,a)},t)}});
@end
@
###
setTimeout(->
if _callback then _callback()
, 0, item)
for item in @broadcasts[id]
setTimeout((item) ->
item()
, 0, item)
when "sync"
for item in @broadcasts[id]
item()
if _callback then _callback()
else
throw "'sync' can only be 'async' or 'sync'."
modify: (id, execute, newid) ->
if id
if execute
oldexecute = (broadcasts) -> broadcasts[id]
@broadcasts[id] = execute
console?.log "Broadcast with ID \"#{id}\" has been modified to execute code:\n\t%s\ninstead of functions:\n[%s]\nwhen called.", execute.toString().replace(/\n/g, "\n\t"), oldexecute(@broadcasts).toString().replace(/\n/g, "\n\t")
if newid
@broadcasts[newid] = @broadcasts[id]
delete @broadcasts[id]
console?.log "Broadcast with ID \"#{id}\" has been renamed to \"#{newid}\"."
else
console?.error "Please pass the \"id\" parameter to Broadcast::modify."
add: (id, execute) ->
if id && execute
@broadcasts[id].push(item) for item in execute
console?.log "Broadcast with ID \"#{id}\" has been set up to execute newly added code:\n\t%s\nwhen called.", execute.toString().replace(/\n/g, "\n\t")
else
console?.error "Please pass all parameters (id, execute) to Broadcast::add." | true | ###
broadcast 1.2
JavaScript function passing done the Scratch way
open-source under the MIT license, (c) PI:NAME:<NAME>END_PI, 2015
<broadcast.coffee>
written in CoffeeScript, JavaScript done right
###
class Broadcast
constructor: ->
@broadcasts = {}
console?.log "New Broadcast class created."
create: (id, execute) ->
if id && execute
@broadcasts[id] = []
@broadcasts[id].push(item) for item in execute
console?.log "Broadcast with ID \"#{id}\" has been set up to execute functions:\n\t%s\nwhen called.", execute.toString().replace(/\n/g, "\n\t")
else
console?.error "Please pass all parameters (id, execute) to Broadcast::create."
shout: (id, sync, _callback) ->
if !id
throw "You did not specify a Broadcast ID."
if !sync
throw "You did not specify a sync type."
switch sync
when "async"
###@cc_on
// conditional IE < 9 only fix for setTimeout params
@if (@_jscript_version <= 9)
(function(f){
window.setTimeout =f(window.setTimeout);
window.setInterval =f(window.setInterval);
})(function(f){return function(c,t){var a=[].slice.call(arguments,2);return f(function(){c.apply(this,a)},t)}});
@end
@
###
setTimeout(->
if _callback then _callback()
, 0, item)
for item in @broadcasts[id]
setTimeout((item) ->
item()
, 0, item)
when "sync"
for item in @broadcasts[id]
item()
if _callback then _callback()
else
throw "'sync' can only be 'async' or 'sync'."
modify: (id, execute, newid) ->
if id
if execute
oldexecute = (broadcasts) -> broadcasts[id]
@broadcasts[id] = execute
console?.log "Broadcast with ID \"#{id}\" has been modified to execute code:\n\t%s\ninstead of functions:\n[%s]\nwhen called.", execute.toString().replace(/\n/g, "\n\t"), oldexecute(@broadcasts).toString().replace(/\n/g, "\n\t")
if newid
@broadcasts[newid] = @broadcasts[id]
delete @broadcasts[id]
console?.log "Broadcast with ID \"#{id}\" has been renamed to \"#{newid}\"."
else
console?.error "Please pass the \"id\" parameter to Broadcast::modify."
add: (id, execute) ->
if id && execute
@broadcasts[id].push(item) for item in execute
console?.log "Broadcast with ID \"#{id}\" has been set up to execute newly added code:\n\t%s\nwhen called.", execute.toString().replace(/\n/g, "\n\t")
else
console?.error "Please pass all parameters (id, execute) to Broadcast::add." |
[
{
"context": "otator.Plugin.Touch.utils = do ->\n # Pinched from Paul Irish's blog.\n # See: http://paulirish.com/2011/req",
"end": 2629,
"score": 0.7603439092636108,
"start": 2622,
"tag": "NAME",
"value": "Paul Ir"
}
] | src/touch/utils.coffee | ck--/annotator.touch.js | 40 | # Adds a new "tap" event to jQuery. This offers improved performance over
# click for touch devices whcih often have up to a 300ms delay before
# triggering callbacks. Instead it uses a combination of touchstart and
# touchend events to to create a fake click. It will also cancel the event
# after 300ms (to allow the user to perform a "longtap") or if the touchend
# event is triggered on a different element.
#
# Additonal options can be provided as part of the eventData object.
#
# preventDefault - If false will not call preventDefault() on the touchstart
# event (deafult: true).
# onTapDown - Callback for the "touchstart" incase additonal code needs
# to be run such as event.stopPropagation().
# onTapUp - Callabck for the "touchend" event, called after the main
# event handler.
# timeout - Time to allow before cancelling the event (default: 300).
#
# Example
#
# jQuery("a").bind "tap", =>
# # This is called on "touchend" on the same element.
#
# options =
# preventDefault: false
# onTapDown: (event) -> event.stopPropagation()
# jQuery(doument).delegate "button", "tap", options, =>
# # This is called on "touchend" on the same element.
jQuery.event.special.tap =
add: (eventHandler) ->
data = eventHandler.data = eventHandler.data or {}
context = this
onTapStart = (event) ->
event.preventDefault() unless data.preventDefault is false
data.onTapDown.apply(this, arguments) if data.onTapDown
data.event = event
data.touched = setTimeout ->
data.touched = null
, data.timeout or 300
jQuery(document).bind(touchend: onTapEnd, mouseup: onTapEnd)
onTapEnd = (event) ->
if data.touched?
clearTimeout(data.touched)
if event.target is context or jQuery.contains(context, event.target)
handler = eventHandler.origHandler or eventHandler.handler
handler.call(this, data.event)
data.touched = null
data.onTapUp.apply(this, arguments) if data.onTapUp
jQuery(document).unbind(touchstart: onTapEnd, mousedown: onTapEnd)
data.tapHandlers = touchstart: onTapStart, mousedown: onTapStart
if eventHandler.selector
jQuery(context).delegate(eventHandler.selector, data.tapHandlers)
else
jQuery(context).bind(data.tapHandlers)
remove: (eventHandler) ->
jQuery(this).unbind(eventHandler.data.tapHandlers)
# Add support for "touch" events.
Annotator.Delegator.natives.push("touchstart", "touchmove", "touchend", "tap")
Annotator.Plugin.Touch.utils = do ->
# Pinched from Paul Irish's blog.
# See: http://paulirish.com/2011/requestanimationframe-for-smart-animating/
vendors = ['ms', 'moz', 'webkit', 'o']
requestAnimationFrame = window.requestAnimationFrame
cancelAnimationFrame = window.cancelAnimationFrame
for prefix in vendors when !requestAnimationFrame
requestAnimationFrame = window["#{prefix}RequestAnimationFrame"]
cancelAnimationFrame = window["#{prefix}CancelAnimationFrame"] or
window["#{prefix}CancelRequestAnimationFrame"]
unless requestAnimationFrame
lastTime = 0
requestAnimationFrame = (callback, element) ->
currTime = new Date().getTime()
timeToCall = Math.max(0, 16 - (currTime - lastTime))
lastTime = currTime + timeToCall
window.setTimeout((-> callback(currTime + timeToCall)), timeToCall)
unless cancelAnimationFrame
cancelAnimationFrame = (id) -> clearTimeout(id)
{
# Public: Cross browser compatibile version of requestAnimationFrame().
#
# callback - A function to be called when the next frame is available.
#
# Examples
#
# var id = utils.requestAnimationFrame ->
# doSomethingCool()
#
# Returns a id to cancel the request.
requestAnimationFrame: requestAnimationFrame
# Public: Cross browser compatibile version of cancelAnimationFrame().
#
# id - A request id.
#
# Examples
#
# id = utils.requestAnimationFrame ->
# thisWillNeverBeCalled()
# utils.cancelAnimationFrame(id)
#
# Returns nothing.
cancelAnimationFrame: cancelAnimationFrame
# Public: Defer a callback until the next available moment. This is useful
# for queuing a function to run in the near future for example to run a
# function after the current callback stack has run.
#
# fn - A function to defer.
#
# Examples
#
# annotator.editor.on "show", ->
# # Hide viewer after rest of "show" events have fired.
# utils.nextTick(annotator.viewer.show)
#
# Returns nothing.
nextTick: (fn) -> setTimeout(fn, 0)
}
| 105824 | # Adds a new "tap" event to jQuery. This offers improved performance over
# click for touch devices whcih often have up to a 300ms delay before
# triggering callbacks. Instead it uses a combination of touchstart and
# touchend events to to create a fake click. It will also cancel the event
# after 300ms (to allow the user to perform a "longtap") or if the touchend
# event is triggered on a different element.
#
# Additonal options can be provided as part of the eventData object.
#
# preventDefault - If false will not call preventDefault() on the touchstart
# event (deafult: true).
# onTapDown - Callback for the "touchstart" incase additonal code needs
# to be run such as event.stopPropagation().
# onTapUp - Callabck for the "touchend" event, called after the main
# event handler.
# timeout - Time to allow before cancelling the event (default: 300).
#
# Example
#
# jQuery("a").bind "tap", =>
# # This is called on "touchend" on the same element.
#
# options =
# preventDefault: false
# onTapDown: (event) -> event.stopPropagation()
# jQuery(doument).delegate "button", "tap", options, =>
# # This is called on "touchend" on the same element.
jQuery.event.special.tap =
add: (eventHandler) ->
data = eventHandler.data = eventHandler.data or {}
context = this
onTapStart = (event) ->
event.preventDefault() unless data.preventDefault is false
data.onTapDown.apply(this, arguments) if data.onTapDown
data.event = event
data.touched = setTimeout ->
data.touched = null
, data.timeout or 300
jQuery(document).bind(touchend: onTapEnd, mouseup: onTapEnd)
onTapEnd = (event) ->
if data.touched?
clearTimeout(data.touched)
if event.target is context or jQuery.contains(context, event.target)
handler = eventHandler.origHandler or eventHandler.handler
handler.call(this, data.event)
data.touched = null
data.onTapUp.apply(this, arguments) if data.onTapUp
jQuery(document).unbind(touchstart: onTapEnd, mousedown: onTapEnd)
data.tapHandlers = touchstart: onTapStart, mousedown: onTapStart
if eventHandler.selector
jQuery(context).delegate(eventHandler.selector, data.tapHandlers)
else
jQuery(context).bind(data.tapHandlers)
remove: (eventHandler) ->
jQuery(this).unbind(eventHandler.data.tapHandlers)
# Add support for "touch" events.
Annotator.Delegator.natives.push("touchstart", "touchmove", "touchend", "tap")
Annotator.Plugin.Touch.utils = do ->
# Pinched from <NAME>ish's blog.
# See: http://paulirish.com/2011/requestanimationframe-for-smart-animating/
vendors = ['ms', 'moz', 'webkit', 'o']
requestAnimationFrame = window.requestAnimationFrame
cancelAnimationFrame = window.cancelAnimationFrame
for prefix in vendors when !requestAnimationFrame
requestAnimationFrame = window["#{prefix}RequestAnimationFrame"]
cancelAnimationFrame = window["#{prefix}CancelAnimationFrame"] or
window["#{prefix}CancelRequestAnimationFrame"]
unless requestAnimationFrame
lastTime = 0
requestAnimationFrame = (callback, element) ->
currTime = new Date().getTime()
timeToCall = Math.max(0, 16 - (currTime - lastTime))
lastTime = currTime + timeToCall
window.setTimeout((-> callback(currTime + timeToCall)), timeToCall)
unless cancelAnimationFrame
cancelAnimationFrame = (id) -> clearTimeout(id)
{
# Public: Cross browser compatibile version of requestAnimationFrame().
#
# callback - A function to be called when the next frame is available.
#
# Examples
#
# var id = utils.requestAnimationFrame ->
# doSomethingCool()
#
# Returns a id to cancel the request.
requestAnimationFrame: requestAnimationFrame
# Public: Cross browser compatibile version of cancelAnimationFrame().
#
# id - A request id.
#
# Examples
#
# id = utils.requestAnimationFrame ->
# thisWillNeverBeCalled()
# utils.cancelAnimationFrame(id)
#
# Returns nothing.
cancelAnimationFrame: cancelAnimationFrame
# Public: Defer a callback until the next available moment. This is useful
# for queuing a function to run in the near future for example to run a
# function after the current callback stack has run.
#
# fn - A function to defer.
#
# Examples
#
# annotator.editor.on "show", ->
# # Hide viewer after rest of "show" events have fired.
# utils.nextTick(annotator.viewer.show)
#
# Returns nothing.
nextTick: (fn) -> setTimeout(fn, 0)
}
| true | # Adds a new "tap" event to jQuery. This offers improved performance over
# click for touch devices whcih often have up to a 300ms delay before
# triggering callbacks. Instead it uses a combination of touchstart and
# touchend events to to create a fake click. It will also cancel the event
# after 300ms (to allow the user to perform a "longtap") or if the touchend
# event is triggered on a different element.
#
# Additonal options can be provided as part of the eventData object.
#
# preventDefault - If false will not call preventDefault() on the touchstart
# event (deafult: true).
# onTapDown - Callback for the "touchstart" incase additonal code needs
# to be run such as event.stopPropagation().
# onTapUp - Callabck for the "touchend" event, called after the main
# event handler.
# timeout - Time to allow before cancelling the event (default: 300).
#
# Example
#
# jQuery("a").bind "tap", =>
# # This is called on "touchend" on the same element.
#
# options =
# preventDefault: false
# onTapDown: (event) -> event.stopPropagation()
# jQuery(doument).delegate "button", "tap", options, =>
# # This is called on "touchend" on the same element.
jQuery.event.special.tap =
add: (eventHandler) ->
data = eventHandler.data = eventHandler.data or {}
context = this
onTapStart = (event) ->
event.preventDefault() unless data.preventDefault is false
data.onTapDown.apply(this, arguments) if data.onTapDown
data.event = event
data.touched = setTimeout ->
data.touched = null
, data.timeout or 300
jQuery(document).bind(touchend: onTapEnd, mouseup: onTapEnd)
onTapEnd = (event) ->
if data.touched?
clearTimeout(data.touched)
if event.target is context or jQuery.contains(context, event.target)
handler = eventHandler.origHandler or eventHandler.handler
handler.call(this, data.event)
data.touched = null
data.onTapUp.apply(this, arguments) if data.onTapUp
jQuery(document).unbind(touchstart: onTapEnd, mousedown: onTapEnd)
data.tapHandlers = touchstart: onTapStart, mousedown: onTapStart
if eventHandler.selector
jQuery(context).delegate(eventHandler.selector, data.tapHandlers)
else
jQuery(context).bind(data.tapHandlers)
remove: (eventHandler) ->
jQuery(this).unbind(eventHandler.data.tapHandlers)
# Add support for "touch" events.
Annotator.Delegator.natives.push("touchstart", "touchmove", "touchend", "tap")
Annotator.Plugin.Touch.utils = do ->
# Pinched from PI:NAME:<NAME>END_PIish's blog.
# See: http://paulirish.com/2011/requestanimationframe-for-smart-animating/
vendors = ['ms', 'moz', 'webkit', 'o']
requestAnimationFrame = window.requestAnimationFrame
cancelAnimationFrame = window.cancelAnimationFrame
for prefix in vendors when !requestAnimationFrame
requestAnimationFrame = window["#{prefix}RequestAnimationFrame"]
cancelAnimationFrame = window["#{prefix}CancelAnimationFrame"] or
window["#{prefix}CancelRequestAnimationFrame"]
unless requestAnimationFrame
lastTime = 0
requestAnimationFrame = (callback, element) ->
currTime = new Date().getTime()
timeToCall = Math.max(0, 16 - (currTime - lastTime))
lastTime = currTime + timeToCall
window.setTimeout((-> callback(currTime + timeToCall)), timeToCall)
unless cancelAnimationFrame
cancelAnimationFrame = (id) -> clearTimeout(id)
{
# Public: Cross browser compatibile version of requestAnimationFrame().
#
# callback - A function to be called when the next frame is available.
#
# Examples
#
# var id = utils.requestAnimationFrame ->
# doSomethingCool()
#
# Returns a id to cancel the request.
requestAnimationFrame: requestAnimationFrame
# Public: Cross browser compatibile version of cancelAnimationFrame().
#
# id - A request id.
#
# Examples
#
# id = utils.requestAnimationFrame ->
# thisWillNeverBeCalled()
# utils.cancelAnimationFrame(id)
#
# Returns nothing.
cancelAnimationFrame: cancelAnimationFrame
# Public: Defer a callback until the next available moment. This is useful
# for queuing a function to run in the near future for example to run a
# function after the current callback stack has run.
#
# fn - A function to defer.
#
# Examples
#
# annotator.editor.on "show", ->
# # Hide viewer after rest of "show" events have fired.
# utils.nextTick(annotator.viewer.show)
#
# Returns nothing.
nextTick: (fn) -> setTimeout(fn, 0)
}
|
[
{
"context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission",
"end": 18,
"score": 0.9991607069969177,
"start": 12,
"tag": "NAME",
"value": "Joyent"
}
] | test/simple/test-cluster-setup-master-argv.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")
cluster = require("cluster")
setTimeout(assert.fail.bind(assert, "setup not emitted"), 1000).unref()
cluster.on "setup", ->
clusterArgs = cluster.settings.args
realArgs = process.argv
assert.equal clusterArgs[clusterArgs.length - 1], realArgs[realArgs.length - 1]
return
assert process.argv[process.argv.length - 1] isnt "OMG,OMG"
process.argv.push "OMG,OMG"
process.argv.push "OMG,OMG"
cluster.setupMaster()
| 111417 | # 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")
cluster = require("cluster")
setTimeout(assert.fail.bind(assert, "setup not emitted"), 1000).unref()
cluster.on "setup", ->
clusterArgs = cluster.settings.args
realArgs = process.argv
assert.equal clusterArgs[clusterArgs.length - 1], realArgs[realArgs.length - 1]
return
assert process.argv[process.argv.length - 1] isnt "OMG,OMG"
process.argv.push "OMG,OMG"
process.argv.push "OMG,OMG"
cluster.setupMaster()
| 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")
cluster = require("cluster")
setTimeout(assert.fail.bind(assert, "setup not emitted"), 1000).unref()
cluster.on "setup", ->
clusterArgs = cluster.settings.args
realArgs = process.argv
assert.equal clusterArgs[clusterArgs.length - 1], realArgs[realArgs.length - 1]
return
assert process.argv[process.argv.length - 1] isnt "OMG,OMG"
process.argv.push "OMG,OMG"
process.argv.push "OMG,OMG"
cluster.setupMaster()
|
[
{
"context": "hubot <text>なんとか - <text>っぽい日本酒を探す\n#\n# Author:\n# yagizombie <yanagihara+zombie@brainpad.co.jp>\n\nhttp = requir",
"end": 346,
"score": 0.9996864795684814,
"start": 336,
"tag": "USERNAME",
"value": "yagizombie"
},
{
"context": "んとか - <text>っぽい日本酒を探す\n#\n# Author:\n# yagizombie <yanagihara+zombie@brainpad.co.jp>\n\nhttp = require 'http'\n\nAPP_ID = process.env.CON",
"end": 380,
"score": 0.9999071359634399,
"start": 348,
"tag": "EMAIL",
"value": "yanagihara+zombie@brainpad.co.jp"
},
{
"context": " p = \"/api/v1/sakes\"\n p = p + '?token=' + APP_ID\n if keyword of table == true\n ",
"end": 2496,
"score": 0.861648440361023,
"start": 2493,
"tag": "KEY",
"value": "APP"
}
] | src/conomi-sake.coffee | yagizombie/hubot-conomi-sake | 1 | # Description
# 日本酒の情報を取得する
# https://www.sakenote.com/access_tokens (Sakenote Database API)
#
# Configuration:
# CONOMI_YD_APP_ID Yahoo! JAPANのWebサービスを利用するためのアプリケーションID
#
# Commands:
# hubot <text(都道府県)>の酒 - <text(都道府県)>のお酒を探す
# hubot <text>ってお酒 - <text>についての日本酒情報を表示する
# hubot <text>なんとか - <text>っぽい日本酒を探す
#
# Author:
# yagizombie <yanagihara+zombie@brainpad.co.jp>
http = require 'http'
APP_ID = process.env.CONOMI_SAKE_TOKEN
table = {
"北海道":1, "ほっかいどう":1,
"青森県":2, "青森":2, "あおもり":2,
"岩手県":3, "岩手":3, "いわて":3,
"宮城県":4, "宮城":4, "みやぎ":4,
"秋田県":5, "秋田":5, "あきた":5,
"山形県":6, "山形":6, "やまがた":6,
"福島県":7, "福島":7, "ふくしま":7,
"茨城県":8, "茨城":8, "いばらき":8,
"栃木県":9, "栃木":9, "とちぎ":9,
"群馬県":10, "群馬":10, "ぐんま":10,
"埼玉県":11, "埼玉":11, "さいたま":11,
"千葉県":12, "千葉":12, "ちば":12,
"東京都":13, "東京":13, "とうきょう":13,
"神奈川県":14, "神奈川":14, "かながわ":14,
"新潟県":15, "新潟":15, "にいがた":15,
"富山県":16, "富山":16, "とやま":16,
"石川県":17, "石川":17, "いしかわ":17,
"福井県":18, "福井":18, "ふくい":18,
"山梨県":19, "山梨":19, "やまなし":19,
"長野県":20, "長野":20, "ながの":20,
"岐阜県":21, "岐阜":21, "ぎふ":21,
"静岡県":22, "静岡":22, "しずおか":22,
"愛知県":23, "愛知":23, "あいち":23,
"三重県":24, "三重":24, "みえ":24,
"滋賀県":25, "滋賀":25, "しが":25,
"京都府":26, "京都":26, "きょうと":26,
"大阪府":27, "大阪":27, "おおさか":27,
"兵庫県":28, "兵庫":28, "ひょうご":28,
"奈良県":29, "奈良":29, "なら":29,
"和歌山県":30, "和歌山":30, "わかやま":30,
"鳥取県":31, "鳥取":31, "とっとり":31,
"島根県":32, "島根":32, "しまね":32,
"岡山県":33, "岡山":33, "おかやま":33,
"広島県":34, "広島":34, "ひろしま":34,
"山口県":35, "山口":35, "やまぐち":35,
"徳島県":36, "徳島":36, "とくしま":36,
"香川県":37, "香川":37, "かがわ":37,
"愛媛県":38, "愛媛":38, "えひめ":38,
"高知県":39, "高知":39, "こうち":39,
"福岡県":40, "福岡":40, "ふくおか":40,
"佐賀県":41, "佐賀":41, "さが":41,
"長崎県":42, "長崎":42, "ながさき":42,
"熊本県":43, "熊本":43, "くまもと":43,
"大分県":44, "大分":44, "おおいた":44,
"宮崎県":45, "宮崎":45, "みやざき":45,
"鹿児島県":46, "鹿児島":46, "かごしま":46,
"沖縄県":47, "沖縄":47, "おきなわ":47
}
module.exports = (robot) ->
robot.respond /(.+)(の情報|のつく酒|って酒|って日本酒|のお酒|のおさけ|の酒|のさけ|なんとか|何とか)$/i, (msg) ->
get_sake_info msg, msg.match[1]
get_sake_info = (msg, keyword="") ->
p = "/api/v1/sakes"
p = p + '?token=' + APP_ID
if keyword of table == true
p = p + '&prefecture_code=' + table[keyword]
else
p = p + '&sake_name=' + encodeURIComponent(keyword)
console.log "http://www.sakenote.com" + p
req = http.get { host:'www.sakenote.com', path:p }, (res) ->
contents = ""
res.on 'data', (chunk) ->
contents += "#{chunk}"
res.on 'end', () ->
j = JSON.parse contents
# console.log j
if j['sakes'].length == 0
msg.send "..."
return
rep = ""
for i, value of j['sakes']
rep += "\n『" + value['sake_name'] + " (" + value['sake_furigana'] + ")』 \n"
if "maker_name" of value == true
rep += " 蔵元: " + value['maker_name'] + " "
if "maker_postcode" of value == true
rep += "〒" + value['maker_postcode'] + " "
if "maker_address" of value == true
rep += value['maker_address']
rep += "\n"
if value['maker_url'] != null
rep += " URL: " + value['maker_url'] + "\n"
msg.send rep
req.on "error", (e) ->
msg.send "(boom)ぅぅぅ... {e.message}"
| 152357 | # Description
# 日本酒の情報を取得する
# https://www.sakenote.com/access_tokens (Sakenote Database API)
#
# Configuration:
# CONOMI_YD_APP_ID Yahoo! JAPANのWebサービスを利用するためのアプリケーションID
#
# Commands:
# hubot <text(都道府県)>の酒 - <text(都道府県)>のお酒を探す
# hubot <text>ってお酒 - <text>についての日本酒情報を表示する
# hubot <text>なんとか - <text>っぽい日本酒を探す
#
# Author:
# yagizombie <<EMAIL>>
http = require 'http'
APP_ID = process.env.CONOMI_SAKE_TOKEN
table = {
"北海道":1, "ほっかいどう":1,
"青森県":2, "青森":2, "あおもり":2,
"岩手県":3, "岩手":3, "いわて":3,
"宮城県":4, "宮城":4, "みやぎ":4,
"秋田県":5, "秋田":5, "あきた":5,
"山形県":6, "山形":6, "やまがた":6,
"福島県":7, "福島":7, "ふくしま":7,
"茨城県":8, "茨城":8, "いばらき":8,
"栃木県":9, "栃木":9, "とちぎ":9,
"群馬県":10, "群馬":10, "ぐんま":10,
"埼玉県":11, "埼玉":11, "さいたま":11,
"千葉県":12, "千葉":12, "ちば":12,
"東京都":13, "東京":13, "とうきょう":13,
"神奈川県":14, "神奈川":14, "かながわ":14,
"新潟県":15, "新潟":15, "にいがた":15,
"富山県":16, "富山":16, "とやま":16,
"石川県":17, "石川":17, "いしかわ":17,
"福井県":18, "福井":18, "ふくい":18,
"山梨県":19, "山梨":19, "やまなし":19,
"長野県":20, "長野":20, "ながの":20,
"岐阜県":21, "岐阜":21, "ぎふ":21,
"静岡県":22, "静岡":22, "しずおか":22,
"愛知県":23, "愛知":23, "あいち":23,
"三重県":24, "三重":24, "みえ":24,
"滋賀県":25, "滋賀":25, "しが":25,
"京都府":26, "京都":26, "きょうと":26,
"大阪府":27, "大阪":27, "おおさか":27,
"兵庫県":28, "兵庫":28, "ひょうご":28,
"奈良県":29, "奈良":29, "なら":29,
"和歌山県":30, "和歌山":30, "わかやま":30,
"鳥取県":31, "鳥取":31, "とっとり":31,
"島根県":32, "島根":32, "しまね":32,
"岡山県":33, "岡山":33, "おかやま":33,
"広島県":34, "広島":34, "ひろしま":34,
"山口県":35, "山口":35, "やまぐち":35,
"徳島県":36, "徳島":36, "とくしま":36,
"香川県":37, "香川":37, "かがわ":37,
"愛媛県":38, "愛媛":38, "えひめ":38,
"高知県":39, "高知":39, "こうち":39,
"福岡県":40, "福岡":40, "ふくおか":40,
"佐賀県":41, "佐賀":41, "さが":41,
"長崎県":42, "長崎":42, "ながさき":42,
"熊本県":43, "熊本":43, "くまもと":43,
"大分県":44, "大分":44, "おおいた":44,
"宮崎県":45, "宮崎":45, "みやざき":45,
"鹿児島県":46, "鹿児島":46, "かごしま":46,
"沖縄県":47, "沖縄":47, "おきなわ":47
}
module.exports = (robot) ->
robot.respond /(.+)(の情報|のつく酒|って酒|って日本酒|のお酒|のおさけ|の酒|のさけ|なんとか|何とか)$/i, (msg) ->
get_sake_info msg, msg.match[1]
get_sake_info = (msg, keyword="") ->
p = "/api/v1/sakes"
p = p + '?token=' + <KEY>_ID
if keyword of table == true
p = p + '&prefecture_code=' + table[keyword]
else
p = p + '&sake_name=' + encodeURIComponent(keyword)
console.log "http://www.sakenote.com" + p
req = http.get { host:'www.sakenote.com', path:p }, (res) ->
contents = ""
res.on 'data', (chunk) ->
contents += "#{chunk}"
res.on 'end', () ->
j = JSON.parse contents
# console.log j
if j['sakes'].length == 0
msg.send "..."
return
rep = ""
for i, value of j['sakes']
rep += "\n『" + value['sake_name'] + " (" + value['sake_furigana'] + ")』 \n"
if "maker_name" of value == true
rep += " 蔵元: " + value['maker_name'] + " "
if "maker_postcode" of value == true
rep += "〒" + value['maker_postcode'] + " "
if "maker_address" of value == true
rep += value['maker_address']
rep += "\n"
if value['maker_url'] != null
rep += " URL: " + value['maker_url'] + "\n"
msg.send rep
req.on "error", (e) ->
msg.send "(boom)ぅぅぅ... {e.message}"
| true | # Description
# 日本酒の情報を取得する
# https://www.sakenote.com/access_tokens (Sakenote Database API)
#
# Configuration:
# CONOMI_YD_APP_ID Yahoo! JAPANのWebサービスを利用するためのアプリケーションID
#
# Commands:
# hubot <text(都道府県)>の酒 - <text(都道府県)>のお酒を探す
# hubot <text>ってお酒 - <text>についての日本酒情報を表示する
# hubot <text>なんとか - <text>っぽい日本酒を探す
#
# Author:
# yagizombie <PI:EMAIL:<EMAIL>END_PI>
http = require 'http'
APP_ID = process.env.CONOMI_SAKE_TOKEN
table = {
"北海道":1, "ほっかいどう":1,
"青森県":2, "青森":2, "あおもり":2,
"岩手県":3, "岩手":3, "いわて":3,
"宮城県":4, "宮城":4, "みやぎ":4,
"秋田県":5, "秋田":5, "あきた":5,
"山形県":6, "山形":6, "やまがた":6,
"福島県":7, "福島":7, "ふくしま":7,
"茨城県":8, "茨城":8, "いばらき":8,
"栃木県":9, "栃木":9, "とちぎ":9,
"群馬県":10, "群馬":10, "ぐんま":10,
"埼玉県":11, "埼玉":11, "さいたま":11,
"千葉県":12, "千葉":12, "ちば":12,
"東京都":13, "東京":13, "とうきょう":13,
"神奈川県":14, "神奈川":14, "かながわ":14,
"新潟県":15, "新潟":15, "にいがた":15,
"富山県":16, "富山":16, "とやま":16,
"石川県":17, "石川":17, "いしかわ":17,
"福井県":18, "福井":18, "ふくい":18,
"山梨県":19, "山梨":19, "やまなし":19,
"長野県":20, "長野":20, "ながの":20,
"岐阜県":21, "岐阜":21, "ぎふ":21,
"静岡県":22, "静岡":22, "しずおか":22,
"愛知県":23, "愛知":23, "あいち":23,
"三重県":24, "三重":24, "みえ":24,
"滋賀県":25, "滋賀":25, "しが":25,
"京都府":26, "京都":26, "きょうと":26,
"大阪府":27, "大阪":27, "おおさか":27,
"兵庫県":28, "兵庫":28, "ひょうご":28,
"奈良県":29, "奈良":29, "なら":29,
"和歌山県":30, "和歌山":30, "わかやま":30,
"鳥取県":31, "鳥取":31, "とっとり":31,
"島根県":32, "島根":32, "しまね":32,
"岡山県":33, "岡山":33, "おかやま":33,
"広島県":34, "広島":34, "ひろしま":34,
"山口県":35, "山口":35, "やまぐち":35,
"徳島県":36, "徳島":36, "とくしま":36,
"香川県":37, "香川":37, "かがわ":37,
"愛媛県":38, "愛媛":38, "えひめ":38,
"高知県":39, "高知":39, "こうち":39,
"福岡県":40, "福岡":40, "ふくおか":40,
"佐賀県":41, "佐賀":41, "さが":41,
"長崎県":42, "長崎":42, "ながさき":42,
"熊本県":43, "熊本":43, "くまもと":43,
"大分県":44, "大分":44, "おおいた":44,
"宮崎県":45, "宮崎":45, "みやざき":45,
"鹿児島県":46, "鹿児島":46, "かごしま":46,
"沖縄県":47, "沖縄":47, "おきなわ":47
}
module.exports = (robot) ->
robot.respond /(.+)(の情報|のつく酒|って酒|って日本酒|のお酒|のおさけ|の酒|のさけ|なんとか|何とか)$/i, (msg) ->
get_sake_info msg, msg.match[1]
get_sake_info = (msg, keyword="") ->
p = "/api/v1/sakes"
p = p + '?token=' + PI:KEY:<KEY>END_PI_ID
if keyword of table == true
p = p + '&prefecture_code=' + table[keyword]
else
p = p + '&sake_name=' + encodeURIComponent(keyword)
console.log "http://www.sakenote.com" + p
req = http.get { host:'www.sakenote.com', path:p }, (res) ->
contents = ""
res.on 'data', (chunk) ->
contents += "#{chunk}"
res.on 'end', () ->
j = JSON.parse contents
# console.log j
if j['sakes'].length == 0
msg.send "..."
return
rep = ""
for i, value of j['sakes']
rep += "\n『" + value['sake_name'] + " (" + value['sake_furigana'] + ")』 \n"
if "maker_name" of value == true
rep += " 蔵元: " + value['maker_name'] + " "
if "maker_postcode" of value == true
rep += "〒" + value['maker_postcode'] + " "
if "maker_address" of value == true
rep += value['maker_address']
rep += "\n"
if value['maker_url'] != null
rep += " URL: " + value['maker_url'] + "\n"
msg.send rep
req.on "error", (e) ->
msg.send "(boom)ぅぅぅ... {e.message}"
|
[
{
"context": "# Copyright (C) 2013 John Judnich\n# Released under The MIT License - see \"LICENSE\" ",
"end": 33,
"score": 0.999871551990509,
"start": 21,
"tag": "NAME",
"value": "John Judnich"
}
] | source/Bounds.coffee | anandprabhakar0507/Kosmos | 46 | # Copyright (C) 2013 John Judnich
# Released under The MIT License - see "LICENSE" file for details.
root = exports ? this
class root.Box
constructor: (x0 = 0, y0 = 0, z0 = 0, x1 = 1, y1 = 1, z1 = 1) ->
@min = vec2.fromValues(x0, y0, z0)
@max = vec2.fromValues(x1, y1, z1)
normalize: ->
for i in [0..2]
if @min[i] > @max[i]
[@min[i], @max[i]] = [@max[i], @min[i]]
getCenter: ->
center = vec3.create()
vec3.add(center, @min, @max)
vec3.scale(center, center, 0.5)
return center
getRadius: ->
cross = vec3.create()
vec3.sub(cross, @max, @min)
return vec3.len(cross) * 0.5
getCorners: ->
corners = []
corners[0] = vec3.fromValues(@max[0], @max[1], @max[2])
corners[1] = vec3.fromValues(@min[0], @max[1], @max[2])
corners[2] = vec3.fromValues(@min[0], @min[1], @max[2])
corners[3] = vec3.fromValues(@max[0], @min[1], @max[2])
corners[4] = vec3.fromValues(@max[0], @max[1], @min[2])
corners[5] = vec3.fromValues(@min[0], @max[1], @min[2])
corners[6] = vec3.fromValues(@min[0], @min[1], @min[2])
corners[7] = vec3.fromValues(@max[0], @min[1], @min[2])
return corners
getCorner: (i) ->
if i == 0
return vec3.fromValues(@max[0], @max[1], @max[2])
else if i == 1
return vec3.fromValues(@min[0], @max[1], @max[2])
else if i == 2
return vec3.fromValues(@min[0], @min[1], @max[2])
else if i == 3
return vec3.fromValues(@max[0], @min[1], @max[2])
else if i == 4
return vec3.fromValues(@max[0], @max[1], @min[2])
else if i == 5
return vec3.fromValues(@min[0], @max[1], @min[2])
else if i == 6
return vec3.fromValues(@min[0], @min[1], @min[2])
else if i == 7
return vec3.fromValues(@max[0], @min[1], @min[2])
else
return null
getOctant: (i) ->
b = new Box()
b.min = @getCenter()
b.max = @getCorner(i)
if b.max == null then return null
b.normalize()
return b
class root.Rect
constructor: (x0 = 0, y0 = 0, x1 = 1, y1 = 1) ->
@min = vec2.fromValues(x0, y0)
@max = vec2.fromValues(x1, y1)
normalize: ->
for i in [0..1]
if @min[i] > @max[i]
[@min[i], @max[i]] = [@max[i], @min[i]]
getCenter: ->
center = vec2.create()
vec2.add(center, @min, @max)
vec2.scale(center, center, 0.5)
return center
getRadius: ->
cross = vec2.create()
vec2.sub(cross, @max, @min)
return vec2.len(cross) * 0.5
getCorners: ->
corners = []
corners[0] = vec2.fromValues(@max[0], @max[1])
corners[1] = vec2.fromValues(@min[0], @max[1])
corners[2] = vec2.fromValues(@min[0], @min[1])
corners[3] = vec2.fromValues(@max[0], @min[1])
return corners
getCorner: (i) ->
if i == 0
return vec2.fromValues(@max[0], @max[1])
else if i == 1
return vec2.fromValues(@min[0], @max[1])
else if i == 2
return vec2.fromValues(@min[0], @min[1])
else if i == 3
return vec2.fromValues(@max[0], @min[1])
else
return null
getQuadrant: (i) ->
b = new Rect()
b.min = @getCenter()
b.max = @getCorner(i)
if b.max == null then return null
b.normalize()
return b
| 89449 | # Copyright (C) 2013 <NAME>
# Released under The MIT License - see "LICENSE" file for details.
root = exports ? this
class root.Box
constructor: (x0 = 0, y0 = 0, z0 = 0, x1 = 1, y1 = 1, z1 = 1) ->
@min = vec2.fromValues(x0, y0, z0)
@max = vec2.fromValues(x1, y1, z1)
normalize: ->
for i in [0..2]
if @min[i] > @max[i]
[@min[i], @max[i]] = [@max[i], @min[i]]
getCenter: ->
center = vec3.create()
vec3.add(center, @min, @max)
vec3.scale(center, center, 0.5)
return center
getRadius: ->
cross = vec3.create()
vec3.sub(cross, @max, @min)
return vec3.len(cross) * 0.5
getCorners: ->
corners = []
corners[0] = vec3.fromValues(@max[0], @max[1], @max[2])
corners[1] = vec3.fromValues(@min[0], @max[1], @max[2])
corners[2] = vec3.fromValues(@min[0], @min[1], @max[2])
corners[3] = vec3.fromValues(@max[0], @min[1], @max[2])
corners[4] = vec3.fromValues(@max[0], @max[1], @min[2])
corners[5] = vec3.fromValues(@min[0], @max[1], @min[2])
corners[6] = vec3.fromValues(@min[0], @min[1], @min[2])
corners[7] = vec3.fromValues(@max[0], @min[1], @min[2])
return corners
getCorner: (i) ->
if i == 0
return vec3.fromValues(@max[0], @max[1], @max[2])
else if i == 1
return vec3.fromValues(@min[0], @max[1], @max[2])
else if i == 2
return vec3.fromValues(@min[0], @min[1], @max[2])
else if i == 3
return vec3.fromValues(@max[0], @min[1], @max[2])
else if i == 4
return vec3.fromValues(@max[0], @max[1], @min[2])
else if i == 5
return vec3.fromValues(@min[0], @max[1], @min[2])
else if i == 6
return vec3.fromValues(@min[0], @min[1], @min[2])
else if i == 7
return vec3.fromValues(@max[0], @min[1], @min[2])
else
return null
getOctant: (i) ->
b = new Box()
b.min = @getCenter()
b.max = @getCorner(i)
if b.max == null then return null
b.normalize()
return b
class root.Rect
constructor: (x0 = 0, y0 = 0, x1 = 1, y1 = 1) ->
@min = vec2.fromValues(x0, y0)
@max = vec2.fromValues(x1, y1)
normalize: ->
for i in [0..1]
if @min[i] > @max[i]
[@min[i], @max[i]] = [@max[i], @min[i]]
getCenter: ->
center = vec2.create()
vec2.add(center, @min, @max)
vec2.scale(center, center, 0.5)
return center
getRadius: ->
cross = vec2.create()
vec2.sub(cross, @max, @min)
return vec2.len(cross) * 0.5
getCorners: ->
corners = []
corners[0] = vec2.fromValues(@max[0], @max[1])
corners[1] = vec2.fromValues(@min[0], @max[1])
corners[2] = vec2.fromValues(@min[0], @min[1])
corners[3] = vec2.fromValues(@max[0], @min[1])
return corners
getCorner: (i) ->
if i == 0
return vec2.fromValues(@max[0], @max[1])
else if i == 1
return vec2.fromValues(@min[0], @max[1])
else if i == 2
return vec2.fromValues(@min[0], @min[1])
else if i == 3
return vec2.fromValues(@max[0], @min[1])
else
return null
getQuadrant: (i) ->
b = new Rect()
b.min = @getCenter()
b.max = @getCorner(i)
if b.max == null then return null
b.normalize()
return b
| true | # Copyright (C) 2013 PI:NAME:<NAME>END_PI
# Released under The MIT License - see "LICENSE" file for details.
root = exports ? this
class root.Box
constructor: (x0 = 0, y0 = 0, z0 = 0, x1 = 1, y1 = 1, z1 = 1) ->
@min = vec2.fromValues(x0, y0, z0)
@max = vec2.fromValues(x1, y1, z1)
normalize: ->
for i in [0..2]
if @min[i] > @max[i]
[@min[i], @max[i]] = [@max[i], @min[i]]
getCenter: ->
center = vec3.create()
vec3.add(center, @min, @max)
vec3.scale(center, center, 0.5)
return center
getRadius: ->
cross = vec3.create()
vec3.sub(cross, @max, @min)
return vec3.len(cross) * 0.5
getCorners: ->
corners = []
corners[0] = vec3.fromValues(@max[0], @max[1], @max[2])
corners[1] = vec3.fromValues(@min[0], @max[1], @max[2])
corners[2] = vec3.fromValues(@min[0], @min[1], @max[2])
corners[3] = vec3.fromValues(@max[0], @min[1], @max[2])
corners[4] = vec3.fromValues(@max[0], @max[1], @min[2])
corners[5] = vec3.fromValues(@min[0], @max[1], @min[2])
corners[6] = vec3.fromValues(@min[0], @min[1], @min[2])
corners[7] = vec3.fromValues(@max[0], @min[1], @min[2])
return corners
getCorner: (i) ->
if i == 0
return vec3.fromValues(@max[0], @max[1], @max[2])
else if i == 1
return vec3.fromValues(@min[0], @max[1], @max[2])
else if i == 2
return vec3.fromValues(@min[0], @min[1], @max[2])
else if i == 3
return vec3.fromValues(@max[0], @min[1], @max[2])
else if i == 4
return vec3.fromValues(@max[0], @max[1], @min[2])
else if i == 5
return vec3.fromValues(@min[0], @max[1], @min[2])
else if i == 6
return vec3.fromValues(@min[0], @min[1], @min[2])
else if i == 7
return vec3.fromValues(@max[0], @min[1], @min[2])
else
return null
getOctant: (i) ->
b = new Box()
b.min = @getCenter()
b.max = @getCorner(i)
if b.max == null then return null
b.normalize()
return b
class root.Rect
constructor: (x0 = 0, y0 = 0, x1 = 1, y1 = 1) ->
@min = vec2.fromValues(x0, y0)
@max = vec2.fromValues(x1, y1)
normalize: ->
for i in [0..1]
if @min[i] > @max[i]
[@min[i], @max[i]] = [@max[i], @min[i]]
getCenter: ->
center = vec2.create()
vec2.add(center, @min, @max)
vec2.scale(center, center, 0.5)
return center
getRadius: ->
cross = vec2.create()
vec2.sub(cross, @max, @min)
return vec2.len(cross) * 0.5
getCorners: ->
corners = []
corners[0] = vec2.fromValues(@max[0], @max[1])
corners[1] = vec2.fromValues(@min[0], @max[1])
corners[2] = vec2.fromValues(@min[0], @min[1])
corners[3] = vec2.fromValues(@max[0], @min[1])
return corners
getCorner: (i) ->
if i == 0
return vec2.fromValues(@max[0], @max[1])
else if i == 1
return vec2.fromValues(@min[0], @max[1])
else if i == 2
return vec2.fromValues(@min[0], @min[1])
else if i == 3
return vec2.fromValues(@max[0], @min[1])
else
return null
getQuadrant: (i) ->
b = new Rect()
b.min = @getCenter()
b.max = @getCorner(i)
if b.max == null then return null
b.normalize()
return b
|
[
{
"context": "###\n# cedux.coffee\n# @author Sidharth Mishra - sidmishraw\n# @description A minimal redux clone",
"end": 44,
"score": 0.999885082244873,
"start": 29,
"tag": "NAME",
"value": "Sidharth Mishra"
},
{
"context": "###\n# cedux.coffee\n# @author Sidharth Mishra - sidmishraw\n# @description A minimal redux clone in coffeescr",
"end": 57,
"score": 0.9995724558830261,
"start": 47,
"tag": "USERNAME",
"value": "sidmishraw"
}
] | src/cfs/cedux.coffee | sidmishraw/cedux | 1 | ###
# cedux.coffee
# @author Sidharth Mishra - sidmishraw
# @description A minimal redux clone in coffeescript
# @created Sun Nov 19 2017 23:05:43 GMT-0800 (PST)
# @last-modified Sun Nov 19 2017 23:05:43 GMT-0800 (PST)
###
#===========================================================#
# /𝞝𝞝𝞝𝞝𝞝𝞝𝞝𝞝𝞝/ #
# /𝞝𝞝𝞝𝞝𝞝𝞝𝞝𝞝𝞝/ #
# /𝞝𝞝/ #
# /𝞝𝞝/ edux #
# /𝞝𝞝𝞝𝞝𝞝𝞝𝞝𝞝𝞝/ #
# /𝞝𝞝𝞝𝞝𝞝𝞝𝞝𝞝𝞝/ #
#===========================================================#
export cedux = ->
do(Store = undefined, cedux = undefined) ->
Store = {
updateCount:0,
stateTree:{},
state: null,
reducer: null
}
cedux =
# createStore
#~~~~~~~~~~~~~~~~
# @param reducer - The reducer is a pure function that takes in an action and the current state
# of the Store and returns a new state for the store
# The reducer is of the form `(state, action) -> state`
#
# @param initialState - The initial state of the Store.
#
createStore: (reducer, initialState) ->
Store.reducer = reducer
Store.state = initialState
cedux
# dispatch
#~~~~~~~~~~~~
# This function acts as dispatcher. It dispatches the incoming actions.
# The incoming action is passed through the reducer. The reducer computes and updates the
# state of the Store.
#
# @param incomingAction - The incoming action to the dispatcher.
#
dispatch: (incomingAction) ->
Store.updateCount += 1
Store.stateTree["StateKey: #{Store.updateCount}"] = Store.state # push it into the state tree
Store.state = Store.reducer Store.state, incomingAction # compute the action from currentState and incomingAction
incomingAction
# getCurrentState
#~~~~~~~~~~~~~~~~~
# Fetches the current state of the Store
#
getCurrentState: ->
Store.state
# getStateTree
#~~~~~~~~~~~~~~~
# Fetches the state history tree
getStateTree: ->
Store.stateTree
| 179376 | ###
# cedux.coffee
# @author <NAME> - sidmishraw
# @description A minimal redux clone in coffeescript
# @created Sun Nov 19 2017 23:05:43 GMT-0800 (PST)
# @last-modified Sun Nov 19 2017 23:05:43 GMT-0800 (PST)
###
#===========================================================#
# /𝞝𝞝𝞝𝞝𝞝𝞝𝞝𝞝𝞝/ #
# /𝞝𝞝𝞝𝞝𝞝𝞝𝞝𝞝𝞝/ #
# /𝞝𝞝/ #
# /𝞝𝞝/ edux #
# /𝞝𝞝𝞝𝞝𝞝𝞝𝞝𝞝𝞝/ #
# /𝞝𝞝𝞝𝞝𝞝𝞝𝞝𝞝𝞝/ #
#===========================================================#
export cedux = ->
do(Store = undefined, cedux = undefined) ->
Store = {
updateCount:0,
stateTree:{},
state: null,
reducer: null
}
cedux =
# createStore
#~~~~~~~~~~~~~~~~
# @param reducer - The reducer is a pure function that takes in an action and the current state
# of the Store and returns a new state for the store
# The reducer is of the form `(state, action) -> state`
#
# @param initialState - The initial state of the Store.
#
createStore: (reducer, initialState) ->
Store.reducer = reducer
Store.state = initialState
cedux
# dispatch
#~~~~~~~~~~~~
# This function acts as dispatcher. It dispatches the incoming actions.
# The incoming action is passed through the reducer. The reducer computes and updates the
# state of the Store.
#
# @param incomingAction - The incoming action to the dispatcher.
#
dispatch: (incomingAction) ->
Store.updateCount += 1
Store.stateTree["StateKey: #{Store.updateCount}"] = Store.state # push it into the state tree
Store.state = Store.reducer Store.state, incomingAction # compute the action from currentState and incomingAction
incomingAction
# getCurrentState
#~~~~~~~~~~~~~~~~~
# Fetches the current state of the Store
#
getCurrentState: ->
Store.state
# getStateTree
#~~~~~~~~~~~~~~~
# Fetches the state history tree
getStateTree: ->
Store.stateTree
| true | ###
# cedux.coffee
# @author PI:NAME:<NAME>END_PI - sidmishraw
# @description A minimal redux clone in coffeescript
# @created Sun Nov 19 2017 23:05:43 GMT-0800 (PST)
# @last-modified Sun Nov 19 2017 23:05:43 GMT-0800 (PST)
###
#===========================================================#
# /𝞝𝞝𝞝𝞝𝞝𝞝𝞝𝞝𝞝/ #
# /𝞝𝞝𝞝𝞝𝞝𝞝𝞝𝞝𝞝/ #
# /𝞝𝞝/ #
# /𝞝𝞝/ edux #
# /𝞝𝞝𝞝𝞝𝞝𝞝𝞝𝞝𝞝/ #
# /𝞝𝞝𝞝𝞝𝞝𝞝𝞝𝞝𝞝/ #
#===========================================================#
export cedux = ->
do(Store = undefined, cedux = undefined) ->
Store = {
updateCount:0,
stateTree:{},
state: null,
reducer: null
}
cedux =
# createStore
#~~~~~~~~~~~~~~~~
# @param reducer - The reducer is a pure function that takes in an action and the current state
# of the Store and returns a new state for the store
# The reducer is of the form `(state, action) -> state`
#
# @param initialState - The initial state of the Store.
#
createStore: (reducer, initialState) ->
Store.reducer = reducer
Store.state = initialState
cedux
# dispatch
#~~~~~~~~~~~~
# This function acts as dispatcher. It dispatches the incoming actions.
# The incoming action is passed through the reducer. The reducer computes and updates the
# state of the Store.
#
# @param incomingAction - The incoming action to the dispatcher.
#
dispatch: (incomingAction) ->
Store.updateCount += 1
Store.stateTree["StateKey: #{Store.updateCount}"] = Store.state # push it into the state tree
Store.state = Store.reducer Store.state, incomingAction # compute the action from currentState and incomingAction
incomingAction
# getCurrentState
#~~~~~~~~~~~~~~~~~
# Fetches the current state of the Store
#
getCurrentState: ->
Store.state
# getStateTree
#~~~~~~~~~~~~~~~
# Fetches the state history tree
getStateTree: ->
Store.stateTree
|
[
{
"context": "lor Picker for the Generator for WolfCage\n\n@author Destin Moulton\n@git https://github.com/destinmoulton/wolfcage\n@l",
"end": 76,
"score": 0.9998515844345093,
"start": 62,
"tag": "NAME",
"value": "Destin Moulton"
},
{
"context": "e\n\n@author Destin Moulton\n@git https://github.com/destinmoulton/wolfcage\n@license MIT\n\nComponent of the Wolfram C",
"end": 114,
"score": 0.9952937364578247,
"start": 101,
"tag": "USERNAME",
"value": "destinmoulton"
}
] | src/MultiColorPicker.coffee | destinmoulton/cagen | 0 | ###
The Color Picker for the Generator for WolfCage
@author Destin Moulton
@git https://github.com/destinmoulton/wolfcage
@license MIT
Component of the Wolfram Cellular Automata Generator (WolfCage)
Add color pickers with color inputs.
###
DOM = require("./DOM.coffee")
Templates = require("./Templates.coffee")
colors = require("./lib/colors.coffee")
class MultiColorPicker
#
# ColorPicker constructor
#
constructor:(BUS) ->
@BUS = BUS
#
# Build the color picker boxes from the template
#
_setColorPickersHex:() ->
@elCPActive.value = @BUS.get('board.cell.style.activeBackgroundColor')
@elCPBorder.value = @BUS.get('board.cell.style.borderColor')
@elCPInactive.value = @BUS.get('board.cell.style.inactiveBackgroundColor')
_buildColorSelectOptions:() ->
options = ""
for color in colors
options += Templates.colorPickerOption(color)
return options
#
# Enable the color picker
#
enableColorPicker:() ->
@elContainer = DOM.elemById('COLORPICKER', 'CONTAINER')
@elContainer.innerHTML = Templates.colorPickers
@elContainer.style.display = "block"
@elCPActive = DOM.elemById('COLORPICKER', 'ACTIVE_HEX')
@elCPBorder = DOM.elemById('COLORPICKER', 'BORDER_HEX')
@elCPInactive = DOM.elemById('COLORPICKER', 'INACTIVE_HEX')
@elCPActive.innerHTML = @_buildColorSelectOptions()
@elCPBorder.innerHTML = @_buildColorSelectOptions()
@elCPInactive.innerHTML = @_buildColorSelectOptions()
@_setColorPickersHex()
@elCPActive.addEventListener('change', (e)=>
@BUS.broadcast('change.cell.style.activebackground', e.target.value)
@_setColorPickersHex()
)
@elCPBorder.addEventListener('change', (e)=>
@BUS.broadcast('change.cell.style.bordercolor', e.target.value)
@_setColorPickersHex()
)
@elCPInactive.addEventListener('change', (e)=>
@BUS.broadcast('change.cell.style.inactivebackground', e.target.value)
@_setColorPickersHex()
)
#
# Disable the color picker
#
disableColorPicker:() ->
@elContainer.innerhtml = ""
@elContainer.style.display = "none"
module.exports = MultiColorPicker | 216797 | ###
The Color Picker for the Generator for WolfCage
@author <NAME>
@git https://github.com/destinmoulton/wolfcage
@license MIT
Component of the Wolfram Cellular Automata Generator (WolfCage)
Add color pickers with color inputs.
###
DOM = require("./DOM.coffee")
Templates = require("./Templates.coffee")
colors = require("./lib/colors.coffee")
class MultiColorPicker
#
# ColorPicker constructor
#
constructor:(BUS) ->
@BUS = BUS
#
# Build the color picker boxes from the template
#
_setColorPickersHex:() ->
@elCPActive.value = @BUS.get('board.cell.style.activeBackgroundColor')
@elCPBorder.value = @BUS.get('board.cell.style.borderColor')
@elCPInactive.value = @BUS.get('board.cell.style.inactiveBackgroundColor')
_buildColorSelectOptions:() ->
options = ""
for color in colors
options += Templates.colorPickerOption(color)
return options
#
# Enable the color picker
#
enableColorPicker:() ->
@elContainer = DOM.elemById('COLORPICKER', 'CONTAINER')
@elContainer.innerHTML = Templates.colorPickers
@elContainer.style.display = "block"
@elCPActive = DOM.elemById('COLORPICKER', 'ACTIVE_HEX')
@elCPBorder = DOM.elemById('COLORPICKER', 'BORDER_HEX')
@elCPInactive = DOM.elemById('COLORPICKER', 'INACTIVE_HEX')
@elCPActive.innerHTML = @_buildColorSelectOptions()
@elCPBorder.innerHTML = @_buildColorSelectOptions()
@elCPInactive.innerHTML = @_buildColorSelectOptions()
@_setColorPickersHex()
@elCPActive.addEventListener('change', (e)=>
@BUS.broadcast('change.cell.style.activebackground', e.target.value)
@_setColorPickersHex()
)
@elCPBorder.addEventListener('change', (e)=>
@BUS.broadcast('change.cell.style.bordercolor', e.target.value)
@_setColorPickersHex()
)
@elCPInactive.addEventListener('change', (e)=>
@BUS.broadcast('change.cell.style.inactivebackground', e.target.value)
@_setColorPickersHex()
)
#
# Disable the color picker
#
disableColorPicker:() ->
@elContainer.innerhtml = ""
@elContainer.style.display = "none"
module.exports = MultiColorPicker | true | ###
The Color Picker for the Generator for WolfCage
@author PI:NAME:<NAME>END_PI
@git https://github.com/destinmoulton/wolfcage
@license MIT
Component of the Wolfram Cellular Automata Generator (WolfCage)
Add color pickers with color inputs.
###
DOM = require("./DOM.coffee")
Templates = require("./Templates.coffee")
colors = require("./lib/colors.coffee")
class MultiColorPicker
#
# ColorPicker constructor
#
constructor:(BUS) ->
@BUS = BUS
#
# Build the color picker boxes from the template
#
_setColorPickersHex:() ->
@elCPActive.value = @BUS.get('board.cell.style.activeBackgroundColor')
@elCPBorder.value = @BUS.get('board.cell.style.borderColor')
@elCPInactive.value = @BUS.get('board.cell.style.inactiveBackgroundColor')
_buildColorSelectOptions:() ->
options = ""
for color in colors
options += Templates.colorPickerOption(color)
return options
#
# Enable the color picker
#
enableColorPicker:() ->
@elContainer = DOM.elemById('COLORPICKER', 'CONTAINER')
@elContainer.innerHTML = Templates.colorPickers
@elContainer.style.display = "block"
@elCPActive = DOM.elemById('COLORPICKER', 'ACTIVE_HEX')
@elCPBorder = DOM.elemById('COLORPICKER', 'BORDER_HEX')
@elCPInactive = DOM.elemById('COLORPICKER', 'INACTIVE_HEX')
@elCPActive.innerHTML = @_buildColorSelectOptions()
@elCPBorder.innerHTML = @_buildColorSelectOptions()
@elCPInactive.innerHTML = @_buildColorSelectOptions()
@_setColorPickersHex()
@elCPActive.addEventListener('change', (e)=>
@BUS.broadcast('change.cell.style.activebackground', e.target.value)
@_setColorPickersHex()
)
@elCPBorder.addEventListener('change', (e)=>
@BUS.broadcast('change.cell.style.bordercolor', e.target.value)
@_setColorPickersHex()
)
@elCPInactive.addEventListener('change', (e)=>
@BUS.broadcast('change.cell.style.inactivebackground', e.target.value)
@_setColorPickersHex()
)
#
# Disable the color picker
#
disableColorPicker:() ->
@elContainer.innerhtml = ""
@elContainer.style.display = "none"
module.exports = MultiColorPicker |
[
{
"context": "eorge.rhcloud.com/shuttle/\"\n localHost = \"http://127.0.0.1:8000/shuttle/\"\n\n host = externalHost\n\n useLocal",
"end": 172,
"score": 0.9983551502227783,
"start": 163,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": "ey('')\n login: (user, password) ->\n pass = saEncPass(password)\n result = $q.defer()\n\n saHttp",
"end": 673,
"score": 0.9933784604072571,
"start": 664,
"tag": "PASSWORD",
"value": "saEncPass"
},
{
"context": "login: (user, password) ->\n pass = saEncPass(password)\n result = $q.defer()\n\n saHttp.post(saA",
"end": 682,
"score": 0.43764016032218933,
"start": 674,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "aHttp.post(saApiEndpoints.login,\n username: user\n password: pass\n ).success((d) ->\n ",
"end": 773,
"score": 0.9106336236000061,
"start": 769,
"tag": "USERNAME",
"value": "user"
},
{
"context": "ts.login,\n username: user\n password: pass\n ).success((d) ->\n if d.success\n ",
"end": 796,
"score": 0.8808974623680115,
"start": 792,
"tag": "PASSWORD",
"value": "pass"
},
{
"context": "s((d) ->\n if d.success\n username = user\n saHttp.setApiKey(d.data)\n resu",
"end": 866,
"score": 0.9890877604484558,
"start": 862,
"tag": "USERNAME",
"value": "user"
}
] | js/services/core.coffee | bassoGeorge/shuttle-up-2015 | 0 | angular.module 'shuttleApp.services', []
.provider('saApiEndpoints', () ->
externalHost = "http://django-bassogeorge.rhcloud.com/shuttle/"
localHost = "http://127.0.0.1:8000/shuttle/"
host = externalHost
useLocalHost: (b) ->
if Boolean(b)
host = localHost
else
host = externalHost
$get: () ->
return {
echo: host
login: host+"login"
}
)
.factory 'saUserCreds', (saApiEndpoints, saEncPass, saHttp, $q) ->
username = ''
return {
username: () -> username
isLoggedIn: () -> Boolean(username)
logout: () ->
username = ''
saHttp.setApiKey('')
login: (user, password) ->
pass = saEncPass(password)
result = $q.defer()
saHttp.post(saApiEndpoints.login,
username: user
password: pass
).success((d) ->
if d.success
username = user
saHttp.setApiKey(d.data)
result.resolve(username)
else
result.reject(d.reason || d.error)
)
return result.promise
}
| 29144 | angular.module 'shuttleApp.services', []
.provider('saApiEndpoints', () ->
externalHost = "http://django-bassogeorge.rhcloud.com/shuttle/"
localHost = "http://127.0.0.1:8000/shuttle/"
host = externalHost
useLocalHost: (b) ->
if Boolean(b)
host = localHost
else
host = externalHost
$get: () ->
return {
echo: host
login: host+"login"
}
)
.factory 'saUserCreds', (saApiEndpoints, saEncPass, saHttp, $q) ->
username = ''
return {
username: () -> username
isLoggedIn: () -> Boolean(username)
logout: () ->
username = ''
saHttp.setApiKey('')
login: (user, password) ->
pass = <PASSWORD>(<PASSWORD>)
result = $q.defer()
saHttp.post(saApiEndpoints.login,
username: user
password: <PASSWORD>
).success((d) ->
if d.success
username = user
saHttp.setApiKey(d.data)
result.resolve(username)
else
result.reject(d.reason || d.error)
)
return result.promise
}
| true | angular.module 'shuttleApp.services', []
.provider('saApiEndpoints', () ->
externalHost = "http://django-bassogeorge.rhcloud.com/shuttle/"
localHost = "http://127.0.0.1:8000/shuttle/"
host = externalHost
useLocalHost: (b) ->
if Boolean(b)
host = localHost
else
host = externalHost
$get: () ->
return {
echo: host
login: host+"login"
}
)
.factory 'saUserCreds', (saApiEndpoints, saEncPass, saHttp, $q) ->
username = ''
return {
username: () -> username
isLoggedIn: () -> Boolean(username)
logout: () ->
username = ''
saHttp.setApiKey('')
login: (user, password) ->
pass = PI:PASSWORD:<PASSWORD>END_PI(PI:PASSWORD:<PASSWORD>END_PI)
result = $q.defer()
saHttp.post(saApiEndpoints.login,
username: user
password: PI:PASSWORD:<PASSWORD>END_PI
).success((d) ->
if d.success
username = user
saHttp.setApiKey(d.data)
result.resolve(username)
else
result.reject(d.reason || d.error)
)
return result.promise
}
|
[
{
"context": "werOptions.map (answerOption) =>\n key = \"question_#{questionId}_answer_#{answerOption.id}\"\n li\n classNa",
"end": 1015,
"score": 0.9949952363967896,
"start": 983,
"tag": "KEY",
"value": "question_#{questionId}_answer_#{"
},
{
"context": " key = \"question_#{questionId}_answer_#{answerOption.id}\"\n li\n className: 'option'",
"end": 1027,
"score": 0.5993161201477051,
"start": 1021,
"tag": "KEY",
"value": "Option"
},
{
"context": "y = \"question_#{questionId}_answer_#{answerOption.id}\"\n li\n className: 'option'\n ",
"end": 1032,
"score": 0.9968802332878113,
"start": 1028,
"tag": "KEY",
"value": "id}\""
}
] | app/assets/javascripts/components/question.coffee | roqua/screensmart | 2 | {div, h1, p, em, ul, li, input, label, i} = React.DOM
@Question = React.createClass
displayName: 'Question'
mixins: [ScrollToOnMountMixin]
propTypes:
question: React.PropTypes.object.isRequired
onAnswerChange: React.PropTypes.func.isRequired
editable: React.PropTypes.bool.isRequired
onOptionClick: (event) ->
question = event.target
@props.onAnswerChange(question.name, parseInt(question.value))
className: ->
className= 'question'
className += ' disabled' if @props.disabled
className
render: ->
{text, intro, answerOptionSet, answerValue} = @props.question
questionId = @props.question.id
div
className: @className()
p
className: 'intro-text'
em
className: ''
intro
p
className: 'text'
text
ul
className: "options answer-option-set-#{answerOptionSet.id}"
answerOptionSet.answerOptions.map (answerOption) =>
key = "question_#{questionId}_answer_#{answerOption.id}"
li
className: 'option'
key: key
input
type: 'radio'
name: questionId
id: key
value: answerOption.id
onChange: @onOptionClick
checked: answerValue == answerOption.id
label
className: 'text'
htmlFor: key
answerOption.text
| 104270 | {div, h1, p, em, ul, li, input, label, i} = React.DOM
@Question = React.createClass
displayName: 'Question'
mixins: [ScrollToOnMountMixin]
propTypes:
question: React.PropTypes.object.isRequired
onAnswerChange: React.PropTypes.func.isRequired
editable: React.PropTypes.bool.isRequired
onOptionClick: (event) ->
question = event.target
@props.onAnswerChange(question.name, parseInt(question.value))
className: ->
className= 'question'
className += ' disabled' if @props.disabled
className
render: ->
{text, intro, answerOptionSet, answerValue} = @props.question
questionId = @props.question.id
div
className: @className()
p
className: 'intro-text'
em
className: ''
intro
p
className: 'text'
text
ul
className: "options answer-option-set-#{answerOptionSet.id}"
answerOptionSet.answerOptions.map (answerOption) =>
key = "<KEY>answer<KEY>.<KEY>
li
className: 'option'
key: key
input
type: 'radio'
name: questionId
id: key
value: answerOption.id
onChange: @onOptionClick
checked: answerValue == answerOption.id
label
className: 'text'
htmlFor: key
answerOption.text
| true | {div, h1, p, em, ul, li, input, label, i} = React.DOM
@Question = React.createClass
displayName: 'Question'
mixins: [ScrollToOnMountMixin]
propTypes:
question: React.PropTypes.object.isRequired
onAnswerChange: React.PropTypes.func.isRequired
editable: React.PropTypes.bool.isRequired
onOptionClick: (event) ->
question = event.target
@props.onAnswerChange(question.name, parseInt(question.value))
className: ->
className= 'question'
className += ' disabled' if @props.disabled
className
render: ->
{text, intro, answerOptionSet, answerValue} = @props.question
questionId = @props.question.id
div
className: @className()
p
className: 'intro-text'
em
className: ''
intro
p
className: 'text'
text
ul
className: "options answer-option-set-#{answerOptionSet.id}"
answerOptionSet.answerOptions.map (answerOption) =>
key = "PI:KEY:<KEY>END_PIanswerPI:KEY:<KEY>END_PI.PI:KEY:<KEY>END_PI
li
className: 'option'
key: key
input
type: 'radio'
name: questionId
id: key
value: answerOption.id
onChange: @onOptionClick
checked: answerValue == answerOption.id
label
className: 'text'
htmlFor: key
answerOption.text
|
[
{
"context": " if passwordChanged\n $scope.user.password = $scope.userData.password\n $scope.user.$update().then ->\n postU",
"end": 714,
"score": 0.9799529910087585,
"start": 690,
"tag": "PASSWORD",
"value": "$scope.userData.password"
},
{
"context": "l: $scope.user.email,\n password: $scope.userData.password\n }).then(postUpdate).catch ->\n ",
"end": 1035,
"score": 0.9431074857711792,
"start": 1018,
"tag": "PASSWORD",
"value": "userData.password"
}
] | frontend/src/controllers/private/profile.coffee | greysteil/evaluator | 1 | angular.module 'evaluator'
.controller 'ProfileController', ($scope, UserAuth, GUC_ID_REGEX, $state) ->
$scope.processing = false
$scope.user = UserAuth.user
$scope.userData = {}
$scope.loading = true
$scope.user.reload().then ->
$scope.loading = false
$scope.update = ->
return if $scope.processing
$scope.processing = true
if $scope.user.student
match = GUC_ID_REGEX.exec $scope.user.guc_id
$scope.user.guc_prefix = match[1]
$scope.user.guc_suffix = match[2]
passwordChanged = $scope.userData.password? &&
$scope.userData.password.length > 2
if passwordChanged
$scope.user.password = $scope.userData.password
$scope.user.$update().then ->
postUpdate = ->
$scope.user = UserAuth.user if passwordChanged
$scope.processing = false
if passwordChanged
UserAuth.logout()
UserAuth.login({
email: $scope.user.email,
password: $scope.userData.password
}).then(postUpdate).catch ->
$state.go 'public.internal_error'
else
postUpdate()
.catch (response) ->
if response.status is 422
$scope.processing = false
$scope.error =
("#{key.split('_').join(' ').capitalize()} #{value}." for key, value of response.data)
.join ' '
else
$state.go '^.internal_error'
| 93824 | angular.module 'evaluator'
.controller 'ProfileController', ($scope, UserAuth, GUC_ID_REGEX, $state) ->
$scope.processing = false
$scope.user = UserAuth.user
$scope.userData = {}
$scope.loading = true
$scope.user.reload().then ->
$scope.loading = false
$scope.update = ->
return if $scope.processing
$scope.processing = true
if $scope.user.student
match = GUC_ID_REGEX.exec $scope.user.guc_id
$scope.user.guc_prefix = match[1]
$scope.user.guc_suffix = match[2]
passwordChanged = $scope.userData.password? &&
$scope.userData.password.length > 2
if passwordChanged
$scope.user.password = <PASSWORD>
$scope.user.$update().then ->
postUpdate = ->
$scope.user = UserAuth.user if passwordChanged
$scope.processing = false
if passwordChanged
UserAuth.logout()
UserAuth.login({
email: $scope.user.email,
password: $scope.<PASSWORD>
}).then(postUpdate).catch ->
$state.go 'public.internal_error'
else
postUpdate()
.catch (response) ->
if response.status is 422
$scope.processing = false
$scope.error =
("#{key.split('_').join(' ').capitalize()} #{value}." for key, value of response.data)
.join ' '
else
$state.go '^.internal_error'
| true | angular.module 'evaluator'
.controller 'ProfileController', ($scope, UserAuth, GUC_ID_REGEX, $state) ->
$scope.processing = false
$scope.user = UserAuth.user
$scope.userData = {}
$scope.loading = true
$scope.user.reload().then ->
$scope.loading = false
$scope.update = ->
return if $scope.processing
$scope.processing = true
if $scope.user.student
match = GUC_ID_REGEX.exec $scope.user.guc_id
$scope.user.guc_prefix = match[1]
$scope.user.guc_suffix = match[2]
passwordChanged = $scope.userData.password? &&
$scope.userData.password.length > 2
if passwordChanged
$scope.user.password = PI:PASSWORD:<PASSWORD>END_PI
$scope.user.$update().then ->
postUpdate = ->
$scope.user = UserAuth.user if passwordChanged
$scope.processing = false
if passwordChanged
UserAuth.logout()
UserAuth.login({
email: $scope.user.email,
password: $scope.PI:PASSWORD:<PASSWORD>END_PI
}).then(postUpdate).catch ->
$state.go 'public.internal_error'
else
postUpdate()
.catch (response) ->
if response.status is 422
$scope.processing = false
$scope.error =
("#{key.split('_').join(' ').capitalize()} #{value}." for key, value of response.data)
.join ' '
else
$state.go '^.internal_error'
|
[
{
"context": "iplayer coin-gathering arena.'\n }\n {\n name: 'Harrowland'\n difficulty: 2\n id: 'harrowland'\n image",
"end": 3034,
"score": 0.7411518096923828,
"start": 3024,
"tag": "NAME",
"value": "Harrowland"
},
{
"context": "eir friends!'\n }\n]\n\noldArenas = [\n {\n name: 'Criss-Cross'\n difficulty: 5\n id: 'criss-cross'\n imag",
"end": 3310,
"score": 0.9913116693496704,
"start": 3299,
"tag": "NAME",
"value": "Criss-Cross"
},
{
"context": "ents to reach the other side!'\n }\n {\n name: 'Greed'\n difficulty: 4\n id: 'greed'\n image: '/f",
"end": 3529,
"score": 0.972650408744812,
"start": 3524,
"tag": "NAME",
"value": "Greed"
},
{
"context": "w Wizards in a dungeon melee!'\n }\n {\n name: 'Gold Rush'\n difficulty: 3\n id: 'gold-rush'\n image:",
"end": 4261,
"score": 0.9595599174499512,
"start": 4252,
"tag": "NAME",
"value": "Gold Rush"
},
{
"context": "ting gold than your opponent!'\n }\n {\n name: 'Brawlwood'\n difficulty: 4\n id: 'brawlwood'\n image:",
"end": 4475,
"score": 0.9232041239738464,
"start": 4466,
"tag": "NAME",
"value": "Brawlwood"
}
] | app/views/ladder/MainLadderView.coffee | adamcsillag/codecombat | 1 | RootView = require 'views/core/RootView'
template = require 'templates/play/ladder_home'
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 MainLadderView extends RootView
id: 'main-ladder-view'
template: template
initialize: ->
@levelStatusMap = []
@levelPlayCountMap = []
@campaigns = campaigns
@sessions = @supermodel.loadCollection(new LevelSessionsCollection(), 'your_sessions', {cache: false}, 0).model
@listenToOnce @sessions, 'sync', @onSessionsLoaded
@getLevelPlayCounts()
onSessionsLoaded: (e) ->
for session in @sessions.models
@levelStatusMap[session.get('levelID')] = if session.get('state')?.complete then 'complete' else 'started'
@render()
getLevelPlayCounts: ->
success = (levelPlayCounts) =>
return if @destroyed
for level in levelPlayCounts
@levelPlayCountMap[level._id] = playtime: level.playtime, sessions: level.sessions
@render() if @supermodel.finished()
levelIDs = []
for campaign in campaigns
for level in campaign.levels
levelIDs.push level.id
levelPlayCountsRequest = @supermodel.addRequestResource 'play_counts', {
url: '/db/level/-/play_counts'
data: {ids: levelIDs}
method: 'POST'
success: success
}, 0
levelPlayCountsRequest.load()
heroArenas = [
{
name: 'Ace of Coders'
difficulty: 3
id: 'ace-of-coders'
image: '/file/db/level/55de80407a57948705777e89/Ace-of-Coders-banner.png'
description: 'Battle for control over the icy treasure chests as your gigantic warrior marshals his armies against his mirror-match nemesis.'
}
{
name: 'Zero Sum'
difficulty: 3
id: 'zero-sum'
image: '/file/db/level/550363b4ec31df9c691ab629/MAR26-Banner_Zero%20Sum.png'
description: 'Unleash your coding creativity in both gold gathering and battle tactics in this alpine mirror match between red sorcerer and blue sorcerer.'
}
{
name: 'Cavern Survival'
difficulty: 1
id: 'cavern-survival'
image: '/file/db/level/544437e0645c0c0000c3291d/OCT30-Cavern%20Survival.png'
description: 'Stay alive longer than your multiplayer opponent amidst hordes of ogres!'
}
{
name: 'Dueling Grounds'
difficulty: 1
id: 'dueling-grounds'
image: '/file/db/level/5442ba0e1e835500007eb1c7/OCT27-Dueling%20Grounds.png'
description: 'Battle head-to-head against another hero in this basic beginner combat arena.'
}
{
name: 'Multiplayer Treasure Grove'
difficulty: 2
id: 'multiplayer-treasure-grove'
image: '/file/db/level/5469643c37600b40e0e09c5b/OCT27-Multiplayer%20Treasure%20Grove.png'
description: 'Mix collection, flags, and combat in this multiplayer coin-gathering arena.'
}
{
name: 'Harrowland'
difficulty: 2
id: 'harrowland'
image: '/file/db/level/54b83c2629843994803c838e/OCT27-Harrowland.png'
description: 'Go head-to-head against another player in this dueling arena--but watch out for their friends!'
}
]
oldArenas = [
{
name: 'Criss-Cross'
difficulty: 5
id: 'criss-cross'
image: '/file/db/level/5391f3d519dc22b8082159b2/banner2.png'
description: 'Participate in a bidding war with opponents to reach the other side!'
}
{
name: 'Greed'
difficulty: 4
id: 'greed'
image: '/file/db/level/53558b5a9914f5a90d7ccddb/greed_banner.jpg'
description: 'Liked Dungeon Arena and Gold Rush? Put them together in this economic arena!'
}
{
name: 'Sky Span (Testing)'
difficulty: 3
id: 'sky-span'
image: '/file/db/level/53c80fce0ddbef000084c667/sky-Span-banner.jpg'
description: 'Preview version of an upgraded Dungeon Arena. Help us with hero balance before release!'
}
{
name: 'Dungeon Arena'
difficulty: 3
id: 'dungeon-arena'
image: '/file/db/level/53173f76c269d400000543c2/Level%20Banner%20Dungeon%20Arena.jpg'
description: 'Play head-to-head against fellow Wizards in a dungeon melee!'
}
{
name: 'Gold Rush'
difficulty: 3
id: 'gold-rush'
image: '/file/db/level/533353722a61b7ca6832840c/Gold-Rush.png'
description: 'Prove you are better at collecting gold than your opponent!'
}
{
name: 'Brawlwood'
difficulty: 4
id: 'brawlwood'
image: '/file/db/level/52d97ecd32362bc86e004e87/Level%20Banner%20Brawlwood.jpg'
description: 'Combat the armies of other Wizards in a strategic forest arena! (Fast computer required.)'
}
]
campaigns = [
{id: 'multiplayer', name: 'Multiplayer Arenas', description: '... in which you code head-to-head against other players.', levels: heroArenas}
#{id: 'old_multiplayer', name: '(Deprecated) Old Multiplayer Arenas', description: 'Relics of a more civilized age. No simulations are run for these older, hero-less multiplayer arenas.', levels: oldArenas}
]
| 138963 | RootView = require 'views/core/RootView'
template = require 'templates/play/ladder_home'
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 MainLadderView extends RootView
id: 'main-ladder-view'
template: template
initialize: ->
@levelStatusMap = []
@levelPlayCountMap = []
@campaigns = campaigns
@sessions = @supermodel.loadCollection(new LevelSessionsCollection(), 'your_sessions', {cache: false}, 0).model
@listenToOnce @sessions, 'sync', @onSessionsLoaded
@getLevelPlayCounts()
onSessionsLoaded: (e) ->
for session in @sessions.models
@levelStatusMap[session.get('levelID')] = if session.get('state')?.complete then 'complete' else 'started'
@render()
getLevelPlayCounts: ->
success = (levelPlayCounts) =>
return if @destroyed
for level in levelPlayCounts
@levelPlayCountMap[level._id] = playtime: level.playtime, sessions: level.sessions
@render() if @supermodel.finished()
levelIDs = []
for campaign in campaigns
for level in campaign.levels
levelIDs.push level.id
levelPlayCountsRequest = @supermodel.addRequestResource 'play_counts', {
url: '/db/level/-/play_counts'
data: {ids: levelIDs}
method: 'POST'
success: success
}, 0
levelPlayCountsRequest.load()
heroArenas = [
{
name: 'Ace of Coders'
difficulty: 3
id: 'ace-of-coders'
image: '/file/db/level/55de80407a57948705777e89/Ace-of-Coders-banner.png'
description: 'Battle for control over the icy treasure chests as your gigantic warrior marshals his armies against his mirror-match nemesis.'
}
{
name: 'Zero Sum'
difficulty: 3
id: 'zero-sum'
image: '/file/db/level/550363b4ec31df9c691ab629/MAR26-Banner_Zero%20Sum.png'
description: 'Unleash your coding creativity in both gold gathering and battle tactics in this alpine mirror match between red sorcerer and blue sorcerer.'
}
{
name: 'Cavern Survival'
difficulty: 1
id: 'cavern-survival'
image: '/file/db/level/544437e0645c0c0000c3291d/OCT30-Cavern%20Survival.png'
description: 'Stay alive longer than your multiplayer opponent amidst hordes of ogres!'
}
{
name: 'Dueling Grounds'
difficulty: 1
id: 'dueling-grounds'
image: '/file/db/level/5442ba0e1e835500007eb1c7/OCT27-Dueling%20Grounds.png'
description: 'Battle head-to-head against another hero in this basic beginner combat arena.'
}
{
name: 'Multiplayer Treasure Grove'
difficulty: 2
id: 'multiplayer-treasure-grove'
image: '/file/db/level/5469643c37600b40e0e09c5b/OCT27-Multiplayer%20Treasure%20Grove.png'
description: 'Mix collection, flags, and combat in this multiplayer coin-gathering arena.'
}
{
name: '<NAME>'
difficulty: 2
id: 'harrowland'
image: '/file/db/level/54b83c2629843994803c838e/OCT27-Harrowland.png'
description: 'Go head-to-head against another player in this dueling arena--but watch out for their friends!'
}
]
oldArenas = [
{
name: '<NAME>'
difficulty: 5
id: 'criss-cross'
image: '/file/db/level/5391f3d519dc22b8082159b2/banner2.png'
description: 'Participate in a bidding war with opponents to reach the other side!'
}
{
name: '<NAME>'
difficulty: 4
id: 'greed'
image: '/file/db/level/53558b5a9914f5a90d7ccddb/greed_banner.jpg'
description: 'Liked Dungeon Arena and Gold Rush? Put them together in this economic arena!'
}
{
name: 'Sky Span (Testing)'
difficulty: 3
id: 'sky-span'
image: '/file/db/level/53c80fce0ddbef000084c667/sky-Span-banner.jpg'
description: 'Preview version of an upgraded Dungeon Arena. Help us with hero balance before release!'
}
{
name: 'Dungeon Arena'
difficulty: 3
id: 'dungeon-arena'
image: '/file/db/level/53173f76c269d400000543c2/Level%20Banner%20Dungeon%20Arena.jpg'
description: 'Play head-to-head against fellow Wizards in a dungeon melee!'
}
{
name: '<NAME>'
difficulty: 3
id: 'gold-rush'
image: '/file/db/level/533353722a61b7ca6832840c/Gold-Rush.png'
description: 'Prove you are better at collecting gold than your opponent!'
}
{
name: '<NAME>'
difficulty: 4
id: 'brawlwood'
image: '/file/db/level/52d97ecd32362bc86e004e87/Level%20Banner%20Brawlwood.jpg'
description: 'Combat the armies of other Wizards in a strategic forest arena! (Fast computer required.)'
}
]
campaigns = [
{id: 'multiplayer', name: 'Multiplayer Arenas', description: '... in which you code head-to-head against other players.', levels: heroArenas}
#{id: 'old_multiplayer', name: '(Deprecated) Old Multiplayer Arenas', description: 'Relics of a more civilized age. No simulations are run for these older, hero-less multiplayer arenas.', levels: oldArenas}
]
| true | RootView = require 'views/core/RootView'
template = require 'templates/play/ladder_home'
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 MainLadderView extends RootView
id: 'main-ladder-view'
template: template
initialize: ->
@levelStatusMap = []
@levelPlayCountMap = []
@campaigns = campaigns
@sessions = @supermodel.loadCollection(new LevelSessionsCollection(), 'your_sessions', {cache: false}, 0).model
@listenToOnce @sessions, 'sync', @onSessionsLoaded
@getLevelPlayCounts()
onSessionsLoaded: (e) ->
for session in @sessions.models
@levelStatusMap[session.get('levelID')] = if session.get('state')?.complete then 'complete' else 'started'
@render()
getLevelPlayCounts: ->
success = (levelPlayCounts) =>
return if @destroyed
for level in levelPlayCounts
@levelPlayCountMap[level._id] = playtime: level.playtime, sessions: level.sessions
@render() if @supermodel.finished()
levelIDs = []
for campaign in campaigns
for level in campaign.levels
levelIDs.push level.id
levelPlayCountsRequest = @supermodel.addRequestResource 'play_counts', {
url: '/db/level/-/play_counts'
data: {ids: levelIDs}
method: 'POST'
success: success
}, 0
levelPlayCountsRequest.load()
heroArenas = [
{
name: 'Ace of Coders'
difficulty: 3
id: 'ace-of-coders'
image: '/file/db/level/55de80407a57948705777e89/Ace-of-Coders-banner.png'
description: 'Battle for control over the icy treasure chests as your gigantic warrior marshals his armies against his mirror-match nemesis.'
}
{
name: 'Zero Sum'
difficulty: 3
id: 'zero-sum'
image: '/file/db/level/550363b4ec31df9c691ab629/MAR26-Banner_Zero%20Sum.png'
description: 'Unleash your coding creativity in both gold gathering and battle tactics in this alpine mirror match between red sorcerer and blue sorcerer.'
}
{
name: 'Cavern Survival'
difficulty: 1
id: 'cavern-survival'
image: '/file/db/level/544437e0645c0c0000c3291d/OCT30-Cavern%20Survival.png'
description: 'Stay alive longer than your multiplayer opponent amidst hordes of ogres!'
}
{
name: 'Dueling Grounds'
difficulty: 1
id: 'dueling-grounds'
image: '/file/db/level/5442ba0e1e835500007eb1c7/OCT27-Dueling%20Grounds.png'
description: 'Battle head-to-head against another hero in this basic beginner combat arena.'
}
{
name: 'Multiplayer Treasure Grove'
difficulty: 2
id: 'multiplayer-treasure-grove'
image: '/file/db/level/5469643c37600b40e0e09c5b/OCT27-Multiplayer%20Treasure%20Grove.png'
description: 'Mix collection, flags, and combat in this multiplayer coin-gathering arena.'
}
{
name: 'PI:NAME:<NAME>END_PI'
difficulty: 2
id: 'harrowland'
image: '/file/db/level/54b83c2629843994803c838e/OCT27-Harrowland.png'
description: 'Go head-to-head against another player in this dueling arena--but watch out for their friends!'
}
]
oldArenas = [
{
name: 'PI:NAME:<NAME>END_PI'
difficulty: 5
id: 'criss-cross'
image: '/file/db/level/5391f3d519dc22b8082159b2/banner2.png'
description: 'Participate in a bidding war with opponents to reach the other side!'
}
{
name: 'PI:NAME:<NAME>END_PI'
difficulty: 4
id: 'greed'
image: '/file/db/level/53558b5a9914f5a90d7ccddb/greed_banner.jpg'
description: 'Liked Dungeon Arena and Gold Rush? Put them together in this economic arena!'
}
{
name: 'Sky Span (Testing)'
difficulty: 3
id: 'sky-span'
image: '/file/db/level/53c80fce0ddbef000084c667/sky-Span-banner.jpg'
description: 'Preview version of an upgraded Dungeon Arena. Help us with hero balance before release!'
}
{
name: 'Dungeon Arena'
difficulty: 3
id: 'dungeon-arena'
image: '/file/db/level/53173f76c269d400000543c2/Level%20Banner%20Dungeon%20Arena.jpg'
description: 'Play head-to-head against fellow Wizards in a dungeon melee!'
}
{
name: 'PI:NAME:<NAME>END_PI'
difficulty: 3
id: 'gold-rush'
image: '/file/db/level/533353722a61b7ca6832840c/Gold-Rush.png'
description: 'Prove you are better at collecting gold than your opponent!'
}
{
name: 'PI:NAME:<NAME>END_PI'
difficulty: 4
id: 'brawlwood'
image: '/file/db/level/52d97ecd32362bc86e004e87/Level%20Banner%20Brawlwood.jpg'
description: 'Combat the armies of other Wizards in a strategic forest arena! (Fast computer required.)'
}
]
campaigns = [
{id: 'multiplayer', name: 'Multiplayer Arenas', description: '... in which you code head-to-head against other players.', levels: heroArenas}
#{id: 'old_multiplayer', name: '(Deprecated) Old Multiplayer Arenas', description: 'Relics of a more civilized age. No simulations are run for these older, hero-less multiplayer arenas.', levels: oldArenas}
]
|
[
{
"context": "': \"\"\"\n {\n ${1}\n @author(Name <x@y.at>)\n @abstract(a short description)\n ",
"end": 6023,
"score": 0.9997918009757996,
"start": 6017,
"tag": "EMAIL",
"value": "x@y.at"
},
{
"context": "': \"\"\"\n {\n ${1}\n @author(Name <x@y.at>)\n @abstract(a short description)\n ",
"end": 6364,
"score": 0.9999181628227234,
"start": 6358,
"tag": "EMAIL",
"value": "x@y.at"
}
] | snippets/language-pascal.cson | eisenwinter/atom-language-pascal-hgb | 0 | '.source.pascal':
'array declaration (var)':
'prefix': 'arrayd'
'body': 'ARRAY[0..${1:size}] OF $0'
'array declaration (const)':
'prefix': 'arrayc'
'body': 'ARRAY[0..${1:size}] OF = ($0)'
'begin … end':
'prefix': 'begin'
'body': """
BEGIN
\t$0
END;
"""
'case … end':
'prefix': 'CASE'
'body': """
CASE ${1:true} OF
\t$0
END; (* /case *)
"""
'case … (with else)':
'prefix': 'casee'
'body': """
CASE ${1:true} OF
\t${2:value}: ${3:statement}
ELSE
$0
END;
"""
'class (no parts)':
'prefix': 'classd'
'body': """
T${1:ClassName} = CLASS(T${2:ancestor})
\t$0
END;
"""
'class (with Create/Destroy)':
'prefix': 'classc'
'body': """
T${1:ClassName} = CLASS(T${2:ancestor})
PRIVATE
\t$0
PROTECTED
\t
public
\tCONSTRUCTOR Create; override;
\tDESTRUCTOR Destroy; override;
PUBLISH
\t
END;
"""
'class full (commented)':
'prefix': 'classfc'
'body': """
T${1:ClassName} = CLASS(T${2:ancestor})
PRIVATE
\t{ private declarations }
\t$0
PROTECTED
\t{ protected declarations }
\t
PUBLIC
\t{ public declarations }
\t
PUBLISHED
\t{ published declarations }
\t
end;
"""
'class full (uncommented)':
'prefix': 'classfu'
'body': """
T${1:ClassName} = class(T${2:ancestor})
private
\t$0
protected
\t
public
\t
published
\t
end;
"""
'constructor descendant':
'prefix': 'CreateC'
'body': 'constructor Create(AOwner: TComponent); override;'
'constructor':
'prefix': 'constructorc'
'body': 'constructor Create(${1:params}); ${2:override;}'
'constructor … destructor':
'prefix': 'constructord'
'body': """
constructor Create(${1:params});
destructor Destroy; override;$0
"""
'destructor':
'prefix': 'destructor'
'body': 'destructor Destroy; override;$0'
'else … end':
'prefix': 'else'
'body': """
ELSE BEGIN
\t$0
END; (* /else *)
"""
'enum':
'prefix': 'enum'
'body': 'T${1:EnumName} = (${2:meOne}, $0);'
'for … begin end':
'prefix': 'forb'
'body': """
FOR ${1:i} := ${2:0} TO ${3:max} DO BEGIN
\t$0
END; (* /for *)
"""
'for in … end':
'prefix': 'forin'
'body': """
FOR ${1:MyElem} IN ${2:MyList} DO BEGIN
\t$0
END; (* /for *)
"""
'for downto … end':
'prefix': 'forr'
'body': """
FOR ${1:i} := ${2:max} DOWNTO ${3:0} DO BEGIN
\t$0
END; (* /for *)
"""
'for … (no begin end)':
'prefix': 'for'
'body': """
FOR ${1:i} := ${2:0} TO ${3:max} DO
\t$0
"""
'function … end':
'prefix': 'function'
'body': """
FUNCTION ${1:MyFunction}(${2:params}) : ${3:returns};
BEGIN
\t$0
END; (* /${1} *)
"""
'if … (no begin end)':
'prefix': 'if'
'body': """
IF ${1:True} THEN
\t$0
"""
'if … end':
'prefix': 'ifb'
'body': """
IF ${1:True} THEN BEGIN
\t$0
END; (* / if *)
"""
'if … else (no begin end)':
'prefix': 'ife'
'body': """
IF ${1:True} THEN
\t${2:then code here}
ELSE
\t${3:else code here}
"""
'if … else end':
'prefix': 'ifeb'
'body': """
IF ${1:True} THEN BEGIN
\t${2:then code here}
END (* /if *)
ELSE BEGIN
\t${3:else code here}
END; (* /else *)
"""
'if not Assigned … (no begin end)':
'prefix': 'ifnass'
'body': """
IF NOT Assigned(${1:variable}) THEN
\t${1:variable} := T${2:ClassName}.Create(${3:params});$0
"""
'if nil … (no begin end)':
'prefix': 'ifnil'
'body': """
IF ${1:variable} = NIL THEN
\t${1:variable} := T${2:ClassName}.Create(${3:params});$0
"""
'interface declaration':
'prefix': 'interface'
'body': """
I${1:InterfaceName}: INTERFACE(${2:ancestor})
\t${3:[GUID]}
\t$0
end;
"""
'procedure':
'prefix': 'procedure'
'body': """
PROCEDURE ${1:MyProcedure}(${2:params});
BEGIN
\t$0
END; (* /${1} *)
"""
'property getter':
'prefix': 'prop'
'body': 'PROPERTY ${1:name}: ${2:type} read ${3:getter} write ${4:setter};$0'
'property field':
'prefix': 'propf'
'body': 'PROPERTY ${1:name}: ${2:type} read F${1:name} write F${1:name};$0'
'property get set':
'prefix': 'propgs'
'body': 'PROPERTY ${1:name}: ${2:type} read Get${1:name} write Set${1:name};$0'
'property read only':
'prefix': 'propro'
'body': 'PROPERTY ${1:name}: ${2:type} read ${3:getter};$0'
'property read only field':
'prefix': 'proprof'
'body': 'PROPERTY ${1:name}: ${2:type} read F${1:name};$0'
'raise':
'prefix': 'raise'
'body': 'RAISE ${1:Exception}.Create(\'${2:Error Message}\');$0'
'region':
'prefix': 'region'
'body': """
{$REGION \'${1:MyRegion}\'}
\t$0
{$ENDREGION}'
"""
'repeat until':
'prefix': 'repeat'
'body': """
REPEAT
\t$0
UNTIL (${1:True});
"""
'set declaration':
'prefix': 'set'
'body': 'T${1:SetName = set of $0};'
'try object … finally':
'prefix': 'try'
'body': """
${1:variable} := ${2:TComponent}.Create(${3:params});
TRY
\t$0
FINALLY
\t${1:variable}
END; (* /try *)
"""
'try … finally':
'prefix': 'tryf'
'body': """
TRY
\t$0
FINALLY
\t$1
END; (* /try *)
"""
'try … except':
'prefix': 'trye'
'body': """
try
\t$0
except
\ton ${1:e}: ${2:Exception} do
end;
"""
'variable':
'prefix': 'VAR'
'body': '${1:variable}: ${2:type};$0'
'unit … implementation … end':
'prefix': 'unitb'
'body': """
{
${1}
@author(Name <x@y.at>)
@abstract(a short description)
@created(2017-03-06)
a large description
@lastmod(2017-03-06)
}
UNIT ${1:unit_name};
INTERFACE
IMPLEMENTATION
$0
END.
"""
'program … end':
'prefix': 'programb'
'body': """
{
${1}
@author(Name <x@y.at>)
@abstract(a short description)
@created(2017-03-06)
a large description
@lastmod(2017-03-06)
}
PROGRAM ${1:program_name};
$0
BEGIN
END.
"""
'while statement':
'prefix': 'whileb'
'body': """
WHILE ${1:statement} DO BEGIN
\t$0
END; (* /while *)
"""
'while not EOF':
'prefix': 'whileneof'
'body': """
${1:dataset}.First;
WHILE NOT ${1:dataset}.EOF DO BEGIN
\t$0
\t${1:dataset}.Next;
END;
"""
'while (no begin end)':
'prefix': 'while'
'body': """
WHILE ${1:statement} DO
\t$0;
"""
'pointer to record':
'prefix': 'ptrrec'
'body': """
${1:RecordName}Ptr = ^${1}
${1} = RECORD
\t$0;
END;
"""
'(pasdoc) function':
'prefix': 'docfunc'
'body': """
{
does something
@param(some parameter)
@returns(something)
}
"""
'(pasdoc) procedure':
'prefix': 'docproc'
'body': """
{
does something
@param(a parameter)
}
"""
'(pasdoc) record':
'prefix': 'docrec'
'body': """
{
record description
@member name explanation
@member next prolly a nil pointer
}
"""
| 129153 | '.source.pascal':
'array declaration (var)':
'prefix': 'arrayd'
'body': 'ARRAY[0..${1:size}] OF $0'
'array declaration (const)':
'prefix': 'arrayc'
'body': 'ARRAY[0..${1:size}] OF = ($0)'
'begin … end':
'prefix': 'begin'
'body': """
BEGIN
\t$0
END;
"""
'case … end':
'prefix': 'CASE'
'body': """
CASE ${1:true} OF
\t$0
END; (* /case *)
"""
'case … (with else)':
'prefix': 'casee'
'body': """
CASE ${1:true} OF
\t${2:value}: ${3:statement}
ELSE
$0
END;
"""
'class (no parts)':
'prefix': 'classd'
'body': """
T${1:ClassName} = CLASS(T${2:ancestor})
\t$0
END;
"""
'class (with Create/Destroy)':
'prefix': 'classc'
'body': """
T${1:ClassName} = CLASS(T${2:ancestor})
PRIVATE
\t$0
PROTECTED
\t
public
\tCONSTRUCTOR Create; override;
\tDESTRUCTOR Destroy; override;
PUBLISH
\t
END;
"""
'class full (commented)':
'prefix': 'classfc'
'body': """
T${1:ClassName} = CLASS(T${2:ancestor})
PRIVATE
\t{ private declarations }
\t$0
PROTECTED
\t{ protected declarations }
\t
PUBLIC
\t{ public declarations }
\t
PUBLISHED
\t{ published declarations }
\t
end;
"""
'class full (uncommented)':
'prefix': 'classfu'
'body': """
T${1:ClassName} = class(T${2:ancestor})
private
\t$0
protected
\t
public
\t
published
\t
end;
"""
'constructor descendant':
'prefix': 'CreateC'
'body': 'constructor Create(AOwner: TComponent); override;'
'constructor':
'prefix': 'constructorc'
'body': 'constructor Create(${1:params}); ${2:override;}'
'constructor … destructor':
'prefix': 'constructord'
'body': """
constructor Create(${1:params});
destructor Destroy; override;$0
"""
'destructor':
'prefix': 'destructor'
'body': 'destructor Destroy; override;$0'
'else … end':
'prefix': 'else'
'body': """
ELSE BEGIN
\t$0
END; (* /else *)
"""
'enum':
'prefix': 'enum'
'body': 'T${1:EnumName} = (${2:meOne}, $0);'
'for … begin end':
'prefix': 'forb'
'body': """
FOR ${1:i} := ${2:0} TO ${3:max} DO BEGIN
\t$0
END; (* /for *)
"""
'for in … end':
'prefix': 'forin'
'body': """
FOR ${1:MyElem} IN ${2:MyList} DO BEGIN
\t$0
END; (* /for *)
"""
'for downto … end':
'prefix': 'forr'
'body': """
FOR ${1:i} := ${2:max} DOWNTO ${3:0} DO BEGIN
\t$0
END; (* /for *)
"""
'for … (no begin end)':
'prefix': 'for'
'body': """
FOR ${1:i} := ${2:0} TO ${3:max} DO
\t$0
"""
'function … end':
'prefix': 'function'
'body': """
FUNCTION ${1:MyFunction}(${2:params}) : ${3:returns};
BEGIN
\t$0
END; (* /${1} *)
"""
'if … (no begin end)':
'prefix': 'if'
'body': """
IF ${1:True} THEN
\t$0
"""
'if … end':
'prefix': 'ifb'
'body': """
IF ${1:True} THEN BEGIN
\t$0
END; (* / if *)
"""
'if … else (no begin end)':
'prefix': 'ife'
'body': """
IF ${1:True} THEN
\t${2:then code here}
ELSE
\t${3:else code here}
"""
'if … else end':
'prefix': 'ifeb'
'body': """
IF ${1:True} THEN BEGIN
\t${2:then code here}
END (* /if *)
ELSE BEGIN
\t${3:else code here}
END; (* /else *)
"""
'if not Assigned … (no begin end)':
'prefix': 'ifnass'
'body': """
IF NOT Assigned(${1:variable}) THEN
\t${1:variable} := T${2:ClassName}.Create(${3:params});$0
"""
'if nil … (no begin end)':
'prefix': 'ifnil'
'body': """
IF ${1:variable} = NIL THEN
\t${1:variable} := T${2:ClassName}.Create(${3:params});$0
"""
'interface declaration':
'prefix': 'interface'
'body': """
I${1:InterfaceName}: INTERFACE(${2:ancestor})
\t${3:[GUID]}
\t$0
end;
"""
'procedure':
'prefix': 'procedure'
'body': """
PROCEDURE ${1:MyProcedure}(${2:params});
BEGIN
\t$0
END; (* /${1} *)
"""
'property getter':
'prefix': 'prop'
'body': 'PROPERTY ${1:name}: ${2:type} read ${3:getter} write ${4:setter};$0'
'property field':
'prefix': 'propf'
'body': 'PROPERTY ${1:name}: ${2:type} read F${1:name} write F${1:name};$0'
'property get set':
'prefix': 'propgs'
'body': 'PROPERTY ${1:name}: ${2:type} read Get${1:name} write Set${1:name};$0'
'property read only':
'prefix': 'propro'
'body': 'PROPERTY ${1:name}: ${2:type} read ${3:getter};$0'
'property read only field':
'prefix': 'proprof'
'body': 'PROPERTY ${1:name}: ${2:type} read F${1:name};$0'
'raise':
'prefix': 'raise'
'body': 'RAISE ${1:Exception}.Create(\'${2:Error Message}\');$0'
'region':
'prefix': 'region'
'body': """
{$REGION \'${1:MyRegion}\'}
\t$0
{$ENDREGION}'
"""
'repeat until':
'prefix': 'repeat'
'body': """
REPEAT
\t$0
UNTIL (${1:True});
"""
'set declaration':
'prefix': 'set'
'body': 'T${1:SetName = set of $0};'
'try object … finally':
'prefix': 'try'
'body': """
${1:variable} := ${2:TComponent}.Create(${3:params});
TRY
\t$0
FINALLY
\t${1:variable}
END; (* /try *)
"""
'try … finally':
'prefix': 'tryf'
'body': """
TRY
\t$0
FINALLY
\t$1
END; (* /try *)
"""
'try … except':
'prefix': 'trye'
'body': """
try
\t$0
except
\ton ${1:e}: ${2:Exception} do
end;
"""
'variable':
'prefix': 'VAR'
'body': '${1:variable}: ${2:type};$0'
'unit … implementation … end':
'prefix': 'unitb'
'body': """
{
${1}
@author(Name <<EMAIL>>)
@abstract(a short description)
@created(2017-03-06)
a large description
@lastmod(2017-03-06)
}
UNIT ${1:unit_name};
INTERFACE
IMPLEMENTATION
$0
END.
"""
'program … end':
'prefix': 'programb'
'body': """
{
${1}
@author(Name <<EMAIL>>)
@abstract(a short description)
@created(2017-03-06)
a large description
@lastmod(2017-03-06)
}
PROGRAM ${1:program_name};
$0
BEGIN
END.
"""
'while statement':
'prefix': 'whileb'
'body': """
WHILE ${1:statement} DO BEGIN
\t$0
END; (* /while *)
"""
'while not EOF':
'prefix': 'whileneof'
'body': """
${1:dataset}.First;
WHILE NOT ${1:dataset}.EOF DO BEGIN
\t$0
\t${1:dataset}.Next;
END;
"""
'while (no begin end)':
'prefix': 'while'
'body': """
WHILE ${1:statement} DO
\t$0;
"""
'pointer to record':
'prefix': 'ptrrec'
'body': """
${1:RecordName}Ptr = ^${1}
${1} = RECORD
\t$0;
END;
"""
'(pasdoc) function':
'prefix': 'docfunc'
'body': """
{
does something
@param(some parameter)
@returns(something)
}
"""
'(pasdoc) procedure':
'prefix': 'docproc'
'body': """
{
does something
@param(a parameter)
}
"""
'(pasdoc) record':
'prefix': 'docrec'
'body': """
{
record description
@member name explanation
@member next prolly a nil pointer
}
"""
| true | '.source.pascal':
'array declaration (var)':
'prefix': 'arrayd'
'body': 'ARRAY[0..${1:size}] OF $0'
'array declaration (const)':
'prefix': 'arrayc'
'body': 'ARRAY[0..${1:size}] OF = ($0)'
'begin … end':
'prefix': 'begin'
'body': """
BEGIN
\t$0
END;
"""
'case … end':
'prefix': 'CASE'
'body': """
CASE ${1:true} OF
\t$0
END; (* /case *)
"""
'case … (with else)':
'prefix': 'casee'
'body': """
CASE ${1:true} OF
\t${2:value}: ${3:statement}
ELSE
$0
END;
"""
'class (no parts)':
'prefix': 'classd'
'body': """
T${1:ClassName} = CLASS(T${2:ancestor})
\t$0
END;
"""
'class (with Create/Destroy)':
'prefix': 'classc'
'body': """
T${1:ClassName} = CLASS(T${2:ancestor})
PRIVATE
\t$0
PROTECTED
\t
public
\tCONSTRUCTOR Create; override;
\tDESTRUCTOR Destroy; override;
PUBLISH
\t
END;
"""
'class full (commented)':
'prefix': 'classfc'
'body': """
T${1:ClassName} = CLASS(T${2:ancestor})
PRIVATE
\t{ private declarations }
\t$0
PROTECTED
\t{ protected declarations }
\t
PUBLIC
\t{ public declarations }
\t
PUBLISHED
\t{ published declarations }
\t
end;
"""
'class full (uncommented)':
'prefix': 'classfu'
'body': """
T${1:ClassName} = class(T${2:ancestor})
private
\t$0
protected
\t
public
\t
published
\t
end;
"""
'constructor descendant':
'prefix': 'CreateC'
'body': 'constructor Create(AOwner: TComponent); override;'
'constructor':
'prefix': 'constructorc'
'body': 'constructor Create(${1:params}); ${2:override;}'
'constructor … destructor':
'prefix': 'constructord'
'body': """
constructor Create(${1:params});
destructor Destroy; override;$0
"""
'destructor':
'prefix': 'destructor'
'body': 'destructor Destroy; override;$0'
'else … end':
'prefix': 'else'
'body': """
ELSE BEGIN
\t$0
END; (* /else *)
"""
'enum':
'prefix': 'enum'
'body': 'T${1:EnumName} = (${2:meOne}, $0);'
'for … begin end':
'prefix': 'forb'
'body': """
FOR ${1:i} := ${2:0} TO ${3:max} DO BEGIN
\t$0
END; (* /for *)
"""
'for in … end':
'prefix': 'forin'
'body': """
FOR ${1:MyElem} IN ${2:MyList} DO BEGIN
\t$0
END; (* /for *)
"""
'for downto … end':
'prefix': 'forr'
'body': """
FOR ${1:i} := ${2:max} DOWNTO ${3:0} DO BEGIN
\t$0
END; (* /for *)
"""
'for … (no begin end)':
'prefix': 'for'
'body': """
FOR ${1:i} := ${2:0} TO ${3:max} DO
\t$0
"""
'function … end':
'prefix': 'function'
'body': """
FUNCTION ${1:MyFunction}(${2:params}) : ${3:returns};
BEGIN
\t$0
END; (* /${1} *)
"""
'if … (no begin end)':
'prefix': 'if'
'body': """
IF ${1:True} THEN
\t$0
"""
'if … end':
'prefix': 'ifb'
'body': """
IF ${1:True} THEN BEGIN
\t$0
END; (* / if *)
"""
'if … else (no begin end)':
'prefix': 'ife'
'body': """
IF ${1:True} THEN
\t${2:then code here}
ELSE
\t${3:else code here}
"""
'if … else end':
'prefix': 'ifeb'
'body': """
IF ${1:True} THEN BEGIN
\t${2:then code here}
END (* /if *)
ELSE BEGIN
\t${3:else code here}
END; (* /else *)
"""
'if not Assigned … (no begin end)':
'prefix': 'ifnass'
'body': """
IF NOT Assigned(${1:variable}) THEN
\t${1:variable} := T${2:ClassName}.Create(${3:params});$0
"""
'if nil … (no begin end)':
'prefix': 'ifnil'
'body': """
IF ${1:variable} = NIL THEN
\t${1:variable} := T${2:ClassName}.Create(${3:params});$0
"""
'interface declaration':
'prefix': 'interface'
'body': """
I${1:InterfaceName}: INTERFACE(${2:ancestor})
\t${3:[GUID]}
\t$0
end;
"""
'procedure':
'prefix': 'procedure'
'body': """
PROCEDURE ${1:MyProcedure}(${2:params});
BEGIN
\t$0
END; (* /${1} *)
"""
'property getter':
'prefix': 'prop'
'body': 'PROPERTY ${1:name}: ${2:type} read ${3:getter} write ${4:setter};$0'
'property field':
'prefix': 'propf'
'body': 'PROPERTY ${1:name}: ${2:type} read F${1:name} write F${1:name};$0'
'property get set':
'prefix': 'propgs'
'body': 'PROPERTY ${1:name}: ${2:type} read Get${1:name} write Set${1:name};$0'
'property read only':
'prefix': 'propro'
'body': 'PROPERTY ${1:name}: ${2:type} read ${3:getter};$0'
'property read only field':
'prefix': 'proprof'
'body': 'PROPERTY ${1:name}: ${2:type} read F${1:name};$0'
'raise':
'prefix': 'raise'
'body': 'RAISE ${1:Exception}.Create(\'${2:Error Message}\');$0'
'region':
'prefix': 'region'
'body': """
{$REGION \'${1:MyRegion}\'}
\t$0
{$ENDREGION}'
"""
'repeat until':
'prefix': 'repeat'
'body': """
REPEAT
\t$0
UNTIL (${1:True});
"""
'set declaration':
'prefix': 'set'
'body': 'T${1:SetName = set of $0};'
'try object … finally':
'prefix': 'try'
'body': """
${1:variable} := ${2:TComponent}.Create(${3:params});
TRY
\t$0
FINALLY
\t${1:variable}
END; (* /try *)
"""
'try … finally':
'prefix': 'tryf'
'body': """
TRY
\t$0
FINALLY
\t$1
END; (* /try *)
"""
'try … except':
'prefix': 'trye'
'body': """
try
\t$0
except
\ton ${1:e}: ${2:Exception} do
end;
"""
'variable':
'prefix': 'VAR'
'body': '${1:variable}: ${2:type};$0'
'unit … implementation … end':
'prefix': 'unitb'
'body': """
{
${1}
@author(Name <PI:EMAIL:<EMAIL>END_PI>)
@abstract(a short description)
@created(2017-03-06)
a large description
@lastmod(2017-03-06)
}
UNIT ${1:unit_name};
INTERFACE
IMPLEMENTATION
$0
END.
"""
'program … end':
'prefix': 'programb'
'body': """
{
${1}
@author(Name <PI:EMAIL:<EMAIL>END_PI>)
@abstract(a short description)
@created(2017-03-06)
a large description
@lastmod(2017-03-06)
}
PROGRAM ${1:program_name};
$0
BEGIN
END.
"""
'while statement':
'prefix': 'whileb'
'body': """
WHILE ${1:statement} DO BEGIN
\t$0
END; (* /while *)
"""
'while not EOF':
'prefix': 'whileneof'
'body': """
${1:dataset}.First;
WHILE NOT ${1:dataset}.EOF DO BEGIN
\t$0
\t${1:dataset}.Next;
END;
"""
'while (no begin end)':
'prefix': 'while'
'body': """
WHILE ${1:statement} DO
\t$0;
"""
'pointer to record':
'prefix': 'ptrrec'
'body': """
${1:RecordName}Ptr = ^${1}
${1} = RECORD
\t$0;
END;
"""
'(pasdoc) function':
'prefix': 'docfunc'
'body': """
{
does something
@param(some parameter)
@returns(something)
}
"""
'(pasdoc) procedure':
'prefix': 'docproc'
'body': """
{
does something
@param(a parameter)
}
"""
'(pasdoc) record':
'prefix': 'docrec'
'body': """
{
record description
@member name explanation
@member next prolly a nil pointer
}
"""
|
[
{
"context": "n. can disable with this\n # https://github.com/webpack/webpack/issues/4240\n node:\n Buffer: false",
"end": 5811,
"score": 0.9968959093093872,
"start": 5804,
"tag": "USERNAME",
"value": "webpack"
},
{
"context": "tches, (match) ->\n key = match.replace('process.env.', '')\n bundle = bundle.replace match, \"'#{",
"end": 7887,
"score": 0.5527758002281189,
"start": 7887,
"tag": "KEY",
"value": ""
}
] | Gulpfile.coffee | FreeRoamApp/free-roam | 14 | fs = require 'fs'
del = require 'del'
_defaults = require 'lodash/defaults'
_defaultsDeep = require 'lodash/defaultsDeep'
_map = require 'lodash/map'
_mapValues = require 'lodash/mapValues'
gulp = require 'gulp'
gutil = require 'gulp-util'
webpack = require 'webpack'
autoprefixer = require 'autoprefixer'
manifest = require 'gulp-manifest'
spawn = require('child_process').spawn
coffeelint = require 'gulp-coffeelint'
webpackStream = require 'webpack-stream'
gulpSequence = require 'gulp-sequence'
WebpackDevServer = require 'webpack-dev-server'
HandleCSSLoader = require 'webpack-handle-css-loader'
TerserPlugin = require 'terser-webpack-plugin'
MiniCssExtractPlugin = require 'mini-css-extract-plugin'
Visualizer = require('webpack-visualizer-plugin')
# BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
gcPub = require 'gulp-gcloud-publish'
gzip = require 'gulp-gzip'
sizereport = require 'gulp-sizereport'
argv = require('yargs').argv
SpeedMeasurePlugin = require 'speed-measure-webpack-plugin'
HardSourceWebpackPlugin = require 'hard-source-webpack-plugin'
smp = new SpeedMeasurePlugin();
config = require './src/config'
Language = require './src/lang'
paths = require './gulp_paths'
webpackBase =
mode: 'development'
module:
exprContextRegExp: /$^/
exprContextCritical: false
resolve:
extensions: ['.coffee', '.js', '.json']
output:
filename: 'bundle.js'
publicPath: "#{config.SCRIPTS_CDN_URL}/"
gulp.task 'dev', ['dev:webpack-server', 'watch:dev:server']
gulp.task 'dist', gulpSequence(
'dist:clean'
['dist:scripts', 'dist:static']
'dist:concat'
'dist:sw'
'dist:gc'
'dist:sizereport'
)
gulp.task 'dist:sw', gulpSequence(
'dist:sw:script'
'dist:sw:replace'
)
gulp.task 'watch', ->
gulp.watch paths.coffee, ['dev:server']
gulp.task 'watch:dev:server', ['dev:server'], ->
gulp.watch paths.coffee, ['dev:server']
gulp.task 'lint', ->
gulp.src paths.coffee
.pipe coffeelint()
.pipe coffeelint.reporter()
gulp.task 'dev:server', ['build:static:dev'], do ->
devServer = null
process.on 'exit', -> devServer?.kill()
->
devServer?.kill()
devServer = spawn 'coffee', ['bin/dev_server.coffee'], {stdio: 'inherit'}
devServer.on 'close', (code) ->
if code is 8
gulp.log 'Error detected, waiting for changes'
gulp.task 'dev:webpack-server', ->
entries = [
"webpack-dev-server/client?#{config.WEBPACK_DEV_URL}"
'webpack/hot/dev-server'
paths.root
]
handleLoader = new HandleCSSLoader {
minimize: false,
extract: false,
sourceMap: false,
cssModules: false
postcss: [
autoprefixer {
browsers: ['> 3% in US', 'last 2 firefox versions']
}
]
}
compiler = webpack _defaultsDeep {
devtool: 'inline-source-map'
entry: entries
output:
path: __dirname
publicPath: "#{config.WEBPACK_DEV_URL}/"
pathinfo: false # seems to improve perf
module:
rules: [
{test: /\.coffee$/, loader: 'coffee-loader'}
handleLoader.css()
handleLoader.styl()
]
plugins: [
new webpack.HotModuleReplacementPlugin()
# new webpack.IgnorePlugin /\.json$/, /lang/
# new HardSourceWebpackPlugin()
new webpack.DefinePlugin
'process.env': _mapValues process.env, (val) -> JSON.stringify val
]
}, webpackBase
webpackOptions =
publicPath: "#{config.WEBPACK_DEV_URL}/"
hot: true
headers: 'Access-Control-Allow-Origin': '*'
noInfo: true
disableHostCheck: true
if config.DEV_USE_HTTPS
console.log 'using https'
webpackOptions.https = true
webpackOptions.key = fs.readFileSync './bin/fr-dev.key'
webpackOptions.cert = fs.readFileSync './bin/fr-dev.crt'
new WebpackDevServer compiler, webpackOptions
.listen config.WEBPACK_DEV_PORT, (err) ->
if err
console.log err
else
console.log
event: 'webpack_server_start'
message: "Webpack listening on port #{config.WEBPACK_DEV_PORT}"
gulp.task 'build:static:dev', ->
gulp.src paths.static
.pipe gulp.dest paths.build
gulp.task 'dist:clean', (cb) ->
del paths.dist + '/*', cb
gulp.task 'dist:static', ['dist:clean'], ->
gulp.src paths.static
.pipe gulp.dest paths.dist
gulp.task 'dist:sw:script', ->
gulp.src paths.sw
.pipe webpackStream(_defaultsDeep({
mode: 'production'
optimization: {
minimizer: [
new TerserPlugin {
parallel: true
terserOptions:
mangle:
reserved: ['process']
}
]
}
module:
rules: [
{test: /\.coffee$/, loader: 'coffee-loader'}
]
output:
filename: 'service_worker.js'
plugins: []
resolve:
extensions: ['.coffee', '.js', '.json']
}, webpackBase), require('webpack'))
.pipe gulp.dest paths.dist
gulp.task 'dist:sw:replace', ->
stats = JSON.parse fs.readFileSync "#{__dirname}/#{paths.dist}/stats.json"
sw = fs.readFileSync "#{__dirname}/#{paths.dist}/service_worker.js", 'utf-8'
sw = sw.replace /\|HASH\|/g, stats.hash
fs.writeFileSync("#{__dirname}/#{paths.dist}/service_worker.js", sw, 'utf-8')
gulp.task 'dist:scripts', ['dist:clean'], ->
handleLoader = new HandleCSSLoader {
minimize: true,
extract: true,
sourceMap: false,
cssModules: false
postcss: [
autoprefixer {
browsers: ['> 3% in US', 'last 2 firefox versions']
}
]
}
_map config.LANGUAGES, (language) ->
fs.writeFileSync(
"#{__dirname}/#{paths.dist}/lang_#{language}.json"
Language.getJsonString language
)
scriptsConfig = _defaultsDeep {
mode: 'production'
# not sure which module is doing it, but the node buffer module is being
# pulled in. can disable with this
# https://github.com/webpack/webpack/issues/4240
node:
Buffer: false
# process: false
optimization: {
# minimize: false
minimizer: [
new TerserPlugin {
parallel: true
terserOptions:
# ecma: 6
ie8: false
mangle:
reserved: ['process']
}
]
}
plugins: [
new Visualizer()
# new BundleAnalyzerPlugin()
new webpack.IgnorePlugin /\.json$/, /lang/
new MiniCssExtractPlugin {
filename: 'bundle.css'
}
->
this.plugin 'done', (stats) ->
if stats.compilation.errors and stats.compilation.errors.length
console.log stats.compilation.errors
process.exit 1
]
# remark requires this (parse-entities -> character-entities)
# character-entities is 38kb and not really necessary. legacy is 1.64kb
resolve:
alias:
'character-entities': 'character-entities-legacy'
output:
# TODO: '[hash].bundle.js' if we have caching issues, or use appcache
filename: 'bundle.js'
chunkFilename: '[name]_bundle_[hash].js',
module:
rules: [
{test: /\.coffee$/, loader: 'coffee-loader'}
handleLoader.css()
handleLoader.styl()
]
}, webpackBase
gulp.src paths.root
.pipe webpackStream scriptsConfig, require('webpack'), (err, stats) ->
if err
gutil.log err
return
statsJson = JSON.stringify {hash: stats.toJson().hash, time: Date.now()}
fs.writeFileSync "#{__dirname}/#{paths.dist}/stats.json", statsJson
.pipe gulp.dest paths.dist
gulp.task 'dist:concat', ->
stats = JSON.parse fs.readFileSync "#{__dirname}/#{paths.dist}/stats.json"
fs.renameSync(
"#{__dirname}/#{paths.dist}/bundle.css"
"#{__dirname}/#{paths.dist}/bundle_#{stats.hash}.css"
)
bundle = fs.readFileSync "#{__dirname}/#{paths.dist}/bundle.js", 'utf-8'
bundle = bundle.replace /\|HASH\|/g, stats.hash
matches = bundle.match(/process\.env\.[a-zA-Z0-9_]+/g)
_map matches, (match) ->
key = match.replace('process.env.', '')
bundle = bundle.replace match, "'#{process.env[key]}'"
_map config.LANGUAGES, (language) ->
lang = fs.readFileSync(
"#{__dirname}/#{paths.dist}/lang_#{language}.json", 'utf-8'
)
fs.writeFileSync(
"#{__dirname}/#{paths.dist}/bundle_#{stats.hash}_#{language}.js"
lang + bundle
, 'utf-8')
gulp.task 'dist:gc', ->
gulp.src("#{__dirname}/#{paths.dist}/*bundle*")
.pipe gzip()
.pipe gcPub {
bucket: 'fdn.uno'
keyFilename: '../padlock/free-roam-google-cloud-storage-creds.json'
projectId: 'free-roam-app'
base: '/d/scripts'
public: true
transformDestination: (path) ->
return path
metadata:
cacheControl: 'max-age=315360000, no-transform, public'
}
gulp.task 'dist:manifest', ['dist:static', 'dist:scripts'], ->
gulp.src paths.manifest
.pipe manifest {
hash: true
timestamp: false
preferOnline: true
fallback: ['/ /offline.html']
}
.pipe gulp.dest paths.dist
gulp.task 'dist:sizereport', ->
gulp.src "#{__dirname}/#{paths.dist}/bundle*"
.pipe sizereport()
| 168101 | fs = require 'fs'
del = require 'del'
_defaults = require 'lodash/defaults'
_defaultsDeep = require 'lodash/defaultsDeep'
_map = require 'lodash/map'
_mapValues = require 'lodash/mapValues'
gulp = require 'gulp'
gutil = require 'gulp-util'
webpack = require 'webpack'
autoprefixer = require 'autoprefixer'
manifest = require 'gulp-manifest'
spawn = require('child_process').spawn
coffeelint = require 'gulp-coffeelint'
webpackStream = require 'webpack-stream'
gulpSequence = require 'gulp-sequence'
WebpackDevServer = require 'webpack-dev-server'
HandleCSSLoader = require 'webpack-handle-css-loader'
TerserPlugin = require 'terser-webpack-plugin'
MiniCssExtractPlugin = require 'mini-css-extract-plugin'
Visualizer = require('webpack-visualizer-plugin')
# BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
gcPub = require 'gulp-gcloud-publish'
gzip = require 'gulp-gzip'
sizereport = require 'gulp-sizereport'
argv = require('yargs').argv
SpeedMeasurePlugin = require 'speed-measure-webpack-plugin'
HardSourceWebpackPlugin = require 'hard-source-webpack-plugin'
smp = new SpeedMeasurePlugin();
config = require './src/config'
Language = require './src/lang'
paths = require './gulp_paths'
webpackBase =
mode: 'development'
module:
exprContextRegExp: /$^/
exprContextCritical: false
resolve:
extensions: ['.coffee', '.js', '.json']
output:
filename: 'bundle.js'
publicPath: "#{config.SCRIPTS_CDN_URL}/"
gulp.task 'dev', ['dev:webpack-server', 'watch:dev:server']
gulp.task 'dist', gulpSequence(
'dist:clean'
['dist:scripts', 'dist:static']
'dist:concat'
'dist:sw'
'dist:gc'
'dist:sizereport'
)
gulp.task 'dist:sw', gulpSequence(
'dist:sw:script'
'dist:sw:replace'
)
gulp.task 'watch', ->
gulp.watch paths.coffee, ['dev:server']
gulp.task 'watch:dev:server', ['dev:server'], ->
gulp.watch paths.coffee, ['dev:server']
gulp.task 'lint', ->
gulp.src paths.coffee
.pipe coffeelint()
.pipe coffeelint.reporter()
gulp.task 'dev:server', ['build:static:dev'], do ->
devServer = null
process.on 'exit', -> devServer?.kill()
->
devServer?.kill()
devServer = spawn 'coffee', ['bin/dev_server.coffee'], {stdio: 'inherit'}
devServer.on 'close', (code) ->
if code is 8
gulp.log 'Error detected, waiting for changes'
gulp.task 'dev:webpack-server', ->
entries = [
"webpack-dev-server/client?#{config.WEBPACK_DEV_URL}"
'webpack/hot/dev-server'
paths.root
]
handleLoader = new HandleCSSLoader {
minimize: false,
extract: false,
sourceMap: false,
cssModules: false
postcss: [
autoprefixer {
browsers: ['> 3% in US', 'last 2 firefox versions']
}
]
}
compiler = webpack _defaultsDeep {
devtool: 'inline-source-map'
entry: entries
output:
path: __dirname
publicPath: "#{config.WEBPACK_DEV_URL}/"
pathinfo: false # seems to improve perf
module:
rules: [
{test: /\.coffee$/, loader: 'coffee-loader'}
handleLoader.css()
handleLoader.styl()
]
plugins: [
new webpack.HotModuleReplacementPlugin()
# new webpack.IgnorePlugin /\.json$/, /lang/
# new HardSourceWebpackPlugin()
new webpack.DefinePlugin
'process.env': _mapValues process.env, (val) -> JSON.stringify val
]
}, webpackBase
webpackOptions =
publicPath: "#{config.WEBPACK_DEV_URL}/"
hot: true
headers: 'Access-Control-Allow-Origin': '*'
noInfo: true
disableHostCheck: true
if config.DEV_USE_HTTPS
console.log 'using https'
webpackOptions.https = true
webpackOptions.key = fs.readFileSync './bin/fr-dev.key'
webpackOptions.cert = fs.readFileSync './bin/fr-dev.crt'
new WebpackDevServer compiler, webpackOptions
.listen config.WEBPACK_DEV_PORT, (err) ->
if err
console.log err
else
console.log
event: 'webpack_server_start'
message: "Webpack listening on port #{config.WEBPACK_DEV_PORT}"
gulp.task 'build:static:dev', ->
gulp.src paths.static
.pipe gulp.dest paths.build
gulp.task 'dist:clean', (cb) ->
del paths.dist + '/*', cb
gulp.task 'dist:static', ['dist:clean'], ->
gulp.src paths.static
.pipe gulp.dest paths.dist
gulp.task 'dist:sw:script', ->
gulp.src paths.sw
.pipe webpackStream(_defaultsDeep({
mode: 'production'
optimization: {
minimizer: [
new TerserPlugin {
parallel: true
terserOptions:
mangle:
reserved: ['process']
}
]
}
module:
rules: [
{test: /\.coffee$/, loader: 'coffee-loader'}
]
output:
filename: 'service_worker.js'
plugins: []
resolve:
extensions: ['.coffee', '.js', '.json']
}, webpackBase), require('webpack'))
.pipe gulp.dest paths.dist
gulp.task 'dist:sw:replace', ->
stats = JSON.parse fs.readFileSync "#{__dirname}/#{paths.dist}/stats.json"
sw = fs.readFileSync "#{__dirname}/#{paths.dist}/service_worker.js", 'utf-8'
sw = sw.replace /\|HASH\|/g, stats.hash
fs.writeFileSync("#{__dirname}/#{paths.dist}/service_worker.js", sw, 'utf-8')
gulp.task 'dist:scripts', ['dist:clean'], ->
handleLoader = new HandleCSSLoader {
minimize: true,
extract: true,
sourceMap: false,
cssModules: false
postcss: [
autoprefixer {
browsers: ['> 3% in US', 'last 2 firefox versions']
}
]
}
_map config.LANGUAGES, (language) ->
fs.writeFileSync(
"#{__dirname}/#{paths.dist}/lang_#{language}.json"
Language.getJsonString language
)
scriptsConfig = _defaultsDeep {
mode: 'production'
# not sure which module is doing it, but the node buffer module is being
# pulled in. can disable with this
# https://github.com/webpack/webpack/issues/4240
node:
Buffer: false
# process: false
optimization: {
# minimize: false
minimizer: [
new TerserPlugin {
parallel: true
terserOptions:
# ecma: 6
ie8: false
mangle:
reserved: ['process']
}
]
}
plugins: [
new Visualizer()
# new BundleAnalyzerPlugin()
new webpack.IgnorePlugin /\.json$/, /lang/
new MiniCssExtractPlugin {
filename: 'bundle.css'
}
->
this.plugin 'done', (stats) ->
if stats.compilation.errors and stats.compilation.errors.length
console.log stats.compilation.errors
process.exit 1
]
# remark requires this (parse-entities -> character-entities)
# character-entities is 38kb and not really necessary. legacy is 1.64kb
resolve:
alias:
'character-entities': 'character-entities-legacy'
output:
# TODO: '[hash].bundle.js' if we have caching issues, or use appcache
filename: 'bundle.js'
chunkFilename: '[name]_bundle_[hash].js',
module:
rules: [
{test: /\.coffee$/, loader: 'coffee-loader'}
handleLoader.css()
handleLoader.styl()
]
}, webpackBase
gulp.src paths.root
.pipe webpackStream scriptsConfig, require('webpack'), (err, stats) ->
if err
gutil.log err
return
statsJson = JSON.stringify {hash: stats.toJson().hash, time: Date.now()}
fs.writeFileSync "#{__dirname}/#{paths.dist}/stats.json", statsJson
.pipe gulp.dest paths.dist
gulp.task 'dist:concat', ->
stats = JSON.parse fs.readFileSync "#{__dirname}/#{paths.dist}/stats.json"
fs.renameSync(
"#{__dirname}/#{paths.dist}/bundle.css"
"#{__dirname}/#{paths.dist}/bundle_#{stats.hash}.css"
)
bundle = fs.readFileSync "#{__dirname}/#{paths.dist}/bundle.js", 'utf-8'
bundle = bundle.replace /\|HASH\|/g, stats.hash
matches = bundle.match(/process\.env\.[a-zA-Z0-9_]+/g)
_map matches, (match) ->
key = match.replace('process<KEY>.env.', '')
bundle = bundle.replace match, "'#{process.env[key]}'"
_map config.LANGUAGES, (language) ->
lang = fs.readFileSync(
"#{__dirname}/#{paths.dist}/lang_#{language}.json", 'utf-8'
)
fs.writeFileSync(
"#{__dirname}/#{paths.dist}/bundle_#{stats.hash}_#{language}.js"
lang + bundle
, 'utf-8')
gulp.task 'dist:gc', ->
gulp.src("#{__dirname}/#{paths.dist}/*bundle*")
.pipe gzip()
.pipe gcPub {
bucket: 'fdn.uno'
keyFilename: '../padlock/free-roam-google-cloud-storage-creds.json'
projectId: 'free-roam-app'
base: '/d/scripts'
public: true
transformDestination: (path) ->
return path
metadata:
cacheControl: 'max-age=315360000, no-transform, public'
}
gulp.task 'dist:manifest', ['dist:static', 'dist:scripts'], ->
gulp.src paths.manifest
.pipe manifest {
hash: true
timestamp: false
preferOnline: true
fallback: ['/ /offline.html']
}
.pipe gulp.dest paths.dist
gulp.task 'dist:sizereport', ->
gulp.src "#{__dirname}/#{paths.dist}/bundle*"
.pipe sizereport()
| true | fs = require 'fs'
del = require 'del'
_defaults = require 'lodash/defaults'
_defaultsDeep = require 'lodash/defaultsDeep'
_map = require 'lodash/map'
_mapValues = require 'lodash/mapValues'
gulp = require 'gulp'
gutil = require 'gulp-util'
webpack = require 'webpack'
autoprefixer = require 'autoprefixer'
manifest = require 'gulp-manifest'
spawn = require('child_process').spawn
coffeelint = require 'gulp-coffeelint'
webpackStream = require 'webpack-stream'
gulpSequence = require 'gulp-sequence'
WebpackDevServer = require 'webpack-dev-server'
HandleCSSLoader = require 'webpack-handle-css-loader'
TerserPlugin = require 'terser-webpack-plugin'
MiniCssExtractPlugin = require 'mini-css-extract-plugin'
Visualizer = require('webpack-visualizer-plugin')
# BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
gcPub = require 'gulp-gcloud-publish'
gzip = require 'gulp-gzip'
sizereport = require 'gulp-sizereport'
argv = require('yargs').argv
SpeedMeasurePlugin = require 'speed-measure-webpack-plugin'
HardSourceWebpackPlugin = require 'hard-source-webpack-plugin'
smp = new SpeedMeasurePlugin();
config = require './src/config'
Language = require './src/lang'
paths = require './gulp_paths'
webpackBase =
mode: 'development'
module:
exprContextRegExp: /$^/
exprContextCritical: false
resolve:
extensions: ['.coffee', '.js', '.json']
output:
filename: 'bundle.js'
publicPath: "#{config.SCRIPTS_CDN_URL}/"
gulp.task 'dev', ['dev:webpack-server', 'watch:dev:server']
gulp.task 'dist', gulpSequence(
'dist:clean'
['dist:scripts', 'dist:static']
'dist:concat'
'dist:sw'
'dist:gc'
'dist:sizereport'
)
gulp.task 'dist:sw', gulpSequence(
'dist:sw:script'
'dist:sw:replace'
)
gulp.task 'watch', ->
gulp.watch paths.coffee, ['dev:server']
gulp.task 'watch:dev:server', ['dev:server'], ->
gulp.watch paths.coffee, ['dev:server']
gulp.task 'lint', ->
gulp.src paths.coffee
.pipe coffeelint()
.pipe coffeelint.reporter()
gulp.task 'dev:server', ['build:static:dev'], do ->
devServer = null
process.on 'exit', -> devServer?.kill()
->
devServer?.kill()
devServer = spawn 'coffee', ['bin/dev_server.coffee'], {stdio: 'inherit'}
devServer.on 'close', (code) ->
if code is 8
gulp.log 'Error detected, waiting for changes'
gulp.task 'dev:webpack-server', ->
entries = [
"webpack-dev-server/client?#{config.WEBPACK_DEV_URL}"
'webpack/hot/dev-server'
paths.root
]
handleLoader = new HandleCSSLoader {
minimize: false,
extract: false,
sourceMap: false,
cssModules: false
postcss: [
autoprefixer {
browsers: ['> 3% in US', 'last 2 firefox versions']
}
]
}
compiler = webpack _defaultsDeep {
devtool: 'inline-source-map'
entry: entries
output:
path: __dirname
publicPath: "#{config.WEBPACK_DEV_URL}/"
pathinfo: false # seems to improve perf
module:
rules: [
{test: /\.coffee$/, loader: 'coffee-loader'}
handleLoader.css()
handleLoader.styl()
]
plugins: [
new webpack.HotModuleReplacementPlugin()
# new webpack.IgnorePlugin /\.json$/, /lang/
# new HardSourceWebpackPlugin()
new webpack.DefinePlugin
'process.env': _mapValues process.env, (val) -> JSON.stringify val
]
}, webpackBase
webpackOptions =
publicPath: "#{config.WEBPACK_DEV_URL}/"
hot: true
headers: 'Access-Control-Allow-Origin': '*'
noInfo: true
disableHostCheck: true
if config.DEV_USE_HTTPS
console.log 'using https'
webpackOptions.https = true
webpackOptions.key = fs.readFileSync './bin/fr-dev.key'
webpackOptions.cert = fs.readFileSync './bin/fr-dev.crt'
new WebpackDevServer compiler, webpackOptions
.listen config.WEBPACK_DEV_PORT, (err) ->
if err
console.log err
else
console.log
event: 'webpack_server_start'
message: "Webpack listening on port #{config.WEBPACK_DEV_PORT}"
gulp.task 'build:static:dev', ->
gulp.src paths.static
.pipe gulp.dest paths.build
gulp.task 'dist:clean', (cb) ->
del paths.dist + '/*', cb
gulp.task 'dist:static', ['dist:clean'], ->
gulp.src paths.static
.pipe gulp.dest paths.dist
gulp.task 'dist:sw:script', ->
gulp.src paths.sw
.pipe webpackStream(_defaultsDeep({
mode: 'production'
optimization: {
minimizer: [
new TerserPlugin {
parallel: true
terserOptions:
mangle:
reserved: ['process']
}
]
}
module:
rules: [
{test: /\.coffee$/, loader: 'coffee-loader'}
]
output:
filename: 'service_worker.js'
plugins: []
resolve:
extensions: ['.coffee', '.js', '.json']
}, webpackBase), require('webpack'))
.pipe gulp.dest paths.dist
gulp.task 'dist:sw:replace', ->
stats = JSON.parse fs.readFileSync "#{__dirname}/#{paths.dist}/stats.json"
sw = fs.readFileSync "#{__dirname}/#{paths.dist}/service_worker.js", 'utf-8'
sw = sw.replace /\|HASH\|/g, stats.hash
fs.writeFileSync("#{__dirname}/#{paths.dist}/service_worker.js", sw, 'utf-8')
gulp.task 'dist:scripts', ['dist:clean'], ->
handleLoader = new HandleCSSLoader {
minimize: true,
extract: true,
sourceMap: false,
cssModules: false
postcss: [
autoprefixer {
browsers: ['> 3% in US', 'last 2 firefox versions']
}
]
}
_map config.LANGUAGES, (language) ->
fs.writeFileSync(
"#{__dirname}/#{paths.dist}/lang_#{language}.json"
Language.getJsonString language
)
scriptsConfig = _defaultsDeep {
mode: 'production'
# not sure which module is doing it, but the node buffer module is being
# pulled in. can disable with this
# https://github.com/webpack/webpack/issues/4240
node:
Buffer: false
# process: false
optimization: {
# minimize: false
minimizer: [
new TerserPlugin {
parallel: true
terserOptions:
# ecma: 6
ie8: false
mangle:
reserved: ['process']
}
]
}
plugins: [
new Visualizer()
# new BundleAnalyzerPlugin()
new webpack.IgnorePlugin /\.json$/, /lang/
new MiniCssExtractPlugin {
filename: 'bundle.css'
}
->
this.plugin 'done', (stats) ->
if stats.compilation.errors and stats.compilation.errors.length
console.log stats.compilation.errors
process.exit 1
]
# remark requires this (parse-entities -> character-entities)
# character-entities is 38kb and not really necessary. legacy is 1.64kb
resolve:
alias:
'character-entities': 'character-entities-legacy'
output:
# TODO: '[hash].bundle.js' if we have caching issues, or use appcache
filename: 'bundle.js'
chunkFilename: '[name]_bundle_[hash].js',
module:
rules: [
{test: /\.coffee$/, loader: 'coffee-loader'}
handleLoader.css()
handleLoader.styl()
]
}, webpackBase
gulp.src paths.root
.pipe webpackStream scriptsConfig, require('webpack'), (err, stats) ->
if err
gutil.log err
return
statsJson = JSON.stringify {hash: stats.toJson().hash, time: Date.now()}
fs.writeFileSync "#{__dirname}/#{paths.dist}/stats.json", statsJson
.pipe gulp.dest paths.dist
gulp.task 'dist:concat', ->
stats = JSON.parse fs.readFileSync "#{__dirname}/#{paths.dist}/stats.json"
fs.renameSync(
"#{__dirname}/#{paths.dist}/bundle.css"
"#{__dirname}/#{paths.dist}/bundle_#{stats.hash}.css"
)
bundle = fs.readFileSync "#{__dirname}/#{paths.dist}/bundle.js", 'utf-8'
bundle = bundle.replace /\|HASH\|/g, stats.hash
matches = bundle.match(/process\.env\.[a-zA-Z0-9_]+/g)
_map matches, (match) ->
key = match.replace('processPI:KEY:<KEY>END_PI.env.', '')
bundle = bundle.replace match, "'#{process.env[key]}'"
_map config.LANGUAGES, (language) ->
lang = fs.readFileSync(
"#{__dirname}/#{paths.dist}/lang_#{language}.json", 'utf-8'
)
fs.writeFileSync(
"#{__dirname}/#{paths.dist}/bundle_#{stats.hash}_#{language}.js"
lang + bundle
, 'utf-8')
gulp.task 'dist:gc', ->
gulp.src("#{__dirname}/#{paths.dist}/*bundle*")
.pipe gzip()
.pipe gcPub {
bucket: 'fdn.uno'
keyFilename: '../padlock/free-roam-google-cloud-storage-creds.json'
projectId: 'free-roam-app'
base: '/d/scripts'
public: true
transformDestination: (path) ->
return path
metadata:
cacheControl: 'max-age=315360000, no-transform, public'
}
gulp.task 'dist:manifest', ['dist:static', 'dist:scripts'], ->
gulp.src paths.manifest
.pipe manifest {
hash: true
timestamp: false
preferOnline: true
fallback: ['/ /offline.html']
}
.pipe gulp.dest paths.dist
gulp.task 'dist:sizereport', ->
gulp.src "#{__dirname}/#{paths.dist}/bundle*"
.pipe sizereport()
|
[
{
"context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public Li",
"end": 43,
"score": 0.9999159574508667,
"start": 29,
"tag": "EMAIL",
"value": "contact@ppy.sh"
}
] | resources/assets/coffee/_classes/fancy-graph.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 @FancyGraph
container: document.getElementsByClassName('js-fancy-graph')
constructor: ->
$(window).on 'throttled-resize', @resize
$(document).on 'turbolinks:load', @initialize
initialize: =>
return if !@container[0]?
@container[0]._chart ?= new FancyChart @container[0]
resize: =>
return if !@container[0]?
@container[0]._chart?.resize()
| 164591 | # 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 @FancyGraph
container: document.getElementsByClassName('js-fancy-graph')
constructor: ->
$(window).on 'throttled-resize', @resize
$(document).on 'turbolinks:load', @initialize
initialize: =>
return if !@container[0]?
@container[0]._chart ?= new FancyChart @container[0]
resize: =>
return if !@container[0]?
@container[0]._chart?.resize()
| 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 @FancyGraph
container: document.getElementsByClassName('js-fancy-graph')
constructor: ->
$(window).on 'throttled-resize', @resize
$(document).on 'turbolinks:load', @initialize
initialize: =>
return if !@container[0]?
@container[0]._chart ?= new FancyChart @container[0]
resize: =>
return if !@container[0]?
@container[0]._chart?.resize()
|
[
{
"context": "ut mostly focuses on helping allies.\n *\n * @name Cleric\n * @magical\n * @support\n * @hp 40+[level*12]+[",
"end": 172,
"score": 0.6327959299087524,
"start": 166,
"tag": "NAME",
"value": "Cleric"
}
] | src/character/classes/Cleric.coffee | sadbear-/IdleLands | 0 |
Class = require "./../base/Class"
`/**
* This class is a healing class. It has some powerful damaging spells, but mostly focuses on helping allies.
*
* @name Cleric
* @magical
* @support
* @hp 40+[level*12]+[con*5]
* @mp 150+[level*3]+[int*2]+[wis*4]
* @itemScore int*0.7 + wis*1.5 - str*0.4 - dex*0.4
* @statPerLevel {str} 2
* @statPerLevel {dex} 1
* @statPerLevel {con} 1
* @statPerLevel {int} 1
* @statPerLevel {wis} 5
* @statPerLevel {agi} 1
* @minDamage 15%
* @mpregen 5%
* @category Classes
* @package Player
*/`
class Cleric extends Class
baseHp: 40
baseHpPerLevel: 12
baseHpPerCon: 5
baseMp: 150
baseMpPerLevel: 3
baseMpPerInt: 2
baseMpPerWis: 4
baseConPerLevel: 2
baseDexPerLevel: 1
baseAgiPerLevel: 1
baseStrPerLevel: 2
baseIntPerLevel: 1
baseWisPerLevel: 5
itemScore: (player, item) ->
item.int*0.7 +
item.wis*1.5 -
item.str*0.4 -
item.dex*0.4
physicalAttackChance: -> -10
mpregen: (player) -> Math.floor(player.mp.maximum*0.05)
minDamage: (player) ->
player.calc.damage()*0.15
load: (player) ->
super player
module.exports = exports = Cleric
| 39705 |
Class = require "./../base/Class"
`/**
* This class is a healing class. It has some powerful damaging spells, but mostly focuses on helping allies.
*
* @name <NAME>
* @magical
* @support
* @hp 40+[level*12]+[con*5]
* @mp 150+[level*3]+[int*2]+[wis*4]
* @itemScore int*0.7 + wis*1.5 - str*0.4 - dex*0.4
* @statPerLevel {str} 2
* @statPerLevel {dex} 1
* @statPerLevel {con} 1
* @statPerLevel {int} 1
* @statPerLevel {wis} 5
* @statPerLevel {agi} 1
* @minDamage 15%
* @mpregen 5%
* @category Classes
* @package Player
*/`
class Cleric extends Class
baseHp: 40
baseHpPerLevel: 12
baseHpPerCon: 5
baseMp: 150
baseMpPerLevel: 3
baseMpPerInt: 2
baseMpPerWis: 4
baseConPerLevel: 2
baseDexPerLevel: 1
baseAgiPerLevel: 1
baseStrPerLevel: 2
baseIntPerLevel: 1
baseWisPerLevel: 5
itemScore: (player, item) ->
item.int*0.7 +
item.wis*1.5 -
item.str*0.4 -
item.dex*0.4
physicalAttackChance: -> -10
mpregen: (player) -> Math.floor(player.mp.maximum*0.05)
minDamage: (player) ->
player.calc.damage()*0.15
load: (player) ->
super player
module.exports = exports = Cleric
| true |
Class = require "./../base/Class"
`/**
* This class is a healing class. It has some powerful damaging spells, but mostly focuses on helping allies.
*
* @name PI:NAME:<NAME>END_PI
* @magical
* @support
* @hp 40+[level*12]+[con*5]
* @mp 150+[level*3]+[int*2]+[wis*4]
* @itemScore int*0.7 + wis*1.5 - str*0.4 - dex*0.4
* @statPerLevel {str} 2
* @statPerLevel {dex} 1
* @statPerLevel {con} 1
* @statPerLevel {int} 1
* @statPerLevel {wis} 5
* @statPerLevel {agi} 1
* @minDamage 15%
* @mpregen 5%
* @category Classes
* @package Player
*/`
class Cleric extends Class
baseHp: 40
baseHpPerLevel: 12
baseHpPerCon: 5
baseMp: 150
baseMpPerLevel: 3
baseMpPerInt: 2
baseMpPerWis: 4
baseConPerLevel: 2
baseDexPerLevel: 1
baseAgiPerLevel: 1
baseStrPerLevel: 2
baseIntPerLevel: 1
baseWisPerLevel: 5
itemScore: (player, item) ->
item.int*0.7 +
item.wis*1.5 -
item.str*0.4 -
item.dex*0.4
physicalAttackChance: -> -10
mpregen: (player) -> Math.floor(player.mp.maximum*0.05)
minDamage: (player) ->
player.calc.damage()*0.15
load: (player) ->
super player
module.exports = exports = Cleric
|
[
{
"context": "rty : 'value'\n auth:\n username : 'Afmrak'\n password : 'stubby'\n response :\n ",
"end": 399,
"score": 0.9980559349060059,
"start": 393,
"tag": "USERNAME",
"value": "Afmrak"
},
{
"context": " username : 'Afmrak'\n password : 'stubby'\n response :\n headers :\n pro",
"end": 429,
"score": 0.9987975358963013,
"start": 423,
"tag": "PASSWORD",
"value": "stubby"
}
] | spec/contract.spec.coffee | bbc/stubby4node | 0 | sut = null
assert = require 'assert'
describe 'contract', ->
data = null
beforeEach ->
sut = require('../lib/models/contract')
data =
request :
url : "something"
method : 'POST'
query :
first: 'value1'
second: 'value2'
post : 'form data'
headers :
property : 'value'
auth:
username : 'Afmrak'
password : 'stubby'
response :
headers :
property : 'value'
status : 204
body : 'success!'
latency: 5000
it 'should return no errors for valid data', ->
result = sut data
assert result is null
it 'should return no errors for an array of valid data', ->
data = [data, data]
result = sut data
assert result is null
it 'should return an array of errors when multiple problems are found', ->
expected = [[
"'response.status' must be integer-like."
],[
"'request.url' is required."
"'request.method' must be one of GET,PUT,POST,HEAD,PATCH,TRACE,DELETE,CONNECT,OPTIONS."
"'response.headers', if supplied, must be an object."
]]
data.response.status = "a string"
data2 =
request:
method: "INVALID"
response:
headers: []
results = sut [data, data2]
assert.deepEqual results, expected
it 'should return array of errors for an array with an invalid datum', ->
invalid = {}
data = [data, invalid]
result = sut data
assert result.length is 1
describe 'request', ->
it 'should return error when missing', ->
expected = ["'request' object is required."]
data.request = null
actual = sut data
assert.deepEqual actual, expected
data.request = undefined
actual = sut data
assert.deepEqual actual, expected
describe 'query', ->
it 'should have no errors when absent', ->
data.request.query = null
result = sut data
assert result is null
data.request.query = undefined
result = sut data
assert result is null
it 'cannot be an array', ->
expected = ["'request.query', if supplied, must be an object."]
data.request.query = ['one', 'two']
actual = sut data
assert.deepEqual actual, expected
it 'cannot be a string', ->
expected = ["'request.query', if supplied, must be an object."]
data.request.query = 'one'
actual = sut data
assert.deepEqual actual, expected
describe 'headers', ->
it 'should have no errors when absent', ->
data.request.headers = null
result = sut data
assert result is null
data.request.headers = undefined
result = sut data
assert result is null
it 'cannot be an array', ->
expected = ["'request.headers', if supplied, must be an object."]
data.request.headers = ['one', 'two']
actual = sut data
assert.deepEqual actual, expected
it 'cannot be a string', ->
expected = ["'request.headers', if supplied, must be an object."]
data.request.headers = 'one'
actual = sut data
assert.deepEqual actual, expected
describe 'url', ->
it 'should return error for a missing url', ->
expected = ["'request.url' is required."]
data.request.url = null
result = sut data
assert.deepEqual result, expected
data.request.url = undefined
result = sut data
assert.deepEqual result, expected
describe 'method', ->
it 'should accept an array of methods', ->
data.request.method = ['put', 'post', 'get']
result = sut data
assert result is null
it 'should accept lowercase methods', ->
data.request.method = 'put'
result = sut data
assert result is null
it 'should have no errors for a missing method (defaults to GET)', ->
data.request.method = null
result = sut data
assert result is null
data.request.method = undefined
result = sut data
assert result is null
it 'should return error if method isnt HTTP 1.1', ->
expected = ["'request.method' must be one of GET,PUT,POST,HEAD,PATCH,TRACE,DELETE,CONNECT,OPTIONS."]
data.request.method = 'QUEST'
result = sut data
assert.deepEqual result, expected
it 'should return no errors for a missing post field', ->
data.request.post = null
result = sut data
assert result is null
data.request.post = undefined
result = sut data
assert result is null
describe 'response', ->
it 'should be optional', ->
data.response = null
result = sut data
assert result is null
data.response = undefined
result = sut data
assert result is null
it 'should be acceptable as a string', ->
data.response = 'http://www.google.com'
result = sut data
assert result is null
it 'should be acceptable as an array', ->
data.response = [
status: 200
]
result = sut data
assert result is null
it 'should return errors if a response in the array is invalid', ->
expected = ["'response.status' must be < 600."]
data.response = [{
status: 200
},{
status: 800
}]
result = sut data
assert.deepEqual result, expected
describe 'headers', ->
it 'should return no errors when absent', ->
data.response.headers = null
result = sut data
assert result is null
data.response.headers = undefined
result = sut data
assert result is null
it 'cannot be an array', ->
expected = ["'response.headers', if supplied, must be an object."]
data.response.headers = ['one', 'two']
actual = sut data
assert.deepEqual actual, expected
it 'cannot be a string', ->
expected = ["'response.headers', if supplied, must be an object."]
data.response.headers = 'one'
actual = sut data
assert.deepEqual actual, expected
describe 'status', ->
it 'should return no erros when absent', ->
data.response.status = null
result = sut data
assert result is null
data.response.status = undefined
result = sut data
assert result is null
it 'should return no errors when it is a number', ->
data.response.status = 400
result = sut data
assert result is null
it 'should return no errors when it is a string of a number', ->
data.response.status = "400"
result = sut data
assert result is null
it 'cannot be a string that is not a number', ->
expected = ["'response.status' must be integer-like."]
data.response.status = "string"
actual = sut data
assert.deepEqual actual, expected
it 'cannot be an object', ->
expected = ["'response.status' must be integer-like."]
data.response.status = {'property':'value'}
actual = sut data
assert.deepEqual actual, expected
it 'should return erros when less than 100', ->
expected = ["'response.status' must be >= 100."]
data.response.status = 99
actual = sut data
assert.deepEqual actual, expected
it 'should return erros when greater than or equal to 500', ->
expected = ["'response.status' must be < 600."]
data.response.status = 666
actual = sut data
assert.deepEqual actual, expected
describe 'latency', ->
it 'should return no errors when it is a number', ->
data.response.latency = 4000
result = sut data
assert result is null
it 'should return no errors when it a string representation of a number', ->
data.response.latency = "4000"
result = sut data
assert result is null
it 'should return an error when a string cannot be parsed as a number', ->
expected = ["'response.latency' must be integer-like."]
data.response.latency = "fred"
actual = sut data
assert.deepEqual actual, expected
it 'should return no errors for an empty body', ->
delete data.response.body
result = sut data
assert result is null
data.response.body = undefined
result = sut data
assert result is null
| 57487 | sut = null
assert = require 'assert'
describe 'contract', ->
data = null
beforeEach ->
sut = require('../lib/models/contract')
data =
request :
url : "something"
method : 'POST'
query :
first: 'value1'
second: 'value2'
post : 'form data'
headers :
property : 'value'
auth:
username : 'Afmrak'
password : '<PASSWORD>'
response :
headers :
property : 'value'
status : 204
body : 'success!'
latency: 5000
it 'should return no errors for valid data', ->
result = sut data
assert result is null
it 'should return no errors for an array of valid data', ->
data = [data, data]
result = sut data
assert result is null
it 'should return an array of errors when multiple problems are found', ->
expected = [[
"'response.status' must be integer-like."
],[
"'request.url' is required."
"'request.method' must be one of GET,PUT,POST,HEAD,PATCH,TRACE,DELETE,CONNECT,OPTIONS."
"'response.headers', if supplied, must be an object."
]]
data.response.status = "a string"
data2 =
request:
method: "INVALID"
response:
headers: []
results = sut [data, data2]
assert.deepEqual results, expected
it 'should return array of errors for an array with an invalid datum', ->
invalid = {}
data = [data, invalid]
result = sut data
assert result.length is 1
describe 'request', ->
it 'should return error when missing', ->
expected = ["'request' object is required."]
data.request = null
actual = sut data
assert.deepEqual actual, expected
data.request = undefined
actual = sut data
assert.deepEqual actual, expected
describe 'query', ->
it 'should have no errors when absent', ->
data.request.query = null
result = sut data
assert result is null
data.request.query = undefined
result = sut data
assert result is null
it 'cannot be an array', ->
expected = ["'request.query', if supplied, must be an object."]
data.request.query = ['one', 'two']
actual = sut data
assert.deepEqual actual, expected
it 'cannot be a string', ->
expected = ["'request.query', if supplied, must be an object."]
data.request.query = 'one'
actual = sut data
assert.deepEqual actual, expected
describe 'headers', ->
it 'should have no errors when absent', ->
data.request.headers = null
result = sut data
assert result is null
data.request.headers = undefined
result = sut data
assert result is null
it 'cannot be an array', ->
expected = ["'request.headers', if supplied, must be an object."]
data.request.headers = ['one', 'two']
actual = sut data
assert.deepEqual actual, expected
it 'cannot be a string', ->
expected = ["'request.headers', if supplied, must be an object."]
data.request.headers = 'one'
actual = sut data
assert.deepEqual actual, expected
describe 'url', ->
it 'should return error for a missing url', ->
expected = ["'request.url' is required."]
data.request.url = null
result = sut data
assert.deepEqual result, expected
data.request.url = undefined
result = sut data
assert.deepEqual result, expected
describe 'method', ->
it 'should accept an array of methods', ->
data.request.method = ['put', 'post', 'get']
result = sut data
assert result is null
it 'should accept lowercase methods', ->
data.request.method = 'put'
result = sut data
assert result is null
it 'should have no errors for a missing method (defaults to GET)', ->
data.request.method = null
result = sut data
assert result is null
data.request.method = undefined
result = sut data
assert result is null
it 'should return error if method isnt HTTP 1.1', ->
expected = ["'request.method' must be one of GET,PUT,POST,HEAD,PATCH,TRACE,DELETE,CONNECT,OPTIONS."]
data.request.method = 'QUEST'
result = sut data
assert.deepEqual result, expected
it 'should return no errors for a missing post field', ->
data.request.post = null
result = sut data
assert result is null
data.request.post = undefined
result = sut data
assert result is null
describe 'response', ->
it 'should be optional', ->
data.response = null
result = sut data
assert result is null
data.response = undefined
result = sut data
assert result is null
it 'should be acceptable as a string', ->
data.response = 'http://www.google.com'
result = sut data
assert result is null
it 'should be acceptable as an array', ->
data.response = [
status: 200
]
result = sut data
assert result is null
it 'should return errors if a response in the array is invalid', ->
expected = ["'response.status' must be < 600."]
data.response = [{
status: 200
},{
status: 800
}]
result = sut data
assert.deepEqual result, expected
describe 'headers', ->
it 'should return no errors when absent', ->
data.response.headers = null
result = sut data
assert result is null
data.response.headers = undefined
result = sut data
assert result is null
it 'cannot be an array', ->
expected = ["'response.headers', if supplied, must be an object."]
data.response.headers = ['one', 'two']
actual = sut data
assert.deepEqual actual, expected
it 'cannot be a string', ->
expected = ["'response.headers', if supplied, must be an object."]
data.response.headers = 'one'
actual = sut data
assert.deepEqual actual, expected
describe 'status', ->
it 'should return no erros when absent', ->
data.response.status = null
result = sut data
assert result is null
data.response.status = undefined
result = sut data
assert result is null
it 'should return no errors when it is a number', ->
data.response.status = 400
result = sut data
assert result is null
it 'should return no errors when it is a string of a number', ->
data.response.status = "400"
result = sut data
assert result is null
it 'cannot be a string that is not a number', ->
expected = ["'response.status' must be integer-like."]
data.response.status = "string"
actual = sut data
assert.deepEqual actual, expected
it 'cannot be an object', ->
expected = ["'response.status' must be integer-like."]
data.response.status = {'property':'value'}
actual = sut data
assert.deepEqual actual, expected
it 'should return erros when less than 100', ->
expected = ["'response.status' must be >= 100."]
data.response.status = 99
actual = sut data
assert.deepEqual actual, expected
it 'should return erros when greater than or equal to 500', ->
expected = ["'response.status' must be < 600."]
data.response.status = 666
actual = sut data
assert.deepEqual actual, expected
describe 'latency', ->
it 'should return no errors when it is a number', ->
data.response.latency = 4000
result = sut data
assert result is null
it 'should return no errors when it a string representation of a number', ->
data.response.latency = "4000"
result = sut data
assert result is null
it 'should return an error when a string cannot be parsed as a number', ->
expected = ["'response.latency' must be integer-like."]
data.response.latency = "fred"
actual = sut data
assert.deepEqual actual, expected
it 'should return no errors for an empty body', ->
delete data.response.body
result = sut data
assert result is null
data.response.body = undefined
result = sut data
assert result is null
| true | sut = null
assert = require 'assert'
describe 'contract', ->
data = null
beforeEach ->
sut = require('../lib/models/contract')
data =
request :
url : "something"
method : 'POST'
query :
first: 'value1'
second: 'value2'
post : 'form data'
headers :
property : 'value'
auth:
username : 'Afmrak'
password : 'PI:PASSWORD:<PASSWORD>END_PI'
response :
headers :
property : 'value'
status : 204
body : 'success!'
latency: 5000
it 'should return no errors for valid data', ->
result = sut data
assert result is null
it 'should return no errors for an array of valid data', ->
data = [data, data]
result = sut data
assert result is null
it 'should return an array of errors when multiple problems are found', ->
expected = [[
"'response.status' must be integer-like."
],[
"'request.url' is required."
"'request.method' must be one of GET,PUT,POST,HEAD,PATCH,TRACE,DELETE,CONNECT,OPTIONS."
"'response.headers', if supplied, must be an object."
]]
data.response.status = "a string"
data2 =
request:
method: "INVALID"
response:
headers: []
results = sut [data, data2]
assert.deepEqual results, expected
it 'should return array of errors for an array with an invalid datum', ->
invalid = {}
data = [data, invalid]
result = sut data
assert result.length is 1
describe 'request', ->
it 'should return error when missing', ->
expected = ["'request' object is required."]
data.request = null
actual = sut data
assert.deepEqual actual, expected
data.request = undefined
actual = sut data
assert.deepEqual actual, expected
describe 'query', ->
it 'should have no errors when absent', ->
data.request.query = null
result = sut data
assert result is null
data.request.query = undefined
result = sut data
assert result is null
it 'cannot be an array', ->
expected = ["'request.query', if supplied, must be an object."]
data.request.query = ['one', 'two']
actual = sut data
assert.deepEqual actual, expected
it 'cannot be a string', ->
expected = ["'request.query', if supplied, must be an object."]
data.request.query = 'one'
actual = sut data
assert.deepEqual actual, expected
describe 'headers', ->
it 'should have no errors when absent', ->
data.request.headers = null
result = sut data
assert result is null
data.request.headers = undefined
result = sut data
assert result is null
it 'cannot be an array', ->
expected = ["'request.headers', if supplied, must be an object."]
data.request.headers = ['one', 'two']
actual = sut data
assert.deepEqual actual, expected
it 'cannot be a string', ->
expected = ["'request.headers', if supplied, must be an object."]
data.request.headers = 'one'
actual = sut data
assert.deepEqual actual, expected
describe 'url', ->
it 'should return error for a missing url', ->
expected = ["'request.url' is required."]
data.request.url = null
result = sut data
assert.deepEqual result, expected
data.request.url = undefined
result = sut data
assert.deepEqual result, expected
describe 'method', ->
it 'should accept an array of methods', ->
data.request.method = ['put', 'post', 'get']
result = sut data
assert result is null
it 'should accept lowercase methods', ->
data.request.method = 'put'
result = sut data
assert result is null
it 'should have no errors for a missing method (defaults to GET)', ->
data.request.method = null
result = sut data
assert result is null
data.request.method = undefined
result = sut data
assert result is null
it 'should return error if method isnt HTTP 1.1', ->
expected = ["'request.method' must be one of GET,PUT,POST,HEAD,PATCH,TRACE,DELETE,CONNECT,OPTIONS."]
data.request.method = 'QUEST'
result = sut data
assert.deepEqual result, expected
it 'should return no errors for a missing post field', ->
data.request.post = null
result = sut data
assert result is null
data.request.post = undefined
result = sut data
assert result is null
describe 'response', ->
it 'should be optional', ->
data.response = null
result = sut data
assert result is null
data.response = undefined
result = sut data
assert result is null
it 'should be acceptable as a string', ->
data.response = 'http://www.google.com'
result = sut data
assert result is null
it 'should be acceptable as an array', ->
data.response = [
status: 200
]
result = sut data
assert result is null
it 'should return errors if a response in the array is invalid', ->
expected = ["'response.status' must be < 600."]
data.response = [{
status: 200
},{
status: 800
}]
result = sut data
assert.deepEqual result, expected
describe 'headers', ->
it 'should return no errors when absent', ->
data.response.headers = null
result = sut data
assert result is null
data.response.headers = undefined
result = sut data
assert result is null
it 'cannot be an array', ->
expected = ["'response.headers', if supplied, must be an object."]
data.response.headers = ['one', 'two']
actual = sut data
assert.deepEqual actual, expected
it 'cannot be a string', ->
expected = ["'response.headers', if supplied, must be an object."]
data.response.headers = 'one'
actual = sut data
assert.deepEqual actual, expected
describe 'status', ->
it 'should return no erros when absent', ->
data.response.status = null
result = sut data
assert result is null
data.response.status = undefined
result = sut data
assert result is null
it 'should return no errors when it is a number', ->
data.response.status = 400
result = sut data
assert result is null
it 'should return no errors when it is a string of a number', ->
data.response.status = "400"
result = sut data
assert result is null
it 'cannot be a string that is not a number', ->
expected = ["'response.status' must be integer-like."]
data.response.status = "string"
actual = sut data
assert.deepEqual actual, expected
it 'cannot be an object', ->
expected = ["'response.status' must be integer-like."]
data.response.status = {'property':'value'}
actual = sut data
assert.deepEqual actual, expected
it 'should return erros when less than 100', ->
expected = ["'response.status' must be >= 100."]
data.response.status = 99
actual = sut data
assert.deepEqual actual, expected
it 'should return erros when greater than or equal to 500', ->
expected = ["'response.status' must be < 600."]
data.response.status = 666
actual = sut data
assert.deepEqual actual, expected
describe 'latency', ->
it 'should return no errors when it is a number', ->
data.response.latency = 4000
result = sut data
assert result is null
it 'should return no errors when it a string representation of a number', ->
data.response.latency = "4000"
result = sut data
assert result is null
it 'should return an error when a string cannot be parsed as a number', ->
expected = ["'response.latency' must be integer-like."]
data.response.latency = "fred"
actual = sut data
assert.deepEqual actual, expected
it 'should return no errors for an empty body', ->
delete data.response.body
result = sut data
assert result is null
data.response.body = undefined
result = sut data
assert result is null
|
[
{
"context": "r.show()\n )\n\n _pageOptions: (e) =>\n KEY = 'optionsView'\n\n row = $(e.target).parents('.page-listing')\n",
"end": 3666,
"score": 0.986200213432312,
"start": 3655,
"tag": "KEY",
"value": "optionsView"
},
{
"context": "end(ich.tpl_show_user({\n username: user.get('username')\n bio: user.get('bio')\n showFollow: sh",
"end": 4797,
"score": 0.996125340461731,
"start": 4789,
"tag": "USERNAME",
"value": "username"
},
{
"context": "er = userDB.get(uid)\n username = user.get('username')\n profileLink = $('<a>').text(username).a",
"end": 5809,
"score": 0.9989988207817078,
"start": 5801,
"tag": "USERNAME",
"value": "username"
},
{
"context": "er = userDB.get(uid)\n username = user.get('username')\n profileLink = $('<a>').text(username).a",
"end": 6337,
"score": 0.9990506768226624,
"start": 6329,
"tag": "USERNAME",
"value": "username"
}
] | jotleaf/static/js/views_home.coffee | reverie/jotleaf.com | 1 | # views_home.coffee is for TopViews other than those that are related just to authentication/accounts and the leaf-viewer
class IndexView extends BaseRegistration
@bodyClass: 'landing-page'
documentTitle: 'Welcome to Jotleaf'
render: =>
context = @commonContext()
content = ich.tpl_index(context)
@setElement(content)
@$findOne('.front-bg').show() #remove?
class HomeView extends TopView
documentTitle: 'Home'
@bodyClass: 'home'
initialize: ->
@makeMainWebsiteView('tpl_home')
@_newsfeed = new NewsFeed()
@_newsfeedView = @makeSubviewInContainer(NewsFeedView, '.news-feed',{ model: @_newsfeed})
@_newsfeed.subscribe()
@makeSubviewInContainer(SuggestedFollowsView, '.suggested-friends')
setTimeout(=>
@$findOne('input.title-input').focus()
, 0)
events: {
'submit form.new-page': '_newPage'
}
unbind: =>
@_newsfeed.unsubscribe()
# TODO: DRY with pagesview somehow: identical
_newPage: (e) =>
e.preventDefault()
form = @$findOne('form.new-page')
form.find('input').attr('disabled', 'disabled')
title = form.findOne('input[type=text]')
button = form.findOne('input[type=submit]')
error = @$findOne('div.new-page.error')
origVal = button.val()
error.hide()
button.val('Creating...')
data = {
title: form.findOne('input[type=text]').val()
}
create = API.xhrMethod('new-page', data)
create.done((response) =>
if response.success
mixpanel.track("Page created", {
"Quick page": false
})
button.val('Created!')
router.internalNavigate(response.data.get_absolute_url)
else if response.status_code == 403
# The user has been unexpectedly logged out
JL.AuthState.setUser(null)
@queueSuccessMessage("You have been logged out. Please login again.")
router._redirect('account/login/')
)
create.fail((err) =>
log "Creating page failed:", err
button.val(origVal)
form.find('input').attr('disabled', false)
error.show()
)
class PagesView extends TopView
documentTitle: 'Pages'
@bodyClass: 'pages'
initialize: ->
@makeMainWebsiteView('tpl_pages')
@makeSubviewInContainer(YourPages, '.page-list')
@makeSubviewInContainer(SuggestedFollowsView, '.suggested-friends')
setTimeout(=>
@$findOne('input.title-input').focus()
, 0)
events: {
'submit form.new-page': '_newPage'
'click .options-button': '_pageOptions'
}
_newPage: (e) =>
e.preventDefault()
form = @$findOne('form.new-page')
form.find('input').attr('disabled', 'disabled')
title = form.findOne('input[type=text]')
button = form.findOne('input[type=submit]')
error = @$findOne('div.new-page.error')
origVal = button.val()
error.hide()
button.val('Creating...')
data = {
title: form.findOne('input[type=text]').val()
}
create = API.xhrMethod('new-page', data)
create.done((response) =>
if response.success
mixpanel.track("Page created", {
"Quick page": false
})
button.val('Created!')
router.internalNavigate(response.data.get_absolute_url)
else if response.status_code == 403
# The user has been unexpectedly logged out
JL.AuthState.setUser(null)
@queueSuccessMessage("You have been logged out. Please login again.")
router._redirect('account/login/')
)
create.fail((err) =>
log "Creating page failed:", err
button.val(origVal)
form.find('input').attr('disabled', false)
error.show()
)
_pageOptions: (e) =>
KEY = 'optionsView'
row = $(e.target).parents('.page-listing')
assert row.length
assert row.data('pageid')
v = row.data(KEY)
if v
v.toggle()
else
v = new OptionsView(
pageId: row.data('pageid') # comes from HTML template
row: row # passed this so it can hide it when deleting
)
@addSubView(v)
v.render()
v.$el.insertAfter(row)
v.show()
row.data(KEY, v)
class ProfileView extends TopView
@bodyClass: 'profile-page'
documentTitle: ->
return "#{@options.username}'s Profile"
initialize: ->
# TODO: canonicalize URL
@makeMainWebsiteView('tpl_loading_msg')
u = Database.modelDB(User).fetchBy('username', @options.username)
u.fail(router.do404)
u.done(@_gotUser)
_gotUser: (user) =>
log "got user", user
@user = user
isYou = user.get('id') == JL.AuthState.getUserId()
if isYou
$('body').addClass('myprofile')
showFollow = not isYou
API.xhrMethod('get-follows', {user_id: user.id}).done(@_gotFollows)
@content.empty()
@content.append(ich.tpl_show_user({
username: user.get('username')
bio: user.get('bio')
showFollow: showFollow
}))
if showFollow
@_checkBoxBtn = makeFollowButton(@$findOne('.follow'), user)
@makeSubviewInContainer(ProfilePageListView, '.page-list-items',{user: user})
unbind: =>
log "unbinding", @
@_checkBoxBtn?.destroy()
_gotFollows: (models) =>
log "Got models", models
userDB = Database2.modelDB(User)
followDB = Database2.modelDB(Follow)
for u in models.user
userDB.addObject(u)
for f in models.follow
followDB.addObject(f)
friends = followDB.getCollection(@user.id)
friendIds = friends.pluck('target_id')
followers = followDB.search({target_id: @user.id})
followerIds = (f.attributes.user_id for f in followers)
# Render friends div
if friendIds.length
el = @$findOne('.friends')
el.text("Following:")
users = $('<div>')
len = friendIds.length
for uid, i in friendIds
user = userDB.get(uid)
username = user.get('username')
profileLink = $('<a>').text(username).attr('href', user.profileUrl())
users.append(profileLink)
if i + 1 < len
users.append(document.createTextNode(', '))
el.append(users).show()
# Render followers div
# TODO: DRY with above
if followerIds.length
el = @$findOne('.followers')
el.text("Followers:")
users = $('<div>')
len = followerIds.length
for uid, i in followerIds
user = userDB.get(uid)
username = user.get('username')
profileLink = $('<a>').text(username).attr('href', user.profileUrl())
profileLink.attr('title', user.get('bio'))
users.append(profileLink)
if i + 1 < len
users.append(document.createTextNode(', '))
el.append(users).show()
| 51791 | # views_home.coffee is for TopViews other than those that are related just to authentication/accounts and the leaf-viewer
class IndexView extends BaseRegistration
@bodyClass: 'landing-page'
documentTitle: 'Welcome to Jotleaf'
render: =>
context = @commonContext()
content = ich.tpl_index(context)
@setElement(content)
@$findOne('.front-bg').show() #remove?
class HomeView extends TopView
documentTitle: 'Home'
@bodyClass: 'home'
initialize: ->
@makeMainWebsiteView('tpl_home')
@_newsfeed = new NewsFeed()
@_newsfeedView = @makeSubviewInContainer(NewsFeedView, '.news-feed',{ model: @_newsfeed})
@_newsfeed.subscribe()
@makeSubviewInContainer(SuggestedFollowsView, '.suggested-friends')
setTimeout(=>
@$findOne('input.title-input').focus()
, 0)
events: {
'submit form.new-page': '_newPage'
}
unbind: =>
@_newsfeed.unsubscribe()
# TODO: DRY with pagesview somehow: identical
_newPage: (e) =>
e.preventDefault()
form = @$findOne('form.new-page')
form.find('input').attr('disabled', 'disabled')
title = form.findOne('input[type=text]')
button = form.findOne('input[type=submit]')
error = @$findOne('div.new-page.error')
origVal = button.val()
error.hide()
button.val('Creating...')
data = {
title: form.findOne('input[type=text]').val()
}
create = API.xhrMethod('new-page', data)
create.done((response) =>
if response.success
mixpanel.track("Page created", {
"Quick page": false
})
button.val('Created!')
router.internalNavigate(response.data.get_absolute_url)
else if response.status_code == 403
# The user has been unexpectedly logged out
JL.AuthState.setUser(null)
@queueSuccessMessage("You have been logged out. Please login again.")
router._redirect('account/login/')
)
create.fail((err) =>
log "Creating page failed:", err
button.val(origVal)
form.find('input').attr('disabled', false)
error.show()
)
class PagesView extends TopView
documentTitle: 'Pages'
@bodyClass: 'pages'
initialize: ->
@makeMainWebsiteView('tpl_pages')
@makeSubviewInContainer(YourPages, '.page-list')
@makeSubviewInContainer(SuggestedFollowsView, '.suggested-friends')
setTimeout(=>
@$findOne('input.title-input').focus()
, 0)
events: {
'submit form.new-page': '_newPage'
'click .options-button': '_pageOptions'
}
_newPage: (e) =>
e.preventDefault()
form = @$findOne('form.new-page')
form.find('input').attr('disabled', 'disabled')
title = form.findOne('input[type=text]')
button = form.findOne('input[type=submit]')
error = @$findOne('div.new-page.error')
origVal = button.val()
error.hide()
button.val('Creating...')
data = {
title: form.findOne('input[type=text]').val()
}
create = API.xhrMethod('new-page', data)
create.done((response) =>
if response.success
mixpanel.track("Page created", {
"Quick page": false
})
button.val('Created!')
router.internalNavigate(response.data.get_absolute_url)
else if response.status_code == 403
# The user has been unexpectedly logged out
JL.AuthState.setUser(null)
@queueSuccessMessage("You have been logged out. Please login again.")
router._redirect('account/login/')
)
create.fail((err) =>
log "Creating page failed:", err
button.val(origVal)
form.find('input').attr('disabled', false)
error.show()
)
_pageOptions: (e) =>
KEY = '<KEY>'
row = $(e.target).parents('.page-listing')
assert row.length
assert row.data('pageid')
v = row.data(KEY)
if v
v.toggle()
else
v = new OptionsView(
pageId: row.data('pageid') # comes from HTML template
row: row # passed this so it can hide it when deleting
)
@addSubView(v)
v.render()
v.$el.insertAfter(row)
v.show()
row.data(KEY, v)
class ProfileView extends TopView
@bodyClass: 'profile-page'
documentTitle: ->
return "#{@options.username}'s Profile"
initialize: ->
# TODO: canonicalize URL
@makeMainWebsiteView('tpl_loading_msg')
u = Database.modelDB(User).fetchBy('username', @options.username)
u.fail(router.do404)
u.done(@_gotUser)
_gotUser: (user) =>
log "got user", user
@user = user
isYou = user.get('id') == JL.AuthState.getUserId()
if isYou
$('body').addClass('myprofile')
showFollow = not isYou
API.xhrMethod('get-follows', {user_id: user.id}).done(@_gotFollows)
@content.empty()
@content.append(ich.tpl_show_user({
username: user.get('username')
bio: user.get('bio')
showFollow: showFollow
}))
if showFollow
@_checkBoxBtn = makeFollowButton(@$findOne('.follow'), user)
@makeSubviewInContainer(ProfilePageListView, '.page-list-items',{user: user})
unbind: =>
log "unbinding", @
@_checkBoxBtn?.destroy()
_gotFollows: (models) =>
log "Got models", models
userDB = Database2.modelDB(User)
followDB = Database2.modelDB(Follow)
for u in models.user
userDB.addObject(u)
for f in models.follow
followDB.addObject(f)
friends = followDB.getCollection(@user.id)
friendIds = friends.pluck('target_id')
followers = followDB.search({target_id: @user.id})
followerIds = (f.attributes.user_id for f in followers)
# Render friends div
if friendIds.length
el = @$findOne('.friends')
el.text("Following:")
users = $('<div>')
len = friendIds.length
for uid, i in friendIds
user = userDB.get(uid)
username = user.get('username')
profileLink = $('<a>').text(username).attr('href', user.profileUrl())
users.append(profileLink)
if i + 1 < len
users.append(document.createTextNode(', '))
el.append(users).show()
# Render followers div
# TODO: DRY with above
if followerIds.length
el = @$findOne('.followers')
el.text("Followers:")
users = $('<div>')
len = followerIds.length
for uid, i in followerIds
user = userDB.get(uid)
username = user.get('username')
profileLink = $('<a>').text(username).attr('href', user.profileUrl())
profileLink.attr('title', user.get('bio'))
users.append(profileLink)
if i + 1 < len
users.append(document.createTextNode(', '))
el.append(users).show()
| true | # views_home.coffee is for TopViews other than those that are related just to authentication/accounts and the leaf-viewer
class IndexView extends BaseRegistration
@bodyClass: 'landing-page'
documentTitle: 'Welcome to Jotleaf'
render: =>
context = @commonContext()
content = ich.tpl_index(context)
@setElement(content)
@$findOne('.front-bg').show() #remove?
class HomeView extends TopView
documentTitle: 'Home'
@bodyClass: 'home'
initialize: ->
@makeMainWebsiteView('tpl_home')
@_newsfeed = new NewsFeed()
@_newsfeedView = @makeSubviewInContainer(NewsFeedView, '.news-feed',{ model: @_newsfeed})
@_newsfeed.subscribe()
@makeSubviewInContainer(SuggestedFollowsView, '.suggested-friends')
setTimeout(=>
@$findOne('input.title-input').focus()
, 0)
events: {
'submit form.new-page': '_newPage'
}
unbind: =>
@_newsfeed.unsubscribe()
# TODO: DRY with pagesview somehow: identical
_newPage: (e) =>
e.preventDefault()
form = @$findOne('form.new-page')
form.find('input').attr('disabled', 'disabled')
title = form.findOne('input[type=text]')
button = form.findOne('input[type=submit]')
error = @$findOne('div.new-page.error')
origVal = button.val()
error.hide()
button.val('Creating...')
data = {
title: form.findOne('input[type=text]').val()
}
create = API.xhrMethod('new-page', data)
create.done((response) =>
if response.success
mixpanel.track("Page created", {
"Quick page": false
})
button.val('Created!')
router.internalNavigate(response.data.get_absolute_url)
else if response.status_code == 403
# The user has been unexpectedly logged out
JL.AuthState.setUser(null)
@queueSuccessMessage("You have been logged out. Please login again.")
router._redirect('account/login/')
)
create.fail((err) =>
log "Creating page failed:", err
button.val(origVal)
form.find('input').attr('disabled', false)
error.show()
)
class PagesView extends TopView
documentTitle: 'Pages'
@bodyClass: 'pages'
initialize: ->
@makeMainWebsiteView('tpl_pages')
@makeSubviewInContainer(YourPages, '.page-list')
@makeSubviewInContainer(SuggestedFollowsView, '.suggested-friends')
setTimeout(=>
@$findOne('input.title-input').focus()
, 0)
events: {
'submit form.new-page': '_newPage'
'click .options-button': '_pageOptions'
}
_newPage: (e) =>
e.preventDefault()
form = @$findOne('form.new-page')
form.find('input').attr('disabled', 'disabled')
title = form.findOne('input[type=text]')
button = form.findOne('input[type=submit]')
error = @$findOne('div.new-page.error')
origVal = button.val()
error.hide()
button.val('Creating...')
data = {
title: form.findOne('input[type=text]').val()
}
create = API.xhrMethod('new-page', data)
create.done((response) =>
if response.success
mixpanel.track("Page created", {
"Quick page": false
})
button.val('Created!')
router.internalNavigate(response.data.get_absolute_url)
else if response.status_code == 403
# The user has been unexpectedly logged out
JL.AuthState.setUser(null)
@queueSuccessMessage("You have been logged out. Please login again.")
router._redirect('account/login/')
)
create.fail((err) =>
log "Creating page failed:", err
button.val(origVal)
form.find('input').attr('disabled', false)
error.show()
)
_pageOptions: (e) =>
KEY = 'PI:KEY:<KEY>END_PI'
row = $(e.target).parents('.page-listing')
assert row.length
assert row.data('pageid')
v = row.data(KEY)
if v
v.toggle()
else
v = new OptionsView(
pageId: row.data('pageid') # comes from HTML template
row: row # passed this so it can hide it when deleting
)
@addSubView(v)
v.render()
v.$el.insertAfter(row)
v.show()
row.data(KEY, v)
class ProfileView extends TopView
@bodyClass: 'profile-page'
documentTitle: ->
return "#{@options.username}'s Profile"
initialize: ->
# TODO: canonicalize URL
@makeMainWebsiteView('tpl_loading_msg')
u = Database.modelDB(User).fetchBy('username', @options.username)
u.fail(router.do404)
u.done(@_gotUser)
_gotUser: (user) =>
log "got user", user
@user = user
isYou = user.get('id') == JL.AuthState.getUserId()
if isYou
$('body').addClass('myprofile')
showFollow = not isYou
API.xhrMethod('get-follows', {user_id: user.id}).done(@_gotFollows)
@content.empty()
@content.append(ich.tpl_show_user({
username: user.get('username')
bio: user.get('bio')
showFollow: showFollow
}))
if showFollow
@_checkBoxBtn = makeFollowButton(@$findOne('.follow'), user)
@makeSubviewInContainer(ProfilePageListView, '.page-list-items',{user: user})
unbind: =>
log "unbinding", @
@_checkBoxBtn?.destroy()
_gotFollows: (models) =>
log "Got models", models
userDB = Database2.modelDB(User)
followDB = Database2.modelDB(Follow)
for u in models.user
userDB.addObject(u)
for f in models.follow
followDB.addObject(f)
friends = followDB.getCollection(@user.id)
friendIds = friends.pluck('target_id')
followers = followDB.search({target_id: @user.id})
followerIds = (f.attributes.user_id for f in followers)
# Render friends div
if friendIds.length
el = @$findOne('.friends')
el.text("Following:")
users = $('<div>')
len = friendIds.length
for uid, i in friendIds
user = userDB.get(uid)
username = user.get('username')
profileLink = $('<a>').text(username).attr('href', user.profileUrl())
users.append(profileLink)
if i + 1 < len
users.append(document.createTextNode(', '))
el.append(users).show()
# Render followers div
# TODO: DRY with above
if followerIds.length
el = @$findOne('.followers')
el.text("Followers:")
users = $('<div>')
len = followerIds.length
for uid, i in followerIds
user = userDB.get(uid)
username = user.get('username')
profileLink = $('<a>').text(username).attr('href', user.profileUrl())
profileLink.attr('title', user.get('bio'))
users.append(profileLink)
if i + 1 < len
users.append(document.createTextNode(', '))
el.append(users).show()
|
[
{
"context": ")\n ok keypath.base is @obj\n equal keypath.key, 'foo.bar.baz'\n\n\n###\n# get(key)\n###\ntest 'get(key) with a simpl",
"end": 676,
"score": 0.9577027559280396,
"start": 665,
"tag": "KEY",
"value": "foo.bar.baz"
},
{
"context": ", 'newVal'\n equal oldVal, 'quxVal'\n equal key, 'foo.bar.baz.qux'\n\ntest \"observe(key, callback) with a deep keypat",
"end": 7261,
"score": 0.9968527555465698,
"start": 7246,
"tag": "KEY",
"value": "foo.bar.baz.qux"
},
{
"context": ", 'newVal'\n equal oldVal, 'quxVal'\n equal key, 'foo.bar.baz.qux'\n\ntest \"observe(key, callback) with a deep keypat",
"end": 7660,
"score": 0.9979162812232971,
"start": 7645,
"tag": "KEY",
"value": "foo.bar.baz.qux"
},
{
"context": ", 'newVal'\n equal oldVal, 'quxVal'\n equal key, 'foo.bar.baz.qux'\n\ntest \"observe(key, callback) with a deep keypat",
"end": 8079,
"score": 0.9985536932945251,
"start": 8064,
"tag": "KEY",
"value": "foo.bar.baz.qux"
},
{
"context": "undefined'\n equal oldVal, 'quxVal'\n equal key, 'foo.bar.baz.qux'\n\ntest \"observe(key, callback) with a deep keypat",
"end": 8446,
"score": 0.9978309869766235,
"start": 8431,
"tag": "KEY",
"value": "foo.bar.baz.qux"
},
{
"context": ", 'newVal'\n equal oldVal, 'quxVal'\n equal key, 'foo.bar.baz.qux'\n\ntest \"observe(key, callback) with a deep keypat",
"end": 8884,
"score": 0.9993419647216797,
"start": 8869,
"tag": "KEY",
"value": "foo.bar.baz.qux"
},
{
"context": "undefined'\n equal oldVal, 'quxVal'\n equal key, 'foo.bar.baz.qux'\n\n @obj.set 'foo.bar', bar\n\n equal callback.cal",
"end": 9284,
"score": 0.9993823766708374,
"start": 9269,
"tag": "KEY",
"value": "foo.bar.baz.qux"
},
{
"context": " equal typeof(oldVal), 'undefined'\n equal key, 'foo.bar.baz.qux'\n\ntest \"observe(key, callback) with a deep keypat",
"end": 9487,
"score": 0.9993820190429688,
"start": 9472,
"tag": "KEY",
"value": "foo.bar.baz.qux"
},
{
"context": "undefined'\n equal oldVal, 'quxVal'\n equal key, 'foo.bar.baz.qux'\n\ntest \"observe(key, callback) with a deep keypat",
"end": 9898,
"score": 0.9993438720703125,
"start": 9883,
"tag": "KEY",
"value": "foo.bar.baz.qux"
},
{
"context": ", 'newVal'\n equal oldVal, 'quxVal'\n equal key, 'foo.bar.baz.qux'\n\ntest \"observe(key, callback) called twice to at",
"end": 10367,
"score": 0.9983603358268738,
"start": 10352,
"tag": "KEY",
"value": "foo.bar.baz.qux"
},
{
"context": "l == oldBar, \"oldVal is not oldBar\"\n equal key, 'foo.bar.baz.foo.bar'\n###\n# observeAndFire(key, callback)\n###\ntest \"ob",
"end": 11272,
"score": 0.9928595423698425,
"start": 11253,
"tag": "KEY",
"value": "foo.bar.baz.foo.bar"
}
] | tests/batman/observable/observable_test.coffee | davidcornu/batman | 0 | getPropertyAccessor = ->
get: createSpy ->
set: createSpy()
unset: createSpy()
QUnit.module 'Batman.Observable',
setup: ->
@obj = Batman
foo: Batman
bar: Batman
baz: Batman
qux: 'quxVal'
@obj.foo.bar.baz.event('corge', @corgeEventSpy = createSpy())
@obj.accessor 'someProperty', (@objPropertyAccessor = getPropertyAccessor())
@obj.foo.accessor 'someProperty', (@fooPropertyAccessor = getPropertyAccessor())
###
# property(key)
###
test 'property(key) returns a keypath of this object with the given key', ->
keypath = @obj.property('foo.bar.baz')
ok keypath.base is @obj
equal keypath.key, 'foo.bar.baz'
###
# get(key)
###
test 'get(key) with a simple key returns the value of that property', ->
ok @obj.get('foo') is @obj.foo
test 'get(key) with a deep keypath returns the value of the property at the end of the keypath', ->
equal @obj.get('foo.bar.baz.qux'), 'quxVal'
test "get(key) with an unresolvable simple key returns undefined", ->
equal typeof(@obj.get('nothing')), 'undefined'
test "get(key) with an unresolvable keypath returns undefined", ->
equal typeof(@obj.get('foo.bar.nothing')), 'undefined'
test "get(key) with a simple key calls resolve() on the result if it is a Batman.Property and returns that instead", ->
@objPropertyAccessor.get.whichReturns('resolvedValue')
equal @obj.get('someProperty'), 'resolvedValue'
deepEqual @objPropertyAccessor.get.lastCallArguments, ['someProperty']
ok @objPropertyAccessor.get.lastCallContext is @obj
test "get(key) with a deep keypath uses the last property's accessor with the last base as the context", ->
@fooPropertyAccessor.get.whichReturns('resolvedValue')
equal @obj.get('foo.someProperty'), 'resolvedValue'
deepEqual @fooPropertyAccessor.get.lastCallArguments, ['someProperty']
ok @fooPropertyAccessor.get.lastCallContext is @obj.foo
test "get(key) is cached until one of its sources changes", ->
@obj.get('foo.someProperty')
equal @fooPropertyAccessor.get.callCount, 1
@obj.get('foo.someProperty')
equal @fooPropertyAccessor.get.callCount, 1
@obj.set('foo.someProperty', yes)
@obj.get('foo.someProperty')
equal @fooPropertyAccessor.get.callCount, 2
@obj.get('foo.someProperty')
equal @fooPropertyAccessor.get.callCount, 2
test "get(key) works with cacheable properties with more than one level of accessor indirection", ->
@obj.accessor 'indirectProperty', -> @get('foo.someProperty')
@obj.get('indirectProperty')
equal @fooPropertyAccessor.get.callCount, 1
@obj.get('indirectProperty')
equal @fooPropertyAccessor.get.callCount, 1
@obj.set('foo.someProperty', yes)
@obj.get('indirectProperty')
equal @fooPropertyAccessor.get.callCount, 2
@obj.get('indirectProperty')
equal @fooPropertyAccessor.get.callCount, 2
test "get(key) works with Batman.Property.withoutTracking", ->
callCount = 0
@obj.accessor 'withoutTrackingProperty', ->
callCount++
@get('foo')
Batman.Property.withoutTracking =>
@get('foo.bar')
true
@obj.get('withoutTrackingProperty')
equal callCount, 1
@obj.set('foo.bar', true)
@obj.get('withoutTrackingProperty')
equal callCount, 1
@obj.set('foo')
@obj.get('withoutTrackingProperty')
equal callCount, 2
###
# set(key)
###
test "set(key, val) with a simple key stores the value in the property", ->
equal @obj.set('foo', 'newVal'), 'newVal'
equal @obj.foo, 'newVal'
test "set(key, val) with a deep keypath stores the value in the property at the end of the keypath", ->
@obj.set 'foo.bar.baz.qux', 'newVal'
equal @obj.foo.bar.baz.qux, 'newVal'
test "set(key, val) with a simple key calls fire(key, val, oldValue)", ->
fooProperty = @obj.property('foo')
spyOn(fooProperty, 'fire')
foo = @obj.foo
@obj.observe 'foo', ->
@obj.set 'foo', 'newVal'
equal fooProperty.fire.lastCallArguments.length, 3
equal fooProperty.fire.lastCallArguments[0], 'newVal'
ok fooProperty.fire.lastCallArguments[1] is foo
test "set(key, val) with a simple key should use the existing value's assign() method if the value is a Batman.Property", ->
@obj.set 'someProperty', 'newVal'
deepEqual @objPropertyAccessor.set.lastCallArguments, ['someProperty', 'newVal']
ok @objPropertyAccessor.set.lastCallContext is @obj
test "set(key, val) with a deep keypath should use the existing value's assign() method if the value is a Batman.Property", ->
@obj.set 'foo.someProperty', 'newVal'
deepEqual @fooPropertyAccessor.set.lastCallArguments, ['someProperty', 'newVal']
ok @fooPropertyAccessor.set.lastCallContext is @obj.foo
###
# unset(key)
###
test "unset(key) deletes the referenced property and returns the removed value", ->
equal @obj.unset('foo.bar.baz.qux'), 'quxVal'
strictEqual @obj.foo.bar.baz.qux, undefined
test "unset(key) with a simple key calls fire(key, undefined, oldValue)", ->
fooProperty = @obj.property('foo')
spyOn(fooProperty, 'fire')
foo = @obj.foo
@obj.observe 'foo', ->
@obj.unset 'foo'
[newVal, oldVal] = fooProperty.fire.lastCallArguments
equal typeof(newVal), 'undefined'
ok oldVal is foo
test "unset(key) with a simple key should use the existing value's remove() method if the value is a Batman.Property", ->
someProperty = @objPropertyAccessor
@obj.unset 'someProperty'
equal someProperty, @objPropertyAccessor
equal @objPropertyAccessor.unset.called, true
ok @objPropertyAccessor.unset.lastCallContext is @obj
test "unset(key) with a deep keypath should use the existing value's remove() method if the value is a Batman.Property", ->
@obj.unset 'foo.someProperty'
equal @fooPropertyAccessor.unset.called, true
ok @fooPropertyAccessor.unset.lastCallContext is @obj.foo
test "unset(key) should remove the property instance if it has no observers", ->
property = @obj.property('foo')
@obj.unset 'foo'
notEqual @obj.property('foo'), property
test "unset(key) should not remove the property instance if it has observers", ->
property = @obj.property('foo')
@obj.observe 'foo', ->
@obj.unset 'foo'
equal @obj.property('foo'), property
###
# getOrSet(key, valueFunction)
###
test "getOrSet(key, valueFunction) does conditional assignment with the return value of the given function", ->
equal @obj.foo, @obj.getOrSet("foo", -> "bar")
equal @obj.foo, @obj.get("foo")
equal "bar", @obj.getOrSet("foo2", -> "bar")
equal "bar", @obj.get("foo2")
###
# observe(key, callback)
###
test "observe(key, callback) stores the callback such that it is called with (value, oldValue, key) when the value of the key changes", ->
callback = createSpy()
ok @obj.observe('foo', callback) is @obj
equal callback.called, false
foo = @obj.foo
@obj.set 'foo', 'newVal'
ok callback.called
[newValue, oldValue, key] = callback.lastCallArguments
equal newValue, 'newVal'
ok oldValue is foo
equal key, 'foo'
test "observe(key, callback) with a deep keypath will fire with the new value when the final key value is changed directly", ->
@obj.observe 'foo.bar.baz.qux', callback = createSpy()
@obj.foo.bar.baz.set 'qux', 'newVal'
ok callback.called
[newVal, oldVal, key] = callback.lastCallArguments
equal newVal, 'newVal'
equal oldVal, 'quxVal'
equal key, 'foo.bar.baz.qux'
test "observe(key, callback) with a deep keypath will fire with the new value when the final key value is changed via the same deep keypath", ->
@obj.observe 'foo.bar.baz.qux', callback = createSpy()
@obj.set 'foo.bar.baz.qux', 'newVal'
ok callback.called
[newVal, oldVal, key] = callback.lastCallArguments
equal newVal, 'newVal'
equal oldVal, 'quxVal'
equal key, 'foo.bar.baz.qux'
test "observe(key, callback) with a deep keypath will fire with the new value when the final key value is changed via an equivalent subset of that deep keypath", ->
@obj.observe 'foo.bar.baz.qux', callback = createSpy()
@obj.foo.set 'bar.baz.qux', 'newVal'
ok callback.called
[newVal, oldVal, key] = callback.lastCallArguments
equal newVal, 'newVal'
equal oldVal, 'quxVal'
equal key, 'foo.bar.baz.qux'
test "observe(key, callback) with a deep keypath will fire with undefined if the key segment chain is broken", ->
@obj.observe 'foo.bar.baz.qux', callback = createSpy()
@obj.set 'foo', 'newVal'
ok callback.called
[newVal, oldVal, key] = callback.lastCallArguments
equal typeof(newVal), 'undefined'
equal oldVal, 'quxVal'
equal key, 'foo.bar.baz.qux'
test "observe(key, callback) with a deep keypath will fire with the new value if an intermediary key is changed such that the keypath resolves to a new value", ->
@obj.observe 'foo.bar.baz.qux', callback = createSpy()
@obj.set 'foo',
bar:
baz:
qux: 'newVal'
ok callback.called
[newVal, oldVal, key] = callback.lastCallArguments
equal newVal, 'newVal'
equal oldVal, 'quxVal'
equal key, 'foo.bar.baz.qux'
test "observe(key, callback) with a deep keypath will fire with a previous value that has been removed and re-added", ->
@obj.observe 'foo.bar.baz.qux', callback = createSpy()
bar = @obj.foo.bar
@obj.unset 'foo.bar'
equal callback.callCount, 1
[newVal, oldVal, key] = callback.lastCallArguments
equal typeof(newVal), 'undefined'
equal oldVal, 'quxVal'
equal key, 'foo.bar.baz.qux'
@obj.set 'foo.bar', bar
equal callback.callCount, 2
[newVal, oldVal, key] = callback.lastCallArguments
equal newVal, 'quxVal'
equal typeof(oldVal), 'undefined'
equal key, 'foo.bar.baz.qux'
test "observe(key, callback) with a deep keypath will not fire if a previous portion of the path is modified", ->
@obj.observe 'foo.bar.baz.qux', callback = createSpy()
bar = @obj.foo.bar
@obj.unset 'foo.bar'
bar.unset 'baz'
equal callback.callCount, 1
[newVal, oldVal, key] = callback.lastCallArguments
equal typeof(newVal), 'undefined'
equal oldVal, 'quxVal'
equal key, 'foo.bar.baz.qux'
test "observe(key, callback) with a deep keypath will fire when a portion of a previously removed and re-added portion is modified", ->
@obj.observe 'foo.bar.baz.qux', callback = createSpy()
bar = @obj.foo.bar
@obj.unset 'foo.bar'
@obj.set 'foo.bar', bar
@obj.set 'foo.bar.baz.qux', 'newVal'
equal callback.callCount, 3
[newVal, oldVal, key] = callback.lastCallArguments
equal newVal, 'newVal'
equal oldVal, 'quxVal'
equal key, 'foo.bar.baz.qux'
test "observe(key, callback) called twice to attach two different observers on the same deep keypath will only fire those observers once each for any given change", ->
@obj.observe 'foo.bar.baz.qux', callback1 = createSpy()
@obj.observe 'foo.bar.baz.qux', callback2 = createSpy()
@obj.set 'foo.bar.baz.qux', 'newVal'
equal callback1.callCount, 1
equal callback2.callCount, 1
test "observe(key, callback) will only fire once and will not break when there's an object cycle", ->
@obj.foo.bar.baz.foo = @obj.foo
@obj.observe 'foo.bar.baz.foo.bar', callback = createSpy()
oldBar = @obj.foo.bar
newBar = Batman
baz: Batman
foo: Batman
bar: 'newVal'
@obj.foo.set 'bar', newBar
equal callback.callCount, 1
[newVal, oldVal, key] = callback.lastCallArguments
equal newVal, 'newVal'
ok oldVal == oldBar, "oldVal is not oldBar"
equal key, 'foo.bar.baz.foo.bar'
###
# observeAndFire(key, callback)
###
test "observeAndFire(key, callback) adds the callback and then calls it immediately", ->
callback = createSpy()
@obj.observeAndFire 'foo.bar.baz.qux', callback
deepEqual callback.lastCallArguments, ['quxVal', 'quxVal', 'foo.bar.baz.qux']
test "observeAndFire(key, callback) fires with the correct current value, even if a property source was changed after the dependent property was cached but while the dependent property was not being observed", ->
klass = class extends Batman.Object
@accessor 'foo', -> @get('bar')
obj = new klass
obj.set('bar', 1) # initialize source
obj.get('foo') # cache dependent
obj.set('bar', 2) # change source
obj.observeAndFire('foo', spy = createSpy())
equal spy.lastCallArguments[0], 2
###
# observeOnce(key, callback)
###
test "observeOnce(key, callback) adds the callback and removes it after the first fire", ->
callback = createSpy()
oldVal = @obj.get 'foo'
@obj.observeOnce 'foo', callback
@obj.set 'foo', 'batman'
@obj.set 'foo', 'gotham'
equal callback.callCount, 1
[newValue, oldValue, key] = callback.lastCallArguments
equal newValue, 'batman'
equal oldVal, oldValue
equal key, 'foo'
###
# forget(key [, callback])
###
test "forget(key, callback) for a simple key will remove the specified callback from that key's observers", ->
callback1 = createSpy()
callback2 = createSpy()
@obj.observe 'foo', callback1
@obj.observe 'foo', callback2
@obj.forget 'foo', callback2
@obj.set 'foo', 'newVal'
equal callback1.callCount, 1
equal callback2.callCount, 0
test "forget(key) for a simple key with no callback specified will forget all observers for that key, leaving observers of other keys untouched", ->
callback1 = createSpy()
callback2 = createSpy()
callback3 = createSpy()
@obj.observe 'foo', callback1
@obj.observe 'foo', callback2
@obj.observe 'someOtherKey', callback3
@obj.forget 'foo'
@obj.set 'foo', 'newVal'
equal callback1.callCount, 0
equal callback2.callCount, 0
@obj.set 'someOtherKey', 'someVal'
equal callback3.callCount, 1
test "forget() without any arguments removes all observers from all of this object's keys", ->
callback1 = createSpy()
callback2 = createSpy()
callback3 = createSpy()
@obj.observe 'foo', callback1
@obj.observe 'foo', callback2
@obj.observe 'someOtherKey', callback3
equal @obj.forget(), @obj, "forget returns object for chaining"
@obj.set 'foo', 'newVal'
equal callback1.callCount, 0
equal callback2.callCount, 0
@obj.set 'someOtherKey', 'someVal'
equal callback3.callCount, 0
test "forget(key) for a deep keypath does not remove any sources when there are still observers present on the keypath", ->
callback1 = createSpy()
callback2 = createSpy()
@obj.observe 'foo.bar.baz', callback1
@obj.observe 'foo.bar.baz', callback2
equal @obj.forget('foo.bar.baz', callback2), @obj, "forget returns object for chaining"
equal @obj.property('foo').handlers.length, 1
equal @obj.foo.property('bar').handlers.length, 1
equal @obj.foo.bar.property('baz').handlers.length, 1
equal @obj.property('foo.bar.baz').sources.length, 3
@obj.foo.bar.set 'baz', 'newBaz'
equal callback1.callCount, 1
@obj.foo.set 'bar', 'newBar'
equal callback1.callCount, 2
@obj.set 'foo', Batman(bar: Batman(baz: 'reconstructedBaz'))
equal callback1.callCount, 3
equal callback2.callCount, 0
| 13613 | getPropertyAccessor = ->
get: createSpy ->
set: createSpy()
unset: createSpy()
QUnit.module 'Batman.Observable',
setup: ->
@obj = Batman
foo: Batman
bar: Batman
baz: Batman
qux: 'quxVal'
@obj.foo.bar.baz.event('corge', @corgeEventSpy = createSpy())
@obj.accessor 'someProperty', (@objPropertyAccessor = getPropertyAccessor())
@obj.foo.accessor 'someProperty', (@fooPropertyAccessor = getPropertyAccessor())
###
# property(key)
###
test 'property(key) returns a keypath of this object with the given key', ->
keypath = @obj.property('foo.bar.baz')
ok keypath.base is @obj
equal keypath.key, '<KEY>'
###
# get(key)
###
test 'get(key) with a simple key returns the value of that property', ->
ok @obj.get('foo') is @obj.foo
test 'get(key) with a deep keypath returns the value of the property at the end of the keypath', ->
equal @obj.get('foo.bar.baz.qux'), 'quxVal'
test "get(key) with an unresolvable simple key returns undefined", ->
equal typeof(@obj.get('nothing')), 'undefined'
test "get(key) with an unresolvable keypath returns undefined", ->
equal typeof(@obj.get('foo.bar.nothing')), 'undefined'
test "get(key) with a simple key calls resolve() on the result if it is a Batman.Property and returns that instead", ->
@objPropertyAccessor.get.whichReturns('resolvedValue')
equal @obj.get('someProperty'), 'resolvedValue'
deepEqual @objPropertyAccessor.get.lastCallArguments, ['someProperty']
ok @objPropertyAccessor.get.lastCallContext is @obj
test "get(key) with a deep keypath uses the last property's accessor with the last base as the context", ->
@fooPropertyAccessor.get.whichReturns('resolvedValue')
equal @obj.get('foo.someProperty'), 'resolvedValue'
deepEqual @fooPropertyAccessor.get.lastCallArguments, ['someProperty']
ok @fooPropertyAccessor.get.lastCallContext is @obj.foo
test "get(key) is cached until one of its sources changes", ->
@obj.get('foo.someProperty')
equal @fooPropertyAccessor.get.callCount, 1
@obj.get('foo.someProperty')
equal @fooPropertyAccessor.get.callCount, 1
@obj.set('foo.someProperty', yes)
@obj.get('foo.someProperty')
equal @fooPropertyAccessor.get.callCount, 2
@obj.get('foo.someProperty')
equal @fooPropertyAccessor.get.callCount, 2
test "get(key) works with cacheable properties with more than one level of accessor indirection", ->
@obj.accessor 'indirectProperty', -> @get('foo.someProperty')
@obj.get('indirectProperty')
equal @fooPropertyAccessor.get.callCount, 1
@obj.get('indirectProperty')
equal @fooPropertyAccessor.get.callCount, 1
@obj.set('foo.someProperty', yes)
@obj.get('indirectProperty')
equal @fooPropertyAccessor.get.callCount, 2
@obj.get('indirectProperty')
equal @fooPropertyAccessor.get.callCount, 2
test "get(key) works with Batman.Property.withoutTracking", ->
callCount = 0
@obj.accessor 'withoutTrackingProperty', ->
callCount++
@get('foo')
Batman.Property.withoutTracking =>
@get('foo.bar')
true
@obj.get('withoutTrackingProperty')
equal callCount, 1
@obj.set('foo.bar', true)
@obj.get('withoutTrackingProperty')
equal callCount, 1
@obj.set('foo')
@obj.get('withoutTrackingProperty')
equal callCount, 2
###
# set(key)
###
test "set(key, val) with a simple key stores the value in the property", ->
equal @obj.set('foo', 'newVal'), 'newVal'
equal @obj.foo, 'newVal'
test "set(key, val) with a deep keypath stores the value in the property at the end of the keypath", ->
@obj.set 'foo.bar.baz.qux', 'newVal'
equal @obj.foo.bar.baz.qux, 'newVal'
test "set(key, val) with a simple key calls fire(key, val, oldValue)", ->
fooProperty = @obj.property('foo')
spyOn(fooProperty, 'fire')
foo = @obj.foo
@obj.observe 'foo', ->
@obj.set 'foo', 'newVal'
equal fooProperty.fire.lastCallArguments.length, 3
equal fooProperty.fire.lastCallArguments[0], 'newVal'
ok fooProperty.fire.lastCallArguments[1] is foo
test "set(key, val) with a simple key should use the existing value's assign() method if the value is a Batman.Property", ->
@obj.set 'someProperty', 'newVal'
deepEqual @objPropertyAccessor.set.lastCallArguments, ['someProperty', 'newVal']
ok @objPropertyAccessor.set.lastCallContext is @obj
test "set(key, val) with a deep keypath should use the existing value's assign() method if the value is a Batman.Property", ->
@obj.set 'foo.someProperty', 'newVal'
deepEqual @fooPropertyAccessor.set.lastCallArguments, ['someProperty', 'newVal']
ok @fooPropertyAccessor.set.lastCallContext is @obj.foo
###
# unset(key)
###
test "unset(key) deletes the referenced property and returns the removed value", ->
equal @obj.unset('foo.bar.baz.qux'), 'quxVal'
strictEqual @obj.foo.bar.baz.qux, undefined
test "unset(key) with a simple key calls fire(key, undefined, oldValue)", ->
fooProperty = @obj.property('foo')
spyOn(fooProperty, 'fire')
foo = @obj.foo
@obj.observe 'foo', ->
@obj.unset 'foo'
[newVal, oldVal] = fooProperty.fire.lastCallArguments
equal typeof(newVal), 'undefined'
ok oldVal is foo
test "unset(key) with a simple key should use the existing value's remove() method if the value is a Batman.Property", ->
someProperty = @objPropertyAccessor
@obj.unset 'someProperty'
equal someProperty, @objPropertyAccessor
equal @objPropertyAccessor.unset.called, true
ok @objPropertyAccessor.unset.lastCallContext is @obj
test "unset(key) with a deep keypath should use the existing value's remove() method if the value is a Batman.Property", ->
@obj.unset 'foo.someProperty'
equal @fooPropertyAccessor.unset.called, true
ok @fooPropertyAccessor.unset.lastCallContext is @obj.foo
test "unset(key) should remove the property instance if it has no observers", ->
property = @obj.property('foo')
@obj.unset 'foo'
notEqual @obj.property('foo'), property
test "unset(key) should not remove the property instance if it has observers", ->
property = @obj.property('foo')
@obj.observe 'foo', ->
@obj.unset 'foo'
equal @obj.property('foo'), property
###
# getOrSet(key, valueFunction)
###
test "getOrSet(key, valueFunction) does conditional assignment with the return value of the given function", ->
equal @obj.foo, @obj.getOrSet("foo", -> "bar")
equal @obj.foo, @obj.get("foo")
equal "bar", @obj.getOrSet("foo2", -> "bar")
equal "bar", @obj.get("foo2")
###
# observe(key, callback)
###
test "observe(key, callback) stores the callback such that it is called with (value, oldValue, key) when the value of the key changes", ->
callback = createSpy()
ok @obj.observe('foo', callback) is @obj
equal callback.called, false
foo = @obj.foo
@obj.set 'foo', 'newVal'
ok callback.called
[newValue, oldValue, key] = callback.lastCallArguments
equal newValue, 'newVal'
ok oldValue is foo
equal key, 'foo'
test "observe(key, callback) with a deep keypath will fire with the new value when the final key value is changed directly", ->
@obj.observe 'foo.bar.baz.qux', callback = createSpy()
@obj.foo.bar.baz.set 'qux', 'newVal'
ok callback.called
[newVal, oldVal, key] = callback.lastCallArguments
equal newVal, 'newVal'
equal oldVal, 'quxVal'
equal key, '<KEY>'
test "observe(key, callback) with a deep keypath will fire with the new value when the final key value is changed via the same deep keypath", ->
@obj.observe 'foo.bar.baz.qux', callback = createSpy()
@obj.set 'foo.bar.baz.qux', 'newVal'
ok callback.called
[newVal, oldVal, key] = callback.lastCallArguments
equal newVal, 'newVal'
equal oldVal, 'quxVal'
equal key, '<KEY>'
test "observe(key, callback) with a deep keypath will fire with the new value when the final key value is changed via an equivalent subset of that deep keypath", ->
@obj.observe 'foo.bar.baz.qux', callback = createSpy()
@obj.foo.set 'bar.baz.qux', 'newVal'
ok callback.called
[newVal, oldVal, key] = callback.lastCallArguments
equal newVal, 'newVal'
equal oldVal, 'quxVal'
equal key, '<KEY>'
test "observe(key, callback) with a deep keypath will fire with undefined if the key segment chain is broken", ->
@obj.observe 'foo.bar.baz.qux', callback = createSpy()
@obj.set 'foo', 'newVal'
ok callback.called
[newVal, oldVal, key] = callback.lastCallArguments
equal typeof(newVal), 'undefined'
equal oldVal, 'quxVal'
equal key, '<KEY>'
test "observe(key, callback) with a deep keypath will fire with the new value if an intermediary key is changed such that the keypath resolves to a new value", ->
@obj.observe 'foo.bar.baz.qux', callback = createSpy()
@obj.set 'foo',
bar:
baz:
qux: 'newVal'
ok callback.called
[newVal, oldVal, key] = callback.lastCallArguments
equal newVal, 'newVal'
equal oldVal, 'quxVal'
equal key, '<KEY>'
test "observe(key, callback) with a deep keypath will fire with a previous value that has been removed and re-added", ->
@obj.observe 'foo.bar.baz.qux', callback = createSpy()
bar = @obj.foo.bar
@obj.unset 'foo.bar'
equal callback.callCount, 1
[newVal, oldVal, key] = callback.lastCallArguments
equal typeof(newVal), 'undefined'
equal oldVal, 'quxVal'
equal key, '<KEY>'
@obj.set 'foo.bar', bar
equal callback.callCount, 2
[newVal, oldVal, key] = callback.lastCallArguments
equal newVal, 'quxVal'
equal typeof(oldVal), 'undefined'
equal key, '<KEY>'
test "observe(key, callback) with a deep keypath will not fire if a previous portion of the path is modified", ->
@obj.observe 'foo.bar.baz.qux', callback = createSpy()
bar = @obj.foo.bar
@obj.unset 'foo.bar'
bar.unset 'baz'
equal callback.callCount, 1
[newVal, oldVal, key] = callback.lastCallArguments
equal typeof(newVal), 'undefined'
equal oldVal, 'quxVal'
equal key, '<KEY>'
test "observe(key, callback) with a deep keypath will fire when a portion of a previously removed and re-added portion is modified", ->
@obj.observe 'foo.bar.baz.qux', callback = createSpy()
bar = @obj.foo.bar
@obj.unset 'foo.bar'
@obj.set 'foo.bar', bar
@obj.set 'foo.bar.baz.qux', 'newVal'
equal callback.callCount, 3
[newVal, oldVal, key] = callback.lastCallArguments
equal newVal, 'newVal'
equal oldVal, 'quxVal'
equal key, '<KEY>'
test "observe(key, callback) called twice to attach two different observers on the same deep keypath will only fire those observers once each for any given change", ->
@obj.observe 'foo.bar.baz.qux', callback1 = createSpy()
@obj.observe 'foo.bar.baz.qux', callback2 = createSpy()
@obj.set 'foo.bar.baz.qux', 'newVal'
equal callback1.callCount, 1
equal callback2.callCount, 1
test "observe(key, callback) will only fire once and will not break when there's an object cycle", ->
@obj.foo.bar.baz.foo = @obj.foo
@obj.observe 'foo.bar.baz.foo.bar', callback = createSpy()
oldBar = @obj.foo.bar
newBar = Batman
baz: Batman
foo: Batman
bar: 'newVal'
@obj.foo.set 'bar', newBar
equal callback.callCount, 1
[newVal, oldVal, key] = callback.lastCallArguments
equal newVal, 'newVal'
ok oldVal == oldBar, "oldVal is not oldBar"
equal key, '<KEY>'
###
# observeAndFire(key, callback)
###
test "observeAndFire(key, callback) adds the callback and then calls it immediately", ->
callback = createSpy()
@obj.observeAndFire 'foo.bar.baz.qux', callback
deepEqual callback.lastCallArguments, ['quxVal', 'quxVal', 'foo.bar.baz.qux']
test "observeAndFire(key, callback) fires with the correct current value, even if a property source was changed after the dependent property was cached but while the dependent property was not being observed", ->
klass = class extends Batman.Object
@accessor 'foo', -> @get('bar')
obj = new klass
obj.set('bar', 1) # initialize source
obj.get('foo') # cache dependent
obj.set('bar', 2) # change source
obj.observeAndFire('foo', spy = createSpy())
equal spy.lastCallArguments[0], 2
###
# observeOnce(key, callback)
###
test "observeOnce(key, callback) adds the callback and removes it after the first fire", ->
callback = createSpy()
oldVal = @obj.get 'foo'
@obj.observeOnce 'foo', callback
@obj.set 'foo', 'batman'
@obj.set 'foo', 'gotham'
equal callback.callCount, 1
[newValue, oldValue, key] = callback.lastCallArguments
equal newValue, 'batman'
equal oldVal, oldValue
equal key, 'foo'
###
# forget(key [, callback])
###
test "forget(key, callback) for a simple key will remove the specified callback from that key's observers", ->
callback1 = createSpy()
callback2 = createSpy()
@obj.observe 'foo', callback1
@obj.observe 'foo', callback2
@obj.forget 'foo', callback2
@obj.set 'foo', 'newVal'
equal callback1.callCount, 1
equal callback2.callCount, 0
test "forget(key) for a simple key with no callback specified will forget all observers for that key, leaving observers of other keys untouched", ->
callback1 = createSpy()
callback2 = createSpy()
callback3 = createSpy()
@obj.observe 'foo', callback1
@obj.observe 'foo', callback2
@obj.observe 'someOtherKey', callback3
@obj.forget 'foo'
@obj.set 'foo', 'newVal'
equal callback1.callCount, 0
equal callback2.callCount, 0
@obj.set 'someOtherKey', 'someVal'
equal callback3.callCount, 1
test "forget() without any arguments removes all observers from all of this object's keys", ->
callback1 = createSpy()
callback2 = createSpy()
callback3 = createSpy()
@obj.observe 'foo', callback1
@obj.observe 'foo', callback2
@obj.observe 'someOtherKey', callback3
equal @obj.forget(), @obj, "forget returns object for chaining"
@obj.set 'foo', 'newVal'
equal callback1.callCount, 0
equal callback2.callCount, 0
@obj.set 'someOtherKey', 'someVal'
equal callback3.callCount, 0
test "forget(key) for a deep keypath does not remove any sources when there are still observers present on the keypath", ->
callback1 = createSpy()
callback2 = createSpy()
@obj.observe 'foo.bar.baz', callback1
@obj.observe 'foo.bar.baz', callback2
equal @obj.forget('foo.bar.baz', callback2), @obj, "forget returns object for chaining"
equal @obj.property('foo').handlers.length, 1
equal @obj.foo.property('bar').handlers.length, 1
equal @obj.foo.bar.property('baz').handlers.length, 1
equal @obj.property('foo.bar.baz').sources.length, 3
@obj.foo.bar.set 'baz', 'newBaz'
equal callback1.callCount, 1
@obj.foo.set 'bar', 'newBar'
equal callback1.callCount, 2
@obj.set 'foo', Batman(bar: Batman(baz: 'reconstructedBaz'))
equal callback1.callCount, 3
equal callback2.callCount, 0
| true | getPropertyAccessor = ->
get: createSpy ->
set: createSpy()
unset: createSpy()
QUnit.module 'Batman.Observable',
setup: ->
@obj = Batman
foo: Batman
bar: Batman
baz: Batman
qux: 'quxVal'
@obj.foo.bar.baz.event('corge', @corgeEventSpy = createSpy())
@obj.accessor 'someProperty', (@objPropertyAccessor = getPropertyAccessor())
@obj.foo.accessor 'someProperty', (@fooPropertyAccessor = getPropertyAccessor())
###
# property(key)
###
test 'property(key) returns a keypath of this object with the given key', ->
keypath = @obj.property('foo.bar.baz')
ok keypath.base is @obj
equal keypath.key, 'PI:KEY:<KEY>END_PI'
###
# get(key)
###
test 'get(key) with a simple key returns the value of that property', ->
ok @obj.get('foo') is @obj.foo
test 'get(key) with a deep keypath returns the value of the property at the end of the keypath', ->
equal @obj.get('foo.bar.baz.qux'), 'quxVal'
test "get(key) with an unresolvable simple key returns undefined", ->
equal typeof(@obj.get('nothing')), 'undefined'
test "get(key) with an unresolvable keypath returns undefined", ->
equal typeof(@obj.get('foo.bar.nothing')), 'undefined'
test "get(key) with a simple key calls resolve() on the result if it is a Batman.Property and returns that instead", ->
@objPropertyAccessor.get.whichReturns('resolvedValue')
equal @obj.get('someProperty'), 'resolvedValue'
deepEqual @objPropertyAccessor.get.lastCallArguments, ['someProperty']
ok @objPropertyAccessor.get.lastCallContext is @obj
test "get(key) with a deep keypath uses the last property's accessor with the last base as the context", ->
@fooPropertyAccessor.get.whichReturns('resolvedValue')
equal @obj.get('foo.someProperty'), 'resolvedValue'
deepEqual @fooPropertyAccessor.get.lastCallArguments, ['someProperty']
ok @fooPropertyAccessor.get.lastCallContext is @obj.foo
test "get(key) is cached until one of its sources changes", ->
@obj.get('foo.someProperty')
equal @fooPropertyAccessor.get.callCount, 1
@obj.get('foo.someProperty')
equal @fooPropertyAccessor.get.callCount, 1
@obj.set('foo.someProperty', yes)
@obj.get('foo.someProperty')
equal @fooPropertyAccessor.get.callCount, 2
@obj.get('foo.someProperty')
equal @fooPropertyAccessor.get.callCount, 2
test "get(key) works with cacheable properties with more than one level of accessor indirection", ->
@obj.accessor 'indirectProperty', -> @get('foo.someProperty')
@obj.get('indirectProperty')
equal @fooPropertyAccessor.get.callCount, 1
@obj.get('indirectProperty')
equal @fooPropertyAccessor.get.callCount, 1
@obj.set('foo.someProperty', yes)
@obj.get('indirectProperty')
equal @fooPropertyAccessor.get.callCount, 2
@obj.get('indirectProperty')
equal @fooPropertyAccessor.get.callCount, 2
test "get(key) works with Batman.Property.withoutTracking", ->
callCount = 0
@obj.accessor 'withoutTrackingProperty', ->
callCount++
@get('foo')
Batman.Property.withoutTracking =>
@get('foo.bar')
true
@obj.get('withoutTrackingProperty')
equal callCount, 1
@obj.set('foo.bar', true)
@obj.get('withoutTrackingProperty')
equal callCount, 1
@obj.set('foo')
@obj.get('withoutTrackingProperty')
equal callCount, 2
###
# set(key)
###
test "set(key, val) with a simple key stores the value in the property", ->
equal @obj.set('foo', 'newVal'), 'newVal'
equal @obj.foo, 'newVal'
test "set(key, val) with a deep keypath stores the value in the property at the end of the keypath", ->
@obj.set 'foo.bar.baz.qux', 'newVal'
equal @obj.foo.bar.baz.qux, 'newVal'
test "set(key, val) with a simple key calls fire(key, val, oldValue)", ->
fooProperty = @obj.property('foo')
spyOn(fooProperty, 'fire')
foo = @obj.foo
@obj.observe 'foo', ->
@obj.set 'foo', 'newVal'
equal fooProperty.fire.lastCallArguments.length, 3
equal fooProperty.fire.lastCallArguments[0], 'newVal'
ok fooProperty.fire.lastCallArguments[1] is foo
test "set(key, val) with a simple key should use the existing value's assign() method if the value is a Batman.Property", ->
@obj.set 'someProperty', 'newVal'
deepEqual @objPropertyAccessor.set.lastCallArguments, ['someProperty', 'newVal']
ok @objPropertyAccessor.set.lastCallContext is @obj
test "set(key, val) with a deep keypath should use the existing value's assign() method if the value is a Batman.Property", ->
@obj.set 'foo.someProperty', 'newVal'
deepEqual @fooPropertyAccessor.set.lastCallArguments, ['someProperty', 'newVal']
ok @fooPropertyAccessor.set.lastCallContext is @obj.foo
###
# unset(key)
###
test "unset(key) deletes the referenced property and returns the removed value", ->
equal @obj.unset('foo.bar.baz.qux'), 'quxVal'
strictEqual @obj.foo.bar.baz.qux, undefined
test "unset(key) with a simple key calls fire(key, undefined, oldValue)", ->
fooProperty = @obj.property('foo')
spyOn(fooProperty, 'fire')
foo = @obj.foo
@obj.observe 'foo', ->
@obj.unset 'foo'
[newVal, oldVal] = fooProperty.fire.lastCallArguments
equal typeof(newVal), 'undefined'
ok oldVal is foo
test "unset(key) with a simple key should use the existing value's remove() method if the value is a Batman.Property", ->
someProperty = @objPropertyAccessor
@obj.unset 'someProperty'
equal someProperty, @objPropertyAccessor
equal @objPropertyAccessor.unset.called, true
ok @objPropertyAccessor.unset.lastCallContext is @obj
test "unset(key) with a deep keypath should use the existing value's remove() method if the value is a Batman.Property", ->
@obj.unset 'foo.someProperty'
equal @fooPropertyAccessor.unset.called, true
ok @fooPropertyAccessor.unset.lastCallContext is @obj.foo
test "unset(key) should remove the property instance if it has no observers", ->
property = @obj.property('foo')
@obj.unset 'foo'
notEqual @obj.property('foo'), property
test "unset(key) should not remove the property instance if it has observers", ->
property = @obj.property('foo')
@obj.observe 'foo', ->
@obj.unset 'foo'
equal @obj.property('foo'), property
###
# getOrSet(key, valueFunction)
###
test "getOrSet(key, valueFunction) does conditional assignment with the return value of the given function", ->
equal @obj.foo, @obj.getOrSet("foo", -> "bar")
equal @obj.foo, @obj.get("foo")
equal "bar", @obj.getOrSet("foo2", -> "bar")
equal "bar", @obj.get("foo2")
###
# observe(key, callback)
###
test "observe(key, callback) stores the callback such that it is called with (value, oldValue, key) when the value of the key changes", ->
callback = createSpy()
ok @obj.observe('foo', callback) is @obj
equal callback.called, false
foo = @obj.foo
@obj.set 'foo', 'newVal'
ok callback.called
[newValue, oldValue, key] = callback.lastCallArguments
equal newValue, 'newVal'
ok oldValue is foo
equal key, 'foo'
test "observe(key, callback) with a deep keypath will fire with the new value when the final key value is changed directly", ->
@obj.observe 'foo.bar.baz.qux', callback = createSpy()
@obj.foo.bar.baz.set 'qux', 'newVal'
ok callback.called
[newVal, oldVal, key] = callback.lastCallArguments
equal newVal, 'newVal'
equal oldVal, 'quxVal'
equal key, 'PI:KEY:<KEY>END_PI'
test "observe(key, callback) with a deep keypath will fire with the new value when the final key value is changed via the same deep keypath", ->
@obj.observe 'foo.bar.baz.qux', callback = createSpy()
@obj.set 'foo.bar.baz.qux', 'newVal'
ok callback.called
[newVal, oldVal, key] = callback.lastCallArguments
equal newVal, 'newVal'
equal oldVal, 'quxVal'
equal key, 'PI:KEY:<KEY>END_PI'
test "observe(key, callback) with a deep keypath will fire with the new value when the final key value is changed via an equivalent subset of that deep keypath", ->
@obj.observe 'foo.bar.baz.qux', callback = createSpy()
@obj.foo.set 'bar.baz.qux', 'newVal'
ok callback.called
[newVal, oldVal, key] = callback.lastCallArguments
equal newVal, 'newVal'
equal oldVal, 'quxVal'
equal key, 'PI:KEY:<KEY>END_PI'
test "observe(key, callback) with a deep keypath will fire with undefined if the key segment chain is broken", ->
@obj.observe 'foo.bar.baz.qux', callback = createSpy()
@obj.set 'foo', 'newVal'
ok callback.called
[newVal, oldVal, key] = callback.lastCallArguments
equal typeof(newVal), 'undefined'
equal oldVal, 'quxVal'
equal key, 'PI:KEY:<KEY>END_PI'
test "observe(key, callback) with a deep keypath will fire with the new value if an intermediary key is changed such that the keypath resolves to a new value", ->
@obj.observe 'foo.bar.baz.qux', callback = createSpy()
@obj.set 'foo',
bar:
baz:
qux: 'newVal'
ok callback.called
[newVal, oldVal, key] = callback.lastCallArguments
equal newVal, 'newVal'
equal oldVal, 'quxVal'
equal key, 'PI:KEY:<KEY>END_PI'
test "observe(key, callback) with a deep keypath will fire with a previous value that has been removed and re-added", ->
@obj.observe 'foo.bar.baz.qux', callback = createSpy()
bar = @obj.foo.bar
@obj.unset 'foo.bar'
equal callback.callCount, 1
[newVal, oldVal, key] = callback.lastCallArguments
equal typeof(newVal), 'undefined'
equal oldVal, 'quxVal'
equal key, 'PI:KEY:<KEY>END_PI'
@obj.set 'foo.bar', bar
equal callback.callCount, 2
[newVal, oldVal, key] = callback.lastCallArguments
equal newVal, 'quxVal'
equal typeof(oldVal), 'undefined'
equal key, 'PI:KEY:<KEY>END_PI'
test "observe(key, callback) with a deep keypath will not fire if a previous portion of the path is modified", ->
@obj.observe 'foo.bar.baz.qux', callback = createSpy()
bar = @obj.foo.bar
@obj.unset 'foo.bar'
bar.unset 'baz'
equal callback.callCount, 1
[newVal, oldVal, key] = callback.lastCallArguments
equal typeof(newVal), 'undefined'
equal oldVal, 'quxVal'
equal key, 'PI:KEY:<KEY>END_PI'
test "observe(key, callback) with a deep keypath will fire when a portion of a previously removed and re-added portion is modified", ->
@obj.observe 'foo.bar.baz.qux', callback = createSpy()
bar = @obj.foo.bar
@obj.unset 'foo.bar'
@obj.set 'foo.bar', bar
@obj.set 'foo.bar.baz.qux', 'newVal'
equal callback.callCount, 3
[newVal, oldVal, key] = callback.lastCallArguments
equal newVal, 'newVal'
equal oldVal, 'quxVal'
equal key, 'PI:KEY:<KEY>END_PI'
test "observe(key, callback) called twice to attach two different observers on the same deep keypath will only fire those observers once each for any given change", ->
@obj.observe 'foo.bar.baz.qux', callback1 = createSpy()
@obj.observe 'foo.bar.baz.qux', callback2 = createSpy()
@obj.set 'foo.bar.baz.qux', 'newVal'
equal callback1.callCount, 1
equal callback2.callCount, 1
test "observe(key, callback) will only fire once and will not break when there's an object cycle", ->
@obj.foo.bar.baz.foo = @obj.foo
@obj.observe 'foo.bar.baz.foo.bar', callback = createSpy()
oldBar = @obj.foo.bar
newBar = Batman
baz: Batman
foo: Batman
bar: 'newVal'
@obj.foo.set 'bar', newBar
equal callback.callCount, 1
[newVal, oldVal, key] = callback.lastCallArguments
equal newVal, 'newVal'
ok oldVal == oldBar, "oldVal is not oldBar"
equal key, 'PI:KEY:<KEY>END_PI'
###
# observeAndFire(key, callback)
###
test "observeAndFire(key, callback) adds the callback and then calls it immediately", ->
callback = createSpy()
@obj.observeAndFire 'foo.bar.baz.qux', callback
deepEqual callback.lastCallArguments, ['quxVal', 'quxVal', 'foo.bar.baz.qux']
test "observeAndFire(key, callback) fires with the correct current value, even if a property source was changed after the dependent property was cached but while the dependent property was not being observed", ->
klass = class extends Batman.Object
@accessor 'foo', -> @get('bar')
obj = new klass
obj.set('bar', 1) # initialize source
obj.get('foo') # cache dependent
obj.set('bar', 2) # change source
obj.observeAndFire('foo', spy = createSpy())
equal spy.lastCallArguments[0], 2
###
# observeOnce(key, callback)
###
test "observeOnce(key, callback) adds the callback and removes it after the first fire", ->
callback = createSpy()
oldVal = @obj.get 'foo'
@obj.observeOnce 'foo', callback
@obj.set 'foo', 'batman'
@obj.set 'foo', 'gotham'
equal callback.callCount, 1
[newValue, oldValue, key] = callback.lastCallArguments
equal newValue, 'batman'
equal oldVal, oldValue
equal key, 'foo'
###
# forget(key [, callback])
###
test "forget(key, callback) for a simple key will remove the specified callback from that key's observers", ->
callback1 = createSpy()
callback2 = createSpy()
@obj.observe 'foo', callback1
@obj.observe 'foo', callback2
@obj.forget 'foo', callback2
@obj.set 'foo', 'newVal'
equal callback1.callCount, 1
equal callback2.callCount, 0
test "forget(key) for a simple key with no callback specified will forget all observers for that key, leaving observers of other keys untouched", ->
callback1 = createSpy()
callback2 = createSpy()
callback3 = createSpy()
@obj.observe 'foo', callback1
@obj.observe 'foo', callback2
@obj.observe 'someOtherKey', callback3
@obj.forget 'foo'
@obj.set 'foo', 'newVal'
equal callback1.callCount, 0
equal callback2.callCount, 0
@obj.set 'someOtherKey', 'someVal'
equal callback3.callCount, 1
test "forget() without any arguments removes all observers from all of this object's keys", ->
callback1 = createSpy()
callback2 = createSpy()
callback3 = createSpy()
@obj.observe 'foo', callback1
@obj.observe 'foo', callback2
@obj.observe 'someOtherKey', callback3
equal @obj.forget(), @obj, "forget returns object for chaining"
@obj.set 'foo', 'newVal'
equal callback1.callCount, 0
equal callback2.callCount, 0
@obj.set 'someOtherKey', 'someVal'
equal callback3.callCount, 0
test "forget(key) for a deep keypath does not remove any sources when there are still observers present on the keypath", ->
callback1 = createSpy()
callback2 = createSpy()
@obj.observe 'foo.bar.baz', callback1
@obj.observe 'foo.bar.baz', callback2
equal @obj.forget('foo.bar.baz', callback2), @obj, "forget returns object for chaining"
equal @obj.property('foo').handlers.length, 1
equal @obj.foo.property('bar').handlers.length, 1
equal @obj.foo.bar.property('baz').handlers.length, 1
equal @obj.property('foo.bar.baz').sources.length, 3
@obj.foo.bar.set 'baz', 'newBaz'
equal callback1.callCount, 1
@obj.foo.set 'bar', 'newBar'
equal callback1.callCount, 2
@obj.set 'foo', Batman(bar: Batman(baz: 'reconstructedBaz'))
equal callback1.callCount, 3
equal callback2.callCount, 0
|
[
{
"context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission",
"end": 18,
"score": 0.9973180890083313,
"start": 12,
"tag": "NAME",
"value": "Joyent"
},
{
"context": "nL=SF\\nO=Joyent\\nOU=Node.js\\nCN=ca1\\nemailAddress=ry@clouds.org\nexports.parseCertString = parseCertString = (s) -",
"end": 6591,
"score": 0.9993244409561157,
"start": 6578,
"tag": "EMAIL",
"value": "ry@clouds.org"
}
] | lib/tls.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"
net = require("net")
url = require("url")
util = require("util")
# Allow {CLIENT_RENEG_LIMIT} client-initiated session renegotiations
# every {CLIENT_RENEG_WINDOW} seconds. An error event is emitted if more
# renegotations are seen. The settings are applied to all remote client
# connections.
exports.CLIENT_RENEG_LIMIT = 3
exports.CLIENT_RENEG_WINDOW = 600
exports.SLAB_BUFFER_SIZE = 10 * 1024 * 1024
# TLS 1.2
# TLS 1.0
exports.DEFAULT_CIPHERS = "ECDHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA256:AES128-GCM-SHA256:" + "RC4:HIGH:!MD5:!aNULL"
exports.DEFAULT_ECDH_CURVE = "prime256v1"
exports.getCiphers = ->
names = process.binding("crypto").getSSLCiphers()
# Drop all-caps names in favor of their lowercase aliases,
ctx = {}
names.forEach (name) ->
name = name.toLowerCase() if /^[0-9A-Z\-]+$/.test(name)
ctx[name] = true
return
Object.getOwnPropertyNames(ctx).sort()
# Convert protocols array into valid OpenSSL protocols list
# ("\x06spdy/2\x08http/1.1\x08http/1.0")
exports.convertNPNProtocols = convertNPNProtocols = (NPNProtocols, out) ->
# If NPNProtocols is Array - translate it into buffer
if util.isArray(NPNProtocols)
buff = new Buffer(NPNProtocols.reduce((p, c) ->
p + 1 + Buffer.byteLength(c)
, 0))
NPNProtocols.reduce ((offset, c) ->
clen = Buffer.byteLength(c)
buff[offset] = clen
buff.write c, offset + 1
offset + 1 + clen
), 0
NPNProtocols = buff
# If it's already a Buffer - store it
out.NPNProtocols = NPNProtocols if util.isBuffer(NPNProtocols)
return
exports.checkServerIdentity = checkServerIdentity = (host, cert) ->
# Create regexp to much hostnames
regexpify = (host, wildcards) ->
# Add trailing dot (make hostnames uniform)
host += "." unless /\.$/.test(host)
# The same applies to hostname with more than one wildcard,
# if hostname has wildcard when wildcards are not allowed,
# or if there are less than two dots after wildcard (i.e. *.com or *d.com)
#
# also
#
# "The client SHOULD NOT attempt to match a presented identifier in
# which the wildcard character comprises a label other than the
# left-most label (e.g., do not match bar.*.example.net)."
# RFC6125
return /$./ if not wildcards and /\*/.test(host) or /[\.\*].*\*/.test(host) or /\*/.test(host) and not /\*.*\..+\..+/.test(host)
# Replace wildcard chars with regexp's wildcard and
# escape all characters that have special meaning in regexps
# (i.e. '.', '[', '{', '*', and others)
re = host.replace(/\*([a-z0-9\\-_\.])|[\.,\-\\\^\$+?*\[\]\(\):!\|{}]/g, (all, sub) ->
return "[a-z0-9\\-_]*" + ((if sub is "-" then "\\-" else sub)) if sub
"\\" + all
)
new RegExp("^" + re + "$", "i")
dnsNames = []
uriNames = []
ips = []
matchCN = true
valid = false
reason = "Unknown reason"
# There're several names to perform check against:
# CN and altnames in certificate extension
# (DNS names, IP addresses, and URIs)
#
# Walk through altnames and generate lists of those names
if cert.subjectaltname
cert.subjectaltname.split(/, /g).forEach (altname) ->
option = altname.match(/^(DNS|IP Address|URI):(.*)$/)
return unless option
if option[1] is "DNS"
dnsNames.push option[2]
else if option[1] is "IP Address"
ips.push option[2]
else if option[1] is "URI"
uri = url.parse(option[2])
uriNames.push uri.hostname if uri
return
# If hostname is an IP address, it should be present in the list of IP
# addresses.
if net.isIP(host)
valid = ips.some((ip) ->
ip is host
)
reason = util.format("IP: %s is not in the cert's list: %s", host, ips.join(", ")) unless valid
else
# Transform hostname to canonical form
host += "." unless /\.$/.test(host)
# Otherwise check all DNS/URI records from certificate
# (with allowed wildcards)
dnsNames = dnsNames.map((name) ->
regexpify name, true
)
# Wildcards ain't allowed in URI names
uriNames = uriNames.map((name) ->
regexpify name, false
)
dnsNames = dnsNames.concat(uriNames)
matchCN = false if dnsNames.length > 0
# Match against Common Name (CN) only if no supported identifiers are
# present.
#
# "As noted, a client MUST NOT seek a match for a reference identifier
# of CN-ID if the presented identifiers include a DNS-ID, SRV-ID,
# URI-ID, or any application-specific identifier types supported by the
# client."
# RFC6125
if matchCN
commonNames = cert.subject.CN
if util.isArray(commonNames)
i = 0
k = commonNames.length
while i < k
dnsNames.push regexpify(commonNames[i], true)
++i
else
dnsNames.push regexpify(commonNames, true)
valid = dnsNames.some((re) ->
re.test host
)
unless valid
if cert.subjectaltname
reason = util.format("Host: %s is not in the cert's altnames: %s", host, cert.subjectaltname)
else
reason = util.format("Host: %s is not cert's CN: %s", host, cert.subject.CN)
unless valid
err = new Error(util.format("Hostname/IP doesn't match certificate's altnames: %j", reason))
err.reason = reason
err.host = host
err.cert = cert
err
# Example:
# C=US\nST=CA\nL=SF\nO=Joyent\nOU=Node.js\nCN=ca1\nemailAddress=ry@clouds.org
exports.parseCertString = parseCertString = (s) ->
out = {}
parts = s.split("\n")
i = 0
len = parts.length
while i < len
sepIndex = parts[i].indexOf("=")
if sepIndex > 0
key = parts[i].slice(0, sepIndex)
value = parts[i].slice(sepIndex + 1)
if key of out
out[key] = [out[key]] unless util.isArray(out[key])
out[key].push value
else
out[key] = value
i++
out
# Public API
exports.createSecureContext = require("_tls_common").createSecureContext
exports.SecureContext = require("_tls_common").SecureContext
exports.TLSSocket = require("_tls_wrap").TLSSocket
exports.Server = require("_tls_wrap").Server
exports.createServer = require("_tls_wrap").createServer
exports.connect = require("_tls_wrap").connect
exports.createSecurePair = require("_tls_legacy").createSecurePair
| 34140 | # 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"
net = require("net")
url = require("url")
util = require("util")
# Allow {CLIENT_RENEG_LIMIT} client-initiated session renegotiations
# every {CLIENT_RENEG_WINDOW} seconds. An error event is emitted if more
# renegotations are seen. The settings are applied to all remote client
# connections.
exports.CLIENT_RENEG_LIMIT = 3
exports.CLIENT_RENEG_WINDOW = 600
exports.SLAB_BUFFER_SIZE = 10 * 1024 * 1024
# TLS 1.2
# TLS 1.0
exports.DEFAULT_CIPHERS = "ECDHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA256:AES128-GCM-SHA256:" + "RC4:HIGH:!MD5:!aNULL"
exports.DEFAULT_ECDH_CURVE = "prime256v1"
exports.getCiphers = ->
names = process.binding("crypto").getSSLCiphers()
# Drop all-caps names in favor of their lowercase aliases,
ctx = {}
names.forEach (name) ->
name = name.toLowerCase() if /^[0-9A-Z\-]+$/.test(name)
ctx[name] = true
return
Object.getOwnPropertyNames(ctx).sort()
# Convert protocols array into valid OpenSSL protocols list
# ("\x06spdy/2\x08http/1.1\x08http/1.0")
exports.convertNPNProtocols = convertNPNProtocols = (NPNProtocols, out) ->
# If NPNProtocols is Array - translate it into buffer
if util.isArray(NPNProtocols)
buff = new Buffer(NPNProtocols.reduce((p, c) ->
p + 1 + Buffer.byteLength(c)
, 0))
NPNProtocols.reduce ((offset, c) ->
clen = Buffer.byteLength(c)
buff[offset] = clen
buff.write c, offset + 1
offset + 1 + clen
), 0
NPNProtocols = buff
# If it's already a Buffer - store it
out.NPNProtocols = NPNProtocols if util.isBuffer(NPNProtocols)
return
exports.checkServerIdentity = checkServerIdentity = (host, cert) ->
# Create regexp to much hostnames
regexpify = (host, wildcards) ->
# Add trailing dot (make hostnames uniform)
host += "." unless /\.$/.test(host)
# The same applies to hostname with more than one wildcard,
# if hostname has wildcard when wildcards are not allowed,
# or if there are less than two dots after wildcard (i.e. *.com or *d.com)
#
# also
#
# "The client SHOULD NOT attempt to match a presented identifier in
# which the wildcard character comprises a label other than the
# left-most label (e.g., do not match bar.*.example.net)."
# RFC6125
return /$./ if not wildcards and /\*/.test(host) or /[\.\*].*\*/.test(host) or /\*/.test(host) and not /\*.*\..+\..+/.test(host)
# Replace wildcard chars with regexp's wildcard and
# escape all characters that have special meaning in regexps
# (i.e. '.', '[', '{', '*', and others)
re = host.replace(/\*([a-z0-9\\-_\.])|[\.,\-\\\^\$+?*\[\]\(\):!\|{}]/g, (all, sub) ->
return "[a-z0-9\\-_]*" + ((if sub is "-" then "\\-" else sub)) if sub
"\\" + all
)
new RegExp("^" + re + "$", "i")
dnsNames = []
uriNames = []
ips = []
matchCN = true
valid = false
reason = "Unknown reason"
# There're several names to perform check against:
# CN and altnames in certificate extension
# (DNS names, IP addresses, and URIs)
#
# Walk through altnames and generate lists of those names
if cert.subjectaltname
cert.subjectaltname.split(/, /g).forEach (altname) ->
option = altname.match(/^(DNS|IP Address|URI):(.*)$/)
return unless option
if option[1] is "DNS"
dnsNames.push option[2]
else if option[1] is "IP Address"
ips.push option[2]
else if option[1] is "URI"
uri = url.parse(option[2])
uriNames.push uri.hostname if uri
return
# If hostname is an IP address, it should be present in the list of IP
# addresses.
if net.isIP(host)
valid = ips.some((ip) ->
ip is host
)
reason = util.format("IP: %s is not in the cert's list: %s", host, ips.join(", ")) unless valid
else
# Transform hostname to canonical form
host += "." unless /\.$/.test(host)
# Otherwise check all DNS/URI records from certificate
# (with allowed wildcards)
dnsNames = dnsNames.map((name) ->
regexpify name, true
)
# Wildcards ain't allowed in URI names
uriNames = uriNames.map((name) ->
regexpify name, false
)
dnsNames = dnsNames.concat(uriNames)
matchCN = false if dnsNames.length > 0
# Match against Common Name (CN) only if no supported identifiers are
# present.
#
# "As noted, a client MUST NOT seek a match for a reference identifier
# of CN-ID if the presented identifiers include a DNS-ID, SRV-ID,
# URI-ID, or any application-specific identifier types supported by the
# client."
# RFC6125
if matchCN
commonNames = cert.subject.CN
if util.isArray(commonNames)
i = 0
k = commonNames.length
while i < k
dnsNames.push regexpify(commonNames[i], true)
++i
else
dnsNames.push regexpify(commonNames, true)
valid = dnsNames.some((re) ->
re.test host
)
unless valid
if cert.subjectaltname
reason = util.format("Host: %s is not in the cert's altnames: %s", host, cert.subjectaltname)
else
reason = util.format("Host: %s is not cert's CN: %s", host, cert.subject.CN)
unless valid
err = new Error(util.format("Hostname/IP doesn't match certificate's altnames: %j", reason))
err.reason = reason
err.host = host
err.cert = cert
err
# Example:
# C=US\nST=CA\nL=SF\nO=Joyent\nOU=Node.js\nCN=ca1\nemailAddress=<EMAIL>
exports.parseCertString = parseCertString = (s) ->
out = {}
parts = s.split("\n")
i = 0
len = parts.length
while i < len
sepIndex = parts[i].indexOf("=")
if sepIndex > 0
key = parts[i].slice(0, sepIndex)
value = parts[i].slice(sepIndex + 1)
if key of out
out[key] = [out[key]] unless util.isArray(out[key])
out[key].push value
else
out[key] = value
i++
out
# Public API
exports.createSecureContext = require("_tls_common").createSecureContext
exports.SecureContext = require("_tls_common").SecureContext
exports.TLSSocket = require("_tls_wrap").TLSSocket
exports.Server = require("_tls_wrap").Server
exports.createServer = require("_tls_wrap").createServer
exports.connect = require("_tls_wrap").connect
exports.createSecurePair = require("_tls_legacy").createSecurePair
| 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"
net = require("net")
url = require("url")
util = require("util")
# Allow {CLIENT_RENEG_LIMIT} client-initiated session renegotiations
# every {CLIENT_RENEG_WINDOW} seconds. An error event is emitted if more
# renegotations are seen. The settings are applied to all remote client
# connections.
exports.CLIENT_RENEG_LIMIT = 3
exports.CLIENT_RENEG_WINDOW = 600
exports.SLAB_BUFFER_SIZE = 10 * 1024 * 1024
# TLS 1.2
# TLS 1.0
exports.DEFAULT_CIPHERS = "ECDHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA256:AES128-GCM-SHA256:" + "RC4:HIGH:!MD5:!aNULL"
exports.DEFAULT_ECDH_CURVE = "prime256v1"
exports.getCiphers = ->
names = process.binding("crypto").getSSLCiphers()
# Drop all-caps names in favor of their lowercase aliases,
ctx = {}
names.forEach (name) ->
name = name.toLowerCase() if /^[0-9A-Z\-]+$/.test(name)
ctx[name] = true
return
Object.getOwnPropertyNames(ctx).sort()
# Convert protocols array into valid OpenSSL protocols list
# ("\x06spdy/2\x08http/1.1\x08http/1.0")
exports.convertNPNProtocols = convertNPNProtocols = (NPNProtocols, out) ->
# If NPNProtocols is Array - translate it into buffer
if util.isArray(NPNProtocols)
buff = new Buffer(NPNProtocols.reduce((p, c) ->
p + 1 + Buffer.byteLength(c)
, 0))
NPNProtocols.reduce ((offset, c) ->
clen = Buffer.byteLength(c)
buff[offset] = clen
buff.write c, offset + 1
offset + 1 + clen
), 0
NPNProtocols = buff
# If it's already a Buffer - store it
out.NPNProtocols = NPNProtocols if util.isBuffer(NPNProtocols)
return
exports.checkServerIdentity = checkServerIdentity = (host, cert) ->
# Create regexp to much hostnames
regexpify = (host, wildcards) ->
# Add trailing dot (make hostnames uniform)
host += "." unless /\.$/.test(host)
# The same applies to hostname with more than one wildcard,
# if hostname has wildcard when wildcards are not allowed,
# or if there are less than two dots after wildcard (i.e. *.com or *d.com)
#
# also
#
# "The client SHOULD NOT attempt to match a presented identifier in
# which the wildcard character comprises a label other than the
# left-most label (e.g., do not match bar.*.example.net)."
# RFC6125
return /$./ if not wildcards and /\*/.test(host) or /[\.\*].*\*/.test(host) or /\*/.test(host) and not /\*.*\..+\..+/.test(host)
# Replace wildcard chars with regexp's wildcard and
# escape all characters that have special meaning in regexps
# (i.e. '.', '[', '{', '*', and others)
re = host.replace(/\*([a-z0-9\\-_\.])|[\.,\-\\\^\$+?*\[\]\(\):!\|{}]/g, (all, sub) ->
return "[a-z0-9\\-_]*" + ((if sub is "-" then "\\-" else sub)) if sub
"\\" + all
)
new RegExp("^" + re + "$", "i")
dnsNames = []
uriNames = []
ips = []
matchCN = true
valid = false
reason = "Unknown reason"
# There're several names to perform check against:
# CN and altnames in certificate extension
# (DNS names, IP addresses, and URIs)
#
# Walk through altnames and generate lists of those names
if cert.subjectaltname
cert.subjectaltname.split(/, /g).forEach (altname) ->
option = altname.match(/^(DNS|IP Address|URI):(.*)$/)
return unless option
if option[1] is "DNS"
dnsNames.push option[2]
else if option[1] is "IP Address"
ips.push option[2]
else if option[1] is "URI"
uri = url.parse(option[2])
uriNames.push uri.hostname if uri
return
# If hostname is an IP address, it should be present in the list of IP
# addresses.
if net.isIP(host)
valid = ips.some((ip) ->
ip is host
)
reason = util.format("IP: %s is not in the cert's list: %s", host, ips.join(", ")) unless valid
else
# Transform hostname to canonical form
host += "." unless /\.$/.test(host)
# Otherwise check all DNS/URI records from certificate
# (with allowed wildcards)
dnsNames = dnsNames.map((name) ->
regexpify name, true
)
# Wildcards ain't allowed in URI names
uriNames = uriNames.map((name) ->
regexpify name, false
)
dnsNames = dnsNames.concat(uriNames)
matchCN = false if dnsNames.length > 0
# Match against Common Name (CN) only if no supported identifiers are
# present.
#
# "As noted, a client MUST NOT seek a match for a reference identifier
# of CN-ID if the presented identifiers include a DNS-ID, SRV-ID,
# URI-ID, or any application-specific identifier types supported by the
# client."
# RFC6125
if matchCN
commonNames = cert.subject.CN
if util.isArray(commonNames)
i = 0
k = commonNames.length
while i < k
dnsNames.push regexpify(commonNames[i], true)
++i
else
dnsNames.push regexpify(commonNames, true)
valid = dnsNames.some((re) ->
re.test host
)
unless valid
if cert.subjectaltname
reason = util.format("Host: %s is not in the cert's altnames: %s", host, cert.subjectaltname)
else
reason = util.format("Host: %s is not cert's CN: %s", host, cert.subject.CN)
unless valid
err = new Error(util.format("Hostname/IP doesn't match certificate's altnames: %j", reason))
err.reason = reason
err.host = host
err.cert = cert
err
# Example:
# C=US\nST=CA\nL=SF\nO=Joyent\nOU=Node.js\nCN=ca1\nemailAddress=PI:EMAIL:<EMAIL>END_PI
exports.parseCertString = parseCertString = (s) ->
out = {}
parts = s.split("\n")
i = 0
len = parts.length
while i < len
sepIndex = parts[i].indexOf("=")
if sepIndex > 0
key = parts[i].slice(0, sepIndex)
value = parts[i].slice(sepIndex + 1)
if key of out
out[key] = [out[key]] unless util.isArray(out[key])
out[key].push value
else
out[key] = value
i++
out
# Public API
exports.createSecureContext = require("_tls_common").createSecureContext
exports.SecureContext = require("_tls_common").SecureContext
exports.TLSSocket = require("_tls_wrap").TLSSocket
exports.Server = require("_tls_wrap").Server
exports.createServer = require("_tls_wrap").createServer
exports.connect = require("_tls_wrap").connect
exports.createSecurePair = require("_tls_legacy").createSecurePair
|
[
{
"context": "-durationpicker editor 1.0.0\n\n Copyright (c) 2016 Tomasz Jakub Rup\n\n https://github.com/tomi77/backbone-forms-boots",
"end": 97,
"score": 0.9998739957809448,
"start": 81,
"tag": "NAME",
"value": "Tomasz Jakub Rup"
},
{
"context": "t (c) 2016 Tomasz Jakub Rup\n\n https://github.com/tomi77/backbone-forms-bootstrap-durationpicker\n\n Releas",
"end": 126,
"score": 0.9995150566101074,
"start": 120,
"tag": "USERNAME",
"value": "tomi77"
}
] | src/bbf-bootstrap-durationpicker.coffee | tomi77/backbone-forms-bootstrap-durationpicker | 0 | ###
Backbone-Forms Bootstrap-durationpicker editor 1.0.0
Copyright (c) 2016 Tomasz Jakub Rup
https://github.com/tomi77/backbone-forms-bootstrap-durationpicker
Released under the MIT license
###
((root, factory) ->
switch
when typeof define is 'function' and define.amd
define ['backbone-forms', 'bootstrap-durationpicker'], factory
when typeof exports is 'object'
require('bootstrap-durationpicker')
factory require('backbone-forms')
else
factory root.Backbone.Form
return
) @, (Form) ->
Text = Form.editors.Text
Form.editors['bootstrap.DurationPicker'] = Text.extend
initialize: (options) ->
Text::initialize.call @, options
@editorOptions = options.schema.editorOptions or {}
return
render: () ->
Text::render.call @
@$el.durationpicker @editorOptions
@
return
| 211541 | ###
Backbone-Forms Bootstrap-durationpicker editor 1.0.0
Copyright (c) 2016 <NAME>
https://github.com/tomi77/backbone-forms-bootstrap-durationpicker
Released under the MIT license
###
((root, factory) ->
switch
when typeof define is 'function' and define.amd
define ['backbone-forms', 'bootstrap-durationpicker'], factory
when typeof exports is 'object'
require('bootstrap-durationpicker')
factory require('backbone-forms')
else
factory root.Backbone.Form
return
) @, (Form) ->
Text = Form.editors.Text
Form.editors['bootstrap.DurationPicker'] = Text.extend
initialize: (options) ->
Text::initialize.call @, options
@editorOptions = options.schema.editorOptions or {}
return
render: () ->
Text::render.call @
@$el.durationpicker @editorOptions
@
return
| true | ###
Backbone-Forms Bootstrap-durationpicker editor 1.0.0
Copyright (c) 2016 PI:NAME:<NAME>END_PI
https://github.com/tomi77/backbone-forms-bootstrap-durationpicker
Released under the MIT license
###
((root, factory) ->
switch
when typeof define is 'function' and define.amd
define ['backbone-forms', 'bootstrap-durationpicker'], factory
when typeof exports is 'object'
require('bootstrap-durationpicker')
factory require('backbone-forms')
else
factory root.Backbone.Form
return
) @, (Form) ->
Text = Form.editors.Text
Form.editors['bootstrap.DurationPicker'] = Text.extend
initialize: (options) ->
Text::initialize.call @, options
@editorOptions = options.schema.editorOptions or {}
return
render: () ->
Text::render.call @
@$el.durationpicker @editorOptions
@
return
|
[
{
"context": "?.UnprocessedItems[ @config.tablenameFiles ]\n\t\t\t\t#@stateinfo.iTodo += _putR.length\n\t\t\t\t#@stateinfo.capacityUni",
"end": 3281,
"score": 0.8570001125335693,
"start": 3271,
"tag": "EMAIL",
"value": "@stateinfo"
},
{
"context": "iles ]\n\t\t\t\t#@stateinfo.iTodo += _putR.length\n\t\t\t\t#@stateinfo.capacityUnits -= _putR.length\n\t\t\t\t@stateinfo.Retri",
"end": 3319,
"score": 0.8296866416931152,
"start": 3309,
"tag": "EMAIL",
"value": "@stateinfo"
}
] | _src/lib/dynamo.coffee | mpneuried/tcs_migrate-media-api | 0 | AWS = require('aws-sdk')
_ = require 'lodash'
async = require "async"
config = require( "./config" )
class Dynamo extends require( "mpbasic" )( config )
defaults: =>
return @extend {}, super,
accessKeyId: null
secretAccessKey: null
region: "eu-west-1"
apiVersion: "2012-08-10"
tablenameDomains: null
tablenameFiles: null
ReturnConsumedCapacity: "TOTAL"
pumps: 10
batchsize: 25
constructor: ->
super
@checked = false
@c_domains = []
@wait = 0
@stateinfo =
capacityUnits: 0
Retries: 0
Errors: 0
#iTodo: 0
@pumping = false
@_configure()
return
_configure: =>
@debug "check", @config
if not @config.accessKeyId
@_handleError( false, "EMISSINGAWSACCESSKEY" )
return
if not @config.secretAccessKey
@_handleError( false, "EMISSINGAWSSECRET" )
return
@client = new AWS.DynamoDB( @config )
@checked = true
@emit "checked"
return
readDomain: ( domain, cb )=>
if not @checked
cb( @_handleError( true, "ECHECKINVALID" ) )
return
params =
TableName: @config.tablenameDomains
Key:
domain:
S: domain
@_getItem params, ( err, domainData )=>
if err
cb( err )
return
@debug "got domain", domainData
if domainData?.domain?
cb( null, domainData )
else
@_handleError( cb, "EDOMAINNOTFOUND", domain: domain )
return
return
migrate: ( domain, tuple, cb )=>
_attr = @_attr2Dynamo( domain, tuple )
@debug "migrate attrs `#{tuple.key}`", _attr, tuple
@update _attr, ( err, result )=>
if err
cb( err )
return
cb( null, result )
return
return
pump: ( domain, fnAddData, fnGetData )=>
if @pumping
return
@pumping = true
@emit "start.pump"
@debug "start pump"
aPumps = for i in [ 1..@config.pumps ]
@_pump( domain, fnAddData, fnGetData )
async.parallel aPumps, ( err, res )=>
@debug "async.parallel return"
@pumping = false
@debug "stop pump"
@emit "stop.pump"
return
return
throttle: =>
@wait += 50
@debug( "throttle #{ @wait }" )
return
accelerate: =>
if @wait - 50 <= 0
@wait = 0
else
@wait -= 50
@debug( "accelerate #{ @wait }" )
return
_pump: ( domain, fnAddData, fnGetData )=>
return ( cba )=>
@debug "_pump"
_sett = fnGetData( @config.batchsize )
if _sett.length > 0
@writeBatch domain, _sett, fnAddData, =>
@emit "data.pumped"
@debug "writeBatch return wait #{@wait}"
_.delay( @_pump( domain, fnAddData, fnGetData ), @wait, cba )
return
else
@debug "writeBatch empty"
cba()
return
writeBatch: ( domain, datas, fnAddData, cb )=>
_datas = []
for tuple in datas
if tuple.PutRequest?
_datas.push( tuple )
else
_datas.push( @_attr2Dynamo( domain, tuple ) )
_dynReq = @_createDynamoRequest( _datas )
@client.batchWriteItem _dynReq, ( err, res )=>
@debug "dynamo written", @wait, res?.ConsumedCapacity[ 0 ]?.CapacityUnits, res?.UnprocessedItems[ @config.tablenameFiles ]?.length or 0, res
if _.isNumber( res?.ConsumedCapacity?[ 0 ]?.CapacityUnits )
@stateinfo.capacityUnits += res?.ConsumedCapacity[ 0 ].CapacityUnits
if not _.isEmpty( res?.UnprocessedItems )
@throttle()
_putR = res?.UnprocessedItems[ @config.tablenameFiles ]
#@stateinfo.iTodo += _putR.length
#@stateinfo.capacityUnits -= _putR.length
@stateinfo.Retries += _putR.length
@debug "retry", _putR
fnAddData( _putR )
cb()
return
else
@accelerate()
if err? and err.statusCode isnt 200
@stateinfo.Errors += 1
@emit "data.error", err, _dynReq
@error( err )
cb()
return
cb()
return
return
_createDynamoRequest: ( _datas )=>
ret =
RequestItems: {}
ReturnConsumedCapacity: "TOTAL"
#ReturnItemCollectionMetrics: "SIZE"
_dyn = []
for data in _datas
try
if data.PutRequest?
_dyn.push data
else
item = @_createItem( data )
if item?
_dyn.push
PutRequest:
Item: item
catch _err
@error "error creating dynamo item", _err, JSON.stringify( data, 1,2 )
ret.RequestItems[ @config.tablenameFiles ] = _dyn
ret
_createItem: ( data )=>
_item =
key:
S: data.key
rev:
S: data.rev
fha:
S: data.fha
#url:
# S: data.url
ttl:
N: ( data.ttl or 0 ).toString()
cty:
S: data.cty
#cln:
# N: data.cln.toString()
acl:
S: data.acl
old:
N: data.old.toString()
crd:
N: data.crd.toString()
_u:
N: data._u.toString()
if not isNaN( data.cln )
_item.cln =
N: data.cln.toString()
if data.cdi?.length
_item.cdi =
S: data.cdi
if data.hgt > 0
_item.hgt =
N: data.hgt.toString()
if data.wdt > 0
_item.wdt =
N: data.wdt.toString()
if _.isString(data.prp)
_item.prp =
S: data.prp
else if data.prp? and Object.keys( data.prp ).length
_item.prp =
S: JSON.stringify( data.prp )
if data.tgs?.length
_item.tgs =
SS: data.tgs
return _item
update: ( data, cb )=>
params =
TableName: @config.tablenameFiles
Item: @_createItem( data )
ReturnConsumedCapacity: @config.ReturnConsumedCapacity
ReturnValues: "NONE"
@_putItem( params, cb )
return
# Attribute Mapping
attrMapping:
key: "key"
rev: "revision"
fha: "filehash"
#url: "url"
ttl: "ttl"
cty: "content_type"
cdi: "content_disposition"
cln: "content_length"
acl: "acl"
hgt: "height"
wdt: "width"
prp: "properties"
tgs: "tags"
old: "isRevision"
crd: "created"
_u: "version"
_attr2Dynamo: ( domain, inp )=>
attrs = {}
for _dyn, _api of @attrMapping
attrs[ _dyn ] = if inp[ _api ]? then inp[ _api ] else null
attrs.fha = domain.bucket + "/" + attrs.fha
attrs.key = domain.domain + ":" + attrs.key
# fix data on missing created date. us modified date
if not attrs.crd? or isNaN( parseInt( attrs.crd, 10 ) )
attrs.crd = @_rev2modDate( attrs.rev )
# fix empty acl data
if not attrs.acl? or attrs.acl not in [ "authenticated-read", "public-read" ]
attrs.acl = "authenticated-read"
return attrs
_rev2modDate: ( rev )=>
return @_now( parseInt( rev, 36 ) )
_now: ( date )=>
if date?
return Math.round( date/1000 )
else
return Math.round( Date.now()/1000 )
# Dynamo Helper Methods
_getItem: ( params, cb )=>
@debug "getItem", params
@client.getItem params, @_processDynamoItemReturn( cb )
return
_putItem: ( params, cb )=>
@debug "putItem", params
@client.putItem params, @_processDynamoPutReturn( cb )
return
_processDynamoItemReturn: ( cb )=>
return ( err, rawData )=>
if err
@_processDynamoError( cb, err )
return
@debug "_processDynamoItemReturn raw", rawData
attrs = @_convertItem( rawData.Item )
@debug "_processDynamoItemReturn", attrs
cb( null, attrs )
return
_processDynamoPutReturn: ( cb )=>
return ( err, rawData )=>
if err
@_processDynamoError( cb, err )
return
#@debug "_processDynamoPutReturn raw", rawData
attrs = {}
@debug "_processDynamoPutReturn", attrs
cb( null, attrs )
return
_convertItem: ( raw )=>
attrs = {}
for _k, _v of raw
_type = Object.keys( _v )[ 0 ]
switch _type
when "S"
attrs[ _k ] = _v[ _type ]
when "SS"
attrs[ _k ] = _v[ _type ]
when "N"
attrs[ _k ] = parseFloat( _v[ _type ] )
return attrs
_processDynamoError: ( cb, err )=>
if err.code is "ResourceNotFoundException"
@_handleError( cb, "EDYNAMOMISSINGTABLE", err )
return
cb( err )
return
ERRORS: =>
return @extend {}, super,
"EDYNAMOMISSINGTABLE": [ 400, "The dynamo table does not exist. Please generate it!" ]
"EDOMAINNOTFOUND": [ 404, "Domain `<%= domain %>` not found. The given domain has not been found in target DynamoDB" ]
"EMISSINGAWSACCESSKEY": [ 401, "Missing AWS Access Key. Please define the option `--awsaccesskey` or it's shortcut -a`" ]
"EMISSINGAWSSECRET": [ 401, "Missing AWS Secret. Please define the option `-awssecret` or it's shortcut `-s`" ]
"ECHECKINVALID": [ 500, "Its not possible to run start if the check has been failed" ]
module.exports = new Dynamo() | 30851 | AWS = require('aws-sdk')
_ = require 'lodash'
async = require "async"
config = require( "./config" )
class Dynamo extends require( "mpbasic" )( config )
defaults: =>
return @extend {}, super,
accessKeyId: null
secretAccessKey: null
region: "eu-west-1"
apiVersion: "2012-08-10"
tablenameDomains: null
tablenameFiles: null
ReturnConsumedCapacity: "TOTAL"
pumps: 10
batchsize: 25
constructor: ->
super
@checked = false
@c_domains = []
@wait = 0
@stateinfo =
capacityUnits: 0
Retries: 0
Errors: 0
#iTodo: 0
@pumping = false
@_configure()
return
_configure: =>
@debug "check", @config
if not @config.accessKeyId
@_handleError( false, "EMISSINGAWSACCESSKEY" )
return
if not @config.secretAccessKey
@_handleError( false, "EMISSINGAWSSECRET" )
return
@client = new AWS.DynamoDB( @config )
@checked = true
@emit "checked"
return
readDomain: ( domain, cb )=>
if not @checked
cb( @_handleError( true, "ECHECKINVALID" ) )
return
params =
TableName: @config.tablenameDomains
Key:
domain:
S: domain
@_getItem params, ( err, domainData )=>
if err
cb( err )
return
@debug "got domain", domainData
if domainData?.domain?
cb( null, domainData )
else
@_handleError( cb, "EDOMAINNOTFOUND", domain: domain )
return
return
migrate: ( domain, tuple, cb )=>
_attr = @_attr2Dynamo( domain, tuple )
@debug "migrate attrs `#{tuple.key}`", _attr, tuple
@update _attr, ( err, result )=>
if err
cb( err )
return
cb( null, result )
return
return
pump: ( domain, fnAddData, fnGetData )=>
if @pumping
return
@pumping = true
@emit "start.pump"
@debug "start pump"
aPumps = for i in [ 1..@config.pumps ]
@_pump( domain, fnAddData, fnGetData )
async.parallel aPumps, ( err, res )=>
@debug "async.parallel return"
@pumping = false
@debug "stop pump"
@emit "stop.pump"
return
return
throttle: =>
@wait += 50
@debug( "throttle #{ @wait }" )
return
accelerate: =>
if @wait - 50 <= 0
@wait = 0
else
@wait -= 50
@debug( "accelerate #{ @wait }" )
return
_pump: ( domain, fnAddData, fnGetData )=>
return ( cba )=>
@debug "_pump"
_sett = fnGetData( @config.batchsize )
if _sett.length > 0
@writeBatch domain, _sett, fnAddData, =>
@emit "data.pumped"
@debug "writeBatch return wait #{@wait}"
_.delay( @_pump( domain, fnAddData, fnGetData ), @wait, cba )
return
else
@debug "writeBatch empty"
cba()
return
writeBatch: ( domain, datas, fnAddData, cb )=>
_datas = []
for tuple in datas
if tuple.PutRequest?
_datas.push( tuple )
else
_datas.push( @_attr2Dynamo( domain, tuple ) )
_dynReq = @_createDynamoRequest( _datas )
@client.batchWriteItem _dynReq, ( err, res )=>
@debug "dynamo written", @wait, res?.ConsumedCapacity[ 0 ]?.CapacityUnits, res?.UnprocessedItems[ @config.tablenameFiles ]?.length or 0, res
if _.isNumber( res?.ConsumedCapacity?[ 0 ]?.CapacityUnits )
@stateinfo.capacityUnits += res?.ConsumedCapacity[ 0 ].CapacityUnits
if not _.isEmpty( res?.UnprocessedItems )
@throttle()
_putR = res?.UnprocessedItems[ @config.tablenameFiles ]
#<EMAIL>.iTodo += _putR.length
#<EMAIL>.capacityUnits -= _putR.length
@stateinfo.Retries += _putR.length
@debug "retry", _putR
fnAddData( _putR )
cb()
return
else
@accelerate()
if err? and err.statusCode isnt 200
@stateinfo.Errors += 1
@emit "data.error", err, _dynReq
@error( err )
cb()
return
cb()
return
return
_createDynamoRequest: ( _datas )=>
ret =
RequestItems: {}
ReturnConsumedCapacity: "TOTAL"
#ReturnItemCollectionMetrics: "SIZE"
_dyn = []
for data in _datas
try
if data.PutRequest?
_dyn.push data
else
item = @_createItem( data )
if item?
_dyn.push
PutRequest:
Item: item
catch _err
@error "error creating dynamo item", _err, JSON.stringify( data, 1,2 )
ret.RequestItems[ @config.tablenameFiles ] = _dyn
ret
_createItem: ( data )=>
_item =
key:
S: data.key
rev:
S: data.rev
fha:
S: data.fha
#url:
# S: data.url
ttl:
N: ( data.ttl or 0 ).toString()
cty:
S: data.cty
#cln:
# N: data.cln.toString()
acl:
S: data.acl
old:
N: data.old.toString()
crd:
N: data.crd.toString()
_u:
N: data._u.toString()
if not isNaN( data.cln )
_item.cln =
N: data.cln.toString()
if data.cdi?.length
_item.cdi =
S: data.cdi
if data.hgt > 0
_item.hgt =
N: data.hgt.toString()
if data.wdt > 0
_item.wdt =
N: data.wdt.toString()
if _.isString(data.prp)
_item.prp =
S: data.prp
else if data.prp? and Object.keys( data.prp ).length
_item.prp =
S: JSON.stringify( data.prp )
if data.tgs?.length
_item.tgs =
SS: data.tgs
return _item
update: ( data, cb )=>
params =
TableName: @config.tablenameFiles
Item: @_createItem( data )
ReturnConsumedCapacity: @config.ReturnConsumedCapacity
ReturnValues: "NONE"
@_putItem( params, cb )
return
# Attribute Mapping
attrMapping:
key: "key"
rev: "revision"
fha: "filehash"
#url: "url"
ttl: "ttl"
cty: "content_type"
cdi: "content_disposition"
cln: "content_length"
acl: "acl"
hgt: "height"
wdt: "width"
prp: "properties"
tgs: "tags"
old: "isRevision"
crd: "created"
_u: "version"
_attr2Dynamo: ( domain, inp )=>
attrs = {}
for _dyn, _api of @attrMapping
attrs[ _dyn ] = if inp[ _api ]? then inp[ _api ] else null
attrs.fha = domain.bucket + "/" + attrs.fha
attrs.key = domain.domain + ":" + attrs.key
# fix data on missing created date. us modified date
if not attrs.crd? or isNaN( parseInt( attrs.crd, 10 ) )
attrs.crd = @_rev2modDate( attrs.rev )
# fix empty acl data
if not attrs.acl? or attrs.acl not in [ "authenticated-read", "public-read" ]
attrs.acl = "authenticated-read"
return attrs
_rev2modDate: ( rev )=>
return @_now( parseInt( rev, 36 ) )
_now: ( date )=>
if date?
return Math.round( date/1000 )
else
return Math.round( Date.now()/1000 )
# Dynamo Helper Methods
_getItem: ( params, cb )=>
@debug "getItem", params
@client.getItem params, @_processDynamoItemReturn( cb )
return
_putItem: ( params, cb )=>
@debug "putItem", params
@client.putItem params, @_processDynamoPutReturn( cb )
return
_processDynamoItemReturn: ( cb )=>
return ( err, rawData )=>
if err
@_processDynamoError( cb, err )
return
@debug "_processDynamoItemReturn raw", rawData
attrs = @_convertItem( rawData.Item )
@debug "_processDynamoItemReturn", attrs
cb( null, attrs )
return
_processDynamoPutReturn: ( cb )=>
return ( err, rawData )=>
if err
@_processDynamoError( cb, err )
return
#@debug "_processDynamoPutReturn raw", rawData
attrs = {}
@debug "_processDynamoPutReturn", attrs
cb( null, attrs )
return
_convertItem: ( raw )=>
attrs = {}
for _k, _v of raw
_type = Object.keys( _v )[ 0 ]
switch _type
when "S"
attrs[ _k ] = _v[ _type ]
when "SS"
attrs[ _k ] = _v[ _type ]
when "N"
attrs[ _k ] = parseFloat( _v[ _type ] )
return attrs
_processDynamoError: ( cb, err )=>
if err.code is "ResourceNotFoundException"
@_handleError( cb, "EDYNAMOMISSINGTABLE", err )
return
cb( err )
return
ERRORS: =>
return @extend {}, super,
"EDYNAMOMISSINGTABLE": [ 400, "The dynamo table does not exist. Please generate it!" ]
"EDOMAINNOTFOUND": [ 404, "Domain `<%= domain %>` not found. The given domain has not been found in target DynamoDB" ]
"EMISSINGAWSACCESSKEY": [ 401, "Missing AWS Access Key. Please define the option `--awsaccesskey` or it's shortcut -a`" ]
"EMISSINGAWSSECRET": [ 401, "Missing AWS Secret. Please define the option `-awssecret` or it's shortcut `-s`" ]
"ECHECKINVALID": [ 500, "Its not possible to run start if the check has been failed" ]
module.exports = new Dynamo() | true | AWS = require('aws-sdk')
_ = require 'lodash'
async = require "async"
config = require( "./config" )
class Dynamo extends require( "mpbasic" )( config )
defaults: =>
return @extend {}, super,
accessKeyId: null
secretAccessKey: null
region: "eu-west-1"
apiVersion: "2012-08-10"
tablenameDomains: null
tablenameFiles: null
ReturnConsumedCapacity: "TOTAL"
pumps: 10
batchsize: 25
constructor: ->
super
@checked = false
@c_domains = []
@wait = 0
@stateinfo =
capacityUnits: 0
Retries: 0
Errors: 0
#iTodo: 0
@pumping = false
@_configure()
return
_configure: =>
@debug "check", @config
if not @config.accessKeyId
@_handleError( false, "EMISSINGAWSACCESSKEY" )
return
if not @config.secretAccessKey
@_handleError( false, "EMISSINGAWSSECRET" )
return
@client = new AWS.DynamoDB( @config )
@checked = true
@emit "checked"
return
readDomain: ( domain, cb )=>
if not @checked
cb( @_handleError( true, "ECHECKINVALID" ) )
return
params =
TableName: @config.tablenameDomains
Key:
domain:
S: domain
@_getItem params, ( err, domainData )=>
if err
cb( err )
return
@debug "got domain", domainData
if domainData?.domain?
cb( null, domainData )
else
@_handleError( cb, "EDOMAINNOTFOUND", domain: domain )
return
return
migrate: ( domain, tuple, cb )=>
_attr = @_attr2Dynamo( domain, tuple )
@debug "migrate attrs `#{tuple.key}`", _attr, tuple
@update _attr, ( err, result )=>
if err
cb( err )
return
cb( null, result )
return
return
pump: ( domain, fnAddData, fnGetData )=>
if @pumping
return
@pumping = true
@emit "start.pump"
@debug "start pump"
aPumps = for i in [ 1..@config.pumps ]
@_pump( domain, fnAddData, fnGetData )
async.parallel aPumps, ( err, res )=>
@debug "async.parallel return"
@pumping = false
@debug "stop pump"
@emit "stop.pump"
return
return
throttle: =>
@wait += 50
@debug( "throttle #{ @wait }" )
return
accelerate: =>
if @wait - 50 <= 0
@wait = 0
else
@wait -= 50
@debug( "accelerate #{ @wait }" )
return
_pump: ( domain, fnAddData, fnGetData )=>
return ( cba )=>
@debug "_pump"
_sett = fnGetData( @config.batchsize )
if _sett.length > 0
@writeBatch domain, _sett, fnAddData, =>
@emit "data.pumped"
@debug "writeBatch return wait #{@wait}"
_.delay( @_pump( domain, fnAddData, fnGetData ), @wait, cba )
return
else
@debug "writeBatch empty"
cba()
return
writeBatch: ( domain, datas, fnAddData, cb )=>
_datas = []
for tuple in datas
if tuple.PutRequest?
_datas.push( tuple )
else
_datas.push( @_attr2Dynamo( domain, tuple ) )
_dynReq = @_createDynamoRequest( _datas )
@client.batchWriteItem _dynReq, ( err, res )=>
@debug "dynamo written", @wait, res?.ConsumedCapacity[ 0 ]?.CapacityUnits, res?.UnprocessedItems[ @config.tablenameFiles ]?.length or 0, res
if _.isNumber( res?.ConsumedCapacity?[ 0 ]?.CapacityUnits )
@stateinfo.capacityUnits += res?.ConsumedCapacity[ 0 ].CapacityUnits
if not _.isEmpty( res?.UnprocessedItems )
@throttle()
_putR = res?.UnprocessedItems[ @config.tablenameFiles ]
#PI:EMAIL:<EMAIL>END_PI.iTodo += _putR.length
#PI:EMAIL:<EMAIL>END_PI.capacityUnits -= _putR.length
@stateinfo.Retries += _putR.length
@debug "retry", _putR
fnAddData( _putR )
cb()
return
else
@accelerate()
if err? and err.statusCode isnt 200
@stateinfo.Errors += 1
@emit "data.error", err, _dynReq
@error( err )
cb()
return
cb()
return
return
_createDynamoRequest: ( _datas )=>
ret =
RequestItems: {}
ReturnConsumedCapacity: "TOTAL"
#ReturnItemCollectionMetrics: "SIZE"
_dyn = []
for data in _datas
try
if data.PutRequest?
_dyn.push data
else
item = @_createItem( data )
if item?
_dyn.push
PutRequest:
Item: item
catch _err
@error "error creating dynamo item", _err, JSON.stringify( data, 1,2 )
ret.RequestItems[ @config.tablenameFiles ] = _dyn
ret
_createItem: ( data )=>
_item =
key:
S: data.key
rev:
S: data.rev
fha:
S: data.fha
#url:
# S: data.url
ttl:
N: ( data.ttl or 0 ).toString()
cty:
S: data.cty
#cln:
# N: data.cln.toString()
acl:
S: data.acl
old:
N: data.old.toString()
crd:
N: data.crd.toString()
_u:
N: data._u.toString()
if not isNaN( data.cln )
_item.cln =
N: data.cln.toString()
if data.cdi?.length
_item.cdi =
S: data.cdi
if data.hgt > 0
_item.hgt =
N: data.hgt.toString()
if data.wdt > 0
_item.wdt =
N: data.wdt.toString()
if _.isString(data.prp)
_item.prp =
S: data.prp
else if data.prp? and Object.keys( data.prp ).length
_item.prp =
S: JSON.stringify( data.prp )
if data.tgs?.length
_item.tgs =
SS: data.tgs
return _item
update: ( data, cb )=>
params =
TableName: @config.tablenameFiles
Item: @_createItem( data )
ReturnConsumedCapacity: @config.ReturnConsumedCapacity
ReturnValues: "NONE"
@_putItem( params, cb )
return
# Attribute Mapping
attrMapping:
key: "key"
rev: "revision"
fha: "filehash"
#url: "url"
ttl: "ttl"
cty: "content_type"
cdi: "content_disposition"
cln: "content_length"
acl: "acl"
hgt: "height"
wdt: "width"
prp: "properties"
tgs: "tags"
old: "isRevision"
crd: "created"
_u: "version"
_attr2Dynamo: ( domain, inp )=>
attrs = {}
for _dyn, _api of @attrMapping
attrs[ _dyn ] = if inp[ _api ]? then inp[ _api ] else null
attrs.fha = domain.bucket + "/" + attrs.fha
attrs.key = domain.domain + ":" + attrs.key
# fix data on missing created date. us modified date
if not attrs.crd? or isNaN( parseInt( attrs.crd, 10 ) )
attrs.crd = @_rev2modDate( attrs.rev )
# fix empty acl data
if not attrs.acl? or attrs.acl not in [ "authenticated-read", "public-read" ]
attrs.acl = "authenticated-read"
return attrs
_rev2modDate: ( rev )=>
return @_now( parseInt( rev, 36 ) )
_now: ( date )=>
if date?
return Math.round( date/1000 )
else
return Math.round( Date.now()/1000 )
# Dynamo Helper Methods
_getItem: ( params, cb )=>
@debug "getItem", params
@client.getItem params, @_processDynamoItemReturn( cb )
return
_putItem: ( params, cb )=>
@debug "putItem", params
@client.putItem params, @_processDynamoPutReturn( cb )
return
_processDynamoItemReturn: ( cb )=>
return ( err, rawData )=>
if err
@_processDynamoError( cb, err )
return
@debug "_processDynamoItemReturn raw", rawData
attrs = @_convertItem( rawData.Item )
@debug "_processDynamoItemReturn", attrs
cb( null, attrs )
return
_processDynamoPutReturn: ( cb )=>
return ( err, rawData )=>
if err
@_processDynamoError( cb, err )
return
#@debug "_processDynamoPutReturn raw", rawData
attrs = {}
@debug "_processDynamoPutReturn", attrs
cb( null, attrs )
return
_convertItem: ( raw )=>
attrs = {}
for _k, _v of raw
_type = Object.keys( _v )[ 0 ]
switch _type
when "S"
attrs[ _k ] = _v[ _type ]
when "SS"
attrs[ _k ] = _v[ _type ]
when "N"
attrs[ _k ] = parseFloat( _v[ _type ] )
return attrs
_processDynamoError: ( cb, err )=>
if err.code is "ResourceNotFoundException"
@_handleError( cb, "EDYNAMOMISSINGTABLE", err )
return
cb( err )
return
ERRORS: =>
return @extend {}, super,
"EDYNAMOMISSINGTABLE": [ 400, "The dynamo table does not exist. Please generate it!" ]
"EDOMAINNOTFOUND": [ 404, "Domain `<%= domain %>` not found. The given domain has not been found in target DynamoDB" ]
"EMISSINGAWSACCESSKEY": [ 401, "Missing AWS Access Key. Please define the option `--awsaccesskey` or it's shortcut -a`" ]
"EMISSINGAWSSECRET": [ 401, "Missing AWS Secret. Please define the option `-awssecret` or it's shortcut `-s`" ]
"ECHECKINVALID": [ 500, "Its not possible to run start if the check has been failed" ]
module.exports = new Dynamo() |
[
{
"context": " describe \"/temp\", ->\n userData = {username: 'temp', password: '2'}\n cookies = null\n\n it \"Shou",
"end": 181,
"score": 0.9962843656539917,
"start": 177,
"tag": "USERNAME",
"value": "temp"
},
{
"context": ", ->\n userData = {username: 'temp', password: '2'}\n cookies = null\n\n it \"Should create a tem",
"end": 196,
"score": 0.9993482232093811,
"start": 195,
"tag": "PASSWORD",
"value": "2"
}
] | lobby/test/int/controllers/auth-int-test.coffee | towerstorm/game | 11 | app = require('../../../lib/app.coffee')
request = require("supertest")(app)
assert = require('assert')
describe "/auth", ->
describe "/temp", ->
userData = {username: 'temp', password: '2'}
cookies = null
it "Should create a temporary user when called with username and password variables", (done) ->
request.get('/auth/temp')
.send(userData)
.expect('Content-Type', /json/)
.expect(200)
.end (err, res) ->
if err then return done(err)
cookies = res.headers['set-cookie'].pop().split(';')[0];
done()
it "Should be able to access /user after it's created", (done) ->
request.get('/auth/temp').send(userData).end (err, res) ->
req = request.get('/user/')
req.cookies = cookies
req.expect(200)
.end (err, res) ->
if err then return done(err)
userInfo = JSON.parse(res.text)
assert.equal(userInfo.stormPoints, 0);
done()
| 153216 | app = require('../../../lib/app.coffee')
request = require("supertest")(app)
assert = require('assert')
describe "/auth", ->
describe "/temp", ->
userData = {username: 'temp', password: '<PASSWORD>'}
cookies = null
it "Should create a temporary user when called with username and password variables", (done) ->
request.get('/auth/temp')
.send(userData)
.expect('Content-Type', /json/)
.expect(200)
.end (err, res) ->
if err then return done(err)
cookies = res.headers['set-cookie'].pop().split(';')[0];
done()
it "Should be able to access /user after it's created", (done) ->
request.get('/auth/temp').send(userData).end (err, res) ->
req = request.get('/user/')
req.cookies = cookies
req.expect(200)
.end (err, res) ->
if err then return done(err)
userInfo = JSON.parse(res.text)
assert.equal(userInfo.stormPoints, 0);
done()
| true | app = require('../../../lib/app.coffee')
request = require("supertest")(app)
assert = require('assert')
describe "/auth", ->
describe "/temp", ->
userData = {username: 'temp', password: 'PI:PASSWORD:<PASSWORD>END_PI'}
cookies = null
it "Should create a temporary user when called with username and password variables", (done) ->
request.get('/auth/temp')
.send(userData)
.expect('Content-Type', /json/)
.expect(200)
.end (err, res) ->
if err then return done(err)
cookies = res.headers['set-cookie'].pop().split(';')[0];
done()
it "Should be able to access /user after it's created", (done) ->
request.get('/auth/temp').send(userData).end (err, res) ->
req = request.get('/user/')
req.cookies = cookies
req.expect(200)
.end (err, res) ->
if err then return done(err)
userInfo = JSON.parse(res.text)
assert.equal(userInfo.stormPoints, 0);
done()
|
[
{
"context": " @namespace COOLSTRAP\n * @class App\n * \n * @author Abraham Barrera <abarrerac@gmail.com> || @abraham_barrera\n * \n###",
"end": 125,
"score": 0.9998928308486938,
"start": 110,
"tag": "NAME",
"value": "Abraham Barrera"
},
{
"context": "RAP\n * @class App\n * \n * @author Abraham Barrera <abarrerac@gmail.com> || @abraham_barrera\n * \n###\n\n# Main App Namespac",
"end": 146,
"score": 0.9999316930770874,
"start": 127,
"tag": "EMAIL",
"value": "abarrerac@gmail.com"
},
{
"context": "* @author Abraham Barrera <abarrerac@gmail.com> || @abraham_barrera\n * \n###\n\n# Main App Namespace\nCOOLSTRAP.App = ((c",
"end": 167,
"score": 0.9995003938674927,
"start": 151,
"tag": "USERNAME",
"value": "@abraham_barrera"
}
] | coolstrap-core/app/assets/javascripts/coolstrap/_Coolstrap.App.coffee | cristianferrarig/coolstrap | 0 | ###
* Coolstrapp Application
* Inspired by LungoJs
*
* @namespace COOLSTRAP
* @class App
*
* @author Abraham Barrera <abarrerac@gmail.com> || @abraham_barrera
*
###
# Main App Namespace
COOLSTRAP.App = ((cool) ->
_sessionId = undefined
_launchOptions =
name: "coolstrap"
log_level: -1
# setup framework
_setupFramework = ->
cool.Framework.Sections.setup()
cool.Framework.Articles.setup()
cool.Framework.Navigation.setup()
# generate session id
_generateSID = ->
_sessionId = "123456"
# init coolstrap app
init = (launch_options) ->
_launchOptions = cool.Util.Core.extend(_launchOptions, launch_options)
_setupFramework()
_generateSID()
init: init
launchOptions: _launchOptions
sessionId: _sessionId
)(COOLSTRAP) | 18541 | ###
* Coolstrapp Application
* Inspired by LungoJs
*
* @namespace COOLSTRAP
* @class App
*
* @author <NAME> <<EMAIL>> || @abraham_barrera
*
###
# Main App Namespace
COOLSTRAP.App = ((cool) ->
_sessionId = undefined
_launchOptions =
name: "coolstrap"
log_level: -1
# setup framework
_setupFramework = ->
cool.Framework.Sections.setup()
cool.Framework.Articles.setup()
cool.Framework.Navigation.setup()
# generate session id
_generateSID = ->
_sessionId = "123456"
# init coolstrap app
init = (launch_options) ->
_launchOptions = cool.Util.Core.extend(_launchOptions, launch_options)
_setupFramework()
_generateSID()
init: init
launchOptions: _launchOptions
sessionId: _sessionId
)(COOLSTRAP) | true | ###
* Coolstrapp Application
* Inspired by LungoJs
*
* @namespace COOLSTRAP
* @class App
*
* @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> || @abraham_barrera
*
###
# Main App Namespace
COOLSTRAP.App = ((cool) ->
_sessionId = undefined
_launchOptions =
name: "coolstrap"
log_level: -1
# setup framework
_setupFramework = ->
cool.Framework.Sections.setup()
cool.Framework.Articles.setup()
cool.Framework.Navigation.setup()
# generate session id
_generateSID = ->
_sessionId = "123456"
# init coolstrap app
init = (launch_options) ->
_launchOptions = cool.Util.Core.extend(_launchOptions, launch_options)
_setupFramework()
_generateSID()
init: init
launchOptions: _launchOptions
sessionId: _sessionId
)(COOLSTRAP) |
[
{
"context": "one) ->\n process.env.HUBOT_GITHUB_TOKEN = \"789abc\"\n network.matchHeader(\"Authorization\", \"to",
"end": 912,
"score": 0.9856200814247131,
"start": 906,
"tag": "PASSWORD",
"value": "789abc"
},
{
"context": " network.matchHeader(\"Authorization\", \"token 789abc\")\n gh.request \"GET\", \"repos/foo/bar/branch",
"end": 972,
"score": 0.9809585809707642,
"start": 966,
"tag": "PASSWORD",
"value": "789abc"
},
{
"context": "one) ->\n process.env.HUBOT_GITHUB_TOKEN = \"789xyz\"\n network.matchHeader(\"Authorization\", \"to",
"end": 2195,
"score": 0.9647011756896973,
"start": 2189,
"tag": "PASSWORD",
"value": "789xyz"
},
{
"context": "ion\", \"token abc\")\n gh.withOptions(token: 'abc').request \"GET\", \"repos/foo/bar/branches\", succes",
"end": 2289,
"score": 0.5765072703361511,
"start": 2286,
"tag": "KEY",
"value": "abc"
}
] | test/request.coffee | dennybaa/githubot | 68 | [ gh, assert, nock, mock_robot ] = require "./test_helper"
describe "github api", ->
describe "general purpose", ->
network = null
success = (done) ->
(body) ->
network.done()
done()
describe "request", ->
response = [ { name: "foo", commit: { sha: "abcdef", url: "xxx" } } ]
beforeEach ->
network = nock("https://api.github.com")
.get("/repos/foo/bar/branches")
.reply(200, response)
it "accepts a full url", (done) ->
gh.request "GET", "https://api.github.com/repos/foo/bar/branches", success done
it "accepts a path", (done) ->
gh.request "GET", "repos/foo/bar/branches", success done
it "accepts a path (leading slash)", (done) ->
gh.request "GET", "repos/foo/bar/branches", success done
it "includes oauth token if exists", (done) ->
process.env.HUBOT_GITHUB_TOKEN = "789abc"
network.matchHeader("Authorization", "token 789abc")
gh.request "GET", "repos/foo/bar/branches", success done
delete process.env.HUBOT_GITHUB_TOKEN
it "includes accept header", (done) ->
network.matchHeader('Accept', 'application/vnd.github.v3+json')
gh.request "GET", "repos/foo/bar/branches", success done
it "allows setting API version", (done) ->
ghPreview = require("../src/githubot") mock_robot, apiVersion: 'preview'
network.matchHeader('Accept', 'application/vnd.github.preview+json')
ghPreview.request "GET", "repos/foo/bar/branches", success done
it "allows setting API version for single request", (done) ->
network.matchHeader('Accept', 'application/vnd.github.special+json')
gh.withOptions(apiVersion: 'special').request "GET", "repos/foo/bar/branches", success done
it "allows setting an API version for single request without robot", (done) ->
noRobot = require("../src/githubot")
newGh = noRobot.withOptions('Accept', 'application/vnd.github.preview+json')
newGh.request "GET", "repos/foo/bar/branches", success done
it "allows setting the oauth token for single request", (done) ->
process.env.HUBOT_GITHUB_TOKEN = "789xyz"
network.matchHeader("Authorization", "token abc")
gh.withOptions(token: 'abc').request "GET", "repos/foo/bar/branches", success done
delete process.env.HUBOT_GITHUB_TOKEN
it "doesn't persist per-request options", (done) ->
network.matchHeader('Accept', 'application/vnd.github.special+json')
gh.withOptions(apiVersion: 'special').request "GET", "repos/foo/bar/branches", ->
network.done()
network2 = nock("https://api.github.com")
.get("/repos/baz/bar/branches")
.matchHeader('Accept', 'application/vnd.github.v3+json')
.reply(200, response)
# Should revert to the defaults on this request
gh.request "GET", "repos/baz/bar/branches", ->
network2.done()
done()
it "includes User-Agent header", (done) ->
network.matchHeader('User-Agent', /GitHubot\/\d+\.\d+\.\d+/)
gh.request "GET", "repos/foo/bar/branches", success done
it "returns parsed json", (done) ->
gh.request "GET", "repos/foo/bar/branches", (data) ->
assert.deepEqual response, data
done()
context "custom base URL", ->
beforeEach ->
network = nock("http://mygithub.internal")
.get("/repos/foo/bar/branches")
.reply(200, response)
it "is used if option exists", (done) ->
process.env.HUBOT_GITHUB_API = "http://mygithub.internal"
gh.request "GET", "repos/foo/bar/branches", success done
delete process.env.HUBOT_GITHUB_API
it "is used if passed explicitly", (done) ->
gh.request "GET", "http://mygithub.internal/repos/foo/bar/branches", success done
describe "get", ->
beforeEach ->
network = nock("https://api.github.com")
.get("/gists")
.reply(200, [])
it "sends request", (done) ->
gh.get "gists", success done
describe "with params", ->
beforeEach ->
network = nock("https://api.github.com")
.get("/users/foo/repos?foo=bar")
.reply(200, [])
it "accepts query params in url", (done) ->
gh.get "https://api.github.com/users/foo/repos?foo=bar", success done
it "accepts query params as hash", (done) ->
gh.get "users/foo/repos", {foo: "bar"}, success done
describe "post", ->
data = description: "A test gist", public: true, files: { "abc.txt": { content: "abcdefg" } }
response = url: "http://api.github.com/gists/1", id: 1
beforeEach ->
network = nock("https://api.github.com")
.post("/gists", data)
.reply(201, response)
it "sends request", (done) ->
gh.post "gists", data, success done
describe "put", ->
data = description: "A test gist", public: true, files: { "abc.txt": { content: "abcdefg" } }
response = url: "http://api.github.com/gists/1", id: 1
beforeEach ->
network = nock("https://api.github.com")
.put("/gists", data)
.reply(201, response)
it "sends request", (done) ->
gh.put "gists", data, success done
describe "patch", ->
data = description: "A test gist", public: true, files: { "abc.txt": { content: "abcdefg" } }
response = url: "http://api.github.com/gists/1", id: 1
beforeEach ->
network = nock("https://api.github.com")
.patch("/gists", data)
.reply(201, response)
it "sends request", (done) ->
gh.patch "gists", data, success done
describe "delete", ->
it "sends request", (done) ->
network = nock("https://api.github.com")
.delete("/gists/345")
.reply(204)
gh.delete "gists/345", success done
it "includes empty body", (done) ->
network = nock("https://api.github.com")
.delete("/gists/345", "")
.matchHeader("Content-Length", 0)
.reply(204)
gh.delete "gists/345", success done
describe "errors", ->
network = null
http = require "scoped-http-client"
never_called = ->
assert.fail(null, null, "Success callback should not be invoked")
beforeEach ->
network = nock("https://api.github.com").get("/foo")
afterEach ->
mock_robot.onError = null
kablooie = ->
mock = {
header: -> mock,
get: () -> (cb) ->
cb new Error "Kablooie!"
}
http._old_create = http.create
http.create = -> mock
afterEach ->
if http._old_create?
http.create = http._old_create
http._old_create = null
it "complains about failed response", (done) ->
network.reply(401, message: "Bad credentials")
mock_robot.onError = (msg) ->
assert.ok /bad credentials/i.exec msg
done()
gh.get "/foo", never_called
it "complains about bad response", (done) ->
network.reply(500, "WTF$$%@! SERVER VOMIT")
mock_robot.onError = (msg) ->
assert.ok /vomit/i.exec msg
done()
gh.get "/foo", never_called
it "complains about client errors", (done) ->
kablooie()
mock_robot.onError = (msg) ->
assert.ok /kablooie/i.exec msg
done()
gh.get "/foo", never_called
describe "with error handler", ->
defaultHandler = gh._errorHandler
beforeEach ->
network = nock("https://api.github.com")
.get("/foo")
afterEach ->
gh._errorHandler = defaultHandler
it "calls handler on error", (done) ->
network.reply(406, message: "I hate you!")
gh.handleErrors (response) ->
assert.equal 406, response.statusCode
assert.equal "I hate you!", response.error
assert.equal '{"message":"I hate you!"}', response.body
done()
gh.get "/foo", never_called
it "doesn't call handler on success", (done) ->
network.reply(201, message: "Hooray!")
gh.handleErrors never_called
gh.get "/foo", -> done()
it "passes body if can't parse response", (done) ->
network.reply(500, "WTF$$%@! SERVER VOMIT")
gh.handleErrors (response) ->
assert.equal 500, response.statusCode
assert.equal "WTF$$%@! SERVER VOMIT", response.body
done()
gh.get "/foo", never_called
it "passes error if request failed", (done) ->
kablooie()
gh.handleErrors (response) ->
assert.ok /kablooie/i.exec response.error
done()
gh.get "/foo", never_called
it "still logs errors", (done) ->
network.reply(406, message: "I hate you!")
expected = 2
cb = ->
expected -= 1
done() if expected is 0
mock_robot.onError = cb
gh.handleErrors cb
gh.get "/foo", never_called
it "works in combination with withOptions", (done) ->
network.matchHeader('Accept', 'application/vnd.github.special+json')
network.reply(406, message: "I hate you!")
gh.handleErrors (response) ->
assert.equal 406, response.statusCode
done()
gh.withOptions(apiVersion: 'special').get "/foo", never_called
it "can be passed as withOptions", (done) ->
network.reply(406, message: "I hate you!")
errHandler = (response) ->
assert.equal 406, response.statusCode
done()
gh.withOptions(errorHandler: errHandler).get "/foo", never_called
describe "without robot given", ->
before ->
gh = require("../src/githubot")
it "complains to stderr", (done) ->
console._old_error = console.error
console.error = (msg) ->
if msg.match /bad credentials/i
console.error = @_old_error
done()
else
@_old_error.call process.stderr, msg
network.reply(401, message: "Bad credentials!")
gh.get "/foo", never_called
| 210518 | [ gh, assert, nock, mock_robot ] = require "./test_helper"
describe "github api", ->
describe "general purpose", ->
network = null
success = (done) ->
(body) ->
network.done()
done()
describe "request", ->
response = [ { name: "foo", commit: { sha: "abcdef", url: "xxx" } } ]
beforeEach ->
network = nock("https://api.github.com")
.get("/repos/foo/bar/branches")
.reply(200, response)
it "accepts a full url", (done) ->
gh.request "GET", "https://api.github.com/repos/foo/bar/branches", success done
it "accepts a path", (done) ->
gh.request "GET", "repos/foo/bar/branches", success done
it "accepts a path (leading slash)", (done) ->
gh.request "GET", "repos/foo/bar/branches", success done
it "includes oauth token if exists", (done) ->
process.env.HUBOT_GITHUB_TOKEN = "<PASSWORD>"
network.matchHeader("Authorization", "token <PASSWORD>")
gh.request "GET", "repos/foo/bar/branches", success done
delete process.env.HUBOT_GITHUB_TOKEN
it "includes accept header", (done) ->
network.matchHeader('Accept', 'application/vnd.github.v3+json')
gh.request "GET", "repos/foo/bar/branches", success done
it "allows setting API version", (done) ->
ghPreview = require("../src/githubot") mock_robot, apiVersion: 'preview'
network.matchHeader('Accept', 'application/vnd.github.preview+json')
ghPreview.request "GET", "repos/foo/bar/branches", success done
it "allows setting API version for single request", (done) ->
network.matchHeader('Accept', 'application/vnd.github.special+json')
gh.withOptions(apiVersion: 'special').request "GET", "repos/foo/bar/branches", success done
it "allows setting an API version for single request without robot", (done) ->
noRobot = require("../src/githubot")
newGh = noRobot.withOptions('Accept', 'application/vnd.github.preview+json')
newGh.request "GET", "repos/foo/bar/branches", success done
it "allows setting the oauth token for single request", (done) ->
process.env.HUBOT_GITHUB_TOKEN = "<PASSWORD>"
network.matchHeader("Authorization", "token abc")
gh.withOptions(token: '<KEY>').request "GET", "repos/foo/bar/branches", success done
delete process.env.HUBOT_GITHUB_TOKEN
it "doesn't persist per-request options", (done) ->
network.matchHeader('Accept', 'application/vnd.github.special+json')
gh.withOptions(apiVersion: 'special').request "GET", "repos/foo/bar/branches", ->
network.done()
network2 = nock("https://api.github.com")
.get("/repos/baz/bar/branches")
.matchHeader('Accept', 'application/vnd.github.v3+json')
.reply(200, response)
# Should revert to the defaults on this request
gh.request "GET", "repos/baz/bar/branches", ->
network2.done()
done()
it "includes User-Agent header", (done) ->
network.matchHeader('User-Agent', /GitHubot\/\d+\.\d+\.\d+/)
gh.request "GET", "repos/foo/bar/branches", success done
it "returns parsed json", (done) ->
gh.request "GET", "repos/foo/bar/branches", (data) ->
assert.deepEqual response, data
done()
context "custom base URL", ->
beforeEach ->
network = nock("http://mygithub.internal")
.get("/repos/foo/bar/branches")
.reply(200, response)
it "is used if option exists", (done) ->
process.env.HUBOT_GITHUB_API = "http://mygithub.internal"
gh.request "GET", "repos/foo/bar/branches", success done
delete process.env.HUBOT_GITHUB_API
it "is used if passed explicitly", (done) ->
gh.request "GET", "http://mygithub.internal/repos/foo/bar/branches", success done
describe "get", ->
beforeEach ->
network = nock("https://api.github.com")
.get("/gists")
.reply(200, [])
it "sends request", (done) ->
gh.get "gists", success done
describe "with params", ->
beforeEach ->
network = nock("https://api.github.com")
.get("/users/foo/repos?foo=bar")
.reply(200, [])
it "accepts query params in url", (done) ->
gh.get "https://api.github.com/users/foo/repos?foo=bar", success done
it "accepts query params as hash", (done) ->
gh.get "users/foo/repos", {foo: "bar"}, success done
describe "post", ->
data = description: "A test gist", public: true, files: { "abc.txt": { content: "abcdefg" } }
response = url: "http://api.github.com/gists/1", id: 1
beforeEach ->
network = nock("https://api.github.com")
.post("/gists", data)
.reply(201, response)
it "sends request", (done) ->
gh.post "gists", data, success done
describe "put", ->
data = description: "A test gist", public: true, files: { "abc.txt": { content: "abcdefg" } }
response = url: "http://api.github.com/gists/1", id: 1
beforeEach ->
network = nock("https://api.github.com")
.put("/gists", data)
.reply(201, response)
it "sends request", (done) ->
gh.put "gists", data, success done
describe "patch", ->
data = description: "A test gist", public: true, files: { "abc.txt": { content: "abcdefg" } }
response = url: "http://api.github.com/gists/1", id: 1
beforeEach ->
network = nock("https://api.github.com")
.patch("/gists", data)
.reply(201, response)
it "sends request", (done) ->
gh.patch "gists", data, success done
describe "delete", ->
it "sends request", (done) ->
network = nock("https://api.github.com")
.delete("/gists/345")
.reply(204)
gh.delete "gists/345", success done
it "includes empty body", (done) ->
network = nock("https://api.github.com")
.delete("/gists/345", "")
.matchHeader("Content-Length", 0)
.reply(204)
gh.delete "gists/345", success done
describe "errors", ->
network = null
http = require "scoped-http-client"
never_called = ->
assert.fail(null, null, "Success callback should not be invoked")
beforeEach ->
network = nock("https://api.github.com").get("/foo")
afterEach ->
mock_robot.onError = null
kablooie = ->
mock = {
header: -> mock,
get: () -> (cb) ->
cb new Error "Kablooie!"
}
http._old_create = http.create
http.create = -> mock
afterEach ->
if http._old_create?
http.create = http._old_create
http._old_create = null
it "complains about failed response", (done) ->
network.reply(401, message: "Bad credentials")
mock_robot.onError = (msg) ->
assert.ok /bad credentials/i.exec msg
done()
gh.get "/foo", never_called
it "complains about bad response", (done) ->
network.reply(500, "WTF$$%@! SERVER VOMIT")
mock_robot.onError = (msg) ->
assert.ok /vomit/i.exec msg
done()
gh.get "/foo", never_called
it "complains about client errors", (done) ->
kablooie()
mock_robot.onError = (msg) ->
assert.ok /kablooie/i.exec msg
done()
gh.get "/foo", never_called
describe "with error handler", ->
defaultHandler = gh._errorHandler
beforeEach ->
network = nock("https://api.github.com")
.get("/foo")
afterEach ->
gh._errorHandler = defaultHandler
it "calls handler on error", (done) ->
network.reply(406, message: "I hate you!")
gh.handleErrors (response) ->
assert.equal 406, response.statusCode
assert.equal "I hate you!", response.error
assert.equal '{"message":"I hate you!"}', response.body
done()
gh.get "/foo", never_called
it "doesn't call handler on success", (done) ->
network.reply(201, message: "Hooray!")
gh.handleErrors never_called
gh.get "/foo", -> done()
it "passes body if can't parse response", (done) ->
network.reply(500, "WTF$$%@! SERVER VOMIT")
gh.handleErrors (response) ->
assert.equal 500, response.statusCode
assert.equal "WTF$$%@! SERVER VOMIT", response.body
done()
gh.get "/foo", never_called
it "passes error if request failed", (done) ->
kablooie()
gh.handleErrors (response) ->
assert.ok /kablooie/i.exec response.error
done()
gh.get "/foo", never_called
it "still logs errors", (done) ->
network.reply(406, message: "I hate you!")
expected = 2
cb = ->
expected -= 1
done() if expected is 0
mock_robot.onError = cb
gh.handleErrors cb
gh.get "/foo", never_called
it "works in combination with withOptions", (done) ->
network.matchHeader('Accept', 'application/vnd.github.special+json')
network.reply(406, message: "I hate you!")
gh.handleErrors (response) ->
assert.equal 406, response.statusCode
done()
gh.withOptions(apiVersion: 'special').get "/foo", never_called
it "can be passed as withOptions", (done) ->
network.reply(406, message: "I hate you!")
errHandler = (response) ->
assert.equal 406, response.statusCode
done()
gh.withOptions(errorHandler: errHandler).get "/foo", never_called
describe "without robot given", ->
before ->
gh = require("../src/githubot")
it "complains to stderr", (done) ->
console._old_error = console.error
console.error = (msg) ->
if msg.match /bad credentials/i
console.error = @_old_error
done()
else
@_old_error.call process.stderr, msg
network.reply(401, message: "Bad credentials!")
gh.get "/foo", never_called
| true | [ gh, assert, nock, mock_robot ] = require "./test_helper"
describe "github api", ->
describe "general purpose", ->
network = null
success = (done) ->
(body) ->
network.done()
done()
describe "request", ->
response = [ { name: "foo", commit: { sha: "abcdef", url: "xxx" } } ]
beforeEach ->
network = nock("https://api.github.com")
.get("/repos/foo/bar/branches")
.reply(200, response)
it "accepts a full url", (done) ->
gh.request "GET", "https://api.github.com/repos/foo/bar/branches", success done
it "accepts a path", (done) ->
gh.request "GET", "repos/foo/bar/branches", success done
it "accepts a path (leading slash)", (done) ->
gh.request "GET", "repos/foo/bar/branches", success done
it "includes oauth token if exists", (done) ->
process.env.HUBOT_GITHUB_TOKEN = "PI:PASSWORD:<PASSWORD>END_PI"
network.matchHeader("Authorization", "token PI:PASSWORD:<PASSWORD>END_PI")
gh.request "GET", "repos/foo/bar/branches", success done
delete process.env.HUBOT_GITHUB_TOKEN
it "includes accept header", (done) ->
network.matchHeader('Accept', 'application/vnd.github.v3+json')
gh.request "GET", "repos/foo/bar/branches", success done
it "allows setting API version", (done) ->
ghPreview = require("../src/githubot") mock_robot, apiVersion: 'preview'
network.matchHeader('Accept', 'application/vnd.github.preview+json')
ghPreview.request "GET", "repos/foo/bar/branches", success done
it "allows setting API version for single request", (done) ->
network.matchHeader('Accept', 'application/vnd.github.special+json')
gh.withOptions(apiVersion: 'special').request "GET", "repos/foo/bar/branches", success done
it "allows setting an API version for single request without robot", (done) ->
noRobot = require("../src/githubot")
newGh = noRobot.withOptions('Accept', 'application/vnd.github.preview+json')
newGh.request "GET", "repos/foo/bar/branches", success done
it "allows setting the oauth token for single request", (done) ->
process.env.HUBOT_GITHUB_TOKEN = "PI:PASSWORD:<PASSWORD>END_PI"
network.matchHeader("Authorization", "token abc")
gh.withOptions(token: 'PI:KEY:<KEY>END_PI').request "GET", "repos/foo/bar/branches", success done
delete process.env.HUBOT_GITHUB_TOKEN
it "doesn't persist per-request options", (done) ->
network.matchHeader('Accept', 'application/vnd.github.special+json')
gh.withOptions(apiVersion: 'special').request "GET", "repos/foo/bar/branches", ->
network.done()
network2 = nock("https://api.github.com")
.get("/repos/baz/bar/branches")
.matchHeader('Accept', 'application/vnd.github.v3+json')
.reply(200, response)
# Should revert to the defaults on this request
gh.request "GET", "repos/baz/bar/branches", ->
network2.done()
done()
it "includes User-Agent header", (done) ->
network.matchHeader('User-Agent', /GitHubot\/\d+\.\d+\.\d+/)
gh.request "GET", "repos/foo/bar/branches", success done
it "returns parsed json", (done) ->
gh.request "GET", "repos/foo/bar/branches", (data) ->
assert.deepEqual response, data
done()
context "custom base URL", ->
beforeEach ->
network = nock("http://mygithub.internal")
.get("/repos/foo/bar/branches")
.reply(200, response)
it "is used if option exists", (done) ->
process.env.HUBOT_GITHUB_API = "http://mygithub.internal"
gh.request "GET", "repos/foo/bar/branches", success done
delete process.env.HUBOT_GITHUB_API
it "is used if passed explicitly", (done) ->
gh.request "GET", "http://mygithub.internal/repos/foo/bar/branches", success done
describe "get", ->
beforeEach ->
network = nock("https://api.github.com")
.get("/gists")
.reply(200, [])
it "sends request", (done) ->
gh.get "gists", success done
describe "with params", ->
beforeEach ->
network = nock("https://api.github.com")
.get("/users/foo/repos?foo=bar")
.reply(200, [])
it "accepts query params in url", (done) ->
gh.get "https://api.github.com/users/foo/repos?foo=bar", success done
it "accepts query params as hash", (done) ->
gh.get "users/foo/repos", {foo: "bar"}, success done
describe "post", ->
data = description: "A test gist", public: true, files: { "abc.txt": { content: "abcdefg" } }
response = url: "http://api.github.com/gists/1", id: 1
beforeEach ->
network = nock("https://api.github.com")
.post("/gists", data)
.reply(201, response)
it "sends request", (done) ->
gh.post "gists", data, success done
describe "put", ->
data = description: "A test gist", public: true, files: { "abc.txt": { content: "abcdefg" } }
response = url: "http://api.github.com/gists/1", id: 1
beforeEach ->
network = nock("https://api.github.com")
.put("/gists", data)
.reply(201, response)
it "sends request", (done) ->
gh.put "gists", data, success done
describe "patch", ->
data = description: "A test gist", public: true, files: { "abc.txt": { content: "abcdefg" } }
response = url: "http://api.github.com/gists/1", id: 1
beforeEach ->
network = nock("https://api.github.com")
.patch("/gists", data)
.reply(201, response)
it "sends request", (done) ->
gh.patch "gists", data, success done
describe "delete", ->
it "sends request", (done) ->
network = nock("https://api.github.com")
.delete("/gists/345")
.reply(204)
gh.delete "gists/345", success done
it "includes empty body", (done) ->
network = nock("https://api.github.com")
.delete("/gists/345", "")
.matchHeader("Content-Length", 0)
.reply(204)
gh.delete "gists/345", success done
describe "errors", ->
network = null
http = require "scoped-http-client"
never_called = ->
assert.fail(null, null, "Success callback should not be invoked")
beforeEach ->
network = nock("https://api.github.com").get("/foo")
afterEach ->
mock_robot.onError = null
kablooie = ->
mock = {
header: -> mock,
get: () -> (cb) ->
cb new Error "Kablooie!"
}
http._old_create = http.create
http.create = -> mock
afterEach ->
if http._old_create?
http.create = http._old_create
http._old_create = null
it "complains about failed response", (done) ->
network.reply(401, message: "Bad credentials")
mock_robot.onError = (msg) ->
assert.ok /bad credentials/i.exec msg
done()
gh.get "/foo", never_called
it "complains about bad response", (done) ->
network.reply(500, "WTF$$%@! SERVER VOMIT")
mock_robot.onError = (msg) ->
assert.ok /vomit/i.exec msg
done()
gh.get "/foo", never_called
it "complains about client errors", (done) ->
kablooie()
mock_robot.onError = (msg) ->
assert.ok /kablooie/i.exec msg
done()
gh.get "/foo", never_called
describe "with error handler", ->
defaultHandler = gh._errorHandler
beforeEach ->
network = nock("https://api.github.com")
.get("/foo")
afterEach ->
gh._errorHandler = defaultHandler
it "calls handler on error", (done) ->
network.reply(406, message: "I hate you!")
gh.handleErrors (response) ->
assert.equal 406, response.statusCode
assert.equal "I hate you!", response.error
assert.equal '{"message":"I hate you!"}', response.body
done()
gh.get "/foo", never_called
it "doesn't call handler on success", (done) ->
network.reply(201, message: "Hooray!")
gh.handleErrors never_called
gh.get "/foo", -> done()
it "passes body if can't parse response", (done) ->
network.reply(500, "WTF$$%@! SERVER VOMIT")
gh.handleErrors (response) ->
assert.equal 500, response.statusCode
assert.equal "WTF$$%@! SERVER VOMIT", response.body
done()
gh.get "/foo", never_called
it "passes error if request failed", (done) ->
kablooie()
gh.handleErrors (response) ->
assert.ok /kablooie/i.exec response.error
done()
gh.get "/foo", never_called
it "still logs errors", (done) ->
network.reply(406, message: "I hate you!")
expected = 2
cb = ->
expected -= 1
done() if expected is 0
mock_robot.onError = cb
gh.handleErrors cb
gh.get "/foo", never_called
it "works in combination with withOptions", (done) ->
network.matchHeader('Accept', 'application/vnd.github.special+json')
network.reply(406, message: "I hate you!")
gh.handleErrors (response) ->
assert.equal 406, response.statusCode
done()
gh.withOptions(apiVersion: 'special').get "/foo", never_called
it "can be passed as withOptions", (done) ->
network.reply(406, message: "I hate you!")
errHandler = (response) ->
assert.equal 406, response.statusCode
done()
gh.withOptions(errorHandler: errHandler).get "/foo", never_called
describe "without robot given", ->
before ->
gh = require("../src/githubot")
it "complains to stderr", (done) ->
console._old_error = console.error
console.error = (msg) ->
if msg.match /bad credentials/i
console.error = @_old_error
done()
else
@_old_error.call process.stderr, msg
network.reply(401, message: "Bad credentials!")
gh.get "/foo", never_called
|
[
{
"context": ":\"#D1D5DA\"\n color:\"#000\"\n specialKeyBG:\"#ACB3BD\"\n keyBG:\"#F7F7F7\"\n shadowY: ios.px(1)\n ",
"end": 4269,
"score": 0.9994684457778931,
"start": 4262,
"tag": "KEY",
"value": "#ACB3BD"
},
{
"context": ":\"#000\"\n specialKeyBG:\"#ACB3BD\"\n keyBG:\"#F7F7F7\"\n shadowY: ios.px(1)\n shadowColor:\"#898",
"end": 4291,
"score": 0.9995303750038147,
"start": 4284,
"tag": "KEY",
"value": "#F7F7F7"
}
] | ios-kit/ios-kit-keyboard.coffee | andrzej-poniatowski/framer-ios-kit | 599 | ios = require 'ios-kit'
exports.defaults =
style:"light"
shift:true
output:undefined
returnText:"return"
state:"letters"
hidden:false
returnColor:"blue"
superLayer:undefined
#Responsabile for keyboard dimensions
device =
"iphone-5":
popUpChar:40
popUpTop:4
height:215
lineHeight:36
letterKey:
keyTop:6
height:39
width:26.5
borderRadius:5
fontSize:22.5
specialKeyWidth:38.5
specialKeyHeight:38.5
space:5
row1:
leading:0
top:0
row2:
leading:19
top:16
row3:
top:16
leading:51
area:
top:11
leading:3
trailing:3
bottom:4
returnWidth:75
popUpOffset:
x:4
y:30
"iphone-6s":
popUpChar:40
popUpTop:6
height:218
lineHeight:40
letterKey:
keyTop:10
height:42
width:31.5
borderRadius:5
fontSize:23
top:10
specialKeyWidth:42
specialKeyHeight:42
space:6
row1:
leading:0
top:0
row2:
leading:22
top:12
row3:
top:12
leading:59
area:
top:12
leading:3
trailing:3
bottom:4
returnWidth:87
popUpOffset:
x:5
y:32
"iphone-6s-plus":
popUpChar:38
popUpTop:6
height:226
lineHeight:42
letterKey:
keyTop:12
height:45
width:36
borderRadius:5
fontSize:24
top:10
specialKeyWidth:45
specialKeyHeight:45
space:5
row1:
leading:0
top:0
row2:
leading:20
top:11
row3:
top:11
leading:63
area:
top:8
leading:4
trailing:4
bottom:5
returnWidth:97
popUpOffset:
x:10
y:38
"ipad":
height:313
lineHeight:55
letterKey:
height:55
width:56
borderRadius:5
fontSize:23
specialKeyWidth:56
specialKeyHeight:55
space:12
returnWidth:106
row1:
leading:0
top:0
row2:
leading:30
top:9
row3:
leading:68
top:9
area:
top:55
leading:6
trailing:6
bottom:8
"ipad-pro":
height:378
lineHeight:61
letterKey:
height:61
width:63
borderRadius:5
fontSize:23
space:7
returnWidth:120
specialKeyHeight:61
specialKeyWidth:93
row1:
leading:111
top:53
row2:
leading:126
top:7
row3:
leading:161
top:7
area:
top:56
leading:4
trailing:4
bottom:4
# Map of key codes
# Codes for all keys
codeMap = { 8:'delete', 9:'tab', 13:'return', 16:'shift', 20:'caps', 32:'space', 27:"dismiss", 33:"!", 34:"\"", 35:"#", 36:"$", 37:"%", 38:"&", 39:"\'", 40:"(", 41:")", 42:"*", 43:"+", 44:",", 45:"-", 47:"/", 46:".", 48:"0", 49:"!", 50:"@", 51:"#", 52:"$", 53:"%", 54:"^", 55:"&", 56:"*", 57:"(", 48:")", 59:"_", 60:"<", 61:"=", 62:">", 63:"?", 64:"@", 65:"A", 66:"B", 67:"C", 68:"D", 69:"E", 70:"F", 71:"G", 72:"H", 73:"I", 74:"J", 75:"K", 76:"L", 77:"M", 78:"N", 79:"O", 80:"P", 81:"Q", 82:"R", 83:"S", 84:"T", 85:"U", 86:"V", 87:"W", 88:"X", 89:"Y", 90:"Z", 91:'cmd', 219:"[", 92:"\\", 221:"]", 94:"^", 95:"_", 96:"`", 97:"a", 98:"b", 99:"c", 100:"d", 101:"e", 102:"f", 103:"g", 104:"h", 105:"i", 106:"j", 107:"k", 108:"l", 109:"m", 110:"n", 111:"o", 112:"p", 113:"q", 114:"r", 115:"s", 116:"t", 117:"u", 118:"v", 119:"w", 120:"x", 121:"y", 122:"z", 123:"{", 124:"|", 125:"}", 126:"~", 186:":", 187:"+", 188:"<", 190:">", 191:"?", 189:"_", 192:"~", 219:"{", 220:"\|", 221:"}", 222:"”"}
arrayOfCodes = Object.keys(codeMap)
letters = ["q", "w", "e", "r", "t", "y", "u", "i", "o", "p", "a", "s", "d", "f", "g", "h", "j", "k", "l", "z", "x", "c", "v", "b", "n", "m"]
numbers = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "-", "/", ":", ";", "(", ")", "$", "&", "@", "\"", ".", ",", "?", "!", "′"]
symbols = ["[", "]", "{", "}", "#", "%", "^", "*", "+", "=", "_", "\\", "|", "~", "<", ">", "€", "£", "¥", "•"]
exports.defaults.props = Object.keys(exports.defaults)
exports.create = (obj) ->
setup = ios.utils.setupComponent(obj, exports.defaults)
#Responsabile for colors
style =
light:
backgroundColor:"#D1D5DA"
color:"#000"
specialKeyBG:"#ACB3BD"
keyBG:"#F7F7F7"
shadowY: ios.px(1)
shadowColor:"#898B8F"
returnBG:ios.color(setup.returnColor)
dark:
backgroundColor:"rgba(0,0,0,.7)"
color:"#FFF"
specialKeyBG:"rgba(67,67,67,.8)"
keyBG:"rgba(105,105,105,.8)"
shadowY: ios.px(1)
shadowColor:"rgba(0,0,0,.4)"
returnBG:ios.color(setup.returnColor)
specs = device[ios.device.name]
colors = style[setup.style]
device
board = new ios.View
name:"Keyboard"
superLayer:setup.superLayer
backgroundColor:style[setup.style].backgroundColor
y:ios.device.height
constraints:
leading:0
trailing:0
bottom:-1 * specs.height
height:specs.height
ios.utils.bgBlur(board)
board.output = (obj) ->
if board.target
if board.target.type == 'field'
board.target.active = false
board.target = obj
if board.target
if board.target.type == 'field'
board.target.active = true
board.hidden = setup.hidden
if board.hidden == false
board.constraints.bottom = 0
ios.layout.set(board)
board.call = () ->
board.y = ios.device.height
board.constraints.bottom = 0
if board.hidden
board.hidden = false
ios.layout.animate
target:board
time:.5
curve:'ease-in-out'
board.bringToFront()
board.dismiss = () ->
board.constraints.bottom = -1 * ios.pt(board.height)
board.hidden = true
board.target.active = false
ios.layout.animate
target:board
time:.5
curve:'ease-in-out'
board.delete = () ->
layer = ""
if board.target
if board.target.type == 'field'
layer = board.target.text
else
layer = board.target
isSpace = layer.html[layer.html.length - 5..layer.html.length - 1 ]
if isSpace != 'nbsp;'
text = layer.html.slice(0, -1)
layer.html = text
else
text = layer.html.slice(0, -6)
layer.html = text
board.capsLock = () ->
board.isCapsLock = true
board.isCapital = true
board.keys.shift.icon.toggle('off')
handleKeyColor(board.keys.shift)
if ios.device.name == 'ipad-pro'
board.keys.shiftalt.icon.toggle('off')
handleKeyColor(board.keys.shiftalt)
board.output(setup.output)
board.keysArray = []
board.keys = {}
board.isCapital = setup.shift
board.area = new ios.View
name:".area"
superLayer:board
constraints: specs.area
backgroundColor:"transparent"
Key = (obj) ->
key = new ios.View
name:".keys." + obj.name
constraints:obj.constraints
superLayer:board.area
borderRadius:ios.px(specs.letterKey.borderRadius)
shadowY:colors.shadowY
shadowColor:colors.shadowColor
key.style.fontFamily = "-apple-system, Helvetica, Arial, sans-serif"
#Disables Zoom
key.on Events.TouchStart, (event) ->
event.preventDefault()
return key
Letter = (obj) ->
key = new Key obj
key.backgroundColor = colors.keyBG
key.html = obj.letter
key.color = colors.color
key.style.textAlign = "center"
key.style.lineHeight = ios.px(specs.lineHeight) + "px"
key.style.fontSize = ios.px(specs.letterKey.fontSize) + "px"
key.value = obj.letter
if key.value == "space" then key.value = " "
if ios.isPad()
key.down = ->
key.backgroundColor = colors.specialKeyBG
if board.target then ios.utils.write(board.target, key.value)
key.up = ->
key.backgroundColor = colors.keyBG
if board.isCapital && board.isCapsLock != true
board.isCapital = false
capitalizeKeys()
board.keys.shift.up()
if ios.isPad() then board.keys.shiftalt.up()
key.on Events.TouchStart, ->
key.down()
key.on Events.TouchEnd, ->
key.up()
else
if key.value != ' '
key.down = ->
board.popUp.visible = true
board.bringToFront()
board.popUp.bringToFront()
board.popUp.midX = key.midX
board.popUp.maxY = key.maxY
board.popUp.text.html = key.value
if board.target then ios.utils.write(board.target, key.value)
key.up = ->
board.popUp.visible = false
if board.isCapital && board.capsLock != true
board.isCapital = false
capitalizeKeys()
board.keys.shift.up()
key.on Events.TouchStart, -> key.down()
key.on Events.TouchEnd, -> key.up()
else
key.down = ->
key.backgroundColor = colors.specialKeyBG
if board.target then ios.utils.write(board.target, key.value)
key.up = ->
key.backgroundColor = colors.keyBG
key.on Events.TouchStart, ->
key.down()
key.on Events.TouchEnd, ->
key.up()
return key
SpecialKey = (obj) ->
key = new Key obj
key.backgroundColor = colors.specialKeyBG
key.color = colors.color
key.style.textAlign = "center"
if ios.device.name == 'ipad-pro'
key.style.fontSize = ios.px(18) + "px"
else
key.style.fontSize = ios.px(16) + "px"
return key
Icon = (obj) ->
icon = new ios.View
name:'icon'
backgroundColor:"transparent"
superLayer:obj.superLayer
constraints:
align:'center'
icon.props = (height:obj.icon.height, width:obj.icon.width, html: obj.icon.svg)
ios.utils.changeFill(icon, colors.color)
return icon
IconWithState = (obj) ->
icon = new ios.View
name:'icon'
backgroundColor:"transparent"
superLayer:obj.superLayer
constraints:
align:'center'
icon.toggle = (state) ->
if state == undefined
if icon.state == 'on' then state = 'off'
else state = 'on'
if state == "on"
if ios.device.name != 'ipad-pro'
icon.html = obj.on.svg
icon.width = obj.on.width
icon.height = obj.on.height
icon.state = 'on'
else
if ios.device.name != 'ipad-pro'
icon.html = obj.off.svg
icon.width = obj.on.width
icon.height = obj.on.height
icon.state = 'off'
ios.utils.changeFill(icon, colors.color)
if obj.state
icon.toggle('on')
else
icon.toggle('off')
return icon
capitalizeKeys = ->
for key in board.keysArray
if board.isCapital
if key.html.length == 1 && key.html.match(/[a-z]/i)
key.html = key.html.toUpperCase()
key.value = key.html
if key.alt
key.alt.destroy()
key.alt = undefined
if key.height > ios.px(46)
key.style.lineHeight = ios.px(specs.letterKey.height) + 'px'
key.style.fontSize = ios.px(23) + 'px'
else
if ios.device.name == 'ipad-pro'
key.style.lineHeight = ios.px(46) + 'px'
else
key.style.lineHeight = ios.px(specs.lineHeight) + 'px'
key.style.fontSize = ios.px(20) + 'px'
key.value = key.html
else
if key.html.length == 1 && key.html.match(/[a-z]/i)
key.html = key.html.toLowerCase()
key.value = key.html
else
if key.alt == undefined
key.alt = new ios.Text
text:""
superLayer:key
color:colors.color
constraints:
align:"horizontal"
bottom:4
fontSize:specs.letterKey.fontSize
if board.topRow
if board.topRow.indexOf(key) != -1
key.style.lineHeight = ios.px(23) + 'px'
key.style.fontSize = ios.px(16) + 'px'
key.alt.style.fontSize = ios.px(16) + 'px'
else
key.style.lineHeight = ios.px(36) + 'px'
key.style.fontSize = ios.px(20) + 'px'
key.alt.style.fontSize = ios.px(20) + 'px'
key.alt.constraints.bottom = 8
switch key.value
when "<"
key.alt.html = "."
when ">"
key.alt.html = ","
when "<"
key.alt.html = "."
when ">"
key.alt.html = ","
when "?"
key.alt.html = "."
when "{"
key.alt.html = "["
when "}"
key.alt.html = "}"
when "\|"
key.alt.html = "\\"
when "~"
key.alt.html = "`"
when "!"
key.alt.html = "."
when "@"
key.alt.html = "2"
when "#"
key.alt.html = "3"
when "$"
key.alt.html = "4"
when "%"
key.alt.html = "5"
when "^"
key.alt.html = "6"
when "&"
key.alt.html = "7"
when "&"
key.alt.html = "7"
when "*"
key.alt.html = "8"
when "("
key.alt.html = "9"
when ")"
key.alt.html = "0"
when "_"
key.alt.html = "-"
when "+"
key.alt.html = "="
else
key.alt.html = "′"
ios.layout.set(key.alt)
if ios.device.name == 'ipad-pro' && key.value == '!' then key.alt.html = '1'
if ios.device.name == 'ipad-pro' && key.value == '?' then key.alt.html = '/'
if ios.device.name == 'ipad-pro' && key.value == ':' then key.alt.html = ';'
if ios.device.name == 'ipad-pro' && key.value == '”' then key.alt.html = '′'
key.value = key.alt.html
handleKeyColor = (key) ->
if ios.isPhone
if key.icon.state == 'on' then key.backgroundColor = colors.keyBG
else key.backgroundColor = colors.specialKeyBG
Space = (obj) ->
key = new Letter obj
key.html = 'space'
key.backgroundColor = colors.keyBG
key.style.lineHeight = ios.px(specs.specialKeyHeight) + "px"
key.style.fontSize = ios.px(16) + 'px'
return key
Shift = (obj) ->
key = new SpecialKey obj
key.icon = new IconWithState
superLayer:key
state:obj.shift
on:ios.utils.svg(ios.assets.shift.on)
off:ios.utils.svg(ios.assets.shift.off)
handleKeyColor(key)
key.on Events.TouchEnd, ->
@.icon.toggle()
handleKeyColor(key)
if @.icon.state == 'on'
board.isCapital = true
else
board.isCapital = false
capitalizeKeys()
key.down = ->
key.icon.toggle('on')
handleKeyColor(key)
board.isCapital = true
capitalizeKeys()
key.up = ->
key.icon.toggle('off')
handleKeyColor(key)
board.isCapital = false
capitalizeKeys()
ios.layout.set(key.icon)
if ios.isPad()
key.on Events.TouchEnd, ->
if @.icon.state == 'on'
board.keys.shift.icon.toggle('on')
board.keys.shiftalt.icon.toggle('on')
else
board.keys.shift.icon.toggle('off')
board.keys.shiftalt.icon.toggle('off')
handleKeyColor(board.keys.shift)
handleKeyColor(board.keys.shiftalt)
return key
Delete = (obj) ->
key = new SpecialKey obj
key.icon = new IconWithState
superLayer:key
on:ios.utils.svg(ios.assets.delete.on)
off:ios.utils.svg(ios.assets.delete.off)
key.fire = -> board.delete()
key.down = ->
key.icon.toggle('on')
handleKeyColor(key)
key.fire()
key.up = ->
key.icon.toggle('off')
handleKeyColor(key)
key.on Events.TouchStart, -> key.down()
key.on Events.TouchEnd, -> key.up()
return key
Numbers = (obj) ->
key = new SpecialKey obj
if ios.isPhone()
key.html = '123'
else
key.html ='.?123'
key.style.lineHeight = ios.px(specs.specialKeyHeight) + "px"
return key
Emoji = (obj) ->
key = new SpecialKey obj
key.icon = new Icon
superLayer:key
icon:ios.utils.svg(ios.assets.emoji)
return key
Return = (obj) ->
key = new SpecialKey obj
key.backgroundColor = colors.returnBG
key.html = setup.returnText
key.style.lineHeight = ios.px(specs.specialKeyHeight) + "px"
key.color = ios.utils.autoColor(colors.returnBG)
key.down = ->
nothingHappens = true
key.up = ->
board.dismiss()
if board.target
if board.target.parent
board.target.parent.active = false
key.on Events.TouchEnd, -> key.down()
key.on Events.TouchStart, -> key.up()
return key
Dismiss = (obj) ->
key = new SpecialKey obj
key.icon = new Icon
superLayer:key
icon:ios.utils.svg(ios.assets.keyboard)
key.icon.scale = .8
key.icon.constraints =
bottom:12
trailing:12
ios.layout.set(key.icon)
key.down = -> board.dismiss()
key.up = -> nothingHappens = false
key.on Events.TouchEnd, -> key.down()
return key
Tab = (obj) ->
key = new SpecialKey obj
key.html = 'tab'
key.style.lineHeight = ios.px(70) + 'px'
key.style.textAlign = 'left'
key.style.paddingLeft = ios.px(12) + 'px'
return key
board.switchLetters = ->
row1Break = 10
row2Break = 19
if ios.isPad()
letters.push '!'
letters.push '?'
if ios.device.name == "ipad-pro"
letters = ["q", "w", "e", "r", "t", "y", "u", "i", "o", "p", "{", "}", "\|", "a", "s", "d", "f", "g", "h", "j", "k", "l", ":", "”", "z", "x", "c", "v", "b", "n", "m", "<", ">", "?"]
topLetters = ["~", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "_", "+"]
row1Break = 13
row2Break = 24
for l, i in letters
key = new Letter
name:l
constraints:
height:specs.letterKey.height
width:specs.letterKey.width
letter:l
if l == 'w' || l == 'r' || l == 'y' || l == 'i' || l == 'p'
key.constraints.width = key.constraints.width + 1
board.keys[l] = key
board.keysArray.push key
if i == 0
key.constraints.leading = specs.row1.leading
key.constraints.top = specs.row1.top
if i > 0 && i < row1Break
key.constraints.leading = [board.keysArray[i - 1], specs.space]
key.constraints.top = specs.row1.top
if i == row1Break
key.constraints.leading = specs.row2.leading
key.constraints.top = [board.keysArray[0], specs.row2.top]
if i > row1Break && i < row2Break
key.constraints.leading = [board.keysArray[i - 1], specs.space]
key.constraints.top = [board.keysArray[0], specs.row2.top]
if i == row2Break
key.constraints.leading = specs.row3.leading
key.constraints.top = [board.keysArray[row1Break], specs.row3.top]
if i > row2Break
key.constraints.leading = [board.keysArray[i - 1], specs.space]
key.constraints.top = [board.keysArray[row1Break], specs.row3.top]
ios.layout.set(key)
board.keys.shift = new Shift
name:"shift"
shift:setup.shift
constraints:
height:specs.specialKeyHeight
width:specs.specialKeyWidth
bottomEdges:board.keys.z
board.keys.delete = new Delete
name:"delete"
constraints:
height:specs.specialKeyHeight
width:specs.specialKeyWidth
bottomEdges:board.keys.z
trailing:0
board.keys.numbers = new Numbers
name:"numbers"
constraints:
height:specs.specialKeyHeight
width:specs.specialKeyWidth
bottom:0
leading:0
board.keys.emoji = new Emoji
name:"emoji"
constraints:
height:specs.specialKeyHeight
width:specs.specialKeyWidth
leading:[board.keys.numbers, specs.space]
bottom:0
board.keys.return = new Return
name:"return"
constraints:
bottom:0
trailing:0
width:specs.returnWidth
height:specs.specialKeyHeight
board.keys.space = new Space
name:"space"
letter:"space"
constraints:
leading:[board.keys.emoji, specs.space]
trailing:[board.keys.return, specs.space]
bottom:0
height:specs.specialKeyHeight
if ios.isPad()
board.keys.return.constraints.bottom = undefined
board.keys.return.constraints.bottomEdges = board.keysArray[row1Break]
board.keys.delete.constraints.top = 0
board.keys.delete.constraints.bottomEdges = undefined
board.keys.delete.constraints.width = 61
board.keys.shiftalt = new Shift
name:"shiftalt"
shift:setup.shift
constraints:
height:specs.specialKeyHeight
width:76
bottomEdges:board.keys.z
trailing:0
board.keys.dismiss = new Dismiss
name:"dismiss"
constraints:
height:specs.specialKeyHeight
width:specs.specialKeyWidth
bottom:0
trailing:0
board.keys.numbersalt = new Numbers
name:"numbersalt"
constraints:
height:specs.specialKeyHeight
width:93
bottom:0
trailing:[board.keys.dismiss, specs.space]
board.keys.space.html = ""
board.keys.space.constraints.trailing = [board.keys.numbersalt, specs.space]
ios.layout.set()
board.topRow = []
if ios.device.name == 'ipad-pro'
for l,i in topLetters
topKey = new Letter
letter:l
name:l
constraints:
height:46
width:63
top:0
if i == 0
topKey.constraints.leading = 0
else
topKey.constraints.leading = [board.topRow[i - 1], specs.space]
topKey.style.lineHeight = ios.px(46) + 'px'
ios.layout.set(topKey)
board.topRow.push topKey
board.keysArray.push topKey
board.keys[l] = topKey
board.keys.delete.icon.destroy()
board.keys.delete.html = 'delete'
board.keys.delete.style.lineHeight = ios.px(53) + 'px'
board.keys.delete.style.textAlign = 'right'
board.keys.delete.style.paddingRight = ios.px(12) + 'px'
board.keys.delete.constraints =
top:0
trailing:0
height:46
width:106
board.keys.shift.icon.destroy()
board.keys.shift.html = 'shift'
board.keys.shift.style.lineHeight = ios.px(70) + 'px'
board.keys.shift.style.textAlign = 'left'
board.keys.shift.style.paddingLeft = ios.px(12) + 'px'
board.keys.shift.constraints.width = 154
board.keys.shiftalt.icon.destroy()
board.keys.shiftalt.html = 'shift'
board.keys.shiftalt.style.lineHeight = ios.px(70) + 'px'
board.keys.shiftalt.style.textAlign = 'right'
board.keys.shiftalt.style.paddingRight = ios.px(12) + 'px'
board.keys.shiftalt.constraints.width = 155
board.keys.emoji.icon.constraints = {leading:15, bottom:11}
board.keys.emoji.constraints =
width:144
height:61
leading:0
bottom:0
ios.layout.set()
board.keys.numbersalt.constraints.width = 93
board.keys.dismiss.constraints.width = 93
board.keys.com = new Letter
name:'.com'
letter:'.com'
constraints:
height:specs.letterKey.height
width:specs.letterKey.width
bottom:0
trailing:[board.keys.numbersalt, specs.space]
board.keys.com.style.fontSize = ios.px(16) + 'px'
board.keys.numbers.constraints =
width:143
height:61
leading:[board.keys.emoji, specs.space]
board.keys.numbers.style.lineHeight = ios.px(70) + 'px'
board.keys.numbers.style.textAlign = 'left'
board.keys.numbers.style.paddingLeft = ios.px(12) + 'px'
board.keys.return.style.lineHeight = ios.px(70) + 'px'
board.keys.return.style.textAlign = 'right'
board.keys.return.style.paddingRight = ios.px(12) + 'px'
board.keys.space.constraints.leading = [board.keys.numbers, specs.space]
board.keys.space.constraints.trailing = [board.keys.com, specs.space]
board.keys.caps = new Shift
name:'caps'
caps: true
constraints:
height:specs.specialKeyHeight
width:119
bottomEdges:board.keysArray[row1Break]
board.keys.caps.icon.destroy()
board.keys.caps.html = 'caps lock'
board.keys.caps.style.lineHeight = ios.px(70) + 'px'
board.keys.caps.style.textAlign = 'left'
board.keys.caps.style.paddingLeft = ios.px(12) + 'px'
board.keys.caps.down = ->
if board.isCapsLock
board.isCapsLock = false
else
board.capsLock()
board.keys.caps.on Events.TouchEnd, ->
board.keys.caps.down()
board.keys.caps.up = ->
nothingHappens = true
board.keys.tab = new Tab
name:'tab'
constraints:
height:specs.specialKeyHeight
width:106
bottomEdges:board.keysArray[0]
ios.layout.set()
if ios.isPhone()
popUp = ios.utils.svg(ios.assets.keyPopUp[setup.style][ios.device.name])
board.popUp = new Layer
height:popUp.height
width:popUp.width
backgroundColor:'transparent'
name:'.popUp'
superLayer:board.area
visible:false
board.popUp.svg = new Layer
html:popUp.svg
height:popUp.height
width:popUp.width
superLayer:board.popUp
name:'.svg'
backgroundColor:'transparent'
board.popUp.text = new ios.Text
text:'A'
superLayer:board.popUp
fontSize:specs.popUpChar
fontWeight:300
color:colors.color
textAlign:'center'
constraints:
align:'horizontal'
top:specs.popUpTop
width:ios.pt(popUp.width)
board.popUp.center()
switch ios.device.name
when 'iphone-6s-plus'
board.popUp.width = board.popUp.width - 18
board.popUp.height = board.popUp.height - 24
board.popUp.svg.x = ios.px(-3)
board.popUp.svg.y = ios.px(-3)
when 'iphone-6s'
board.popUp.width = board.popUp.width - 12
board.popUp.height = board.popUp.height - 12
board.popUp.svg.x = ios.px(-3)
board.popUp.svg.y = ios.px(-2)
when 'iphone-5'
board.popUp.width = board.popUp.width - 12
board.popUp.height = board.popUp.height - 12
board.popUp.svg.x = ios.px(-3)
board.popUp.svg.y = ios.px(-2)
capitalizeKeys()
board.switch = (state) ->
switch state
when "letters"
board.switchLetters()
board.switch("letters")
document.addEventListener 'keydown', (e) ->
if arrayOfCodes.indexOf(e.keyCode.toString()) != -1
key = board.keys[codeMap[e.keyCode].toLowerCase()]
if key then key.down()
if ios.isPad()
if key == board.keys.shift || key == board.keys.shiftalt
board.keys.shift.down()
board.keys.shiftalt.icon.toggle('on')
handleKeyColor(board.keys.shiftalt)
document.addEventListener 'keyup', (e) ->
if arrayOfCodes.indexOf(e.keyCode.toString()) != -1
key = board.keys[codeMap[e.keyCode].toLowerCase()]
if key then key.up()
if ios.isPad()
if key == board.keys.shift || key == board.keys.shiftalt
board.keys.shift.up()
board.keys.shiftalt.icon.toggle('off')
handleKeyColor(board.keys.shiftalt)
capitalizeKeys()
return board
| 113749 | ios = require 'ios-kit'
exports.defaults =
style:"light"
shift:true
output:undefined
returnText:"return"
state:"letters"
hidden:false
returnColor:"blue"
superLayer:undefined
#Responsabile for keyboard dimensions
device =
"iphone-5":
popUpChar:40
popUpTop:4
height:215
lineHeight:36
letterKey:
keyTop:6
height:39
width:26.5
borderRadius:5
fontSize:22.5
specialKeyWidth:38.5
specialKeyHeight:38.5
space:5
row1:
leading:0
top:0
row2:
leading:19
top:16
row3:
top:16
leading:51
area:
top:11
leading:3
trailing:3
bottom:4
returnWidth:75
popUpOffset:
x:4
y:30
"iphone-6s":
popUpChar:40
popUpTop:6
height:218
lineHeight:40
letterKey:
keyTop:10
height:42
width:31.5
borderRadius:5
fontSize:23
top:10
specialKeyWidth:42
specialKeyHeight:42
space:6
row1:
leading:0
top:0
row2:
leading:22
top:12
row3:
top:12
leading:59
area:
top:12
leading:3
trailing:3
bottom:4
returnWidth:87
popUpOffset:
x:5
y:32
"iphone-6s-plus":
popUpChar:38
popUpTop:6
height:226
lineHeight:42
letterKey:
keyTop:12
height:45
width:36
borderRadius:5
fontSize:24
top:10
specialKeyWidth:45
specialKeyHeight:45
space:5
row1:
leading:0
top:0
row2:
leading:20
top:11
row3:
top:11
leading:63
area:
top:8
leading:4
trailing:4
bottom:5
returnWidth:97
popUpOffset:
x:10
y:38
"ipad":
height:313
lineHeight:55
letterKey:
height:55
width:56
borderRadius:5
fontSize:23
specialKeyWidth:56
specialKeyHeight:55
space:12
returnWidth:106
row1:
leading:0
top:0
row2:
leading:30
top:9
row3:
leading:68
top:9
area:
top:55
leading:6
trailing:6
bottom:8
"ipad-pro":
height:378
lineHeight:61
letterKey:
height:61
width:63
borderRadius:5
fontSize:23
space:7
returnWidth:120
specialKeyHeight:61
specialKeyWidth:93
row1:
leading:111
top:53
row2:
leading:126
top:7
row3:
leading:161
top:7
area:
top:56
leading:4
trailing:4
bottom:4
# Map of key codes
# Codes for all keys
codeMap = { 8:'delete', 9:'tab', 13:'return', 16:'shift', 20:'caps', 32:'space', 27:"dismiss", 33:"!", 34:"\"", 35:"#", 36:"$", 37:"%", 38:"&", 39:"\'", 40:"(", 41:")", 42:"*", 43:"+", 44:",", 45:"-", 47:"/", 46:".", 48:"0", 49:"!", 50:"@", 51:"#", 52:"$", 53:"%", 54:"^", 55:"&", 56:"*", 57:"(", 48:")", 59:"_", 60:"<", 61:"=", 62:">", 63:"?", 64:"@", 65:"A", 66:"B", 67:"C", 68:"D", 69:"E", 70:"F", 71:"G", 72:"H", 73:"I", 74:"J", 75:"K", 76:"L", 77:"M", 78:"N", 79:"O", 80:"P", 81:"Q", 82:"R", 83:"S", 84:"T", 85:"U", 86:"V", 87:"W", 88:"X", 89:"Y", 90:"Z", 91:'cmd', 219:"[", 92:"\\", 221:"]", 94:"^", 95:"_", 96:"`", 97:"a", 98:"b", 99:"c", 100:"d", 101:"e", 102:"f", 103:"g", 104:"h", 105:"i", 106:"j", 107:"k", 108:"l", 109:"m", 110:"n", 111:"o", 112:"p", 113:"q", 114:"r", 115:"s", 116:"t", 117:"u", 118:"v", 119:"w", 120:"x", 121:"y", 122:"z", 123:"{", 124:"|", 125:"}", 126:"~", 186:":", 187:"+", 188:"<", 190:">", 191:"?", 189:"_", 192:"~", 219:"{", 220:"\|", 221:"}", 222:"”"}
arrayOfCodes = Object.keys(codeMap)
letters = ["q", "w", "e", "r", "t", "y", "u", "i", "o", "p", "a", "s", "d", "f", "g", "h", "j", "k", "l", "z", "x", "c", "v", "b", "n", "m"]
numbers = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "-", "/", ":", ";", "(", ")", "$", "&", "@", "\"", ".", ",", "?", "!", "′"]
symbols = ["[", "]", "{", "}", "#", "%", "^", "*", "+", "=", "_", "\\", "|", "~", "<", ">", "€", "£", "¥", "•"]
exports.defaults.props = Object.keys(exports.defaults)
exports.create = (obj) ->
setup = ios.utils.setupComponent(obj, exports.defaults)
#Responsabile for colors
style =
light:
backgroundColor:"#D1D5DA"
color:"#000"
specialKeyBG:"<KEY>"
keyBG:"<KEY>"
shadowY: ios.px(1)
shadowColor:"#898B8F"
returnBG:ios.color(setup.returnColor)
dark:
backgroundColor:"rgba(0,0,0,.7)"
color:"#FFF"
specialKeyBG:"rgba(67,67,67,.8)"
keyBG:"rgba(105,105,105,.8)"
shadowY: ios.px(1)
shadowColor:"rgba(0,0,0,.4)"
returnBG:ios.color(setup.returnColor)
specs = device[ios.device.name]
colors = style[setup.style]
device
board = new ios.View
name:"Keyboard"
superLayer:setup.superLayer
backgroundColor:style[setup.style].backgroundColor
y:ios.device.height
constraints:
leading:0
trailing:0
bottom:-1 * specs.height
height:specs.height
ios.utils.bgBlur(board)
board.output = (obj) ->
if board.target
if board.target.type == 'field'
board.target.active = false
board.target = obj
if board.target
if board.target.type == 'field'
board.target.active = true
board.hidden = setup.hidden
if board.hidden == false
board.constraints.bottom = 0
ios.layout.set(board)
board.call = () ->
board.y = ios.device.height
board.constraints.bottom = 0
if board.hidden
board.hidden = false
ios.layout.animate
target:board
time:.5
curve:'ease-in-out'
board.bringToFront()
board.dismiss = () ->
board.constraints.bottom = -1 * ios.pt(board.height)
board.hidden = true
board.target.active = false
ios.layout.animate
target:board
time:.5
curve:'ease-in-out'
board.delete = () ->
layer = ""
if board.target
if board.target.type == 'field'
layer = board.target.text
else
layer = board.target
isSpace = layer.html[layer.html.length - 5..layer.html.length - 1 ]
if isSpace != 'nbsp;'
text = layer.html.slice(0, -1)
layer.html = text
else
text = layer.html.slice(0, -6)
layer.html = text
board.capsLock = () ->
board.isCapsLock = true
board.isCapital = true
board.keys.shift.icon.toggle('off')
handleKeyColor(board.keys.shift)
if ios.device.name == 'ipad-pro'
board.keys.shiftalt.icon.toggle('off')
handleKeyColor(board.keys.shiftalt)
board.output(setup.output)
board.keysArray = []
board.keys = {}
board.isCapital = setup.shift
board.area = new ios.View
name:".area"
superLayer:board
constraints: specs.area
backgroundColor:"transparent"
Key = (obj) ->
key = new ios.View
name:".keys." + obj.name
constraints:obj.constraints
superLayer:board.area
borderRadius:ios.px(specs.letterKey.borderRadius)
shadowY:colors.shadowY
shadowColor:colors.shadowColor
key.style.fontFamily = "-apple-system, Helvetica, Arial, sans-serif"
#Disables Zoom
key.on Events.TouchStart, (event) ->
event.preventDefault()
return key
Letter = (obj) ->
key = new Key obj
key.backgroundColor = colors.keyBG
key.html = obj.letter
key.color = colors.color
key.style.textAlign = "center"
key.style.lineHeight = ios.px(specs.lineHeight) + "px"
key.style.fontSize = ios.px(specs.letterKey.fontSize) + "px"
key.value = obj.letter
if key.value == "space" then key.value = " "
if ios.isPad()
key.down = ->
key.backgroundColor = colors.specialKeyBG
if board.target then ios.utils.write(board.target, key.value)
key.up = ->
key.backgroundColor = colors.keyBG
if board.isCapital && board.isCapsLock != true
board.isCapital = false
capitalizeKeys()
board.keys.shift.up()
if ios.isPad() then board.keys.shiftalt.up()
key.on Events.TouchStart, ->
key.down()
key.on Events.TouchEnd, ->
key.up()
else
if key.value != ' '
key.down = ->
board.popUp.visible = true
board.bringToFront()
board.popUp.bringToFront()
board.popUp.midX = key.midX
board.popUp.maxY = key.maxY
board.popUp.text.html = key.value
if board.target then ios.utils.write(board.target, key.value)
key.up = ->
board.popUp.visible = false
if board.isCapital && board.capsLock != true
board.isCapital = false
capitalizeKeys()
board.keys.shift.up()
key.on Events.TouchStart, -> key.down()
key.on Events.TouchEnd, -> key.up()
else
key.down = ->
key.backgroundColor = colors.specialKeyBG
if board.target then ios.utils.write(board.target, key.value)
key.up = ->
key.backgroundColor = colors.keyBG
key.on Events.TouchStart, ->
key.down()
key.on Events.TouchEnd, ->
key.up()
return key
SpecialKey = (obj) ->
key = new Key obj
key.backgroundColor = colors.specialKeyBG
key.color = colors.color
key.style.textAlign = "center"
if ios.device.name == 'ipad-pro'
key.style.fontSize = ios.px(18) + "px"
else
key.style.fontSize = ios.px(16) + "px"
return key
Icon = (obj) ->
icon = new ios.View
name:'icon'
backgroundColor:"transparent"
superLayer:obj.superLayer
constraints:
align:'center'
icon.props = (height:obj.icon.height, width:obj.icon.width, html: obj.icon.svg)
ios.utils.changeFill(icon, colors.color)
return icon
IconWithState = (obj) ->
icon = new ios.View
name:'icon'
backgroundColor:"transparent"
superLayer:obj.superLayer
constraints:
align:'center'
icon.toggle = (state) ->
if state == undefined
if icon.state == 'on' then state = 'off'
else state = 'on'
if state == "on"
if ios.device.name != 'ipad-pro'
icon.html = obj.on.svg
icon.width = obj.on.width
icon.height = obj.on.height
icon.state = 'on'
else
if ios.device.name != 'ipad-pro'
icon.html = obj.off.svg
icon.width = obj.on.width
icon.height = obj.on.height
icon.state = 'off'
ios.utils.changeFill(icon, colors.color)
if obj.state
icon.toggle('on')
else
icon.toggle('off')
return icon
capitalizeKeys = ->
for key in board.keysArray
if board.isCapital
if key.html.length == 1 && key.html.match(/[a-z]/i)
key.html = key.html.toUpperCase()
key.value = key.html
if key.alt
key.alt.destroy()
key.alt = undefined
if key.height > ios.px(46)
key.style.lineHeight = ios.px(specs.letterKey.height) + 'px'
key.style.fontSize = ios.px(23) + 'px'
else
if ios.device.name == 'ipad-pro'
key.style.lineHeight = ios.px(46) + 'px'
else
key.style.lineHeight = ios.px(specs.lineHeight) + 'px'
key.style.fontSize = ios.px(20) + 'px'
key.value = key.html
else
if key.html.length == 1 && key.html.match(/[a-z]/i)
key.html = key.html.toLowerCase()
key.value = key.html
else
if key.alt == undefined
key.alt = new ios.Text
text:""
superLayer:key
color:colors.color
constraints:
align:"horizontal"
bottom:4
fontSize:specs.letterKey.fontSize
if board.topRow
if board.topRow.indexOf(key) != -1
key.style.lineHeight = ios.px(23) + 'px'
key.style.fontSize = ios.px(16) + 'px'
key.alt.style.fontSize = ios.px(16) + 'px'
else
key.style.lineHeight = ios.px(36) + 'px'
key.style.fontSize = ios.px(20) + 'px'
key.alt.style.fontSize = ios.px(20) + 'px'
key.alt.constraints.bottom = 8
switch key.value
when "<"
key.alt.html = "."
when ">"
key.alt.html = ","
when "<"
key.alt.html = "."
when ">"
key.alt.html = ","
when "?"
key.alt.html = "."
when "{"
key.alt.html = "["
when "}"
key.alt.html = "}"
when "\|"
key.alt.html = "\\"
when "~"
key.alt.html = "`"
when "!"
key.alt.html = "."
when "@"
key.alt.html = "2"
when "#"
key.alt.html = "3"
when "$"
key.alt.html = "4"
when "%"
key.alt.html = "5"
when "^"
key.alt.html = "6"
when "&"
key.alt.html = "7"
when "&"
key.alt.html = "7"
when "*"
key.alt.html = "8"
when "("
key.alt.html = "9"
when ")"
key.alt.html = "0"
when "_"
key.alt.html = "-"
when "+"
key.alt.html = "="
else
key.alt.html = "′"
ios.layout.set(key.alt)
if ios.device.name == 'ipad-pro' && key.value == '!' then key.alt.html = '1'
if ios.device.name == 'ipad-pro' && key.value == '?' then key.alt.html = '/'
if ios.device.name == 'ipad-pro' && key.value == ':' then key.alt.html = ';'
if ios.device.name == 'ipad-pro' && key.value == '”' then key.alt.html = '′'
key.value = key.alt.html
handleKeyColor = (key) ->
if ios.isPhone
if key.icon.state == 'on' then key.backgroundColor = colors.keyBG
else key.backgroundColor = colors.specialKeyBG
Space = (obj) ->
key = new Letter obj
key.html = 'space'
key.backgroundColor = colors.keyBG
key.style.lineHeight = ios.px(specs.specialKeyHeight) + "px"
key.style.fontSize = ios.px(16) + 'px'
return key
Shift = (obj) ->
key = new SpecialKey obj
key.icon = new IconWithState
superLayer:key
state:obj.shift
on:ios.utils.svg(ios.assets.shift.on)
off:ios.utils.svg(ios.assets.shift.off)
handleKeyColor(key)
key.on Events.TouchEnd, ->
@.icon.toggle()
handleKeyColor(key)
if @.icon.state == 'on'
board.isCapital = true
else
board.isCapital = false
capitalizeKeys()
key.down = ->
key.icon.toggle('on')
handleKeyColor(key)
board.isCapital = true
capitalizeKeys()
key.up = ->
key.icon.toggle('off')
handleKeyColor(key)
board.isCapital = false
capitalizeKeys()
ios.layout.set(key.icon)
if ios.isPad()
key.on Events.TouchEnd, ->
if @.icon.state == 'on'
board.keys.shift.icon.toggle('on')
board.keys.shiftalt.icon.toggle('on')
else
board.keys.shift.icon.toggle('off')
board.keys.shiftalt.icon.toggle('off')
handleKeyColor(board.keys.shift)
handleKeyColor(board.keys.shiftalt)
return key
Delete = (obj) ->
key = new SpecialKey obj
key.icon = new IconWithState
superLayer:key
on:ios.utils.svg(ios.assets.delete.on)
off:ios.utils.svg(ios.assets.delete.off)
key.fire = -> board.delete()
key.down = ->
key.icon.toggle('on')
handleKeyColor(key)
key.fire()
key.up = ->
key.icon.toggle('off')
handleKeyColor(key)
key.on Events.TouchStart, -> key.down()
key.on Events.TouchEnd, -> key.up()
return key
Numbers = (obj) ->
key = new SpecialKey obj
if ios.isPhone()
key.html = '123'
else
key.html ='.?123'
key.style.lineHeight = ios.px(specs.specialKeyHeight) + "px"
return key
Emoji = (obj) ->
key = new SpecialKey obj
key.icon = new Icon
superLayer:key
icon:ios.utils.svg(ios.assets.emoji)
return key
Return = (obj) ->
key = new SpecialKey obj
key.backgroundColor = colors.returnBG
key.html = setup.returnText
key.style.lineHeight = ios.px(specs.specialKeyHeight) + "px"
key.color = ios.utils.autoColor(colors.returnBG)
key.down = ->
nothingHappens = true
key.up = ->
board.dismiss()
if board.target
if board.target.parent
board.target.parent.active = false
key.on Events.TouchEnd, -> key.down()
key.on Events.TouchStart, -> key.up()
return key
Dismiss = (obj) ->
key = new SpecialKey obj
key.icon = new Icon
superLayer:key
icon:ios.utils.svg(ios.assets.keyboard)
key.icon.scale = .8
key.icon.constraints =
bottom:12
trailing:12
ios.layout.set(key.icon)
key.down = -> board.dismiss()
key.up = -> nothingHappens = false
key.on Events.TouchEnd, -> key.down()
return key
Tab = (obj) ->
key = new SpecialKey obj
key.html = 'tab'
key.style.lineHeight = ios.px(70) + 'px'
key.style.textAlign = 'left'
key.style.paddingLeft = ios.px(12) + 'px'
return key
board.switchLetters = ->
row1Break = 10
row2Break = 19
if ios.isPad()
letters.push '!'
letters.push '?'
if ios.device.name == "ipad-pro"
letters = ["q", "w", "e", "r", "t", "y", "u", "i", "o", "p", "{", "}", "\|", "a", "s", "d", "f", "g", "h", "j", "k", "l", ":", "”", "z", "x", "c", "v", "b", "n", "m", "<", ">", "?"]
topLetters = ["~", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "_", "+"]
row1Break = 13
row2Break = 24
for l, i in letters
key = new Letter
name:l
constraints:
height:specs.letterKey.height
width:specs.letterKey.width
letter:l
if l == 'w' || l == 'r' || l == 'y' || l == 'i' || l == 'p'
key.constraints.width = key.constraints.width + 1
board.keys[l] = key
board.keysArray.push key
if i == 0
key.constraints.leading = specs.row1.leading
key.constraints.top = specs.row1.top
if i > 0 && i < row1Break
key.constraints.leading = [board.keysArray[i - 1], specs.space]
key.constraints.top = specs.row1.top
if i == row1Break
key.constraints.leading = specs.row2.leading
key.constraints.top = [board.keysArray[0], specs.row2.top]
if i > row1Break && i < row2Break
key.constraints.leading = [board.keysArray[i - 1], specs.space]
key.constraints.top = [board.keysArray[0], specs.row2.top]
if i == row2Break
key.constraints.leading = specs.row3.leading
key.constraints.top = [board.keysArray[row1Break], specs.row3.top]
if i > row2Break
key.constraints.leading = [board.keysArray[i - 1], specs.space]
key.constraints.top = [board.keysArray[row1Break], specs.row3.top]
ios.layout.set(key)
board.keys.shift = new Shift
name:"shift"
shift:setup.shift
constraints:
height:specs.specialKeyHeight
width:specs.specialKeyWidth
bottomEdges:board.keys.z
board.keys.delete = new Delete
name:"delete"
constraints:
height:specs.specialKeyHeight
width:specs.specialKeyWidth
bottomEdges:board.keys.z
trailing:0
board.keys.numbers = new Numbers
name:"numbers"
constraints:
height:specs.specialKeyHeight
width:specs.specialKeyWidth
bottom:0
leading:0
board.keys.emoji = new Emoji
name:"emoji"
constraints:
height:specs.specialKeyHeight
width:specs.specialKeyWidth
leading:[board.keys.numbers, specs.space]
bottom:0
board.keys.return = new Return
name:"return"
constraints:
bottom:0
trailing:0
width:specs.returnWidth
height:specs.specialKeyHeight
board.keys.space = new Space
name:"space"
letter:"space"
constraints:
leading:[board.keys.emoji, specs.space]
trailing:[board.keys.return, specs.space]
bottom:0
height:specs.specialKeyHeight
if ios.isPad()
board.keys.return.constraints.bottom = undefined
board.keys.return.constraints.bottomEdges = board.keysArray[row1Break]
board.keys.delete.constraints.top = 0
board.keys.delete.constraints.bottomEdges = undefined
board.keys.delete.constraints.width = 61
board.keys.shiftalt = new Shift
name:"shiftalt"
shift:setup.shift
constraints:
height:specs.specialKeyHeight
width:76
bottomEdges:board.keys.z
trailing:0
board.keys.dismiss = new Dismiss
name:"dismiss"
constraints:
height:specs.specialKeyHeight
width:specs.specialKeyWidth
bottom:0
trailing:0
board.keys.numbersalt = new Numbers
name:"numbersalt"
constraints:
height:specs.specialKeyHeight
width:93
bottom:0
trailing:[board.keys.dismiss, specs.space]
board.keys.space.html = ""
board.keys.space.constraints.trailing = [board.keys.numbersalt, specs.space]
ios.layout.set()
board.topRow = []
if ios.device.name == 'ipad-pro'
for l,i in topLetters
topKey = new Letter
letter:l
name:l
constraints:
height:46
width:63
top:0
if i == 0
topKey.constraints.leading = 0
else
topKey.constraints.leading = [board.topRow[i - 1], specs.space]
topKey.style.lineHeight = ios.px(46) + 'px'
ios.layout.set(topKey)
board.topRow.push topKey
board.keysArray.push topKey
board.keys[l] = topKey
board.keys.delete.icon.destroy()
board.keys.delete.html = 'delete'
board.keys.delete.style.lineHeight = ios.px(53) + 'px'
board.keys.delete.style.textAlign = 'right'
board.keys.delete.style.paddingRight = ios.px(12) + 'px'
board.keys.delete.constraints =
top:0
trailing:0
height:46
width:106
board.keys.shift.icon.destroy()
board.keys.shift.html = 'shift'
board.keys.shift.style.lineHeight = ios.px(70) + 'px'
board.keys.shift.style.textAlign = 'left'
board.keys.shift.style.paddingLeft = ios.px(12) + 'px'
board.keys.shift.constraints.width = 154
board.keys.shiftalt.icon.destroy()
board.keys.shiftalt.html = 'shift'
board.keys.shiftalt.style.lineHeight = ios.px(70) + 'px'
board.keys.shiftalt.style.textAlign = 'right'
board.keys.shiftalt.style.paddingRight = ios.px(12) + 'px'
board.keys.shiftalt.constraints.width = 155
board.keys.emoji.icon.constraints = {leading:15, bottom:11}
board.keys.emoji.constraints =
width:144
height:61
leading:0
bottom:0
ios.layout.set()
board.keys.numbersalt.constraints.width = 93
board.keys.dismiss.constraints.width = 93
board.keys.com = new Letter
name:'.com'
letter:'.com'
constraints:
height:specs.letterKey.height
width:specs.letterKey.width
bottom:0
trailing:[board.keys.numbersalt, specs.space]
board.keys.com.style.fontSize = ios.px(16) + 'px'
board.keys.numbers.constraints =
width:143
height:61
leading:[board.keys.emoji, specs.space]
board.keys.numbers.style.lineHeight = ios.px(70) + 'px'
board.keys.numbers.style.textAlign = 'left'
board.keys.numbers.style.paddingLeft = ios.px(12) + 'px'
board.keys.return.style.lineHeight = ios.px(70) + 'px'
board.keys.return.style.textAlign = 'right'
board.keys.return.style.paddingRight = ios.px(12) + 'px'
board.keys.space.constraints.leading = [board.keys.numbers, specs.space]
board.keys.space.constraints.trailing = [board.keys.com, specs.space]
board.keys.caps = new Shift
name:'caps'
caps: true
constraints:
height:specs.specialKeyHeight
width:119
bottomEdges:board.keysArray[row1Break]
board.keys.caps.icon.destroy()
board.keys.caps.html = 'caps lock'
board.keys.caps.style.lineHeight = ios.px(70) + 'px'
board.keys.caps.style.textAlign = 'left'
board.keys.caps.style.paddingLeft = ios.px(12) + 'px'
board.keys.caps.down = ->
if board.isCapsLock
board.isCapsLock = false
else
board.capsLock()
board.keys.caps.on Events.TouchEnd, ->
board.keys.caps.down()
board.keys.caps.up = ->
nothingHappens = true
board.keys.tab = new Tab
name:'tab'
constraints:
height:specs.specialKeyHeight
width:106
bottomEdges:board.keysArray[0]
ios.layout.set()
if ios.isPhone()
popUp = ios.utils.svg(ios.assets.keyPopUp[setup.style][ios.device.name])
board.popUp = new Layer
height:popUp.height
width:popUp.width
backgroundColor:'transparent'
name:'.popUp'
superLayer:board.area
visible:false
board.popUp.svg = new Layer
html:popUp.svg
height:popUp.height
width:popUp.width
superLayer:board.popUp
name:'.svg'
backgroundColor:'transparent'
board.popUp.text = new ios.Text
text:'A'
superLayer:board.popUp
fontSize:specs.popUpChar
fontWeight:300
color:colors.color
textAlign:'center'
constraints:
align:'horizontal'
top:specs.popUpTop
width:ios.pt(popUp.width)
board.popUp.center()
switch ios.device.name
when 'iphone-6s-plus'
board.popUp.width = board.popUp.width - 18
board.popUp.height = board.popUp.height - 24
board.popUp.svg.x = ios.px(-3)
board.popUp.svg.y = ios.px(-3)
when 'iphone-6s'
board.popUp.width = board.popUp.width - 12
board.popUp.height = board.popUp.height - 12
board.popUp.svg.x = ios.px(-3)
board.popUp.svg.y = ios.px(-2)
when 'iphone-5'
board.popUp.width = board.popUp.width - 12
board.popUp.height = board.popUp.height - 12
board.popUp.svg.x = ios.px(-3)
board.popUp.svg.y = ios.px(-2)
capitalizeKeys()
board.switch = (state) ->
switch state
when "letters"
board.switchLetters()
board.switch("letters")
document.addEventListener 'keydown', (e) ->
if arrayOfCodes.indexOf(e.keyCode.toString()) != -1
key = board.keys[codeMap[e.keyCode].toLowerCase()]
if key then key.down()
if ios.isPad()
if key == board.keys.shift || key == board.keys.shiftalt
board.keys.shift.down()
board.keys.shiftalt.icon.toggle('on')
handleKeyColor(board.keys.shiftalt)
document.addEventListener 'keyup', (e) ->
if arrayOfCodes.indexOf(e.keyCode.toString()) != -1
key = board.keys[codeMap[e.keyCode].toLowerCase()]
if key then key.up()
if ios.isPad()
if key == board.keys.shift || key == board.keys.shiftalt
board.keys.shift.up()
board.keys.shiftalt.icon.toggle('off')
handleKeyColor(board.keys.shiftalt)
capitalizeKeys()
return board
| true | ios = require 'ios-kit'
exports.defaults =
style:"light"
shift:true
output:undefined
returnText:"return"
state:"letters"
hidden:false
returnColor:"blue"
superLayer:undefined
#Responsabile for keyboard dimensions
device =
"iphone-5":
popUpChar:40
popUpTop:4
height:215
lineHeight:36
letterKey:
keyTop:6
height:39
width:26.5
borderRadius:5
fontSize:22.5
specialKeyWidth:38.5
specialKeyHeight:38.5
space:5
row1:
leading:0
top:0
row2:
leading:19
top:16
row3:
top:16
leading:51
area:
top:11
leading:3
trailing:3
bottom:4
returnWidth:75
popUpOffset:
x:4
y:30
"iphone-6s":
popUpChar:40
popUpTop:6
height:218
lineHeight:40
letterKey:
keyTop:10
height:42
width:31.5
borderRadius:5
fontSize:23
top:10
specialKeyWidth:42
specialKeyHeight:42
space:6
row1:
leading:0
top:0
row2:
leading:22
top:12
row3:
top:12
leading:59
area:
top:12
leading:3
trailing:3
bottom:4
returnWidth:87
popUpOffset:
x:5
y:32
"iphone-6s-plus":
popUpChar:38
popUpTop:6
height:226
lineHeight:42
letterKey:
keyTop:12
height:45
width:36
borderRadius:5
fontSize:24
top:10
specialKeyWidth:45
specialKeyHeight:45
space:5
row1:
leading:0
top:0
row2:
leading:20
top:11
row3:
top:11
leading:63
area:
top:8
leading:4
trailing:4
bottom:5
returnWidth:97
popUpOffset:
x:10
y:38
"ipad":
height:313
lineHeight:55
letterKey:
height:55
width:56
borderRadius:5
fontSize:23
specialKeyWidth:56
specialKeyHeight:55
space:12
returnWidth:106
row1:
leading:0
top:0
row2:
leading:30
top:9
row3:
leading:68
top:9
area:
top:55
leading:6
trailing:6
bottom:8
"ipad-pro":
height:378
lineHeight:61
letterKey:
height:61
width:63
borderRadius:5
fontSize:23
space:7
returnWidth:120
specialKeyHeight:61
specialKeyWidth:93
row1:
leading:111
top:53
row2:
leading:126
top:7
row3:
leading:161
top:7
area:
top:56
leading:4
trailing:4
bottom:4
# Map of key codes
# Codes for all keys
codeMap = { 8:'delete', 9:'tab', 13:'return', 16:'shift', 20:'caps', 32:'space', 27:"dismiss", 33:"!", 34:"\"", 35:"#", 36:"$", 37:"%", 38:"&", 39:"\'", 40:"(", 41:")", 42:"*", 43:"+", 44:",", 45:"-", 47:"/", 46:".", 48:"0", 49:"!", 50:"@", 51:"#", 52:"$", 53:"%", 54:"^", 55:"&", 56:"*", 57:"(", 48:")", 59:"_", 60:"<", 61:"=", 62:">", 63:"?", 64:"@", 65:"A", 66:"B", 67:"C", 68:"D", 69:"E", 70:"F", 71:"G", 72:"H", 73:"I", 74:"J", 75:"K", 76:"L", 77:"M", 78:"N", 79:"O", 80:"P", 81:"Q", 82:"R", 83:"S", 84:"T", 85:"U", 86:"V", 87:"W", 88:"X", 89:"Y", 90:"Z", 91:'cmd', 219:"[", 92:"\\", 221:"]", 94:"^", 95:"_", 96:"`", 97:"a", 98:"b", 99:"c", 100:"d", 101:"e", 102:"f", 103:"g", 104:"h", 105:"i", 106:"j", 107:"k", 108:"l", 109:"m", 110:"n", 111:"o", 112:"p", 113:"q", 114:"r", 115:"s", 116:"t", 117:"u", 118:"v", 119:"w", 120:"x", 121:"y", 122:"z", 123:"{", 124:"|", 125:"}", 126:"~", 186:":", 187:"+", 188:"<", 190:">", 191:"?", 189:"_", 192:"~", 219:"{", 220:"\|", 221:"}", 222:"”"}
arrayOfCodes = Object.keys(codeMap)
letters = ["q", "w", "e", "r", "t", "y", "u", "i", "o", "p", "a", "s", "d", "f", "g", "h", "j", "k", "l", "z", "x", "c", "v", "b", "n", "m"]
numbers = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "-", "/", ":", ";", "(", ")", "$", "&", "@", "\"", ".", ",", "?", "!", "′"]
symbols = ["[", "]", "{", "}", "#", "%", "^", "*", "+", "=", "_", "\\", "|", "~", "<", ">", "€", "£", "¥", "•"]
exports.defaults.props = Object.keys(exports.defaults)
exports.create = (obj) ->
setup = ios.utils.setupComponent(obj, exports.defaults)
#Responsabile for colors
style =
light:
backgroundColor:"#D1D5DA"
color:"#000"
specialKeyBG:"PI:KEY:<KEY>END_PI"
keyBG:"PI:KEY:<KEY>END_PI"
shadowY: ios.px(1)
shadowColor:"#898B8F"
returnBG:ios.color(setup.returnColor)
dark:
backgroundColor:"rgba(0,0,0,.7)"
color:"#FFF"
specialKeyBG:"rgba(67,67,67,.8)"
keyBG:"rgba(105,105,105,.8)"
shadowY: ios.px(1)
shadowColor:"rgba(0,0,0,.4)"
returnBG:ios.color(setup.returnColor)
specs = device[ios.device.name]
colors = style[setup.style]
device
board = new ios.View
name:"Keyboard"
superLayer:setup.superLayer
backgroundColor:style[setup.style].backgroundColor
y:ios.device.height
constraints:
leading:0
trailing:0
bottom:-1 * specs.height
height:specs.height
ios.utils.bgBlur(board)
board.output = (obj) ->
if board.target
if board.target.type == 'field'
board.target.active = false
board.target = obj
if board.target
if board.target.type == 'field'
board.target.active = true
board.hidden = setup.hidden
if board.hidden == false
board.constraints.bottom = 0
ios.layout.set(board)
board.call = () ->
board.y = ios.device.height
board.constraints.bottom = 0
if board.hidden
board.hidden = false
ios.layout.animate
target:board
time:.5
curve:'ease-in-out'
board.bringToFront()
board.dismiss = () ->
board.constraints.bottom = -1 * ios.pt(board.height)
board.hidden = true
board.target.active = false
ios.layout.animate
target:board
time:.5
curve:'ease-in-out'
board.delete = () ->
layer = ""
if board.target
if board.target.type == 'field'
layer = board.target.text
else
layer = board.target
isSpace = layer.html[layer.html.length - 5..layer.html.length - 1 ]
if isSpace != 'nbsp;'
text = layer.html.slice(0, -1)
layer.html = text
else
text = layer.html.slice(0, -6)
layer.html = text
board.capsLock = () ->
board.isCapsLock = true
board.isCapital = true
board.keys.shift.icon.toggle('off')
handleKeyColor(board.keys.shift)
if ios.device.name == 'ipad-pro'
board.keys.shiftalt.icon.toggle('off')
handleKeyColor(board.keys.shiftalt)
board.output(setup.output)
board.keysArray = []
board.keys = {}
board.isCapital = setup.shift
board.area = new ios.View
name:".area"
superLayer:board
constraints: specs.area
backgroundColor:"transparent"
Key = (obj) ->
key = new ios.View
name:".keys." + obj.name
constraints:obj.constraints
superLayer:board.area
borderRadius:ios.px(specs.letterKey.borderRadius)
shadowY:colors.shadowY
shadowColor:colors.shadowColor
key.style.fontFamily = "-apple-system, Helvetica, Arial, sans-serif"
#Disables Zoom
key.on Events.TouchStart, (event) ->
event.preventDefault()
return key
Letter = (obj) ->
key = new Key obj
key.backgroundColor = colors.keyBG
key.html = obj.letter
key.color = colors.color
key.style.textAlign = "center"
key.style.lineHeight = ios.px(specs.lineHeight) + "px"
key.style.fontSize = ios.px(specs.letterKey.fontSize) + "px"
key.value = obj.letter
if key.value == "space" then key.value = " "
if ios.isPad()
key.down = ->
key.backgroundColor = colors.specialKeyBG
if board.target then ios.utils.write(board.target, key.value)
key.up = ->
key.backgroundColor = colors.keyBG
if board.isCapital && board.isCapsLock != true
board.isCapital = false
capitalizeKeys()
board.keys.shift.up()
if ios.isPad() then board.keys.shiftalt.up()
key.on Events.TouchStart, ->
key.down()
key.on Events.TouchEnd, ->
key.up()
else
if key.value != ' '
key.down = ->
board.popUp.visible = true
board.bringToFront()
board.popUp.bringToFront()
board.popUp.midX = key.midX
board.popUp.maxY = key.maxY
board.popUp.text.html = key.value
if board.target then ios.utils.write(board.target, key.value)
key.up = ->
board.popUp.visible = false
if board.isCapital && board.capsLock != true
board.isCapital = false
capitalizeKeys()
board.keys.shift.up()
key.on Events.TouchStart, -> key.down()
key.on Events.TouchEnd, -> key.up()
else
key.down = ->
key.backgroundColor = colors.specialKeyBG
if board.target then ios.utils.write(board.target, key.value)
key.up = ->
key.backgroundColor = colors.keyBG
key.on Events.TouchStart, ->
key.down()
key.on Events.TouchEnd, ->
key.up()
return key
SpecialKey = (obj) ->
key = new Key obj
key.backgroundColor = colors.specialKeyBG
key.color = colors.color
key.style.textAlign = "center"
if ios.device.name == 'ipad-pro'
key.style.fontSize = ios.px(18) + "px"
else
key.style.fontSize = ios.px(16) + "px"
return key
Icon = (obj) ->
icon = new ios.View
name:'icon'
backgroundColor:"transparent"
superLayer:obj.superLayer
constraints:
align:'center'
icon.props = (height:obj.icon.height, width:obj.icon.width, html: obj.icon.svg)
ios.utils.changeFill(icon, colors.color)
return icon
IconWithState = (obj) ->
icon = new ios.View
name:'icon'
backgroundColor:"transparent"
superLayer:obj.superLayer
constraints:
align:'center'
icon.toggle = (state) ->
if state == undefined
if icon.state == 'on' then state = 'off'
else state = 'on'
if state == "on"
if ios.device.name != 'ipad-pro'
icon.html = obj.on.svg
icon.width = obj.on.width
icon.height = obj.on.height
icon.state = 'on'
else
if ios.device.name != 'ipad-pro'
icon.html = obj.off.svg
icon.width = obj.on.width
icon.height = obj.on.height
icon.state = 'off'
ios.utils.changeFill(icon, colors.color)
if obj.state
icon.toggle('on')
else
icon.toggle('off')
return icon
capitalizeKeys = ->
for key in board.keysArray
if board.isCapital
if key.html.length == 1 && key.html.match(/[a-z]/i)
key.html = key.html.toUpperCase()
key.value = key.html
if key.alt
key.alt.destroy()
key.alt = undefined
if key.height > ios.px(46)
key.style.lineHeight = ios.px(specs.letterKey.height) + 'px'
key.style.fontSize = ios.px(23) + 'px'
else
if ios.device.name == 'ipad-pro'
key.style.lineHeight = ios.px(46) + 'px'
else
key.style.lineHeight = ios.px(specs.lineHeight) + 'px'
key.style.fontSize = ios.px(20) + 'px'
key.value = key.html
else
if key.html.length == 1 && key.html.match(/[a-z]/i)
key.html = key.html.toLowerCase()
key.value = key.html
else
if key.alt == undefined
key.alt = new ios.Text
text:""
superLayer:key
color:colors.color
constraints:
align:"horizontal"
bottom:4
fontSize:specs.letterKey.fontSize
if board.topRow
if board.topRow.indexOf(key) != -1
key.style.lineHeight = ios.px(23) + 'px'
key.style.fontSize = ios.px(16) + 'px'
key.alt.style.fontSize = ios.px(16) + 'px'
else
key.style.lineHeight = ios.px(36) + 'px'
key.style.fontSize = ios.px(20) + 'px'
key.alt.style.fontSize = ios.px(20) + 'px'
key.alt.constraints.bottom = 8
switch key.value
when "<"
key.alt.html = "."
when ">"
key.alt.html = ","
when "<"
key.alt.html = "."
when ">"
key.alt.html = ","
when "?"
key.alt.html = "."
when "{"
key.alt.html = "["
when "}"
key.alt.html = "}"
when "\|"
key.alt.html = "\\"
when "~"
key.alt.html = "`"
when "!"
key.alt.html = "."
when "@"
key.alt.html = "2"
when "#"
key.alt.html = "3"
when "$"
key.alt.html = "4"
when "%"
key.alt.html = "5"
when "^"
key.alt.html = "6"
when "&"
key.alt.html = "7"
when "&"
key.alt.html = "7"
when "*"
key.alt.html = "8"
when "("
key.alt.html = "9"
when ")"
key.alt.html = "0"
when "_"
key.alt.html = "-"
when "+"
key.alt.html = "="
else
key.alt.html = "′"
ios.layout.set(key.alt)
if ios.device.name == 'ipad-pro' && key.value == '!' then key.alt.html = '1'
if ios.device.name == 'ipad-pro' && key.value == '?' then key.alt.html = '/'
if ios.device.name == 'ipad-pro' && key.value == ':' then key.alt.html = ';'
if ios.device.name == 'ipad-pro' && key.value == '”' then key.alt.html = '′'
key.value = key.alt.html
handleKeyColor = (key) ->
if ios.isPhone
if key.icon.state == 'on' then key.backgroundColor = colors.keyBG
else key.backgroundColor = colors.specialKeyBG
Space = (obj) ->
key = new Letter obj
key.html = 'space'
key.backgroundColor = colors.keyBG
key.style.lineHeight = ios.px(specs.specialKeyHeight) + "px"
key.style.fontSize = ios.px(16) + 'px'
return key
Shift = (obj) ->
key = new SpecialKey obj
key.icon = new IconWithState
superLayer:key
state:obj.shift
on:ios.utils.svg(ios.assets.shift.on)
off:ios.utils.svg(ios.assets.shift.off)
handleKeyColor(key)
key.on Events.TouchEnd, ->
@.icon.toggle()
handleKeyColor(key)
if @.icon.state == 'on'
board.isCapital = true
else
board.isCapital = false
capitalizeKeys()
key.down = ->
key.icon.toggle('on')
handleKeyColor(key)
board.isCapital = true
capitalizeKeys()
key.up = ->
key.icon.toggle('off')
handleKeyColor(key)
board.isCapital = false
capitalizeKeys()
ios.layout.set(key.icon)
if ios.isPad()
key.on Events.TouchEnd, ->
if @.icon.state == 'on'
board.keys.shift.icon.toggle('on')
board.keys.shiftalt.icon.toggle('on')
else
board.keys.shift.icon.toggle('off')
board.keys.shiftalt.icon.toggle('off')
handleKeyColor(board.keys.shift)
handleKeyColor(board.keys.shiftalt)
return key
Delete = (obj) ->
key = new SpecialKey obj
key.icon = new IconWithState
superLayer:key
on:ios.utils.svg(ios.assets.delete.on)
off:ios.utils.svg(ios.assets.delete.off)
key.fire = -> board.delete()
key.down = ->
key.icon.toggle('on')
handleKeyColor(key)
key.fire()
key.up = ->
key.icon.toggle('off')
handleKeyColor(key)
key.on Events.TouchStart, -> key.down()
key.on Events.TouchEnd, -> key.up()
return key
Numbers = (obj) ->
key = new SpecialKey obj
if ios.isPhone()
key.html = '123'
else
key.html ='.?123'
key.style.lineHeight = ios.px(specs.specialKeyHeight) + "px"
return key
Emoji = (obj) ->
key = new SpecialKey obj
key.icon = new Icon
superLayer:key
icon:ios.utils.svg(ios.assets.emoji)
return key
Return = (obj) ->
key = new SpecialKey obj
key.backgroundColor = colors.returnBG
key.html = setup.returnText
key.style.lineHeight = ios.px(specs.specialKeyHeight) + "px"
key.color = ios.utils.autoColor(colors.returnBG)
key.down = ->
nothingHappens = true
key.up = ->
board.dismiss()
if board.target
if board.target.parent
board.target.parent.active = false
key.on Events.TouchEnd, -> key.down()
key.on Events.TouchStart, -> key.up()
return key
Dismiss = (obj) ->
key = new SpecialKey obj
key.icon = new Icon
superLayer:key
icon:ios.utils.svg(ios.assets.keyboard)
key.icon.scale = .8
key.icon.constraints =
bottom:12
trailing:12
ios.layout.set(key.icon)
key.down = -> board.dismiss()
key.up = -> nothingHappens = false
key.on Events.TouchEnd, -> key.down()
return key
Tab = (obj) ->
key = new SpecialKey obj
key.html = 'tab'
key.style.lineHeight = ios.px(70) + 'px'
key.style.textAlign = 'left'
key.style.paddingLeft = ios.px(12) + 'px'
return key
board.switchLetters = ->
row1Break = 10
row2Break = 19
if ios.isPad()
letters.push '!'
letters.push '?'
if ios.device.name == "ipad-pro"
letters = ["q", "w", "e", "r", "t", "y", "u", "i", "o", "p", "{", "}", "\|", "a", "s", "d", "f", "g", "h", "j", "k", "l", ":", "”", "z", "x", "c", "v", "b", "n", "m", "<", ">", "?"]
topLetters = ["~", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "_", "+"]
row1Break = 13
row2Break = 24
for l, i in letters
key = new Letter
name:l
constraints:
height:specs.letterKey.height
width:specs.letterKey.width
letter:l
if l == 'w' || l == 'r' || l == 'y' || l == 'i' || l == 'p'
key.constraints.width = key.constraints.width + 1
board.keys[l] = key
board.keysArray.push key
if i == 0
key.constraints.leading = specs.row1.leading
key.constraints.top = specs.row1.top
if i > 0 && i < row1Break
key.constraints.leading = [board.keysArray[i - 1], specs.space]
key.constraints.top = specs.row1.top
if i == row1Break
key.constraints.leading = specs.row2.leading
key.constraints.top = [board.keysArray[0], specs.row2.top]
if i > row1Break && i < row2Break
key.constraints.leading = [board.keysArray[i - 1], specs.space]
key.constraints.top = [board.keysArray[0], specs.row2.top]
if i == row2Break
key.constraints.leading = specs.row3.leading
key.constraints.top = [board.keysArray[row1Break], specs.row3.top]
if i > row2Break
key.constraints.leading = [board.keysArray[i - 1], specs.space]
key.constraints.top = [board.keysArray[row1Break], specs.row3.top]
ios.layout.set(key)
board.keys.shift = new Shift
name:"shift"
shift:setup.shift
constraints:
height:specs.specialKeyHeight
width:specs.specialKeyWidth
bottomEdges:board.keys.z
board.keys.delete = new Delete
name:"delete"
constraints:
height:specs.specialKeyHeight
width:specs.specialKeyWidth
bottomEdges:board.keys.z
trailing:0
board.keys.numbers = new Numbers
name:"numbers"
constraints:
height:specs.specialKeyHeight
width:specs.specialKeyWidth
bottom:0
leading:0
board.keys.emoji = new Emoji
name:"emoji"
constraints:
height:specs.specialKeyHeight
width:specs.specialKeyWidth
leading:[board.keys.numbers, specs.space]
bottom:0
board.keys.return = new Return
name:"return"
constraints:
bottom:0
trailing:0
width:specs.returnWidth
height:specs.specialKeyHeight
board.keys.space = new Space
name:"space"
letter:"space"
constraints:
leading:[board.keys.emoji, specs.space]
trailing:[board.keys.return, specs.space]
bottom:0
height:specs.specialKeyHeight
if ios.isPad()
board.keys.return.constraints.bottom = undefined
board.keys.return.constraints.bottomEdges = board.keysArray[row1Break]
board.keys.delete.constraints.top = 0
board.keys.delete.constraints.bottomEdges = undefined
board.keys.delete.constraints.width = 61
board.keys.shiftalt = new Shift
name:"shiftalt"
shift:setup.shift
constraints:
height:specs.specialKeyHeight
width:76
bottomEdges:board.keys.z
trailing:0
board.keys.dismiss = new Dismiss
name:"dismiss"
constraints:
height:specs.specialKeyHeight
width:specs.specialKeyWidth
bottom:0
trailing:0
board.keys.numbersalt = new Numbers
name:"numbersalt"
constraints:
height:specs.specialKeyHeight
width:93
bottom:0
trailing:[board.keys.dismiss, specs.space]
board.keys.space.html = ""
board.keys.space.constraints.trailing = [board.keys.numbersalt, specs.space]
ios.layout.set()
board.topRow = []
if ios.device.name == 'ipad-pro'
for l,i in topLetters
topKey = new Letter
letter:l
name:l
constraints:
height:46
width:63
top:0
if i == 0
topKey.constraints.leading = 0
else
topKey.constraints.leading = [board.topRow[i - 1], specs.space]
topKey.style.lineHeight = ios.px(46) + 'px'
ios.layout.set(topKey)
board.topRow.push topKey
board.keysArray.push topKey
board.keys[l] = topKey
board.keys.delete.icon.destroy()
board.keys.delete.html = 'delete'
board.keys.delete.style.lineHeight = ios.px(53) + 'px'
board.keys.delete.style.textAlign = 'right'
board.keys.delete.style.paddingRight = ios.px(12) + 'px'
board.keys.delete.constraints =
top:0
trailing:0
height:46
width:106
board.keys.shift.icon.destroy()
board.keys.shift.html = 'shift'
board.keys.shift.style.lineHeight = ios.px(70) + 'px'
board.keys.shift.style.textAlign = 'left'
board.keys.shift.style.paddingLeft = ios.px(12) + 'px'
board.keys.shift.constraints.width = 154
board.keys.shiftalt.icon.destroy()
board.keys.shiftalt.html = 'shift'
board.keys.shiftalt.style.lineHeight = ios.px(70) + 'px'
board.keys.shiftalt.style.textAlign = 'right'
board.keys.shiftalt.style.paddingRight = ios.px(12) + 'px'
board.keys.shiftalt.constraints.width = 155
board.keys.emoji.icon.constraints = {leading:15, bottom:11}
board.keys.emoji.constraints =
width:144
height:61
leading:0
bottom:0
ios.layout.set()
board.keys.numbersalt.constraints.width = 93
board.keys.dismiss.constraints.width = 93
board.keys.com = new Letter
name:'.com'
letter:'.com'
constraints:
height:specs.letterKey.height
width:specs.letterKey.width
bottom:0
trailing:[board.keys.numbersalt, specs.space]
board.keys.com.style.fontSize = ios.px(16) + 'px'
board.keys.numbers.constraints =
width:143
height:61
leading:[board.keys.emoji, specs.space]
board.keys.numbers.style.lineHeight = ios.px(70) + 'px'
board.keys.numbers.style.textAlign = 'left'
board.keys.numbers.style.paddingLeft = ios.px(12) + 'px'
board.keys.return.style.lineHeight = ios.px(70) + 'px'
board.keys.return.style.textAlign = 'right'
board.keys.return.style.paddingRight = ios.px(12) + 'px'
board.keys.space.constraints.leading = [board.keys.numbers, specs.space]
board.keys.space.constraints.trailing = [board.keys.com, specs.space]
board.keys.caps = new Shift
name:'caps'
caps: true
constraints:
height:specs.specialKeyHeight
width:119
bottomEdges:board.keysArray[row1Break]
board.keys.caps.icon.destroy()
board.keys.caps.html = 'caps lock'
board.keys.caps.style.lineHeight = ios.px(70) + 'px'
board.keys.caps.style.textAlign = 'left'
board.keys.caps.style.paddingLeft = ios.px(12) + 'px'
board.keys.caps.down = ->
if board.isCapsLock
board.isCapsLock = false
else
board.capsLock()
board.keys.caps.on Events.TouchEnd, ->
board.keys.caps.down()
board.keys.caps.up = ->
nothingHappens = true
board.keys.tab = new Tab
name:'tab'
constraints:
height:specs.specialKeyHeight
width:106
bottomEdges:board.keysArray[0]
ios.layout.set()
if ios.isPhone()
popUp = ios.utils.svg(ios.assets.keyPopUp[setup.style][ios.device.name])
board.popUp = new Layer
height:popUp.height
width:popUp.width
backgroundColor:'transparent'
name:'.popUp'
superLayer:board.area
visible:false
board.popUp.svg = new Layer
html:popUp.svg
height:popUp.height
width:popUp.width
superLayer:board.popUp
name:'.svg'
backgroundColor:'transparent'
board.popUp.text = new ios.Text
text:'A'
superLayer:board.popUp
fontSize:specs.popUpChar
fontWeight:300
color:colors.color
textAlign:'center'
constraints:
align:'horizontal'
top:specs.popUpTop
width:ios.pt(popUp.width)
board.popUp.center()
switch ios.device.name
when 'iphone-6s-plus'
board.popUp.width = board.popUp.width - 18
board.popUp.height = board.popUp.height - 24
board.popUp.svg.x = ios.px(-3)
board.popUp.svg.y = ios.px(-3)
when 'iphone-6s'
board.popUp.width = board.popUp.width - 12
board.popUp.height = board.popUp.height - 12
board.popUp.svg.x = ios.px(-3)
board.popUp.svg.y = ios.px(-2)
when 'iphone-5'
board.popUp.width = board.popUp.width - 12
board.popUp.height = board.popUp.height - 12
board.popUp.svg.x = ios.px(-3)
board.popUp.svg.y = ios.px(-2)
capitalizeKeys()
board.switch = (state) ->
switch state
when "letters"
board.switchLetters()
board.switch("letters")
document.addEventListener 'keydown', (e) ->
if arrayOfCodes.indexOf(e.keyCode.toString()) != -1
key = board.keys[codeMap[e.keyCode].toLowerCase()]
if key then key.down()
if ios.isPad()
if key == board.keys.shift || key == board.keys.shiftalt
board.keys.shift.down()
board.keys.shiftalt.icon.toggle('on')
handleKeyColor(board.keys.shiftalt)
document.addEventListener 'keyup', (e) ->
if arrayOfCodes.indexOf(e.keyCode.toString()) != -1
key = board.keys[codeMap[e.keyCode].toLowerCase()]
if key then key.up()
if ios.isPad()
if key == board.keys.shift || key == board.keys.shiftalt
board.keys.shift.up()
board.keys.shiftalt.icon.toggle('off')
handleKeyColor(board.keys.shiftalt)
capitalizeKeys()
return board
|
[
{
"context": "\"\n\nnetuno.callbacks =\n create: (func)->\n key = netuno.newUid()\n netuno.callbacks[key] = func\n return key",
"end": 726,
"score": 0.8779361844062805,
"start": 713,
"tag": "KEY",
"value": "netuno.newUid"
},
{
"context": "nfig\n if (config.name == null)\n return\n key = netuno.newUid()\n $.ajax(\n type: 'POST'\n url: \"#{ netuno.co",
"end": 21777,
"score": 0.9983717799186707,
"start": 21762,
"tag": "KEY",
"value": "netuno.newUid()"
},
{
"context": ": \"Reference link\",\n name : \"Name\",\n url : \"Address\",\n ",
"end": 28546,
"score": 0.9994381070137024,
"start": 28542,
"tag": "NAME",
"value": "Name"
}
] | bundle/base/web/netuno/scripts/sbadmin/netuno/core.coffee | netuno-org/platform | 19 |
toastr.options = {
"closeButton": true,
"debug": false,
"newestOnTop": true,
"progressBar": false,
"positionClass": "toast-top-center",
"preventDuplicates": true,
"onclick": null,
"showDuration": "300",
"hideDuration": "1000",
"timeOut": "3000",
"extendedTimeOut": "1000",
"showEasing": "swing",
"hideEasing": "linear",
"showMethod": "fadeIn",
"hideMethod": "fadeOut"
}
$ ->
$('form').submit ->
false
return
netuno.newUid = ()->
s4 = () ->
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1)
return "#{ s4() }#{ s4() }_#{ s4() }_#{ s4() }_#{ s4() }_#{ s4() }#{ s4() }#{ s4() }"
netuno.callbacks =
create: (func)->
key = netuno.newUid()
netuno.callbacks[key] = func
return key
remove: (key)->
delete netuno.callbacks[key]
netuno.menu = (menu)->
navMenuHtml = "<li><a netuno-navigation-dashboard href=\"#netuno_dashboard\"><i class=\"fa fa-fw fa-dashboard\"></i> #{ netuno.lang['menu.dashboard'] }</a></li>"
containersHtml = ''
buildMenu = (type, parentUId, items, level) ->
menuHtml = '';
if level > 0
menuHtml += '<ul>'
for item in items
expand = ""
if item.items.length > 0
expand = " data-toggle="
menuHtml += '<li>'
menuHtml += "<a netuno-navigation-#{ type }-item.name href=\"\#\" netuno-#{ type }=\"#{ item.name }\"#{ expand }>"
menuHtml += "#{ item.text }"
if item.items.length > 0
menuHtml += "<i class=\"fa fa-fw fa-caret-down\"></i>"
menuHtml += "</a>"
if item.items.length > 0
menuHtml += buildMenu(type, item.uid, item.items, level + 1)
menuHtml += '</li>'
containersHtml += "<div netuno-container-#{ type }-#{ item.name } netuno-#{ type } netuno-#{ type }-uid=\"#{ item.uid }\" netuno-#{ type }-name=\"#{ item.name }\">"
if type is 'form'
containersHtml += "<div class=\"netuno-form-edit\" netuno-#{ type }-edit=\"#{ item.name }\"></div>"
containersHtml += "<div class=\"netuno-form-search\" netuno-#{ type }-search=\"#{ item.name }\"></div>"
containersHtml += "</div>"
if level > 0
menuHtml += '</ul>'
return menuHtml
if menu.forms.length > 0
navMenuHtml += "<li class=\"nav-section-title\"><h4> <i class=\"fa fa-fw fa-edit\"></i>#{ netuno.lang['menu.forms'] }</h4></li>"
navMenuHtml += buildMenu 'form', 0, menu.forms, 0
if menu.reports.length > 0
navMenuHtml += "<li class=\"nav-section-title\"><h4> <i class=\"fa fa-fw fa-area-chart\"></i>#{ netuno.lang['menu.reports'] }</h4></li>"
navMenuHtml += buildMenu 'report', 0, menu.reports, 0
navbar = $('[netuno-navigation]')
navbar.append(navMenuHtml).show().find('ul').hide()
navbar.trigger('netuno:loaded')
containers = $('[netuno-containers]')
containers.append(containersHtml)
containers.trigger('netuno:loaded')
netuno.navigationLoaded()
netuno.loadForm = (container) ->
container = $(container) unless container instanceof jQuery
container = if container.is("[netuno-form][netuno-form-uid]") then container else container.closest("[netuno-form][netuno-form-uid]")
containerSearch = container.children('[netuno-form-search]')
data = { 'netuno_table_uid': container.attr('netuno-form-uid') }
if container.is("[netuno-form-relation]")
data['netuno_relation_table_uid'] = container.attr('netuno-table-uid')
data['netuno_relation_item_uid'] = container.attr('netuno-item-uid')
if containerSearch.is(':empty')
containerSearch.html("<div class=\"netuno-loader\">Loading...</div>")
$.ajax(
type: 'POST'
url: "#{ netuno.config.urlAdmin }Search#{ netuno.config.extension }"
data: data
success: (response) ->
containerSearch.html(response)
netuno.contentLoaded(containerSearch)
)
container.show()
netuno.formSearchDataTableBulk = {}
netuno.formSearchDataTableBulkActive = (tableId, callback) ->
netuno.formSearchDataTableBulk[tableId] = {
active: true,
callback: callback,
uids: []
}
table = $("\##{tableId}")
searchContainer = table.parents("[netuno-form-search]:first")
searchContainer.find("[netuno-form-search-buttons]").find("button").prop('disabled', true).fadeTo("slow", 0.5)
searchContainer.find("h1.page-header").find('button').prop('disabled', true).fadeTo("slow", 0.5)
netuno.formSearchDataTableBulkInactive = (tableId) ->
if netuno.formSearchDataTableBulk[tableId]?
delete netuno.formSearchDataTableBulk[tableId]
table = $("\##{tableId}")
tableBody = table.find('tbody')
tableBody.find('tr').each () ->
tr = $(this)
tr.removeClass('selected')
searchContainer = table.parents("[netuno-form-search]:first")
searchContainer.find("[netuno-form-search-buttons]").find("button").prop('disabled', false).fadeTo("slow", 1)
searchContainer.find("h1.page-header").find('button').prop('disabled', false).fadeTo("slow", 1)
netuno.executeFormSearchBulk = (settings) ->
settings = $.extend {
action: null
tableId: null
callback: (resut)->
}, settings
table = $("\##{settings.tableId}")
container = table.parents("[netuno-form][netuno-form-uid]:first")
container.data({
pageNumber: 0,
pageLength: 0,
rowIndex: 0
})
uids = netuno.formSearchDataTableBulk[settings.tableId].uids
$.ajax(
type: 'POST'
url: "#{ netuno.config.urlAdmin }Search#{ netuno.config.extension }"
dataType: 'json'
contentType : 'application/json',
data: JSON.stringify({
netuno_action: "bulk-#{settings.action}"
netuno_table_name: container.attr('netuno-form-name'),
netuno_items_uids: uids
})
success: (response) ->
settings.callback(response)
)
netuno.loadFormSearchDataTable = (table) ->
table = $(table) unless table instanceof jQuery
isButton = table.is('button')
container = table.parents("[netuno-form][netuno-form-uid]:first")
table = container.find("[netuno-form-search-table=#{ container.attr('netuno-form-name') }]:first") unless table.is('table')
tableId = table.attr('id')
netuno.formSearchDataTableBulkInactive tableId
containerSearch = container.children('[netuno-form-search]')
containerSearchForm = containerSearch.find("form[name=netuno_form_#{ container.attr('netuno-form-name') }_search]:first")
tableBody = table.find('tbody')
tableBody.empty()
dt = null
findDataTableTR = (e) ->
if e.tagName.toLowerCase() is 'tr'
return e
if e.parentNode.tagName.toLowerCase() is 'tr'
return e.parentNode
return findDataTableTR(e.parentNode)
if table.find('th').length > 0
netuno.unmask containerSearchForm if isButton
dt = table.dataTable(
"pagingType": "full_numbers"
"pageLength": 25
"processing": false
"serverSide": true
"destroy": true
"displayStart": if container.data().pageNumber > 0 then container.data().pageNumber * 25 else null
"ajax": {
"url": "#{ netuno.config.urlAdmin }Search#{ netuno.config.extension }?netuno_action=datasource&"+ containerSearchForm.serialize()
"type": "POST"
}
"preDrawCallback": (settings) ->
tableBody.html("<tr><td colspan=\"1000\" style=\"background-color: #ffffff;\"><div style=\"width: 100%;\"><div class=\"netuno-loader\">Loading...</div></div></td></tr>")
"drawCallback": (settings, json) ->
netuno.mask table
pageNumber = Math.ceil(settings._iDisplayStart / settings._iDisplayLength);
tableBody.find('tr').data({ pageNumber, pageLength: tableBody.find('tr').length})
tableBody.find('tr').each((index) ->
tr = $(this)
tr.data({ rowIndex: index })
tr.off('click').on 'click', (event) ->
tr = $(findDataTableTR(event.target))
uid = tr.children(':first-child').children('span').html()
if netuno.formSearchDataTableBulk[tableId]? and netuno.formSearchDataTableBulk[tableId].active
if tr.hasClass('selected')
tr.removeClass('selected')
netuno.formSearchDataTableBulk[tableId].uids = netuno.formSearchDataTableBulk[tableId].uids.filter (i) ->
i isnt uid
else
tr.addClass('selected')
netuno.formSearchDataTableBulk[tableId].uids.push(uid)
netuno.formSearchDataTableBulk[tableId].callback(netuno.formSearchDataTableBulk[tableId])
else
window.scrollTo(container.offset().left, container.offset().top - 70)
container.data({
pageNumber: tr.data().pageNumber,
pageLength: tr.data().pageLength,
rowIndex: tr.data().rowIndex
})
netuno.loadFormEdit(table, uid)
)
if netuno.formSearchDataTableBulk[tableId]? and netuno.formSearchDataTableBulk[tableId].active
tableBody.find('tr').each () ->
tr = $(this)
trUID = tr.children(':first-child').children('span').html()
if netuno.formSearchDataTableBulk[tableId].uids.find((uid) -> uid == trUID)
tr.addClass('selected')
,
"initComplete": (settings, json) ->
table.fadeIn()
,
"language": netuno.config.dataTable,
"dom": 'pitip',
"tableTools": {
"sSwfPath": "#{ netuno.config.urlScripts }/plugins/datatables-tabletools/swf/copy_csv_xls_pdf.swf"
}
)
netuno.mask containerSearchForm if isButton
netuno.loadFormEdit = (container, item) ->
container = $(container) unless container instanceof jQuery
container = if container.is("[netuno-form][netuno-form-uid]") then container else container.parents("[netuno-form][netuno-form-uid]:first")
container.children('[netuno-form-search]').hide()
data = {
'netuno_table_uid': container.attr('netuno-form-uid'),
'netuno_item_uid': item,
'netuno_edit_only': container.is("[netuno-form-edit-only]"),
'netuno_zone': container.attr('netuno-zone')
}
if container.is("[netuno-form-relation]")
data['netuno_relation_table_uid'] = container.attr('netuno-table-uid')
data['netuno_relation_item_uid'] = container.attr('netuno-item-uid')
containerEdit = container.children('[netuno-form-edit]')
containerEdit.empty()
containerEdit.html("<div class=\"netuno-loader\">Loading...</div>")
containerEdit.show()
$.ajax(
type: 'POST'
url: "#{ netuno.config.urlAdmin }Edit#{ netuno.config.extension }"
data: data
success: (response) ->
containerEdit.html(response);
netuno.contentLoaded(containerEdit)
containerEditForm = containerEdit.find("form[name=netuno_form_#{ container.attr('netuno-form-name') }_edit]")
if (containerEditForm.length > 0)
netuno.loadValidation(containerEditForm)
if typeof item == 'undefined' or item == null or item == ''
container.trigger('netuno:new')
else
container.trigger('netuno:edit', [ item ])
)
netuno.backFormEdit = (element, disableSearchTableRefresh) ->
element = $(element) unless element instanceof jQuery
container = if element.is("[netuno-form][netuno-form-uid]") then element else element.parents("[netuno-form][netuno-form-uid]:first")
container.children('[netuno-form-edit]').empty().hide()
container.children('[netuno-form-search]').show()
if (disableSearchTableRefresh != true)
table = container.find("[netuno-form-search-table=#{ container.attr('netuno-form-name') }]:first");
table.hide()
netuno.loadFormSearchDataTable(table)
container.trigger('netuno:back')
netuno.saveFormEdit = (element, fromRelation) ->
element = $(element) unless element instanceof jQuery
container = if element.is("[netuno-form][netuno-form-uid]") then element else element.parents("[netuno-form][netuno-form-uid]:first")
containerEdit = container.children('[netuno-form-edit]')
containerEditForm = containerEdit.find("form[name=netuno_form_#{ container.attr('netuno-form-name') }_edit]:first")
netuno.unmask containerEditForm
containerEditForm.ajaxForm().submit()
if containerEditForm.validate().valid()
callback = netuno.callbacks.create((uid)->
container.trigger('netuno:save', [ uid ])
)
containerEditForm.ajaxForm(
url: "#{ netuno.config.urlAdmin }Edit#{ netuno.config.extension }?netuno_action=save&netuno_autosave=#{ typeof fromRelation != 'undefined' }&netuno_callback=#{ callback }"
iframe: false
success: (response) ->
containerEdit.html(response)
containerEditForm = containerEdit.find("form[name=netuno_form_#{ container.attr('netuno-form-name') }_edit]:first")
if (containerEditForm.length > 0)
netuno.contentLoaded(containerEdit)
netuno.loadValidation(containerEditForm)
if (typeof fromRelation != 'undefined')
containerEditForm.find("button[netuno-form-edit-relation-button=#{ fromRelation }]:first").trigger('click')
).submit()
return true
else
netuno.mask containerEditForm
return false
netuno.deleteFormEdit = (element) ->
element = $(element) unless element instanceof jQuery
container = if element.is("[netuno-form][netuno-form-uid]") then element else element.parents("[netuno-form][netuno-form-uid]:first")
containerEdit = container.children('[netuno-form-edit]')
if (!containerEdit.is(':empty'))
containerEditForm = containerEdit.find("form[name=netuno_form_#{ container.attr('netuno-form-name') }_edit]:first")
netuno.unmask containerEditForm
callback = netuno.callbacks.create((uid)->
container.trigger('netuno:delete', [ uid ])
)
$.ajax(
type: 'POST'
url: "#{ netuno.config.urlAdmin }Edit#{ netuno.config.extension }?netuno_action=delete&netuno_callback=#{ callback }"
data: containerEditForm.serialize()
success: (response) ->
if (container.data().pageNumber > 0 && container.data().pageLength == 1)
container.data({pageNumber: container.data().pageNumber - 1})
containerEdit.html(response)
netuno.contentLoaded(containerEdit)
containerEditForm = containerEdit.find("form[name=netuno_form_#{ container.attr('netuno-form-name') }_edit]:first")
if (containerEditForm.length > 0)
netuno.loadValidation(containerEditForm)
)
netuno.loadReport = (container) ->
container = $(container) unless container instanceof jQuery
container = if container.is("[netuno-report][netuno-report-uid]") then container else container.parents("[netuno-report][netuno-report-uid]:first")
container.children('[netuno-report-search]').hide()
if container.is(':empty')
$.ajax(
type: 'POST'
url: "#{ netuno.config.urlAdmin }Report#{ netuno.config.extension }"
data: {'netuno_report_uid': container.attr('netuno-report-uid')}
success: (response) ->
container.html(response);
netuno.contentLoaded(container)
)
container.show()
netuno.buildReport = (report) ->
report = $(report) unless report instanceof jQuery
container = report.parents("[netuno-report][netuno-report-uid]:first")
containerResult = container.children("[netuno-report-result=#{ container.attr('netuno-report-name') }]")
containerForm = container.find("form[name=netuno_report_#{ container.attr('netuno-report-name') }_form]:first")
containerForm.ajaxForm().submit()
if containerForm.validate().valid()
containerForm.ajaxForm(
url: "#{ netuno.config.urlAdmin }ReportBuilder#{ netuno.config.extension }"
iframe: false
success: (response) ->
containerResult.html(response)
netuno.contentLoaded(containerResult)
).submit()
return true
else
return false
netuno.loadValidation = (form) ->
form = $(form) unless form instanceof jQuery
form = if form.is("form") then form else form.closest("form")
rules = {}
form.find("[validation]").each ()->
element = $(this)
validation = S(element.attr("validation"))
rules[element.attr("name")] = {}
if validation.contains("required")
rules[element.attr("name")]["required"] = true
if validation.contains("email")
rules[element.attr("name")]["email"] = true
form.validate({
"errorElement": 'span'
"errorClass": 'help-block'
"focusInvalid": false
"ignore": ""
"rules": rules
"invalidHandler": (event, validator) ->
"highlight": (element) ->
$(element).closest('.form-group').addClass('has-error')
"success": (label) ->
label.closest('.form-group').removeClass('has-error')
label.remove();
"errorPlacement": (error, element) ->
error.insertAfter(element.closest('.input-icon'))
})
netuno.downloadProgress = (url) ->
time = new Date().getTime()
$("body").append("<iframe id=\"netuno_download_#{ time }\" src=\"#{ url }&downloadToken=#{ time }\" style=\"display: none;\"></iframe>");
if (!navigator.userAgent.match(/msie/i))
modal = $('#netuno_download')
modal.modal('show');
tickStatus = () ->
$('\#netuno_download_progress_bar').css('width', "100%").attr('aria-valuenow', 100);
$.ajax({
type: 'POST',
url: "#{url }&downloadToken=#{ time }&downloadStatus=true",
success: (response) ->
if (response == 'done')
iframe = $("\#netuno_download_#{ time }")
if ($("\#netuno_download_#{ time }").length > 0)
window.setTimeout(() ->
modal.modal('hide')
$('\#netuno_download_progress_bar').css('width', "0%").attr('aria-valuenow', 0)
iframe.remove()
, 1000);
else
window.setTimeout(tickStatus, 1000);
});
tickStatus();
netuno.keepAlive = ()->
if typeof netuno.config.user != 'undefined'
$.ajax {
type: 'POST',
url: "#{ netuno.config.urlAdmin }KeepAlive#{ netuno.config.extension }",
success: (response)->
if response == "1"
window.setTimeout('netuno.keepAlive();', 360000)
else
document.location.href = "#{ netuno.config.urlAdmin }Index#{ netuno.config.extension }"
}
netuno.loadLinks = (container)->
container.find("a").on "click", ()->
element = $(this)
if element.attr("rel") is "external"
if element.attr("target") is "_blank"
window.open(element.attr("href"))
return false
else
window.location.href = element.attr("href")
return false
else
if element.is("[data-toggle]")
ul = element.parent().children('ul')
if ul.is(':hidden')
ul.fadeIn()
element.children('i:last-child').removeClass('fa-caret-down').addClass('fa-caret-up')
else
ul.fadeOut()
element.children('i:last-child').removeClass('fa-caret-up').addClass('fa-caret-down')
if element.parents('.navbar-nav').length == 1
if ($('body > div.dev').length == 0 || element.parents('.nav-management').length == 0)
$('.navbar-toggle:visible').click()
element.trigger('netuno:click')
window.scrollTo(0, 0)
if element.is("[netuno-content]")
container = $(element.attr("href"))
$("#containers > div").hide()
if container.length > 0 and container.is(":empty")
$.ajax
url: element.attr('netuno-content'),
success: (response) ->
container.html(response);
netuno.contentLoaded(container)
container.show()
return false
else if element.is("[netuno-form]")
formName = element.attr("netuno-form")
$("\#containers > div").hide()
netuno.loadForm($("\#containers > div[netuno-form-name=#{ formName }]"))
return false
else if element.is("[netuno-report]")
reportName = element.attr("netuno-report")
$("#containers > div").hide()
netuno.loadReport($("\#containers > div[netuno-report-name=#{ reportName }]"))
return false
else if element.attr("href") isnt "#"
container = $(element.attr("href"))
$("#containers > div").hide()
container.show()
return false
netuno.mask = (container)->
container.find('[data-mask]').each(()->
o = $(this)
if (o.attr('data-mask') != null and o.attr('data-mask') != '')
o.mask(o.attr('data-mask'), {
reverse: o.attr('data-mask-reverse') is 'true'
selectOnFocus: o.attr('data-mask-selectonfocus') is 'true'
})
)
netuno.unmask = (container)->
container.find('[data-mask]').each(()->
o = $(this)
if (typeof o.data().mask isnt 'undefined' and o.data().mask isnt null)
if o.text() isnt ''
data = o.data()
delete data.mask
o.data(data)
else
o.unmask()
)
netuno.addContentLoad (container)->
netuno.loadLinks(container)
netuno.addContentLoad (container)->
container.find("select").select2(
theme: "bootstrap"
placeholder: ""
maximumSelectionSize: 6
)
netuno.addContentLoad (container)->
netuno.mask(container)
netuno.openRelation = (name) ->
container = $("\#netuno_form_#{ name }")
containerSearch = container.children('[netuno-form-search]')
if containerSearch.is(':empty')
$.ajax(
type: 'POST'
url: "#{ netuno.config.urlAdmin }Search#{ netuno.config.extension }"
data: { 'netuno_table_uid': container.attr('netuno-form-uid') }
success: (response) ->
containerSearch.html(response);
netuno.contentLoaded(containerSearch)
)
container.show()
netuno.addPageLoad ()->
netuno.loadLinks($("body"))
netuno.modal = {}
netuno.modal.stack = []
netuno.modal.create = (config) ->
config = $.extend {
name: null,
container: $('body')
relation: false
callback: (modal)->
}, config
if (config.name == null)
return
key = netuno.newUid()
$.ajax(
type: 'POST'
url: "#{ netuno.config.urlAdmin }Edit#{ netuno.config.extension }"
dataType: 'json'
data: {
netuno_action: 'uid'
netuno_table_name: config.name
}
success: (response) ->
modalRelationParam = ""
modalRelationFormParam = ""
if (config.relation)
modalRelationParam = "netuno-form-edit-relation-modal=\"#{ config.name }\""
modalRelationFormParam = "netuno-form-relation netuno-table-uid=\"#{ config.relation.table_uid }\" netuno-item-uid=\"#{ config.relation.item_uid }\""
config.container.append("""
<div id="netuno-modal-#{ key }" #{ modalRelationParam } class="netuno-modal">
<div class="container-fluid">
<div netuno-form netuno-form-uid="#{ response.uid }" netuno-form-name="#{ config.name }" #{ modalRelationFormParam }>
<div class="netuno-form-edit" netuno-form-edit></div>
<div class="netuno-form-search" netuno-form-search></div>
</div>
</div>
</div>
""")
config.callback($("\#netuno-modal-#{ key }"))
)
netuno.modal.showAndLoad = (modal)->
modal = $(modal) unless modal instanceof jQuery
netuno.modal.show(modal)
netuno.loadForm(modal.find('[netuno-form]'))
netuno.modal.show = (modal)->
modal = $(modal) unless modal instanceof jQuery
modal.trigger('netuno:modal:show')
$('#netuno-modal-curtain').fadeIn()
$('#netuno-modal-close').show()
modal.show()
netuno.modal.stack.push(modal)
modal.trigger('netuno:modal:shown')
netuno.modal.hide = (modal)->
modal = $(modal) unless modal instanceof jQuery
modal.trigger('netuno:modal:hide')
modal.hide()
for i in [0 ... netuno.modal.stack.length]
if (netuno.modal.stack[i] == modal)
netuno.modal.stack.splice(i, 1)
if (netuno.modal.stack.length == 0)
$('#netuno-modal-curtain').fadeOut()
$('#netuno-modal-close').hide()
modal.trigger('netuno:modal:hidden')
netuno.modal.hideLast = ()->
if (netuno.modal.stack.length > 0)
netuno.modal.hide(netuno.modal.stack[netuno.modal.stack.length - 1])
netuno.com = {}
netuno.com['text'] =
'html': {
'load': (id, css)->
summernote = $("\##{ id }").summernote({
callbacks: {
onImageUpload: (files) ->
upload = (file) ->
comUid = summernote.attr('netuno-texthtml-uid')
formData = new FormData()
formData.append "com_uid", comUid
formData.append "file", file, file.name
$.ajax({
method: "POST"
url: "#{ netuno.config.urlAdmin }com/TextHtml#{ netuno.config.extension }"
contentType: false
cache: false
processData: false
data: formData
dataType: "json"
success: (data) ->
summernote.summernote("insertImage", data.url)
error: (jqXHR, textStatus, errorThrown) ->
console.error("#{ textStatus } #{ errorThrown }")
})
upload(file) for file in files
},
height: 200
})
}
'md': {
'load': (id) ->
container = $("\##{ id }")
textarea = container.find("[netuno-textmd-uid]")
comUid = textarea.attr('netuno-textmd-uid')
window.setTimeout(()->
editor = editormd(id, {
width: "100%",
height: "400px",
path: "/netuno/scripts/sbadmin/plugins/editor.md/lib/",
codeFold : true,
emoji: true,
taskList: true,
tocm: true,
tex: true,
flowChart: true,
sequenceDiagram: true,
imageUpload: true,
imageFormats: ["jpg", "jpeg", "gif", "png", "svg", "webp"],
imageUploadURL: "#{ netuno.config.urlAdmin }com/TextMD#{ netuno.config.extension }?com_uid=#{ comUid }",
onfullscreen: ()->
editor.editor.css('z-index', 10000)
onfullscreenExit: ()->
editor.editor.css('z-index', 0)
onload: ()->
this.unwatch()
this.previewed()
lang : {
name : "en",
description : "Open source online Markdown editor.",
tocTitle : "Table of Contents",
toolbar : {
undo : "Undo(Ctrl+Z)",
redo : "Redo(Ctrl+Y)",
bold : "Bold",
del : "Strikethrough",
italic : "Italic",
quote : "Block quote",
ucwords : "Words first letter convert to uppercase",
uppercase : "Selection text convert to uppercase",
lowercase : "Selection text convert to lowercase",
h1 : "Heading 1",
h2 : "Heading 2",
h3 : "Heading 3",
h4 : "Heading 4",
h5 : "Heading 5",
h6 : "Heading 6",
"list-ul" : "Unordered list",
"list-ol" : "Ordered list",
hr : "Horizontal rule",
link : "Link",
"reference-link" : "Reference link",
image : "Image",
code : "Code inline",
"preformatted-text" : "Preformatted text / Code block (Tab indent)",
"code-block" : "Code block (Multi-languages)",
table : "Tables",
datetime : "Datetime",
emoji : "Emoji",
"html-entities" : "HTML Entities",
pagebreak : "Page break",
watch : "Unwatch",
unwatch : "Watch",
preview : "HTML Preview (Press Shift + ESC exit)",
fullscreen : "Fullscreen (Press ESC exit)",
clear : "Clear",
search : "Search",
help : "Help",
info : "About "
},
buttons : {
enter : "Enter",
cancel : "Cancel",
close : "Close"
},
dialog : {
link : {
title : "Link",
url : "Address",
urlTitle : "Title",
urlEmpty : "Error: Please fill in the link address."
},
referenceLink : {
title : "Reference link",
name : "Name",
url : "Address",
urlId : "ID",
urlTitle : "Title",
nameEmpty: "Error: Reference name can't be empty.",
idEmpty : "Error: Please fill in reference link id.",
urlEmpty : "Error: Please fill in reference link url address."
},
image : {
title : "Image",
url : "Address",
link : "Link",
alt : "Title",
uploadButton : "Upload",
imageURLEmpty : "Error: picture url address can't be empty.",
uploadFileEmpty : "Error: upload pictures cannot be empty!",
formatNotAllowed : "Error: only allows to upload pictures file, upload allowed image file format:"
},
preformattedText : {
title : "Preformatted text / Codes",
emptyAlert : "Error: Please fill in the Preformatted text or content of the codes.",
placeholder : "coding now...."
},
codeBlock : {
title : "Code block",
selectLabel : "Languages: ",
selectDefaultText : "select a code language...",
otherLanguage : "Other languages",
unselectedLanguageAlert : "Error: Please select the code language.",
codeEmptyAlert : "Error: Please fill in the code content.",
placeholder : "coding now...."
},
htmlEntities : {
title : "HTML Entities"
},
help : {
title : "Help"
}
}
}
})
, 250)
}
netuno.com['select'] =
callbacks: []
getConfig: (fieldId, service, ajaxParams) ->
netuno.com.select.loadCallbacksForFieldId(fieldId)
delayCallbacks = new Date().getTime()
field = $("\##{ fieldId }")
placeholder = netuno.config.com.lang.select["defaulttext"]
if field.attr("multiple")
placeholder = $('<div />').html(placeholder).text()
# dropdownParent: field.parent()
return {
theme: "bootstrap"
placeholder: placeholder
allowClear: true,
data: [ ]
ajax: {
url: service
dataType: 'json'
delay: 250
data: (params) ->
return $.extend(true, {
q: params.term,
page: params.page,
page_limit: 10
}, ajaxParams)
processResults: (data, params) ->
params.page = 1 if params.page?
return { results: data }
}
templateResult: (item) ->
return item.label
templateSelection: (item) ->
$("\##{ fieldId }").parent().parent().removeClass("has-error")
if (new Date().getTime() < delayCallbacks + 250)
if item.label
return item.label
else
return item.text
for key of netuno.com.select.callbacks[fieldId]
callback = netuno.com.select.callbacks[fieldId][key]
if ($.isFunction(callback))
callback(item.id)
delayCallbacks = new Date().getTime()
if item.label
return item.label
else
return item.text
escapeMarkup: (m)->
return m
}
callbackForFieldId: (fieldId, key, callback)->
netuno.com.select.loadCallbacksForFieldId(fieldId)
netuno.com.select.callbacks[fieldId][key] = callback
loadCallbacksForFieldId: (fieldId)->
if fieldId? and fieldId.length > 0 and not netuno.com.select.callbacks[fieldId]?
netuno.com.select.callbacks[fieldId] = {}
load: (fieldId, comUid, service)->
$("\##{ fieldId }").select2(netuno.com.select.getConfig(fieldId, service, { com_uid: comUid }))
loadInContainer: (container)->
container.find("select[netuno-select-uid]").each(()->
select = $(this)
select.select2('destroy')
value = select.attr('value')
comUid = select.attr('netuno-select-uid')
service = select.attr('netuno-select-service')
if comUid? and comUid isnt ''
select2 = select.select2(netuno.com.select.getConfig(select.attr('id'), service, { com_uid: comUid }))
if value? and value isnt ''
option = $('<option selected>Loading...</option>').val(value)
select.append(option)
select.trigger('change')
$.ajax({
dataType: "jsonp"
url: "#{ service }?com_uid=#{ comUid }&data_uid=#{ value }"
}).then((data) ->
if data? and data.label? and data.id?
option.html(data.label).val(data.id)
option.removeData()
select.trigger('change')
selectId = select.attr('id')
selectContainer = $("\#select2-#{ selectId }-container");
selectContainer.html(data.label)
selectContainer.prepend($(document.createElement("span")).addClass('select2-selection__clear').text('×').data(data).on('click', (e)->
select = $("\##{ selectId }")
select.attr("value", "")
select.empty()
netuno.com.select.loadInContainer(select.parent())
e.preventDefault()
))
selectContainer.find('.select2-selection__clear').data(data)
)
)
container.find("select[netuno-select-link]").each(()->
link = $(this).attr('netuno-select-link')
columnSeparator = $(this).attr('netuno-select-column-separator')
maxColumnLength = $(this).attr('netuno-select-max-column-length')
onlyActives = $(this).attr('netuno-select-only-actives')
service = $(this).attr('netuno-select-service')
if link? and link isnt ''
$(this).select2(netuno.com.select.getConfig($(this).attr('id'), service, {
link: link,
column_separator: columnSeparator,
max_column_length: maxColumnLength,
only_actives: onlyActives
}));
)
container.find("select[netuno-select-service]:not([netuno-select-uid],[netuno-select-link])").each(()->
service = $(this).attr('netuno-select-service')
if service? and service isnt ''
select = $(this)
select.select2('destroy')
value = select.attr('value')
service = select.attr('netuno-select-service')
select2 = $(this).select2(netuno.com.select.getConfig($(this).attr('id'), service))
if value? and value isnt ''
option = $('<option selected>Loading...</option>').val(value)
select.append(option).trigger('change')
$.ajax({
dataType: "jsonp"
url: "#{ service }&data_uid=#{ value }"
}).then((data) ->
if data? and data.label? and data.id?
option.html(data.label).val(data.id)
option.removeData()
select.trigger('change')
selectId = select.attr('id')
selectContainer = $("\#select2-#{ selectId }-container");
selectContainer.html(data.label)
selectContainer.prepend($(document.createElement("span")).addClass('select2-selection__clear').text('×').data(data).on('click', ()->
$("\##{ selectId }").val('')
$(this).parent().empty()
))
selectContainer.find('.select2-selection__clear').data(data)
)
)
setValue: (select, uid) ->
select
.empty()
.append($('<option></option>'))
.append(
$('<option selected></option>')
.val(uid)
)
.val(uid)
.attr('value', uid)
netuno.com.select.loadInContainer(select.parent())
netuno.com['multiselect'] =
loadInContainer: (container)->
container.find("select[netuno-multiselect-uid]").each(()->
input = $(this)
input.select2('destroy')
value = input.attr('value')
comUid = input.attr('netuno-multiselect-uid')
service = input.attr('netuno-multiselect-service')
if comUid? and comUid isnt ''
select2 = input.select2(netuno.com.multiselect.getConfig(input.attr('id'), service, { com_uid: comUid }))
)
,
load: (fieldId, designId, referenceId) ->
$("\##{fieldId}").select2(
formatNoMatches: ()->
return netuno.config.com.lang.multiselect["noresults"]
,
formatSearching: ()->
return netuno.config.com.lang.multiselect["searching"]
,
placeholder: $('<div />').html(netuno.config.com.lang.multiselect["defaulttext"]).text(),
ajax: {
url: "com/MultiSelect.netuno",
dataType: 'jsonp',
data: (term, page)->
return {
id: designId,
q: term,
page: page,
page_limit: 10
}
,
results: (data, page)->
return {results: data}
},
id: (item)->
return item.id
,
initSelection: (element, callback)->
dataIds = $(element).val()
if (dataIds != "")
$.ajax("com/MultiSelect.netuno", {
data: {
id: designId,
dataids: dataIds,
referenceid: referenceId
},
dataType: "jsonp"
}).done((data)->
callback(data)
)
,
formatResult: (item)->
return item.label
,
formatSelection: (item)->
return item.label
,
escapeMarkup: (m)->
return m
,
multiple: true,
tokenSeparators: [",", " "]
)
netuno.com['date'] =
load: (fieldId, container, callback) ->
$("\##{ fieldId }").on('change', callback).datepicker({
format: "yyyy-mm-dd",
autoclose: true,
todayHighlight: true,
orientation: "auto"
container: "\##{ container }"
})
netuno.com['time'] =
load: (fieldId, container, callback) ->
control = $("\##{ fieldId }").on('change', callback).clockpicker({
autoclose: true,
placement: 'top'
})
return control
netuno.com['checkbox'] =
loadInContainer: (container)->
container.find("[type=\"checkbox\"]").each ()->
$(this).bootstrapSwitch(
size: "small"
onText: "<i class=\"fa fa-check\"></i>"
offText: "<i class=\"fa fa-close\"></i>"
)
netuno.com['color'] =
load: (fieldId) ->
control = $("\##{ fieldId }").colorpicker()
return control
netuno.com['image'] =
load: (id)->
upload = $("\##{ id }")
if ($("\##{ id }-value").val().length > 0)
value = $("\##{ id }-value").val()
else
$("\##{ id }-btView").hide()
upload.on("change", ()->
input = $(this)
numFiles = if input.get(0).files then input.get(0).files.length else 1
label = input.val().replace(/\\/g, '/').replace(/.*\//, '')
input.trigger('fileselect', [numFiles, label])
)
upload.on('fileselect', (event, numFiles, label) ->
$("\##{ id }-null").val('false')
input = $(this).parents('.input-group').find(':text')
log = if numFiles > 1 then "#{numFiles } files selected" else label
if (input.length > 0)
input.val(log)
)
view: (id, url)->
window.open(url, "_blank")
clear: (id)->
$("\##{ id }").val('').parents('.input-group').find(':text').val('')
$("\##{ id }-fileFeedback").html('')
$("\##{ id }-null").val('true')
$("\##{ id }-preview").hide()
$("\##{ id }-btView").hide()
netuno.com['file'] =
load: (id)->
upload = $("\##{ id }")
if ($("\##{ id }-value").val().length == 0)
$("\##{ id }-btView").hide()
upload.on("change", ()->
input = $(this)
numFiles = if input.get(0).files then input.get(0).files.length else 1
label = input.val().replace(/\\/g, '/').replace(/.*\//, '')
input.trigger('fileselect', [numFiles, label])
)
upload.on('fileselect', (event, numFiles, label) ->
$("\##{ id }-null").val('false')
input = $(this).parents('.input-group').find(':text')
log = if numFiles > 1 then "#{numFiles } files selected" else label
if (input.length > 0)
input.val(log)
)
view: (id)->
value = $("\##{ id }-value")
window.open(value.attr('file-url'))
clear: (id)->
$("\##{ id }").val('').parents('.input-group').find(':text').val('')
$("\##{ id }-fileFeedback").html('')
$("\##{ id }-null").val('true')
$("\##{ id }-btView").hide()
restore: (id)->
$(document).ready ()->
netuno.pageLoaded()
netuno.addContentLoad (container) ->
netuno.com['select'].loadInContainer(container)
netuno.addContentLoad (container) ->
netuno.com['checkbox'].loadInContainer(container)
netuno.keepAlive()
$(document).on 'show.bs.modal', (event)->
target = $(event.target)
parents = target.parents('.modal')
if (parents.length > 0)
target.detach().appendTo('body').attr('netuno-parent-modal-id', $(parents[0]).attr('id'))
$(parents[0]).modal('hide')
$(document).on 'hidden.bs.modal', (event)->
target = $(event.target)
if (target.attr('netuno-parent-modal-id'))
target.detach().appendTo("\##{ target.attr('netuno-parent-modal-id') }")
$("\##{ target.attr('netuno-parent-modal-id') }").modal('show')
#$(event.relatedTarget).parents('.modal')
#$(event.relatedTarget).parents('.modal').modal('hide')
#$(document).on 'shown.bs.modal', (event) ->
# if ($('body').hasClass('modal-open') == false)
# $('body').addClass('modal-open')
| 138050 |
toastr.options = {
"closeButton": true,
"debug": false,
"newestOnTop": true,
"progressBar": false,
"positionClass": "toast-top-center",
"preventDuplicates": true,
"onclick": null,
"showDuration": "300",
"hideDuration": "1000",
"timeOut": "3000",
"extendedTimeOut": "1000",
"showEasing": "swing",
"hideEasing": "linear",
"showMethod": "fadeIn",
"hideMethod": "fadeOut"
}
$ ->
$('form').submit ->
false
return
netuno.newUid = ()->
s4 = () ->
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1)
return "#{ s4() }#{ s4() }_#{ s4() }_#{ s4() }_#{ s4() }_#{ s4() }#{ s4() }#{ s4() }"
netuno.callbacks =
create: (func)->
key = <KEY>()
netuno.callbacks[key] = func
return key
remove: (key)->
delete netuno.callbacks[key]
netuno.menu = (menu)->
navMenuHtml = "<li><a netuno-navigation-dashboard href=\"#netuno_dashboard\"><i class=\"fa fa-fw fa-dashboard\"></i> #{ netuno.lang['menu.dashboard'] }</a></li>"
containersHtml = ''
buildMenu = (type, parentUId, items, level) ->
menuHtml = '';
if level > 0
menuHtml += '<ul>'
for item in items
expand = ""
if item.items.length > 0
expand = " data-toggle="
menuHtml += '<li>'
menuHtml += "<a netuno-navigation-#{ type }-item.name href=\"\#\" netuno-#{ type }=\"#{ item.name }\"#{ expand }>"
menuHtml += "#{ item.text }"
if item.items.length > 0
menuHtml += "<i class=\"fa fa-fw fa-caret-down\"></i>"
menuHtml += "</a>"
if item.items.length > 0
menuHtml += buildMenu(type, item.uid, item.items, level + 1)
menuHtml += '</li>'
containersHtml += "<div netuno-container-#{ type }-#{ item.name } netuno-#{ type } netuno-#{ type }-uid=\"#{ item.uid }\" netuno-#{ type }-name=\"#{ item.name }\">"
if type is 'form'
containersHtml += "<div class=\"netuno-form-edit\" netuno-#{ type }-edit=\"#{ item.name }\"></div>"
containersHtml += "<div class=\"netuno-form-search\" netuno-#{ type }-search=\"#{ item.name }\"></div>"
containersHtml += "</div>"
if level > 0
menuHtml += '</ul>'
return menuHtml
if menu.forms.length > 0
navMenuHtml += "<li class=\"nav-section-title\"><h4> <i class=\"fa fa-fw fa-edit\"></i>#{ netuno.lang['menu.forms'] }</h4></li>"
navMenuHtml += buildMenu 'form', 0, menu.forms, 0
if menu.reports.length > 0
navMenuHtml += "<li class=\"nav-section-title\"><h4> <i class=\"fa fa-fw fa-area-chart\"></i>#{ netuno.lang['menu.reports'] }</h4></li>"
navMenuHtml += buildMenu 'report', 0, menu.reports, 0
navbar = $('[netuno-navigation]')
navbar.append(navMenuHtml).show().find('ul').hide()
navbar.trigger('netuno:loaded')
containers = $('[netuno-containers]')
containers.append(containersHtml)
containers.trigger('netuno:loaded')
netuno.navigationLoaded()
netuno.loadForm = (container) ->
container = $(container) unless container instanceof jQuery
container = if container.is("[netuno-form][netuno-form-uid]") then container else container.closest("[netuno-form][netuno-form-uid]")
containerSearch = container.children('[netuno-form-search]')
data = { 'netuno_table_uid': container.attr('netuno-form-uid') }
if container.is("[netuno-form-relation]")
data['netuno_relation_table_uid'] = container.attr('netuno-table-uid')
data['netuno_relation_item_uid'] = container.attr('netuno-item-uid')
if containerSearch.is(':empty')
containerSearch.html("<div class=\"netuno-loader\">Loading...</div>")
$.ajax(
type: 'POST'
url: "#{ netuno.config.urlAdmin }Search#{ netuno.config.extension }"
data: data
success: (response) ->
containerSearch.html(response)
netuno.contentLoaded(containerSearch)
)
container.show()
netuno.formSearchDataTableBulk = {}
netuno.formSearchDataTableBulkActive = (tableId, callback) ->
netuno.formSearchDataTableBulk[tableId] = {
active: true,
callback: callback,
uids: []
}
table = $("\##{tableId}")
searchContainer = table.parents("[netuno-form-search]:first")
searchContainer.find("[netuno-form-search-buttons]").find("button").prop('disabled', true).fadeTo("slow", 0.5)
searchContainer.find("h1.page-header").find('button').prop('disabled', true).fadeTo("slow", 0.5)
netuno.formSearchDataTableBulkInactive = (tableId) ->
if netuno.formSearchDataTableBulk[tableId]?
delete netuno.formSearchDataTableBulk[tableId]
table = $("\##{tableId}")
tableBody = table.find('tbody')
tableBody.find('tr').each () ->
tr = $(this)
tr.removeClass('selected')
searchContainer = table.parents("[netuno-form-search]:first")
searchContainer.find("[netuno-form-search-buttons]").find("button").prop('disabled', false).fadeTo("slow", 1)
searchContainer.find("h1.page-header").find('button').prop('disabled', false).fadeTo("slow", 1)
netuno.executeFormSearchBulk = (settings) ->
settings = $.extend {
action: null
tableId: null
callback: (resut)->
}, settings
table = $("\##{settings.tableId}")
container = table.parents("[netuno-form][netuno-form-uid]:first")
container.data({
pageNumber: 0,
pageLength: 0,
rowIndex: 0
})
uids = netuno.formSearchDataTableBulk[settings.tableId].uids
$.ajax(
type: 'POST'
url: "#{ netuno.config.urlAdmin }Search#{ netuno.config.extension }"
dataType: 'json'
contentType : 'application/json',
data: JSON.stringify({
netuno_action: "bulk-#{settings.action}"
netuno_table_name: container.attr('netuno-form-name'),
netuno_items_uids: uids
})
success: (response) ->
settings.callback(response)
)
netuno.loadFormSearchDataTable = (table) ->
table = $(table) unless table instanceof jQuery
isButton = table.is('button')
container = table.parents("[netuno-form][netuno-form-uid]:first")
table = container.find("[netuno-form-search-table=#{ container.attr('netuno-form-name') }]:first") unless table.is('table')
tableId = table.attr('id')
netuno.formSearchDataTableBulkInactive tableId
containerSearch = container.children('[netuno-form-search]')
containerSearchForm = containerSearch.find("form[name=netuno_form_#{ container.attr('netuno-form-name') }_search]:first")
tableBody = table.find('tbody')
tableBody.empty()
dt = null
findDataTableTR = (e) ->
if e.tagName.toLowerCase() is 'tr'
return e
if e.parentNode.tagName.toLowerCase() is 'tr'
return e.parentNode
return findDataTableTR(e.parentNode)
if table.find('th').length > 0
netuno.unmask containerSearchForm if isButton
dt = table.dataTable(
"pagingType": "full_numbers"
"pageLength": 25
"processing": false
"serverSide": true
"destroy": true
"displayStart": if container.data().pageNumber > 0 then container.data().pageNumber * 25 else null
"ajax": {
"url": "#{ netuno.config.urlAdmin }Search#{ netuno.config.extension }?netuno_action=datasource&"+ containerSearchForm.serialize()
"type": "POST"
}
"preDrawCallback": (settings) ->
tableBody.html("<tr><td colspan=\"1000\" style=\"background-color: #ffffff;\"><div style=\"width: 100%;\"><div class=\"netuno-loader\">Loading...</div></div></td></tr>")
"drawCallback": (settings, json) ->
netuno.mask table
pageNumber = Math.ceil(settings._iDisplayStart / settings._iDisplayLength);
tableBody.find('tr').data({ pageNumber, pageLength: tableBody.find('tr').length})
tableBody.find('tr').each((index) ->
tr = $(this)
tr.data({ rowIndex: index })
tr.off('click').on 'click', (event) ->
tr = $(findDataTableTR(event.target))
uid = tr.children(':first-child').children('span').html()
if netuno.formSearchDataTableBulk[tableId]? and netuno.formSearchDataTableBulk[tableId].active
if tr.hasClass('selected')
tr.removeClass('selected')
netuno.formSearchDataTableBulk[tableId].uids = netuno.formSearchDataTableBulk[tableId].uids.filter (i) ->
i isnt uid
else
tr.addClass('selected')
netuno.formSearchDataTableBulk[tableId].uids.push(uid)
netuno.formSearchDataTableBulk[tableId].callback(netuno.formSearchDataTableBulk[tableId])
else
window.scrollTo(container.offset().left, container.offset().top - 70)
container.data({
pageNumber: tr.data().pageNumber,
pageLength: tr.data().pageLength,
rowIndex: tr.data().rowIndex
})
netuno.loadFormEdit(table, uid)
)
if netuno.formSearchDataTableBulk[tableId]? and netuno.formSearchDataTableBulk[tableId].active
tableBody.find('tr').each () ->
tr = $(this)
trUID = tr.children(':first-child').children('span').html()
if netuno.formSearchDataTableBulk[tableId].uids.find((uid) -> uid == trUID)
tr.addClass('selected')
,
"initComplete": (settings, json) ->
table.fadeIn()
,
"language": netuno.config.dataTable,
"dom": 'pitip',
"tableTools": {
"sSwfPath": "#{ netuno.config.urlScripts }/plugins/datatables-tabletools/swf/copy_csv_xls_pdf.swf"
}
)
netuno.mask containerSearchForm if isButton
netuno.loadFormEdit = (container, item) ->
container = $(container) unless container instanceof jQuery
container = if container.is("[netuno-form][netuno-form-uid]") then container else container.parents("[netuno-form][netuno-form-uid]:first")
container.children('[netuno-form-search]').hide()
data = {
'netuno_table_uid': container.attr('netuno-form-uid'),
'netuno_item_uid': item,
'netuno_edit_only': container.is("[netuno-form-edit-only]"),
'netuno_zone': container.attr('netuno-zone')
}
if container.is("[netuno-form-relation]")
data['netuno_relation_table_uid'] = container.attr('netuno-table-uid')
data['netuno_relation_item_uid'] = container.attr('netuno-item-uid')
containerEdit = container.children('[netuno-form-edit]')
containerEdit.empty()
containerEdit.html("<div class=\"netuno-loader\">Loading...</div>")
containerEdit.show()
$.ajax(
type: 'POST'
url: "#{ netuno.config.urlAdmin }Edit#{ netuno.config.extension }"
data: data
success: (response) ->
containerEdit.html(response);
netuno.contentLoaded(containerEdit)
containerEditForm = containerEdit.find("form[name=netuno_form_#{ container.attr('netuno-form-name') }_edit]")
if (containerEditForm.length > 0)
netuno.loadValidation(containerEditForm)
if typeof item == 'undefined' or item == null or item == ''
container.trigger('netuno:new')
else
container.trigger('netuno:edit', [ item ])
)
netuno.backFormEdit = (element, disableSearchTableRefresh) ->
element = $(element) unless element instanceof jQuery
container = if element.is("[netuno-form][netuno-form-uid]") then element else element.parents("[netuno-form][netuno-form-uid]:first")
container.children('[netuno-form-edit]').empty().hide()
container.children('[netuno-form-search]').show()
if (disableSearchTableRefresh != true)
table = container.find("[netuno-form-search-table=#{ container.attr('netuno-form-name') }]:first");
table.hide()
netuno.loadFormSearchDataTable(table)
container.trigger('netuno:back')
netuno.saveFormEdit = (element, fromRelation) ->
element = $(element) unless element instanceof jQuery
container = if element.is("[netuno-form][netuno-form-uid]") then element else element.parents("[netuno-form][netuno-form-uid]:first")
containerEdit = container.children('[netuno-form-edit]')
containerEditForm = containerEdit.find("form[name=netuno_form_#{ container.attr('netuno-form-name') }_edit]:first")
netuno.unmask containerEditForm
containerEditForm.ajaxForm().submit()
if containerEditForm.validate().valid()
callback = netuno.callbacks.create((uid)->
container.trigger('netuno:save', [ uid ])
)
containerEditForm.ajaxForm(
url: "#{ netuno.config.urlAdmin }Edit#{ netuno.config.extension }?netuno_action=save&netuno_autosave=#{ typeof fromRelation != 'undefined' }&netuno_callback=#{ callback }"
iframe: false
success: (response) ->
containerEdit.html(response)
containerEditForm = containerEdit.find("form[name=netuno_form_#{ container.attr('netuno-form-name') }_edit]:first")
if (containerEditForm.length > 0)
netuno.contentLoaded(containerEdit)
netuno.loadValidation(containerEditForm)
if (typeof fromRelation != 'undefined')
containerEditForm.find("button[netuno-form-edit-relation-button=#{ fromRelation }]:first").trigger('click')
).submit()
return true
else
netuno.mask containerEditForm
return false
netuno.deleteFormEdit = (element) ->
element = $(element) unless element instanceof jQuery
container = if element.is("[netuno-form][netuno-form-uid]") then element else element.parents("[netuno-form][netuno-form-uid]:first")
containerEdit = container.children('[netuno-form-edit]')
if (!containerEdit.is(':empty'))
containerEditForm = containerEdit.find("form[name=netuno_form_#{ container.attr('netuno-form-name') }_edit]:first")
netuno.unmask containerEditForm
callback = netuno.callbacks.create((uid)->
container.trigger('netuno:delete', [ uid ])
)
$.ajax(
type: 'POST'
url: "#{ netuno.config.urlAdmin }Edit#{ netuno.config.extension }?netuno_action=delete&netuno_callback=#{ callback }"
data: containerEditForm.serialize()
success: (response) ->
if (container.data().pageNumber > 0 && container.data().pageLength == 1)
container.data({pageNumber: container.data().pageNumber - 1})
containerEdit.html(response)
netuno.contentLoaded(containerEdit)
containerEditForm = containerEdit.find("form[name=netuno_form_#{ container.attr('netuno-form-name') }_edit]:first")
if (containerEditForm.length > 0)
netuno.loadValidation(containerEditForm)
)
netuno.loadReport = (container) ->
container = $(container) unless container instanceof jQuery
container = if container.is("[netuno-report][netuno-report-uid]") then container else container.parents("[netuno-report][netuno-report-uid]:first")
container.children('[netuno-report-search]').hide()
if container.is(':empty')
$.ajax(
type: 'POST'
url: "#{ netuno.config.urlAdmin }Report#{ netuno.config.extension }"
data: {'netuno_report_uid': container.attr('netuno-report-uid')}
success: (response) ->
container.html(response);
netuno.contentLoaded(container)
)
container.show()
netuno.buildReport = (report) ->
report = $(report) unless report instanceof jQuery
container = report.parents("[netuno-report][netuno-report-uid]:first")
containerResult = container.children("[netuno-report-result=#{ container.attr('netuno-report-name') }]")
containerForm = container.find("form[name=netuno_report_#{ container.attr('netuno-report-name') }_form]:first")
containerForm.ajaxForm().submit()
if containerForm.validate().valid()
containerForm.ajaxForm(
url: "#{ netuno.config.urlAdmin }ReportBuilder#{ netuno.config.extension }"
iframe: false
success: (response) ->
containerResult.html(response)
netuno.contentLoaded(containerResult)
).submit()
return true
else
return false
netuno.loadValidation = (form) ->
form = $(form) unless form instanceof jQuery
form = if form.is("form") then form else form.closest("form")
rules = {}
form.find("[validation]").each ()->
element = $(this)
validation = S(element.attr("validation"))
rules[element.attr("name")] = {}
if validation.contains("required")
rules[element.attr("name")]["required"] = true
if validation.contains("email")
rules[element.attr("name")]["email"] = true
form.validate({
"errorElement": 'span'
"errorClass": 'help-block'
"focusInvalid": false
"ignore": ""
"rules": rules
"invalidHandler": (event, validator) ->
"highlight": (element) ->
$(element).closest('.form-group').addClass('has-error')
"success": (label) ->
label.closest('.form-group').removeClass('has-error')
label.remove();
"errorPlacement": (error, element) ->
error.insertAfter(element.closest('.input-icon'))
})
netuno.downloadProgress = (url) ->
time = new Date().getTime()
$("body").append("<iframe id=\"netuno_download_#{ time }\" src=\"#{ url }&downloadToken=#{ time }\" style=\"display: none;\"></iframe>");
if (!navigator.userAgent.match(/msie/i))
modal = $('#netuno_download')
modal.modal('show');
tickStatus = () ->
$('\#netuno_download_progress_bar').css('width', "100%").attr('aria-valuenow', 100);
$.ajax({
type: 'POST',
url: "#{url }&downloadToken=#{ time }&downloadStatus=true",
success: (response) ->
if (response == 'done')
iframe = $("\#netuno_download_#{ time }")
if ($("\#netuno_download_#{ time }").length > 0)
window.setTimeout(() ->
modal.modal('hide')
$('\#netuno_download_progress_bar').css('width', "0%").attr('aria-valuenow', 0)
iframe.remove()
, 1000);
else
window.setTimeout(tickStatus, 1000);
});
tickStatus();
netuno.keepAlive = ()->
if typeof netuno.config.user != 'undefined'
$.ajax {
type: 'POST',
url: "#{ netuno.config.urlAdmin }KeepAlive#{ netuno.config.extension }",
success: (response)->
if response == "1"
window.setTimeout('netuno.keepAlive();', 360000)
else
document.location.href = "#{ netuno.config.urlAdmin }Index#{ netuno.config.extension }"
}
netuno.loadLinks = (container)->
container.find("a").on "click", ()->
element = $(this)
if element.attr("rel") is "external"
if element.attr("target") is "_blank"
window.open(element.attr("href"))
return false
else
window.location.href = element.attr("href")
return false
else
if element.is("[data-toggle]")
ul = element.parent().children('ul')
if ul.is(':hidden')
ul.fadeIn()
element.children('i:last-child').removeClass('fa-caret-down').addClass('fa-caret-up')
else
ul.fadeOut()
element.children('i:last-child').removeClass('fa-caret-up').addClass('fa-caret-down')
if element.parents('.navbar-nav').length == 1
if ($('body > div.dev').length == 0 || element.parents('.nav-management').length == 0)
$('.navbar-toggle:visible').click()
element.trigger('netuno:click')
window.scrollTo(0, 0)
if element.is("[netuno-content]")
container = $(element.attr("href"))
$("#containers > div").hide()
if container.length > 0 and container.is(":empty")
$.ajax
url: element.attr('netuno-content'),
success: (response) ->
container.html(response);
netuno.contentLoaded(container)
container.show()
return false
else if element.is("[netuno-form]")
formName = element.attr("netuno-form")
$("\#containers > div").hide()
netuno.loadForm($("\#containers > div[netuno-form-name=#{ formName }]"))
return false
else if element.is("[netuno-report]")
reportName = element.attr("netuno-report")
$("#containers > div").hide()
netuno.loadReport($("\#containers > div[netuno-report-name=#{ reportName }]"))
return false
else if element.attr("href") isnt "#"
container = $(element.attr("href"))
$("#containers > div").hide()
container.show()
return false
netuno.mask = (container)->
container.find('[data-mask]').each(()->
o = $(this)
if (o.attr('data-mask') != null and o.attr('data-mask') != '')
o.mask(o.attr('data-mask'), {
reverse: o.attr('data-mask-reverse') is 'true'
selectOnFocus: o.attr('data-mask-selectonfocus') is 'true'
})
)
netuno.unmask = (container)->
container.find('[data-mask]').each(()->
o = $(this)
if (typeof o.data().mask isnt 'undefined' and o.data().mask isnt null)
if o.text() isnt ''
data = o.data()
delete data.mask
o.data(data)
else
o.unmask()
)
netuno.addContentLoad (container)->
netuno.loadLinks(container)
netuno.addContentLoad (container)->
container.find("select").select2(
theme: "bootstrap"
placeholder: ""
maximumSelectionSize: 6
)
netuno.addContentLoad (container)->
netuno.mask(container)
netuno.openRelation = (name) ->
container = $("\#netuno_form_#{ name }")
containerSearch = container.children('[netuno-form-search]')
if containerSearch.is(':empty')
$.ajax(
type: 'POST'
url: "#{ netuno.config.urlAdmin }Search#{ netuno.config.extension }"
data: { 'netuno_table_uid': container.attr('netuno-form-uid') }
success: (response) ->
containerSearch.html(response);
netuno.contentLoaded(containerSearch)
)
container.show()
netuno.addPageLoad ()->
netuno.loadLinks($("body"))
netuno.modal = {}
netuno.modal.stack = []
netuno.modal.create = (config) ->
config = $.extend {
name: null,
container: $('body')
relation: false
callback: (modal)->
}, config
if (config.name == null)
return
key = <KEY>
$.ajax(
type: 'POST'
url: "#{ netuno.config.urlAdmin }Edit#{ netuno.config.extension }"
dataType: 'json'
data: {
netuno_action: 'uid'
netuno_table_name: config.name
}
success: (response) ->
modalRelationParam = ""
modalRelationFormParam = ""
if (config.relation)
modalRelationParam = "netuno-form-edit-relation-modal=\"#{ config.name }\""
modalRelationFormParam = "netuno-form-relation netuno-table-uid=\"#{ config.relation.table_uid }\" netuno-item-uid=\"#{ config.relation.item_uid }\""
config.container.append("""
<div id="netuno-modal-#{ key }" #{ modalRelationParam } class="netuno-modal">
<div class="container-fluid">
<div netuno-form netuno-form-uid="#{ response.uid }" netuno-form-name="#{ config.name }" #{ modalRelationFormParam }>
<div class="netuno-form-edit" netuno-form-edit></div>
<div class="netuno-form-search" netuno-form-search></div>
</div>
</div>
</div>
""")
config.callback($("\#netuno-modal-#{ key }"))
)
netuno.modal.showAndLoad = (modal)->
modal = $(modal) unless modal instanceof jQuery
netuno.modal.show(modal)
netuno.loadForm(modal.find('[netuno-form]'))
netuno.modal.show = (modal)->
modal = $(modal) unless modal instanceof jQuery
modal.trigger('netuno:modal:show')
$('#netuno-modal-curtain').fadeIn()
$('#netuno-modal-close').show()
modal.show()
netuno.modal.stack.push(modal)
modal.trigger('netuno:modal:shown')
netuno.modal.hide = (modal)->
modal = $(modal) unless modal instanceof jQuery
modal.trigger('netuno:modal:hide')
modal.hide()
for i in [0 ... netuno.modal.stack.length]
if (netuno.modal.stack[i] == modal)
netuno.modal.stack.splice(i, 1)
if (netuno.modal.stack.length == 0)
$('#netuno-modal-curtain').fadeOut()
$('#netuno-modal-close').hide()
modal.trigger('netuno:modal:hidden')
netuno.modal.hideLast = ()->
if (netuno.modal.stack.length > 0)
netuno.modal.hide(netuno.modal.stack[netuno.modal.stack.length - 1])
netuno.com = {}
netuno.com['text'] =
'html': {
'load': (id, css)->
summernote = $("\##{ id }").summernote({
callbacks: {
onImageUpload: (files) ->
upload = (file) ->
comUid = summernote.attr('netuno-texthtml-uid')
formData = new FormData()
formData.append "com_uid", comUid
formData.append "file", file, file.name
$.ajax({
method: "POST"
url: "#{ netuno.config.urlAdmin }com/TextHtml#{ netuno.config.extension }"
contentType: false
cache: false
processData: false
data: formData
dataType: "json"
success: (data) ->
summernote.summernote("insertImage", data.url)
error: (jqXHR, textStatus, errorThrown) ->
console.error("#{ textStatus } #{ errorThrown }")
})
upload(file) for file in files
},
height: 200
})
}
'md': {
'load': (id) ->
container = $("\##{ id }")
textarea = container.find("[netuno-textmd-uid]")
comUid = textarea.attr('netuno-textmd-uid')
window.setTimeout(()->
editor = editormd(id, {
width: "100%",
height: "400px",
path: "/netuno/scripts/sbadmin/plugins/editor.md/lib/",
codeFold : true,
emoji: true,
taskList: true,
tocm: true,
tex: true,
flowChart: true,
sequenceDiagram: true,
imageUpload: true,
imageFormats: ["jpg", "jpeg", "gif", "png", "svg", "webp"],
imageUploadURL: "#{ netuno.config.urlAdmin }com/TextMD#{ netuno.config.extension }?com_uid=#{ comUid }",
onfullscreen: ()->
editor.editor.css('z-index', 10000)
onfullscreenExit: ()->
editor.editor.css('z-index', 0)
onload: ()->
this.unwatch()
this.previewed()
lang : {
name : "en",
description : "Open source online Markdown editor.",
tocTitle : "Table of Contents",
toolbar : {
undo : "Undo(Ctrl+Z)",
redo : "Redo(Ctrl+Y)",
bold : "Bold",
del : "Strikethrough",
italic : "Italic",
quote : "Block quote",
ucwords : "Words first letter convert to uppercase",
uppercase : "Selection text convert to uppercase",
lowercase : "Selection text convert to lowercase",
h1 : "Heading 1",
h2 : "Heading 2",
h3 : "Heading 3",
h4 : "Heading 4",
h5 : "Heading 5",
h6 : "Heading 6",
"list-ul" : "Unordered list",
"list-ol" : "Ordered list",
hr : "Horizontal rule",
link : "Link",
"reference-link" : "Reference link",
image : "Image",
code : "Code inline",
"preformatted-text" : "Preformatted text / Code block (Tab indent)",
"code-block" : "Code block (Multi-languages)",
table : "Tables",
datetime : "Datetime",
emoji : "Emoji",
"html-entities" : "HTML Entities",
pagebreak : "Page break",
watch : "Unwatch",
unwatch : "Watch",
preview : "HTML Preview (Press Shift + ESC exit)",
fullscreen : "Fullscreen (Press ESC exit)",
clear : "Clear",
search : "Search",
help : "Help",
info : "About "
},
buttons : {
enter : "Enter",
cancel : "Cancel",
close : "Close"
},
dialog : {
link : {
title : "Link",
url : "Address",
urlTitle : "Title",
urlEmpty : "Error: Please fill in the link address."
},
referenceLink : {
title : "Reference link",
name : "<NAME>",
url : "Address",
urlId : "ID",
urlTitle : "Title",
nameEmpty: "Error: Reference name can't be empty.",
idEmpty : "Error: Please fill in reference link id.",
urlEmpty : "Error: Please fill in reference link url address."
},
image : {
title : "Image",
url : "Address",
link : "Link",
alt : "Title",
uploadButton : "Upload",
imageURLEmpty : "Error: picture url address can't be empty.",
uploadFileEmpty : "Error: upload pictures cannot be empty!",
formatNotAllowed : "Error: only allows to upload pictures file, upload allowed image file format:"
},
preformattedText : {
title : "Preformatted text / Codes",
emptyAlert : "Error: Please fill in the Preformatted text or content of the codes.",
placeholder : "coding now...."
},
codeBlock : {
title : "Code block",
selectLabel : "Languages: ",
selectDefaultText : "select a code language...",
otherLanguage : "Other languages",
unselectedLanguageAlert : "Error: Please select the code language.",
codeEmptyAlert : "Error: Please fill in the code content.",
placeholder : "coding now...."
},
htmlEntities : {
title : "HTML Entities"
},
help : {
title : "Help"
}
}
}
})
, 250)
}
netuno.com['select'] =
callbacks: []
getConfig: (fieldId, service, ajaxParams) ->
netuno.com.select.loadCallbacksForFieldId(fieldId)
delayCallbacks = new Date().getTime()
field = $("\##{ fieldId }")
placeholder = netuno.config.com.lang.select["defaulttext"]
if field.attr("multiple")
placeholder = $('<div />').html(placeholder).text()
# dropdownParent: field.parent()
return {
theme: "bootstrap"
placeholder: placeholder
allowClear: true,
data: [ ]
ajax: {
url: service
dataType: 'json'
delay: 250
data: (params) ->
return $.extend(true, {
q: params.term,
page: params.page,
page_limit: 10
}, ajaxParams)
processResults: (data, params) ->
params.page = 1 if params.page?
return { results: data }
}
templateResult: (item) ->
return item.label
templateSelection: (item) ->
$("\##{ fieldId }").parent().parent().removeClass("has-error")
if (new Date().getTime() < delayCallbacks + 250)
if item.label
return item.label
else
return item.text
for key of netuno.com.select.callbacks[fieldId]
callback = netuno.com.select.callbacks[fieldId][key]
if ($.isFunction(callback))
callback(item.id)
delayCallbacks = new Date().getTime()
if item.label
return item.label
else
return item.text
escapeMarkup: (m)->
return m
}
callbackForFieldId: (fieldId, key, callback)->
netuno.com.select.loadCallbacksForFieldId(fieldId)
netuno.com.select.callbacks[fieldId][key] = callback
loadCallbacksForFieldId: (fieldId)->
if fieldId? and fieldId.length > 0 and not netuno.com.select.callbacks[fieldId]?
netuno.com.select.callbacks[fieldId] = {}
load: (fieldId, comUid, service)->
$("\##{ fieldId }").select2(netuno.com.select.getConfig(fieldId, service, { com_uid: comUid }))
loadInContainer: (container)->
container.find("select[netuno-select-uid]").each(()->
select = $(this)
select.select2('destroy')
value = select.attr('value')
comUid = select.attr('netuno-select-uid')
service = select.attr('netuno-select-service')
if comUid? and comUid isnt ''
select2 = select.select2(netuno.com.select.getConfig(select.attr('id'), service, { com_uid: comUid }))
if value? and value isnt ''
option = $('<option selected>Loading...</option>').val(value)
select.append(option)
select.trigger('change')
$.ajax({
dataType: "jsonp"
url: "#{ service }?com_uid=#{ comUid }&data_uid=#{ value }"
}).then((data) ->
if data? and data.label? and data.id?
option.html(data.label).val(data.id)
option.removeData()
select.trigger('change')
selectId = select.attr('id')
selectContainer = $("\#select2-#{ selectId }-container");
selectContainer.html(data.label)
selectContainer.prepend($(document.createElement("span")).addClass('select2-selection__clear').text('×').data(data).on('click', (e)->
select = $("\##{ selectId }")
select.attr("value", "")
select.empty()
netuno.com.select.loadInContainer(select.parent())
e.preventDefault()
))
selectContainer.find('.select2-selection__clear').data(data)
)
)
container.find("select[netuno-select-link]").each(()->
link = $(this).attr('netuno-select-link')
columnSeparator = $(this).attr('netuno-select-column-separator')
maxColumnLength = $(this).attr('netuno-select-max-column-length')
onlyActives = $(this).attr('netuno-select-only-actives')
service = $(this).attr('netuno-select-service')
if link? and link isnt ''
$(this).select2(netuno.com.select.getConfig($(this).attr('id'), service, {
link: link,
column_separator: columnSeparator,
max_column_length: maxColumnLength,
only_actives: onlyActives
}));
)
container.find("select[netuno-select-service]:not([netuno-select-uid],[netuno-select-link])").each(()->
service = $(this).attr('netuno-select-service')
if service? and service isnt ''
select = $(this)
select.select2('destroy')
value = select.attr('value')
service = select.attr('netuno-select-service')
select2 = $(this).select2(netuno.com.select.getConfig($(this).attr('id'), service))
if value? and value isnt ''
option = $('<option selected>Loading...</option>').val(value)
select.append(option).trigger('change')
$.ajax({
dataType: "jsonp"
url: "#{ service }&data_uid=#{ value }"
}).then((data) ->
if data? and data.label? and data.id?
option.html(data.label).val(data.id)
option.removeData()
select.trigger('change')
selectId = select.attr('id')
selectContainer = $("\#select2-#{ selectId }-container");
selectContainer.html(data.label)
selectContainer.prepend($(document.createElement("span")).addClass('select2-selection__clear').text('×').data(data).on('click', ()->
$("\##{ selectId }").val('')
$(this).parent().empty()
))
selectContainer.find('.select2-selection__clear').data(data)
)
)
setValue: (select, uid) ->
select
.empty()
.append($('<option></option>'))
.append(
$('<option selected></option>')
.val(uid)
)
.val(uid)
.attr('value', uid)
netuno.com.select.loadInContainer(select.parent())
netuno.com['multiselect'] =
loadInContainer: (container)->
container.find("select[netuno-multiselect-uid]").each(()->
input = $(this)
input.select2('destroy')
value = input.attr('value')
comUid = input.attr('netuno-multiselect-uid')
service = input.attr('netuno-multiselect-service')
if comUid? and comUid isnt ''
select2 = input.select2(netuno.com.multiselect.getConfig(input.attr('id'), service, { com_uid: comUid }))
)
,
load: (fieldId, designId, referenceId) ->
$("\##{fieldId}").select2(
formatNoMatches: ()->
return netuno.config.com.lang.multiselect["noresults"]
,
formatSearching: ()->
return netuno.config.com.lang.multiselect["searching"]
,
placeholder: $('<div />').html(netuno.config.com.lang.multiselect["defaulttext"]).text(),
ajax: {
url: "com/MultiSelect.netuno",
dataType: 'jsonp',
data: (term, page)->
return {
id: designId,
q: term,
page: page,
page_limit: 10
}
,
results: (data, page)->
return {results: data}
},
id: (item)->
return item.id
,
initSelection: (element, callback)->
dataIds = $(element).val()
if (dataIds != "")
$.ajax("com/MultiSelect.netuno", {
data: {
id: designId,
dataids: dataIds,
referenceid: referenceId
},
dataType: "jsonp"
}).done((data)->
callback(data)
)
,
formatResult: (item)->
return item.label
,
formatSelection: (item)->
return item.label
,
escapeMarkup: (m)->
return m
,
multiple: true,
tokenSeparators: [",", " "]
)
netuno.com['date'] =
load: (fieldId, container, callback) ->
$("\##{ fieldId }").on('change', callback).datepicker({
format: "yyyy-mm-dd",
autoclose: true,
todayHighlight: true,
orientation: "auto"
container: "\##{ container }"
})
netuno.com['time'] =
load: (fieldId, container, callback) ->
control = $("\##{ fieldId }").on('change', callback).clockpicker({
autoclose: true,
placement: 'top'
})
return control
netuno.com['checkbox'] =
loadInContainer: (container)->
container.find("[type=\"checkbox\"]").each ()->
$(this).bootstrapSwitch(
size: "small"
onText: "<i class=\"fa fa-check\"></i>"
offText: "<i class=\"fa fa-close\"></i>"
)
netuno.com['color'] =
load: (fieldId) ->
control = $("\##{ fieldId }").colorpicker()
return control
netuno.com['image'] =
load: (id)->
upload = $("\##{ id }")
if ($("\##{ id }-value").val().length > 0)
value = $("\##{ id }-value").val()
else
$("\##{ id }-btView").hide()
upload.on("change", ()->
input = $(this)
numFiles = if input.get(0).files then input.get(0).files.length else 1
label = input.val().replace(/\\/g, '/').replace(/.*\//, '')
input.trigger('fileselect', [numFiles, label])
)
upload.on('fileselect', (event, numFiles, label) ->
$("\##{ id }-null").val('false')
input = $(this).parents('.input-group').find(':text')
log = if numFiles > 1 then "#{numFiles } files selected" else label
if (input.length > 0)
input.val(log)
)
view: (id, url)->
window.open(url, "_blank")
clear: (id)->
$("\##{ id }").val('').parents('.input-group').find(':text').val('')
$("\##{ id }-fileFeedback").html('')
$("\##{ id }-null").val('true')
$("\##{ id }-preview").hide()
$("\##{ id }-btView").hide()
netuno.com['file'] =
load: (id)->
upload = $("\##{ id }")
if ($("\##{ id }-value").val().length == 0)
$("\##{ id }-btView").hide()
upload.on("change", ()->
input = $(this)
numFiles = if input.get(0).files then input.get(0).files.length else 1
label = input.val().replace(/\\/g, '/').replace(/.*\//, '')
input.trigger('fileselect', [numFiles, label])
)
upload.on('fileselect', (event, numFiles, label) ->
$("\##{ id }-null").val('false')
input = $(this).parents('.input-group').find(':text')
log = if numFiles > 1 then "#{numFiles } files selected" else label
if (input.length > 0)
input.val(log)
)
view: (id)->
value = $("\##{ id }-value")
window.open(value.attr('file-url'))
clear: (id)->
$("\##{ id }").val('').parents('.input-group').find(':text').val('')
$("\##{ id }-fileFeedback").html('')
$("\##{ id }-null").val('true')
$("\##{ id }-btView").hide()
restore: (id)->
$(document).ready ()->
netuno.pageLoaded()
netuno.addContentLoad (container) ->
netuno.com['select'].loadInContainer(container)
netuno.addContentLoad (container) ->
netuno.com['checkbox'].loadInContainer(container)
netuno.keepAlive()
$(document).on 'show.bs.modal', (event)->
target = $(event.target)
parents = target.parents('.modal')
if (parents.length > 0)
target.detach().appendTo('body').attr('netuno-parent-modal-id', $(parents[0]).attr('id'))
$(parents[0]).modal('hide')
$(document).on 'hidden.bs.modal', (event)->
target = $(event.target)
if (target.attr('netuno-parent-modal-id'))
target.detach().appendTo("\##{ target.attr('netuno-parent-modal-id') }")
$("\##{ target.attr('netuno-parent-modal-id') }").modal('show')
#$(event.relatedTarget).parents('.modal')
#$(event.relatedTarget).parents('.modal').modal('hide')
#$(document).on 'shown.bs.modal', (event) ->
# if ($('body').hasClass('modal-open') == false)
# $('body').addClass('modal-open')
| true |
toastr.options = {
"closeButton": true,
"debug": false,
"newestOnTop": true,
"progressBar": false,
"positionClass": "toast-top-center",
"preventDuplicates": true,
"onclick": null,
"showDuration": "300",
"hideDuration": "1000",
"timeOut": "3000",
"extendedTimeOut": "1000",
"showEasing": "swing",
"hideEasing": "linear",
"showMethod": "fadeIn",
"hideMethod": "fadeOut"
}
$ ->
$('form').submit ->
false
return
netuno.newUid = ()->
s4 = () ->
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1)
return "#{ s4() }#{ s4() }_#{ s4() }_#{ s4() }_#{ s4() }_#{ s4() }#{ s4() }#{ s4() }"
netuno.callbacks =
create: (func)->
key = PI:KEY:<KEY>END_PI()
netuno.callbacks[key] = func
return key
remove: (key)->
delete netuno.callbacks[key]
netuno.menu = (menu)->
navMenuHtml = "<li><a netuno-navigation-dashboard href=\"#netuno_dashboard\"><i class=\"fa fa-fw fa-dashboard\"></i> #{ netuno.lang['menu.dashboard'] }</a></li>"
containersHtml = ''
buildMenu = (type, parentUId, items, level) ->
menuHtml = '';
if level > 0
menuHtml += '<ul>'
for item in items
expand = ""
if item.items.length > 0
expand = " data-toggle="
menuHtml += '<li>'
menuHtml += "<a netuno-navigation-#{ type }-item.name href=\"\#\" netuno-#{ type }=\"#{ item.name }\"#{ expand }>"
menuHtml += "#{ item.text }"
if item.items.length > 0
menuHtml += "<i class=\"fa fa-fw fa-caret-down\"></i>"
menuHtml += "</a>"
if item.items.length > 0
menuHtml += buildMenu(type, item.uid, item.items, level + 1)
menuHtml += '</li>'
containersHtml += "<div netuno-container-#{ type }-#{ item.name } netuno-#{ type } netuno-#{ type }-uid=\"#{ item.uid }\" netuno-#{ type }-name=\"#{ item.name }\">"
if type is 'form'
containersHtml += "<div class=\"netuno-form-edit\" netuno-#{ type }-edit=\"#{ item.name }\"></div>"
containersHtml += "<div class=\"netuno-form-search\" netuno-#{ type }-search=\"#{ item.name }\"></div>"
containersHtml += "</div>"
if level > 0
menuHtml += '</ul>'
return menuHtml
if menu.forms.length > 0
navMenuHtml += "<li class=\"nav-section-title\"><h4> <i class=\"fa fa-fw fa-edit\"></i>#{ netuno.lang['menu.forms'] }</h4></li>"
navMenuHtml += buildMenu 'form', 0, menu.forms, 0
if menu.reports.length > 0
navMenuHtml += "<li class=\"nav-section-title\"><h4> <i class=\"fa fa-fw fa-area-chart\"></i>#{ netuno.lang['menu.reports'] }</h4></li>"
navMenuHtml += buildMenu 'report', 0, menu.reports, 0
navbar = $('[netuno-navigation]')
navbar.append(navMenuHtml).show().find('ul').hide()
navbar.trigger('netuno:loaded')
containers = $('[netuno-containers]')
containers.append(containersHtml)
containers.trigger('netuno:loaded')
netuno.navigationLoaded()
netuno.loadForm = (container) ->
container = $(container) unless container instanceof jQuery
container = if container.is("[netuno-form][netuno-form-uid]") then container else container.closest("[netuno-form][netuno-form-uid]")
containerSearch = container.children('[netuno-form-search]')
data = { 'netuno_table_uid': container.attr('netuno-form-uid') }
if container.is("[netuno-form-relation]")
data['netuno_relation_table_uid'] = container.attr('netuno-table-uid')
data['netuno_relation_item_uid'] = container.attr('netuno-item-uid')
if containerSearch.is(':empty')
containerSearch.html("<div class=\"netuno-loader\">Loading...</div>")
$.ajax(
type: 'POST'
url: "#{ netuno.config.urlAdmin }Search#{ netuno.config.extension }"
data: data
success: (response) ->
containerSearch.html(response)
netuno.contentLoaded(containerSearch)
)
container.show()
netuno.formSearchDataTableBulk = {}
netuno.formSearchDataTableBulkActive = (tableId, callback) ->
netuno.formSearchDataTableBulk[tableId] = {
active: true,
callback: callback,
uids: []
}
table = $("\##{tableId}")
searchContainer = table.parents("[netuno-form-search]:first")
searchContainer.find("[netuno-form-search-buttons]").find("button").prop('disabled', true).fadeTo("slow", 0.5)
searchContainer.find("h1.page-header").find('button').prop('disabled', true).fadeTo("slow", 0.5)
netuno.formSearchDataTableBulkInactive = (tableId) ->
if netuno.formSearchDataTableBulk[tableId]?
delete netuno.formSearchDataTableBulk[tableId]
table = $("\##{tableId}")
tableBody = table.find('tbody')
tableBody.find('tr').each () ->
tr = $(this)
tr.removeClass('selected')
searchContainer = table.parents("[netuno-form-search]:first")
searchContainer.find("[netuno-form-search-buttons]").find("button").prop('disabled', false).fadeTo("slow", 1)
searchContainer.find("h1.page-header").find('button').prop('disabled', false).fadeTo("slow", 1)
netuno.executeFormSearchBulk = (settings) ->
settings = $.extend {
action: null
tableId: null
callback: (resut)->
}, settings
table = $("\##{settings.tableId}")
container = table.parents("[netuno-form][netuno-form-uid]:first")
container.data({
pageNumber: 0,
pageLength: 0,
rowIndex: 0
})
uids = netuno.formSearchDataTableBulk[settings.tableId].uids
$.ajax(
type: 'POST'
url: "#{ netuno.config.urlAdmin }Search#{ netuno.config.extension }"
dataType: 'json'
contentType : 'application/json',
data: JSON.stringify({
netuno_action: "bulk-#{settings.action}"
netuno_table_name: container.attr('netuno-form-name'),
netuno_items_uids: uids
})
success: (response) ->
settings.callback(response)
)
netuno.loadFormSearchDataTable = (table) ->
table = $(table) unless table instanceof jQuery
isButton = table.is('button')
container = table.parents("[netuno-form][netuno-form-uid]:first")
table = container.find("[netuno-form-search-table=#{ container.attr('netuno-form-name') }]:first") unless table.is('table')
tableId = table.attr('id')
netuno.formSearchDataTableBulkInactive tableId
containerSearch = container.children('[netuno-form-search]')
containerSearchForm = containerSearch.find("form[name=netuno_form_#{ container.attr('netuno-form-name') }_search]:first")
tableBody = table.find('tbody')
tableBody.empty()
dt = null
findDataTableTR = (e) ->
if e.tagName.toLowerCase() is 'tr'
return e
if e.parentNode.tagName.toLowerCase() is 'tr'
return e.parentNode
return findDataTableTR(e.parentNode)
if table.find('th').length > 0
netuno.unmask containerSearchForm if isButton
dt = table.dataTable(
"pagingType": "full_numbers"
"pageLength": 25
"processing": false
"serverSide": true
"destroy": true
"displayStart": if container.data().pageNumber > 0 then container.data().pageNumber * 25 else null
"ajax": {
"url": "#{ netuno.config.urlAdmin }Search#{ netuno.config.extension }?netuno_action=datasource&"+ containerSearchForm.serialize()
"type": "POST"
}
"preDrawCallback": (settings) ->
tableBody.html("<tr><td colspan=\"1000\" style=\"background-color: #ffffff;\"><div style=\"width: 100%;\"><div class=\"netuno-loader\">Loading...</div></div></td></tr>")
"drawCallback": (settings, json) ->
netuno.mask table
pageNumber = Math.ceil(settings._iDisplayStart / settings._iDisplayLength);
tableBody.find('tr').data({ pageNumber, pageLength: tableBody.find('tr').length})
tableBody.find('tr').each((index) ->
tr = $(this)
tr.data({ rowIndex: index })
tr.off('click').on 'click', (event) ->
tr = $(findDataTableTR(event.target))
uid = tr.children(':first-child').children('span').html()
if netuno.formSearchDataTableBulk[tableId]? and netuno.formSearchDataTableBulk[tableId].active
if tr.hasClass('selected')
tr.removeClass('selected')
netuno.formSearchDataTableBulk[tableId].uids = netuno.formSearchDataTableBulk[tableId].uids.filter (i) ->
i isnt uid
else
tr.addClass('selected')
netuno.formSearchDataTableBulk[tableId].uids.push(uid)
netuno.formSearchDataTableBulk[tableId].callback(netuno.formSearchDataTableBulk[tableId])
else
window.scrollTo(container.offset().left, container.offset().top - 70)
container.data({
pageNumber: tr.data().pageNumber,
pageLength: tr.data().pageLength,
rowIndex: tr.data().rowIndex
})
netuno.loadFormEdit(table, uid)
)
if netuno.formSearchDataTableBulk[tableId]? and netuno.formSearchDataTableBulk[tableId].active
tableBody.find('tr').each () ->
tr = $(this)
trUID = tr.children(':first-child').children('span').html()
if netuno.formSearchDataTableBulk[tableId].uids.find((uid) -> uid == trUID)
tr.addClass('selected')
,
"initComplete": (settings, json) ->
table.fadeIn()
,
"language": netuno.config.dataTable,
"dom": 'pitip',
"tableTools": {
"sSwfPath": "#{ netuno.config.urlScripts }/plugins/datatables-tabletools/swf/copy_csv_xls_pdf.swf"
}
)
netuno.mask containerSearchForm if isButton
netuno.loadFormEdit = (container, item) ->
container = $(container) unless container instanceof jQuery
container = if container.is("[netuno-form][netuno-form-uid]") then container else container.parents("[netuno-form][netuno-form-uid]:first")
container.children('[netuno-form-search]').hide()
data = {
'netuno_table_uid': container.attr('netuno-form-uid'),
'netuno_item_uid': item,
'netuno_edit_only': container.is("[netuno-form-edit-only]"),
'netuno_zone': container.attr('netuno-zone')
}
if container.is("[netuno-form-relation]")
data['netuno_relation_table_uid'] = container.attr('netuno-table-uid')
data['netuno_relation_item_uid'] = container.attr('netuno-item-uid')
containerEdit = container.children('[netuno-form-edit]')
containerEdit.empty()
containerEdit.html("<div class=\"netuno-loader\">Loading...</div>")
containerEdit.show()
$.ajax(
type: 'POST'
url: "#{ netuno.config.urlAdmin }Edit#{ netuno.config.extension }"
data: data
success: (response) ->
containerEdit.html(response);
netuno.contentLoaded(containerEdit)
containerEditForm = containerEdit.find("form[name=netuno_form_#{ container.attr('netuno-form-name') }_edit]")
if (containerEditForm.length > 0)
netuno.loadValidation(containerEditForm)
if typeof item == 'undefined' or item == null or item == ''
container.trigger('netuno:new')
else
container.trigger('netuno:edit', [ item ])
)
netuno.backFormEdit = (element, disableSearchTableRefresh) ->
element = $(element) unless element instanceof jQuery
container = if element.is("[netuno-form][netuno-form-uid]") then element else element.parents("[netuno-form][netuno-form-uid]:first")
container.children('[netuno-form-edit]').empty().hide()
container.children('[netuno-form-search]').show()
if (disableSearchTableRefresh != true)
table = container.find("[netuno-form-search-table=#{ container.attr('netuno-form-name') }]:first");
table.hide()
netuno.loadFormSearchDataTable(table)
container.trigger('netuno:back')
netuno.saveFormEdit = (element, fromRelation) ->
element = $(element) unless element instanceof jQuery
container = if element.is("[netuno-form][netuno-form-uid]") then element else element.parents("[netuno-form][netuno-form-uid]:first")
containerEdit = container.children('[netuno-form-edit]')
containerEditForm = containerEdit.find("form[name=netuno_form_#{ container.attr('netuno-form-name') }_edit]:first")
netuno.unmask containerEditForm
containerEditForm.ajaxForm().submit()
if containerEditForm.validate().valid()
callback = netuno.callbacks.create((uid)->
container.trigger('netuno:save', [ uid ])
)
containerEditForm.ajaxForm(
url: "#{ netuno.config.urlAdmin }Edit#{ netuno.config.extension }?netuno_action=save&netuno_autosave=#{ typeof fromRelation != 'undefined' }&netuno_callback=#{ callback }"
iframe: false
success: (response) ->
containerEdit.html(response)
containerEditForm = containerEdit.find("form[name=netuno_form_#{ container.attr('netuno-form-name') }_edit]:first")
if (containerEditForm.length > 0)
netuno.contentLoaded(containerEdit)
netuno.loadValidation(containerEditForm)
if (typeof fromRelation != 'undefined')
containerEditForm.find("button[netuno-form-edit-relation-button=#{ fromRelation }]:first").trigger('click')
).submit()
return true
else
netuno.mask containerEditForm
return false
netuno.deleteFormEdit = (element) ->
element = $(element) unless element instanceof jQuery
container = if element.is("[netuno-form][netuno-form-uid]") then element else element.parents("[netuno-form][netuno-form-uid]:first")
containerEdit = container.children('[netuno-form-edit]')
if (!containerEdit.is(':empty'))
containerEditForm = containerEdit.find("form[name=netuno_form_#{ container.attr('netuno-form-name') }_edit]:first")
netuno.unmask containerEditForm
callback = netuno.callbacks.create((uid)->
container.trigger('netuno:delete', [ uid ])
)
$.ajax(
type: 'POST'
url: "#{ netuno.config.urlAdmin }Edit#{ netuno.config.extension }?netuno_action=delete&netuno_callback=#{ callback }"
data: containerEditForm.serialize()
success: (response) ->
if (container.data().pageNumber > 0 && container.data().pageLength == 1)
container.data({pageNumber: container.data().pageNumber - 1})
containerEdit.html(response)
netuno.contentLoaded(containerEdit)
containerEditForm = containerEdit.find("form[name=netuno_form_#{ container.attr('netuno-form-name') }_edit]:first")
if (containerEditForm.length > 0)
netuno.loadValidation(containerEditForm)
)
netuno.loadReport = (container) ->
container = $(container) unless container instanceof jQuery
container = if container.is("[netuno-report][netuno-report-uid]") then container else container.parents("[netuno-report][netuno-report-uid]:first")
container.children('[netuno-report-search]').hide()
if container.is(':empty')
$.ajax(
type: 'POST'
url: "#{ netuno.config.urlAdmin }Report#{ netuno.config.extension }"
data: {'netuno_report_uid': container.attr('netuno-report-uid')}
success: (response) ->
container.html(response);
netuno.contentLoaded(container)
)
container.show()
netuno.buildReport = (report) ->
report = $(report) unless report instanceof jQuery
container = report.parents("[netuno-report][netuno-report-uid]:first")
containerResult = container.children("[netuno-report-result=#{ container.attr('netuno-report-name') }]")
containerForm = container.find("form[name=netuno_report_#{ container.attr('netuno-report-name') }_form]:first")
containerForm.ajaxForm().submit()
if containerForm.validate().valid()
containerForm.ajaxForm(
url: "#{ netuno.config.urlAdmin }ReportBuilder#{ netuno.config.extension }"
iframe: false
success: (response) ->
containerResult.html(response)
netuno.contentLoaded(containerResult)
).submit()
return true
else
return false
netuno.loadValidation = (form) ->
form = $(form) unless form instanceof jQuery
form = if form.is("form") then form else form.closest("form")
rules = {}
form.find("[validation]").each ()->
element = $(this)
validation = S(element.attr("validation"))
rules[element.attr("name")] = {}
if validation.contains("required")
rules[element.attr("name")]["required"] = true
if validation.contains("email")
rules[element.attr("name")]["email"] = true
form.validate({
"errorElement": 'span'
"errorClass": 'help-block'
"focusInvalid": false
"ignore": ""
"rules": rules
"invalidHandler": (event, validator) ->
"highlight": (element) ->
$(element).closest('.form-group').addClass('has-error')
"success": (label) ->
label.closest('.form-group').removeClass('has-error')
label.remove();
"errorPlacement": (error, element) ->
error.insertAfter(element.closest('.input-icon'))
})
netuno.downloadProgress = (url) ->
time = new Date().getTime()
$("body").append("<iframe id=\"netuno_download_#{ time }\" src=\"#{ url }&downloadToken=#{ time }\" style=\"display: none;\"></iframe>");
if (!navigator.userAgent.match(/msie/i))
modal = $('#netuno_download')
modal.modal('show');
tickStatus = () ->
$('\#netuno_download_progress_bar').css('width', "100%").attr('aria-valuenow', 100);
$.ajax({
type: 'POST',
url: "#{url }&downloadToken=#{ time }&downloadStatus=true",
success: (response) ->
if (response == 'done')
iframe = $("\#netuno_download_#{ time }")
if ($("\#netuno_download_#{ time }").length > 0)
window.setTimeout(() ->
modal.modal('hide')
$('\#netuno_download_progress_bar').css('width', "0%").attr('aria-valuenow', 0)
iframe.remove()
, 1000);
else
window.setTimeout(tickStatus, 1000);
});
tickStatus();
netuno.keepAlive = ()->
if typeof netuno.config.user != 'undefined'
$.ajax {
type: 'POST',
url: "#{ netuno.config.urlAdmin }KeepAlive#{ netuno.config.extension }",
success: (response)->
if response == "1"
window.setTimeout('netuno.keepAlive();', 360000)
else
document.location.href = "#{ netuno.config.urlAdmin }Index#{ netuno.config.extension }"
}
netuno.loadLinks = (container)->
container.find("a").on "click", ()->
element = $(this)
if element.attr("rel") is "external"
if element.attr("target") is "_blank"
window.open(element.attr("href"))
return false
else
window.location.href = element.attr("href")
return false
else
if element.is("[data-toggle]")
ul = element.parent().children('ul')
if ul.is(':hidden')
ul.fadeIn()
element.children('i:last-child').removeClass('fa-caret-down').addClass('fa-caret-up')
else
ul.fadeOut()
element.children('i:last-child').removeClass('fa-caret-up').addClass('fa-caret-down')
if element.parents('.navbar-nav').length == 1
if ($('body > div.dev').length == 0 || element.parents('.nav-management').length == 0)
$('.navbar-toggle:visible').click()
element.trigger('netuno:click')
window.scrollTo(0, 0)
if element.is("[netuno-content]")
container = $(element.attr("href"))
$("#containers > div").hide()
if container.length > 0 and container.is(":empty")
$.ajax
url: element.attr('netuno-content'),
success: (response) ->
container.html(response);
netuno.contentLoaded(container)
container.show()
return false
else if element.is("[netuno-form]")
formName = element.attr("netuno-form")
$("\#containers > div").hide()
netuno.loadForm($("\#containers > div[netuno-form-name=#{ formName }]"))
return false
else if element.is("[netuno-report]")
reportName = element.attr("netuno-report")
$("#containers > div").hide()
netuno.loadReport($("\#containers > div[netuno-report-name=#{ reportName }]"))
return false
else if element.attr("href") isnt "#"
container = $(element.attr("href"))
$("#containers > div").hide()
container.show()
return false
netuno.mask = (container)->
container.find('[data-mask]').each(()->
o = $(this)
if (o.attr('data-mask') != null and o.attr('data-mask') != '')
o.mask(o.attr('data-mask'), {
reverse: o.attr('data-mask-reverse') is 'true'
selectOnFocus: o.attr('data-mask-selectonfocus') is 'true'
})
)
netuno.unmask = (container)->
container.find('[data-mask]').each(()->
o = $(this)
if (typeof o.data().mask isnt 'undefined' and o.data().mask isnt null)
if o.text() isnt ''
data = o.data()
delete data.mask
o.data(data)
else
o.unmask()
)
netuno.addContentLoad (container)->
netuno.loadLinks(container)
netuno.addContentLoad (container)->
container.find("select").select2(
theme: "bootstrap"
placeholder: ""
maximumSelectionSize: 6
)
netuno.addContentLoad (container)->
netuno.mask(container)
netuno.openRelation = (name) ->
container = $("\#netuno_form_#{ name }")
containerSearch = container.children('[netuno-form-search]')
if containerSearch.is(':empty')
$.ajax(
type: 'POST'
url: "#{ netuno.config.urlAdmin }Search#{ netuno.config.extension }"
data: { 'netuno_table_uid': container.attr('netuno-form-uid') }
success: (response) ->
containerSearch.html(response);
netuno.contentLoaded(containerSearch)
)
container.show()
netuno.addPageLoad ()->
netuno.loadLinks($("body"))
netuno.modal = {}
netuno.modal.stack = []
netuno.modal.create = (config) ->
config = $.extend {
name: null,
container: $('body')
relation: false
callback: (modal)->
}, config
if (config.name == null)
return
key = PI:KEY:<KEY>END_PI
$.ajax(
type: 'POST'
url: "#{ netuno.config.urlAdmin }Edit#{ netuno.config.extension }"
dataType: 'json'
data: {
netuno_action: 'uid'
netuno_table_name: config.name
}
success: (response) ->
modalRelationParam = ""
modalRelationFormParam = ""
if (config.relation)
modalRelationParam = "netuno-form-edit-relation-modal=\"#{ config.name }\""
modalRelationFormParam = "netuno-form-relation netuno-table-uid=\"#{ config.relation.table_uid }\" netuno-item-uid=\"#{ config.relation.item_uid }\""
config.container.append("""
<div id="netuno-modal-#{ key }" #{ modalRelationParam } class="netuno-modal">
<div class="container-fluid">
<div netuno-form netuno-form-uid="#{ response.uid }" netuno-form-name="#{ config.name }" #{ modalRelationFormParam }>
<div class="netuno-form-edit" netuno-form-edit></div>
<div class="netuno-form-search" netuno-form-search></div>
</div>
</div>
</div>
""")
config.callback($("\#netuno-modal-#{ key }"))
)
netuno.modal.showAndLoad = (modal)->
modal = $(modal) unless modal instanceof jQuery
netuno.modal.show(modal)
netuno.loadForm(modal.find('[netuno-form]'))
netuno.modal.show = (modal)->
modal = $(modal) unless modal instanceof jQuery
modal.trigger('netuno:modal:show')
$('#netuno-modal-curtain').fadeIn()
$('#netuno-modal-close').show()
modal.show()
netuno.modal.stack.push(modal)
modal.trigger('netuno:modal:shown')
netuno.modal.hide = (modal)->
modal = $(modal) unless modal instanceof jQuery
modal.trigger('netuno:modal:hide')
modal.hide()
for i in [0 ... netuno.modal.stack.length]
if (netuno.modal.stack[i] == modal)
netuno.modal.stack.splice(i, 1)
if (netuno.modal.stack.length == 0)
$('#netuno-modal-curtain').fadeOut()
$('#netuno-modal-close').hide()
modal.trigger('netuno:modal:hidden')
netuno.modal.hideLast = ()->
if (netuno.modal.stack.length > 0)
netuno.modal.hide(netuno.modal.stack[netuno.modal.stack.length - 1])
netuno.com = {}
netuno.com['text'] =
'html': {
'load': (id, css)->
summernote = $("\##{ id }").summernote({
callbacks: {
onImageUpload: (files) ->
upload = (file) ->
comUid = summernote.attr('netuno-texthtml-uid')
formData = new FormData()
formData.append "com_uid", comUid
formData.append "file", file, file.name
$.ajax({
method: "POST"
url: "#{ netuno.config.urlAdmin }com/TextHtml#{ netuno.config.extension }"
contentType: false
cache: false
processData: false
data: formData
dataType: "json"
success: (data) ->
summernote.summernote("insertImage", data.url)
error: (jqXHR, textStatus, errorThrown) ->
console.error("#{ textStatus } #{ errorThrown }")
})
upload(file) for file in files
},
height: 200
})
}
'md': {
'load': (id) ->
container = $("\##{ id }")
textarea = container.find("[netuno-textmd-uid]")
comUid = textarea.attr('netuno-textmd-uid')
window.setTimeout(()->
editor = editormd(id, {
width: "100%",
height: "400px",
path: "/netuno/scripts/sbadmin/plugins/editor.md/lib/",
codeFold : true,
emoji: true,
taskList: true,
tocm: true,
tex: true,
flowChart: true,
sequenceDiagram: true,
imageUpload: true,
imageFormats: ["jpg", "jpeg", "gif", "png", "svg", "webp"],
imageUploadURL: "#{ netuno.config.urlAdmin }com/TextMD#{ netuno.config.extension }?com_uid=#{ comUid }",
onfullscreen: ()->
editor.editor.css('z-index', 10000)
onfullscreenExit: ()->
editor.editor.css('z-index', 0)
onload: ()->
this.unwatch()
this.previewed()
lang : {
name : "en",
description : "Open source online Markdown editor.",
tocTitle : "Table of Contents",
toolbar : {
undo : "Undo(Ctrl+Z)",
redo : "Redo(Ctrl+Y)",
bold : "Bold",
del : "Strikethrough",
italic : "Italic",
quote : "Block quote",
ucwords : "Words first letter convert to uppercase",
uppercase : "Selection text convert to uppercase",
lowercase : "Selection text convert to lowercase",
h1 : "Heading 1",
h2 : "Heading 2",
h3 : "Heading 3",
h4 : "Heading 4",
h5 : "Heading 5",
h6 : "Heading 6",
"list-ul" : "Unordered list",
"list-ol" : "Ordered list",
hr : "Horizontal rule",
link : "Link",
"reference-link" : "Reference link",
image : "Image",
code : "Code inline",
"preformatted-text" : "Preformatted text / Code block (Tab indent)",
"code-block" : "Code block (Multi-languages)",
table : "Tables",
datetime : "Datetime",
emoji : "Emoji",
"html-entities" : "HTML Entities",
pagebreak : "Page break",
watch : "Unwatch",
unwatch : "Watch",
preview : "HTML Preview (Press Shift + ESC exit)",
fullscreen : "Fullscreen (Press ESC exit)",
clear : "Clear",
search : "Search",
help : "Help",
info : "About "
},
buttons : {
enter : "Enter",
cancel : "Cancel",
close : "Close"
},
dialog : {
link : {
title : "Link",
url : "Address",
urlTitle : "Title",
urlEmpty : "Error: Please fill in the link address."
},
referenceLink : {
title : "Reference link",
name : "PI:NAME:<NAME>END_PI",
url : "Address",
urlId : "ID",
urlTitle : "Title",
nameEmpty: "Error: Reference name can't be empty.",
idEmpty : "Error: Please fill in reference link id.",
urlEmpty : "Error: Please fill in reference link url address."
},
image : {
title : "Image",
url : "Address",
link : "Link",
alt : "Title",
uploadButton : "Upload",
imageURLEmpty : "Error: picture url address can't be empty.",
uploadFileEmpty : "Error: upload pictures cannot be empty!",
formatNotAllowed : "Error: only allows to upload pictures file, upload allowed image file format:"
},
preformattedText : {
title : "Preformatted text / Codes",
emptyAlert : "Error: Please fill in the Preformatted text or content of the codes.",
placeholder : "coding now...."
},
codeBlock : {
title : "Code block",
selectLabel : "Languages: ",
selectDefaultText : "select a code language...",
otherLanguage : "Other languages",
unselectedLanguageAlert : "Error: Please select the code language.",
codeEmptyAlert : "Error: Please fill in the code content.",
placeholder : "coding now...."
},
htmlEntities : {
title : "HTML Entities"
},
help : {
title : "Help"
}
}
}
})
, 250)
}
netuno.com['select'] =
callbacks: []
getConfig: (fieldId, service, ajaxParams) ->
netuno.com.select.loadCallbacksForFieldId(fieldId)
delayCallbacks = new Date().getTime()
field = $("\##{ fieldId }")
placeholder = netuno.config.com.lang.select["defaulttext"]
if field.attr("multiple")
placeholder = $('<div />').html(placeholder).text()
# dropdownParent: field.parent()
return {
theme: "bootstrap"
placeholder: placeholder
allowClear: true,
data: [ ]
ajax: {
url: service
dataType: 'json'
delay: 250
data: (params) ->
return $.extend(true, {
q: params.term,
page: params.page,
page_limit: 10
}, ajaxParams)
processResults: (data, params) ->
params.page = 1 if params.page?
return { results: data }
}
templateResult: (item) ->
return item.label
templateSelection: (item) ->
$("\##{ fieldId }").parent().parent().removeClass("has-error")
if (new Date().getTime() < delayCallbacks + 250)
if item.label
return item.label
else
return item.text
for key of netuno.com.select.callbacks[fieldId]
callback = netuno.com.select.callbacks[fieldId][key]
if ($.isFunction(callback))
callback(item.id)
delayCallbacks = new Date().getTime()
if item.label
return item.label
else
return item.text
escapeMarkup: (m)->
return m
}
callbackForFieldId: (fieldId, key, callback)->
netuno.com.select.loadCallbacksForFieldId(fieldId)
netuno.com.select.callbacks[fieldId][key] = callback
loadCallbacksForFieldId: (fieldId)->
if fieldId? and fieldId.length > 0 and not netuno.com.select.callbacks[fieldId]?
netuno.com.select.callbacks[fieldId] = {}
load: (fieldId, comUid, service)->
$("\##{ fieldId }").select2(netuno.com.select.getConfig(fieldId, service, { com_uid: comUid }))
loadInContainer: (container)->
container.find("select[netuno-select-uid]").each(()->
select = $(this)
select.select2('destroy')
value = select.attr('value')
comUid = select.attr('netuno-select-uid')
service = select.attr('netuno-select-service')
if comUid? and comUid isnt ''
select2 = select.select2(netuno.com.select.getConfig(select.attr('id'), service, { com_uid: comUid }))
if value? and value isnt ''
option = $('<option selected>Loading...</option>').val(value)
select.append(option)
select.trigger('change')
$.ajax({
dataType: "jsonp"
url: "#{ service }?com_uid=#{ comUid }&data_uid=#{ value }"
}).then((data) ->
if data? and data.label? and data.id?
option.html(data.label).val(data.id)
option.removeData()
select.trigger('change')
selectId = select.attr('id')
selectContainer = $("\#select2-#{ selectId }-container");
selectContainer.html(data.label)
selectContainer.prepend($(document.createElement("span")).addClass('select2-selection__clear').text('×').data(data).on('click', (e)->
select = $("\##{ selectId }")
select.attr("value", "")
select.empty()
netuno.com.select.loadInContainer(select.parent())
e.preventDefault()
))
selectContainer.find('.select2-selection__clear').data(data)
)
)
container.find("select[netuno-select-link]").each(()->
link = $(this).attr('netuno-select-link')
columnSeparator = $(this).attr('netuno-select-column-separator')
maxColumnLength = $(this).attr('netuno-select-max-column-length')
onlyActives = $(this).attr('netuno-select-only-actives')
service = $(this).attr('netuno-select-service')
if link? and link isnt ''
$(this).select2(netuno.com.select.getConfig($(this).attr('id'), service, {
link: link,
column_separator: columnSeparator,
max_column_length: maxColumnLength,
only_actives: onlyActives
}));
)
container.find("select[netuno-select-service]:not([netuno-select-uid],[netuno-select-link])").each(()->
service = $(this).attr('netuno-select-service')
if service? and service isnt ''
select = $(this)
select.select2('destroy')
value = select.attr('value')
service = select.attr('netuno-select-service')
select2 = $(this).select2(netuno.com.select.getConfig($(this).attr('id'), service))
if value? and value isnt ''
option = $('<option selected>Loading...</option>').val(value)
select.append(option).trigger('change')
$.ajax({
dataType: "jsonp"
url: "#{ service }&data_uid=#{ value }"
}).then((data) ->
if data? and data.label? and data.id?
option.html(data.label).val(data.id)
option.removeData()
select.trigger('change')
selectId = select.attr('id')
selectContainer = $("\#select2-#{ selectId }-container");
selectContainer.html(data.label)
selectContainer.prepend($(document.createElement("span")).addClass('select2-selection__clear').text('×').data(data).on('click', ()->
$("\##{ selectId }").val('')
$(this).parent().empty()
))
selectContainer.find('.select2-selection__clear').data(data)
)
)
setValue: (select, uid) ->
select
.empty()
.append($('<option></option>'))
.append(
$('<option selected></option>')
.val(uid)
)
.val(uid)
.attr('value', uid)
netuno.com.select.loadInContainer(select.parent())
netuno.com['multiselect'] =
loadInContainer: (container)->
container.find("select[netuno-multiselect-uid]").each(()->
input = $(this)
input.select2('destroy')
value = input.attr('value')
comUid = input.attr('netuno-multiselect-uid')
service = input.attr('netuno-multiselect-service')
if comUid? and comUid isnt ''
select2 = input.select2(netuno.com.multiselect.getConfig(input.attr('id'), service, { com_uid: comUid }))
)
,
load: (fieldId, designId, referenceId) ->
$("\##{fieldId}").select2(
formatNoMatches: ()->
return netuno.config.com.lang.multiselect["noresults"]
,
formatSearching: ()->
return netuno.config.com.lang.multiselect["searching"]
,
placeholder: $('<div />').html(netuno.config.com.lang.multiselect["defaulttext"]).text(),
ajax: {
url: "com/MultiSelect.netuno",
dataType: 'jsonp',
data: (term, page)->
return {
id: designId,
q: term,
page: page,
page_limit: 10
}
,
results: (data, page)->
return {results: data}
},
id: (item)->
return item.id
,
initSelection: (element, callback)->
dataIds = $(element).val()
if (dataIds != "")
$.ajax("com/MultiSelect.netuno", {
data: {
id: designId,
dataids: dataIds,
referenceid: referenceId
},
dataType: "jsonp"
}).done((data)->
callback(data)
)
,
formatResult: (item)->
return item.label
,
formatSelection: (item)->
return item.label
,
escapeMarkup: (m)->
return m
,
multiple: true,
tokenSeparators: [",", " "]
)
netuno.com['date'] =
load: (fieldId, container, callback) ->
$("\##{ fieldId }").on('change', callback).datepicker({
format: "yyyy-mm-dd",
autoclose: true,
todayHighlight: true,
orientation: "auto"
container: "\##{ container }"
})
netuno.com['time'] =
load: (fieldId, container, callback) ->
control = $("\##{ fieldId }").on('change', callback).clockpicker({
autoclose: true,
placement: 'top'
})
return control
netuno.com['checkbox'] =
loadInContainer: (container)->
container.find("[type=\"checkbox\"]").each ()->
$(this).bootstrapSwitch(
size: "small"
onText: "<i class=\"fa fa-check\"></i>"
offText: "<i class=\"fa fa-close\"></i>"
)
netuno.com['color'] =
load: (fieldId) ->
control = $("\##{ fieldId }").colorpicker()
return control
netuno.com['image'] =
load: (id)->
upload = $("\##{ id }")
if ($("\##{ id }-value").val().length > 0)
value = $("\##{ id }-value").val()
else
$("\##{ id }-btView").hide()
upload.on("change", ()->
input = $(this)
numFiles = if input.get(0).files then input.get(0).files.length else 1
label = input.val().replace(/\\/g, '/').replace(/.*\//, '')
input.trigger('fileselect', [numFiles, label])
)
upload.on('fileselect', (event, numFiles, label) ->
$("\##{ id }-null").val('false')
input = $(this).parents('.input-group').find(':text')
log = if numFiles > 1 then "#{numFiles } files selected" else label
if (input.length > 0)
input.val(log)
)
view: (id, url)->
window.open(url, "_blank")
clear: (id)->
$("\##{ id }").val('').parents('.input-group').find(':text').val('')
$("\##{ id }-fileFeedback").html('')
$("\##{ id }-null").val('true')
$("\##{ id }-preview").hide()
$("\##{ id }-btView").hide()
netuno.com['file'] =
load: (id)->
upload = $("\##{ id }")
if ($("\##{ id }-value").val().length == 0)
$("\##{ id }-btView").hide()
upload.on("change", ()->
input = $(this)
numFiles = if input.get(0).files then input.get(0).files.length else 1
label = input.val().replace(/\\/g, '/').replace(/.*\//, '')
input.trigger('fileselect', [numFiles, label])
)
upload.on('fileselect', (event, numFiles, label) ->
$("\##{ id }-null").val('false')
input = $(this).parents('.input-group').find(':text')
log = if numFiles > 1 then "#{numFiles } files selected" else label
if (input.length > 0)
input.val(log)
)
view: (id)->
value = $("\##{ id }-value")
window.open(value.attr('file-url'))
clear: (id)->
$("\##{ id }").val('').parents('.input-group').find(':text').val('')
$("\##{ id }-fileFeedback").html('')
$("\##{ id }-null").val('true')
$("\##{ id }-btView").hide()
restore: (id)->
$(document).ready ()->
netuno.pageLoaded()
netuno.addContentLoad (container) ->
netuno.com['select'].loadInContainer(container)
netuno.addContentLoad (container) ->
netuno.com['checkbox'].loadInContainer(container)
netuno.keepAlive()
$(document).on 'show.bs.modal', (event)->
target = $(event.target)
parents = target.parents('.modal')
if (parents.length > 0)
target.detach().appendTo('body').attr('netuno-parent-modal-id', $(parents[0]).attr('id'))
$(parents[0]).modal('hide')
$(document).on 'hidden.bs.modal', (event)->
target = $(event.target)
if (target.attr('netuno-parent-modal-id'))
target.detach().appendTo("\##{ target.attr('netuno-parent-modal-id') }")
$("\##{ target.attr('netuno-parent-modal-id') }").modal('show')
#$(event.relatedTarget).parents('.modal')
#$(event.relatedTarget).parents('.modal').modal('hide')
#$(document).on 'shown.bs.modal', (event) ->
# if ($('body').hasClass('modal-open') == false)
# $('body').addClass('modal-open')
|
[
{
"context": "player\"\n\n characters = [\n Player\n name: \"STEVE\"\n url: \"http://2.pixiecdn.com/sprites/131822",
"end": 447,
"score": 0.9992182850837708,
"start": 442,
"tag": "NAME",
"value": "STEVE"
},
{
"context": " conversation: [{\n text: \"\"\"\n STEVE: Remember that project that I was really\n ",
"end": 588,
"score": 0.5569043159484863,
"start": 583,
"tag": "NAME",
"value": "STEVE"
},
{
"context": "cks.\n \"\"\"\n }]\n Player\n name: \"MARCO\"\n url: \"http://1.pixiecdn.com/sprites/131825",
"end": 997,
"score": 0.999068021774292,
"start": 992,
"tag": "NAME",
"value": "MARCO"
},
{
"context": " conversation: [{\n text: \"\"\"\n MARCO: So... is this like the break room or are we\n ",
"end": 1137,
"score": 0.7973702549934387,
"start": 1132,
"tag": "NAME",
"value": "MARCO"
},
{
"context": " \"\"\"\n }, {\n text: \"\"\"\n STEVE: About that... have you been having any\n ",
"end": 1332,
"score": 0.5467438101768494,
"start": 1330,
"tag": "NAME",
"value": "VE"
},
{
"context": " \"\"\"\n }, {\n text: \"\"\"\n MARCO: I don't know man, but it's totally not a\n ",
"end": 1541,
"score": 0.9475276470184326,
"start": 1536,
"tag": "NAME",
"value": "MARCO"
},
{
"context": "vent: \"knightJr\"\n }]\n Player\n name: \"BROGRE\"\n url: \"http://2.pixiecdn.com/sprites/131794",
"end": 1761,
"score": 0.9995987415313721,
"start": 1755,
"tag": "NAME",
"value": "BROGRE"
},
{
"context": " conversation: [{\n text: \"\"\"\n BROGRE: Heyy duder... We were having a party with\n ",
"end": 1904,
"score": 0.9929612874984741,
"start": 1898,
"tag": "NAME",
"value": "BROGRE"
},
{
"context": "event: \"brogre0\"\n }]\n Player\n name: \"Knight Jr\"\n url: \"http://0.pixiecdn.com/sprites/131792",
"end": 2136,
"score": 0.9989477396011353,
"start": 2127,
"tag": "NAME",
"value": "Knight Jr"
},
{
"context": "\"\n x: -1\n y: -1\n Player\n name: \"Door\"\n x: 9\n y: 8\n url: \"http://1.pixie",
"end": 2250,
"score": 0.8536889553070068,
"start": 2246,
"tag": "NAME",
"value": "Door"
},
{
"context": " event: \"door\"\n }]\n Player\n name: \"Wiz\"\n url: \"http://3.pixiecdn.com/sprites/131843",
"end": 2618,
"score": 0.9990954995155334,
"start": 2615,
"tag": "NAME",
"value": "Wiz"
},
{
"context": " event: \"fire\"\n }]\n Player\n name: \"Barb\"\n url: \"http://0.pixiecdn.com/sprites/131852",
"end": 3274,
"score": 0.9987989664077759,
"start": 3270,
"tag": "NAME",
"value": "Barb"
},
{
"context": " event: \"restart\"\n }]\n Item\n name: \"Knight Jr Carcass\"\n x: -1\n y: 7\n url: \"http://3.pixi",
"end": 6421,
"score": 0.8750947713851929,
"start": 6404,
"tag": "NAME",
"value": "Knight Jr Carcass"
},
{
"context": " event: \"carco\"\n }]\n Item\n name: \"Victory\"\n x: 9\n y: 14\n trigger: true\n ",
"end": 6659,
"score": 0.9992498159408569,
"start": 6652,
"tag": "NAME",
"value": "Victory"
}
] | map.coffee | STRd6/ld33 | 2 | module.exports = ->
tileWidth = 32
tileHeight = 32
tvURL = "http://1.pixiecdn.com/sprites/131781/original."
t = 0
tiles = [
"http://0.pixiecdn.com/sprites/131780/original."
"http://3.pixiecdn.com/sprites/131775/original."
"http://0.pixiecdn.com/sprites/131788/original."
].map (name) ->
img = new Image
img.src = name
return img
Player = require "./player"
characters = [
Player
name: "STEVE"
url: "http://2.pixiecdn.com/sprites/131822/original."
x: 10
y: 5
conversation: [{
text: """
STEVE: Remember that project that I was really
excited to be working on?
"""
}, {
text: "YOU:"
options: [
"Yeah (um) totally!"
"Uhhh... not really..."
]
}, {
text: """
STEVE: Yeah... well BOSS called up and told me to
cancel it...
...
Sucks.
"""
}]
Player
name: "MARCO"
url: "http://1.pixiecdn.com/sprites/131825/original."
x: 9
y: 3
conversation: [{
text: """
MARCO: So... is this like the break room or are we
supposed to be working here... The CRAIGSLIST ad
wasn't really specific.
"""
}, {
text: """
STEVE: About that... have you been having any
trouble with your paychecks? Because I haven't
been able to cash mine the past few weeks...
"""
}, {
text: """
MARCO: I don't know man, but it's totally not a
scam. My mom is really good at identifying
scams and she said this looks legit.
"""
event: "knightJr"
}]
Player
name: "BROGRE"
url: "http://2.pixiecdn.com/sprites/131794/original."
x: -1
y: -1
conversation: [{
text: """
BROGRE: Heyy duder... We were having a party with
some BudLight Lime® Lime-A-Ritas and were
wondering if we could borrow some rock salt...
"""
event: "brogre0"
}]
Player
name: "Knight Jr"
url: "http://0.pixiecdn.com/sprites/131792/original."
x: -1
y: -1
Player
name: "Door"
x: 9
y: 8
url: "http://1.pixiecdn.com/sprites/131837/original."
conversation: [{
text: """
STEVE: BOSS says we shouldn't go out there.
"""
options: [
"YOU: Damnit STEVE, shut the fuck up."
"YOU: Thanks for the Pro-Tip™"
]
event: "door"
}]
Player
name: "Wiz"
url: "http://3.pixiecdn.com/sprites/131843/original."
x: -1
y: 8
conversation: [{
text: """
THE WIZ: Get ready to BURN!
"""
}, {
text: """
THE WIZ: Just a little longer...
"""
}, {
text: """
...
"""
}, {
text: """
THE WIZ: Hold on... miscast...
"""
}, {
text: """
Fire erupts from the wizard's hands!
A gigantic fireball fills the room!
The TV is destroyed!
... and also STEVE died.
"""
event: "fire"
}]
Player
name: "Barb"
url: "http://0.pixiecdn.com/sprites/131852/original."
x: -1
y: 8
conversation: [{
text: "AXE MANIAC: I smell BBQ!"
}, {
text: """
AXE MANIAC: Looks like most of it is pretty
over done...
Ah, this one's still fresh!
"""
event: "butcher"
}, {
text: """
AXE MANIAC butchers MARCO.
AXE MANIAC picks up 14kg of GOBLIN MEAT
AXE MANIAC eats 2kg of GOBLIN MEAT
AXE MANIAC is no longer STARVING
"""
event: "satiated"
}]
]
map = """
00000000000000000000
00000011111100000000
00000012222100000000
00000012222100000000
00000012222100000000
00000012222100000000
00000012222100000000
00000012222100000000
00000011111100000000
00000000000000000000
00000000000000000000
00000000000000000000
00000000000000000000
00000000000000000000
00000000000000000000
""".split("\n")
.map (row) ->
row.split("")
Item = (I) ->
if typeof I.url is "string"
img = new Image
img.src = I.url
else if Array.isArray(I.url)
imgs = I.url.map (url) ->
i = new Image
i.src = url
i
I: I
draw: (canvas) ->
if img
canvas.drawImage(img, I.x * tileWidth, I.y * tileHeight)
else if imgs
canvas.drawImage(imgs.wrap(Math.floor(t/0.25)), I.x * tileWidth, I.y * tileHeight)
conversation: ->
if I.conversation
I.conversation.map (c) ->
extend {font: I.font}, c
interact: ->
if conversation = this.conversation()
showConversation conversation
else if message = I.messages?.rand()
showDialog
text: message
font: I.font
items = [
Item
name: "TV"
x: 8
y: 3
url: tvURL
conversation: [{
text: """
There's a bunch of old DVDs here...
What do you want to watch?
"""
options: [
"Die Hard"
"Nothing"
]
event: "tv1"
}]
Item
name: "Table"
x: 7
y: 4
url: "http://2.pixiecdn.com/sprites/131826/original."
Item
name: "Crate"
x: 9
y: 2
url: "http://0.pixiecdn.com/sprites/131836/original."
conversation: [{
text: """
STEVE: BOSS says we shouldn't mess into that...
"""
options: [
"Whatever"
"Actually, you're probably right..."
]
event: "crate"
}]
Item
name: "Trap"
x: 9
y: 11
trigger: true
conversation: [{
text: """
A trapdoor in the ceiling opens and a rock
falls on your head!
"""
}, {
text: """
You die.
"""
}, {
text: """
What do you want on your tombstone?
"""
}, {
text: """
HAH! JK, goblins don't get tombstones.
"""
}, {
text: """
Better luck next time!
"""
event: "restart"
}]
Item
name: "Knight Jr Carcass"
x: -1
y: 7
url: "http://3.pixiecdn.com/sprites/131839/original."
conversation: [{
text: """
This kid looks like he's 12.
"""
event: "carco"
}]
Item
name: "Victory"
x: 9
y: 14
trigger: true
conversation: [{
text: """
As you leave that death filled room, you
pick up a sword and become...
An Adventurer!
"""
event: ->
setTimeout ->
alert 'O_O Congratulations! G_G'
, 1000
}]
]
passable: ({x, y}) ->
(map[y][x] is "2") and !this.characterAt({x, y})
characterAt: ({x, y}) ->
characters.filter (character) ->
character.I.x is x and character.I.y is y
.first()
characters: characters
items: items
map: map
draw: (canvas) ->
canvas.fill "rgb(32, 16, 16)"
# Draw Tiles
map.forEach (row, y) ->
row.forEach (i, x) ->
canvas.drawImage tiles[i], x * tileWidth, y * tileHeight
# Draw Stuff
items.forEach (item) ->
item.draw(canvas)
characters.forEach (character) ->
character.draw(canvas)
updateItem: (name, changes) ->
items.forEach (item) ->
if item.I.name is name
extend item.I, changes
replaceItem: (index, item) ->
oldItem = items[index]
item.x ?= oldItem.I.x
item.y ?= oldItem.I.y
items[index] = Item item
addItem: (item) ->
items.push Item item
triggerItems: ({x, y}) ->
items.forEach (item) ->
if item.I.x is x and item.I.y is y
if item.I.trigger
item.interact()
update: (dt) ->
t += dt
interact: ({x, y}) ->
interacted = false
items.forEach (item) ->
if item.I.x is x and item.I.y is y
item.interact()
interacted = true
return if interacted
characters.forEach (character) ->
if (character.I.x - x).abs() + (character.I.y - y).abs() <= 1
character.interact()
interacted = true
| 23183 | module.exports = ->
tileWidth = 32
tileHeight = 32
tvURL = "http://1.pixiecdn.com/sprites/131781/original."
t = 0
tiles = [
"http://0.pixiecdn.com/sprites/131780/original."
"http://3.pixiecdn.com/sprites/131775/original."
"http://0.pixiecdn.com/sprites/131788/original."
].map (name) ->
img = new Image
img.src = name
return img
Player = require "./player"
characters = [
Player
name: "<NAME>"
url: "http://2.pixiecdn.com/sprites/131822/original."
x: 10
y: 5
conversation: [{
text: """
<NAME>: Remember that project that I was really
excited to be working on?
"""
}, {
text: "YOU:"
options: [
"Yeah (um) totally!"
"Uhhh... not really..."
]
}, {
text: """
STEVE: Yeah... well BOSS called up and told me to
cancel it...
...
Sucks.
"""
}]
Player
name: "<NAME>"
url: "http://1.pixiecdn.com/sprites/131825/original."
x: 9
y: 3
conversation: [{
text: """
<NAME>: So... is this like the break room or are we
supposed to be working here... The CRAIGSLIST ad
wasn't really specific.
"""
}, {
text: """
STE<NAME>: About that... have you been having any
trouble with your paychecks? Because I haven't
been able to cash mine the past few weeks...
"""
}, {
text: """
<NAME>: I don't know man, but it's totally not a
scam. My mom is really good at identifying
scams and she said this looks legit.
"""
event: "knightJr"
}]
Player
name: "<NAME>"
url: "http://2.pixiecdn.com/sprites/131794/original."
x: -1
y: -1
conversation: [{
text: """
<NAME>: Heyy duder... We were having a party with
some BudLight Lime® Lime-A-Ritas and were
wondering if we could borrow some rock salt...
"""
event: "brogre0"
}]
Player
name: "<NAME>"
url: "http://0.pixiecdn.com/sprites/131792/original."
x: -1
y: -1
Player
name: "<NAME>"
x: 9
y: 8
url: "http://1.pixiecdn.com/sprites/131837/original."
conversation: [{
text: """
STEVE: BOSS says we shouldn't go out there.
"""
options: [
"YOU: Damnit STEVE, shut the fuck up."
"YOU: Thanks for the Pro-Tip™"
]
event: "door"
}]
Player
name: "<NAME>"
url: "http://3.pixiecdn.com/sprites/131843/original."
x: -1
y: 8
conversation: [{
text: """
THE WIZ: Get ready to BURN!
"""
}, {
text: """
THE WIZ: Just a little longer...
"""
}, {
text: """
...
"""
}, {
text: """
THE WIZ: Hold on... miscast...
"""
}, {
text: """
Fire erupts from the wizard's hands!
A gigantic fireball fills the room!
The TV is destroyed!
... and also STEVE died.
"""
event: "fire"
}]
Player
name: "<NAME>"
url: "http://0.pixiecdn.com/sprites/131852/original."
x: -1
y: 8
conversation: [{
text: "AXE MANIAC: I smell BBQ!"
}, {
text: """
AXE MANIAC: Looks like most of it is pretty
over done...
Ah, this one's still fresh!
"""
event: "butcher"
}, {
text: """
AXE MANIAC butchers MARCO.
AXE MANIAC picks up 14kg of GOBLIN MEAT
AXE MANIAC eats 2kg of GOBLIN MEAT
AXE MANIAC is no longer STARVING
"""
event: "satiated"
}]
]
map = """
00000000000000000000
00000011111100000000
00000012222100000000
00000012222100000000
00000012222100000000
00000012222100000000
00000012222100000000
00000012222100000000
00000011111100000000
00000000000000000000
00000000000000000000
00000000000000000000
00000000000000000000
00000000000000000000
00000000000000000000
""".split("\n")
.map (row) ->
row.split("")
Item = (I) ->
if typeof I.url is "string"
img = new Image
img.src = I.url
else if Array.isArray(I.url)
imgs = I.url.map (url) ->
i = new Image
i.src = url
i
I: I
draw: (canvas) ->
if img
canvas.drawImage(img, I.x * tileWidth, I.y * tileHeight)
else if imgs
canvas.drawImage(imgs.wrap(Math.floor(t/0.25)), I.x * tileWidth, I.y * tileHeight)
conversation: ->
if I.conversation
I.conversation.map (c) ->
extend {font: I.font}, c
interact: ->
if conversation = this.conversation()
showConversation conversation
else if message = I.messages?.rand()
showDialog
text: message
font: I.font
items = [
Item
name: "TV"
x: 8
y: 3
url: tvURL
conversation: [{
text: """
There's a bunch of old DVDs here...
What do you want to watch?
"""
options: [
"Die Hard"
"Nothing"
]
event: "tv1"
}]
Item
name: "Table"
x: 7
y: 4
url: "http://2.pixiecdn.com/sprites/131826/original."
Item
name: "Crate"
x: 9
y: 2
url: "http://0.pixiecdn.com/sprites/131836/original."
conversation: [{
text: """
STEVE: BOSS says we shouldn't mess into that...
"""
options: [
"Whatever"
"Actually, you're probably right..."
]
event: "crate"
}]
Item
name: "Trap"
x: 9
y: 11
trigger: true
conversation: [{
text: """
A trapdoor in the ceiling opens and a rock
falls on your head!
"""
}, {
text: """
You die.
"""
}, {
text: """
What do you want on your tombstone?
"""
}, {
text: """
HAH! JK, goblins don't get tombstones.
"""
}, {
text: """
Better luck next time!
"""
event: "restart"
}]
Item
name: "<NAME>"
x: -1
y: 7
url: "http://3.pixiecdn.com/sprites/131839/original."
conversation: [{
text: """
This kid looks like he's 12.
"""
event: "carco"
}]
Item
name: "<NAME>"
x: 9
y: 14
trigger: true
conversation: [{
text: """
As you leave that death filled room, you
pick up a sword and become...
An Adventurer!
"""
event: ->
setTimeout ->
alert 'O_O Congratulations! G_G'
, 1000
}]
]
passable: ({x, y}) ->
(map[y][x] is "2") and !this.characterAt({x, y})
characterAt: ({x, y}) ->
characters.filter (character) ->
character.I.x is x and character.I.y is y
.first()
characters: characters
items: items
map: map
draw: (canvas) ->
canvas.fill "rgb(32, 16, 16)"
# Draw Tiles
map.forEach (row, y) ->
row.forEach (i, x) ->
canvas.drawImage tiles[i], x * tileWidth, y * tileHeight
# Draw Stuff
items.forEach (item) ->
item.draw(canvas)
characters.forEach (character) ->
character.draw(canvas)
updateItem: (name, changes) ->
items.forEach (item) ->
if item.I.name is name
extend item.I, changes
replaceItem: (index, item) ->
oldItem = items[index]
item.x ?= oldItem.I.x
item.y ?= oldItem.I.y
items[index] = Item item
addItem: (item) ->
items.push Item item
triggerItems: ({x, y}) ->
items.forEach (item) ->
if item.I.x is x and item.I.y is y
if item.I.trigger
item.interact()
update: (dt) ->
t += dt
interact: ({x, y}) ->
interacted = false
items.forEach (item) ->
if item.I.x is x and item.I.y is y
item.interact()
interacted = true
return if interacted
characters.forEach (character) ->
if (character.I.x - x).abs() + (character.I.y - y).abs() <= 1
character.interact()
interacted = true
| true | module.exports = ->
tileWidth = 32
tileHeight = 32
tvURL = "http://1.pixiecdn.com/sprites/131781/original."
t = 0
tiles = [
"http://0.pixiecdn.com/sprites/131780/original."
"http://3.pixiecdn.com/sprites/131775/original."
"http://0.pixiecdn.com/sprites/131788/original."
].map (name) ->
img = new Image
img.src = name
return img
Player = require "./player"
characters = [
Player
name: "PI:NAME:<NAME>END_PI"
url: "http://2.pixiecdn.com/sprites/131822/original."
x: 10
y: 5
conversation: [{
text: """
PI:NAME:<NAME>END_PI: Remember that project that I was really
excited to be working on?
"""
}, {
text: "YOU:"
options: [
"Yeah (um) totally!"
"Uhhh... not really..."
]
}, {
text: """
STEVE: Yeah... well BOSS called up and told me to
cancel it...
...
Sucks.
"""
}]
Player
name: "PI:NAME:<NAME>END_PI"
url: "http://1.pixiecdn.com/sprites/131825/original."
x: 9
y: 3
conversation: [{
text: """
PI:NAME:<NAME>END_PI: So... is this like the break room or are we
supposed to be working here... The CRAIGSLIST ad
wasn't really specific.
"""
}, {
text: """
STEPI:NAME:<NAME>END_PI: About that... have you been having any
trouble with your paychecks? Because I haven't
been able to cash mine the past few weeks...
"""
}, {
text: """
PI:NAME:<NAME>END_PI: I don't know man, but it's totally not a
scam. My mom is really good at identifying
scams and she said this looks legit.
"""
event: "knightJr"
}]
Player
name: "PI:NAME:<NAME>END_PI"
url: "http://2.pixiecdn.com/sprites/131794/original."
x: -1
y: -1
conversation: [{
text: """
PI:NAME:<NAME>END_PI: Heyy duder... We were having a party with
some BudLight Lime® Lime-A-Ritas and were
wondering if we could borrow some rock salt...
"""
event: "brogre0"
}]
Player
name: "PI:NAME:<NAME>END_PI"
url: "http://0.pixiecdn.com/sprites/131792/original."
x: -1
y: -1
Player
name: "PI:NAME:<NAME>END_PI"
x: 9
y: 8
url: "http://1.pixiecdn.com/sprites/131837/original."
conversation: [{
text: """
STEVE: BOSS says we shouldn't go out there.
"""
options: [
"YOU: Damnit STEVE, shut the fuck up."
"YOU: Thanks for the Pro-Tip™"
]
event: "door"
}]
Player
name: "PI:NAME:<NAME>END_PI"
url: "http://3.pixiecdn.com/sprites/131843/original."
x: -1
y: 8
conversation: [{
text: """
THE WIZ: Get ready to BURN!
"""
}, {
text: """
THE WIZ: Just a little longer...
"""
}, {
text: """
...
"""
}, {
text: """
THE WIZ: Hold on... miscast...
"""
}, {
text: """
Fire erupts from the wizard's hands!
A gigantic fireball fills the room!
The TV is destroyed!
... and also STEVE died.
"""
event: "fire"
}]
Player
name: "PI:NAME:<NAME>END_PI"
url: "http://0.pixiecdn.com/sprites/131852/original."
x: -1
y: 8
conversation: [{
text: "AXE MANIAC: I smell BBQ!"
}, {
text: """
AXE MANIAC: Looks like most of it is pretty
over done...
Ah, this one's still fresh!
"""
event: "butcher"
}, {
text: """
AXE MANIAC butchers MARCO.
AXE MANIAC picks up 14kg of GOBLIN MEAT
AXE MANIAC eats 2kg of GOBLIN MEAT
AXE MANIAC is no longer STARVING
"""
event: "satiated"
}]
]
map = """
00000000000000000000
00000011111100000000
00000012222100000000
00000012222100000000
00000012222100000000
00000012222100000000
00000012222100000000
00000012222100000000
00000011111100000000
00000000000000000000
00000000000000000000
00000000000000000000
00000000000000000000
00000000000000000000
00000000000000000000
""".split("\n")
.map (row) ->
row.split("")
Item = (I) ->
if typeof I.url is "string"
img = new Image
img.src = I.url
else if Array.isArray(I.url)
imgs = I.url.map (url) ->
i = new Image
i.src = url
i
I: I
draw: (canvas) ->
if img
canvas.drawImage(img, I.x * tileWidth, I.y * tileHeight)
else if imgs
canvas.drawImage(imgs.wrap(Math.floor(t/0.25)), I.x * tileWidth, I.y * tileHeight)
conversation: ->
if I.conversation
I.conversation.map (c) ->
extend {font: I.font}, c
interact: ->
if conversation = this.conversation()
showConversation conversation
else if message = I.messages?.rand()
showDialog
text: message
font: I.font
items = [
Item
name: "TV"
x: 8
y: 3
url: tvURL
conversation: [{
text: """
There's a bunch of old DVDs here...
What do you want to watch?
"""
options: [
"Die Hard"
"Nothing"
]
event: "tv1"
}]
Item
name: "Table"
x: 7
y: 4
url: "http://2.pixiecdn.com/sprites/131826/original."
Item
name: "Crate"
x: 9
y: 2
url: "http://0.pixiecdn.com/sprites/131836/original."
conversation: [{
text: """
STEVE: BOSS says we shouldn't mess into that...
"""
options: [
"Whatever"
"Actually, you're probably right..."
]
event: "crate"
}]
Item
name: "Trap"
x: 9
y: 11
trigger: true
conversation: [{
text: """
A trapdoor in the ceiling opens and a rock
falls on your head!
"""
}, {
text: """
You die.
"""
}, {
text: """
What do you want on your tombstone?
"""
}, {
text: """
HAH! JK, goblins don't get tombstones.
"""
}, {
text: """
Better luck next time!
"""
event: "restart"
}]
Item
name: "PI:NAME:<NAME>END_PI"
x: -1
y: 7
url: "http://3.pixiecdn.com/sprites/131839/original."
conversation: [{
text: """
This kid looks like he's 12.
"""
event: "carco"
}]
Item
name: "PI:NAME:<NAME>END_PI"
x: 9
y: 14
trigger: true
conversation: [{
text: """
As you leave that death filled room, you
pick up a sword and become...
An Adventurer!
"""
event: ->
setTimeout ->
alert 'O_O Congratulations! G_G'
, 1000
}]
]
passable: ({x, y}) ->
(map[y][x] is "2") and !this.characterAt({x, y})
characterAt: ({x, y}) ->
characters.filter (character) ->
character.I.x is x and character.I.y is y
.first()
characters: characters
items: items
map: map
draw: (canvas) ->
canvas.fill "rgb(32, 16, 16)"
# Draw Tiles
map.forEach (row, y) ->
row.forEach (i, x) ->
canvas.drawImage tiles[i], x * tileWidth, y * tileHeight
# Draw Stuff
items.forEach (item) ->
item.draw(canvas)
characters.forEach (character) ->
character.draw(canvas)
updateItem: (name, changes) ->
items.forEach (item) ->
if item.I.name is name
extend item.I, changes
replaceItem: (index, item) ->
oldItem = items[index]
item.x ?= oldItem.I.x
item.y ?= oldItem.I.y
items[index] = Item item
addItem: (item) ->
items.push Item item
triggerItems: ({x, y}) ->
items.forEach (item) ->
if item.I.x is x and item.I.y is y
if item.I.trigger
item.interact()
update: (dt) ->
t += dt
interact: ({x, y}) ->
interacted = false
items.forEach (item) ->
if item.I.x is x and item.I.y is y
item.interact()
interacted = true
return if interacted
characters.forEach (character) ->
if (character.I.x - x).abs() + (character.I.y - y).abs() <= 1
character.interact()
interacted = true
|
[
{
"context": "an the values provided in configuration.\n# @author Burak Yigit Kaya aka BYK\n###\n\n'use strict'\n\n#---------------------",
"end": 152,
"score": 0.9998920559883118,
"start": 136,
"tag": "NAME",
"value": "Burak Yigit Kaya"
},
{
"context": "d in configuration.\n# @author Burak Yigit Kaya aka BYK\n###\n\n'use strict'\n\n#-----------------------------",
"end": 160,
"score": 0.9768561124801636,
"start": 157,
"tag": "USERNAME",
"value": "BYK"
}
] | src/rules/id-length.coffee | danielbayley/eslint-plugin-coffee | 21 | ###*
# @fileoverview Rule that warns when identifier names are shorter or longer
# than the values provided in configuration.
# @author Burak Yigit Kaya aka BYK
###
'use strict'
#------------------------------------------------------------------------------
# Rule Definition
#------------------------------------------------------------------------------
module.exports =
meta:
docs:
description: 'enforce minimum and maximum identifier lengths'
category: 'Stylistic Issues'
recommended: no
url: 'https://eslint.org/docs/rules/id-length'
schema: [
type: 'object'
properties:
min:
type: 'number'
max:
type: 'number'
exceptions:
type: 'array'
uniqueItems: yes
items:
type: 'string'
properties:
enum: ['always', 'never']
additionalProperties: no
]
create: (context) ->
options = context.options[0] or {}
minLength = options.min ? 2
maxLength = options.max ? Infinity
properties = options.properties isnt 'never'
exceptions = (if options.exceptions then options.exceptions else []).reduce(
(obj, item) ->
obj[item] = yes
obj
,
{}
)
isSupportedExpression = (node, parent) ->
prevNode = node
currentNode = parent
while currentNode?
switch currentNode.type
when 'MemberExpression'
return no unless prevNode is currentNode.property
return no unless properties
return no if currentNode.computed
assigningToMemberExpression = yes
when 'AssignmentPattern'
return no unless prevNode is currentNode.left
when 'ObjectPattern', 'ArrayPattern'
;
when 'ObjectExpression'
return currentNode.parent.type is 'AssignmentExpression'
# when 'VariableDeclarator'
# (parent, node) -> parent.id is node
when 'AssignmentExpression'
return no unless prevNode is currentNode.left
return yes if assigningToMemberExpression
return yes if node.declaration
return no
when 'Property'
if currentNode.parent.type is 'ObjectExpression'
return no unless properties
return no unless (
prevNode is
currentNode[
if currentNode.parent.type is 'ObjectPattern'
'value'
else
'key'
]
)
when 'ClassDeclaration'
return prevNode is currentNode.id
when 'FunctionDeclaration', 'FunctionExpression', 'ArrowFunctionExpression'
return prevNode is currentNode.id or prevNode in currentNode.params
when 'MethodDefinition'
return prevNode is currentNode.key and not currentNode.computed
when 'CatchClause'
return prevNode is currentNode.param
when 'ImportDefaultSpecifier', 'RestElement'
return yes
else
return yes if node.declaration
return no
prevNode = currentNode
currentNode = currentNode.parent
Identifier: (node) ->
{name, parent} = node
isShort = name.length < minLength
isLong = name.length > maxLength
return if not (isShort or isLong) or exceptions[name] # Nothing to report
isValidExpression = isSupportedExpression node, parent
context.report {
node
message:
if isShort
"Identifier name '{{name}}' is too short (< {{min}})."
else
"Identifier name '{{name}}' is too long (> {{max}})."
data: {name, min: minLength, max: maxLength}
} if isValidExpression
| 67685 | ###*
# @fileoverview Rule that warns when identifier names are shorter or longer
# than the values provided in configuration.
# @author <NAME> aka BYK
###
'use strict'
#------------------------------------------------------------------------------
# Rule Definition
#------------------------------------------------------------------------------
module.exports =
meta:
docs:
description: 'enforce minimum and maximum identifier lengths'
category: 'Stylistic Issues'
recommended: no
url: 'https://eslint.org/docs/rules/id-length'
schema: [
type: 'object'
properties:
min:
type: 'number'
max:
type: 'number'
exceptions:
type: 'array'
uniqueItems: yes
items:
type: 'string'
properties:
enum: ['always', 'never']
additionalProperties: no
]
create: (context) ->
options = context.options[0] or {}
minLength = options.min ? 2
maxLength = options.max ? Infinity
properties = options.properties isnt 'never'
exceptions = (if options.exceptions then options.exceptions else []).reduce(
(obj, item) ->
obj[item] = yes
obj
,
{}
)
isSupportedExpression = (node, parent) ->
prevNode = node
currentNode = parent
while currentNode?
switch currentNode.type
when 'MemberExpression'
return no unless prevNode is currentNode.property
return no unless properties
return no if currentNode.computed
assigningToMemberExpression = yes
when 'AssignmentPattern'
return no unless prevNode is currentNode.left
when 'ObjectPattern', 'ArrayPattern'
;
when 'ObjectExpression'
return currentNode.parent.type is 'AssignmentExpression'
# when 'VariableDeclarator'
# (parent, node) -> parent.id is node
when 'AssignmentExpression'
return no unless prevNode is currentNode.left
return yes if assigningToMemberExpression
return yes if node.declaration
return no
when 'Property'
if currentNode.parent.type is 'ObjectExpression'
return no unless properties
return no unless (
prevNode is
currentNode[
if currentNode.parent.type is 'ObjectPattern'
'value'
else
'key'
]
)
when 'ClassDeclaration'
return prevNode is currentNode.id
when 'FunctionDeclaration', 'FunctionExpression', 'ArrowFunctionExpression'
return prevNode is currentNode.id or prevNode in currentNode.params
when 'MethodDefinition'
return prevNode is currentNode.key and not currentNode.computed
when 'CatchClause'
return prevNode is currentNode.param
when 'ImportDefaultSpecifier', 'RestElement'
return yes
else
return yes if node.declaration
return no
prevNode = currentNode
currentNode = currentNode.parent
Identifier: (node) ->
{name, parent} = node
isShort = name.length < minLength
isLong = name.length > maxLength
return if not (isShort or isLong) or exceptions[name] # Nothing to report
isValidExpression = isSupportedExpression node, parent
context.report {
node
message:
if isShort
"Identifier name '{{name}}' is too short (< {{min}})."
else
"Identifier name '{{name}}' is too long (> {{max}})."
data: {name, min: minLength, max: maxLength}
} if isValidExpression
| true | ###*
# @fileoverview Rule that warns when identifier names are shorter or longer
# than the values provided in configuration.
# @author PI:NAME:<NAME>END_PI aka BYK
###
'use strict'
#------------------------------------------------------------------------------
# Rule Definition
#------------------------------------------------------------------------------
module.exports =
meta:
docs:
description: 'enforce minimum and maximum identifier lengths'
category: 'Stylistic Issues'
recommended: no
url: 'https://eslint.org/docs/rules/id-length'
schema: [
type: 'object'
properties:
min:
type: 'number'
max:
type: 'number'
exceptions:
type: 'array'
uniqueItems: yes
items:
type: 'string'
properties:
enum: ['always', 'never']
additionalProperties: no
]
create: (context) ->
options = context.options[0] or {}
minLength = options.min ? 2
maxLength = options.max ? Infinity
properties = options.properties isnt 'never'
exceptions = (if options.exceptions then options.exceptions else []).reduce(
(obj, item) ->
obj[item] = yes
obj
,
{}
)
isSupportedExpression = (node, parent) ->
prevNode = node
currentNode = parent
while currentNode?
switch currentNode.type
when 'MemberExpression'
return no unless prevNode is currentNode.property
return no unless properties
return no if currentNode.computed
assigningToMemberExpression = yes
when 'AssignmentPattern'
return no unless prevNode is currentNode.left
when 'ObjectPattern', 'ArrayPattern'
;
when 'ObjectExpression'
return currentNode.parent.type is 'AssignmentExpression'
# when 'VariableDeclarator'
# (parent, node) -> parent.id is node
when 'AssignmentExpression'
return no unless prevNode is currentNode.left
return yes if assigningToMemberExpression
return yes if node.declaration
return no
when 'Property'
if currentNode.parent.type is 'ObjectExpression'
return no unless properties
return no unless (
prevNode is
currentNode[
if currentNode.parent.type is 'ObjectPattern'
'value'
else
'key'
]
)
when 'ClassDeclaration'
return prevNode is currentNode.id
when 'FunctionDeclaration', 'FunctionExpression', 'ArrowFunctionExpression'
return prevNode is currentNode.id or prevNode in currentNode.params
when 'MethodDefinition'
return prevNode is currentNode.key and not currentNode.computed
when 'CatchClause'
return prevNode is currentNode.param
when 'ImportDefaultSpecifier', 'RestElement'
return yes
else
return yes if node.declaration
return no
prevNode = currentNode
currentNode = currentNode.parent
Identifier: (node) ->
{name, parent} = node
isShort = name.length < minLength
isLong = name.length > maxLength
return if not (isShort or isLong) or exceptions[name] # Nothing to report
isValidExpression = isSupportedExpression node, parent
context.report {
node
message:
if isShort
"Identifier name '{{name}}' is too short (< {{min}})."
else
"Identifier name '{{name}}' is too long (> {{max}})."
data: {name, min: minLength, max: maxLength}
} if isValidExpression
|
[
{
"context": "er destructuring from arrays and objects\n# @author Alex LaFroscia\n###\n'use strict'\n\n#------------------------------",
"end": 90,
"score": 0.999838650226593,
"start": 76,
"tag": "NAME",
"value": "Alex LaFroscia"
}
] | src/rules/prefer-destructuring.coffee | danielbayley/eslint-plugin-coffee | 21 | ###*
# @fileoverview Prefer destructuring from arrays and objects
# @author Alex LaFroscia
###
'use strict'
#------------------------------------------------------------------------------
# Rule Definition
#------------------------------------------------------------------------------
module.exports =
meta:
docs:
description: 'require destructuring from arrays and/or objects'
category: 'ECMAScript 6'
recommended: no
url: 'https://eslint.org/docs/rules/prefer-destructuring'
schema: [
###
# old support {array: Boolean, object: Boolean}
# new support {VariableDeclarator: {}, AssignmentExpression: {}}
###
type: 'object'
properties:
array:
type: 'boolean'
object:
type: 'boolean'
additionalProperties: no
,
type: 'object'
properties:
enforceForRenamedProperties:
type: 'boolean'
additionalProperties: no
]
create: (context) ->
enabledTypes = context.options[0] ? array: yes, object: yes
enforceForRenamedProperties =
context.options[1]?.enforceForRenamedProperties
#--------------------------------------------------------------------------
# Helpers
#--------------------------------------------------------------------------
###*
# @param {string} nodeType "AssignmentExpression" or "VariableDeclarator"
# @param {string} destructuringType "array" or "object"
# @returns {boolean} `true` if the destructuring type should be checked for the given node
###
shouldCheck = (destructuringType) ->
enabledTypes[destructuringType]
###*
# Determines if the given node is accessing an array index
#
# This is used to differentiate array index access from object property
# access.
#
# @param {ASTNode} node the node to evaluate
# @returns {boolean} whether or not the node is an integer
###
isArrayIndexAccess = (node) -> Number.isInteger node.property.value
###*
# Report that the given node should use destructuring
#
# @param {ASTNode} reportNode the node to report
# @param {string} type the type of destructuring that should have been done
# @returns {void}
###
report = (reportNode, type) ->
context.report
node: reportNode, message: 'Use {{type}} destructuring.', data: {type}
###*
# Check that the `prefer-destructuring` rules are followed based on the
# given left- and right-hand side of the assignment.
#
# Pulled out into a separate method so that VariableDeclarators and
# AssignmentExpressions can share the same verification logic.
#
# @param {ASTNode} leftNode the left-hand side of the assignment
# @param {ASTNode} rightNode the right-hand side of the assignment
# @param {ASTNode} reportNode the node to report the error on
# @returns {void}
###
performCheck = (leftNode, rightNode, reportNode) ->
return if (
rightNode.type isnt 'MemberExpression' or
rightNode.object.type is 'Super' or
rightNode.optional
)
if isArrayIndexAccess rightNode
if shouldCheck 'array' then report reportNode, 'array'
return
return unless shouldCheck 'object'
if enforceForRenamedProperties
report reportNode, 'object'
return
{property} = rightNode
if (
(property.type is 'Literal' and leftNode.name is property.value) or
(property.type is 'Identifier' and
leftNode.name is property.name and
not rightNode.computed)
)
report reportNode, 'object'
###*
# Run the `prefer-destructuring` check on an AssignmentExpression
#
# @param {ASTNode} node the AssignmentExpression node
# @returns {void}
###
checkAssigmentExpression = (node) ->
if node.operator is '=' then performCheck node.left, node.right, node
#--------------------------------------------------------------------------
# Public
#--------------------------------------------------------------------------
AssignmentExpression: checkAssigmentExpression
| 210445 | ###*
# @fileoverview Prefer destructuring from arrays and objects
# @author <NAME>
###
'use strict'
#------------------------------------------------------------------------------
# Rule Definition
#------------------------------------------------------------------------------
module.exports =
meta:
docs:
description: 'require destructuring from arrays and/or objects'
category: 'ECMAScript 6'
recommended: no
url: 'https://eslint.org/docs/rules/prefer-destructuring'
schema: [
###
# old support {array: Boolean, object: Boolean}
# new support {VariableDeclarator: {}, AssignmentExpression: {}}
###
type: 'object'
properties:
array:
type: 'boolean'
object:
type: 'boolean'
additionalProperties: no
,
type: 'object'
properties:
enforceForRenamedProperties:
type: 'boolean'
additionalProperties: no
]
create: (context) ->
enabledTypes = context.options[0] ? array: yes, object: yes
enforceForRenamedProperties =
context.options[1]?.enforceForRenamedProperties
#--------------------------------------------------------------------------
# Helpers
#--------------------------------------------------------------------------
###*
# @param {string} nodeType "AssignmentExpression" or "VariableDeclarator"
# @param {string} destructuringType "array" or "object"
# @returns {boolean} `true` if the destructuring type should be checked for the given node
###
shouldCheck = (destructuringType) ->
enabledTypes[destructuringType]
###*
# Determines if the given node is accessing an array index
#
# This is used to differentiate array index access from object property
# access.
#
# @param {ASTNode} node the node to evaluate
# @returns {boolean} whether or not the node is an integer
###
isArrayIndexAccess = (node) -> Number.isInteger node.property.value
###*
# Report that the given node should use destructuring
#
# @param {ASTNode} reportNode the node to report
# @param {string} type the type of destructuring that should have been done
# @returns {void}
###
report = (reportNode, type) ->
context.report
node: reportNode, message: 'Use {{type}} destructuring.', data: {type}
###*
# Check that the `prefer-destructuring` rules are followed based on the
# given left- and right-hand side of the assignment.
#
# Pulled out into a separate method so that VariableDeclarators and
# AssignmentExpressions can share the same verification logic.
#
# @param {ASTNode} leftNode the left-hand side of the assignment
# @param {ASTNode} rightNode the right-hand side of the assignment
# @param {ASTNode} reportNode the node to report the error on
# @returns {void}
###
performCheck = (leftNode, rightNode, reportNode) ->
return if (
rightNode.type isnt 'MemberExpression' or
rightNode.object.type is 'Super' or
rightNode.optional
)
if isArrayIndexAccess rightNode
if shouldCheck 'array' then report reportNode, 'array'
return
return unless shouldCheck 'object'
if enforceForRenamedProperties
report reportNode, 'object'
return
{property} = rightNode
if (
(property.type is 'Literal' and leftNode.name is property.value) or
(property.type is 'Identifier' and
leftNode.name is property.name and
not rightNode.computed)
)
report reportNode, 'object'
###*
# Run the `prefer-destructuring` check on an AssignmentExpression
#
# @param {ASTNode} node the AssignmentExpression node
# @returns {void}
###
checkAssigmentExpression = (node) ->
if node.operator is '=' then performCheck node.left, node.right, node
#--------------------------------------------------------------------------
# Public
#--------------------------------------------------------------------------
AssignmentExpression: checkAssigmentExpression
| true | ###*
# @fileoverview Prefer destructuring from arrays and objects
# @author PI:NAME:<NAME>END_PI
###
'use strict'
#------------------------------------------------------------------------------
# Rule Definition
#------------------------------------------------------------------------------
module.exports =
meta:
docs:
description: 'require destructuring from arrays and/or objects'
category: 'ECMAScript 6'
recommended: no
url: 'https://eslint.org/docs/rules/prefer-destructuring'
schema: [
###
# old support {array: Boolean, object: Boolean}
# new support {VariableDeclarator: {}, AssignmentExpression: {}}
###
type: 'object'
properties:
array:
type: 'boolean'
object:
type: 'boolean'
additionalProperties: no
,
type: 'object'
properties:
enforceForRenamedProperties:
type: 'boolean'
additionalProperties: no
]
create: (context) ->
enabledTypes = context.options[0] ? array: yes, object: yes
enforceForRenamedProperties =
context.options[1]?.enforceForRenamedProperties
#--------------------------------------------------------------------------
# Helpers
#--------------------------------------------------------------------------
###*
# @param {string} nodeType "AssignmentExpression" or "VariableDeclarator"
# @param {string} destructuringType "array" or "object"
# @returns {boolean} `true` if the destructuring type should be checked for the given node
###
shouldCheck = (destructuringType) ->
enabledTypes[destructuringType]
###*
# Determines if the given node is accessing an array index
#
# This is used to differentiate array index access from object property
# access.
#
# @param {ASTNode} node the node to evaluate
# @returns {boolean} whether or not the node is an integer
###
isArrayIndexAccess = (node) -> Number.isInteger node.property.value
###*
# Report that the given node should use destructuring
#
# @param {ASTNode} reportNode the node to report
# @param {string} type the type of destructuring that should have been done
# @returns {void}
###
report = (reportNode, type) ->
context.report
node: reportNode, message: 'Use {{type}} destructuring.', data: {type}
###*
# Check that the `prefer-destructuring` rules are followed based on the
# given left- and right-hand side of the assignment.
#
# Pulled out into a separate method so that VariableDeclarators and
# AssignmentExpressions can share the same verification logic.
#
# @param {ASTNode} leftNode the left-hand side of the assignment
# @param {ASTNode} rightNode the right-hand side of the assignment
# @param {ASTNode} reportNode the node to report the error on
# @returns {void}
###
performCheck = (leftNode, rightNode, reportNode) ->
return if (
rightNode.type isnt 'MemberExpression' or
rightNode.object.type is 'Super' or
rightNode.optional
)
if isArrayIndexAccess rightNode
if shouldCheck 'array' then report reportNode, 'array'
return
return unless shouldCheck 'object'
if enforceForRenamedProperties
report reportNode, 'object'
return
{property} = rightNode
if (
(property.type is 'Literal' and leftNode.name is property.value) or
(property.type is 'Identifier' and
leftNode.name is property.name and
not rightNode.computed)
)
report reportNode, 'object'
###*
# Run the `prefer-destructuring` check on an AssignmentExpression
#
# @param {ASTNode} node the AssignmentExpression node
# @returns {void}
###
checkAssigmentExpression = (node) ->
if node.operator is '=' then performCheck node.left, node.right, node
#--------------------------------------------------------------------------
# Public
#--------------------------------------------------------------------------
AssignmentExpression: checkAssigmentExpression
|
[
{
"context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public Li",
"end": 43,
"score": 0.999912440776825,
"start": 29,
"tag": "EMAIL",
"value": "contact@ppy.sh"
}
] | resources/assets/coffee/react/profile-page/top-ranks.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 { ExtraHeader } from './extra-header'
import { PlayDetailList } from 'play-detail-list'
import * as React from 'react'
import { div, h2, h3, ul, li, a, p, pre, span } from 'react-dom-factories'
import { ShowMoreLink } from 'show-more-link'
el = React.createElement
export class TopRanks extends React.PureComponent
render: =>
div
className: 'page-extra'
el ExtraHeader, name: @props.name, withEdit: @props.withEdit
div null,
h3 className: 'title title--page-extra-small', osu.trans('users.show.extra.top_ranks.best.title')
@renderScores 'scoresBest', 'best'
div null,
h3
className: 'title title--page-extra-small'
osu.trans('users.show.extra.top_ranks.first.title')
' '
if @props.user.scores_first_count > 0
span className: 'title__count',
osu.formatNumber(@props.user.scores_first_count)
@renderScores 'scoresFirsts', 'firsts'
renderScores: (key, type) =>
pagination = @props.pagination[key]
scores = @props[key]
if scores?.error
p className: 'profile-extra-entries', scores.error
else if scores?.length
div className: 'profile-extra-entries',
el PlayDetailList, scores: scores
div className: 'profile-extra-entries__item',
el ShowMoreLink,
modifiers: ['profile-page', 't-greyseafoam-dark']
event: 'profile:showMore'
hasMore: pagination.hasMore
loading: pagination.loading
data:
name: key
url: laroute.route 'users.scores',
user: @props.user.id
type: type
mode: @props.currentMode
else
p className: 'profile-extra-entries', osu.trans('users.show.extra.top_ranks.empty')
| 62889 | # 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 { ExtraHeader } from './extra-header'
import { PlayDetailList } from 'play-detail-list'
import * as React from 'react'
import { div, h2, h3, ul, li, a, p, pre, span } from 'react-dom-factories'
import { ShowMoreLink } from 'show-more-link'
el = React.createElement
export class TopRanks extends React.PureComponent
render: =>
div
className: 'page-extra'
el ExtraHeader, name: @props.name, withEdit: @props.withEdit
div null,
h3 className: 'title title--page-extra-small', osu.trans('users.show.extra.top_ranks.best.title')
@renderScores 'scoresBest', 'best'
div null,
h3
className: 'title title--page-extra-small'
osu.trans('users.show.extra.top_ranks.first.title')
' '
if @props.user.scores_first_count > 0
span className: 'title__count',
osu.formatNumber(@props.user.scores_first_count)
@renderScores 'scoresFirsts', 'firsts'
renderScores: (key, type) =>
pagination = @props.pagination[key]
scores = @props[key]
if scores?.error
p className: 'profile-extra-entries', scores.error
else if scores?.length
div className: 'profile-extra-entries',
el PlayDetailList, scores: scores
div className: 'profile-extra-entries__item',
el ShowMoreLink,
modifiers: ['profile-page', 't-greyseafoam-dark']
event: 'profile:showMore'
hasMore: pagination.hasMore
loading: pagination.loading
data:
name: key
url: laroute.route 'users.scores',
user: @props.user.id
type: type
mode: @props.currentMode
else
p className: 'profile-extra-entries', osu.trans('users.show.extra.top_ranks.empty')
| 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 { ExtraHeader } from './extra-header'
import { PlayDetailList } from 'play-detail-list'
import * as React from 'react'
import { div, h2, h3, ul, li, a, p, pre, span } from 'react-dom-factories'
import { ShowMoreLink } from 'show-more-link'
el = React.createElement
export class TopRanks extends React.PureComponent
render: =>
div
className: 'page-extra'
el ExtraHeader, name: @props.name, withEdit: @props.withEdit
div null,
h3 className: 'title title--page-extra-small', osu.trans('users.show.extra.top_ranks.best.title')
@renderScores 'scoresBest', 'best'
div null,
h3
className: 'title title--page-extra-small'
osu.trans('users.show.extra.top_ranks.first.title')
' '
if @props.user.scores_first_count > 0
span className: 'title__count',
osu.formatNumber(@props.user.scores_first_count)
@renderScores 'scoresFirsts', 'firsts'
renderScores: (key, type) =>
pagination = @props.pagination[key]
scores = @props[key]
if scores?.error
p className: 'profile-extra-entries', scores.error
else if scores?.length
div className: 'profile-extra-entries',
el PlayDetailList, scores: scores
div className: 'profile-extra-entries__item',
el ShowMoreLink,
modifiers: ['profile-page', 't-greyseafoam-dark']
event: 'profile:showMore'
hasMore: pagination.hasMore
loading: pagination.loading
data:
name: key
url: laroute.route 'users.scores',
user: @props.user.id
type: type
mode: @props.currentMode
else
p className: 'profile-extra-entries', osu.trans('users.show.extra.top_ranks.empty')
|
[
{
"context": "###\n# @author Will Steinmetz\n# jQuery notification plug-in inspired by the not",
"end": 28,
"score": 0.9998626708984375,
"start": 14,
"tag": "NAME",
"value": "Will Steinmetz"
},
{
"context": "ation style of Windows 8\n# Copyright (c)2013-2015, Will Steinmetz\n# Licensed under the BSD license.\n# http://openso",
"end": 147,
"score": 0.9998315572738647,
"start": 133,
"tag": "NAME",
"value": "Will Steinmetz"
}
] | public/third_party/notific8/grunt/contrib-watch.coffee | pvndn/spa | 130 | ###
# @author Will Steinmetz
# jQuery notification plug-in inspired by the notification style of Windows 8
# Copyright (c)2013-2015, Will Steinmetz
# Licensed under the BSD license.
# http://opensource.org/licenses/BSD-3-Clause
###
module.exports = (grunt) ->
grunt.config('watch',
options:
atBegin: ['copy:font']
sass:
files: [
'src/sass/*.scss'
]
tasks: ['clean:css', 'sass', 'cssmin', 'copy:css']
options:
spawn: false
coffee:
files: [
'src/coffee/*.coffee'
]
tasks: ['clean:js', 'coffee', 'uglify', 'copy:js']
options:
spawn: false
jade:
files: [
'src/jade/**/*.jade'
]
tasks: ['jade']
options:
spawn: false
)
grunt.loadNpmTasks 'grunt-contrib-watch'
| 189751 | ###
# @author <NAME>
# jQuery notification plug-in inspired by the notification style of Windows 8
# Copyright (c)2013-2015, <NAME>
# Licensed under the BSD license.
# http://opensource.org/licenses/BSD-3-Clause
###
module.exports = (grunt) ->
grunt.config('watch',
options:
atBegin: ['copy:font']
sass:
files: [
'src/sass/*.scss'
]
tasks: ['clean:css', 'sass', 'cssmin', 'copy:css']
options:
spawn: false
coffee:
files: [
'src/coffee/*.coffee'
]
tasks: ['clean:js', 'coffee', 'uglify', 'copy:js']
options:
spawn: false
jade:
files: [
'src/jade/**/*.jade'
]
tasks: ['jade']
options:
spawn: false
)
grunt.loadNpmTasks 'grunt-contrib-watch'
| true | ###
# @author PI:NAME:<NAME>END_PI
# jQuery notification plug-in inspired by the notification style of Windows 8
# Copyright (c)2013-2015, PI:NAME:<NAME>END_PI
# Licensed under the BSD license.
# http://opensource.org/licenses/BSD-3-Clause
###
module.exports = (grunt) ->
grunt.config('watch',
options:
atBegin: ['copy:font']
sass:
files: [
'src/sass/*.scss'
]
tasks: ['clean:css', 'sass', 'cssmin', 'copy:css']
options:
spawn: false
coffee:
files: [
'src/coffee/*.coffee'
]
tasks: ['clean:js', 'coffee', 'uglify', 'copy:js']
options:
spawn: false
jade:
files: [
'src/jade/**/*.jade'
]
tasks: ['jade']
options:
spawn: false
)
grunt.loadNpmTasks 'grunt-contrib-watch'
|
[
{
"context": "customCoffee = new Coffee({\n functions: {\n marius: {\n color: 'red'\n },\n valjean: {",
"end": 195,
"score": 0.7001802921295166,
"start": 189,
"tag": "NAME",
"value": "marius"
},
{
"context": " marius: {\n color: 'red'\n },\n valjean: {},\n eponine: {\n value: true,\n ",
"end": 242,
"score": 0.8066526651382446,
"start": 235,
"tag": "NAME",
"value": "valjean"
},
{
"context": "tomSerialization = customCoffee.parse(\n '''\n marius eponine 10\n alert random 100\n cosette 20\n ",
"end": 537,
"score": 0.8841947317123413,
"start": 531,
"tag": "NAME",
"value": "marius"
},
{
"context": "ses=\"Call works-as-method-call mostly-block\"\n >marius <socket\n precedence=\"-1\"\n handwritten=\"",
"end": 784,
"score": 0.8803153038024902,
"start": 778,
"tag": "NAME",
"value": "marius"
}
] | test/src/cstest.coffee | takeratta/droplet | 145 | helper = require '../../src/helper.coffee'
Coffee = require '../../src/languages/coffee.coffee'
asyncTest 'Parser configurability', ->
customCoffee = new Coffee({
functions: {
marius: {
color: 'red'
},
valjean: {},
eponine: {
value: true,
color: 'purplish'
},
fantine: {
value: true
},
cosette: {
command: true,
value: true
}
}
})
window.customSerialization = customSerialization = customCoffee.parse(
'''
marius eponine 10
alert random 100
cosette 20
''').serialize()
expectedSerialization = '''<document
><block
precedence="0"
color="red"
socketLevel="0"
classes="Call works-as-method-call mostly-block"
>marius <socket
precedence="-1"
handwritten="false"
classes="Call works-as-method-call"
><block
precedence="0"
color="purplish"
socketLevel="0"
classes="Call works-as-method-call mostly-value"
>eponine <socket
precedence="-1"
handwritten="false"
classes="Value">10</socket></block></socket></block>\n<block
precedence="0"
color="blue"
socketLevel="0"
classes="Call works-as-method-call any-drop"
><socket
precedence="0"
handwritten="false"
classes="Value"
>alert</socket> <socket
precedence="-1"
handwritten="false"
classes="Call works-as-method-call"
><block
precedence="0"
color="blue"
socketLevel="0"
classes="Call works-as-method-call any-drop"
><socket
precedence="0"
handwritten="false"
classes="Value"
>random</socket> <socket
precedence="-1"
handwritten="false"
classes="Value">100</socket></block></socket></block>\n<block
precedence="0"
color="blue"
socketLevel="0"
classes="Call works-as-method-call any-drop">cosette <socket
precedence="-1"
handwritten="false"
classes="Value">20</socket></block></document>'''
strictEqual(
helper.xmlPrettyPrint(customSerialization),
helper.xmlPrettyPrint(expectedSerialization),
'Custom known functions work')
return start()
asyncTest 'Dotted methods', ->
customCoffee = new Coffee({
functions: {
'console.log': {},
speak: {},
'Math.log': {
value: true
},
'*.toString': {
value: true
},
'?.fd': {
command: true
},
log: {
value: true
},
setTimeout: {
command: true,
value: true
}
}
})
customSerialization = customCoffee.parse(
'console.log Math.log log x.toString log.fd()\nfd()').serialize()
expectedSerialization = '''<document
><block
precedence="0"
color="blue"
socketLevel="0"
classes="Call works-as-method-call mostly-block"
>console.log <socket
precedence="-1"
handwritten="false"
classes="Call works-as-method-call"
><block
precedence="0"
color="green"
socketLevel="0"
classes="Call works-as-method-call mostly-value"
>Math.log <socket
precedence="-1"
handwritten="false"
classes="Call works-as-method-call"
><block
precedence="0"
color="green"
socketLevel="0"
classes="Call works-as-method-call mostly-value"
>log <socket
precedence="-1"
handwritten="false"
classes="Call works-as-method-call"
><block
precedence="0"
color="green"
socketLevel="0"
classes="Call works-as-method-call mostly-value"
><socket
precedence="0"
handwritten="false"
classes="Literal"
>x</socket>.toString <socket
precedence="-1"
handwritten="false"
classes="Call works-as-method-call"
><block
precedence="0"
color="blue"
socketLevel="0"
classes="Call works-as-method-call mostly-block"
><socket
precedence="0"
handwritten="false"
classes="Literal"
>log</socket>.fd()</block></socket
></block></socket
></block></socket
></block></socket></block
>\n<block
precedence="0"
color="blue"
socketLevel="0"
classes="Call works-as-method-call mostly-block"
>fd()</block></document>'''
strictEqual(
helper.xmlPrettyPrint(customSerialization),
helper.xmlPrettyPrint(expectedSerialization),
'Dotted known functions work')
start()
asyncTest 'Merged code blocks', ->
coffee = new Coffee()
customSerialization = coffee.parse(
'''
x = (y) -> y * y
alert \'clickme\', ->
console.log \'ouch\'
'''
).serialize()
expectedSerialization = '''<document
><block
precedence="0"
color="purple"
socketLevel="0"
classes="Assign mostly-block"><socket
precedence="0"
handwritten="false"
classes="Value lvalue"
>x</socket
> = (<socket
precedence="0"
handwritten="false"
classes="forbid-all __function_param__"
>y</socket
>) -> <socket
precedence="0"
handwritten="false"
classes="Block"
><block
precedence="5"
color="green"
socketLevel="0"
classes="Op value-only"
><socket
precedence="5"
handwritten="false"
classes="Value"
>y</socket
> * <socket
precedence="5"
handwritten="false"
classes="Value"
>y</socket></block></socket></block
>\n<block
precedence="0"
color="blue"
socketLevel="0"
classes="Call works-as-method-call mostly-block"
>alert <socket
precedence="0"
handwritten="false"
classes="Value"
>'clickme'</socket
>, -><indent
prefix=" "
classes=""
>\n<block
precedence="0"
color="blue"
socketLevel="0"
classes="Call works-as-method-call mostly-block"
>console.log <socket
precedence="-1"
handwritten="false"
classes="Value"
>'ouch'</socket></block></indent></block></document>
'''
strictEqual(
helper.xmlPrettyPrint(customSerialization),
helper.xmlPrettyPrint(expectedSerialization),
'Merged code blocks work')
return start()
asyncTest 'Custom Colors', ->
customCoffee = new Coffee({
categories: {
functions: {color: '#111'},
returns: {color: '#222'},
comments: {color: '#333'},
arithmetic: {color: '#444'},
containers: {color: '#666'},
assignments: {color: '#777'},
loops: {color: '#888'},
conditionals: {color: '#999'},
value: {color: '#aaa'},
command: {color: '#bbb'}
}
})
customSerialization = customCoffee.parse(
'return b != (a += [c + d][0])').serialize()
expectedSerialization = '''<document
><block
precedence="0"
color="#222"
socketLevel="0"
classes="Return block-only"
>return <socket
precedence="0"
handwritten="false"
classes="Op"
><block
precedence="3"
color="cyan"
socketLevel="0"
classes="Op value-only"
><socket
precedence="3"
handwritten="false"
classes="Value"
>b</socket
> != <socket
precedence="3"
handwritten="false"
classes="Value"
><block
precedence="0"
color="#777"
socketLevel="0"
classes="Assign mostly-block"
>(<socket
precedence="0"
handwritten="false"
classes="Value lvalue"
>a</socket
> += <socket
precedence="0"
handwritten="false"
classes="Value"
><block
precedence="0"
color="#aaa"
socketLevel="0"
classes="Value mostly-value"
><socket
precedence="0"
handwritten="false"
classes="Arr"
><block
precedence="100"
color="#666"
socketLevel="0"
classes="Arr value-only"
>[<indent
prefix=" "
classes=""
><block
precedence="4"
color="#444"
socketLevel="0"
classes="Op value-only"
><socket
precedence="4"
handwritten="false"
classes="Value"
>c</socket
> + <socket
precedence="4"
handwritten="false"
classes="Value"
>d</socket
></block
></indent
>]</block
></socket
>[<socket
precedence="0"
handwritten="false"
classes="Value"
>0</socket
>]</block
></socket
>)</block
></socket
></block
></socket
></block
></document>'''
strictEqual(
helper.xmlPrettyPrint(customSerialization),
helper.xmlPrettyPrint(expectedSerialization),
'Custom colors work')
start()
| 128236 | helper = require '../../src/helper.coffee'
Coffee = require '../../src/languages/coffee.coffee'
asyncTest 'Parser configurability', ->
customCoffee = new Coffee({
functions: {
<NAME>: {
color: 'red'
},
<NAME>: {},
eponine: {
value: true,
color: 'purplish'
},
fantine: {
value: true
},
cosette: {
command: true,
value: true
}
}
})
window.customSerialization = customSerialization = customCoffee.parse(
'''
<NAME> eponine 10
alert random 100
cosette 20
''').serialize()
expectedSerialization = '''<document
><block
precedence="0"
color="red"
socketLevel="0"
classes="Call works-as-method-call mostly-block"
><NAME> <socket
precedence="-1"
handwritten="false"
classes="Call works-as-method-call"
><block
precedence="0"
color="purplish"
socketLevel="0"
classes="Call works-as-method-call mostly-value"
>eponine <socket
precedence="-1"
handwritten="false"
classes="Value">10</socket></block></socket></block>\n<block
precedence="0"
color="blue"
socketLevel="0"
classes="Call works-as-method-call any-drop"
><socket
precedence="0"
handwritten="false"
classes="Value"
>alert</socket> <socket
precedence="-1"
handwritten="false"
classes="Call works-as-method-call"
><block
precedence="0"
color="blue"
socketLevel="0"
classes="Call works-as-method-call any-drop"
><socket
precedence="0"
handwritten="false"
classes="Value"
>random</socket> <socket
precedence="-1"
handwritten="false"
classes="Value">100</socket></block></socket></block>\n<block
precedence="0"
color="blue"
socketLevel="0"
classes="Call works-as-method-call any-drop">cosette <socket
precedence="-1"
handwritten="false"
classes="Value">20</socket></block></document>'''
strictEqual(
helper.xmlPrettyPrint(customSerialization),
helper.xmlPrettyPrint(expectedSerialization),
'Custom known functions work')
return start()
asyncTest 'Dotted methods', ->
customCoffee = new Coffee({
functions: {
'console.log': {},
speak: {},
'Math.log': {
value: true
},
'*.toString': {
value: true
},
'?.fd': {
command: true
},
log: {
value: true
},
setTimeout: {
command: true,
value: true
}
}
})
customSerialization = customCoffee.parse(
'console.log Math.log log x.toString log.fd()\nfd()').serialize()
expectedSerialization = '''<document
><block
precedence="0"
color="blue"
socketLevel="0"
classes="Call works-as-method-call mostly-block"
>console.log <socket
precedence="-1"
handwritten="false"
classes="Call works-as-method-call"
><block
precedence="0"
color="green"
socketLevel="0"
classes="Call works-as-method-call mostly-value"
>Math.log <socket
precedence="-1"
handwritten="false"
classes="Call works-as-method-call"
><block
precedence="0"
color="green"
socketLevel="0"
classes="Call works-as-method-call mostly-value"
>log <socket
precedence="-1"
handwritten="false"
classes="Call works-as-method-call"
><block
precedence="0"
color="green"
socketLevel="0"
classes="Call works-as-method-call mostly-value"
><socket
precedence="0"
handwritten="false"
classes="Literal"
>x</socket>.toString <socket
precedence="-1"
handwritten="false"
classes="Call works-as-method-call"
><block
precedence="0"
color="blue"
socketLevel="0"
classes="Call works-as-method-call mostly-block"
><socket
precedence="0"
handwritten="false"
classes="Literal"
>log</socket>.fd()</block></socket
></block></socket
></block></socket
></block></socket></block
>\n<block
precedence="0"
color="blue"
socketLevel="0"
classes="Call works-as-method-call mostly-block"
>fd()</block></document>'''
strictEqual(
helper.xmlPrettyPrint(customSerialization),
helper.xmlPrettyPrint(expectedSerialization),
'Dotted known functions work')
start()
asyncTest 'Merged code blocks', ->
coffee = new Coffee()
customSerialization = coffee.parse(
'''
x = (y) -> y * y
alert \'clickme\', ->
console.log \'ouch\'
'''
).serialize()
expectedSerialization = '''<document
><block
precedence="0"
color="purple"
socketLevel="0"
classes="Assign mostly-block"><socket
precedence="0"
handwritten="false"
classes="Value lvalue"
>x</socket
> = (<socket
precedence="0"
handwritten="false"
classes="forbid-all __function_param__"
>y</socket
>) -> <socket
precedence="0"
handwritten="false"
classes="Block"
><block
precedence="5"
color="green"
socketLevel="0"
classes="Op value-only"
><socket
precedence="5"
handwritten="false"
classes="Value"
>y</socket
> * <socket
precedence="5"
handwritten="false"
classes="Value"
>y</socket></block></socket></block
>\n<block
precedence="0"
color="blue"
socketLevel="0"
classes="Call works-as-method-call mostly-block"
>alert <socket
precedence="0"
handwritten="false"
classes="Value"
>'clickme'</socket
>, -><indent
prefix=" "
classes=""
>\n<block
precedence="0"
color="blue"
socketLevel="0"
classes="Call works-as-method-call mostly-block"
>console.log <socket
precedence="-1"
handwritten="false"
classes="Value"
>'ouch'</socket></block></indent></block></document>
'''
strictEqual(
helper.xmlPrettyPrint(customSerialization),
helper.xmlPrettyPrint(expectedSerialization),
'Merged code blocks work')
return start()
asyncTest 'Custom Colors', ->
customCoffee = new Coffee({
categories: {
functions: {color: '#111'},
returns: {color: '#222'},
comments: {color: '#333'},
arithmetic: {color: '#444'},
containers: {color: '#666'},
assignments: {color: '#777'},
loops: {color: '#888'},
conditionals: {color: '#999'},
value: {color: '#aaa'},
command: {color: '#bbb'}
}
})
customSerialization = customCoffee.parse(
'return b != (a += [c + d][0])').serialize()
expectedSerialization = '''<document
><block
precedence="0"
color="#222"
socketLevel="0"
classes="Return block-only"
>return <socket
precedence="0"
handwritten="false"
classes="Op"
><block
precedence="3"
color="cyan"
socketLevel="0"
classes="Op value-only"
><socket
precedence="3"
handwritten="false"
classes="Value"
>b</socket
> != <socket
precedence="3"
handwritten="false"
classes="Value"
><block
precedence="0"
color="#777"
socketLevel="0"
classes="Assign mostly-block"
>(<socket
precedence="0"
handwritten="false"
classes="Value lvalue"
>a</socket
> += <socket
precedence="0"
handwritten="false"
classes="Value"
><block
precedence="0"
color="#aaa"
socketLevel="0"
classes="Value mostly-value"
><socket
precedence="0"
handwritten="false"
classes="Arr"
><block
precedence="100"
color="#666"
socketLevel="0"
classes="Arr value-only"
>[<indent
prefix=" "
classes=""
><block
precedence="4"
color="#444"
socketLevel="0"
classes="Op value-only"
><socket
precedence="4"
handwritten="false"
classes="Value"
>c</socket
> + <socket
precedence="4"
handwritten="false"
classes="Value"
>d</socket
></block
></indent
>]</block
></socket
>[<socket
precedence="0"
handwritten="false"
classes="Value"
>0</socket
>]</block
></socket
>)</block
></socket
></block
></socket
></block
></document>'''
strictEqual(
helper.xmlPrettyPrint(customSerialization),
helper.xmlPrettyPrint(expectedSerialization),
'Custom colors work')
start()
| true | helper = require '../../src/helper.coffee'
Coffee = require '../../src/languages/coffee.coffee'
asyncTest 'Parser configurability', ->
customCoffee = new Coffee({
functions: {
PI:NAME:<NAME>END_PI: {
color: 'red'
},
PI:NAME:<NAME>END_PI: {},
eponine: {
value: true,
color: 'purplish'
},
fantine: {
value: true
},
cosette: {
command: true,
value: true
}
}
})
window.customSerialization = customSerialization = customCoffee.parse(
'''
PI:NAME:<NAME>END_PI eponine 10
alert random 100
cosette 20
''').serialize()
expectedSerialization = '''<document
><block
precedence="0"
color="red"
socketLevel="0"
classes="Call works-as-method-call mostly-block"
>PI:NAME:<NAME>END_PI <socket
precedence="-1"
handwritten="false"
classes="Call works-as-method-call"
><block
precedence="0"
color="purplish"
socketLevel="0"
classes="Call works-as-method-call mostly-value"
>eponine <socket
precedence="-1"
handwritten="false"
classes="Value">10</socket></block></socket></block>\n<block
precedence="0"
color="blue"
socketLevel="0"
classes="Call works-as-method-call any-drop"
><socket
precedence="0"
handwritten="false"
classes="Value"
>alert</socket> <socket
precedence="-1"
handwritten="false"
classes="Call works-as-method-call"
><block
precedence="0"
color="blue"
socketLevel="0"
classes="Call works-as-method-call any-drop"
><socket
precedence="0"
handwritten="false"
classes="Value"
>random</socket> <socket
precedence="-1"
handwritten="false"
classes="Value">100</socket></block></socket></block>\n<block
precedence="0"
color="blue"
socketLevel="0"
classes="Call works-as-method-call any-drop">cosette <socket
precedence="-1"
handwritten="false"
classes="Value">20</socket></block></document>'''
strictEqual(
helper.xmlPrettyPrint(customSerialization),
helper.xmlPrettyPrint(expectedSerialization),
'Custom known functions work')
return start()
asyncTest 'Dotted methods', ->
customCoffee = new Coffee({
functions: {
'console.log': {},
speak: {},
'Math.log': {
value: true
},
'*.toString': {
value: true
},
'?.fd': {
command: true
},
log: {
value: true
},
setTimeout: {
command: true,
value: true
}
}
})
customSerialization = customCoffee.parse(
'console.log Math.log log x.toString log.fd()\nfd()').serialize()
expectedSerialization = '''<document
><block
precedence="0"
color="blue"
socketLevel="0"
classes="Call works-as-method-call mostly-block"
>console.log <socket
precedence="-1"
handwritten="false"
classes="Call works-as-method-call"
><block
precedence="0"
color="green"
socketLevel="0"
classes="Call works-as-method-call mostly-value"
>Math.log <socket
precedence="-1"
handwritten="false"
classes="Call works-as-method-call"
><block
precedence="0"
color="green"
socketLevel="0"
classes="Call works-as-method-call mostly-value"
>log <socket
precedence="-1"
handwritten="false"
classes="Call works-as-method-call"
><block
precedence="0"
color="green"
socketLevel="0"
classes="Call works-as-method-call mostly-value"
><socket
precedence="0"
handwritten="false"
classes="Literal"
>x</socket>.toString <socket
precedence="-1"
handwritten="false"
classes="Call works-as-method-call"
><block
precedence="0"
color="blue"
socketLevel="0"
classes="Call works-as-method-call mostly-block"
><socket
precedence="0"
handwritten="false"
classes="Literal"
>log</socket>.fd()</block></socket
></block></socket
></block></socket
></block></socket></block
>\n<block
precedence="0"
color="blue"
socketLevel="0"
classes="Call works-as-method-call mostly-block"
>fd()</block></document>'''
strictEqual(
helper.xmlPrettyPrint(customSerialization),
helper.xmlPrettyPrint(expectedSerialization),
'Dotted known functions work')
start()
asyncTest 'Merged code blocks', ->
coffee = new Coffee()
customSerialization = coffee.parse(
'''
x = (y) -> y * y
alert \'clickme\', ->
console.log \'ouch\'
'''
).serialize()
expectedSerialization = '''<document
><block
precedence="0"
color="purple"
socketLevel="0"
classes="Assign mostly-block"><socket
precedence="0"
handwritten="false"
classes="Value lvalue"
>x</socket
> = (<socket
precedence="0"
handwritten="false"
classes="forbid-all __function_param__"
>y</socket
>) -> <socket
precedence="0"
handwritten="false"
classes="Block"
><block
precedence="5"
color="green"
socketLevel="0"
classes="Op value-only"
><socket
precedence="5"
handwritten="false"
classes="Value"
>y</socket
> * <socket
precedence="5"
handwritten="false"
classes="Value"
>y</socket></block></socket></block
>\n<block
precedence="0"
color="blue"
socketLevel="0"
classes="Call works-as-method-call mostly-block"
>alert <socket
precedence="0"
handwritten="false"
classes="Value"
>'clickme'</socket
>, -><indent
prefix=" "
classes=""
>\n<block
precedence="0"
color="blue"
socketLevel="0"
classes="Call works-as-method-call mostly-block"
>console.log <socket
precedence="-1"
handwritten="false"
classes="Value"
>'ouch'</socket></block></indent></block></document>
'''
strictEqual(
helper.xmlPrettyPrint(customSerialization),
helper.xmlPrettyPrint(expectedSerialization),
'Merged code blocks work')
return start()
asyncTest 'Custom Colors', ->
customCoffee = new Coffee({
categories: {
functions: {color: '#111'},
returns: {color: '#222'},
comments: {color: '#333'},
arithmetic: {color: '#444'},
containers: {color: '#666'},
assignments: {color: '#777'},
loops: {color: '#888'},
conditionals: {color: '#999'},
value: {color: '#aaa'},
command: {color: '#bbb'}
}
})
customSerialization = customCoffee.parse(
'return b != (a += [c + d][0])').serialize()
expectedSerialization = '''<document
><block
precedence="0"
color="#222"
socketLevel="0"
classes="Return block-only"
>return <socket
precedence="0"
handwritten="false"
classes="Op"
><block
precedence="3"
color="cyan"
socketLevel="0"
classes="Op value-only"
><socket
precedence="3"
handwritten="false"
classes="Value"
>b</socket
> != <socket
precedence="3"
handwritten="false"
classes="Value"
><block
precedence="0"
color="#777"
socketLevel="0"
classes="Assign mostly-block"
>(<socket
precedence="0"
handwritten="false"
classes="Value lvalue"
>a</socket
> += <socket
precedence="0"
handwritten="false"
classes="Value"
><block
precedence="0"
color="#aaa"
socketLevel="0"
classes="Value mostly-value"
><socket
precedence="0"
handwritten="false"
classes="Arr"
><block
precedence="100"
color="#666"
socketLevel="0"
classes="Arr value-only"
>[<indent
prefix=" "
classes=""
><block
precedence="4"
color="#444"
socketLevel="0"
classes="Op value-only"
><socket
precedence="4"
handwritten="false"
classes="Value"
>c</socket
> + <socket
precedence="4"
handwritten="false"
classes="Value"
>d</socket
></block
></indent
>]</block
></socket
>[<socket
precedence="0"
handwritten="false"
classes="Value"
>0</socket
>]</block
></socket
>)</block
></socket
></block
></socket
></block
></document>'''
strictEqual(
helper.xmlPrettyPrint(customSerialization),
helper.xmlPrettyPrint(expectedSerialization),
'Custom colors work')
start()
|
[
{
"context": "_key\n\tif offset_y && !offset_x\n\t\tif align_key == 'top-left' || align_key == 'bottom-left'\n\t\t\tadd_offset_x = ",
"end": 7004,
"score": 0.8783443570137024,
"start": 6996,
"tag": "KEY",
"value": "top-left"
},
{
"context": "t_x\n\t\tif align_key == 'top-left' || align_key == 'bottom-left'\n\t\t\tadd_offset_x = -ctx.dim/2\n\t\telse if align_key",
"end": 7034,
"score": 0.8422459959983826,
"start": 7023,
"tag": "KEY",
"value": "bottom-left"
},
{
"context": "add_offset_x = -ctx.dim/2\n\t\telse if align_key == 'top-right' || align_key == 'bottom-right'\n\t\t\tadd_offse",
"end": 7093,
"score": 0.7035508155822754,
"start": 7089,
"tag": "KEY",
"value": "top-"
},
{
"context": "else if align_key == 'top-right' || align_key == 'bottom-right'\n\t\t\tadd_offset_x = ctx.dim/2\n\t\t# else if align_ke",
"end": 7129,
"score": 0.7881079316139221,
"start": 7117,
"tag": "KEY",
"value": "bottom-right"
},
{
"context": "dd_offset_x = ctx.dim/2\n\t\t# else if align_key == 'left-up' || align_key == 'left-down'\n\t\t# \tadd_offset_x = ",
"end": 7192,
"score": 0.9275252819061279,
"start": 7185,
"tag": "KEY",
"value": "left-up"
},
{
"context": "# else if align_key == 'left-up' || align_key == 'left-down'\n\t\t# \tadd_offset_x = -ctx.dim/2\n\t\t# else if align",
"end": 7220,
"score": 0.9355643391609192,
"start": 7211,
"tag": "KEY",
"value": "left-down"
},
{
"context": "d_offset_x = -ctx.dim/2\n\t\t# else if align_key == 'right-up' || align_key == 'right-down'\n\t\t# \tadd_offset_x =",
"end": 7287,
"score": 0.9364936947822571,
"start": 7279,
"tag": "KEY",
"value": "right-up"
},
{
"context": " else if align_key == 'right-up' || align_key == 'right-down'\n\t\t# \tadd_offset_x = ctx.dim/2\n\t\n\tif offset_x && ",
"end": 7316,
"score": 0.8384996056556702,
"start": 7306,
"tag": "KEY",
"value": "right-down"
},
{
"context": "\n\t\n\tif offset_x && !offset_y\n\t\t# if align_key == 'top-left' || align_key == 'bottom-left'\n\t\t# \tadd_offset_y ",
"end": 7405,
"score": 0.8999598622322083,
"start": 7397,
"tag": "KEY",
"value": "top-left"
},
{
"context": "y\n\t\t# if align_key == 'top-left' || align_key == 'bottom-left'\n\t\t# \tadd_offset_y = -ctx.dim/2\n\t\t# else if align",
"end": 7435,
"score": 0.9085790514945984,
"start": 7424,
"tag": "KEY",
"value": "bottom-left"
},
{
"context": "d_offset_y = -ctx.dim/2\n\t\t# else if align_key == 'top-right' || align_key == 'bottom-right'\n\t\t# \tadd_offset_y",
"end": 7503,
"score": 0.9542651176452637,
"start": 7494,
"tag": "KEY",
"value": "top-right"
},
{
"context": "else if align_key == 'top-right' || align_key == 'bottom-right'\n\t\t# \tadd_offset_y = ctx.dim/2\n\t\tif align_key == ",
"end": 7534,
"score": 0.9365761280059814,
"start": 7522,
"tag": "KEY",
"value": "bottom-right"
},
{
"context": "\n\t\t# \tadd_offset_y = ctx.dim/2\n\t\tif align_key == 'right-down' || align_key == 'left-down'\n\t\t\tadd_offset_y = -c",
"end": 7595,
"score": 0.9395396709442139,
"start": 7585,
"tag": "KEY",
"value": "right-down"
},
{
"context": "2\n\t\tif align_key == 'right-down' || align_key == 'left-down'\n\t\t\tadd_offset_y = -ctx.dim/2\n\t\telse if align_key",
"end": 7623,
"score": 0.8835570812225342,
"start": 7614,
"tag": "KEY",
"value": "left-down"
},
{
"context": "add_offset_y = -ctx.dim/2\n\t\telse if align_key == 'right-up' || align_key == 'left-up'\n\t\t\tadd_offset_y = ctx.",
"end": 7686,
"score": 0.7933072447776794,
"start": 7678,
"tag": "KEY",
"value": "right-up"
},
{
"context": "\telse if align_key == 'right-up' || align_key == 'left-up'\n\t\t\tadd_offset_y = ctx.dim/2\n\n\n\n\toffset_x += add_",
"end": 7712,
"score": 0.791996955871582,
"start": 7705,
"tag": "KEY",
"value": "left-up"
},
{
"context": "t_x,offset_y\n\t# if align_key\n\t# \tif align_key == 'right-down' || align_key == 'right-down' || align_key == 'le",
"end": 7933,
"score": 0.957897424697876,
"start": 7923,
"tag": "KEY",
"value": "right-down"
},
{
"context": "\t# \tif align_key == 'right-down' || align_key == 'right-down' || align_key == 'left-down' || align_key == 'lef",
"end": 7962,
"score": 0.908770740032196,
"start": 7952,
"tag": "KEY",
"value": "right-down"
},
{
"context": "wn' || align_key == 'right-down' || align_key == 'left-down' || align_key == 'left-up'\n\t# \t\tif offset_x\n\t# \t\t",
"end": 7990,
"score": 0.9294407963752747,
"start": 7981,
"tag": "KEY",
"value": "left-down"
},
{
"context": "own' || align_key == 'left-down' || align_key == 'left-up'\n\t# \t\tif offset_x\n\t# \t\t\tlog align_key,offset_x\n\t#",
"end": 8016,
"score": 0.9373436570167542,
"start": 8009,
"tag": "KEY",
"value": "left-up"
}
] | components/Align.coffee | lerp-io/editor-gui | 2 | MIN_HEIGHT = 10
MIN_WIDTH = 300
BAR_DIM = 12
REBAR_DIM = 4
#neveragain
guessAlign = (width,height,ctx,x,y)->
if !ctx.align
pre_align = initAlign(ctx,x,y,width,height)
else
pre_align = ctx.align
switch pre_align
when 'right-down'
return ctx.vert && 'right-down' || 'bottom-right'
when 'right-up'
return ctx.vert && 'right-up' || 'top-right'
when 'left-down'
return ctx.vert && 'left-down' || 'bottom-left'
when 'left-up'
return ctx.vert && 'left-up' || 'top-left'
when 'bottom-right'
return ctx.vert && 'right-down' || 'bottom-right'
when 'bottom-left'
return ctx.vert && 'left-down' || 'bottom-left'
when 'top-right'
return ctx.vert && 'right-up' || 'top-right'
when 'top-left'
return ctx.vert && 'left-up' || 'top-left'
else
throw new Error 'invalid align key'
initAlign = (ctx,x,y,width,height)->
# log 'init align',x,width/2,ctx.view_rect.width/2
if x + width/2 < ctx.view_rect.width/2
if y + height/2 < ctx.view_rect.height/2
return ctx.vert && 'right-down' || 'bottom-right'
else
return ctx.vert && 'right-up' || 'top-right'
else
if y + height/2 < ctx.view_rect.height/2
return ctx.vert && 'left-down' || 'bottom-left'
else
return ctx.vert && 'left-up' || 'top-left'
checkFitAlignRight = (ctx,width,height)->
Math.min(ctx.view_rect.right - (ctx.sel_x + width),0)
checkFitAlignLeft = (ctx,width,height)->
Math.min((ctx.sel_x + ctx.sel_w - width) - ctx.view_rect.left,0)
checkFitAlignUp = (ctx,width,height)->
Math.min((ctx.sel_y + ctx.dim - height) - ctx.view_rect.top,0)
checkFitAlignDown = (ctx,width,height)->
Math.min(ctx.view_rect.bottom - (ctx.sel_y + height),0)
checkFitPositionBottom = (ctx,width,height)->
Math.min(ctx.view_rect.bottom - (ctx.y + ctx.height + height),0)
checkFitPositionTop = (ctx,width,height)->
Math.min((ctx.y - height) - (ctx.view_rect.top),0)
checkfitPositionLeft = (ctx,width,height)->
Math.min((ctx.x - width) - (ctx.view_rect.left),0)
checkfitPositionRight = (ctx,width,height)->
Math.min((ctx.view_rect.right) - (ctx.x + ctx.width + width),0)
fixAlign = (align_key,ctx,width,height)->
switch align_key
when 'right-down'
left = checkfitPositionLeft(ctx,width,height) > checkfitPositionRight(ctx,width,height)
up = checkFitAlignDown(ctx,width,height) < checkFitAlignUp(ctx,width,height)
if left
if up then return 'left-up'
else return 'left-down'
else
if up then return 'right-up'
else return 'right-down'
when 'right-up'
left = checkfitPositionLeft(ctx,width,height) > checkfitPositionRight(ctx,width,height)
up = checkFitAlignDown(ctx,width,height) < checkFitAlignUp(ctx,width,height)
if left
if down then return 'left-down'
else return 'left-up'
else
if down then return 'right-down'
else return 'right-up'
when 'left-down'
right = checkfitPositionLeft(ctx,width,height) < checkfitPositionRight(ctx,width,height)
up = checkFitAlignDown(ctx,width,height) < checkFitAlignUp(ctx,width,height)
if right
if up then return 'right-up'
else return 'right-down'
else
if up then return 'left-up'
else return 'left-down'
when 'left-up'
right = checkfitPositionLeft(ctx,width,height) < checkfitPositionRight(ctx,width,height)
down = checkFitAlignUp(ctx,width,height) < checkFitAlignDown(ctx,width,height)
if right
if down then return 'right-down'
else return 'right-up'
else
if down then return 'left-down'
else return 'left-up'
when 'bottom-right'
top = checkFitPositionBottom(ctx,width,height) < checkFitPositionTop(ctx,width,height)
left = checkFitAlignRight(ctx,width,height) < checkFitAlignLeft(ctx,width,height)
if top
if left then return 'top-left'
else return 'top-right'
else
if left then return 'bottom-left'
else return 'bottom-right'
when 'bottom-left'
top = checkFitPositionTop(ctx,width,height) > checkFitPositionBottom(ctx,width,height)
right = checkFitAlignLeft(ctx,width,height) < checkFitAlignRight(ctx,width,height)
if top
if right then return 'top-right'
else return 'top-left'
else
if right then return 'bottom-right'
else return 'bottom-left'
when 'top-right'
bottom = checkFitPositionBottom(ctx,width,height) > checkFitPositionTop(ctx,width,height)
left = checkFitAlignLeft(ctx,width,height) > checkFitAlignRight(ctx,width,height)
if bottom
if left then return 'bottom-left'
else return 'bottom-right'
else
if left then return 'top-left'
else return 'top-right'
when 'top-left'
bottom = checkFitPositionBottom(ctx,width,height) > checkFitPositionTop(ctx,width,height)
right = checkFitAlignLeft(ctx,width,height) < checkFitAlignRight(ctx,width,height)
if bottom
if right then return 'bottom-right'
else return 'bottom-left'
else
if right then return 'top-right'
else return 'top-left'
clampHeight = (ctx,height)->
if ctx.root && ctx.clamp_height
return Math.max(Math.min(ctx.view_rect.height- BAR_DIM - REBAR_DIM,Math.min(ctx.clamp_height,height)),MIN_HEIGHT)
else if ctx.root
return Math.max(Math.min(ctx.view_rect.height - BAR_DIM - REBAR_DIM,height),MIN_HEIGHT)
else
return Math.max(Math.min(height,ctx.view_rect.height),MIN_HEIGHT)
clampWidth = (ctx,width)->
if ctx.root && ctx.clamp_width
return Math.max(Math.min(ctx.view_rect.width - BAR_DIM - REBAR_DIM,ctx.clamp_width),MIN_WIDTH)
else if ctx.root
return Math.min(ctx.view_rect.width - BAR_DIM - REBAR_DIM,MIN_WIDTH)
else
return Math.max(Math.min(width,ctx.view_rect.width),MIN_WIDTH)
getAlignDirections = (align_key)->
a = align_key.split('-')
right = a[0] == 'right'
left = a[0] == 'left'
down = a[1] == 'down'
up = a[1] == 'up'
bottom = a[0] == 'bottom'
top = a[0] == 'top'
return [left,right,bottom,top,up,down]
getPosition = (width,height,ctx,align_key)->
x = y = 0
switch align_key
when 'right-down'
x = ctx.x + ctx.width
y = ctx.sel_y
when 'right-up'
x = (ctx.x + ctx.width)
y = ctx.sel_y + ctx.dim - height
when 'left-down'
x = ctx.x - width
y = ctx.sel_y
when 'left-up'
x = (ctx.x - width)
y = ctx.sel_y + ctx.dim - height
when 'bottom-right'
x = ctx.sel_x
y = ctx.y+ctx.height
when 'bottom-left'
x = (ctx.sel_x + ctx.sel_w) - width
y = ctx.y+ctx.height
when 'top-right'
x = ctx.sel_x
y = ctx.y-height
when 'top-left'
x = (ctx.sel_x + ctx.sel_w) - width
y = ctx.y-height
else
throw new Error 'invalid align key'
return [x,y]
clampPosition = (ctx,x,y,width,height,align_key)->
offset_x = 0
offset_y = 0
add_offset_x = 0
add_offset_y = 0
if x + width > ctx.view_rect.right
offset_x = ctx.view_rect.right - (x + width)
else if x < ctx.view_rect.left
offset_x = ctx.view_rect.left - x
if y + height > ctx.view_rect.bottom
offset_y = ctx.view_rect.bottom - (y + height)
else if y < ctx.view_rect.top
offset_y = ctx.view_rect.top - y
# log align_key
if offset_y && !offset_x
if align_key == 'top-left' || align_key == 'bottom-left'
add_offset_x = -ctx.dim/2
else if align_key == 'top-right' || align_key == 'bottom-right'
add_offset_x = ctx.dim/2
# else if align_key == 'left-up' || align_key == 'left-down'
# add_offset_x = -ctx.dim/2
# else if align_key == 'right-up' || align_key == 'right-down'
# add_offset_x = ctx.dim/2
if offset_x && !offset_y
# if align_key == 'top-left' || align_key == 'bottom-left'
# add_offset_y = -ctx.dim/2
# else if align_key == 'top-right' || align_key == 'bottom-right'
# add_offset_y = ctx.dim/2
if align_key == 'right-down' || align_key == 'left-down'
add_offset_y = -ctx.dim/2
else if align_key == 'right-up' || align_key == 'left-up'
add_offset_y = ctx.dim/2
offset_x += add_offset_x
offset_y += add_offset_y
# if offset_x && !offset_y
# offset_y -= ctx.dim/2
# log offset_x,offset_y
# if align_key
# if align_key == 'right-down' || align_key == 'right-down' || align_key == 'left-down' || align_key == 'left-up'
# if offset_x
# log align_key,offset_x
# offset_y += ctx.dim/2
# else
# else
# if offset_x
# log align_key,offset_x
# offset_y -= ctx.dim/2
# else if offset_y
# log align_key,offset_y
# offset_x -= ctx.dim/2
return [offset_x,offset_y]
export {clampPosition,getPosition,fixAlign,guessAlign,clampHeight,clampWidth} | 168228 | MIN_HEIGHT = 10
MIN_WIDTH = 300
BAR_DIM = 12
REBAR_DIM = 4
#neveragain
guessAlign = (width,height,ctx,x,y)->
if !ctx.align
pre_align = initAlign(ctx,x,y,width,height)
else
pre_align = ctx.align
switch pre_align
when 'right-down'
return ctx.vert && 'right-down' || 'bottom-right'
when 'right-up'
return ctx.vert && 'right-up' || 'top-right'
when 'left-down'
return ctx.vert && 'left-down' || 'bottom-left'
when 'left-up'
return ctx.vert && 'left-up' || 'top-left'
when 'bottom-right'
return ctx.vert && 'right-down' || 'bottom-right'
when 'bottom-left'
return ctx.vert && 'left-down' || 'bottom-left'
when 'top-right'
return ctx.vert && 'right-up' || 'top-right'
when 'top-left'
return ctx.vert && 'left-up' || 'top-left'
else
throw new Error 'invalid align key'
initAlign = (ctx,x,y,width,height)->
# log 'init align',x,width/2,ctx.view_rect.width/2
if x + width/2 < ctx.view_rect.width/2
if y + height/2 < ctx.view_rect.height/2
return ctx.vert && 'right-down' || 'bottom-right'
else
return ctx.vert && 'right-up' || 'top-right'
else
if y + height/2 < ctx.view_rect.height/2
return ctx.vert && 'left-down' || 'bottom-left'
else
return ctx.vert && 'left-up' || 'top-left'
checkFitAlignRight = (ctx,width,height)->
Math.min(ctx.view_rect.right - (ctx.sel_x + width),0)
checkFitAlignLeft = (ctx,width,height)->
Math.min((ctx.sel_x + ctx.sel_w - width) - ctx.view_rect.left,0)
checkFitAlignUp = (ctx,width,height)->
Math.min((ctx.sel_y + ctx.dim - height) - ctx.view_rect.top,0)
checkFitAlignDown = (ctx,width,height)->
Math.min(ctx.view_rect.bottom - (ctx.sel_y + height),0)
checkFitPositionBottom = (ctx,width,height)->
Math.min(ctx.view_rect.bottom - (ctx.y + ctx.height + height),0)
checkFitPositionTop = (ctx,width,height)->
Math.min((ctx.y - height) - (ctx.view_rect.top),0)
checkfitPositionLeft = (ctx,width,height)->
Math.min((ctx.x - width) - (ctx.view_rect.left),0)
checkfitPositionRight = (ctx,width,height)->
Math.min((ctx.view_rect.right) - (ctx.x + ctx.width + width),0)
fixAlign = (align_key,ctx,width,height)->
switch align_key
when 'right-down'
left = checkfitPositionLeft(ctx,width,height) > checkfitPositionRight(ctx,width,height)
up = checkFitAlignDown(ctx,width,height) < checkFitAlignUp(ctx,width,height)
if left
if up then return 'left-up'
else return 'left-down'
else
if up then return 'right-up'
else return 'right-down'
when 'right-up'
left = checkfitPositionLeft(ctx,width,height) > checkfitPositionRight(ctx,width,height)
up = checkFitAlignDown(ctx,width,height) < checkFitAlignUp(ctx,width,height)
if left
if down then return 'left-down'
else return 'left-up'
else
if down then return 'right-down'
else return 'right-up'
when 'left-down'
right = checkfitPositionLeft(ctx,width,height) < checkfitPositionRight(ctx,width,height)
up = checkFitAlignDown(ctx,width,height) < checkFitAlignUp(ctx,width,height)
if right
if up then return 'right-up'
else return 'right-down'
else
if up then return 'left-up'
else return 'left-down'
when 'left-up'
right = checkfitPositionLeft(ctx,width,height) < checkfitPositionRight(ctx,width,height)
down = checkFitAlignUp(ctx,width,height) < checkFitAlignDown(ctx,width,height)
if right
if down then return 'right-down'
else return 'right-up'
else
if down then return 'left-down'
else return 'left-up'
when 'bottom-right'
top = checkFitPositionBottom(ctx,width,height) < checkFitPositionTop(ctx,width,height)
left = checkFitAlignRight(ctx,width,height) < checkFitAlignLeft(ctx,width,height)
if top
if left then return 'top-left'
else return 'top-right'
else
if left then return 'bottom-left'
else return 'bottom-right'
when 'bottom-left'
top = checkFitPositionTop(ctx,width,height) > checkFitPositionBottom(ctx,width,height)
right = checkFitAlignLeft(ctx,width,height) < checkFitAlignRight(ctx,width,height)
if top
if right then return 'top-right'
else return 'top-left'
else
if right then return 'bottom-right'
else return 'bottom-left'
when 'top-right'
bottom = checkFitPositionBottom(ctx,width,height) > checkFitPositionTop(ctx,width,height)
left = checkFitAlignLeft(ctx,width,height) > checkFitAlignRight(ctx,width,height)
if bottom
if left then return 'bottom-left'
else return 'bottom-right'
else
if left then return 'top-left'
else return 'top-right'
when 'top-left'
bottom = checkFitPositionBottom(ctx,width,height) > checkFitPositionTop(ctx,width,height)
right = checkFitAlignLeft(ctx,width,height) < checkFitAlignRight(ctx,width,height)
if bottom
if right then return 'bottom-right'
else return 'bottom-left'
else
if right then return 'top-right'
else return 'top-left'
clampHeight = (ctx,height)->
if ctx.root && ctx.clamp_height
return Math.max(Math.min(ctx.view_rect.height- BAR_DIM - REBAR_DIM,Math.min(ctx.clamp_height,height)),MIN_HEIGHT)
else if ctx.root
return Math.max(Math.min(ctx.view_rect.height - BAR_DIM - REBAR_DIM,height),MIN_HEIGHT)
else
return Math.max(Math.min(height,ctx.view_rect.height),MIN_HEIGHT)
clampWidth = (ctx,width)->
if ctx.root && ctx.clamp_width
return Math.max(Math.min(ctx.view_rect.width - BAR_DIM - REBAR_DIM,ctx.clamp_width),MIN_WIDTH)
else if ctx.root
return Math.min(ctx.view_rect.width - BAR_DIM - REBAR_DIM,MIN_WIDTH)
else
return Math.max(Math.min(width,ctx.view_rect.width),MIN_WIDTH)
getAlignDirections = (align_key)->
a = align_key.split('-')
right = a[0] == 'right'
left = a[0] == 'left'
down = a[1] == 'down'
up = a[1] == 'up'
bottom = a[0] == 'bottom'
top = a[0] == 'top'
return [left,right,bottom,top,up,down]
getPosition = (width,height,ctx,align_key)->
x = y = 0
switch align_key
when 'right-down'
x = ctx.x + ctx.width
y = ctx.sel_y
when 'right-up'
x = (ctx.x + ctx.width)
y = ctx.sel_y + ctx.dim - height
when 'left-down'
x = ctx.x - width
y = ctx.sel_y
when 'left-up'
x = (ctx.x - width)
y = ctx.sel_y + ctx.dim - height
when 'bottom-right'
x = ctx.sel_x
y = ctx.y+ctx.height
when 'bottom-left'
x = (ctx.sel_x + ctx.sel_w) - width
y = ctx.y+ctx.height
when 'top-right'
x = ctx.sel_x
y = ctx.y-height
when 'top-left'
x = (ctx.sel_x + ctx.sel_w) - width
y = ctx.y-height
else
throw new Error 'invalid align key'
return [x,y]
clampPosition = (ctx,x,y,width,height,align_key)->
offset_x = 0
offset_y = 0
add_offset_x = 0
add_offset_y = 0
if x + width > ctx.view_rect.right
offset_x = ctx.view_rect.right - (x + width)
else if x < ctx.view_rect.left
offset_x = ctx.view_rect.left - x
if y + height > ctx.view_rect.bottom
offset_y = ctx.view_rect.bottom - (y + height)
else if y < ctx.view_rect.top
offset_y = ctx.view_rect.top - y
# log align_key
if offset_y && !offset_x
if align_key == '<KEY>' || align_key == '<KEY>'
add_offset_x = -ctx.dim/2
else if align_key == '<KEY>right' || align_key == '<KEY>'
add_offset_x = ctx.dim/2
# else if align_key == '<KEY>' || align_key == '<KEY>'
# add_offset_x = -ctx.dim/2
# else if align_key == '<KEY>' || align_key == '<KEY>'
# add_offset_x = ctx.dim/2
if offset_x && !offset_y
# if align_key == '<KEY>' || align_key == '<KEY>'
# add_offset_y = -ctx.dim/2
# else if align_key == '<KEY>' || align_key == '<KEY>'
# add_offset_y = ctx.dim/2
if align_key == '<KEY>' || align_key == '<KEY>'
add_offset_y = -ctx.dim/2
else if align_key == '<KEY>' || align_key == '<KEY>'
add_offset_y = ctx.dim/2
offset_x += add_offset_x
offset_y += add_offset_y
# if offset_x && !offset_y
# offset_y -= ctx.dim/2
# log offset_x,offset_y
# if align_key
# if align_key == '<KEY>' || align_key == '<KEY>' || align_key == '<KEY>' || align_key == '<KEY>'
# if offset_x
# log align_key,offset_x
# offset_y += ctx.dim/2
# else
# else
# if offset_x
# log align_key,offset_x
# offset_y -= ctx.dim/2
# else if offset_y
# log align_key,offset_y
# offset_x -= ctx.dim/2
return [offset_x,offset_y]
export {clampPosition,getPosition,fixAlign,guessAlign,clampHeight,clampWidth} | true | MIN_HEIGHT = 10
MIN_WIDTH = 300
BAR_DIM = 12
REBAR_DIM = 4
#neveragain
guessAlign = (width,height,ctx,x,y)->
if !ctx.align
pre_align = initAlign(ctx,x,y,width,height)
else
pre_align = ctx.align
switch pre_align
when 'right-down'
return ctx.vert && 'right-down' || 'bottom-right'
when 'right-up'
return ctx.vert && 'right-up' || 'top-right'
when 'left-down'
return ctx.vert && 'left-down' || 'bottom-left'
when 'left-up'
return ctx.vert && 'left-up' || 'top-left'
when 'bottom-right'
return ctx.vert && 'right-down' || 'bottom-right'
when 'bottom-left'
return ctx.vert && 'left-down' || 'bottom-left'
when 'top-right'
return ctx.vert && 'right-up' || 'top-right'
when 'top-left'
return ctx.vert && 'left-up' || 'top-left'
else
throw new Error 'invalid align key'
initAlign = (ctx,x,y,width,height)->
# log 'init align',x,width/2,ctx.view_rect.width/2
if x + width/2 < ctx.view_rect.width/2
if y + height/2 < ctx.view_rect.height/2
return ctx.vert && 'right-down' || 'bottom-right'
else
return ctx.vert && 'right-up' || 'top-right'
else
if y + height/2 < ctx.view_rect.height/2
return ctx.vert && 'left-down' || 'bottom-left'
else
return ctx.vert && 'left-up' || 'top-left'
checkFitAlignRight = (ctx,width,height)->
Math.min(ctx.view_rect.right - (ctx.sel_x + width),0)
checkFitAlignLeft = (ctx,width,height)->
Math.min((ctx.sel_x + ctx.sel_w - width) - ctx.view_rect.left,0)
checkFitAlignUp = (ctx,width,height)->
Math.min((ctx.sel_y + ctx.dim - height) - ctx.view_rect.top,0)
checkFitAlignDown = (ctx,width,height)->
Math.min(ctx.view_rect.bottom - (ctx.sel_y + height),0)
checkFitPositionBottom = (ctx,width,height)->
Math.min(ctx.view_rect.bottom - (ctx.y + ctx.height + height),0)
checkFitPositionTop = (ctx,width,height)->
Math.min((ctx.y - height) - (ctx.view_rect.top),0)
checkfitPositionLeft = (ctx,width,height)->
Math.min((ctx.x - width) - (ctx.view_rect.left),0)
checkfitPositionRight = (ctx,width,height)->
Math.min((ctx.view_rect.right) - (ctx.x + ctx.width + width),0)
fixAlign = (align_key,ctx,width,height)->
switch align_key
when 'right-down'
left = checkfitPositionLeft(ctx,width,height) > checkfitPositionRight(ctx,width,height)
up = checkFitAlignDown(ctx,width,height) < checkFitAlignUp(ctx,width,height)
if left
if up then return 'left-up'
else return 'left-down'
else
if up then return 'right-up'
else return 'right-down'
when 'right-up'
left = checkfitPositionLeft(ctx,width,height) > checkfitPositionRight(ctx,width,height)
up = checkFitAlignDown(ctx,width,height) < checkFitAlignUp(ctx,width,height)
if left
if down then return 'left-down'
else return 'left-up'
else
if down then return 'right-down'
else return 'right-up'
when 'left-down'
right = checkfitPositionLeft(ctx,width,height) < checkfitPositionRight(ctx,width,height)
up = checkFitAlignDown(ctx,width,height) < checkFitAlignUp(ctx,width,height)
if right
if up then return 'right-up'
else return 'right-down'
else
if up then return 'left-up'
else return 'left-down'
when 'left-up'
right = checkfitPositionLeft(ctx,width,height) < checkfitPositionRight(ctx,width,height)
down = checkFitAlignUp(ctx,width,height) < checkFitAlignDown(ctx,width,height)
if right
if down then return 'right-down'
else return 'right-up'
else
if down then return 'left-down'
else return 'left-up'
when 'bottom-right'
top = checkFitPositionBottom(ctx,width,height) < checkFitPositionTop(ctx,width,height)
left = checkFitAlignRight(ctx,width,height) < checkFitAlignLeft(ctx,width,height)
if top
if left then return 'top-left'
else return 'top-right'
else
if left then return 'bottom-left'
else return 'bottom-right'
when 'bottom-left'
top = checkFitPositionTop(ctx,width,height) > checkFitPositionBottom(ctx,width,height)
right = checkFitAlignLeft(ctx,width,height) < checkFitAlignRight(ctx,width,height)
if top
if right then return 'top-right'
else return 'top-left'
else
if right then return 'bottom-right'
else return 'bottom-left'
when 'top-right'
bottom = checkFitPositionBottom(ctx,width,height) > checkFitPositionTop(ctx,width,height)
left = checkFitAlignLeft(ctx,width,height) > checkFitAlignRight(ctx,width,height)
if bottom
if left then return 'bottom-left'
else return 'bottom-right'
else
if left then return 'top-left'
else return 'top-right'
when 'top-left'
bottom = checkFitPositionBottom(ctx,width,height) > checkFitPositionTop(ctx,width,height)
right = checkFitAlignLeft(ctx,width,height) < checkFitAlignRight(ctx,width,height)
if bottom
if right then return 'bottom-right'
else return 'bottom-left'
else
if right then return 'top-right'
else return 'top-left'
clampHeight = (ctx,height)->
if ctx.root && ctx.clamp_height
return Math.max(Math.min(ctx.view_rect.height- BAR_DIM - REBAR_DIM,Math.min(ctx.clamp_height,height)),MIN_HEIGHT)
else if ctx.root
return Math.max(Math.min(ctx.view_rect.height - BAR_DIM - REBAR_DIM,height),MIN_HEIGHT)
else
return Math.max(Math.min(height,ctx.view_rect.height),MIN_HEIGHT)
clampWidth = (ctx,width)->
if ctx.root && ctx.clamp_width
return Math.max(Math.min(ctx.view_rect.width - BAR_DIM - REBAR_DIM,ctx.clamp_width),MIN_WIDTH)
else if ctx.root
return Math.min(ctx.view_rect.width - BAR_DIM - REBAR_DIM,MIN_WIDTH)
else
return Math.max(Math.min(width,ctx.view_rect.width),MIN_WIDTH)
getAlignDirections = (align_key)->
a = align_key.split('-')
right = a[0] == 'right'
left = a[0] == 'left'
down = a[1] == 'down'
up = a[1] == 'up'
bottom = a[0] == 'bottom'
top = a[0] == 'top'
return [left,right,bottom,top,up,down]
getPosition = (width,height,ctx,align_key)->
x = y = 0
switch align_key
when 'right-down'
x = ctx.x + ctx.width
y = ctx.sel_y
when 'right-up'
x = (ctx.x + ctx.width)
y = ctx.sel_y + ctx.dim - height
when 'left-down'
x = ctx.x - width
y = ctx.sel_y
when 'left-up'
x = (ctx.x - width)
y = ctx.sel_y + ctx.dim - height
when 'bottom-right'
x = ctx.sel_x
y = ctx.y+ctx.height
when 'bottom-left'
x = (ctx.sel_x + ctx.sel_w) - width
y = ctx.y+ctx.height
when 'top-right'
x = ctx.sel_x
y = ctx.y-height
when 'top-left'
x = (ctx.sel_x + ctx.sel_w) - width
y = ctx.y-height
else
throw new Error 'invalid align key'
return [x,y]
clampPosition = (ctx,x,y,width,height,align_key)->
offset_x = 0
offset_y = 0
add_offset_x = 0
add_offset_y = 0
if x + width > ctx.view_rect.right
offset_x = ctx.view_rect.right - (x + width)
else if x < ctx.view_rect.left
offset_x = ctx.view_rect.left - x
if y + height > ctx.view_rect.bottom
offset_y = ctx.view_rect.bottom - (y + height)
else if y < ctx.view_rect.top
offset_y = ctx.view_rect.top - y
# log align_key
if offset_y && !offset_x
if align_key == 'PI:KEY:<KEY>END_PI' || align_key == 'PI:KEY:<KEY>END_PI'
add_offset_x = -ctx.dim/2
else if align_key == 'PI:KEY:<KEY>END_PIright' || align_key == 'PI:KEY:<KEY>END_PI'
add_offset_x = ctx.dim/2
# else if align_key == 'PI:KEY:<KEY>END_PI' || align_key == 'PI:KEY:<KEY>END_PI'
# add_offset_x = -ctx.dim/2
# else if align_key == 'PI:KEY:<KEY>END_PI' || align_key == 'PI:KEY:<KEY>END_PI'
# add_offset_x = ctx.dim/2
if offset_x && !offset_y
# if align_key == 'PI:KEY:<KEY>END_PI' || align_key == 'PI:KEY:<KEY>END_PI'
# add_offset_y = -ctx.dim/2
# else if align_key == 'PI:KEY:<KEY>END_PI' || align_key == 'PI:KEY:<KEY>END_PI'
# add_offset_y = ctx.dim/2
if align_key == 'PI:KEY:<KEY>END_PI' || align_key == 'PI:KEY:<KEY>END_PI'
add_offset_y = -ctx.dim/2
else if align_key == 'PI:KEY:<KEY>END_PI' || align_key == 'PI:KEY:<KEY>END_PI'
add_offset_y = ctx.dim/2
offset_x += add_offset_x
offset_y += add_offset_y
# if offset_x && !offset_y
# offset_y -= ctx.dim/2
# log offset_x,offset_y
# if align_key
# if align_key == 'PI:KEY:<KEY>END_PI' || align_key == 'PI:KEY:<KEY>END_PI' || align_key == 'PI:KEY:<KEY>END_PI' || align_key == 'PI:KEY:<KEY>END_PI'
# if offset_x
# log align_key,offset_x
# offset_y += ctx.dim/2
# else
# else
# if offset_x
# log align_key,offset_x
# offset_y -= ctx.dim/2
# else if offset_y
# log align_key,offset_y
# offset_x -= ctx.dim/2
return [offset_x,offset_y]
export {clampPosition,getPosition,fixAlign,guessAlign,clampHeight,clampWidth} |
[
{
"context": "# Animation Collections\n# by Isaac Weinhausen\n# http://isaacw.com\n\n\n\n\n# Import modules\n# ------",
"end": 45,
"score": 0.9998903870582581,
"start": 29,
"tag": "NAME",
"value": "Isaac Weinhausen"
}
] | AnimationCollections.framer/app.coffee | ekfuhrmann/framer-animation-collections | 0 | # Animation Collections
# by Isaac Weinhausen
# http://isaacw.com
# Import modules
# -------------------------------------
{AnimationSequence} = require "AnimationSequence"
{AnimationSet} = require "AnimationSet"
# App
# -------------------------------------
# Override defaults
Framer.Defaults.Layer.backgroundColor = "#877DD7"
Framer.Defaults.Animation.time = 0.75
# Set canvas props
bg1 = new BackgroundLayer
backgroundColor: "#292929"
bg2 = new BackgroundLayer
backgroundColor: "white"
# Render shape
square = new Layer
width: 80
height: 80
borderRadius: 8
square.center()
# Define animations
rotateAnimation = new Animation
layer: square
properties:
rotation: 360
moveAnimation = new Animation
layer: square
properties:
scale: 2
tweenAnimation = new Animation
layer: square
properties:
borderRadius: 40
fadeBgAnimation = new Animation
layer: bg1
properties:
opacity: 0
# Create an animation sequence and add animations
squaresAnimation = new AnimationSequence
animations:
first: rotateAnimation
second: moveAnimation
third: fadeBgAnimation
fourth: tweenAnimation
# Call the start() method to see it in action
squaresAnimation.start()
| 65528 | # Animation Collections
# by <NAME>
# http://isaacw.com
# Import modules
# -------------------------------------
{AnimationSequence} = require "AnimationSequence"
{AnimationSet} = require "AnimationSet"
# App
# -------------------------------------
# Override defaults
Framer.Defaults.Layer.backgroundColor = "#877DD7"
Framer.Defaults.Animation.time = 0.75
# Set canvas props
bg1 = new BackgroundLayer
backgroundColor: "#292929"
bg2 = new BackgroundLayer
backgroundColor: "white"
# Render shape
square = new Layer
width: 80
height: 80
borderRadius: 8
square.center()
# Define animations
rotateAnimation = new Animation
layer: square
properties:
rotation: 360
moveAnimation = new Animation
layer: square
properties:
scale: 2
tweenAnimation = new Animation
layer: square
properties:
borderRadius: 40
fadeBgAnimation = new Animation
layer: bg1
properties:
opacity: 0
# Create an animation sequence and add animations
squaresAnimation = new AnimationSequence
animations:
first: rotateAnimation
second: moveAnimation
third: fadeBgAnimation
fourth: tweenAnimation
# Call the start() method to see it in action
squaresAnimation.start()
| true | # Animation Collections
# by PI:NAME:<NAME>END_PI
# http://isaacw.com
# Import modules
# -------------------------------------
{AnimationSequence} = require "AnimationSequence"
{AnimationSet} = require "AnimationSet"
# App
# -------------------------------------
# Override defaults
Framer.Defaults.Layer.backgroundColor = "#877DD7"
Framer.Defaults.Animation.time = 0.75
# Set canvas props
bg1 = new BackgroundLayer
backgroundColor: "#292929"
bg2 = new BackgroundLayer
backgroundColor: "white"
# Render shape
square = new Layer
width: 80
height: 80
borderRadius: 8
square.center()
# Define animations
rotateAnimation = new Animation
layer: square
properties:
rotation: 360
moveAnimation = new Animation
layer: square
properties:
scale: 2
tweenAnimation = new Animation
layer: square
properties:
borderRadius: 40
fadeBgAnimation = new Animation
layer: bg1
properties:
opacity: 0
# Create an animation sequence and add animations
squaresAnimation = new AnimationSequence
animations:
first: rotateAnimation
second: moveAnimation
third: fadeBgAnimation
fourth: tweenAnimation
# Call the start() method to see it in action
squaresAnimation.start()
|
[
{
"context": "module.exports =\n name: 'Contact'\n primaryKey: 'hash'\n properties:\n name:\n ",
"end": 33,
"score": 0.9878815412521362,
"start": 26,
"tag": "NAME",
"value": "Contact"
}
] | src/api/models/contact.coffee | marcus433/dropmail | 0 | module.exports =
name: 'Contact'
primaryKey: 'hash'
properties:
name:
type: 'string'
default: ''
address:
type: 'string'
indexed: true
hash: 'string'
addressHash: 'string'
cached:
type: 'bool'
default: false
uncacheable:
type: 'bool'
default: false
rank:
type: 'int'
default: 0
| 199897 | module.exports =
name: '<NAME>'
primaryKey: 'hash'
properties:
name:
type: 'string'
default: ''
address:
type: 'string'
indexed: true
hash: 'string'
addressHash: 'string'
cached:
type: 'bool'
default: false
uncacheable:
type: 'bool'
default: false
rank:
type: 'int'
default: 0
| true | module.exports =
name: 'PI:NAME:<NAME>END_PI'
primaryKey: 'hash'
properties:
name:
type: 'string'
default: ''
address:
type: 'string'
indexed: true
hash: 'string'
addressHash: 'string'
cached:
type: 'bool'
default: false
uncacheable:
type: 'bool'
default: false
rank:
type: 'int'
default: 0
|
[
{
"context": "uired'\n looksGood: 'Looks good'\n userName: 'User name'\n badChars: \"Only letters, numbers, '.', '_', ",
"end": 536,
"score": 0.9995316863059998,
"start": 527,
"tag": "USERNAME",
"value": "User name"
},
{
"context": "tPassword: 'Forget your password?'\n password: 'Password'\n passwordTooShort: 'Must be at least 8 charac",
"end": 706,
"score": 0.9979866743087769,
"start": 698,
"tag": "PASSWORD",
"value": "Password"
},
{
"context": "'\n password: 'Password'\n passwordTooShort: 'Must be at least 8 characters'\n confirmPassword: 'Confirm password'\n pass",
"end": 760,
"score": 0.9607681632041931,
"start": 731,
"tag": "PASSWORD",
"value": "Must be at least 8 characters"
},
{
"context": "t be at least 8 characters'\n confirmPassword: 'Confirm password'\n passwordsDontMatch: 'These don’t match'\n ",
"end": 800,
"score": 0.988679826259613,
"start": 784,
"tag": "PASSWORD",
"value": "Confirm password"
},
{
"context": "h this address already exists'\n realName: 'Real name'\n whyRealName: 'We’ll use this to give you cre",
"end": 1027,
"score": 0.55825275182724,
"start": 1023,
"tag": "NAME",
"value": "name"
},
{
"context": "od: 'Nombre de usuario disponible'\n userName: 'Nombre de usuario'\n badChars: \"Sólo letras, números, '.', '_', y",
"end": 1634,
"score": 0.999569833278656,
"start": 1617,
"tag": "USERNAME",
"value": "Nombre de usuario"
},
{
"context": "e de usuario ya está en uso'\n forgotPassword: '¿Olvidó su contraseña?'\n password: 'Contraseña'\n",
"end": 1768,
"score": 0.6109752058982849,
"start": 1768,
"tag": "PASSWORD",
"value": ""
},
{
"context": "e usuario ya está en uso'\n forgotPassword: '¿Olvidó su contraseña?'\n password: 'Contraseña'\n p",
"end": 1774,
"score": 0.6849882006645203,
"start": 1771,
"tag": "PASSWORD",
"value": "vid"
},
{
"context": "Password: '¿Olvidó su contraseña?'\n password: 'Contraseña'\n passwordTooShort: 'Debe ser de al menos 8 ca",
"end": 1817,
"score": 0.9986652135848999,
"start": 1807,
"tag": "PASSWORD",
"value": "Contraseña"
},
{
"context": "s 8 caracteres de longitud'\n confirmPassword: 'Confirmar contraseña'\n passwordsDontMatch: 'Las contraseñas no coin",
"end": 1931,
"score": 0.9989055395126343,
"start": 1911,
"tag": "PASSWORD",
"value": "Confirmar contraseña"
},
{
"context": "sta dirección de correo ya existe'\n realName: 'Nombre real'\n whyRealName: 'Vamos a usarlo para darte créd",
"end": 2179,
"score": 0.9244927167892456,
"start": 2168,
"tag": "NAME",
"value": "Nombre real"
},
{
"context": "ault()\n login = @refs.name.value\n password = @refs.password.value\n email = @refs.email.value\n",
"end": 10622,
"score": 0.7203629612922668,
"start": 10622,
"tag": "PASSWORD",
"value": ""
},
{
"context": "\n login = @refs.name.value\n password = @refs.password.value\n email = @refs.email.value\n credited_",
"end": 10637,
"score": 0.6556259393692017,
"start": 10629,
"tag": "PASSWORD",
"value": "password"
}
] | app/partials/register-form.cjsx | Crentist/Panoptes-frontend-spanish | 0 | counterpart = require 'counterpart'
React = require 'react'
PromiseToSetState = require '../lib/promise-to-set-state'
auth = require 'panoptes-client/lib/auth'
Translate = require 'react-translate-component'
LoadingIndicator = require '../components/loading-indicator'
debounce = require 'debounce'
apiClient = require 'panoptes-client/lib/api-client'
REMOTE_CHECK_DELAY = 1000
MIN_PASSWORD_LENGTH = 8
counterpart.registerTranslations 'en',
registerForm:
required: 'Required'
looksGood: 'Looks good'
userName: 'User name'
badChars: "Only letters, numbers, '.', '_', and '-'."
nameConflict: 'That username is taken'
forgotPassword: 'Forget your password?'
password: 'Password'
passwordTooShort: 'Must be at least 8 characters'
confirmPassword: 'Confirm password'
passwordsDontMatch: 'These don’t match'
passLooksGood: 'Looks good'
emailLooksGood: 'Looks good'
email: 'Email address'
emailConflict: 'An account with this address already exists'
realName: 'Real name'
whyRealName: 'We’ll use this to give you credit in scientific papers, posters, etc'
agreeToPrivacyPolicy: 'You agree to our %(link)s (required)'
privacyPolicy: 'privacy policy'
okayToEmail: 'It’s okay to send me email every once in a while.'
betaTester: 'I’d like to help test new projects, and be emailed when they’re available.'
register: 'Register'
alreadySignedIn: 'Signed in as %(name)s'
signOut: 'Sign out'
counterpart.registerTranslations 'es',
registerForm:
required: 'Requerido'
looksGood: 'Nombre de usuario disponible'
userName: 'Nombre de usuario'
badChars: "Sólo letras, números, '.', '_', y '-'."
nameConflict: 'El nombre de usuario ya está en uso'
forgotPassword: '¿Olvidó su contraseña?'
password: 'Contraseña'
passwordTooShort: 'Debe ser de al menos 8 caracteres de longitud'
confirmPassword: 'Confirmar contraseña'
passwordsDontMatch: 'Las contraseñas no coinciden'
passLooksGood: 'OK'
emailLooksGood: 'OK'
email: 'Dirección de correo electrónico'
emailConflict: 'Una cuenta con esta dirección de correo ya existe'
realName: 'Nombre real'
whyRealName: 'Vamos a usarlo para darte crédito en publicaciones científicas, posters, etc'
agreeToPrivacyPolicy: 'Estás de acuerdo con nuestras %(link)s (requerido)'
privacyPolicy: 'políticas de privacidad'
okayToEmail: 'Estoy de acuerdo con recibir correos electrónicos de vez en cuando.'
betaTester: 'Me gustaría ayudar a probar nuevos proyectos, y que se me envíe un correo electrónico cuando estén disponubles'
register: 'Registrarse'
alreadySignedIn: 'Sesión iniciada como %(name)s'
signOut: 'Cerrar sesión'
module.exports = React.createClass
displayName: 'RegisterForm'
mixins: [PromiseToSetState]
getDefaultProps: ->
project: {}
getInitialState: ->
badNameChars: null
nameConflict: null
passwordTooShort: null
passwordsDontMatch: null
emailConflict: null
agreedToPrivacyPolicy: null
error: null
render: ->
{badNameChars, nameConflict, passwordTooShort, passwordsDontMatch, emailConflict} = @state
<form method="POST" onSubmit={@handleSubmit}>
<label>
<span className="columns-container inline spread">
<Translate content="registerForm.userName" />
{if badNameChars?.length > 0
<Translate className="form-help error" content="registerForm.badChars" />
else if "nameConflict" of @state.pending
<LoadingIndicator />
else if nameConflict?
if nameConflict
<span className="form-help error">
<Translate content="registerForm.nameConflict" />{' '}
<a href="#{document.baseURI.slice(0, -1)}/reset-password" onClick={@props.onSuccess}>
<Translate content="registerForm.forgotPassword" />
</a>
</span>
else
<span className="form-help success">
<Translate content="registerForm.looksGood" />
</span>}
</span>
<input type="text" ref="name" className="standard-input full" disabled={@props.user?} autoFocus onChange={@handleNameChange} />
</label>
<br />
<label>
<span className="columns-container inline spread">
<Translate content="registerForm.password" />
{if passwordTooShort
<Translate className="form-help error" content="registerForm.passwordTooShort" />}
</span>
<input type="password" ref="password" className="standard-input full" disabled={@props.user?} onChange={@handlePasswordChange} />
</label>
<br />
<label>
<span className="columns-container inline spread">
<Translate content="registerForm.confirmPassword" /><br />
{if passwordsDontMatch?
if passwordsDontMatch
<Translate className="form-help error" content="registerForm.passwordsDontMatch" />
else if not passwordTooShort
<Translate className="form-help success" content="registerForm.passLooksGood" />}
</span>
<input type="password" ref="confirmedPassword" className="standard-input full" disabled={@state.props?} onChange={@handlePasswordChange} />
</label>
<br />
<label>
<span className="columns-container inline spread">
<Translate content="registerForm.email" />
{if 'emailConflict' of @state.pending
<LoadingIndicator />
else if emailConflict?
if emailConflict
<span className="form-help error">
<Translate content="registerForm.emailConflict" />{' '}
<a href="#{document.baseURI.slice(0, -1)}/reset-password" onClick={@props.onSuccess}>
<Translate content="registerForm.forgotPassword" />
</a>
</span>
else
<Translate className="form-help success" content="registerForm.emailLooksGood" />
else
<Translate className="form-help info" content="registerForm.required" />}
</span>
<input type="text" ref="email" className="standard-input full" disabled={@state.props?} onChange={@handleEmailChange} />
</label>
<br />
<label>
<span className="columns-container inline spread">
<Translate content="registerForm.realName" />
</span>
<input type="text" ref="realName" className="standard-input full" disabled={@props.user?} />
<Translate component="span" className="form-help info" content="registerForm.whyRealName" />
</label>
<br />
<br />
<label>
<input type="checkbox" ref="agreesToPrivacyPolicy" disabled={@props.user?} onChange={@handlePrivacyPolicyChange} />
{privacyPolicyLink = <a target="_blank" href="#{document.baseURI.slice(0, -1)}/privacy"><Translate content="registerForm.privacyPolicy" /></a>; null}
<Translate component="span" content="registerForm.agreeToPrivacyPolicy" link={privacyPolicyLink} />
</label>
<br />
<br />
<label>
<input type="checkbox" ref="okayToEmail" defaultChecked={true} disabled={@props.user?} onChange={@forceUpdate.bind this, null} />
<Translate component="span" content="registerForm.okayToEmail" />
</label><br />
<label>
<input type="checkbox" ref="betaTester" disabled={@props.user?} onChange={@forceUpdate.bind this, null} />
<Translate component="span" content="registerForm.betaTester" />
</label><br />
<p style={textAlign: 'center'}>
{if 'user' of @state.pending
<LoadingIndicator />
else if @props.user?
<span className="form-help warning">
<Translate content="registerForm.alreadySignedIn" name={@props.user.login} />{' '}
<button type="button" className="minor-button" onClick={@handleSignOut}><Translate content="registerForm.signOut" /></button>
</span>
else if @state.error?
<span className="form-help error">{@state.error.toString()}</span>
else
<span> </span>}
</p>
<div>
<button type="submit" className="standard-button full" disabled={not @isFormValid() or Object.keys(@state.pending).length isnt 0 or @props.user?}>
<Translate content="registerForm.register" />
</button>
</div>
</form>
handleNameChange: ->
name = @refs.name.value
exists = name.length isnt 0
badChars = (char for char in name.split('') when char.match(/[\w\-\.\ \']/) is null)
@setState
badNameChars: badChars
nameConflict: null
nameExists: exists
if exists and badChars.length is 0
@debouncedCheckForNameConflict ?= debounce @checkForNameConflict, REMOTE_CHECK_DELAY
@debouncedCheckForNameConflict name
debouncedCheckForNameConflict: null
checkForNameConflict: (username) ->
@promiseToSetState nameConflict: auth.register(login: username).catch (error) ->
error.message.match(/login(.+)taken/mi) ? false
handlePasswordChange: ->
password = @refs.password.value
confirmedPassword = @refs.confirmedPassword.value
exists = password.length isnt 0
longEnough = password.length >= MIN_PASSWORD_LENGTH
asLong = confirmedPassword.length >= password.length
matches = password is confirmedPassword
@setState
passwordTooShort: if exists then not longEnough
passwordsDontMatch: if exists and asLong then not matches
handleEmailChange: ->
@promiseToSetState emailConflict: Promise.resolve null # Cancel any existing request.
email = @refs.email.value
if email.match /.+@.+\..+/
@debouncedCheckForEmailConflict ?= debounce @checkForEmailConflict, REMOTE_CHECK_DELAY
@debouncedCheckForEmailConflict email
debouncedCheckForEmailConflict: null
checkForEmailConflict: (email) ->
@promiseToSetState emailConflict: auth.register({email}).catch (error) ->
error.message.match(/email(.+)taken/mi) ? false
handlePrivacyPolicyChange: ->
@setState agreesToPrivacyPolicy: @refs.agreesToPrivacyPolicy.checked
isFormValid: ->
{badNameChars, nameConflict, passwordsDontMatch, emailConflict, agreesToPrivacyPolicy, nameExists} = @state
badNameChars?.length is 0 and not nameConflict and not passwordsDontMatch and not emailConflict and nameExists and agreesToPrivacyPolicy
handleSubmit: (e) ->
e.preventDefault()
login = @refs.name.value
password = @refs.password.value
email = @refs.email.value
credited_name = @refs.realName.value
global_email_communication = @refs.okayToEmail.checked
project_email_communication = global_email_communication
beta_email_communication = @refs.betaTester.checked
project_id = @props.project?.id
@setState error: null
@props.onSubmit?()
auth.register {login, password, email, credited_name, project_email_communication, global_email_communication, project_id, beta_email_communication}
.then =>
@props.onSuccess? arguments...
.catch (error) =>
@setState {error}
@props.onFailure? arguments...
handleSignOut: ->
auth.signOut()
| 38893 | counterpart = require 'counterpart'
React = require 'react'
PromiseToSetState = require '../lib/promise-to-set-state'
auth = require 'panoptes-client/lib/auth'
Translate = require 'react-translate-component'
LoadingIndicator = require '../components/loading-indicator'
debounce = require 'debounce'
apiClient = require 'panoptes-client/lib/api-client'
REMOTE_CHECK_DELAY = 1000
MIN_PASSWORD_LENGTH = 8
counterpart.registerTranslations 'en',
registerForm:
required: 'Required'
looksGood: 'Looks good'
userName: 'User name'
badChars: "Only letters, numbers, '.', '_', and '-'."
nameConflict: 'That username is taken'
forgotPassword: 'Forget your password?'
password: '<PASSWORD>'
passwordTooShort: '<PASSWORD>'
confirmPassword: '<PASSWORD>'
passwordsDontMatch: 'These don’t match'
passLooksGood: 'Looks good'
emailLooksGood: 'Looks good'
email: 'Email address'
emailConflict: 'An account with this address already exists'
realName: 'Real <NAME>'
whyRealName: 'We’ll use this to give you credit in scientific papers, posters, etc'
agreeToPrivacyPolicy: 'You agree to our %(link)s (required)'
privacyPolicy: 'privacy policy'
okayToEmail: 'It’s okay to send me email every once in a while.'
betaTester: 'I’d like to help test new projects, and be emailed when they’re available.'
register: 'Register'
alreadySignedIn: 'Signed in as %(name)s'
signOut: 'Sign out'
counterpart.registerTranslations 'es',
registerForm:
required: 'Requerido'
looksGood: 'Nombre de usuario disponible'
userName: 'Nombre de usuario'
badChars: "Sólo letras, números, '.', '_', y '-'."
nameConflict: 'El nombre de usuario ya está en uso'
forgotPassword: '<PASSWORD>¿Ol<PASSWORD>ó su contraseña?'
password: '<PASSWORD>'
passwordTooShort: 'Debe ser de al menos 8 caracteres de longitud'
confirmPassword: '<PASSWORD>'
passwordsDontMatch: 'Las contraseñas no coinciden'
passLooksGood: 'OK'
emailLooksGood: 'OK'
email: 'Dirección de correo electrónico'
emailConflict: 'Una cuenta con esta dirección de correo ya existe'
realName: '<NAME>'
whyRealName: 'Vamos a usarlo para darte crédito en publicaciones científicas, posters, etc'
agreeToPrivacyPolicy: 'Estás de acuerdo con nuestras %(link)s (requerido)'
privacyPolicy: 'políticas de privacidad'
okayToEmail: 'Estoy de acuerdo con recibir correos electrónicos de vez en cuando.'
betaTester: 'Me gustaría ayudar a probar nuevos proyectos, y que se me envíe un correo electrónico cuando estén disponubles'
register: 'Registrarse'
alreadySignedIn: 'Sesión iniciada como %(name)s'
signOut: 'Cerrar sesión'
module.exports = React.createClass
displayName: 'RegisterForm'
mixins: [PromiseToSetState]
getDefaultProps: ->
project: {}
getInitialState: ->
badNameChars: null
nameConflict: null
passwordTooShort: null
passwordsDontMatch: null
emailConflict: null
agreedToPrivacyPolicy: null
error: null
render: ->
{badNameChars, nameConflict, passwordTooShort, passwordsDontMatch, emailConflict} = @state
<form method="POST" onSubmit={@handleSubmit}>
<label>
<span className="columns-container inline spread">
<Translate content="registerForm.userName" />
{if badNameChars?.length > 0
<Translate className="form-help error" content="registerForm.badChars" />
else if "nameConflict" of @state.pending
<LoadingIndicator />
else if nameConflict?
if nameConflict
<span className="form-help error">
<Translate content="registerForm.nameConflict" />{' '}
<a href="#{document.baseURI.slice(0, -1)}/reset-password" onClick={@props.onSuccess}>
<Translate content="registerForm.forgotPassword" />
</a>
</span>
else
<span className="form-help success">
<Translate content="registerForm.looksGood" />
</span>}
</span>
<input type="text" ref="name" className="standard-input full" disabled={@props.user?} autoFocus onChange={@handleNameChange} />
</label>
<br />
<label>
<span className="columns-container inline spread">
<Translate content="registerForm.password" />
{if passwordTooShort
<Translate className="form-help error" content="registerForm.passwordTooShort" />}
</span>
<input type="password" ref="password" className="standard-input full" disabled={@props.user?} onChange={@handlePasswordChange} />
</label>
<br />
<label>
<span className="columns-container inline spread">
<Translate content="registerForm.confirmPassword" /><br />
{if passwordsDontMatch?
if passwordsDontMatch
<Translate className="form-help error" content="registerForm.passwordsDontMatch" />
else if not passwordTooShort
<Translate className="form-help success" content="registerForm.passLooksGood" />}
</span>
<input type="password" ref="confirmedPassword" className="standard-input full" disabled={@state.props?} onChange={@handlePasswordChange} />
</label>
<br />
<label>
<span className="columns-container inline spread">
<Translate content="registerForm.email" />
{if 'emailConflict' of @state.pending
<LoadingIndicator />
else if emailConflict?
if emailConflict
<span className="form-help error">
<Translate content="registerForm.emailConflict" />{' '}
<a href="#{document.baseURI.slice(0, -1)}/reset-password" onClick={@props.onSuccess}>
<Translate content="registerForm.forgotPassword" />
</a>
</span>
else
<Translate className="form-help success" content="registerForm.emailLooksGood" />
else
<Translate className="form-help info" content="registerForm.required" />}
</span>
<input type="text" ref="email" className="standard-input full" disabled={@state.props?} onChange={@handleEmailChange} />
</label>
<br />
<label>
<span className="columns-container inline spread">
<Translate content="registerForm.realName" />
</span>
<input type="text" ref="realName" className="standard-input full" disabled={@props.user?} />
<Translate component="span" className="form-help info" content="registerForm.whyRealName" />
</label>
<br />
<br />
<label>
<input type="checkbox" ref="agreesToPrivacyPolicy" disabled={@props.user?} onChange={@handlePrivacyPolicyChange} />
{privacyPolicyLink = <a target="_blank" href="#{document.baseURI.slice(0, -1)}/privacy"><Translate content="registerForm.privacyPolicy" /></a>; null}
<Translate component="span" content="registerForm.agreeToPrivacyPolicy" link={privacyPolicyLink} />
</label>
<br />
<br />
<label>
<input type="checkbox" ref="okayToEmail" defaultChecked={true} disabled={@props.user?} onChange={@forceUpdate.bind this, null} />
<Translate component="span" content="registerForm.okayToEmail" />
</label><br />
<label>
<input type="checkbox" ref="betaTester" disabled={@props.user?} onChange={@forceUpdate.bind this, null} />
<Translate component="span" content="registerForm.betaTester" />
</label><br />
<p style={textAlign: 'center'}>
{if 'user' of @state.pending
<LoadingIndicator />
else if @props.user?
<span className="form-help warning">
<Translate content="registerForm.alreadySignedIn" name={@props.user.login} />{' '}
<button type="button" className="minor-button" onClick={@handleSignOut}><Translate content="registerForm.signOut" /></button>
</span>
else if @state.error?
<span className="form-help error">{@state.error.toString()}</span>
else
<span> </span>}
</p>
<div>
<button type="submit" className="standard-button full" disabled={not @isFormValid() or Object.keys(@state.pending).length isnt 0 or @props.user?}>
<Translate content="registerForm.register" />
</button>
</div>
</form>
handleNameChange: ->
name = @refs.name.value
exists = name.length isnt 0
badChars = (char for char in name.split('') when char.match(/[\w\-\.\ \']/) is null)
@setState
badNameChars: badChars
nameConflict: null
nameExists: exists
if exists and badChars.length is 0
@debouncedCheckForNameConflict ?= debounce @checkForNameConflict, REMOTE_CHECK_DELAY
@debouncedCheckForNameConflict name
debouncedCheckForNameConflict: null
checkForNameConflict: (username) ->
@promiseToSetState nameConflict: auth.register(login: username).catch (error) ->
error.message.match(/login(.+)taken/mi) ? false
handlePasswordChange: ->
password = @refs.password.value
confirmedPassword = @refs.confirmedPassword.value
exists = password.length isnt 0
longEnough = password.length >= MIN_PASSWORD_LENGTH
asLong = confirmedPassword.length >= password.length
matches = password is confirmedPassword
@setState
passwordTooShort: if exists then not longEnough
passwordsDontMatch: if exists and asLong then not matches
handleEmailChange: ->
@promiseToSetState emailConflict: Promise.resolve null # Cancel any existing request.
email = @refs.email.value
if email.match /.+@.+\..+/
@debouncedCheckForEmailConflict ?= debounce @checkForEmailConflict, REMOTE_CHECK_DELAY
@debouncedCheckForEmailConflict email
debouncedCheckForEmailConflict: null
checkForEmailConflict: (email) ->
@promiseToSetState emailConflict: auth.register({email}).catch (error) ->
error.message.match(/email(.+)taken/mi) ? false
handlePrivacyPolicyChange: ->
@setState agreesToPrivacyPolicy: @refs.agreesToPrivacyPolicy.checked
isFormValid: ->
{badNameChars, nameConflict, passwordsDontMatch, emailConflict, agreesToPrivacyPolicy, nameExists} = @state
badNameChars?.length is 0 and not nameConflict and not passwordsDontMatch and not emailConflict and nameExists and agreesToPrivacyPolicy
handleSubmit: (e) ->
e.preventDefault()
login = @refs.name.value
password =<PASSWORD> @refs.<PASSWORD>.value
email = @refs.email.value
credited_name = @refs.realName.value
global_email_communication = @refs.okayToEmail.checked
project_email_communication = global_email_communication
beta_email_communication = @refs.betaTester.checked
project_id = @props.project?.id
@setState error: null
@props.onSubmit?()
auth.register {login, password, email, credited_name, project_email_communication, global_email_communication, project_id, beta_email_communication}
.then =>
@props.onSuccess? arguments...
.catch (error) =>
@setState {error}
@props.onFailure? arguments...
handleSignOut: ->
auth.signOut()
| true | counterpart = require 'counterpart'
React = require 'react'
PromiseToSetState = require '../lib/promise-to-set-state'
auth = require 'panoptes-client/lib/auth'
Translate = require 'react-translate-component'
LoadingIndicator = require '../components/loading-indicator'
debounce = require 'debounce'
apiClient = require 'panoptes-client/lib/api-client'
REMOTE_CHECK_DELAY = 1000
MIN_PASSWORD_LENGTH = 8
counterpart.registerTranslations 'en',
registerForm:
required: 'Required'
looksGood: 'Looks good'
userName: 'User name'
badChars: "Only letters, numbers, '.', '_', and '-'."
nameConflict: 'That username is taken'
forgotPassword: 'Forget your password?'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
passwordTooShort: 'PI:PASSWORD:<PASSWORD>END_PI'
confirmPassword: 'PI:PASSWORD:<PASSWORD>END_PI'
passwordsDontMatch: 'These don’t match'
passLooksGood: 'Looks good'
emailLooksGood: 'Looks good'
email: 'Email address'
emailConflict: 'An account with this address already exists'
realName: 'Real PI:NAME:<NAME>END_PI'
whyRealName: 'We’ll use this to give you credit in scientific papers, posters, etc'
agreeToPrivacyPolicy: 'You agree to our %(link)s (required)'
privacyPolicy: 'privacy policy'
okayToEmail: 'It’s okay to send me email every once in a while.'
betaTester: 'I’d like to help test new projects, and be emailed when they’re available.'
register: 'Register'
alreadySignedIn: 'Signed in as %(name)s'
signOut: 'Sign out'
counterpart.registerTranslations 'es',
registerForm:
required: 'Requerido'
looksGood: 'Nombre de usuario disponible'
userName: 'Nombre de usuario'
badChars: "Sólo letras, números, '.', '_', y '-'."
nameConflict: 'El nombre de usuario ya está en uso'
forgotPassword: 'PI:PASSWORD:<PASSWORD>END_PI¿OlPI:PASSWORD:<PASSWORD>END_PIó su contraseña?'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
passwordTooShort: 'Debe ser de al menos 8 caracteres de longitud'
confirmPassword: 'PI:PASSWORD:<PASSWORD>END_PI'
passwordsDontMatch: 'Las contraseñas no coinciden'
passLooksGood: 'OK'
emailLooksGood: 'OK'
email: 'Dirección de correo electrónico'
emailConflict: 'Una cuenta con esta dirección de correo ya existe'
realName: 'PI:NAME:<NAME>END_PI'
whyRealName: 'Vamos a usarlo para darte crédito en publicaciones científicas, posters, etc'
agreeToPrivacyPolicy: 'Estás de acuerdo con nuestras %(link)s (requerido)'
privacyPolicy: 'políticas de privacidad'
okayToEmail: 'Estoy de acuerdo con recibir correos electrónicos de vez en cuando.'
betaTester: 'Me gustaría ayudar a probar nuevos proyectos, y que se me envíe un correo electrónico cuando estén disponubles'
register: 'Registrarse'
alreadySignedIn: 'Sesión iniciada como %(name)s'
signOut: 'Cerrar sesión'
module.exports = React.createClass
displayName: 'RegisterForm'
mixins: [PromiseToSetState]
getDefaultProps: ->
project: {}
getInitialState: ->
badNameChars: null
nameConflict: null
passwordTooShort: null
passwordsDontMatch: null
emailConflict: null
agreedToPrivacyPolicy: null
error: null
render: ->
{badNameChars, nameConflict, passwordTooShort, passwordsDontMatch, emailConflict} = @state
<form method="POST" onSubmit={@handleSubmit}>
<label>
<span className="columns-container inline spread">
<Translate content="registerForm.userName" />
{if badNameChars?.length > 0
<Translate className="form-help error" content="registerForm.badChars" />
else if "nameConflict" of @state.pending
<LoadingIndicator />
else if nameConflict?
if nameConflict
<span className="form-help error">
<Translate content="registerForm.nameConflict" />{' '}
<a href="#{document.baseURI.slice(0, -1)}/reset-password" onClick={@props.onSuccess}>
<Translate content="registerForm.forgotPassword" />
</a>
</span>
else
<span className="form-help success">
<Translate content="registerForm.looksGood" />
</span>}
</span>
<input type="text" ref="name" className="standard-input full" disabled={@props.user?} autoFocus onChange={@handleNameChange} />
</label>
<br />
<label>
<span className="columns-container inline spread">
<Translate content="registerForm.password" />
{if passwordTooShort
<Translate className="form-help error" content="registerForm.passwordTooShort" />}
</span>
<input type="password" ref="password" className="standard-input full" disabled={@props.user?} onChange={@handlePasswordChange} />
</label>
<br />
<label>
<span className="columns-container inline spread">
<Translate content="registerForm.confirmPassword" /><br />
{if passwordsDontMatch?
if passwordsDontMatch
<Translate className="form-help error" content="registerForm.passwordsDontMatch" />
else if not passwordTooShort
<Translate className="form-help success" content="registerForm.passLooksGood" />}
</span>
<input type="password" ref="confirmedPassword" className="standard-input full" disabled={@state.props?} onChange={@handlePasswordChange} />
</label>
<br />
<label>
<span className="columns-container inline spread">
<Translate content="registerForm.email" />
{if 'emailConflict' of @state.pending
<LoadingIndicator />
else if emailConflict?
if emailConflict
<span className="form-help error">
<Translate content="registerForm.emailConflict" />{' '}
<a href="#{document.baseURI.slice(0, -1)}/reset-password" onClick={@props.onSuccess}>
<Translate content="registerForm.forgotPassword" />
</a>
</span>
else
<Translate className="form-help success" content="registerForm.emailLooksGood" />
else
<Translate className="form-help info" content="registerForm.required" />}
</span>
<input type="text" ref="email" className="standard-input full" disabled={@state.props?} onChange={@handleEmailChange} />
</label>
<br />
<label>
<span className="columns-container inline spread">
<Translate content="registerForm.realName" />
</span>
<input type="text" ref="realName" className="standard-input full" disabled={@props.user?} />
<Translate component="span" className="form-help info" content="registerForm.whyRealName" />
</label>
<br />
<br />
<label>
<input type="checkbox" ref="agreesToPrivacyPolicy" disabled={@props.user?} onChange={@handlePrivacyPolicyChange} />
{privacyPolicyLink = <a target="_blank" href="#{document.baseURI.slice(0, -1)}/privacy"><Translate content="registerForm.privacyPolicy" /></a>; null}
<Translate component="span" content="registerForm.agreeToPrivacyPolicy" link={privacyPolicyLink} />
</label>
<br />
<br />
<label>
<input type="checkbox" ref="okayToEmail" defaultChecked={true} disabled={@props.user?} onChange={@forceUpdate.bind this, null} />
<Translate component="span" content="registerForm.okayToEmail" />
</label><br />
<label>
<input type="checkbox" ref="betaTester" disabled={@props.user?} onChange={@forceUpdate.bind this, null} />
<Translate component="span" content="registerForm.betaTester" />
</label><br />
<p style={textAlign: 'center'}>
{if 'user' of @state.pending
<LoadingIndicator />
else if @props.user?
<span className="form-help warning">
<Translate content="registerForm.alreadySignedIn" name={@props.user.login} />{' '}
<button type="button" className="minor-button" onClick={@handleSignOut}><Translate content="registerForm.signOut" /></button>
</span>
else if @state.error?
<span className="form-help error">{@state.error.toString()}</span>
else
<span> </span>}
</p>
<div>
<button type="submit" className="standard-button full" disabled={not @isFormValid() or Object.keys(@state.pending).length isnt 0 or @props.user?}>
<Translate content="registerForm.register" />
</button>
</div>
</form>
handleNameChange: ->
name = @refs.name.value
exists = name.length isnt 0
badChars = (char for char in name.split('') when char.match(/[\w\-\.\ \']/) is null)
@setState
badNameChars: badChars
nameConflict: null
nameExists: exists
if exists and badChars.length is 0
@debouncedCheckForNameConflict ?= debounce @checkForNameConflict, REMOTE_CHECK_DELAY
@debouncedCheckForNameConflict name
debouncedCheckForNameConflict: null
checkForNameConflict: (username) ->
@promiseToSetState nameConflict: auth.register(login: username).catch (error) ->
error.message.match(/login(.+)taken/mi) ? false
handlePasswordChange: ->
password = @refs.password.value
confirmedPassword = @refs.confirmedPassword.value
exists = password.length isnt 0
longEnough = password.length >= MIN_PASSWORD_LENGTH
asLong = confirmedPassword.length >= password.length
matches = password is confirmedPassword
@setState
passwordTooShort: if exists then not longEnough
passwordsDontMatch: if exists and asLong then not matches
handleEmailChange: ->
@promiseToSetState emailConflict: Promise.resolve null # Cancel any existing request.
email = @refs.email.value
if email.match /.+@.+\..+/
@debouncedCheckForEmailConflict ?= debounce @checkForEmailConflict, REMOTE_CHECK_DELAY
@debouncedCheckForEmailConflict email
debouncedCheckForEmailConflict: null
checkForEmailConflict: (email) ->
@promiseToSetState emailConflict: auth.register({email}).catch (error) ->
error.message.match(/email(.+)taken/mi) ? false
handlePrivacyPolicyChange: ->
@setState agreesToPrivacyPolicy: @refs.agreesToPrivacyPolicy.checked
isFormValid: ->
{badNameChars, nameConflict, passwordsDontMatch, emailConflict, agreesToPrivacyPolicy, nameExists} = @state
badNameChars?.length is 0 and not nameConflict and not passwordsDontMatch and not emailConflict and nameExists and agreesToPrivacyPolicy
handleSubmit: (e) ->
e.preventDefault()
login = @refs.name.value
password =PI:PASSWORD:<PASSWORD>END_PI @refs.PI:PASSWORD:<PASSWORD>END_PI.value
email = @refs.email.value
credited_name = @refs.realName.value
global_email_communication = @refs.okayToEmail.checked
project_email_communication = global_email_communication
beta_email_communication = @refs.betaTester.checked
project_id = @props.project?.id
@setState error: null
@props.onSubmit?()
auth.register {login, password, email, credited_name, project_email_communication, global_email_communication, project_id, beta_email_communication}
.then =>
@props.onSuccess? arguments...
.catch (error) =>
@setState {error}
@props.onFailure? arguments...
handleSignOut: ->
auth.signOut()
|
[
{
"context": " json: true, qs: { q: args, api_key: 'dc6zaTOxFJmzC' }\n })\n return msg.reply 'No ",
"end": 3358,
"score": 0.5229266881942749,
"start": 3356,
"tag": "KEY",
"value": "za"
}
] | modules/image.coffee | ChetAlv/TamagoMusic | 27 | Chance = require 'chance'
request = require 'request'
# sorry about this, i lost a bet
tumblr = require('tumblr.js').createClient { consumer_key: process.env.TUMBLR_CONSUMER_KEY }
# Google Image Search API
CSE = require('request-promise').defaults {
baseUrl: 'https://www.googleapis.com/customsearch/'
simple: true
}
# Imgur fallback
Imgur = require('request-promise').defaults {
baseUrl: 'https://api.imgur.com/3/'
headers:
Authorization: "Client-ID #{process.env.IMGUR_KEY}"
simple: true
}
# Giphy
Giphy = require('request-promise').defaults {
baseUrl: 'http://api.giphy.com/v1/gifs/'
simple: true
}
class ImageModule extends BotModule
init: ->
chance = new Chance()
@registerCommand 'img', {
allowDM: true
aliases: ['rimg','imgn','rimgn']
includeCommandNameInArgs: true
}, ({ msg, args, s, l })=>
random = args[0].indexOf('rimg') >= 0
nsfw = (s.allowNSFW or msg.channel.nsfw) and args[0].indexOf('imgn') >= 0
# Find the image
try
r = await @getImages(args[1], nsfw)
return msg.reply l.generic.noResults unless r.items?
# Pick the first result by default
image = r.items[0]
# Pick a random result if using the random command
image = chance.pickone r.items if random
# Send the image
msg.reply '', embed: {
title: l.generic.sauceBtn
url: image.image.contextLink
image: { url: image.link }
}
catch err
if err.statusCode is 403
return msg.reply l.image.dailyLimit
msg.reply l.generic.error
@registerCommand 'imgur', ({ msg, args, l, s })=>
try
# Find something on imgur
results = await Imgur.get('/gallery/search/top/0/', json: true, qs: {
q: args
})
# Random by default
if results.success and results.data
nsfw = (s.allowNSFW or msg.channel.nsfw)
image = chance.pickone results.data.filter (i)=>
not i.is_album and not i.is_ad and (nsfw or not i.nsfw)
msg.reply '', embed: {
title: l.generic.sauceBtn
url: "https://imgur.com/#{image.id}"
image: { url: image.link }
}
else msg.reply l.generic.noResults
catch err
if err.statusCode is 403
return msg.reply l.image.dailyLimit
if err.statusCode is 404
return msg.reply l.generic.noResults
msg.reply l.generic.error
@registerCommand 'tumblr', ({ msg, args, l })=>
# Query the tumblr tag
tumblr.taggedPosts args, (err, data)=>
return msg.reply l.generic.error if err
# Filter only image results
try
results = data.filter((r)=> r.type is 'photo')
return msg.reply l.generic.noResults unless results.length
# Pick a random image
image = chance.pickone results
msg.reply '', embed: {
title: l.generic.sauceBtn
url: image.post_url
image: { url: image.photos[0].original_size.url }
}
catch e
Core.log e,2
msg.reply l.generic.error
@registerCommand 'giphy', { aliases: ['gif'], allowDM: true }, ({ msg, args, locale })=>
try
{ data } = await Giphy.get('search', {
json: true, qs: { q: args, api_key: 'dc6zaTOxFJmzC' }
})
return msg.reply 'No results' unless data.length
msg.reply chance.pickone(data).bitly_url
getImages: (query, nsfw)->
safe = 'high'
safe = 'off' if nsfw
# Fetch the results straight from Google
result = await CSE.get 'v1', { json: true, qs: {
searchType: 'image'
q: query
cx: process.env.GOOGLE_CX
key: process.env.GOOGLE_KEY
safe
} }
return result
module.exports = ImageModule
| 219176 | Chance = require 'chance'
request = require 'request'
# sorry about this, i lost a bet
tumblr = require('tumblr.js').createClient { consumer_key: process.env.TUMBLR_CONSUMER_KEY }
# Google Image Search API
CSE = require('request-promise').defaults {
baseUrl: 'https://www.googleapis.com/customsearch/'
simple: true
}
# Imgur fallback
Imgur = require('request-promise').defaults {
baseUrl: 'https://api.imgur.com/3/'
headers:
Authorization: "Client-ID #{process.env.IMGUR_KEY}"
simple: true
}
# Giphy
Giphy = require('request-promise').defaults {
baseUrl: 'http://api.giphy.com/v1/gifs/'
simple: true
}
class ImageModule extends BotModule
init: ->
chance = new Chance()
@registerCommand 'img', {
allowDM: true
aliases: ['rimg','imgn','rimgn']
includeCommandNameInArgs: true
}, ({ msg, args, s, l })=>
random = args[0].indexOf('rimg') >= 0
nsfw = (s.allowNSFW or msg.channel.nsfw) and args[0].indexOf('imgn') >= 0
# Find the image
try
r = await @getImages(args[1], nsfw)
return msg.reply l.generic.noResults unless r.items?
# Pick the first result by default
image = r.items[0]
# Pick a random result if using the random command
image = chance.pickone r.items if random
# Send the image
msg.reply '', embed: {
title: l.generic.sauceBtn
url: image.image.contextLink
image: { url: image.link }
}
catch err
if err.statusCode is 403
return msg.reply l.image.dailyLimit
msg.reply l.generic.error
@registerCommand 'imgur', ({ msg, args, l, s })=>
try
# Find something on imgur
results = await Imgur.get('/gallery/search/top/0/', json: true, qs: {
q: args
})
# Random by default
if results.success and results.data
nsfw = (s.allowNSFW or msg.channel.nsfw)
image = chance.pickone results.data.filter (i)=>
not i.is_album and not i.is_ad and (nsfw or not i.nsfw)
msg.reply '', embed: {
title: l.generic.sauceBtn
url: "https://imgur.com/#{image.id}"
image: { url: image.link }
}
else msg.reply l.generic.noResults
catch err
if err.statusCode is 403
return msg.reply l.image.dailyLimit
if err.statusCode is 404
return msg.reply l.generic.noResults
msg.reply l.generic.error
@registerCommand 'tumblr', ({ msg, args, l })=>
# Query the tumblr tag
tumblr.taggedPosts args, (err, data)=>
return msg.reply l.generic.error if err
# Filter only image results
try
results = data.filter((r)=> r.type is 'photo')
return msg.reply l.generic.noResults unless results.length
# Pick a random image
image = chance.pickone results
msg.reply '', embed: {
title: l.generic.sauceBtn
url: image.post_url
image: { url: image.photos[0].original_size.url }
}
catch e
Core.log e,2
msg.reply l.generic.error
@registerCommand 'giphy', { aliases: ['gif'], allowDM: true }, ({ msg, args, locale })=>
try
{ data } = await Giphy.get('search', {
json: true, qs: { q: args, api_key: 'dc6<KEY>TOxFJmzC' }
})
return msg.reply 'No results' unless data.length
msg.reply chance.pickone(data).bitly_url
getImages: (query, nsfw)->
safe = 'high'
safe = 'off' if nsfw
# Fetch the results straight from Google
result = await CSE.get 'v1', { json: true, qs: {
searchType: 'image'
q: query
cx: process.env.GOOGLE_CX
key: process.env.GOOGLE_KEY
safe
} }
return result
module.exports = ImageModule
| true | Chance = require 'chance'
request = require 'request'
# sorry about this, i lost a bet
tumblr = require('tumblr.js').createClient { consumer_key: process.env.TUMBLR_CONSUMER_KEY }
# Google Image Search API
CSE = require('request-promise').defaults {
baseUrl: 'https://www.googleapis.com/customsearch/'
simple: true
}
# Imgur fallback
Imgur = require('request-promise').defaults {
baseUrl: 'https://api.imgur.com/3/'
headers:
Authorization: "Client-ID #{process.env.IMGUR_KEY}"
simple: true
}
# Giphy
Giphy = require('request-promise').defaults {
baseUrl: 'http://api.giphy.com/v1/gifs/'
simple: true
}
class ImageModule extends BotModule
init: ->
chance = new Chance()
@registerCommand 'img', {
allowDM: true
aliases: ['rimg','imgn','rimgn']
includeCommandNameInArgs: true
}, ({ msg, args, s, l })=>
random = args[0].indexOf('rimg') >= 0
nsfw = (s.allowNSFW or msg.channel.nsfw) and args[0].indexOf('imgn') >= 0
# Find the image
try
r = await @getImages(args[1], nsfw)
return msg.reply l.generic.noResults unless r.items?
# Pick the first result by default
image = r.items[0]
# Pick a random result if using the random command
image = chance.pickone r.items if random
# Send the image
msg.reply '', embed: {
title: l.generic.sauceBtn
url: image.image.contextLink
image: { url: image.link }
}
catch err
if err.statusCode is 403
return msg.reply l.image.dailyLimit
msg.reply l.generic.error
@registerCommand 'imgur', ({ msg, args, l, s })=>
try
# Find something on imgur
results = await Imgur.get('/gallery/search/top/0/', json: true, qs: {
q: args
})
# Random by default
if results.success and results.data
nsfw = (s.allowNSFW or msg.channel.nsfw)
image = chance.pickone results.data.filter (i)=>
not i.is_album and not i.is_ad and (nsfw or not i.nsfw)
msg.reply '', embed: {
title: l.generic.sauceBtn
url: "https://imgur.com/#{image.id}"
image: { url: image.link }
}
else msg.reply l.generic.noResults
catch err
if err.statusCode is 403
return msg.reply l.image.dailyLimit
if err.statusCode is 404
return msg.reply l.generic.noResults
msg.reply l.generic.error
@registerCommand 'tumblr', ({ msg, args, l })=>
# Query the tumblr tag
tumblr.taggedPosts args, (err, data)=>
return msg.reply l.generic.error if err
# Filter only image results
try
results = data.filter((r)=> r.type is 'photo')
return msg.reply l.generic.noResults unless results.length
# Pick a random image
image = chance.pickone results
msg.reply '', embed: {
title: l.generic.sauceBtn
url: image.post_url
image: { url: image.photos[0].original_size.url }
}
catch e
Core.log e,2
msg.reply l.generic.error
@registerCommand 'giphy', { aliases: ['gif'], allowDM: true }, ({ msg, args, locale })=>
try
{ data } = await Giphy.get('search', {
json: true, qs: { q: args, api_key: 'dc6PI:KEY:<KEY>END_PITOxFJmzC' }
})
return msg.reply 'No results' unless data.length
msg.reply chance.pickone(data).bitly_url
getImages: (query, nsfw)->
safe = 'high'
safe = 'off' if nsfw
# Fetch the results straight from Google
result = await CSE.get 'v1', { json: true, qs: {
searchType: 'image'
q: query
cx: process.env.GOOGLE_CX
key: process.env.GOOGLE_KEY
safe
} }
return result
module.exports = ImageModule
|
[
{
"context": "bluConfig =\n uuid: 'user-uuid'\n token: 'user-token'\n hostname: 'localhost'\n port: 0xd00d\n ",
"end": 741,
"score": 0.9076917171478271,
"start": 731,
"tag": "PASSWORD",
"value": "user-token"
},
{
"context": " .reply 201, uuid: \"inquisitor-uuid\", token: \"inquisitor-token\"\n\n beforeEach 'mock getMonitoredDevices, out o",
"end": 1349,
"score": 0.926666259765625,
"start": 1333,
"tag": "PASSWORD",
"value": "inquisitor-token"
}
] | test/connect-spec.coffee | octoblu/inquisitor | 0 | {afterEach, beforeEach, describe, it} = global
{expect} = require 'chai'
sinon = require 'sinon'
URL = require 'url'
_ = require 'lodash'
enableDestroy = require 'server-destroy'
shmock = require 'shmock'
SocketIO = require 'socket.io'
Inquisitor = require '..'
describe 'connect', ->
beforeEach 'meshblu', ->
@meshblu = shmock 0xd00d
enableDestroy(@meshblu)
afterEach (done) ->
@meshblu.destroy done
beforeEach 'setup socket.io', ->
@firehoseServer = new SocketIO 0xcaf1
afterEach 'close socket.io', (done) ->
_.delay =>
@firehoseServer.close()
done()
, 50
beforeEach ->
meshbluConfig =
uuid: 'user-uuid'
token: 'user-token'
hostname: 'localhost'
port: 0xd00d
protocol: 'http'
firehoseConfig =
hostname: 'localhost'
port: 0xcaf1
protocol: 'http'
uuid = 'inquisitor-uuid'
@userAuth = new Buffer('user-uuid:user-token').toString 'base64'
@sut = new Inquisitor {meshbluConfig, firehoseConfig, uuid}
it 'should exist', ->
expect(@sut).to.exist
describe '->connect', ->
beforeEach ->
@meshblu
.post '/devices/inquisitor-uuid/tokens'
.set 'Authorization', "Basic #{@userAuth}"
.reply 201, uuid: "inquisitor-uuid", token: "inquisitor-token"
beforeEach 'mock getMonitoredDevices, out of laziness', ->
@deviceMap =
'device-1':
device: { uuid: 'device-1', statusDevice: 'status-device', otherProperty: false }
statusDevice: 'status-device'
errors: ['look-an-error']
'device-2':
device: { uuid: 'device-2', errors: ['yet-another-error'] }
statusDevice: 'device-2'
errors: ['yet-another-error']
@sut.getMonitoredDevices = sinon.stub().yields null, @deviceMap
beforeEach (done) ->
@firehoseServer.on 'connection', (@socket) =>
{@pathname, @query} = URL.parse @socket.client.request.url, true
@uuid = @socket.client.request.headers['x-meshblu-uuid']
@token = @socket.client.request.headers['x-meshblu-token']
done()
@sut.connect =>
return null
afterEach (done) ->
@sut.stop done
return null
it 'should connect', ->
expect(@socket).to.exist
expect(@pathname).to.equal '/socket.io/v1/inquisitor-uuid/'
it 'should pass along the auth info', ->
expect(@uuid).to.equal 'inquisitor-uuid'
expect(@token).to.equal 'inquisitor-token'
expect(@query.uuid).to.equal 'inquisitor-uuid'
expect(@query.token).to.equal 'inquisitor-token'
describe 'when we get a config update from the firehose', ->
beforeEach (done) ->
@sut.on 'status-update', (@message) => done()
changeEvent =
metadata:
route: [
{
from: "device-2"
to: "inquisitor-uuid"
type: "configure.sent"
}
{
from: "inquisitor-uuid"
to: "inquisitor-uuid"
type: "configure.sent"
}
]
rawData: JSON.stringify(
uuid: "device-2"
errors: [
message: '#watchit'
code: 101
]
)
@socket.emit 'message', changeEvent
it 'should emit a message in the right format', ->
expectedMessage =
uuid: 'device-2'
statusDevice: 'device-2'
errors: [
message: '#watchit'
code: 101
]
device:
uuid: "device-2"
errors: [
message: '#watchit'
code: 101
]
expect(@message).to.deep.equal expectedMessage
describe 'when we get a config update from the firehose from a status-device', ->
beforeEach (done) ->
@sut.on 'status-update', (@message) => done()
changeEvent =
metadata:
route: [
{
from: "status-device"
to: "inquisitor-uuid"
type: "configure.sent"
}
{
from: "inquisitor-uuid"
to: "inquisitor-uuid"
type: "configure.sent"
}
]
rawData: JSON.stringify(
uuid: "status-device"
errors: [
message: '#watchit'
code: 101
]
)
@socket.emit 'message', changeEvent
it 'should emit a message in the right format', ->
expectedMessage =
statusDevice: 'status-device'
uuid: 'device-1'
errors: [
message: '#watchit'
code: 101
]
device:
uuid: 'device-1'
statusDevice: 'status-device'
otherProperty: false
expect(@message).to.deep.equal expectedMessage
| 105183 | {afterEach, beforeEach, describe, it} = global
{expect} = require 'chai'
sinon = require 'sinon'
URL = require 'url'
_ = require 'lodash'
enableDestroy = require 'server-destroy'
shmock = require 'shmock'
SocketIO = require 'socket.io'
Inquisitor = require '..'
describe 'connect', ->
beforeEach 'meshblu', ->
@meshblu = shmock 0xd00d
enableDestroy(@meshblu)
afterEach (done) ->
@meshblu.destroy done
beforeEach 'setup socket.io', ->
@firehoseServer = new SocketIO 0xcaf1
afterEach 'close socket.io', (done) ->
_.delay =>
@firehoseServer.close()
done()
, 50
beforeEach ->
meshbluConfig =
uuid: 'user-uuid'
token: '<PASSWORD>'
hostname: 'localhost'
port: 0xd00d
protocol: 'http'
firehoseConfig =
hostname: 'localhost'
port: 0xcaf1
protocol: 'http'
uuid = 'inquisitor-uuid'
@userAuth = new Buffer('user-uuid:user-token').toString 'base64'
@sut = new Inquisitor {meshbluConfig, firehoseConfig, uuid}
it 'should exist', ->
expect(@sut).to.exist
describe '->connect', ->
beforeEach ->
@meshblu
.post '/devices/inquisitor-uuid/tokens'
.set 'Authorization', "Basic #{@userAuth}"
.reply 201, uuid: "inquisitor-uuid", token: "<PASSWORD>"
beforeEach 'mock getMonitoredDevices, out of laziness', ->
@deviceMap =
'device-1':
device: { uuid: 'device-1', statusDevice: 'status-device', otherProperty: false }
statusDevice: 'status-device'
errors: ['look-an-error']
'device-2':
device: { uuid: 'device-2', errors: ['yet-another-error'] }
statusDevice: 'device-2'
errors: ['yet-another-error']
@sut.getMonitoredDevices = sinon.stub().yields null, @deviceMap
beforeEach (done) ->
@firehoseServer.on 'connection', (@socket) =>
{@pathname, @query} = URL.parse @socket.client.request.url, true
@uuid = @socket.client.request.headers['x-meshblu-uuid']
@token = @socket.client.request.headers['x-meshblu-token']
done()
@sut.connect =>
return null
afterEach (done) ->
@sut.stop done
return null
it 'should connect', ->
expect(@socket).to.exist
expect(@pathname).to.equal '/socket.io/v1/inquisitor-uuid/'
it 'should pass along the auth info', ->
expect(@uuid).to.equal 'inquisitor-uuid'
expect(@token).to.equal 'inquisitor-token'
expect(@query.uuid).to.equal 'inquisitor-uuid'
expect(@query.token).to.equal 'inquisitor-token'
describe 'when we get a config update from the firehose', ->
beforeEach (done) ->
@sut.on 'status-update', (@message) => done()
changeEvent =
metadata:
route: [
{
from: "device-2"
to: "inquisitor-uuid"
type: "configure.sent"
}
{
from: "inquisitor-uuid"
to: "inquisitor-uuid"
type: "configure.sent"
}
]
rawData: JSON.stringify(
uuid: "device-2"
errors: [
message: '#watchit'
code: 101
]
)
@socket.emit 'message', changeEvent
it 'should emit a message in the right format', ->
expectedMessage =
uuid: 'device-2'
statusDevice: 'device-2'
errors: [
message: '#watchit'
code: 101
]
device:
uuid: "device-2"
errors: [
message: '#watchit'
code: 101
]
expect(@message).to.deep.equal expectedMessage
describe 'when we get a config update from the firehose from a status-device', ->
beforeEach (done) ->
@sut.on 'status-update', (@message) => done()
changeEvent =
metadata:
route: [
{
from: "status-device"
to: "inquisitor-uuid"
type: "configure.sent"
}
{
from: "inquisitor-uuid"
to: "inquisitor-uuid"
type: "configure.sent"
}
]
rawData: JSON.stringify(
uuid: "status-device"
errors: [
message: '#watchit'
code: 101
]
)
@socket.emit 'message', changeEvent
it 'should emit a message in the right format', ->
expectedMessage =
statusDevice: 'status-device'
uuid: 'device-1'
errors: [
message: '#watchit'
code: 101
]
device:
uuid: 'device-1'
statusDevice: 'status-device'
otherProperty: false
expect(@message).to.deep.equal expectedMessage
| true | {afterEach, beforeEach, describe, it} = global
{expect} = require 'chai'
sinon = require 'sinon'
URL = require 'url'
_ = require 'lodash'
enableDestroy = require 'server-destroy'
shmock = require 'shmock'
SocketIO = require 'socket.io'
Inquisitor = require '..'
describe 'connect', ->
beforeEach 'meshblu', ->
@meshblu = shmock 0xd00d
enableDestroy(@meshblu)
afterEach (done) ->
@meshblu.destroy done
beforeEach 'setup socket.io', ->
@firehoseServer = new SocketIO 0xcaf1
afterEach 'close socket.io', (done) ->
_.delay =>
@firehoseServer.close()
done()
, 50
beforeEach ->
meshbluConfig =
uuid: 'user-uuid'
token: 'PI:PASSWORD:<PASSWORD>END_PI'
hostname: 'localhost'
port: 0xd00d
protocol: 'http'
firehoseConfig =
hostname: 'localhost'
port: 0xcaf1
protocol: 'http'
uuid = 'inquisitor-uuid'
@userAuth = new Buffer('user-uuid:user-token').toString 'base64'
@sut = new Inquisitor {meshbluConfig, firehoseConfig, uuid}
it 'should exist', ->
expect(@sut).to.exist
describe '->connect', ->
beforeEach ->
@meshblu
.post '/devices/inquisitor-uuid/tokens'
.set 'Authorization', "Basic #{@userAuth}"
.reply 201, uuid: "inquisitor-uuid", token: "PI:PASSWORD:<PASSWORD>END_PI"
beforeEach 'mock getMonitoredDevices, out of laziness', ->
@deviceMap =
'device-1':
device: { uuid: 'device-1', statusDevice: 'status-device', otherProperty: false }
statusDevice: 'status-device'
errors: ['look-an-error']
'device-2':
device: { uuid: 'device-2', errors: ['yet-another-error'] }
statusDevice: 'device-2'
errors: ['yet-another-error']
@sut.getMonitoredDevices = sinon.stub().yields null, @deviceMap
beforeEach (done) ->
@firehoseServer.on 'connection', (@socket) =>
{@pathname, @query} = URL.parse @socket.client.request.url, true
@uuid = @socket.client.request.headers['x-meshblu-uuid']
@token = @socket.client.request.headers['x-meshblu-token']
done()
@sut.connect =>
return null
afterEach (done) ->
@sut.stop done
return null
it 'should connect', ->
expect(@socket).to.exist
expect(@pathname).to.equal '/socket.io/v1/inquisitor-uuid/'
it 'should pass along the auth info', ->
expect(@uuid).to.equal 'inquisitor-uuid'
expect(@token).to.equal 'inquisitor-token'
expect(@query.uuid).to.equal 'inquisitor-uuid'
expect(@query.token).to.equal 'inquisitor-token'
describe 'when we get a config update from the firehose', ->
beforeEach (done) ->
@sut.on 'status-update', (@message) => done()
changeEvent =
metadata:
route: [
{
from: "device-2"
to: "inquisitor-uuid"
type: "configure.sent"
}
{
from: "inquisitor-uuid"
to: "inquisitor-uuid"
type: "configure.sent"
}
]
rawData: JSON.stringify(
uuid: "device-2"
errors: [
message: '#watchit'
code: 101
]
)
@socket.emit 'message', changeEvent
it 'should emit a message in the right format', ->
expectedMessage =
uuid: 'device-2'
statusDevice: 'device-2'
errors: [
message: '#watchit'
code: 101
]
device:
uuid: "device-2"
errors: [
message: '#watchit'
code: 101
]
expect(@message).to.deep.equal expectedMessage
describe 'when we get a config update from the firehose from a status-device', ->
beforeEach (done) ->
@sut.on 'status-update', (@message) => done()
changeEvent =
metadata:
route: [
{
from: "status-device"
to: "inquisitor-uuid"
type: "configure.sent"
}
{
from: "inquisitor-uuid"
to: "inquisitor-uuid"
type: "configure.sent"
}
]
rawData: JSON.stringify(
uuid: "status-device"
errors: [
message: '#watchit'
code: 101
]
)
@socket.emit 'message', changeEvent
it 'should emit a message in the right format', ->
expectedMessage =
statusDevice: 'status-device'
uuid: 'device-1'
errors: [
message: '#watchit'
code: 101
]
device:
uuid: 'device-1'
statusDevice: 'status-device'
otherProperty: false
expect(@message).to.deep.equal expectedMessage
|
[
{
"context": " ->\n $http.post '/login',\n username: username\n password: password\n .success (da",
"end": 180,
"score": 0.9991062879562378,
"start": 172,
"tag": "USERNAME",
"value": "username"
},
{
"context": ",\n username: username\n password: password\n .success (data) ->\n Session.crea",
"end": 209,
"score": 0.997820258140564,
"start": 201,
"tag": "PASSWORD",
"value": "password"
},
{
"context": " $http.post '/api/users',\n username: username\n password: password\n .success (da",
"end": 549,
"score": 0.9984739422798157,
"start": 541,
"tag": "USERNAME",
"value": "username"
},
{
"context": ",\n username: username\n password: password\n .success (data) ->\n Session.crea",
"end": 578,
"score": 0.9971080422401428,
"start": 570,
"tag": "PASSWORD",
"value": "password"
}
] | src/scripts/services/UserService.coffee | zodoz/EC2Manager | 0 | angular.module 'EC2Manager'
.factory 'UserService', ($rootScope, $http, Session)->
login = (username, password, cb) ->
$http.post '/login',
username: username
password: password
.success (data) ->
Session.create data.id, data.user
cb null, data.user
.error (data, status, header, config) ->
Session.destroy()
cb data
#TODO find ways to report errors
signup = (username, password, cb) ->
$http.post '/api/users',
username: username
password: password
.success (data) ->
Session.create data.id, data.user
cb null, data.user
.error (data) ->
Session.destroy()
console.log 'signup failure: ', data
cb data
#TODO find ways to report errors
logout = ->
$http.post '/logout'
.success (data) ->
console.log 'logout success', data
Session.destroy()
.error (data) ->
console.log 'logout error', data
isLoggedIn = ->
!!Session.user
login: login
logout: logout
signup: signup
isLoggedIn: isLoggedIn
| 30632 | angular.module 'EC2Manager'
.factory 'UserService', ($rootScope, $http, Session)->
login = (username, password, cb) ->
$http.post '/login',
username: username
password: <PASSWORD>
.success (data) ->
Session.create data.id, data.user
cb null, data.user
.error (data, status, header, config) ->
Session.destroy()
cb data
#TODO find ways to report errors
signup = (username, password, cb) ->
$http.post '/api/users',
username: username
password: <PASSWORD>
.success (data) ->
Session.create data.id, data.user
cb null, data.user
.error (data) ->
Session.destroy()
console.log 'signup failure: ', data
cb data
#TODO find ways to report errors
logout = ->
$http.post '/logout'
.success (data) ->
console.log 'logout success', data
Session.destroy()
.error (data) ->
console.log 'logout error', data
isLoggedIn = ->
!!Session.user
login: login
logout: logout
signup: signup
isLoggedIn: isLoggedIn
| true | angular.module 'EC2Manager'
.factory 'UserService', ($rootScope, $http, Session)->
login = (username, password, cb) ->
$http.post '/login',
username: username
password: PI:PASSWORD:<PASSWORD>END_PI
.success (data) ->
Session.create data.id, data.user
cb null, data.user
.error (data, status, header, config) ->
Session.destroy()
cb data
#TODO find ways to report errors
signup = (username, password, cb) ->
$http.post '/api/users',
username: username
password: PI:PASSWORD:<PASSWORD>END_PI
.success (data) ->
Session.create data.id, data.user
cb null, data.user
.error (data) ->
Session.destroy()
console.log 'signup failure: ', data
cb data
#TODO find ways to report errors
logout = ->
$http.post '/logout'
.success (data) ->
console.log 'logout success', data
Session.destroy()
.error (data) ->
console.log 'logout error', data
isLoggedIn = ->
!!Session.user
login: login
logout: logout
signup: signup
isLoggedIn: isLoggedIn
|
[
{
"context": "{}\"\n\t\t\t\t\tfields: \"object:{}\"\n\t\t\tgroup:\n\t\t\t\tkeys: \"object:{_id:1}\"\n\t\t\t\tcondition: \"object:{}\"\n\t\t\t\tinitial: \"object:{",
"end": 7066,
"score": 0.986841082572937,
"start": 7051,
"tag": "KEY",
"value": "object:{_id:1}\""
},
{
"context": "ope: \"object: {}\"\n\t\t\tdistinct:\n\t\t\t\tkey: \"string:\\\"_id\\\"\"\n\t\t\t\tquery: \"object:{}\"\n\t\t\tcount:\n\t\t\t\tquery: \"o",
"end": 7801,
"score": 0.7206195592880249,
"start": 7799,
"tag": "KEY",
"value": "id"
}
] | lib/src_modules/models/Report.coffee | tifroz/macxplore | 0 | _ = require 'underscore'
MongoDoc = require 'macmodel'
events = require 'events'
Seq = require 'seq'
coffee = require 'coffeescript'
util = require 'util'
streamify = require "stream-array"
mr2FlatJson = require("helpers").streams.mr2FlatJson
logger = console
class Report extends MongoDoc
init: ->
#logger.info "OK initialized Report"
getTargetedCollection: (fn)->
if dbname = @_data.database and colname = @_data.collection
if collection = MongoDoc.db.databases[dbname]?.collections[colname]
fn?(null, collection)
if @_data._id is undefined
return fn?(new Error("Can't get collection without the report's _id"))
dbname = null
colname = null
self = @
Seq().seq ->
logger.debug "getTargetedCollection will fillFromStorage"
self.fillFromStorage this
.seq (r)->
logger.debug "getTargetedCollection will linkDatabaseIfExists"
data = r.data()
dbname = data.database
colname = data.collection
report = r
MongoDoc.db.linkDatabaseIfExists dbname, this
.seq ->
logger.debug "getTargetedCollection will return collection"
if collection = MongoDoc.db.databases[dbname]?.collections[colname]
fn?(null, collection)
else
fn?(new Error("Database #{dbname} could not be linked for #{colname} (#{_.keys(MongoDoc.db.databases[dbname].collections)})"))
.catch (boo)->
fn?(boo)
getParsedParameters: (qType)->
if qType is undefined
qType = "all"
if @_parsedParameters is undefined
@_parsedParameters = {}
if @_parsedParameters[qType]
return @_parsedParameters[qType]
else if @_parsedParameters.all?[qType]
return @_parsedParameters.all?[qType]
else
recursiveParse = (path, obj, result)->
for key, value of obj
if path is null
p = key
else
p = "#{path}.#{key}"
if _.isString value
separatorIndex = value.indexOf(":")
type = value.substring(0, separatorIndex)
cscript = value.substring(separatorIndex+1).trim()
if cscript.length > 0
try
jscript = coffee.compile cscript, bare: true
logger.debug "#{p} jscript: #{jscript}"
evaluated = undefined
eval "evaluated = #{jscript}"
catch err
err.message = "Error compiling #{p}: #{err.message}"
throw err
if evaluated isnt undefined
if evaluated isnt null
switch type
when 'function'
unless _.isFunction evaluated
throw new Error("Value for '#{p}' must evaluate to a function")
when 'number'
if isNaN evaluated
throw new Error("Value for '#{p}' must evaluate to a number")
when 'string'
unless _.isString evaluated
throw new Error("Value for '#{p}' must evaluate to a string")
result[key] = evaluated
else
result[key] = {}
recursiveParse("#{p}", value, result[key])
@_parsedParameters = {}
@_parsedParameters[qType] = {}
if qType is "all"
obj = @data().parameters
else
obj = @data().parameters[qType]
if not obj
throw new Error("No inputs for parameters of type '#{qType}'")
recursiveParse(null, obj, @_parsedParameters[qType])
return @_parsedParameters[qType]
getSampleCursor: (fn)->
self = @
Seq().seq ->
self.getTargetedCollection this
.seq (c)->
qType = self.data().type
try
params = self.getParsedParameters(qType)
catch boo
return fn?(boo)
selector = {}
options = {sort: {_id: -1}}
switch qType
when "find"
selector = params.selector
_.extend options, params.options
when "aggregate"
for cmd in params.pipeline
if cmd.$match
selector = cmd.$match
break
when "group"
selector = params.condition
when "count", "distinct"
selector = params.query
when "mapReduce"
selector = params.options.query
else
return fn?(new Error("getCursor() can't be used with queries of type '#{qType}'"))
if selector is undefined or selector is null
selector = {}
logger.debug util.format("SampleCursor with selector %j\nand options %j", selector, options)
cursor = c.find(selector, options)
fn?(null, cursor)
.catch (boo)->
fn?(boo)
getCursor: (fn)->
self = @
Seq().seq ->
self.getTargetedCollection this
.seq (c)->
qType = self.data().type
try
params = self.getParsedParameters(qType)
catch boo
return fn?(boo)
switch qType
when "find"
cursor = c.find(params.selector, params.options)
fn?(null, cursor)
when "aggregate"
cursor = c.aggregate(params.pipeline, {cursor: {batchSize:1}})
fn?(null, cursor)
else
fn?(new Error("getCursor() can't be used with queries of type '#{qType}'"))
.catch (boo)->
fn?(boo)
getStream: (fn)->
self = @
Seq().seq ->
logger.debug util.format("Will get targeted collection")
self.getTargetedCollection this
.seq (c)->
logger.debug util.format("OK have targeted collection")
qType = self.data().type
try
params = self.getParsedParameters(qType)
catch boo
return fn?(boo)
switch qType
when "group"
c.group params.keys, params.condition, params.initial, params.reduce, params.finalize, true, {}, (err, list)->
if err
fn?(err)
else
fn?(null, streamify(list))
when "mapReduce"
logger.debug util.format("mapReduce with map #{params.map}, reduce: #{params.reduce}, options keys: #{_.keys(params.options)}, options: %j", params.options)
c.mapReduce params.map, params.reduce, params.options, (err, list)->
if err
fn?(err)
else
fn?(null, streamify(list).pipe(mr2FlatJson()))
#c.mapReduce (->emit(this.locale,1)), (->return 1), {out: {inline: 1}}, fn
when "distinct"
c.distinct params.key, params.query, (err, list)->
if err
fn?(err)
else
makeKVJson = (key, value)->
kv = {}
kv[key] = value
return kv
json = (makeKVJson(params.key,v) for v in list)
#logger.debug util.format("Distinct: %j", json)
fn?(null, streamify(json))
when "count"
logger.debug util.format("count with query %j", params.query)
c.count params.query, {}, (err, count)->
if err
fn?(err)
else
fn?(null, streamify([count: count]))
else
fn?(new Error("getReportData() can't be used with queries of type '#{qType}'"))
.catch (boo)->
fn?(boo)
Report.makeCopy = (original) ->
og = original.data()
data =
name: "#{og.name} copy"
for attributeName in ["database", "collection", "comment", "type", "mode", "parameters", "tags"]
data[attributeName] = og[attributeName]
return new Report(data)
Report.makeDefaultReport = (dbname, colname) ->
data =
name: "New #{colname}"
database: dbname
collection: colname
comment: "(Enter comment here)"
type: "find"
mode: "manual"
tags: [dbname, colname]
parameters:
find:
selector: "object:{}"
options:
sort: "object:{}"
fields: "object:{}"
group:
keys: "object:{_id:1}"
condition: "object:{}"
initial: "object:{\n\ttotal: 0\n\tcount: 0\n} # The initial aggregation object (result)"
reduce: "function:(curr, result)->\n\t#result.total += curr.item.qty\n\t#result.count += 1\n"
finalize: "function:(result)->\n\t#e.g compute and add an average count to the result\n\t#return result\n"
mapReduce:
map: "function:()->\n\t#emit(this.key, this.value)\n"
reduce: "function:(key, values)->\n\treturn 1"
options:
query: "object:{}"
sort: "object:{}"
limit: "number:"
out: "object:{inline: 1} # {replace:'collectionName'}, {merge:'collectionName'}, {reduce:'collectionName'}"
finalize: "function:"
scope: "object: {}"
distinct:
key: "string:\"_id\""
query: "object:{}"
count:
query: "object:{}"
aggregate:
pipeline: "array:[]"
return new Report(data)
_.extend Report, events.EventEmitter.prototype
Report.setLogger logger
Report.collectionName = "report"
MongoDoc.register(Report)
module.exports = Report
| 177213 | _ = require 'underscore'
MongoDoc = require 'macmodel'
events = require 'events'
Seq = require 'seq'
coffee = require 'coffeescript'
util = require 'util'
streamify = require "stream-array"
mr2FlatJson = require("helpers").streams.mr2FlatJson
logger = console
class Report extends MongoDoc
init: ->
#logger.info "OK initialized Report"
getTargetedCollection: (fn)->
if dbname = @_data.database and colname = @_data.collection
if collection = MongoDoc.db.databases[dbname]?.collections[colname]
fn?(null, collection)
if @_data._id is undefined
return fn?(new Error("Can't get collection without the report's _id"))
dbname = null
colname = null
self = @
Seq().seq ->
logger.debug "getTargetedCollection will fillFromStorage"
self.fillFromStorage this
.seq (r)->
logger.debug "getTargetedCollection will linkDatabaseIfExists"
data = r.data()
dbname = data.database
colname = data.collection
report = r
MongoDoc.db.linkDatabaseIfExists dbname, this
.seq ->
logger.debug "getTargetedCollection will return collection"
if collection = MongoDoc.db.databases[dbname]?.collections[colname]
fn?(null, collection)
else
fn?(new Error("Database #{dbname} could not be linked for #{colname} (#{_.keys(MongoDoc.db.databases[dbname].collections)})"))
.catch (boo)->
fn?(boo)
getParsedParameters: (qType)->
if qType is undefined
qType = "all"
if @_parsedParameters is undefined
@_parsedParameters = {}
if @_parsedParameters[qType]
return @_parsedParameters[qType]
else if @_parsedParameters.all?[qType]
return @_parsedParameters.all?[qType]
else
recursiveParse = (path, obj, result)->
for key, value of obj
if path is null
p = key
else
p = "#{path}.#{key}"
if _.isString value
separatorIndex = value.indexOf(":")
type = value.substring(0, separatorIndex)
cscript = value.substring(separatorIndex+1).trim()
if cscript.length > 0
try
jscript = coffee.compile cscript, bare: true
logger.debug "#{p} jscript: #{jscript}"
evaluated = undefined
eval "evaluated = #{jscript}"
catch err
err.message = "Error compiling #{p}: #{err.message}"
throw err
if evaluated isnt undefined
if evaluated isnt null
switch type
when 'function'
unless _.isFunction evaluated
throw new Error("Value for '#{p}' must evaluate to a function")
when 'number'
if isNaN evaluated
throw new Error("Value for '#{p}' must evaluate to a number")
when 'string'
unless _.isString evaluated
throw new Error("Value for '#{p}' must evaluate to a string")
result[key] = evaluated
else
result[key] = {}
recursiveParse("#{p}", value, result[key])
@_parsedParameters = {}
@_parsedParameters[qType] = {}
if qType is "all"
obj = @data().parameters
else
obj = @data().parameters[qType]
if not obj
throw new Error("No inputs for parameters of type '#{qType}'")
recursiveParse(null, obj, @_parsedParameters[qType])
return @_parsedParameters[qType]
getSampleCursor: (fn)->
self = @
Seq().seq ->
self.getTargetedCollection this
.seq (c)->
qType = self.data().type
try
params = self.getParsedParameters(qType)
catch boo
return fn?(boo)
selector = {}
options = {sort: {_id: -1}}
switch qType
when "find"
selector = params.selector
_.extend options, params.options
when "aggregate"
for cmd in params.pipeline
if cmd.$match
selector = cmd.$match
break
when "group"
selector = params.condition
when "count", "distinct"
selector = params.query
when "mapReduce"
selector = params.options.query
else
return fn?(new Error("getCursor() can't be used with queries of type '#{qType}'"))
if selector is undefined or selector is null
selector = {}
logger.debug util.format("SampleCursor with selector %j\nand options %j", selector, options)
cursor = c.find(selector, options)
fn?(null, cursor)
.catch (boo)->
fn?(boo)
getCursor: (fn)->
self = @
Seq().seq ->
self.getTargetedCollection this
.seq (c)->
qType = self.data().type
try
params = self.getParsedParameters(qType)
catch boo
return fn?(boo)
switch qType
when "find"
cursor = c.find(params.selector, params.options)
fn?(null, cursor)
when "aggregate"
cursor = c.aggregate(params.pipeline, {cursor: {batchSize:1}})
fn?(null, cursor)
else
fn?(new Error("getCursor() can't be used with queries of type '#{qType}'"))
.catch (boo)->
fn?(boo)
getStream: (fn)->
self = @
Seq().seq ->
logger.debug util.format("Will get targeted collection")
self.getTargetedCollection this
.seq (c)->
logger.debug util.format("OK have targeted collection")
qType = self.data().type
try
params = self.getParsedParameters(qType)
catch boo
return fn?(boo)
switch qType
when "group"
c.group params.keys, params.condition, params.initial, params.reduce, params.finalize, true, {}, (err, list)->
if err
fn?(err)
else
fn?(null, streamify(list))
when "mapReduce"
logger.debug util.format("mapReduce with map #{params.map}, reduce: #{params.reduce}, options keys: #{_.keys(params.options)}, options: %j", params.options)
c.mapReduce params.map, params.reduce, params.options, (err, list)->
if err
fn?(err)
else
fn?(null, streamify(list).pipe(mr2FlatJson()))
#c.mapReduce (->emit(this.locale,1)), (->return 1), {out: {inline: 1}}, fn
when "distinct"
c.distinct params.key, params.query, (err, list)->
if err
fn?(err)
else
makeKVJson = (key, value)->
kv = {}
kv[key] = value
return kv
json = (makeKVJson(params.key,v) for v in list)
#logger.debug util.format("Distinct: %j", json)
fn?(null, streamify(json))
when "count"
logger.debug util.format("count with query %j", params.query)
c.count params.query, {}, (err, count)->
if err
fn?(err)
else
fn?(null, streamify([count: count]))
else
fn?(new Error("getReportData() can't be used with queries of type '#{qType}'"))
.catch (boo)->
fn?(boo)
Report.makeCopy = (original) ->
og = original.data()
data =
name: "#{og.name} copy"
for attributeName in ["database", "collection", "comment", "type", "mode", "parameters", "tags"]
data[attributeName] = og[attributeName]
return new Report(data)
Report.makeDefaultReport = (dbname, colname) ->
data =
name: "New #{colname}"
database: dbname
collection: colname
comment: "(Enter comment here)"
type: "find"
mode: "manual"
tags: [dbname, colname]
parameters:
find:
selector: "object:{}"
options:
sort: "object:{}"
fields: "object:{}"
group:
keys: "<KEY>
condition: "object:{}"
initial: "object:{\n\ttotal: 0\n\tcount: 0\n} # The initial aggregation object (result)"
reduce: "function:(curr, result)->\n\t#result.total += curr.item.qty\n\t#result.count += 1\n"
finalize: "function:(result)->\n\t#e.g compute and add an average count to the result\n\t#return result\n"
mapReduce:
map: "function:()->\n\t#emit(this.key, this.value)\n"
reduce: "function:(key, values)->\n\treturn 1"
options:
query: "object:{}"
sort: "object:{}"
limit: "number:"
out: "object:{inline: 1} # {replace:'collectionName'}, {merge:'collectionName'}, {reduce:'collectionName'}"
finalize: "function:"
scope: "object: {}"
distinct:
key: "string:\"_<KEY>\""
query: "object:{}"
count:
query: "object:{}"
aggregate:
pipeline: "array:[]"
return new Report(data)
_.extend Report, events.EventEmitter.prototype
Report.setLogger logger
Report.collectionName = "report"
MongoDoc.register(Report)
module.exports = Report
| true | _ = require 'underscore'
MongoDoc = require 'macmodel'
events = require 'events'
Seq = require 'seq'
coffee = require 'coffeescript'
util = require 'util'
streamify = require "stream-array"
mr2FlatJson = require("helpers").streams.mr2FlatJson
logger = console
class Report extends MongoDoc
init: ->
#logger.info "OK initialized Report"
getTargetedCollection: (fn)->
if dbname = @_data.database and colname = @_data.collection
if collection = MongoDoc.db.databases[dbname]?.collections[colname]
fn?(null, collection)
if @_data._id is undefined
return fn?(new Error("Can't get collection without the report's _id"))
dbname = null
colname = null
self = @
Seq().seq ->
logger.debug "getTargetedCollection will fillFromStorage"
self.fillFromStorage this
.seq (r)->
logger.debug "getTargetedCollection will linkDatabaseIfExists"
data = r.data()
dbname = data.database
colname = data.collection
report = r
MongoDoc.db.linkDatabaseIfExists dbname, this
.seq ->
logger.debug "getTargetedCollection will return collection"
if collection = MongoDoc.db.databases[dbname]?.collections[colname]
fn?(null, collection)
else
fn?(new Error("Database #{dbname} could not be linked for #{colname} (#{_.keys(MongoDoc.db.databases[dbname].collections)})"))
.catch (boo)->
fn?(boo)
getParsedParameters: (qType)->
if qType is undefined
qType = "all"
if @_parsedParameters is undefined
@_parsedParameters = {}
if @_parsedParameters[qType]
return @_parsedParameters[qType]
else if @_parsedParameters.all?[qType]
return @_parsedParameters.all?[qType]
else
recursiveParse = (path, obj, result)->
for key, value of obj
if path is null
p = key
else
p = "#{path}.#{key}"
if _.isString value
separatorIndex = value.indexOf(":")
type = value.substring(0, separatorIndex)
cscript = value.substring(separatorIndex+1).trim()
if cscript.length > 0
try
jscript = coffee.compile cscript, bare: true
logger.debug "#{p} jscript: #{jscript}"
evaluated = undefined
eval "evaluated = #{jscript}"
catch err
err.message = "Error compiling #{p}: #{err.message}"
throw err
if evaluated isnt undefined
if evaluated isnt null
switch type
when 'function'
unless _.isFunction evaluated
throw new Error("Value for '#{p}' must evaluate to a function")
when 'number'
if isNaN evaluated
throw new Error("Value for '#{p}' must evaluate to a number")
when 'string'
unless _.isString evaluated
throw new Error("Value for '#{p}' must evaluate to a string")
result[key] = evaluated
else
result[key] = {}
recursiveParse("#{p}", value, result[key])
@_parsedParameters = {}
@_parsedParameters[qType] = {}
if qType is "all"
obj = @data().parameters
else
obj = @data().parameters[qType]
if not obj
throw new Error("No inputs for parameters of type '#{qType}'")
recursiveParse(null, obj, @_parsedParameters[qType])
return @_parsedParameters[qType]
getSampleCursor: (fn)->
self = @
Seq().seq ->
self.getTargetedCollection this
.seq (c)->
qType = self.data().type
try
params = self.getParsedParameters(qType)
catch boo
return fn?(boo)
selector = {}
options = {sort: {_id: -1}}
switch qType
when "find"
selector = params.selector
_.extend options, params.options
when "aggregate"
for cmd in params.pipeline
if cmd.$match
selector = cmd.$match
break
when "group"
selector = params.condition
when "count", "distinct"
selector = params.query
when "mapReduce"
selector = params.options.query
else
return fn?(new Error("getCursor() can't be used with queries of type '#{qType}'"))
if selector is undefined or selector is null
selector = {}
logger.debug util.format("SampleCursor with selector %j\nand options %j", selector, options)
cursor = c.find(selector, options)
fn?(null, cursor)
.catch (boo)->
fn?(boo)
getCursor: (fn)->
self = @
Seq().seq ->
self.getTargetedCollection this
.seq (c)->
qType = self.data().type
try
params = self.getParsedParameters(qType)
catch boo
return fn?(boo)
switch qType
when "find"
cursor = c.find(params.selector, params.options)
fn?(null, cursor)
when "aggregate"
cursor = c.aggregate(params.pipeline, {cursor: {batchSize:1}})
fn?(null, cursor)
else
fn?(new Error("getCursor() can't be used with queries of type '#{qType}'"))
.catch (boo)->
fn?(boo)
getStream: (fn)->
self = @
Seq().seq ->
logger.debug util.format("Will get targeted collection")
self.getTargetedCollection this
.seq (c)->
logger.debug util.format("OK have targeted collection")
qType = self.data().type
try
params = self.getParsedParameters(qType)
catch boo
return fn?(boo)
switch qType
when "group"
c.group params.keys, params.condition, params.initial, params.reduce, params.finalize, true, {}, (err, list)->
if err
fn?(err)
else
fn?(null, streamify(list))
when "mapReduce"
logger.debug util.format("mapReduce with map #{params.map}, reduce: #{params.reduce}, options keys: #{_.keys(params.options)}, options: %j", params.options)
c.mapReduce params.map, params.reduce, params.options, (err, list)->
if err
fn?(err)
else
fn?(null, streamify(list).pipe(mr2FlatJson()))
#c.mapReduce (->emit(this.locale,1)), (->return 1), {out: {inline: 1}}, fn
when "distinct"
c.distinct params.key, params.query, (err, list)->
if err
fn?(err)
else
makeKVJson = (key, value)->
kv = {}
kv[key] = value
return kv
json = (makeKVJson(params.key,v) for v in list)
#logger.debug util.format("Distinct: %j", json)
fn?(null, streamify(json))
when "count"
logger.debug util.format("count with query %j", params.query)
c.count params.query, {}, (err, count)->
if err
fn?(err)
else
fn?(null, streamify([count: count]))
else
fn?(new Error("getReportData() can't be used with queries of type '#{qType}'"))
.catch (boo)->
fn?(boo)
Report.makeCopy = (original) ->
og = original.data()
data =
name: "#{og.name} copy"
for attributeName in ["database", "collection", "comment", "type", "mode", "parameters", "tags"]
data[attributeName] = og[attributeName]
return new Report(data)
Report.makeDefaultReport = (dbname, colname) ->
data =
name: "New #{colname}"
database: dbname
collection: colname
comment: "(Enter comment here)"
type: "find"
mode: "manual"
tags: [dbname, colname]
parameters:
find:
selector: "object:{}"
options:
sort: "object:{}"
fields: "object:{}"
group:
keys: "PI:KEY:<KEY>END_PI
condition: "object:{}"
initial: "object:{\n\ttotal: 0\n\tcount: 0\n} # The initial aggregation object (result)"
reduce: "function:(curr, result)->\n\t#result.total += curr.item.qty\n\t#result.count += 1\n"
finalize: "function:(result)->\n\t#e.g compute and add an average count to the result\n\t#return result\n"
mapReduce:
map: "function:()->\n\t#emit(this.key, this.value)\n"
reduce: "function:(key, values)->\n\treturn 1"
options:
query: "object:{}"
sort: "object:{}"
limit: "number:"
out: "object:{inline: 1} # {replace:'collectionName'}, {merge:'collectionName'}, {reduce:'collectionName'}"
finalize: "function:"
scope: "object: {}"
distinct:
key: "string:\"_PI:KEY:<KEY>END_PI\""
query: "object:{}"
count:
query: "object:{}"
aggregate:
pipeline: "array:[]"
return new Report(data)
_.extend Report, events.EventEmitter.prototype
Report.setLogger logger
Report.collectionName = "report"
MongoDoc.register(Report)
module.exports = Report
|
[
{
"context": "name: \"Simon Bramble\"\njob_title: \"Content Designer\"\ngrade: \"SEO\"\nsalar",
"end": 20,
"score": 0.9998955726623535,
"start": 7,
"tag": "NAME",
"value": "Simon Bramble"
},
{
"context": "\"Business Transformation Group\"\nmanager:\n name: \"Tom Adams\"\n phone: \"0789 126 4474\"\noffice: \"Newcastle, Ben",
"end": 236,
"score": 0.9998846054077148,
"start": 227,
"tag": "NAME",
"value": "Tom Adams"
},
{
"context": "eavement payment service. You'll work closely with Gavin Elliot, lead interaction designer, on this service.\"\n]\n",
"end": 636,
"score": 0.9997594952583313,
"start": 624,
"tag": "NAME",
"value": "Gavin Elliot"
}
] | app/data/users/simon.cson | dwpdigitaltech/DWPwelcome | 0 | name: "Simon Bramble"
job_title: "Content Designer"
grade: "SEO"
salary: "£40,000"
pay_date: "25 April 2016"
annual_leave: 25
section: "User Experience and Design"
directorate: "Business Transformation Group"
manager:
name: "Tom Adams"
phone: "0789 126 4474"
office: "Newcastle, Benton Park View"
role: [
"As a content designer you're expected to create content to support DWP's digital services."
"You'll usually be assigned to one or 2 specific services and work as part of an agile team in each service you work on."
"Your first team will be working on the bereavement payment service. You'll work closely with Gavin Elliot, lead interaction designer, on this service."
]
| 178881 | name: "<NAME>"
job_title: "Content Designer"
grade: "SEO"
salary: "£40,000"
pay_date: "25 April 2016"
annual_leave: 25
section: "User Experience and Design"
directorate: "Business Transformation Group"
manager:
name: "<NAME>"
phone: "0789 126 4474"
office: "Newcastle, Benton Park View"
role: [
"As a content designer you're expected to create content to support DWP's digital services."
"You'll usually be assigned to one or 2 specific services and work as part of an agile team in each service you work on."
"Your first team will be working on the bereavement payment service. You'll work closely with <NAME>, lead interaction designer, on this service."
]
| true | name: "PI:NAME:<NAME>END_PI"
job_title: "Content Designer"
grade: "SEO"
salary: "£40,000"
pay_date: "25 April 2016"
annual_leave: 25
section: "User Experience and Design"
directorate: "Business Transformation Group"
manager:
name: "PI:NAME:<NAME>END_PI"
phone: "0789 126 4474"
office: "Newcastle, Benton Park View"
role: [
"As a content designer you're expected to create content to support DWP's digital services."
"You'll usually be assigned to one or 2 specific services and work as part of an agile team in each service you work on."
"Your first team will be working on the bereavement payment service. You'll work closely with PI:NAME:<NAME>END_PI, lead interaction designer, on this service."
]
|
[
{
"context": "author: <span><a key={0} href=\"https://github.com/PHELiOX\">Artoria</a></span>\n displayName: <span><FontAwe",
"end": 3753,
"score": 0.9989209175109863,
"start": 3746,
"tag": "USERNAME",
"value": "PHELiOX"
},
{
"context": "span><a key={0} href=\"https://github.com/PHELiOX\">Artoria</a></span>\n displayName: <span><FontAwesome key=",
"end": 3762,
"score": 0.669978141784668,
"start": 3755,
"tag": "NAME",
"value": "Artoria"
},
{
"context": "ray.isArray(track)\n warn \"no quest track id #{@memberId}\"\n track = []\n @track = Object.clone(",
"end": 15804,
"score": 0.6217827200889587,
"start": 15793,
"tag": "USERNAME",
"value": "#{@memberId"
}
] | index.cjsx | PHELiOX/plugin-quest-tracker | 0 | {ROOT, EXROOT} = global
{ROOT, layout, _, $, $$, React, ReactBootstrap} = window
{Label, OverlayTrigger, Tooltip} = ReactBootstrap
fs = require 'fs-extra'
path = require 'path'
CSON = require 'cson'
{log, warn, error} = require(path.join(ROOT, 'lib', 'utils'))
questDataPath = path.join(EXROOT, 'questdata.cson')
submarines = [530, 531, 532, 533, 534, 535, 570, 571, 572]
aircraftcarriers = [510, 512, 523, 525, 528, 560, 565, 579]
supplyships = [558, 526, 513]
trackpooldaily = [
#daily
201, 216, 210, 218, 226, 230, 211, 212, 303, 304, 402, 403, 503, 504, 605, 606, 607, 608, 609, 619, 702
]
trackpoolweekly = [
#weekly
214, 220, 213, 221, 228, 229, 241, 242, 243, 261, 302, 404, 410, 411, 613, 703
]
CODEA = 214
# Local time -> Task Refresh time(GMT + 4)
getCurrentDay = ->
curTime = new Date()
curTime.setTime(curTime.getTime() + (curTime.getTimezoneOffset() + 240) * 60000)
curTime.getDay()
prevDay = getCurrentDay()
# TODO: merge quest requirement with quest.cson
getTargetById = (id) ->
switch id
# daily
when 201
return 1
when 216
return 1
when 210
return 10
when 218
return 3
when 226
return 5
when 230
return 6
when 211
return 3
when 212
return 5
when 303
return 3
when 304
return 5
when 402
return 3
when 403
return 10
when 503
return 5
when 504
return 15
when 605
return 1
when 606
return 1
when 607
return 3
when 608
return 3
when 609
return 2
when 619
return 1
when 702
return 2
# weekly
when 214
return 6 + 12 + 24 + 36
when 220
return 20
when 213
return 20
when 221
return 50
when 228
return 15
when 229
return 12
when 241
return 5
when 242
return 1
when 243
return 2
when 261
return 3
when 302
return 20
when 404
return 30
when 410
return 1
when 411
return 6
when 613
return 24
when 703
return 15
# monthly
# when 249
# return 1
# when 256
# return 3
# when 257
# return 1
# when 259
# return 1
# when 265
# return 1
# when 266
# return 1
else
return 1
getProgressById = (id, track) ->
if id not in trackpooldaily.concat trackpoolweekly
return 0
idx = _.findIndex track, (t) ->
t.id == id
if idx == -1
return 0
else
return track[idx].progress
setProgressByTask = (task, progress, track) ->
if task.id not in trackpooldaily.concat trackpoolweekly
return
idx = _.findIndex track, (t) ->
t.id == task.id
if idx != -1
track[idx] =
progress: progress # save progress as digit
id: task.id
name: task.name
content: task.content
category: task.category
type: task.type
else
newTask = Object.clone(emptyTask)
newTask =
progress: progress # save progress as digit
id: task.id
name: task.name
content: task.content
category: task.category
type: task.type
track.push newTask
getCategoryById = (id) ->
cat = Math.floor(id / 100)
saveTracker = (track) ->
try
fs.writeFileSync questDataPath, CSON.stringify(track)
catch e
warn e
readTracker = ->
try
fs.accessSync questDataPath, fs.R_OK | fs.W_OK
track = CSON.parseCSONFile questDataPath
catch e
warn e
return track
emptyTask =
name: '未接受'
id: 100000
content: '...'
progress: ''
category: 0
type: 0
module.exports =
name: 'QuestTracker'
priority: 10
author: <span><a key={0} href="https://github.com/PHELiOX">Artoria</a></span>
displayName: <span><FontAwesome key={0} name='check-circle-o' /> 任务进度</span>
description: '跟踪激活中的任务完成情况'
show: true
version: '1.0.0'
reactClass: React.createClass
track: []
memberId: 0
mapArea: 0
mapInfo: 0
isBoss: false
rank: ""
percent: [0, 0, 0, 0, 0, 0]
progress: [0, 0, 0, 0, 0, 0]
target: [1, 1, 1, 1, 1, 1]
codeA: [0, 0, 0, 0] # fight, S, boss fight, boss SAB
codeAtarget: [36, 6, 24, 12]
nowHp: null
enemyId: null
tasks: [Object.clone(emptyTask), Object.clone(emptyTask), Object.clone(emptyTask),
Object.clone(emptyTask), Object.clone(emptyTask), Object.clone(emptyTask)]
handleResponse: (e) ->
flag = false
{method, path, body, postBody} = e.detail
newPercent = [0, 0, 0, 0, 0, 0]
newProgress = [0, 0, 0, 0, 0, 0]
newTarget = [1, 1, 1, 1, 1, 1]
switch path
# check id to store progress separately
when '/kcsapi/api_get_member/basic'
@memberId = parseInt(body.api_member_id)
when '/kcsapi/api_req_quest/clearitemget'
if postBody.api_quest_id?
complete = parseInt(postBody.api_quest_id)
@track = @track.filter (t) -> t.id != complete
idx = _.findIndex @tasks, (t) -> t.id == complete
return if idx == -1
tasks[idx] = Object.clone(emptyTask)
else
for task, i in @tasks
continue if !task? or task.id is 100000
# calibrate current progress
progress = @progress[i]
target = @target[i]
# id 分类
cat = getCategoryById task.id
switch cat
when 2
switch path
# possible bug when refresh game
when '/kcsapi/api_req_map/start'
@mapArea = body.api_maparea_id
@mapInfo = body.api_mapinfo_no
@isBoss = false
when '/kcsapi/api_req_map/next'
if body.api_bosscell_no == body.api_no
@isBoss = true
when '/kcsapi/api_req_sortie/battleresult'
@rank = body.api_win_rank
when 3
switch path
when '/kcsapi/api_req_practice/battle_result'
switch task.id
when 303
flag = true
progress += 1
when 304, 302
switch body.api_win_rank
when "A", "S", "B"
progress += 1
flag = true
when 4
switch path
when '/kcsapi/api_req_mission/result'
switch task.id
when 410, 411
if body.api_clear_result > 0
if body.api_quest_name is "東京急行" or body.api_quest_name is "東京急行(弐)"
progress += 1
flag = true
when 402, 403, 404
if body.api_clear_result > 0
progress += 1
flag = true
when 5
switch path
when '/kcsapi/api_req_nyukyo/start'
switch task.id
when 503
progress += 1
flag = true
when'/kcsapi/api_req_hokyu/charge'
switch task.id
when 504
progress += 1
flag = true
when 6
switch path
when '/kcsapi/api_req_kousyou/createitem'
if task.id == 605 || 607
progress += 1
flag = true
when '/kcsapi/api_req_kousyou/createship'
if task.id == 606 || 608
progress += 1
flag = true
when '/kcsapi/api_req_kousyou/destroyitem2'
if task.id == 613
progress += 1
flag = true
when '/kcsapi/api_req_kousyou/destroyship'
if task.id == 609
progress += 1
flag = true
when '/kcsapi/api_req_kousyou/remodel_slot'
if task.id == 619
progress += 1
flag = true
when 7
switch path
when '/kcsapi/api_req_kaisou/powerup'
switch task.id
when 702, 703
if body.api_powerup_flag == 1
progress += 1
flag = true
newProgress[i] = progress = if progress > target then target else progress
newTarget[i] = target
newPercent[i] = Math.floor(progress / target * 100)
# Save progress by memberId and questId
if task.id != CODEA
setProgressByTask task, progress, @track
saveTracker @track
if flag
@progress = newProgress
@target = newTarget
@percent = newPercent
event = new CustomEvent 'task.update',
bubbles: true
cancelable: true
detail:
codeA: @codeA
percent: newPercent
progress: newProgress
target: newTarget
window.dispatchEvent event
handleBattleResult: (e) ->
flag = false
{isCombined, nowHp, enemyId, rank} = e.detail
newPercent = [0, 0, 0, 0, 0, 0]
newProgress = [0, 0, 0, 0, 0, 0]
newTarget = [1, 1, 1, 1, 1, 1]
codeA = @codeA
if not isCombined
nowHp = nowHp[5..11] # add 0 slot
@rank = rank
for task, i in @tasks
continue if !task? or task.id is 100000
progress = @progress[i]
target = @target[i]
switch task.id
# fight
when 216, 210
progress += 1
flag = true
# All win
when 201
switch @rank
when "A", "S", "B"
progress += 1
flag = true
# Supply ship
when 218, 212, 213, 221
for id, j in enemyId
if id in supplyships and nowHp[j] is 0
progress += 1
flag = true
# Aircraft Carrier
when 211, 220
for id, j in enemyId
if id in aircraftcarriers and nowHp[j] is 0
progress += 1
flag = true
break
# Submarines
when 230, 228
for id, j in enemyId
if id in submarines and nowHp[j] is 0
progress += 1
flag = true
break
# southwest
when 226
if @mapArea == 2
if @isBoss
switch @rank
when "A", "S", "B"
progress += 1
flag = true
# west
when 229
if @mapArea == 4
if @isBoss
switch @rank
when "A", "S", "B"
progress += 1
flag = true
# west 4-4
when 242
if @mapArea == 4 and @mapInfo == 4
if @isBoss
switch @rank
when "A", "S", "B"
progress += 1
flag = true
# north 3-3...3-5
when 241
if @mapArea == 3 and @mapInfo > 2
if @isBoss
switch @rank
when "A", "S", "B"
progress += 1
flag = true
# south 5-2
when 243
if @mapArea == 5 and @mapInfo == 2
if @isBoss
switch @rank
when "S"
progress += 1
flag = true
# near 1-5
when 261
if @mapArea == 1 and @mapInfo == 5
if @isBoss
switch @rank
when "A", "S"
progress += 1
flag = true
# Code A # fight, S, boss fight, boss SAB
when 214
if codeA[0] < @codeAtarget[0]
codeA[0] += 1
flag = true
if @rank == "S"
if codeA[1] < @codeAtarget[1]
codeA[1] += 1
if @isBoss
if codeA[2] < @codeAtarget[2]
codeA[2] += 1
if @isBoss and (@rank == "S" || "A" || "B")
if codeA[3] < @codeAtarget[3]
codeA[3] += 1
progress = codeA.reduce (a, b) -> a + b
newProgress[i] = progress = if progress > target then target else progress
newTarget[i] = target
newPercent[i] = Math.floor(progress / target * 100)
# Save progress by memberId and questId
if task.id == CODEA
setProgressByTask task, codeA, @track
else
setProgressByTask task, progress, @track
saveTracker @track
if flag
@codeA = codeA
@progress = newProgress
@target = newTarget
@percent = newPercent
event = new CustomEvent 'task.update',
bubbles: true
cancelable: true
detail:
codeA: codeA
percent: newPercent
progress: newProgress
target: newTarget
window.dispatchEvent event
handleTaskDidChange: (e) ->
{tasks} = e.detail
newPercent = [0, 0, 0, 0, 0, 0]
newProgress = [0, 0, 0, 0, 0, 0]
newTarget = [1, 1, 1, 1, 1, 1]
codeA = @codeA
# Save Data
for task, i in @tasks
continue unless task?
if task.id == CODEA
setProgressByTask task, @codeA, @track
else
setProgressByTask task, @progress[i], @track
# lower the frequency saving settings to increase performance
@tracks = _.sortBy @tracks, (e) -> e.id
saveTracker @track
# refresh quests
for task, i in tasks
if task.id == CODEA
codeA = getProgressById task.id, @track
if codeA == 0
codeA = [0, 0, 0, 0]
progress = codeA.reduce (a, b) -> a + b
else
progress = getProgressById task.id, @track
target = getTargetById task.id
percent = Math.floor(progress / target * 100)
actual = 0
if task.progress == '达成'
actual = 100
else if task.progress == '50%'
actual = 50
else if task.progress == '80%'
actual = 80
if percent < actual
progress = Math.ceil(actual / 100 * target)
newProgress[i] = progress
newTarget[i] = target
newPercent[i] = percent = Math.floor(progress / target * 100)
@tasks = Object.clone tasks
@codeA = codeA
@progress = newProgress
@target = newTarget
@percent = newPercent
# notify shipview
event = new CustomEvent 'task.update',
bubbles: true
cancelable: true
detail:
codeA: codeA
percent: newPercent
progress: newProgress
target: newTarget
window.dispatchEvent event
refreshTrack: ->
curDay = getCurrentDay()
return if prevDay == curDay
@track = @track.filter (t) -> t.type not in [2, 4, 5]
if curDay is 1
@track = @track.filter (t) -> t.type not in [3]
@track = _.sortBy @track, (t) -> t.id
saveTracker @track
prevDay = curDay
componentWillMount: ->
# Read saved config
track = readTracker()
if not Array.isArray(track)
warn "no quest track id #{@memberId}"
track = []
@track = Object.clone(track)
idx = _.findIndex @track, (t) -> t.id == CODEA
if idx != -1
codeA = Object.clone(@track[idx].progress)
@track[idx].progress = codeA
@codeA = codeA
componentDidMount: ->
window.addEventListener "task.change", @handleTaskDidChange
window.addEventListener "battle.result", @handleBattleResult
window.addEventListener "game.response", @handleResponse
@interval = setInterval @refreshTrack, 30000
# window.addEventListener "window.beforeclose", @saveTracker
componentWillUnmount: ->
window.removeEventListener "task.change", @handleTaskDidChange
window.removeEventListener "battle.result", @handleBattleResult
window.removeEventListener "game.response", @handleResponse
clearInterval @interval
# window.removeEventListener "window.beforeclose", @saveTracker
render: ->
<div/>
| 178044 | {ROOT, EXROOT} = global
{ROOT, layout, _, $, $$, React, ReactBootstrap} = window
{Label, OverlayTrigger, Tooltip} = ReactBootstrap
fs = require 'fs-extra'
path = require 'path'
CSON = require 'cson'
{log, warn, error} = require(path.join(ROOT, 'lib', 'utils'))
questDataPath = path.join(EXROOT, 'questdata.cson')
submarines = [530, 531, 532, 533, 534, 535, 570, 571, 572]
aircraftcarriers = [510, 512, 523, 525, 528, 560, 565, 579]
supplyships = [558, 526, 513]
trackpooldaily = [
#daily
201, 216, 210, 218, 226, 230, 211, 212, 303, 304, 402, 403, 503, 504, 605, 606, 607, 608, 609, 619, 702
]
trackpoolweekly = [
#weekly
214, 220, 213, 221, 228, 229, 241, 242, 243, 261, 302, 404, 410, 411, 613, 703
]
CODEA = 214
# Local time -> Task Refresh time(GMT + 4)
getCurrentDay = ->
curTime = new Date()
curTime.setTime(curTime.getTime() + (curTime.getTimezoneOffset() + 240) * 60000)
curTime.getDay()
prevDay = getCurrentDay()
# TODO: merge quest requirement with quest.cson
getTargetById = (id) ->
switch id
# daily
when 201
return 1
when 216
return 1
when 210
return 10
when 218
return 3
when 226
return 5
when 230
return 6
when 211
return 3
when 212
return 5
when 303
return 3
when 304
return 5
when 402
return 3
when 403
return 10
when 503
return 5
when 504
return 15
when 605
return 1
when 606
return 1
when 607
return 3
when 608
return 3
when 609
return 2
when 619
return 1
when 702
return 2
# weekly
when 214
return 6 + 12 + 24 + 36
when 220
return 20
when 213
return 20
when 221
return 50
when 228
return 15
when 229
return 12
when 241
return 5
when 242
return 1
when 243
return 2
when 261
return 3
when 302
return 20
when 404
return 30
when 410
return 1
when 411
return 6
when 613
return 24
when 703
return 15
# monthly
# when 249
# return 1
# when 256
# return 3
# when 257
# return 1
# when 259
# return 1
# when 265
# return 1
# when 266
# return 1
else
return 1
getProgressById = (id, track) ->
if id not in trackpooldaily.concat trackpoolweekly
return 0
idx = _.findIndex track, (t) ->
t.id == id
if idx == -1
return 0
else
return track[idx].progress
setProgressByTask = (task, progress, track) ->
if task.id not in trackpooldaily.concat trackpoolweekly
return
idx = _.findIndex track, (t) ->
t.id == task.id
if idx != -1
track[idx] =
progress: progress # save progress as digit
id: task.id
name: task.name
content: task.content
category: task.category
type: task.type
else
newTask = Object.clone(emptyTask)
newTask =
progress: progress # save progress as digit
id: task.id
name: task.name
content: task.content
category: task.category
type: task.type
track.push newTask
getCategoryById = (id) ->
cat = Math.floor(id / 100)
saveTracker = (track) ->
try
fs.writeFileSync questDataPath, CSON.stringify(track)
catch e
warn e
readTracker = ->
try
fs.accessSync questDataPath, fs.R_OK | fs.W_OK
track = CSON.parseCSONFile questDataPath
catch e
warn e
return track
emptyTask =
name: '未接受'
id: 100000
content: '...'
progress: ''
category: 0
type: 0
module.exports =
name: 'QuestTracker'
priority: 10
author: <span><a key={0} href="https://github.com/PHELiOX"><NAME></a></span>
displayName: <span><FontAwesome key={0} name='check-circle-o' /> 任务进度</span>
description: '跟踪激活中的任务完成情况'
show: true
version: '1.0.0'
reactClass: React.createClass
track: []
memberId: 0
mapArea: 0
mapInfo: 0
isBoss: false
rank: ""
percent: [0, 0, 0, 0, 0, 0]
progress: [0, 0, 0, 0, 0, 0]
target: [1, 1, 1, 1, 1, 1]
codeA: [0, 0, 0, 0] # fight, S, boss fight, boss SAB
codeAtarget: [36, 6, 24, 12]
nowHp: null
enemyId: null
tasks: [Object.clone(emptyTask), Object.clone(emptyTask), Object.clone(emptyTask),
Object.clone(emptyTask), Object.clone(emptyTask), Object.clone(emptyTask)]
handleResponse: (e) ->
flag = false
{method, path, body, postBody} = e.detail
newPercent = [0, 0, 0, 0, 0, 0]
newProgress = [0, 0, 0, 0, 0, 0]
newTarget = [1, 1, 1, 1, 1, 1]
switch path
# check id to store progress separately
when '/kcsapi/api_get_member/basic'
@memberId = parseInt(body.api_member_id)
when '/kcsapi/api_req_quest/clearitemget'
if postBody.api_quest_id?
complete = parseInt(postBody.api_quest_id)
@track = @track.filter (t) -> t.id != complete
idx = _.findIndex @tasks, (t) -> t.id == complete
return if idx == -1
tasks[idx] = Object.clone(emptyTask)
else
for task, i in @tasks
continue if !task? or task.id is 100000
# calibrate current progress
progress = @progress[i]
target = @target[i]
# id 分类
cat = getCategoryById task.id
switch cat
when 2
switch path
# possible bug when refresh game
when '/kcsapi/api_req_map/start'
@mapArea = body.api_maparea_id
@mapInfo = body.api_mapinfo_no
@isBoss = false
when '/kcsapi/api_req_map/next'
if body.api_bosscell_no == body.api_no
@isBoss = true
when '/kcsapi/api_req_sortie/battleresult'
@rank = body.api_win_rank
when 3
switch path
when '/kcsapi/api_req_practice/battle_result'
switch task.id
when 303
flag = true
progress += 1
when 304, 302
switch body.api_win_rank
when "A", "S", "B"
progress += 1
flag = true
when 4
switch path
when '/kcsapi/api_req_mission/result'
switch task.id
when 410, 411
if body.api_clear_result > 0
if body.api_quest_name is "東京急行" or body.api_quest_name is "東京急行(弐)"
progress += 1
flag = true
when 402, 403, 404
if body.api_clear_result > 0
progress += 1
flag = true
when 5
switch path
when '/kcsapi/api_req_nyukyo/start'
switch task.id
when 503
progress += 1
flag = true
when'/kcsapi/api_req_hokyu/charge'
switch task.id
when 504
progress += 1
flag = true
when 6
switch path
when '/kcsapi/api_req_kousyou/createitem'
if task.id == 605 || 607
progress += 1
flag = true
when '/kcsapi/api_req_kousyou/createship'
if task.id == 606 || 608
progress += 1
flag = true
when '/kcsapi/api_req_kousyou/destroyitem2'
if task.id == 613
progress += 1
flag = true
when '/kcsapi/api_req_kousyou/destroyship'
if task.id == 609
progress += 1
flag = true
when '/kcsapi/api_req_kousyou/remodel_slot'
if task.id == 619
progress += 1
flag = true
when 7
switch path
when '/kcsapi/api_req_kaisou/powerup'
switch task.id
when 702, 703
if body.api_powerup_flag == 1
progress += 1
flag = true
newProgress[i] = progress = if progress > target then target else progress
newTarget[i] = target
newPercent[i] = Math.floor(progress / target * 100)
# Save progress by memberId and questId
if task.id != CODEA
setProgressByTask task, progress, @track
saveTracker @track
if flag
@progress = newProgress
@target = newTarget
@percent = newPercent
event = new CustomEvent 'task.update',
bubbles: true
cancelable: true
detail:
codeA: @codeA
percent: newPercent
progress: newProgress
target: newTarget
window.dispatchEvent event
handleBattleResult: (e) ->
flag = false
{isCombined, nowHp, enemyId, rank} = e.detail
newPercent = [0, 0, 0, 0, 0, 0]
newProgress = [0, 0, 0, 0, 0, 0]
newTarget = [1, 1, 1, 1, 1, 1]
codeA = @codeA
if not isCombined
nowHp = nowHp[5..11] # add 0 slot
@rank = rank
for task, i in @tasks
continue if !task? or task.id is 100000
progress = @progress[i]
target = @target[i]
switch task.id
# fight
when 216, 210
progress += 1
flag = true
# All win
when 201
switch @rank
when "A", "S", "B"
progress += 1
flag = true
# Supply ship
when 218, 212, 213, 221
for id, j in enemyId
if id in supplyships and nowHp[j] is 0
progress += 1
flag = true
# Aircraft Carrier
when 211, 220
for id, j in enemyId
if id in aircraftcarriers and nowHp[j] is 0
progress += 1
flag = true
break
# Submarines
when 230, 228
for id, j in enemyId
if id in submarines and nowHp[j] is 0
progress += 1
flag = true
break
# southwest
when 226
if @mapArea == 2
if @isBoss
switch @rank
when "A", "S", "B"
progress += 1
flag = true
# west
when 229
if @mapArea == 4
if @isBoss
switch @rank
when "A", "S", "B"
progress += 1
flag = true
# west 4-4
when 242
if @mapArea == 4 and @mapInfo == 4
if @isBoss
switch @rank
when "A", "S", "B"
progress += 1
flag = true
# north 3-3...3-5
when 241
if @mapArea == 3 and @mapInfo > 2
if @isBoss
switch @rank
when "A", "S", "B"
progress += 1
flag = true
# south 5-2
when 243
if @mapArea == 5 and @mapInfo == 2
if @isBoss
switch @rank
when "S"
progress += 1
flag = true
# near 1-5
when 261
if @mapArea == 1 and @mapInfo == 5
if @isBoss
switch @rank
when "A", "S"
progress += 1
flag = true
# Code A # fight, S, boss fight, boss SAB
when 214
if codeA[0] < @codeAtarget[0]
codeA[0] += 1
flag = true
if @rank == "S"
if codeA[1] < @codeAtarget[1]
codeA[1] += 1
if @isBoss
if codeA[2] < @codeAtarget[2]
codeA[2] += 1
if @isBoss and (@rank == "S" || "A" || "B")
if codeA[3] < @codeAtarget[3]
codeA[3] += 1
progress = codeA.reduce (a, b) -> a + b
newProgress[i] = progress = if progress > target then target else progress
newTarget[i] = target
newPercent[i] = Math.floor(progress / target * 100)
# Save progress by memberId and questId
if task.id == CODEA
setProgressByTask task, codeA, @track
else
setProgressByTask task, progress, @track
saveTracker @track
if flag
@codeA = codeA
@progress = newProgress
@target = newTarget
@percent = newPercent
event = new CustomEvent 'task.update',
bubbles: true
cancelable: true
detail:
codeA: codeA
percent: newPercent
progress: newProgress
target: newTarget
window.dispatchEvent event
handleTaskDidChange: (e) ->
{tasks} = e.detail
newPercent = [0, 0, 0, 0, 0, 0]
newProgress = [0, 0, 0, 0, 0, 0]
newTarget = [1, 1, 1, 1, 1, 1]
codeA = @codeA
# Save Data
for task, i in @tasks
continue unless task?
if task.id == CODEA
setProgressByTask task, @codeA, @track
else
setProgressByTask task, @progress[i], @track
# lower the frequency saving settings to increase performance
@tracks = _.sortBy @tracks, (e) -> e.id
saveTracker @track
# refresh quests
for task, i in tasks
if task.id == CODEA
codeA = getProgressById task.id, @track
if codeA == 0
codeA = [0, 0, 0, 0]
progress = codeA.reduce (a, b) -> a + b
else
progress = getProgressById task.id, @track
target = getTargetById task.id
percent = Math.floor(progress / target * 100)
actual = 0
if task.progress == '达成'
actual = 100
else if task.progress == '50%'
actual = 50
else if task.progress == '80%'
actual = 80
if percent < actual
progress = Math.ceil(actual / 100 * target)
newProgress[i] = progress
newTarget[i] = target
newPercent[i] = percent = Math.floor(progress / target * 100)
@tasks = Object.clone tasks
@codeA = codeA
@progress = newProgress
@target = newTarget
@percent = newPercent
# notify shipview
event = new CustomEvent 'task.update',
bubbles: true
cancelable: true
detail:
codeA: codeA
percent: newPercent
progress: newProgress
target: newTarget
window.dispatchEvent event
refreshTrack: ->
curDay = getCurrentDay()
return if prevDay == curDay
@track = @track.filter (t) -> t.type not in [2, 4, 5]
if curDay is 1
@track = @track.filter (t) -> t.type not in [3]
@track = _.sortBy @track, (t) -> t.id
saveTracker @track
prevDay = curDay
componentWillMount: ->
# Read saved config
track = readTracker()
if not Array.isArray(track)
warn "no quest track id #{@memberId}"
track = []
@track = Object.clone(track)
idx = _.findIndex @track, (t) -> t.id == CODEA
if idx != -1
codeA = Object.clone(@track[idx].progress)
@track[idx].progress = codeA
@codeA = codeA
componentDidMount: ->
window.addEventListener "task.change", @handleTaskDidChange
window.addEventListener "battle.result", @handleBattleResult
window.addEventListener "game.response", @handleResponse
@interval = setInterval @refreshTrack, 30000
# window.addEventListener "window.beforeclose", @saveTracker
componentWillUnmount: ->
window.removeEventListener "task.change", @handleTaskDidChange
window.removeEventListener "battle.result", @handleBattleResult
window.removeEventListener "game.response", @handleResponse
clearInterval @interval
# window.removeEventListener "window.beforeclose", @saveTracker
render: ->
<div/>
| true | {ROOT, EXROOT} = global
{ROOT, layout, _, $, $$, React, ReactBootstrap} = window
{Label, OverlayTrigger, Tooltip} = ReactBootstrap
fs = require 'fs-extra'
path = require 'path'
CSON = require 'cson'
{log, warn, error} = require(path.join(ROOT, 'lib', 'utils'))
questDataPath = path.join(EXROOT, 'questdata.cson')
submarines = [530, 531, 532, 533, 534, 535, 570, 571, 572]
aircraftcarriers = [510, 512, 523, 525, 528, 560, 565, 579]
supplyships = [558, 526, 513]
trackpooldaily = [
#daily
201, 216, 210, 218, 226, 230, 211, 212, 303, 304, 402, 403, 503, 504, 605, 606, 607, 608, 609, 619, 702
]
trackpoolweekly = [
#weekly
214, 220, 213, 221, 228, 229, 241, 242, 243, 261, 302, 404, 410, 411, 613, 703
]
CODEA = 214
# Local time -> Task Refresh time(GMT + 4)
getCurrentDay = ->
curTime = new Date()
curTime.setTime(curTime.getTime() + (curTime.getTimezoneOffset() + 240) * 60000)
curTime.getDay()
prevDay = getCurrentDay()
# TODO: merge quest requirement with quest.cson
getTargetById = (id) ->
switch id
# daily
when 201
return 1
when 216
return 1
when 210
return 10
when 218
return 3
when 226
return 5
when 230
return 6
when 211
return 3
when 212
return 5
when 303
return 3
when 304
return 5
when 402
return 3
when 403
return 10
when 503
return 5
when 504
return 15
when 605
return 1
when 606
return 1
when 607
return 3
when 608
return 3
when 609
return 2
when 619
return 1
when 702
return 2
# weekly
when 214
return 6 + 12 + 24 + 36
when 220
return 20
when 213
return 20
when 221
return 50
when 228
return 15
when 229
return 12
when 241
return 5
when 242
return 1
when 243
return 2
when 261
return 3
when 302
return 20
when 404
return 30
when 410
return 1
when 411
return 6
when 613
return 24
when 703
return 15
# monthly
# when 249
# return 1
# when 256
# return 3
# when 257
# return 1
# when 259
# return 1
# when 265
# return 1
# when 266
# return 1
else
return 1
getProgressById = (id, track) ->
if id not in trackpooldaily.concat trackpoolweekly
return 0
idx = _.findIndex track, (t) ->
t.id == id
if idx == -1
return 0
else
return track[idx].progress
setProgressByTask = (task, progress, track) ->
if task.id not in trackpooldaily.concat trackpoolweekly
return
idx = _.findIndex track, (t) ->
t.id == task.id
if idx != -1
track[idx] =
progress: progress # save progress as digit
id: task.id
name: task.name
content: task.content
category: task.category
type: task.type
else
newTask = Object.clone(emptyTask)
newTask =
progress: progress # save progress as digit
id: task.id
name: task.name
content: task.content
category: task.category
type: task.type
track.push newTask
getCategoryById = (id) ->
cat = Math.floor(id / 100)
saveTracker = (track) ->
try
fs.writeFileSync questDataPath, CSON.stringify(track)
catch e
warn e
readTracker = ->
try
fs.accessSync questDataPath, fs.R_OK | fs.W_OK
track = CSON.parseCSONFile questDataPath
catch e
warn e
return track
emptyTask =
name: '未接受'
id: 100000
content: '...'
progress: ''
category: 0
type: 0
module.exports =
name: 'QuestTracker'
priority: 10
author: <span><a key={0} href="https://github.com/PHELiOX">PI:NAME:<NAME>END_PI</a></span>
displayName: <span><FontAwesome key={0} name='check-circle-o' /> 任务进度</span>
description: '跟踪激活中的任务完成情况'
show: true
version: '1.0.0'
reactClass: React.createClass
track: []
memberId: 0
mapArea: 0
mapInfo: 0
isBoss: false
rank: ""
percent: [0, 0, 0, 0, 0, 0]
progress: [0, 0, 0, 0, 0, 0]
target: [1, 1, 1, 1, 1, 1]
codeA: [0, 0, 0, 0] # fight, S, boss fight, boss SAB
codeAtarget: [36, 6, 24, 12]
nowHp: null
enemyId: null
tasks: [Object.clone(emptyTask), Object.clone(emptyTask), Object.clone(emptyTask),
Object.clone(emptyTask), Object.clone(emptyTask), Object.clone(emptyTask)]
handleResponse: (e) ->
flag = false
{method, path, body, postBody} = e.detail
newPercent = [0, 0, 0, 0, 0, 0]
newProgress = [0, 0, 0, 0, 0, 0]
newTarget = [1, 1, 1, 1, 1, 1]
switch path
# check id to store progress separately
when '/kcsapi/api_get_member/basic'
@memberId = parseInt(body.api_member_id)
when '/kcsapi/api_req_quest/clearitemget'
if postBody.api_quest_id?
complete = parseInt(postBody.api_quest_id)
@track = @track.filter (t) -> t.id != complete
idx = _.findIndex @tasks, (t) -> t.id == complete
return if idx == -1
tasks[idx] = Object.clone(emptyTask)
else
for task, i in @tasks
continue if !task? or task.id is 100000
# calibrate current progress
progress = @progress[i]
target = @target[i]
# id 分类
cat = getCategoryById task.id
switch cat
when 2
switch path
# possible bug when refresh game
when '/kcsapi/api_req_map/start'
@mapArea = body.api_maparea_id
@mapInfo = body.api_mapinfo_no
@isBoss = false
when '/kcsapi/api_req_map/next'
if body.api_bosscell_no == body.api_no
@isBoss = true
when '/kcsapi/api_req_sortie/battleresult'
@rank = body.api_win_rank
when 3
switch path
when '/kcsapi/api_req_practice/battle_result'
switch task.id
when 303
flag = true
progress += 1
when 304, 302
switch body.api_win_rank
when "A", "S", "B"
progress += 1
flag = true
when 4
switch path
when '/kcsapi/api_req_mission/result'
switch task.id
when 410, 411
if body.api_clear_result > 0
if body.api_quest_name is "東京急行" or body.api_quest_name is "東京急行(弐)"
progress += 1
flag = true
when 402, 403, 404
if body.api_clear_result > 0
progress += 1
flag = true
when 5
switch path
when '/kcsapi/api_req_nyukyo/start'
switch task.id
when 503
progress += 1
flag = true
when'/kcsapi/api_req_hokyu/charge'
switch task.id
when 504
progress += 1
flag = true
when 6
switch path
when '/kcsapi/api_req_kousyou/createitem'
if task.id == 605 || 607
progress += 1
flag = true
when '/kcsapi/api_req_kousyou/createship'
if task.id == 606 || 608
progress += 1
flag = true
when '/kcsapi/api_req_kousyou/destroyitem2'
if task.id == 613
progress += 1
flag = true
when '/kcsapi/api_req_kousyou/destroyship'
if task.id == 609
progress += 1
flag = true
when '/kcsapi/api_req_kousyou/remodel_slot'
if task.id == 619
progress += 1
flag = true
when 7
switch path
when '/kcsapi/api_req_kaisou/powerup'
switch task.id
when 702, 703
if body.api_powerup_flag == 1
progress += 1
flag = true
newProgress[i] = progress = if progress > target then target else progress
newTarget[i] = target
newPercent[i] = Math.floor(progress / target * 100)
# Save progress by memberId and questId
if task.id != CODEA
setProgressByTask task, progress, @track
saveTracker @track
if flag
@progress = newProgress
@target = newTarget
@percent = newPercent
event = new CustomEvent 'task.update',
bubbles: true
cancelable: true
detail:
codeA: @codeA
percent: newPercent
progress: newProgress
target: newTarget
window.dispatchEvent event
handleBattleResult: (e) ->
flag = false
{isCombined, nowHp, enemyId, rank} = e.detail
newPercent = [0, 0, 0, 0, 0, 0]
newProgress = [0, 0, 0, 0, 0, 0]
newTarget = [1, 1, 1, 1, 1, 1]
codeA = @codeA
if not isCombined
nowHp = nowHp[5..11] # add 0 slot
@rank = rank
for task, i in @tasks
continue if !task? or task.id is 100000
progress = @progress[i]
target = @target[i]
switch task.id
# fight
when 216, 210
progress += 1
flag = true
# All win
when 201
switch @rank
when "A", "S", "B"
progress += 1
flag = true
# Supply ship
when 218, 212, 213, 221
for id, j in enemyId
if id in supplyships and nowHp[j] is 0
progress += 1
flag = true
# Aircraft Carrier
when 211, 220
for id, j in enemyId
if id in aircraftcarriers and nowHp[j] is 0
progress += 1
flag = true
break
# Submarines
when 230, 228
for id, j in enemyId
if id in submarines and nowHp[j] is 0
progress += 1
flag = true
break
# southwest
when 226
if @mapArea == 2
if @isBoss
switch @rank
when "A", "S", "B"
progress += 1
flag = true
# west
when 229
if @mapArea == 4
if @isBoss
switch @rank
when "A", "S", "B"
progress += 1
flag = true
# west 4-4
when 242
if @mapArea == 4 and @mapInfo == 4
if @isBoss
switch @rank
when "A", "S", "B"
progress += 1
flag = true
# north 3-3...3-5
when 241
if @mapArea == 3 and @mapInfo > 2
if @isBoss
switch @rank
when "A", "S", "B"
progress += 1
flag = true
# south 5-2
when 243
if @mapArea == 5 and @mapInfo == 2
if @isBoss
switch @rank
when "S"
progress += 1
flag = true
# near 1-5
when 261
if @mapArea == 1 and @mapInfo == 5
if @isBoss
switch @rank
when "A", "S"
progress += 1
flag = true
# Code A # fight, S, boss fight, boss SAB
when 214
if codeA[0] < @codeAtarget[0]
codeA[0] += 1
flag = true
if @rank == "S"
if codeA[1] < @codeAtarget[1]
codeA[1] += 1
if @isBoss
if codeA[2] < @codeAtarget[2]
codeA[2] += 1
if @isBoss and (@rank == "S" || "A" || "B")
if codeA[3] < @codeAtarget[3]
codeA[3] += 1
progress = codeA.reduce (a, b) -> a + b
newProgress[i] = progress = if progress > target then target else progress
newTarget[i] = target
newPercent[i] = Math.floor(progress / target * 100)
# Save progress by memberId and questId
if task.id == CODEA
setProgressByTask task, codeA, @track
else
setProgressByTask task, progress, @track
saveTracker @track
if flag
@codeA = codeA
@progress = newProgress
@target = newTarget
@percent = newPercent
event = new CustomEvent 'task.update',
bubbles: true
cancelable: true
detail:
codeA: codeA
percent: newPercent
progress: newProgress
target: newTarget
window.dispatchEvent event
handleTaskDidChange: (e) ->
{tasks} = e.detail
newPercent = [0, 0, 0, 0, 0, 0]
newProgress = [0, 0, 0, 0, 0, 0]
newTarget = [1, 1, 1, 1, 1, 1]
codeA = @codeA
# Save Data
for task, i in @tasks
continue unless task?
if task.id == CODEA
setProgressByTask task, @codeA, @track
else
setProgressByTask task, @progress[i], @track
# lower the frequency saving settings to increase performance
@tracks = _.sortBy @tracks, (e) -> e.id
saveTracker @track
# refresh quests
for task, i in tasks
if task.id == CODEA
codeA = getProgressById task.id, @track
if codeA == 0
codeA = [0, 0, 0, 0]
progress = codeA.reduce (a, b) -> a + b
else
progress = getProgressById task.id, @track
target = getTargetById task.id
percent = Math.floor(progress / target * 100)
actual = 0
if task.progress == '达成'
actual = 100
else if task.progress == '50%'
actual = 50
else if task.progress == '80%'
actual = 80
if percent < actual
progress = Math.ceil(actual / 100 * target)
newProgress[i] = progress
newTarget[i] = target
newPercent[i] = percent = Math.floor(progress / target * 100)
@tasks = Object.clone tasks
@codeA = codeA
@progress = newProgress
@target = newTarget
@percent = newPercent
# notify shipview
event = new CustomEvent 'task.update',
bubbles: true
cancelable: true
detail:
codeA: codeA
percent: newPercent
progress: newProgress
target: newTarget
window.dispatchEvent event
refreshTrack: ->
curDay = getCurrentDay()
return if prevDay == curDay
@track = @track.filter (t) -> t.type not in [2, 4, 5]
if curDay is 1
@track = @track.filter (t) -> t.type not in [3]
@track = _.sortBy @track, (t) -> t.id
saveTracker @track
prevDay = curDay
componentWillMount: ->
# Read saved config
track = readTracker()
if not Array.isArray(track)
warn "no quest track id #{@memberId}"
track = []
@track = Object.clone(track)
idx = _.findIndex @track, (t) -> t.id == CODEA
if idx != -1
codeA = Object.clone(@track[idx].progress)
@track[idx].progress = codeA
@codeA = codeA
componentDidMount: ->
window.addEventListener "task.change", @handleTaskDidChange
window.addEventListener "battle.result", @handleBattleResult
window.addEventListener "game.response", @handleResponse
@interval = setInterval @refreshTrack, 30000
# window.addEventListener "window.beforeclose", @saveTracker
componentWillUnmount: ->
window.removeEventListener "task.change", @handleTaskDidChange
window.removeEventListener "battle.result", @handleBattleResult
window.removeEventListener "game.response", @handleResponse
clearInterval @interval
# window.removeEventListener "window.beforeclose", @saveTracker
render: ->
<div/>
|
[
{
"context": "------------------\n\nclass Animal\n constructor: (@name) ->\n\n move: (meters) ->\n alert @name + \" move",
"end": 84,
"score": 0.7628734111785889,
"start": 80,
"tag": "USERNAME",
"value": "name"
},
{
"context": "ert \"Galloping...\"\n super 45\n\nsam = new Snake \"Sammy the Python\"\ntom = new Horse \"Tommy the Palomino\"\n\nsam.move()",
"end": 337,
"score": 0.9957014322280884,
"start": 321,
"tag": "NAME",
"value": "Sammy the Python"
},
{
"context": "m = new Snake \"Sammy the Python\"\ntom = new Horse \"Tommy the Palomino\"\n\nsam.move()\ntom.move()\n\n\n# 2. Tests ------------",
"end": 374,
"score": 0.9973811507225037,
"start": 356,
"tag": "NAME",
"value": "Tommy the Palomino"
}
] | spec/coffeescript.coffee | mdeboer/tone-syntax | 91 |
# 1. Example ----------------------------------
class Animal
constructor: (@name) ->
move: (meters) ->
alert @name + " moved #{meters}m."
class Snake extends Animal
move: ->
alert "Slithering..."
super 5
class Horse extends Animal
move: ->
alert "Galloping..."
super 45
sam = new Snake "Sammy the Python"
tom = new Horse "Tommy the Palomino"
sam.move()
tom.move()
# 2. Tests ----------------------------------
# Assignment:
number = 42
opposite = true
not-true = false
# Conditions:
number = -42 if opposite
# Functions:
square = (x) -> x * x
# Arrays:
list = [1, 2, 3, 4, 5]
# Objects:
math =
root: Math.sqrt
square: square
cube: (x) -> x * square x
# Splats:
race = (winner, runners...) ->
print winner, runners
# Existence:
alert "I knew it!" if elvis?
# Array comprehensions:
cubes = (math.cube num for num in list)
| 80302 |
# 1. Example ----------------------------------
class Animal
constructor: (@name) ->
move: (meters) ->
alert @name + " moved #{meters}m."
class Snake extends Animal
move: ->
alert "Slithering..."
super 5
class Horse extends Animal
move: ->
alert "Galloping..."
super 45
sam = new Snake "<NAME>"
tom = new Horse "<NAME>"
sam.move()
tom.move()
# 2. Tests ----------------------------------
# Assignment:
number = 42
opposite = true
not-true = false
# Conditions:
number = -42 if opposite
# Functions:
square = (x) -> x * x
# Arrays:
list = [1, 2, 3, 4, 5]
# Objects:
math =
root: Math.sqrt
square: square
cube: (x) -> x * square x
# Splats:
race = (winner, runners...) ->
print winner, runners
# Existence:
alert "I knew it!" if elvis?
# Array comprehensions:
cubes = (math.cube num for num in list)
| true |
# 1. Example ----------------------------------
class Animal
constructor: (@name) ->
move: (meters) ->
alert @name + " moved #{meters}m."
class Snake extends Animal
move: ->
alert "Slithering..."
super 5
class Horse extends Animal
move: ->
alert "Galloping..."
super 45
sam = new Snake "PI:NAME:<NAME>END_PI"
tom = new Horse "PI:NAME:<NAME>END_PI"
sam.move()
tom.move()
# 2. Tests ----------------------------------
# Assignment:
number = 42
opposite = true
not-true = false
# Conditions:
number = -42 if opposite
# Functions:
square = (x) -> x * x
# Arrays:
list = [1, 2, 3, 4, 5]
# Objects:
math =
root: Math.sqrt
square: square
cube: (x) -> x * square x
# Splats:
race = (winner, runners...) ->
print winner, runners
# Existence:
alert "I knew it!" if elvis?
# Array comprehensions:
cubes = (math.cube num for num in list)
|
[
{
"context": "# @author mr.doob / http://mrdoob.com/\n# @author mikael emtinger / ",
"end": 17,
"score": 0.9887886643409729,
"start": 10,
"tag": "NAME",
"value": "mr.doob"
},
{
"context": "# @author mr.doob / http://mrdoob.com/\n# @author mikael emtinger / http://gomo.se/\n# @author aladjev.andrew@gmail.",
"end": 64,
"score": 0.9998430609703064,
"start": 49,
"tag": "NAME",
"value": "mikael emtinger"
},
{
"context": "author mikael emtinger / http://gomo.se/\n# @author aladjev.andrew@gmail.com\n\n#= require new_src/core/object_3d\n#= require new",
"end": 117,
"score": 0.9999096393585205,
"start": 93,
"tag": "EMAIL",
"value": "aladjev.andrew@gmail.com"
}
] | source/javascripts/new_src/cameras/camera.coffee | andrew-aladev/three.js | 0 | # @author mr.doob / http://mrdoob.com/
# @author mikael emtinger / http://gomo.se/
# @author aladjev.andrew@gmail.com
#= require new_src/core/object_3d
#= require new_src/core/matrix_4
class Camera extends THREE.Object3D
constructor: ->
super()
@matrixWorldInverse = new THREE.Matrix4()
@projectionMatrix = new THREE.Matrix4()
@projectionMatrixInverse = new THREE.Matrix4()
lookAt: (vector) ->
@matrix.lookAt @position, vector, @up
@rotation.getRotationFromMatrix @matrix if @rotationAutoUpdate
namespace "THREE", (exports) ->
exports.Camera = Camera | 140584 | # @author <NAME> / http://mrdoob.com/
# @author <NAME> / http://gomo.se/
# @author <EMAIL>
#= require new_src/core/object_3d
#= require new_src/core/matrix_4
class Camera extends THREE.Object3D
constructor: ->
super()
@matrixWorldInverse = new THREE.Matrix4()
@projectionMatrix = new THREE.Matrix4()
@projectionMatrixInverse = new THREE.Matrix4()
lookAt: (vector) ->
@matrix.lookAt @position, vector, @up
@rotation.getRotationFromMatrix @matrix if @rotationAutoUpdate
namespace "THREE", (exports) ->
exports.Camera = Camera | true | # @author PI:NAME:<NAME>END_PI / http://mrdoob.com/
# @author PI:NAME:<NAME>END_PI / http://gomo.se/
# @author PI:EMAIL:<EMAIL>END_PI
#= require new_src/core/object_3d
#= require new_src/core/matrix_4
class Camera extends THREE.Object3D
constructor: ->
super()
@matrixWorldInverse = new THREE.Matrix4()
@projectionMatrix = new THREE.Matrix4()
@projectionMatrixInverse = new THREE.Matrix4()
lookAt: (vector) ->
@matrix.lookAt @position, vector, @up
@rotation.getRotationFromMatrix @matrix if @rotationAutoUpdate
namespace "THREE", (exports) ->
exports.Camera = Camera |
[
{
"context": "#\n# * grunt-express-server\n# * https://github.com/ericclemmons/grunt-express-server\n# *\n# * Copyright (c) 2013 E",
"end": 62,
"score": 0.998761773109436,
"start": 50,
"tag": "USERNAME",
"value": "ericclemmons"
},
{
"context": "ns/grunt-express-server\n# *\n# * Copyright (c) 2013 Eric Clemmons\n# * Licensed under the MIT license.\n\n#\npath = req",
"end": 124,
"score": 0.9998698234558105,
"start": 111,
"tag": "NAME",
"value": "Eric Clemmons"
},
{
"context": "\n done = @async()\n config = grunt.config.get(@name)\n targetConfig = config[@target]\n if server",
"end": 503,
"score": 0.9624272584915161,
"start": 498,
"tag": "USERNAME",
"value": "@name"
}
] | tasks/express-server.coffee | davemaurakis/sumbro | 3 | #
# * grunt-express-server
# * https://github.com/ericclemmons/grunt-express-server
# *
# * Copyright (c) 2013 Eric Clemmons
# * Licensed under the MIT license.
#
path = require 'path'
server = null # Store server between live reloads to close/restart express
module.exports = (grunt) ->
@registerTask 'express-keepalive', 'keep an express server alive', ->
done = @async()
@registerMultiTask 'express', 'Start an express web server', ->
done = @async()
config = grunt.config.get(@name)
targetConfig = config[@target]
if server
console.log 'Killing existing Express server'
server.kill 'SIGTERM'
server = null
server = grunt.util.spawn
cmd: 'coffee'
args: [targetConfig]
fallback: ->
# Prevent EADDRINUSE from breaking Grunt
, (err, result, code) ->
server.stdout.on 'data', ->
done() if done
done = null
server.stdout.pipe process.stdout
server.stderr.pipe process.stdout
| 224538 | #
# * grunt-express-server
# * https://github.com/ericclemmons/grunt-express-server
# *
# * Copyright (c) 2013 <NAME>
# * Licensed under the MIT license.
#
path = require 'path'
server = null # Store server between live reloads to close/restart express
module.exports = (grunt) ->
@registerTask 'express-keepalive', 'keep an express server alive', ->
done = @async()
@registerMultiTask 'express', 'Start an express web server', ->
done = @async()
config = grunt.config.get(@name)
targetConfig = config[@target]
if server
console.log 'Killing existing Express server'
server.kill 'SIGTERM'
server = null
server = grunt.util.spawn
cmd: 'coffee'
args: [targetConfig]
fallback: ->
# Prevent EADDRINUSE from breaking Grunt
, (err, result, code) ->
server.stdout.on 'data', ->
done() if done
done = null
server.stdout.pipe process.stdout
server.stderr.pipe process.stdout
| true | #
# * grunt-express-server
# * https://github.com/ericclemmons/grunt-express-server
# *
# * Copyright (c) 2013 PI:NAME:<NAME>END_PI
# * Licensed under the MIT license.
#
path = require 'path'
server = null # Store server between live reloads to close/restart express
module.exports = (grunt) ->
@registerTask 'express-keepalive', 'keep an express server alive', ->
done = @async()
@registerMultiTask 'express', 'Start an express web server', ->
done = @async()
config = grunt.config.get(@name)
targetConfig = config[@target]
if server
console.log 'Killing existing Express server'
server.kill 'SIGTERM'
server = null
server = grunt.util.spawn
cmd: 'coffee'
args: [targetConfig]
fallback: ->
# Prevent EADDRINUSE from breaking Grunt
, (err, result, code) ->
server.stdout.on 'data', ->
done() if done
done = null
server.stdout.pipe process.stdout
server.stderr.pipe process.stdout
|
[
{
"context": "d make requests to redmine server\n#\n# 10.03.2015\n# Kirill Temnov\n#\n\n# coffeelint: disable=max_line_length, enable=",
"end": 115,
"score": 0.9998652935028076,
"start": 102,
"tag": "NAME",
"value": "Kirill Temnov"
}
] | index.coffee | KirillTemnov/redmine-eye | 1 | #!/usr/bin/env coffee
#
# Read data from config and make requests to redmine server
#
# 10.03.2015
# Kirill Temnov
#
# coffeelint: disable=max_line_length, enable=colon_assignment_spacing
usage = """
Usage: ry COMMAND [--debug] [--pid PROJECT_ID]
COMMANDS:
projects - list projects(--limit, --offset)
log - list of issues
time - work time
issue - create an issue
issues - batch create several issues
i - info on issue
aw - add watcher
ms - list of milestones
conf - configuration
project-stat - statistics on project tasks
stat - statistics on project users
statuses - list of statuses
user - user stat in project
help - help on command
team, teams - manage teams
watch - filter tasks
users - list of redmine users (fetch all users only by admin)
groups - list of redmine groups
star, unstar - star or unstar issue
"""
argv = require("optimist").usage(usage).argv
DEBUG_MODE = argv.debug
if 0 is argv._.length
if argv.v
pkg = require "./package.json"
console.log pkg.name
console.log "version: #{pkg.version}"
console.log "created with ☕ script"
return
else
return console.log usage
{setup, config} = require "./config"
if "conf" in argv._
if 1 is argv._.length
for k, v of config.get()
console.log "#{k}\t:\t#{v}"
if 2 is argv._.length
console.log config.get(argv._[1]) or "{not found}"
if 3 is argv._.length
if "del" is argv._[1] # remove element
config.clear argv._[2]
else
config.set argv._[1], argv._[2]
config.save (err) -> # todo move config saving in separate function
if err
console.error "error saving config"
else
console.log "#{argv._[1]}\t:\t#{argv._[2]}\nsaved."
return
return unless setup()
#console.log "ARGV = #{JSON.stringify argv, null, 2}"
{copyArgv, padRight, dup, DUMP_JSON_BODY, DUMP_JSON, DUMP_USERS, DUMP_USER_SORTED_ISSUES, DUMP_USER_SORTED_ISSUES_NC, DUMP_ISSUE, RedmineAPI} = require "./redmine-api"
#--------------------------------------------------------------------------------
#
# Get user, for who we'll apply command (team or user)
#
getWho = (argvObj=argv) ->
who = argvObj._
who = ["me"] if 0 is who.length
teams = config.get("teams") or {}
who = who[0]
if teams[who]?
teams[who]
else if ("me" is who) or /^\d+$/.test who
[who]
else
[]
api = new RedmineAPI config
ARGV = copyArgv argv
if argv._[0] in ["star", "unstar"]
cmd = argv._.shift()
if "star" is cmd
stars = config.get("stars") or {}
subcmd = argv._[0]
if "show" is subcmd
console.log "todo show"
else
now = (new Date).getTime()
for issue in argv._
if /^\d+$/.test issue
stars[issue] = now
config.set "stars", stars
config.save (err) ->
if err
console.error "error saving config"
else
console.log "implement unstar"
return
if "projects" is argv._[0]
ARGV.limit ||= 100
if DEBUG_MODE
api.getProjects ARGV, DUMP_JSON_BODY
else
api.getProjects ARGV
return
# stelth mode
if "projects-info" is argv._[0]
proceed_projects = 0
ARGV.limit = 100
console.log "fetch projects"
api.getProjects ARGV, (err, resp, body) ->
unless err
body = JSON.parse body
body.projects.map (p) ->
opts = project_id: p.id, status_id: "open", all: yes
newApi = new RedmineAPI config
newApi.getIssues opts, (err, issues) ->
unless err
console.log "| #{padRight issues.length, 6} | #{padRight p.name, 50} | #{padRight p.identifier, 25} | "
# todo add total count
if "log" is argv._[0]
ARGV.status_id = "*" # TODO watch this!
if DEBUG_MODE
api.getIssues ARGV, DUMP_JSON
else
api.getIssues ARGV
return
if "aw" is argv._[0]
argv._.shift()
who = getWho()
issues = argv._[1..].filter (t) -> /^\d+$/.test t
api.addWatcher users: who, issues: issues
# console.log "who = #{JSON.stringify who, null, 2}"
# console.log "tasks = #{JSON.stringify issues, null, 2}"
return
# watch my tasks
if "watch" is argv._[0]
fn = DUMP_USER_SORTED_ISSUES
if argv["nocolor"]?
fn = DUMP_USER_SORTED_ISSUES_NC
if argv["closed"]?
ARGV.status_id = "closed"
if argv["all"]?
ARGV.all = yes
argv._.shift()
who = argv._ # list of users/groups
ARGV.status_id ||= "open"
ARGV.limit ||= 100
who = ["me"] if 0 is who.length
teams = config.get("teams") or {}
for name in who
userArgs = copyArgv ARGV
# search team
if teams[name]?
for person_id in teams[name]
teamUserArgs = copyArgv ARGV
teamUserArgs.assigned_to_id = person_id
# add extra creation instance for prevent broke counters
api = new RedmineAPI config
api.getIssues teamUserArgs, fn
else
if name is "me"
userArgs.assigned_to_id = "me"
else if /^\d+$/.test name
userArgs.assigned_to_id = name
else
continue
# add extra creation instance for prevent broke counters
api = new RedmineAPI config
api.getIssues userArgs, fn
return
if argv._[0] in ["ms", "versions"]
if DEBUG_MODE
api.getVersions pid: argv.pid, DUMP_JSON_BODY
else
api.getVersions pid: argv.pid
return
if "time" is argv._[0]
# search teams
argv._.shift()
who = argv._
who = ["me"] if 0 is who.length
teams = config.get("teams") or {}
name = who.pop()
if "me" is name
ARGV.user_id = "me"
else if teams[name]?
ARGV.user_id = teams[name].join ","
else if /^\d+$/.test name
ARGV.user_id = name
if DEBUG_MODE
api.getTimeEntries ARGV, DUMP_JSON
else
api.getTimeEntries ARGV
return
if "users" is argv._[0]
ARGV.limit ||= 100 # Lifehack
if "yes" is config.get "admin"
api.getUsers ARGV
else
unless ARGV["pid"] or ARGV["project_id"]
console.error "You are not admin. Set `admin` option in config, or set `--pid` option".red # TODO add localization
else
api.getProjectUsers ARGV # TODO change dump function
return
if "groups" is argv._[0]
api.getGroups ARGV
return
if "project-stat" is argv._[0]
api.getProjectStat ARGV
return
if "stat" is argv._[0]
unless ARGV.sort in ["name", "created", "work", "closed", "done"]
ARGV.sort = "created"
api.getUsersStat ARGV
return
if "user" is argv._[0]
api.getUserStat ARGV
return
if "issue" is argv._[0]
api.createIssue ARGV, argv._[1..].join " "
return
if "i" is argv._[0]
if 1 is argv._.length
console.error "empty ussues list" # todo localization
return
for i in argv._[1..]
if DEBUG_MODE
api.getIssueInfo i, {}, DUMP_JSON_BODY
else
api.getIssueInfo i, {}, DUMP_ISSUE
#api.getIssueInfo
if "statuses" is argv._[0]
if DEBUG_MODE
api.getIssueStatuses {}, DUMP_JSON_BODY
else
api.getIssueStatuses()
return
if "trackers" is argv._[0]
api.getTrackers ARGV
return
if "team" is argv._[0]
[name, action, ids] = argv._[1..]
teams = config.get("teams") or {}
action ||= "list"
getNameAndId = (id, name) -> "| #{padRight id, 4} | #{padRight name, 30} |"
printNameAndID = (id, name) -> console.log getNameAndId id, name
switch action
when "list"
console.log "" # TODO move this ugly peace of code somewhere
if "yes" is config.get "admin" # show admin users
ARGV.limit = 100
api.getUsers ARGV, (err, resp, body) ->
if err is null
body = JSON.parse body
console.log dup "=", 41
for u in body.users
if u.id.toString() in teams[name]
printNameAndID "#{u.id}", "#{u.firstname} #{u.lastname}"
if "me" in teams[name]
api.getCurrentUser (err, resp, body) ->
if err
console.log getNameAndId("me", "Can't fetch my name").red
else
me = JSON.parse body
console.log getNameAndId("#{me.user.id}", "#{me.user.firstname} #{me.user.lastname}").bold
console.log dup "=", 41
console.log ""
else
console.log dup "=", 41
console.log ""
else
console.error "#{resp.request.method}\t#{resp.request.uri.href}"
console.error err
else
console.log dup "=", 41
teams[name].map (id) -> printNameAndID id, "user ...."
console.log dup "=", 41
console.log ""
return
when "add"
unless teams[name]?
teams[name] = []
ids.toString().split(",").map (id) ->
return if not id or 0 is id.length
unless id in teams[name]
teams[name].push id
when "remove", "rm"
if teams[name]?
rmMembers = ids.toString().split ","
newTeam = []
for i in teams[name]
newTeam.push i unless i in rmMembers
teams[name] = newTeam
delete teams[name] if 0 is newTeam.length
else
return # don't save anything
config.set "teams", teams
config.save (err) ->
if err
console.error "error saving team"
else
console.log "team updated"
return
if "teams" is argv._[0]
for k,v of config.get("teams") or {}
console.log k
return
| 180895 | #!/usr/bin/env coffee
#
# Read data from config and make requests to redmine server
#
# 10.03.2015
# <NAME>
#
# coffeelint: disable=max_line_length, enable=colon_assignment_spacing
usage = """
Usage: ry COMMAND [--debug] [--pid PROJECT_ID]
COMMANDS:
projects - list projects(--limit, --offset)
log - list of issues
time - work time
issue - create an issue
issues - batch create several issues
i - info on issue
aw - add watcher
ms - list of milestones
conf - configuration
project-stat - statistics on project tasks
stat - statistics on project users
statuses - list of statuses
user - user stat in project
help - help on command
team, teams - manage teams
watch - filter tasks
users - list of redmine users (fetch all users only by admin)
groups - list of redmine groups
star, unstar - star or unstar issue
"""
argv = require("optimist").usage(usage).argv
DEBUG_MODE = argv.debug
if 0 is argv._.length
if argv.v
pkg = require "./package.json"
console.log pkg.name
console.log "version: #{pkg.version}"
console.log "created with ☕ script"
return
else
return console.log usage
{setup, config} = require "./config"
if "conf" in argv._
if 1 is argv._.length
for k, v of config.get()
console.log "#{k}\t:\t#{v}"
if 2 is argv._.length
console.log config.get(argv._[1]) or "{not found}"
if 3 is argv._.length
if "del" is argv._[1] # remove element
config.clear argv._[2]
else
config.set argv._[1], argv._[2]
config.save (err) -> # todo move config saving in separate function
if err
console.error "error saving config"
else
console.log "#{argv._[1]}\t:\t#{argv._[2]}\nsaved."
return
return unless setup()
#console.log "ARGV = #{JSON.stringify argv, null, 2}"
{copyArgv, padRight, dup, DUMP_JSON_BODY, DUMP_JSON, DUMP_USERS, DUMP_USER_SORTED_ISSUES, DUMP_USER_SORTED_ISSUES_NC, DUMP_ISSUE, RedmineAPI} = require "./redmine-api"
#--------------------------------------------------------------------------------
#
# Get user, for who we'll apply command (team or user)
#
getWho = (argvObj=argv) ->
who = argvObj._
who = ["me"] if 0 is who.length
teams = config.get("teams") or {}
who = who[0]
if teams[who]?
teams[who]
else if ("me" is who) or /^\d+$/.test who
[who]
else
[]
api = new RedmineAPI config
ARGV = copyArgv argv
if argv._[0] in ["star", "unstar"]
cmd = argv._.shift()
if "star" is cmd
stars = config.get("stars") or {}
subcmd = argv._[0]
if "show" is subcmd
console.log "todo show"
else
now = (new Date).getTime()
for issue in argv._
if /^\d+$/.test issue
stars[issue] = now
config.set "stars", stars
config.save (err) ->
if err
console.error "error saving config"
else
console.log "implement unstar"
return
if "projects" is argv._[0]
ARGV.limit ||= 100
if DEBUG_MODE
api.getProjects ARGV, DUMP_JSON_BODY
else
api.getProjects ARGV
return
# stelth mode
if "projects-info" is argv._[0]
proceed_projects = 0
ARGV.limit = 100
console.log "fetch projects"
api.getProjects ARGV, (err, resp, body) ->
unless err
body = JSON.parse body
body.projects.map (p) ->
opts = project_id: p.id, status_id: "open", all: yes
newApi = new RedmineAPI config
newApi.getIssues opts, (err, issues) ->
unless err
console.log "| #{padRight issues.length, 6} | #{padRight p.name, 50} | #{padRight p.identifier, 25} | "
# todo add total count
if "log" is argv._[0]
ARGV.status_id = "*" # TODO watch this!
if DEBUG_MODE
api.getIssues ARGV, DUMP_JSON
else
api.getIssues ARGV
return
if "aw" is argv._[0]
argv._.shift()
who = getWho()
issues = argv._[1..].filter (t) -> /^\d+$/.test t
api.addWatcher users: who, issues: issues
# console.log "who = #{JSON.stringify who, null, 2}"
# console.log "tasks = #{JSON.stringify issues, null, 2}"
return
# watch my tasks
if "watch" is argv._[0]
fn = DUMP_USER_SORTED_ISSUES
if argv["nocolor"]?
fn = DUMP_USER_SORTED_ISSUES_NC
if argv["closed"]?
ARGV.status_id = "closed"
if argv["all"]?
ARGV.all = yes
argv._.shift()
who = argv._ # list of users/groups
ARGV.status_id ||= "open"
ARGV.limit ||= 100
who = ["me"] if 0 is who.length
teams = config.get("teams") or {}
for name in who
userArgs = copyArgv ARGV
# search team
if teams[name]?
for person_id in teams[name]
teamUserArgs = copyArgv ARGV
teamUserArgs.assigned_to_id = person_id
# add extra creation instance for prevent broke counters
api = new RedmineAPI config
api.getIssues teamUserArgs, fn
else
if name is "me"
userArgs.assigned_to_id = "me"
else if /^\d+$/.test name
userArgs.assigned_to_id = name
else
continue
# add extra creation instance for prevent broke counters
api = new RedmineAPI config
api.getIssues userArgs, fn
return
if argv._[0] in ["ms", "versions"]
if DEBUG_MODE
api.getVersions pid: argv.pid, DUMP_JSON_BODY
else
api.getVersions pid: argv.pid
return
if "time" is argv._[0]
# search teams
argv._.shift()
who = argv._
who = ["me"] if 0 is who.length
teams = config.get("teams") or {}
name = who.pop()
if "me" is name
ARGV.user_id = "me"
else if teams[name]?
ARGV.user_id = teams[name].join ","
else if /^\d+$/.test name
ARGV.user_id = name
if DEBUG_MODE
api.getTimeEntries ARGV, DUMP_JSON
else
api.getTimeEntries ARGV
return
if "users" is argv._[0]
ARGV.limit ||= 100 # Lifehack
if "yes" is config.get "admin"
api.getUsers ARGV
else
unless ARGV["pid"] or ARGV["project_id"]
console.error "You are not admin. Set `admin` option in config, or set `--pid` option".red # TODO add localization
else
api.getProjectUsers ARGV # TODO change dump function
return
if "groups" is argv._[0]
api.getGroups ARGV
return
if "project-stat" is argv._[0]
api.getProjectStat ARGV
return
if "stat" is argv._[0]
unless ARGV.sort in ["name", "created", "work", "closed", "done"]
ARGV.sort = "created"
api.getUsersStat ARGV
return
if "user" is argv._[0]
api.getUserStat ARGV
return
if "issue" is argv._[0]
api.createIssue ARGV, argv._[1..].join " "
return
if "i" is argv._[0]
if 1 is argv._.length
console.error "empty ussues list" # todo localization
return
for i in argv._[1..]
if DEBUG_MODE
api.getIssueInfo i, {}, DUMP_JSON_BODY
else
api.getIssueInfo i, {}, DUMP_ISSUE
#api.getIssueInfo
if "statuses" is argv._[0]
if DEBUG_MODE
api.getIssueStatuses {}, DUMP_JSON_BODY
else
api.getIssueStatuses()
return
if "trackers" is argv._[0]
api.getTrackers ARGV
return
if "team" is argv._[0]
[name, action, ids] = argv._[1..]
teams = config.get("teams") or {}
action ||= "list"
getNameAndId = (id, name) -> "| #{padRight id, 4} | #{padRight name, 30} |"
printNameAndID = (id, name) -> console.log getNameAndId id, name
switch action
when "list"
console.log "" # TODO move this ugly peace of code somewhere
if "yes" is config.get "admin" # show admin users
ARGV.limit = 100
api.getUsers ARGV, (err, resp, body) ->
if err is null
body = JSON.parse body
console.log dup "=", 41
for u in body.users
if u.id.toString() in teams[name]
printNameAndID "#{u.id}", "#{u.firstname} #{u.lastname}"
if "me" in teams[name]
api.getCurrentUser (err, resp, body) ->
if err
console.log getNameAndId("me", "Can't fetch my name").red
else
me = JSON.parse body
console.log getNameAndId("#{me.user.id}", "#{me.user.firstname} #{me.user.lastname}").bold
console.log dup "=", 41
console.log ""
else
console.log dup "=", 41
console.log ""
else
console.error "#{resp.request.method}\t#{resp.request.uri.href}"
console.error err
else
console.log dup "=", 41
teams[name].map (id) -> printNameAndID id, "user ...."
console.log dup "=", 41
console.log ""
return
when "add"
unless teams[name]?
teams[name] = []
ids.toString().split(",").map (id) ->
return if not id or 0 is id.length
unless id in teams[name]
teams[name].push id
when "remove", "rm"
if teams[name]?
rmMembers = ids.toString().split ","
newTeam = []
for i in teams[name]
newTeam.push i unless i in rmMembers
teams[name] = newTeam
delete teams[name] if 0 is newTeam.length
else
return # don't save anything
config.set "teams", teams
config.save (err) ->
if err
console.error "error saving team"
else
console.log "team updated"
return
if "teams" is argv._[0]
for k,v of config.get("teams") or {}
console.log k
return
| true | #!/usr/bin/env coffee
#
# Read data from config and make requests to redmine server
#
# 10.03.2015
# PI:NAME:<NAME>END_PI
#
# coffeelint: disable=max_line_length, enable=colon_assignment_spacing
usage = """
Usage: ry COMMAND [--debug] [--pid PROJECT_ID]
COMMANDS:
projects - list projects(--limit, --offset)
log - list of issues
time - work time
issue - create an issue
issues - batch create several issues
i - info on issue
aw - add watcher
ms - list of milestones
conf - configuration
project-stat - statistics on project tasks
stat - statistics on project users
statuses - list of statuses
user - user stat in project
help - help on command
team, teams - manage teams
watch - filter tasks
users - list of redmine users (fetch all users only by admin)
groups - list of redmine groups
star, unstar - star or unstar issue
"""
argv = require("optimist").usage(usage).argv
DEBUG_MODE = argv.debug
if 0 is argv._.length
if argv.v
pkg = require "./package.json"
console.log pkg.name
console.log "version: #{pkg.version}"
console.log "created with ☕ script"
return
else
return console.log usage
{setup, config} = require "./config"
if "conf" in argv._
if 1 is argv._.length
for k, v of config.get()
console.log "#{k}\t:\t#{v}"
if 2 is argv._.length
console.log config.get(argv._[1]) or "{not found}"
if 3 is argv._.length
if "del" is argv._[1] # remove element
config.clear argv._[2]
else
config.set argv._[1], argv._[2]
config.save (err) -> # todo move config saving in separate function
if err
console.error "error saving config"
else
console.log "#{argv._[1]}\t:\t#{argv._[2]}\nsaved."
return
return unless setup()
#console.log "ARGV = #{JSON.stringify argv, null, 2}"
{copyArgv, padRight, dup, DUMP_JSON_BODY, DUMP_JSON, DUMP_USERS, DUMP_USER_SORTED_ISSUES, DUMP_USER_SORTED_ISSUES_NC, DUMP_ISSUE, RedmineAPI} = require "./redmine-api"
#--------------------------------------------------------------------------------
#
# Get user, for who we'll apply command (team or user)
#
getWho = (argvObj=argv) ->
who = argvObj._
who = ["me"] if 0 is who.length
teams = config.get("teams") or {}
who = who[0]
if teams[who]?
teams[who]
else if ("me" is who) or /^\d+$/.test who
[who]
else
[]
api = new RedmineAPI config
ARGV = copyArgv argv
if argv._[0] in ["star", "unstar"]
cmd = argv._.shift()
if "star" is cmd
stars = config.get("stars") or {}
subcmd = argv._[0]
if "show" is subcmd
console.log "todo show"
else
now = (new Date).getTime()
for issue in argv._
if /^\d+$/.test issue
stars[issue] = now
config.set "stars", stars
config.save (err) ->
if err
console.error "error saving config"
else
console.log "implement unstar"
return
if "projects" is argv._[0]
ARGV.limit ||= 100
if DEBUG_MODE
api.getProjects ARGV, DUMP_JSON_BODY
else
api.getProjects ARGV
return
# stelth mode
if "projects-info" is argv._[0]
proceed_projects = 0
ARGV.limit = 100
console.log "fetch projects"
api.getProjects ARGV, (err, resp, body) ->
unless err
body = JSON.parse body
body.projects.map (p) ->
opts = project_id: p.id, status_id: "open", all: yes
newApi = new RedmineAPI config
newApi.getIssues opts, (err, issues) ->
unless err
console.log "| #{padRight issues.length, 6} | #{padRight p.name, 50} | #{padRight p.identifier, 25} | "
# todo add total count
if "log" is argv._[0]
ARGV.status_id = "*" # TODO watch this!
if DEBUG_MODE
api.getIssues ARGV, DUMP_JSON
else
api.getIssues ARGV
return
if "aw" is argv._[0]
argv._.shift()
who = getWho()
issues = argv._[1..].filter (t) -> /^\d+$/.test t
api.addWatcher users: who, issues: issues
# console.log "who = #{JSON.stringify who, null, 2}"
# console.log "tasks = #{JSON.stringify issues, null, 2}"
return
# watch my tasks
if "watch" is argv._[0]
fn = DUMP_USER_SORTED_ISSUES
if argv["nocolor"]?
fn = DUMP_USER_SORTED_ISSUES_NC
if argv["closed"]?
ARGV.status_id = "closed"
if argv["all"]?
ARGV.all = yes
argv._.shift()
who = argv._ # list of users/groups
ARGV.status_id ||= "open"
ARGV.limit ||= 100
who = ["me"] if 0 is who.length
teams = config.get("teams") or {}
for name in who
userArgs = copyArgv ARGV
# search team
if teams[name]?
for person_id in teams[name]
teamUserArgs = copyArgv ARGV
teamUserArgs.assigned_to_id = person_id
# add extra creation instance for prevent broke counters
api = new RedmineAPI config
api.getIssues teamUserArgs, fn
else
if name is "me"
userArgs.assigned_to_id = "me"
else if /^\d+$/.test name
userArgs.assigned_to_id = name
else
continue
# add extra creation instance for prevent broke counters
api = new RedmineAPI config
api.getIssues userArgs, fn
return
if argv._[0] in ["ms", "versions"]
if DEBUG_MODE
api.getVersions pid: argv.pid, DUMP_JSON_BODY
else
api.getVersions pid: argv.pid
return
if "time" is argv._[0]
# search teams
argv._.shift()
who = argv._
who = ["me"] if 0 is who.length
teams = config.get("teams") or {}
name = who.pop()
if "me" is name
ARGV.user_id = "me"
else if teams[name]?
ARGV.user_id = teams[name].join ","
else if /^\d+$/.test name
ARGV.user_id = name
if DEBUG_MODE
api.getTimeEntries ARGV, DUMP_JSON
else
api.getTimeEntries ARGV
return
if "users" is argv._[0]
ARGV.limit ||= 100 # Lifehack
if "yes" is config.get "admin"
api.getUsers ARGV
else
unless ARGV["pid"] or ARGV["project_id"]
console.error "You are not admin. Set `admin` option in config, or set `--pid` option".red # TODO add localization
else
api.getProjectUsers ARGV # TODO change dump function
return
if "groups" is argv._[0]
api.getGroups ARGV
return
if "project-stat" is argv._[0]
api.getProjectStat ARGV
return
if "stat" is argv._[0]
unless ARGV.sort in ["name", "created", "work", "closed", "done"]
ARGV.sort = "created"
api.getUsersStat ARGV
return
if "user" is argv._[0]
api.getUserStat ARGV
return
if "issue" is argv._[0]
api.createIssue ARGV, argv._[1..].join " "
return
if "i" is argv._[0]
if 1 is argv._.length
console.error "empty ussues list" # todo localization
return
for i in argv._[1..]
if DEBUG_MODE
api.getIssueInfo i, {}, DUMP_JSON_BODY
else
api.getIssueInfo i, {}, DUMP_ISSUE
#api.getIssueInfo
if "statuses" is argv._[0]
if DEBUG_MODE
api.getIssueStatuses {}, DUMP_JSON_BODY
else
api.getIssueStatuses()
return
if "trackers" is argv._[0]
api.getTrackers ARGV
return
if "team" is argv._[0]
[name, action, ids] = argv._[1..]
teams = config.get("teams") or {}
action ||= "list"
getNameAndId = (id, name) -> "| #{padRight id, 4} | #{padRight name, 30} |"
printNameAndID = (id, name) -> console.log getNameAndId id, name
switch action
when "list"
console.log "" # TODO move this ugly peace of code somewhere
if "yes" is config.get "admin" # show admin users
ARGV.limit = 100
api.getUsers ARGV, (err, resp, body) ->
if err is null
body = JSON.parse body
console.log dup "=", 41
for u in body.users
if u.id.toString() in teams[name]
printNameAndID "#{u.id}", "#{u.firstname} #{u.lastname}"
if "me" in teams[name]
api.getCurrentUser (err, resp, body) ->
if err
console.log getNameAndId("me", "Can't fetch my name").red
else
me = JSON.parse body
console.log getNameAndId("#{me.user.id}", "#{me.user.firstname} #{me.user.lastname}").bold
console.log dup "=", 41
console.log ""
else
console.log dup "=", 41
console.log ""
else
console.error "#{resp.request.method}\t#{resp.request.uri.href}"
console.error err
else
console.log dup "=", 41
teams[name].map (id) -> printNameAndID id, "user ...."
console.log dup "=", 41
console.log ""
return
when "add"
unless teams[name]?
teams[name] = []
ids.toString().split(",").map (id) ->
return if not id or 0 is id.length
unless id in teams[name]
teams[name].push id
when "remove", "rm"
if teams[name]?
rmMembers = ids.toString().split ","
newTeam = []
for i in teams[name]
newTeam.push i unless i in rmMembers
teams[name] = newTeam
delete teams[name] if 0 is newTeam.length
else
return # don't save anything
config.set "teams", teams
config.save (err) ->
if err
console.error "error saving team"
else
console.log "team updated"
return
if "teams" is argv._[0]
for k,v of config.get("teams") or {}
console.log k
return
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.