language
stringclasses
5 values
text
stringlengths
15
988k
JavaScript
class Footer extends React.Component { render() { var style = { backgroundColor: '#FFFFFF', borderTop: '1px solid #E7E7E7', position: 'fixed', bottom: 0, margin: 0, height: '60px', width: '100%' }; return ( <div style={style} className="ui equal width height grid"> <div style={{ textAlign: 'right', paddingTop: 0, paddingRight: 0 }} className="column" > {/* <img src={Logo} alt="" /> </div> <div style={{ textAlign: 'left', verticalAlign: 'middle', paddingLeft: 0 }} className="column" > */} <div> <p> initiable.com &copy; {new Date().getFullYear()}. All rights reserved. </p> </div> </div> </div> ); } }
JavaScript
class ResourceMapper { static select(id){ try { resource = IdentifyMap[id]; return {status: 0, message: 'Ok', results: resource}; } catch (e) { try{ let resource = {}; const resource_data = connection.query(`SELECT * FROM resource where id= '${id}'`); if (resource_data.length > 0){ const resource_id = resource_data[0].id; const resource_type = resource_data[0].type; const query = connection.query(`SELECT * FROM ${resource_type} where resource_id= '${resource_id}'`) const child_data = query[0]; child_data.title = resource_data[0].title; switch(resource_type){ case "book": resource = new Book(child_data,resource_id); break; case "magazine": resource = new Magazine(child_data,resource_id); break; case "movie": resource = new Movie(child_data,resource_id); console.log(resource); break; case "music": resource = new Music(child_data,resource_id); break; } resource.resource_type = resource_type; IdentifyMap[resource_id] = resource; return {status: 0, message: 'Ok', results: resource}; } else { throw "Invalid Resource Id." } } catch (error){ return{ status: 1, message: 'Error: ' + error, error} } } } static advSelect(search,isadvancedSearch){ if(isadvancedSearch){ let verifyIfNoelement= { checked:[]}; let AllInfo = []; let SearchInfoId = []; if(!(JSON.stringify(verifyIfNoelement) == JSON.stringify(search))){ if(search['checked'].length !=0){ // if the client check at least one type let parameter =false; let query=""; for(let x=0;x<search['checked'].length;x++){ switch(search['checked'][x]){ // iterate over type checked case "book": parameter = false; query =" Select * from book LEFT JOIN resource on book.resource_id = resource.id "; if(!(search['titleSearch'] == undefined) && search['titleSearch'] != ''){ let titleToArray = search['titleSearch'].split(" "); // title to array by part query+="where "; parameter = true; for(let i=0;i<titleToArray.length;i++){ if(i==0) query+="title LIKE '%"+titleToArray[i]+"%' "; else{ query+=" OR title LIKE '%"+titleToArray[i]+"%'"; } } } if(!(search['pickedAuthor'] == undefined) && search['pickedAuthor'] != ''){ if(parameter) query+=" OR author = '"+search['pickedAuthor']+"'"; else{ query+="where "; parameter = true; query+="author = '"+search['pickedAuthor']+"'"; }} if(!(search['ISBNSearch'] == undefined) && search['ISBNSearch'] != ''){ if(parameter) query+=" OR ISBN_10 LIKE '%"+search['ISBNSearch']+"%' OR ISBN_13 LIKE '%"+search['ISBNSearch']+"%'"; else{ query+="where "; query+="ISBN_10 LIKE '%"+search['ISBNSearch']+"%' OR ISBN_13 LIKE '%"+search['ISBNSearch']+"%'"; } } const bookInfo = connection.query(query); for (let i=0; i<bookInfo.length;i++){ const LoanOrNot = connection.query("SELECT SUM(CASE WHEN user_id is NOT NULL THEN 1 else 0 END) as loan, SUM(CASE WHEN user_id is NULL THEN 1 else 0 END) as available FROM resource_line_item where resource_id = '"+bookInfo[i]['resource_id']+"' "); if(SearchInfoId.indexOf(bookInfo[i]['resource_id']) == -1){ SearchInfoId.push(bookInfo[i]['resource_id']); bookInfo[i]['loan']=LoanOrNot[0]['loan']; bookInfo[i]['available']=LoanOrNot[0]['available']; bookInfo[i]['restype']="book"; const LineItem = connection.query(" SELECT * FROM resource_line_item where resource_id = '"+bookInfo[i]['resource_id']+"' "); bookInfo[i]['lineItem']=[]; let eachInfo ={}; for(let info=0;info< LineItem.length;info++){ eachInfo = {id:LineItem[info]['id'],resource_id:LineItem[info]['resource_id'],user_id:LineItem[info]['user_id'],date_due:LineItem[info]['date_due']} bookInfo[i]['lineItem'].push(eachInfo); } AllInfo.push(bookInfo[i]); } } break; case "magazine": parameter = false; query =" Select * from magazine LEFT JOIN resource on magazine.resource_id = resource.id "; if(!(search['titleSearch'] == undefined) && search['titleSearch'] != ''){ let titleToArray = search['titleSearch'].split(" "); // title to array by part query+="where "; parameter = true; for(let i=0;i<titleToArray.length;i++){ if(i==0) query+="title LIKE '%"+titleToArray[i]+"%' "; else{ query+=" OR title LIKE '%"+titleToArray[i]+"%'"; } } } if(!(search['pickedPublisher'] == undefined) && search['pickedPublisher'] != ''){ if(parameter) query+=" OR publisher = '"+search['pickedPublisher']+"'"; else{ query+="where "; parameter = true; query+="publisher = '"+search['pickedPublisher']+"'"; }} if(!(search['ISBNSearch'] == undefined) && search['ISBNSearch'] != ''){ if(parameter) query+=" OR ISBN_10 LIKE '%"+search['ISBNSearch']+"%' OR ISBN_13 LIKE '%"+search['ISBNSearch']+"%'"; else{ query+="where "; query+="ISBN_10 LIKE '%"+search['ISBNSearch']+"%' OR ISBN_13 LIKE '%"+search['ISBNSearch']+"%'"; } } const magazineInfo = connection.query(query); for (let i=0; i<magazineInfo.length;i++){ const LoanOrNot = connection.query("SELECT SUM(CASE WHEN user_id is NOT NULL THEN 1 else 0 END) as loan, SUM(CASE WHEN user_id is NULL THEN 1 else 0 END) as available FROM resource_line_item where resource_id = '"+magazineInfo[i]['resource_id']+"' "); if(SearchInfoId.indexOf(magazineInfo[i]['resource_id']) == -1){ SearchInfoId.push(magazineInfo[i]['resource_id']); magazineInfo[i]['loan']=LoanOrNot[0]['loan']; magazineInfo[i]['available']=LoanOrNot[0]['available']; magazineInfo[i]['restype']="magazine"; const LineItem = connection.query(" SELECT * FROM resource_line_item where resource_id = '"+magazineInfo[i]['resource_id']+"' "); magazineInfo[i]['lineItem']=[]; let eachInfo ={}; for(let info=0;info< LineItem.length;info++){ eachInfo = {id:LineItem[info]['id'],resource_id:LineItem[info]['resource_id'],user_id:LineItem[info]['user_id'],date_due:LineItem[info]['date_due']} magazineInfo[i]['lineItem'].push(eachInfo); } AllInfo.push(magazineInfo[i]); } } break; case "music": parameter = false; query =" Select * from music LEFT JOIN resource on music.resource_id = resource.id "; if(!(search['titleSearch'] == undefined) && search['titleSearch'] != ''){ let titleToArray = search['titleSearch'].split(" "); // title to array by part query+="where "; parameter = true; for(let i=0;i<titleToArray.length;i++){ if(i==0) query+="title LIKE '%"+titleToArray[i]+"%' "; else{ query+=" OR title LIKE '%"+titleToArray[i]+"%'"; } } } if(!(search['pickedArtist'] == undefined) && search['pickedArtist'] != ''){ if(parameter) query+=" OR artist = '"+search['pickedArtist']+"'"; else{ query+="where "; parameter = true; query+="artist = '"+search['pickedArtist']+"'"; }} const musicInfo = connection.query(query); for (let i=0; i<musicInfo.length;i++){ const LoanOrNot = connection.query("SELECT SUM(CASE WHEN user_id is NOT NULL THEN 1 else 0 END) as loan, SUM(CASE WHEN user_id is NULL THEN 1 else 0 END) as available FROM resource_line_item where resource_id = '"+musicInfo[i]['resource_id']+"' "); if(SearchInfoId.indexOf(musicInfo[i]['resource_id']) == -1){ SearchInfoId.push(musicInfo[i]['resource_id']); musicInfo[i]['loan']=LoanOrNot[0]['loan']; musicInfo[i]['available']=LoanOrNot[0]['available']; musicInfo[i]['restype']="music"; const LineItem = connection.query(" SELECT * FROM resource_line_item where resource_id = '"+musicInfo[i]['resource_id']+"' "); musicInfo[i]['lineItem']=[]; let eachInfo ={}; for(let info=0;info< LineItem.length;info++){ eachInfo = {id:LineItem[info]['id'],resource_id:LineItem[info]['resource_id'],user_id:LineItem[info]['user_id'],date_due:LineItem[info]['date_due']} musicInfo[i]['lineItem'].push(eachInfo); } AllInfo.push(musicInfo[i]); } } break; case "movie": parameter = false; query =" Select * from movie LEFT JOIN resource on movie.resource_id = resource.id "; if(!(search['titleSearch'] == undefined) && search['titleSearch'] != ''){ let titleToArray = search['titleSearch'].split(" "); // title to array by part query+="where "; parameter = true; for(let i=0;i<titleToArray.length;i++){ if(i==0) query+="title LIKE '%"+titleToArray[i]+"%' "; else{ query+=" OR title LIKE '%"+titleToArray[i]+"%'"; } } } if(!(search['pickedDirector'] == undefined) && search['pickedDirector'] != ''){ if(parameter) query+=" OR director = '"+search['pickedDirector']+"'"; else{ query+="where "; parameter = true; query+="director = '"+search['pickedDirector']+"'"; }} const movieInfo = connection.query(query); for (let i=0; i<movieInfo.length;i++){ const LoanOrNot = connection.query("SELECT SUM(CASE WHEN user_id is NOT NULL THEN 1 else 0 END) as loan, SUM(CASE WHEN user_id is NULL THEN 1 else 0 END) as available FROM resource_line_item where resource_id = '"+movieInfo[i]['resource_id']+"' "); if(SearchInfoId.indexOf(movieInfo[i]['resource_id']) == -1){ SearchInfoId.push(movieInfo[i]['resource_id']); movieInfo[i]['loan']=LoanOrNot[0]['loan']; movieInfo[i]['available']=LoanOrNot[0]['available']; movieInfo[i]['restype']="movie"; const LineItem = connection.query(" SELECT * FROM resource_line_item where resource_id = '"+movieInfo[i]['resource_id']+"' "); movieInfo[i]['lineItem']=[]; let eachInfo ={}; for(let info=0;info< LineItem.length;info++){ eachInfo = {id:LineItem[info]['id'],resource_id:LineItem[info]['resource_id'],user_id:LineItem[info]['user_id'],date_due:LineItem[info]['date_due']} movieInfo[i]['lineItem'].push(eachInfo); } AllInfo.push(movieInfo[i]); } } break; } } return AllInfo; }else{ // if the client does not check a type let parameter =false; let query=""; if((!(search['titleSearch'] == undefined) && search['titleSearch'] != '') || (!(search['pickedAuthor'] == undefined) && search['pickedAuthor'] != '') ||(!(search['ISBNSearch'] == undefined) && search['ISBNSearch'] != '')){ query =" Select * from book LEFT JOIN resource on book.resource_id = resource.id "; if(!(search['titleSearch'] == undefined) && search['titleSearch'] != ''){ let titleToArray = search['titleSearch'].split(" "); // title to array by part query+="where "; parameter = true; for(let i=0;i<titleToArray.length;i++){ if(i==0) query+="title LIKE '%"+titleToArray[i]+"%' "; else{ query+=" OR title LIKE '%"+titleToArray[i]+"%'"; } } } if(!(search['pickedAuthor'] == undefined) && search['pickedAuthor'] != ''){ if(parameter) query+=" OR author = '"+search['pickedAuthor']+"'"; else{ query+="where "; parameter = true; query+="author = '"+search['pickedAuthor']+"'"; }} if(!(search['ISBNSearch'] == undefined) && search['ISBNSearch'] != ''){ if(parameter) query+=" OR ISBN_10 LIKE '%"+search['ISBNSearch']+"%' OR ISBN_13 LIKE '%"+search['ISBNSearch']+"%'"; else{ query+="where "; query+="ISBN_10 LIKE '%"+search['ISBNSearch']+"%' OR ISBN_13 LIKE '%"+search['ISBNSearch']+"%'"; } } const bookInfo = connection.query(query); for (let i=0; i<bookInfo.length;i++){ const LoanOrNot = connection.query("SELECT SUM(CASE WHEN user_id is NOT NULL THEN 1 else 0 END) as loan, SUM(CASE WHEN user_id is NULL THEN 1 else 0 END) as available FROM resource_line_item where resource_id = '"+bookInfo[i]['resource_id']+"' "); if(SearchInfoId.indexOf(bookInfo[i]['resource_id']) == -1){ SearchInfoId.push(bookInfo[i]['resource_id']); bookInfo[i]['loan']=LoanOrNot[0]['loan']; bookInfo[i]['available']=LoanOrNot[0]['available']; bookInfo[i]['restype']="book"; const LineItem = connection.query(" SELECT * FROM resource_line_item where resource_id = '"+bookInfo[i]['resource_id']+"' "); bookInfo[i]['lineItem']=[]; let eachInfo ={}; for(let info=0;info< LineItem.length;info++){ eachInfo = {id:LineItem[info]['id'],resource_id:LineItem[info]['resource_id'],user_id:LineItem[info]['user_id'],date_due:LineItem[info]['date_due']} bookInfo[i]['lineItem'].push(eachInfo); } AllInfo.push(bookInfo[i]); } } } parameter = false; if((!(search['titleSearch'] == undefined) && search['titleSearch'] != '') || (!(search['pickedPublisher'] == undefined) && search['pickedPublisher'] != '') || (!(search['ISBNSearch'] == undefined) && search['ISBNSearch'] != '')){ query =" Select * from magazine LEFT JOIN resource on magazine.resource_id = resource.id "; if(!(search['titleSearch'] == undefined) && search['titleSearch'] != ''){ let titleToArray = search['titleSearch'].split(" "); // title to array by part query+="where "; parameter = true; for(let i=0;i<titleToArray.length;i++){ if(i==0) query+="title LIKE '%"+titleToArray[i]+"%' "; else{ query+=" OR title LIKE '%"+titleToArray[i]+"%'"; } } } if(!(search['pickedPublisher'] == undefined) && search['pickedPublisher'] != ''){ if(parameter) query+=" OR publisher = '"+search['pickedPublisher']+"'"; else{ query+="where "; parameter = true; query+="publisher = '"+search['pickedPublisher']+"'"; }} if(!(search['ISBNSearch'] == undefined) && search['ISBNSearch'] != ''){ if(parameter) query+=" OR ISBN_10 LIKE '%"+search['ISBNSearch']+"%' OR ISBN_13 LIKE '%"+search['ISBNSearch']+"%'"; else{ query+="where "; query+="ISBN_10 LIKE '%"+search['ISBNSearch']+"%' OR ISBN_13 LIKE '%"+search['ISBNSearch']+"%'"; } } const magazineInfo = connection.query(query); for (let i=0; i<magazineInfo.length;i++){ const LoanOrNot = connection.query("SELECT SUM(CASE WHEN user_id is NOT NULL THEN 1 else 0 END) as loan, SUM(CASE WHEN user_id is NULL THEN 1 else 0 END) as available FROM resource_line_item where resource_id = '"+magazineInfo[i]['resource_id']+"' "); if(SearchInfoId.indexOf(magazineInfo[i]['resource_id']) == -1){ SearchInfoId.push(magazineInfo[i]['resource_id']); magazineInfo[i]['loan']=LoanOrNot[0]['loan']; magazineInfo[i]['available']=LoanOrNot[0]['available']; magazineInfo[i]['restype']="magazine"; const LineItem = connection.query(" SELECT * FROM resource_line_item where resource_id = '"+magazineInfo[i]['resource_id']+"' "); magazineInfo[i]['lineItem']=[]; let eachInfo ={}; for(let info=0;info< LineItem.length;info++){ eachInfo = {id:LineItem[info]['id'],resource_id:LineItem[info]['resource_id'],user_id:LineItem[info]['user_id'],date_due:LineItem[info]['date_due']} magazineInfo[i]['lineItem'].push(eachInfo); } AllInfo.push(magazineInfo[i]); } } } parameter = false; if((!(search['titleSearch'] == undefined) && search['titleSearch'] != '') || (!(search['pickedArtist'] == undefined) && search['pickedArtist'] != '')){ query =" Select * from music LEFT JOIN resource on music.resource_id = resource.id "; if(!(search['titleSearch'] == undefined) && search['titleSearch'] != ''){ let titleToArray = search['titleSearch'].split(" "); // title to array by part query+="where "; parameter = true; for(let i=0;i<titleToArray.length;i++){ if(i==0) query+="title LIKE '%"+titleToArray[i]+"%' "; else{ query+=" OR title LIKE '%"+titleToArray[i]+"%'"; } } } if(!(search['pickedArtist'] == undefined) && search['pickedArtist'] != ''){ if(parameter) query+=" OR artist = '"+search['pickedArtist']+"'"; else{ query+="where "; parameter = true; query+="artist = '"+search['pickedArtist']+"'"; }} const musicInfo = connection.query(query); for (let i=0; i<musicInfo.length;i++){ const LoanOrNot = connection.query("SELECT SUM(CASE WHEN user_id is NOT NULL THEN 1 else 0 END) as loan, SUM(CASE WHEN user_id is NULL THEN 1 else 0 END) as available FROM resource_line_item where resource_id = '"+musicInfo[i]['resource_id']+"' "); if(SearchInfoId.indexOf(musicInfo[i]['resource_id']) == -1){ SearchInfoId.push(musicInfo[i]['resource_id']); musicInfo[i]['loan']=LoanOrNot[0]['loan']; musicInfo[i]['available']=LoanOrNot[0]['available']; musicInfo[i]['restype']="music"; const LineItem = connection.query(" SELECT * FROM resource_line_item where resource_id = '"+musicInfo[i]['resource_id']+"' "); musicInfo[i]['lineItem']=[]; let eachInfo ={}; for(let info=0;info< LineItem.length;info++){ eachInfo = {id:LineItem[info]['id'],resource_id:LineItem[info]['resource_id'],user_id:LineItem[info]['user_id'],date_due:LineItem[info]['date_due']} musicInfo[i]['lineItem'].push(eachInfo); } AllInfo.push(musicInfo[i]); } } } parameter = false; if((!(search['titleSearch'] == undefined) && search['titleSearch'] != '') || (!(search['pickedDirector'] == undefined) && search['pickedDirector'] != '')){ query =" Select * from movie LEFT JOIN resource on movie.resource_id = resource.id "; if(!(search['titleSearch'] == undefined) && search['titleSearch'] != ''){ let titleToArray = search['titleSearch'].split(" "); // title to array by part query+="where "; parameter = true; for(let i=0;i<titleToArray.length;i++){ if(i==0) query+="title LIKE '%"+titleToArray[i]+"%' "; else{ query+=" OR title LIKE '%"+titleToArray[i]+"%'"; } } } if(!(search['pickedDirector'] == undefined) && search['pickedDirector'] != ''){ if(parameter) query+=" OR director = '"+search['pickedDirector']+"'"; else{ query+="where "; parameter = true; query+="director = '"+search['pickedDirector']+"'"; }} const movieInfo = connection.query(query); for (let i=0; i<movieInfo.length;i++){ const LoanOrNot = connection.query("SELECT SUM(CASE WHEN user_id is NOT NULL THEN 1 else 0 END) as loan, SUM(CASE WHEN user_id is NULL THEN 1 else 0 END) as available FROM resource_line_item where resource_id = '"+movieInfo[i]['resource_id']+"' "); if(SearchInfoId.indexOf(movieInfo[i]['resource_id']) == -1){ SearchInfoId.push(movieInfo[i]['resource_id']); movieInfo[i]['loan']=LoanOrNot[0]['loan']; movieInfo[i]['available']=LoanOrNot[0]['available']; movieInfo[i]['restype']="movie"; const LineItem = connection.query(" SELECT * FROM resource_line_item where resource_id = '"+movieInfo[i]['resource_id']+"' "); movieInfo[i]['lineItem']=[]; let eachInfo ={}; for(let info=0;info< LineItem.length;info++){ eachInfo = {id:LineItem[info]['id'],resource_id:LineItem[info]['resource_id'],user_id:LineItem[info]['user_id'],date_due:LineItem[info]['date_due']} movieInfo[i]['lineItem'].push(eachInfo); } AllInfo.push(movieInfo[i]); } }} return AllInfo; } }else{ let query =" Select * from book LEFT JOIN resource on book.resource_id = resource.id "; const bookInfo = connection.query(query); for (let i=0; i<bookInfo.length;i++){ const LoanOrNot = connection.query("SELECT SUM(CASE WHEN user_id is NOT NULL THEN 1 else 0 END) as loan, SUM(CASE WHEN user_id is NULL THEN 1 else 0 END) as available FROM resource_line_item where resource_id = '"+bookInfo[i]['resource_id']+"' "); if(SearchInfoId.indexOf(bookInfo[i]['resource_id']) == -1){ SearchInfoId.push(bookInfo[i]['resource_id']); bookInfo[i]['loan']=LoanOrNot[0]['loan']; bookInfo[i]['available']=LoanOrNot[0]['available']; bookInfo[i]['restype']="book"; const LineItem = connection.query(" SELECT * FROM resource_line_item where resource_id = '"+bookInfo[i]['resource_id']+"' "); bookInfo[i]['lineItem']=[]; let eachInfo ={}; for(let info=0;info< LineItem.length;info++){ eachInfo = {id:LineItem[info]['id'],resource_id:LineItem[info]['resource_id'],user_id:LineItem[info]['user_id'],date_due:LineItem[info]['date_due']} bookInfo[i]['lineItem'].push(eachInfo); } AllInfo.push(bookInfo[i]); } } query =" Select * from magazine LEFT JOIN resource on magazine.resource_id = resource.id "; const magazineInfo = connection.query(query); for (let i=0; i<magazineInfo.length;i++){ const LoanOrNot = connection.query("SELECT SUM(CASE WHEN user_id is NOT NULL THEN 1 else 0 END) as loan, SUM(CASE WHEN user_id is NULL THEN 1 else 0 END) as available FROM resource_line_item where resource_id = '"+magazineInfo[i]['resource_id']+"' "); if(SearchInfoId.indexOf(magazineInfo[i]['resource_id']) == -1){ SearchInfoId.push(magazineInfo[i]['resource_id']); magazineInfo[i]['loan']=LoanOrNot[0]['loan']; magazineInfo[i]['available']=LoanOrNot[0]['available']; magazineInfo[i]['restype']="magazine"; const LineItem = connection.query(" SELECT * FROM resource_line_item where resource_id = '"+magazineInfo[i]['resource_id']+"' "); magazineInfo[i]['lineItem']=[]; let eachInfo ={}; for(let info=0;info< LineItem.length;info++){ eachInfo = {id:LineItem[info]['id'],resource_id:LineItem[info]['resource_id'],user_id:LineItem[info]['user_id'],date_due:LineItem[info]['date_due']} magazineInfo[i]['lineItem'].push(eachInfo); } AllInfo.push(magazineInfo[i]); } } query =" Select * from movie LEFT JOIN resource on movie.resource_id = resource.id "; const movieInfo = connection.query(query); for (let i=0; i<movieInfo.length;i++){ const LoanOrNot = connection.query("SELECT SUM(CASE WHEN user_id is NOT NULL THEN 1 else 0 END) as loan, SUM(CASE WHEN user_id is NULL THEN 1 else 0 END) as available FROM resource_line_item where resource_id = '"+movieInfo[i]['resource_id']+"' "); if(SearchInfoId.indexOf(movieInfo[i]['resource_id']) == -1){ SearchInfoId.push(movieInfo[i]['resource_id']); movieInfo[i]['loan']=LoanOrNot[0]['loan']; movieInfo[i]['available']=LoanOrNot[0]['available']; movieInfo[i]['restype']="movie"; const LineItem = connection.query(" SELECT * FROM resource_line_item where resource_id = '"+movieInfo[i]['resource_id']+"' "); movieInfo[i]['lineItem']=[]; let eachInfo ={}; for(let info=0;info< LineItem.length;info++){ eachInfo = {id:LineItem[info]['id'],resource_id:LineItem[info]['resource_id'],user_id:LineItem[info]['user_id'],date_due:LineItem[info]['date_due']} movieInfo[i]['lineItem'].push(eachInfo); } AllInfo.push(movieInfo[i]); } } query =" Select * from music LEFT JOIN resource on music.resource_id = resource.id "; const musicInfo = connection.query(query); for (let i=0; i<musicInfo.length;i++){ const LoanOrNot = connection.query("SELECT SUM(CASE WHEN user_id is NOT NULL THEN 1 else 0 END) as loan, SUM(CASE WHEN user_id is NULL THEN 1 else 0 END) as available FROM resource_line_item where resource_id = '"+musicInfo[i]['resource_id']+"' "); if(SearchInfoId.indexOf(musicInfo[i]['resource_id']) == -1){ SearchInfoId.push(musicInfo[i]['resource_id']); musicInfo[i]['loan']=LoanOrNot[0]['loan']; musicInfo[i]['available']=LoanOrNot[0]['available']; musicInfo[i]['restype']="music"; const LineItem = connection.query(" SELECT * FROM resource_line_item where resource_id = '"+musicInfo[i]['resource_id']+"' "); musicInfo[i]['lineItem']=[]; let eachInfo ={}; for(let info=0;info< LineItem.length;info++){ eachInfo = {id:LineItem[info]['id'],resource_id:LineItem[info]['resource_id'],user_id:LineItem[info]['user_id'],date_due:LineItem[info]['date_due']} musicInfo[i]['lineItem'].push(eachInfo); } AllInfo.push(musicInfo[i]); } } console.log(AllInfo); return AllInfo; } }else{ let SearchToArray = search.split(" "); console.log(SearchToArray); let AllInfo = []; let SearchInfoId = []; for(let x=0;x<SearchToArray.length;x++){ if(SearchToArray[0] !=''){ const bookInfo = connection.query("SELECT * FROM book LEFT JOIN resource on book.resource_id = resource.id where title LIKE '%"+SearchToArray[x]+"%' OR author LIKE '%"+SearchToArray[x]+"%' OR isbn_10 LIKE '%"+SearchToArray[x]+"%' OR isbn_13 LIKE '%"+SearchToArray[x]+"%'"); for (let i=0; i<bookInfo.length;i++){ const LoanOrNot = connection.query("SELECT SUM(CASE WHEN user_id is NOT NULL THEN 1 else 0 END) as loan, SUM(CASE WHEN user_id is NULL THEN 1 else 0 END) as available FROM resource_line_item where resource_id = '"+bookInfo[i]['resource_id']+"' "); console.log(LoanOrNot[0]['loan']); if(SearchInfoId.indexOf(bookInfo[i]['resource_id']) == -1){ SearchInfoId.push(bookInfo[i]['resource_id']); bookInfo[i]['loan']=LoanOrNot[0]['loan']; bookInfo[i]['available']=LoanOrNot[0]['available']; bookInfo[i]['restype']="book"; const LineItem = connection.query(" SELECT * FROM resource_line_item where resource_id = '"+bookInfo[i]['resource_id']+"' "); bookInfo[i]['lineItem']=[]; let eachInfo ={}; for(let info=0;info< LineItem.length;info++){ eachInfo = {id:LineItem[info]['id'],resource_id:LineItem[info]['resource_id'],user_id:LineItem[info]['user_id'],date_due:LineItem[info]['date_due']} bookInfo[i]['lineItem'].push(eachInfo); } AllInfo.push(bookInfo[i]); } } const magazineInfo = connection.query("SELECT * FROM magazine LEFT JOIN resource on magazine.resource_id = resource.id where title LIKE '%"+SearchToArray[x]+"%' OR publisher LIKE '%"+SearchToArray[x]+"%' OR isbn_10 LIKE '%"+SearchToArray[x]+"%' OR isbn_13 LIKE '%"+SearchToArray[x]+"%'"); for (let i=0; i<magazineInfo.length;i++){ if(SearchInfoId.indexOf(magazineInfo[i]['resource_id']) == -1){ const LoanOrNot = connection.query("SELECT SUM(CASE WHEN user_id is NOT NULL THEN 1 else 0 END) as loan, SUM(CASE WHEN user_id is NULL THEN 1 else 0 END) as available FROM resource_line_item where resource_id = '"+magazineInfo[i]['resource_id']+"' "); SearchInfoId.push(magazineInfo[i]['resource_id']); magazineInfo[i]['loan']=LoanOrNot[0]['loan']; magazineInfo[i]['available']=LoanOrNot[0]['available']; magazineInfo[i]['restype']="magazine"; const LineItem = connection.query(" SELECT * FROM resource_line_item where resource_id = '"+magazineInfo[i]['resource_id']+"' "); magazineInfo[i]['lineItem']=[]; let eachInfo ={}; for(let info=0;info< LineItem.length;info++){ eachInfo = {id:LineItem[info]['id'],resource_id:LineItem[info]['resource_id'],user_id:LineItem[info]['user_id'],date_due:LineItem[info]['date_due']} magazineInfo[i]['lineItem'].push(eachInfo); } AllInfo.push(magazineInfo[i]); } } const movieInfo = connection.query("SELECT * FROM movie LEFT JOIN resource on movie.resource_id = resource.id where title LIKE '%"+SearchToArray[x]+"%' OR director LIKE '%"+SearchToArray[x]+"%'"); for (let i=0; i<movieInfo.length;i++){ if(SearchInfoId.indexOf(movieInfo[i]['resource_id']) == -1){ const LoanOrNot = connection.query("SELECT SUM(CASE WHEN user_id is NOT NULL THEN 1 else 0 END) as loan, SUM(CASE WHEN user_id is NULL THEN 1 else 0 END) as available FROM resource_line_item where resource_id = '"+movieInfo[i]['resource_id']+"' "); SearchInfoId.push(movieInfo[i]['resource_id']); movieInfo[i]['loan']=LoanOrNot[0]['loan']; movieInfo[i]['available']=LoanOrNot[0]['available']; movieInfo[i]['restype']="movie"; const LineItem = connection.query(" SELECT * FROM resource_line_item where resource_id = '"+movieInfo[i]['resource_id']+"' "); movieInfo[i]['lineItem']=[]; let eachInfo ={}; for(let info=0;info< LineItem.length;info++){ eachInfo = {id:LineItem[info]['id'],resource_id:LineItem[info]['resource_id'],user_id:LineItem[info]['user_id'],date_due:LineItem[info]['date_due']} movieInfo[i]['lineItem'].push(eachInfo); } AllInfo.push(movieInfo[i]); } } const musicInfo = connection.query("SELECT * FROM music LEFT JOIN resource on music.resource_id = resource.id where title LIKE '%"+SearchToArray[x]+"%'"); for (let i=0; i<musicInfo.length;i++){ if(SearchInfoId.indexOf(musicInfo[i]['resource_id']) == -1){ const LoanOrNot = connection.query("SELECT SUM(CASE WHEN user_id is NOT NULL THEN 1 else 0 END) as loan, SUM(CASE WHEN user_id is NULL THEN 1 else 0 END) as available FROM resource_line_item where resource_id = '"+musicInfo[i]['resource_id']+"' "); SearchInfoId.push(musicInfo[i]['resource_id']); musicInfo[i]['loan']=LoanOrNot[0]['loan']; musicInfo[i]['available']=LoanOrNot[0]['available']; musicInfo[i]['restype']="music"; const LineItem = connection.query(" SELECT * FROM resource_line_item where resource_id = '"+musicInfo[i]['resource_id']+"' "); musicInfo[i]['lineItem']=[]; let eachInfo ={}; for(let info=0;info< LineItem.length;info++){ eachInfo = {id:LineItem[info]['id'],resource_id:LineItem[info]['resource_id'],user_id:LineItem[info]['user_id'],date_due:LineItem[info]['date_due']} musicInfo[i]['lineItem'].push(eachInfo); } AllInfo.push(musicInfo[i]); } }} }; return AllInfo; } } static selectAll(){ try{ let resources = []; let resource = {}; const book_data = connection.query(`select r.title, r.id, b.author, b.format, b.pages, b.publisher, b.language, b.isbn_10, b.isbn_13, b.resource_id from resource as r left join book as b on r.id=b.resource_id where type='book' `); const music_data = connection.query(`select r.title, r.id, mu.type, mu.artist, mu.release, mu.ASIN, mu.label, mu.resource_id from resource as r left join music as mu on r.id=mu.resource_id where r.type='music' `); const movie_data = connection.query(` select r.title, r.id, mo.director, mo.producers, mo.actors, mo.language, mo.subtitles, mo.dubbed, mo.release_date, mo.run_time, mo.resource_id from resource as r left join movie as mo on r.id=mo.resource_id where r.type='movie' `); const magazine_data = connection.query(` select r.title, r.id, ma.publisher, ma.language, ma.isbn_10, ma.isbn_13, ma.resource_id from resource as r left join magazine as ma on r.id=ma.resource_id where r.type='magazine' `); for (let i=0; i<book_data.length;i++){ resource = book_data[i] resource.restype = 'book'; const LineItem = connection.query(`SELECT * FROM resource_line_item where resource_id =${resource.id}`); resource['lineItem'] = []; let eachInfo = {}; for(let info=0;info< LineItem.length;info++){ eachInfo = { id:LineItem[info]['id'], resource_id:LineItem[info]['resource_id'],user_id:LineItem[info]['user_id'],date_due:LineItem[info]['date_due']} resource['lineItem'].push(eachInfo); } resources.push( resource ); IdentifyMap[resource.id] = resource; } for (let i=0; i<magazine_data.length;i++){ resource = magazine_data[i] resource.restype = 'magazine'; const LineItem = connection.query(`SELECT * FROM resource_line_item where resource_id =${resource.id}`); resource['lineItem'] = []; let eachInfo = {}; for(let info=0;info< LineItem.length;info++){ eachInfo = { id:LineItem[info]['id'], resource_id:LineItem[info]['resource_id'],user_id:LineItem[info]['user_id'],date_due:LineItem[info]['date_due']} resource['lineItem'].push(eachInfo); } resources.push( resource ); IdentifyMap[resource.id] = resource; } for (let i=0; i<music_data.length;i++){ resource = music_data[i] resource.restype = 'music'; const LineItem = connection.query(`SELECT * FROM resource_line_item where resource_id =${resource.id}`); resource['lineItem'] = []; let eachInfo = {}; for(let info=0;info< LineItem.length;info++){ eachInfo = { id:LineItem[info]['id'], resource_id:LineItem[info]['resource_id'],user_id:LineItem[info]['user_id'],date_due:LineItem[info]['date_due']} resource['lineItem'].push(eachInfo); } resources.push( resource ); IdentifyMap[resource.id] = resource; } for (let i=0; i<movie_data.length;i++){ resource = movie_data[i] resource.restype = 'movie'; const LineItem = connection.query(`SELECT * FROM resource_line_item where resource_id =${resource.id}`); resource['lineItem'] = []; let eachInfo = {}; for(let info=0;info< LineItem.length;info++){ eachInfo = { id:LineItem[info]['id'], resource_id:LineItem[info]['resource_id'],user_id:LineItem[info]['user_id'],date_due:LineItem[info]['date_due']} resource['lineItem'].push(eachInfo); } resources.push( resource ); IdentifyMap[resource.id] = resource; } return {status: 0, message: 'Ok', results: resources}; } catch (error){ return{ status: 1, message: 'Error: ' + error, error} } } // Method add New Line Item for a specific Ressource static addLineItem(resource_id){ try{ let data = connection.query("INSERT INTO resource_line_item (resource_id, date_due) VALUES ("+resource_id+", '')"); let data2 = connection.query(`SELECT * FROM resource_line_item WHERE id=${data.insertId}`) return {message: 'Resource Added', lineItem: data2[0]}; }catch(error){ return {message: 'Resource '+error}; } } static deleteLineItem(resource_line_item_id){ try{ connection.query("DELETE FROM resource_line_item where id ="+resource_line_item_id); return {message: 'Resource Deleted'}; }catch(error){ return {message: 'Resource '+error}; } } // Method to insert resource into resources table static insert(resource_obj, type) { try{ type = type.toLowerCase(); const parent_obj = {"type":type, "title": resource_obj.title, "id":0}; // parent resource obj fits this schema delete resource_obj.id; // make it fit for the child table delete resource_obj.title; // make it fit for the child table const parent_data = connection.query(`INSERT INTO resource VALUES( ${this.objectToQueryString(parent_obj)} )`); // Insert resource data (parent) resource_obj.resource_id = parent_data.insertId; // with the insert id of the resource table, reference the fk of the child data to the pk of the parent resource_obj.id = 0; connection.query(`INSERT INTO ${type} VALUES (${this.objectToQueryString(resource_obj)})`); // Insert into the child table the child data (book, magazine, music, movie) //const date = new Date(Date.now() + (1000 /*sec*/ * 60 /*min*/ * 60 /*hour*/ * 24 /*day*/ * 10)).toString(); const resource_line_item = {"id":0, "resource_id": parent_data.insertId, "user_id": null, "date_due": ''}; // declare schema for the line item instance (this table represents the number of instances) connection.query(`INSERT INTO resource_line_item (id, resource_id, user_id, date_due) VALUES(0, ${resource_line_item.resource_id}, NULL, '${resource_line_item.date_due}')`); const resource = this.select(parent_data.insertId).results return {status: 0, message: 'Resource Added', results: resource}; } catch(error){ return{ status: 1, message: 'Error' +error, error} } } // This method will make a sql call to delete an entire resource record once called static delete(id) { try{ delete IdentifyMap[id]; const data = connection.query(`SELECT * FROM resource where id=${id}`); if (data.length > 0){ const type = data[0].type; const resource_line_item_data = connection.query(`DELETE FROM resource_line_item WHERE resource_id=${id}`); const child_data = connection.query(`DELETE FROM ${type} where resource_id=${id}`); const resource_data = connection.query(`DELETE FROM resource where id=${id}`); return {status : 0, message : 'Resource deleted.'}; } else { return {status : 1, message : 'Nothing to delete.'} } } catch(error){ return {status : 1, message : 'Error' +error, error} } } // Method to update relevant resource given the new information static update(resource_obj, type) { try { console.log(resource_obj) console.log(type); type = type.toLowerCase(); connection.query(`UPDATE resource SET title = '${resource_obj.title}' WHERE id='${resource_obj.id}'`); const id = resource_obj.id; delete resource_obj.id; delete resource_obj.title; delete resource_obj.available; const data = connection.query(`UPDATE ${type} SET ${this.objectToUpdateString(resource_obj)} WHERE resource_id='${id}'`); return {status : 0, message : 'Resource updated.', results : data} } catch(error) { return {status : 1, message : 'Error' +error, error} } } //Get all authors for advanced search static getAllAuthors(){ try{ const data = connection.query(`SELECT DISTINCT author from book`); return {status: 0, message: 'Ok', results: data}; } catch (error){ return{ status: 1, message: 'Error: ' + error, error} } } //Get all authors for advanced search static getAllDirectors(){ try{ const data = connection.query(`SELECT DISTINCT director from movie`); return {status: 0, message: 'Ok', results: data}; } catch (error){ return{ status: 1, message: 'Error: ' + error, error} } } //Get all publishers for advanced search static getAllPublishers(){ try{ const data = connection.query(`select distinct publisher from magazine`); return {status: 0, message: 'Ok', results: data}; } catch (error){ return{ status: 1, message: 'Error: ' + error, error} } } //Get all artists for advanced search static getAllArtists(){ try{ const data = connection.query(`select distinct artist from music`); return {status: 0, message: 'Ok', results: data}; } catch (error){ return{ status: 1, message: 'Error: ' + error, error} } } // Helper. This method turns an object into a string formated for an SQL query static objectToQueryString(object) { return Object.values(object).map(x => "'" + x + "'").join(','); } static objectToUpdateString(object) { return Object.keys(object).map(key =>'`' + key +'`' + "='" + object[key] + "'").join(' , ') } }
JavaScript
class XCash extends Driver { constructor(options) { super({ timeout: 100, // 10 requests per second supports: { circulating: true, max: true, }, options, }); } /** * @augments Driver.fetchMaxSupply * @async */ async fetchMaxSupply() { const max = await this.request('https://explorer.x-cash.org/gettotalsupply'); return Number(max); } /** * @augments Driver.fetchTotalSupply * @async */ async fetchTotalSupply() { const total = await this.request('https://explorer.x-cash.org/getgeneratedsupply'); return Number(total); } /** * @augments Driver.fetchCirculatingSupply * @async */ async fetchCirculatingSupply() { const circulating = await this.request('https://explorer.x-cash.org/getcirculatingsupply'); return Number(circulating); } /** * @augments Driver.getSupply */ async getSupply() { const total = await this.fetchTotalSupply(); const max = await this.fetchMaxSupply(); const circulating = await this.fetchCirculatingSupply(); return new Supply({ total, max, circulating, }); } }
JavaScript
class Rail { constructor(opts) { for (let o in opts) { this[o] = opts[o]; } let app, tray, cell, img, nav, dot, tot, old, free, fact, cur = 0; const buildframe = () => { let n = 0; app = document.getElementById(this.slide_id); img = app.getElementsByTagName("img"); tray = document.createElement('div'); tray.className = 'slide-tray'; while (img.length > 0) { let cell = document.createElement('div'); cell.className = 'cell'; n++; cell.id = n; cell.append(img[0]); tray.append(cell); } app.append(tray); } const buildnavbar = () => { let n = 0; nav = document.createElement('div'); nav.className = 'dot-tray'; for (let i = 0; i < img.length; i++) { dot = document.createElement('div'); dot.className = 'dot'; n++; dot.id = n; nav.append(dot); } app.append(nav); nav.firstChild.classList.add('Rail-active'); } const clone = () => { cell = tray.getElementsByClassName("cell"); let i1 = cell[0].cloneNode(true), o1 = cell[1].cloneNode(true), i2 = cell[img.length - 1].cloneNode(true), o2 = cell[img.length - 2].cloneNode(true); i1.id = o1.id = o2.id = i2.id = ''; tray.append(i1); tray.append(o1); tray.insertBefore(i2, cell[0]); tray.insertBefore(o2, cell[0]); }; const configparts = () => { buildframe(); if (this.slide_navagation) buildnavbar(); clone(); tot = img.length; tray.style.width = `${100 * tot}%`; for (let c = 0; c < cell.length; c++) { cell[c].style.width = `${100 / tot}%`; } translate(cur = 2); }; const currentdot = () => { for (let i = 0; i < nav.children.length; i++) { nav.children[i].classList.remove('Rail-active'); if (cur === 1) { nav.children[tot - 5].classList.add('Rail-active'); } else if (cur === tot - 2) { nav.children[0].classList.add('Rail-active'); } else { nav.children[cur - 2].classList.add('Rail-active'); } } } const translate = (cur) => tray.style.transform = `translate(${cur / tot * -100}%)`; const transition = (spe, eas) => tray.style.transition = `transform ${spe}ms ${eas || 'linear'}`; const device = (e) => { return e.changedTouches ? e.changedTouches[0] : e; }; const factor = (e) => { let pos = Math.max(device(e).clientX, old) - Math.min(device(e).clientX, old); let speed = (app.clientWidth - pos) * (this.slide_speed / app.clientWidth); return Math.round(speed); }; const unlock = (e) => { e.preventDefault(); free = true; old = device(e).clientX; }; const drag = (e) => { if (free) { transition(0); let bounds = -Math.round(cell[cur].offsetLeft - (device(e).clientX - old)); tray.style.transform = `translate(${bounds}px)`; fact = factor(e); } }; const slide = (e) => { if (free) { if (device(e).clientX < old - app.clientWidth / 10) { if (cur > tot - 4) { setTimeout(() => { transition(0); translate(cur = 2); }, fact); } translate((cur += 1)); } else if (device(e).clientX > old + app.clientWidth / 10) { if (cur < 3) { setTimeout(() => { transition(0); translate(cur = tot - 3); }, fact); } translate(cur -= 1); } else { translate(cur); } transition(fact, this.slide_style); currentdot(); } }; const relock = () => free = false; const controlbar = (e) => { let target = e.target.id; if (target) { translate(cur = Number(target) + 1); } currentdot(); transition(this.slide_speed, this.slide_style); } const listen = (elm, arg, fnt) => arg.forEach(evt => elm.addEventListener(evt, fnt, { passive: false })); (() => { configparts(); listen(nav, ['click'], controlbar); listen(tray, ['mousedown', 'touchstart'], unlock); listen(window, ['mousemove', 'touchmove'], drag); listen(window, ['mouseup', 'touchend'], slide); listen(window, ['mouseup', 'touchend'], relock); })(); } }
JavaScript
class NzCalendarHeaderComponent { /** * @param {?} i18n * @param {?} dateHelper */ constructor(i18n, dateHelper) { this.i18n = i18n; this.dateHelper = dateHelper; this.mode = 'month'; this.fullscreen = true; this.modeChange = new EventEmitter(); this.activeDate = new CandyDate(); this.yearChange = new EventEmitter(); this.monthChange = new EventEmitter(); // @Output() readonly valueChange: EventEmitter<CandyDate> = new EventEmitter(); this.yearOffset = 10; this.yearTotal = 20; } /** * @return {?} */ get activeYear() { return this.activeDate.getYear(); } /** * @return {?} */ get activeMonth() { return this.activeDate.getMonth(); } /** * @return {?} */ get size() { return this.fullscreen ? 'default' : 'small'; } /** * @return {?} */ get yearTypeText() { return this.i18n.getLocale().Calendar.year; } /** * @return {?} */ get monthTypeText() { return this.i18n.getLocale().Calendar.month; } /** * @return {?} */ ngOnInit() { this.setUpYears(); this.setUpMonths(); } /** * @param {?} year * @return {?} */ updateYear(year) { this.yearChange.emit(year); this.setUpYears(year); } /** * @private * @param {?=} year * @return {?} */ setUpYears(year) { /** @type {?} */ const start = (year || this.activeYear) - this.yearOffset; /** @type {?} */ const end = start + this.yearTotal; this.years = []; for (let i = start; i < end; i++) { this.years.push({ label: `${i}`, value: i }); } } /** * @private * @return {?} */ setUpMonths() { this.months = []; for (let i = 0; i < 12; i++) { /** @type {?} */ const dateInMonth = this.activeDate.setMonth(i); /** @type {?} */ const monthText = this.dateHelper.format(dateInMonth.nativeDate, 'MMM'); this.months.push({ label: monthText, value: i }); } } }
JavaScript
class NzCalendarComponent { /** * @param {?} cdr */ constructor(cdr) { this.cdr = cdr; this.activeDate = new CandyDate(); this.prefixCls = 'ant-fullcalendar'; this.onChangeFn = (/** * @return {?} */ () => { }); this.onTouchFn = (/** * @return {?} */ () => { }); this.nzMode = 'month'; this.nzModeChange = new EventEmitter(); this.nzPanelChange = new EventEmitter(); this.nzSelectChange = new EventEmitter(); this.nzValueChange = new EventEmitter(); this.nzFullscreen = true; } /** * @param {?} value * @return {?} */ set nzValue(value) { this.updateDate(new CandyDate(value), false); } /** * @return {?} */ get dateCell() { return this.nzDateCell || this.nzDateCellChild; } /** * @return {?} */ get dateFullCell() { return this.nzDateFullCell || this.nzDateFullCellChild; } /** * @return {?} */ get monthCell() { return this.nzMonthCell || this.nzMonthCellChild; } /** * @return {?} */ get monthFullCell() { return this.nzMonthFullCell || this.nzMonthFullCellChild; } /** * @deprecated use `[nzFullscreen]` instead. * @param {?} value * @return {?} */ set nzCard(value) { warnDeprecation(`'nzCard' is going to be removed in 9.0.0. Please use 'nzFullscreen' instead.`); this.nzFullscreen = !toBoolean(value); } /** * @return {?} */ get nzCard() { return !this.nzFullscreen; } /** * @param {?} mode * @return {?} */ onModeChange(mode) { this.nzModeChange.emit(mode); this.nzPanelChange.emit({ date: this.activeDate.nativeDate, mode }); } /** * @param {?} year * @return {?} */ onYearSelect(year) { /** @type {?} */ const date = this.activeDate.setYear(year); this.updateDate(date); } /** * @param {?} month * @return {?} */ onMonthSelect(month) { /** @type {?} */ const date = this.activeDate.setMonth(month); this.updateDate(date); } /** * @param {?} date * @return {?} */ onDateSelect(date) { // Only activeDate is enough in calendar // this.value = date; this.updateDate(date); } /** * @param {?} value * @return {?} */ writeValue(value) { this.updateDate(new CandyDate((/** @type {?} */ (value))), false); this.cdr.markForCheck(); } /** * @param {?} fn * @return {?} */ registerOnChange(fn) { this.onChangeFn = fn; } /** * @param {?} fn * @return {?} */ registerOnTouched(fn) { this.onTouchFn = fn; } /** * @private * @param {?} date * @param {?=} touched * @return {?} */ updateDate(date, touched = true) { this.activeDate = date; if (touched) { this.onChangeFn(date.nativeDate); this.onTouchFn(); this.nzSelectChange.emit(date.nativeDate); this.nzValueChange.emit(date.nativeDate); } } }
JavaScript
class PDF { constructor(url, canvas) { this.url = url; this.canvas = canvas; this.context = canvas.getContext('2d'); this.currentPage = 1; this.maxPages = 1; this.currentScale = 1.75; this.currentScaleText = document.getElementById('zoom-level'); if (matchMedia('only screen and (max-width: 480px)').matches) { this.currentScale = 0.5; } this.currentScaleText.textContent = this.currentScale * 100 + '%'; } handlePreviousPage() { if (this.currentPage == 1) { return; } this.currentPage -= 1; this.handle(); } handleNextPage() { if (this.currentPage == this.maxPages) { return; } this.currentPage += 1; this.handle(); } handleZoomChange(zoom = null) { if (this.currentScale == 0.25 && !zoom) { return; } if (zoom) { this.currentScale += 0.25; this.currentScaleText.textContent = this.currentScale * 100 + '%'; return this.handle(); } this.currentScale -= 0.25; this.currentScaleText.textContent = this.currentScale * 100 + '%'; return this.handle(); } prepare() { let previousPageButton = document .getElementById('previous-page-button') .addEventListener('click', () => this.handlePreviousPage()); let nextPageButton = document .getElementById('next-page-button') .addEventListener('click', () => this.handleNextPage()); let zoomInButton = document .getElementById('zoom-in') .addEventListener('click', () => this.handleZoomChange(true)); let zoomOutButton = document .getElementById('zoom-out') .addEventListener('click', () => this.handleZoomChange()); return this; } setPagesInViewport() { let currentPageContainer = document.getElementById( 'current-page-container' ); let totalPageContainer = document.getElementById( 'total-page-container' ); let paginationButtonContainer = document.getElementById( 'pagination-button-container' ); currentPageContainer.innerText = this.currentPage; totalPageContainer.innerText = this.maxPages; if (this.maxPages > 1) { paginationButtonContainer.style.display = 'flex'; } } async handle() { let pdf = await pdfjsLib.getDocument(this.url).promise; let page = await pdf.getPage(this.currentPage); this.maxPages = pdf.numPages; let viewport = await page.getViewport({ scale: this.currentScale }); this.canvas.height = viewport.height; this.canvas.width = viewport.width; page.render({ canvasContext: this.context, viewport, }); this.setPagesInViewport(); } }
JavaScript
@connect(({ search_org, loading }) => ({search_org})) class SortableTreeCont extends React.Component { // handle the organization name suggestions handleTreeChange=(value) => { // if(!!value){ console.log("changed data"+JSON.stringify(value)); this.props.dispatch({ type: 'search_org/treeChange', payload: {"value": value} }); // } } render() { const { onChange, onSelect } = this.props; const { search_org, loading } = this.props; //Making search_org model as property const { tree_data } = search_org;//we need only few props from state return ( <div style={{ height: 500 }}> <SortableTree treeData={tree_data} onChange={this.handleTreeChange} /> </div> ); } }
JavaScript
class Export { /** * Telecharge un contenu * * @param {any} content le contenu a telecharger * @param {string} file nom du fichier * @returns {void} */ static download(content, file = 'download.txt') { let a = Html.create('a', { href: 'data:text/plain;charset=utf-8,' + encodeURIComponent(content), download: file, style: 'display:none' }); Html.append(a); a.click(); Html.remove(a); } /** * Affiche du texte dans un nouvel onglet * * @param {string} content le contenu de la page * @returns {void} */ static fullScreen(content) { let tab = window.open('about:blank', '_blank'); tab.document.write('<pre>' + content + '</pre>'); tab.document.close(); } }
JavaScript
class AtomWorkspacePolyfill extends PolyfillObjectMixin { constructor() { super( atom.workspace, ['itemForURI','getItemByURI','getItemsByURI','hide','openTextFile', 'getChannel','addDep','removeDep', 'addDep_uriOpening', 'addDep_item', 'removeDep_item', 'addDep_itemOpened', 'removeDep_itemOpened', 'addDep_itemDestroyed','removeDep_itemDestroyed', 'addDep_itemActivated', 'removeDep_itemActivated', ,'addDep_itemDeactivated', 'removeDep_itemDeactivated', 'addDep_textEditor','removeDep_textEditor','addDep_textEditorOpened','removeDep_textEditorOpened', 'addDep_textEditorActivated','removeDep_textEditorActivated', ,'addDep_textEditorDeactivated','removeDep_textEditorDeactivated', 'addDep_pane', 'removeDep_pane', 'addDep_paneOpened', 'removeDep_paneOpened', 'addDep_paneDestroyed','removeDep_paneDestroyed', 'addDep_paneActivated', 'removeDep_paneActivated', ,'addDep_paneDeactivated', 'removeDep_paneDeactivated' ] ); } getTarget() {return atom.workspace;} doesTargetAlreadySupportFeature() {return !!this.target.getItemByURI;} isTargetStillCompatibleWithThisPollyfill() {return true;} ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Polyfill Methods... // These methods are writtien in the context of the target object and will be dynamically added to that object when this polyfill // is installed. If the name matches an existing method of the target object, it will be replaced and the original will be // available as orig_<methodName> // The 'this' pointer of these methods will be the target object, not the polyfill object when they are invoked. // extend openTextFile to support a convention to use the querystring to specify which type of editor to open the file in. // I wanted the default behavior for .bgdeps files to open in the cyto graphical view but I also wanted to support a button // in that view to open the file in a text editor. I had some success with calling the undocumented atom.workspace.openTextFile // from my plugin's oppener function when I detected the querystring but because that method is async and the openers are invoked // synchronously, I could not make it work reliably. An alternate patch would be to fix open to resolve promises if the opener // callback returns one but that would be harder since its in the middle of a method. async openTextFile(uri, options) { const uriNew = uri.replace(/[?]editor=text\s*$/,""); if (uriNew!=uri && !fs.existsSync(uri) && fs.existsSync(uriNew)) uri = uriNew; return this.orig_openTextFile(uri,options) } // return the normalized DependentsGraph channel that represents the passed in values. // Params: // <objType> : one of (item|textEditor|pane). The type of workspace object to be dependent on. // <actionType> : one of (<emptyString>|opened|destroyed|activated|deactivated) The action on <objType> to be dependent on // <uriSpec> : limit the dependency relationship to changes to <objTypes> that match uriSpec. // uriSpec can be a RegExp object or the string representation of a RegExp object (like '/<exp>/[<flags>]') // if uriSpec is a string not matching the RegExp syntax, <objType> URI that start with that string will be matched. getChannel(objType, actionType, uriSpec) { if (!objType) return deps.fAll; var channel = objType; if (uriSpec && uriSpec!='/^/') { channel += '('+uriSpec.toString()+')' } if (actionType) channel += '.'+actionType return channel; } // This returns the WorkspaceItem with the given uri if it is open. Otherwise it returns false. It will not open a uri. // If <uri> matches multiple items, only the first found will be returned. (See getItemsByURI(uri)) // If <uri> does not match any items, undefined will be returned // Alternative: // atom.workspace.paneForURI(uri).itemForURI(uri) // Params: // <uri> : a string or RegExp that will match the uri of the items to hide. A string will be interpretted as the leteral // prefix to match. e.g. 'atom://config' will match 'atom://config/bg-tree-view-toolbar' itemForURI(uriSpec) {return this.getItemByURI(uriSpec)} getItemByURI(uriSpec) { uriSpec = URISpecToRegex(uriSpec) const items = atom.workspace.getPaneItems(); return items.find((item)=>{return uriSpec.test(GetURI(item))}); } // This returns 0 or more WorkspaceItems with the given uri if it is open. It will not open a uri. // If <uri> matches multiple items, all will be returned. (See getItemsByURI(uri)) // If <uri> does not match any items, undefined will be returned // Params: // <uri> : a string or RegExp that will match the uri of the items to hide. A string will be interpretted as the leteral // prefix to match. e.g. 'atom://config' will match 'atom://config/bg-tree-view-toolbar' getItemsByURI(uriSpec) { uriSpec = URISpecToRegex(uriSpec) const items = atom.workspace.getPaneItems(); return items.filter((item)=>{return uriSpec.test(GetURI(item))}); } // this overrides the original hide(uri) method to make it more tolerant to uri matching. For example, the actual uri might // have a #<anchor> suffix and this will match the prefix regardless of the suffix // If <uri> matches multiple items, they all will be hidden. // If <uri> does not match any items, nothing will be done and it is not an error // Params: // <uri> : a string or RegExp that will match the uri of the items to hide. A string will be interpretted as the leteral // prefix to match. e.g. 'atom://config' will match 'atom://config/bg-tree-view-toolbar' hide(uriSpec) { for (const item of this.getItemsByURI(uriSpec)) { this.orig_hide(GetURI(item)); } } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // DependentsGraph Integration: // The following methods provide wrappers over deps.add(... ) and deps.remove(... ). This is just syntaxic sugar that makes // it more obvious to users of the atom.workspace how to make their objects dependent on atom.workspace changes and which // channels can be declared dependence on. // At the bottom of this module is the AtomWorkspaceChannelNode class which is the actual integration that ties Atom's Event // Subscription model into the DependentsGraph system. // // The significant difference in using these methods to subscribe to changes rather than the ::on<somthing> methods is that // you do not have to store disposable objects to later remove the subscription. Because the addDep... family of functions // declare a dependency between two objects, when either one is removed from the DependentsGraph system, the subscription // will be canceled. It also means that the subscription is uniquely identified by {obj1,channel,obj2} so calling the // coresponding removeDep<...> function with the same parameters will remove just that one subscription. // // These wrapper are more terse than calling the deps system directly.... // atom.workspace.addDep_itemOpened(uriSpec, obj2, callback); // ... is the same as ... // deps.add({obj:atom.workspace,channel:atom.workspace.getChannel('item', 'opened', uriSpec) }, obj2, callback); // <obj2>.onWorkspaceChanged(<objType>, <actionType>, <obj>, ...) // callback(<objType>, <actionType>, <obj>, ...) // callback('item', 'opened', <item>, <pane>, <index>) // callback('item', 'destroyed', <item>, <pane>, <index>) // callback('item', 'activated', <item>, <previousActiveItem>) // callback('item', 'deactivated', <item>, <newActiveItem>) // callback('textEditor', 'opened', <editor>, <pane>, <index>) // callback('textEditor', 'activated', <editor>, <previousActiveEditor>) // callback('textEditor', 'deactivated', <editor>, <newActiveEditor>) // callback('pane', 'opened' <pane>) // callback('pane', 'destroyed' <pane>) // callback('pane', 'activated' <pane>, <previousActivePane>) // callback('pane', 'deactivated' <pane>, <newActivePane>) addDep( obj2, callback) {deps.add( this, obj2, callback);} removeDep(obj2) {deps.remove(this, obj2);} // <obj2>.onURIOpening(uri) // Note: not sure if this should follow the DependentsGraph pattern yet. This is a plugin pattern where the callback implements // polymorphism. Maybe that should be a different pattern. The key difference between this and other addDep* relations is that // the callback can return a value which changes the behavior of the source side of the relationship. // Return Value: // <viewOrItem> : Can be an object inherited from HTMLElement or an item that as a registered view addDep_uriOpening(uriSpec, obj2, callback) {deps.add({obj:this, channel:this.getChannel('uri', 'opening', uriSpec)},obj2,callback)} // <obj2>.onWorkspaceItemChanged(<actionType>, <item>, ...) // callback('opened', <item>, <pane>, <index>) // callback('destroyed', <item>, <pane>, <index>) // callback('activated', <item>, <previousActiveItem>) // callback('deactivated', <item>, <newActiveItem>) // where: // <item> : is the item matching the uriSpec // <pane> : is the workspace pane that contains <item> // <index>: is the index of <item> in <pane>.items addDep_item( uriSpec, obj2, callback) {deps.add( {obj:this, channel:this.getChannel('item', '', uriSpec) }, obj2, callback);} removeDep_item(uriSpec, obj2) {deps.remove({obj:this, channel:this.getChannel('item', '', uriSpec) }, obj2);} // <obj2>.onWorkspaceItemOpened(<item>, <pane>, <index>) // callback(<openedItem>, <pane>, <index>) addDep_itemOpened( uriSpec, obj2, callback) {deps.add( {obj:this, channel:this.getChannel('item', 'opened', uriSpec) }, obj2, callback);} removeDep_itemOpened(uriSpec, obj2) {deps.remove({obj:this, channel:this.getChannel('item', 'opened', uriSpec) }, obj2);} // <obj2>.onWorkspaceItemDestroyed(<item>, <pane>, <index>) // callback(<destroyedItem>, <pane>, <index>) addDep_itemDestroyed( uriSpec, obj2, callback) {deps.add( {obj:this, channel:this.getChannel('item', 'destroyed', uriSpec) }, obj2, callback);} removeDep_itemDestroyed(uriSpec, obj2) {deps.remove({obj:this, channel:this.getChannel('item', 'destroyed', uriSpec) }, obj2);} // <obj2>.onWorkspaceItemActivated(<item>, <previousActiveItem>) // callback(<activateditem>, <previousActiveItem>) addDep_itemActivated( uriSpec, obj2, callback) {deps.add( {obj:this, channel:this.getChannel('item', 'activated', uriSpec) }, obj2, callback);} removeDep_itemActivated(uriSpec, obj2) {deps.remove({obj:this, channel:this.getChannel('item', 'activated', uriSpec) }, obj2);} // <obj2>.onWorkspaceItemDeactivated(<item>, <newActiveItem>) // callback(<deactivateditem>, <newActiveItem>) addDep_itemDeactivated( uriSpec, obj2, callback) {deps.add( {obj:this, channel:this.getChannel('item', 'deactivated', uriSpec) }, obj2, callback);} removeDep_itemDeactivated(uriSpec, obj2) {deps.remove({obj:this, channel:this.getChannel('item', 'deactivated', uriSpec) }, obj2);} // <obj2>.onWorkspaceTextEditorChanged(<actionType>, <editor>, ...) // callback('opened', <editor>, <pane>, <index>) // callback('activated', <editor>, <previousActiveEditor>) // callback('deactivated', <editor>, <newActiveEditor>) addDep_textEditor( uriSpec, obj2, callback) {deps.add( {obj:this, channel:this.getChannel('textEditor', '', uriSpec) }, obj2, callback);} removeDep_textEditor(uriSpec, obj2) {deps.remove({obj:this, channel:this.getChannel('textEditor', '', uriSpec) }, obj2);} // <obj2>.onWorkspaceTextEditorOpened(<editor>, <pane>, <index>) // callback(<openedEditor>, <pane>, <index>) addDep_textEditorOpened( uriSpec, obj2, callback) {deps.add( {obj:this, channel:this.getChannel('textEditor', 'opened', uriSpec) }, obj2, callback);} removeDep_textEditorOpened(uriSpec, obj2) {deps.remove({obj:this, channel:this.getChannel('textEditor', 'opened', uriSpec) }, obj2);} // <obj2>.onWorkspaceTextEditorActivated(<editor>, <previousActiveEditor>) // callback(<activatedEditor>, <previousActiveEditor>) addDep_textEditorActivated( uriSpec, obj2, callback) {deps.add( {obj:this, channel:this.getChannel('textEditor', 'activated', uriSpec) }, obj2, callback);} removeDep_textEditorActivated(uriSpec, obj2) {deps.remove({obj:this, channel:this.getChannel('textEditor', 'activated', uriSpec) }, obj2);} // <obj2>.onWorkspaceTextEditorDeactivated(<editor>, <newActiveEditor>) // callback(<deactivatedEditor>, <newActiveEditor>) addDep_textEditorDeactivated( uriSpec, obj2, callback) {deps.add( {obj:this, channel:this.getChannel('textEditor', 'deactivated', uriSpec) }, obj2, callback);} removeDep_textEditorDeactivated(uriSpec, obj2) {deps.remove({obj:this, channel:this.getChannel('textEditor', 'deactivated', uriSpec) }, obj2);} // <obj2>.onWorkspaceTextPaneChanged(<actionType>, <pane>, ...) // callback('opened' <pane>) // callback('destroyed' <pane>) // callback('activated' <pane>, <previousActivePane>) // callback('deactivated' <pane>, <newActivePane>) addDep_pane( obj2, callback) {deps.add( {obj:this, channel:'panes' }, obj2, callback);} removeDep_pane(obj2) {deps.remove({obj:this, channel:'panes' }, obj2);} // <obj2>.onWorkspaceTextPaneOpened(<pane>) // callback(<openedPane>) addDep_paneOpened( obj2, callback) {deps.add({obj:this, channel:'panes.opened' }, obj2, callback);} removeDep_paneOpened(obj2) {deps.remove({obj:this, channel:'panes.opened' }, obj2);} // <obj2>.onWorkspaceTextPaneDestroyed(<pane>) // callback(<destroyedPane>) addDep_paneDestroyed( obj2, callback) {deps.add({obj:this, channel:'panes.destroyed' }, obj2, callback);} removeDep_paneDestroyed(obj2) {deps.remove({obj:this, channel:'panes.destroyed' }, obj2);} // <obj2>.onWorkspaceTextPaneActivated(<pane>, <previousActivePane>) // callback(<activatedPane>, <previousActivePane>) addDep_paneActivated( obj2, callback) {deps.add({obj:this, channel:'panes.activated' }, obj2, callback);} removeDep_paneActivated(obj2) {deps.remove({obj:this, channel:'panes.activated' }, obj2);} // <obj2>.onWorkspaceTextPaneDeactivated(<pane>, <newActivePane>) // callback(<deactivatedPane>, <newActivePane>) addDep_paneDeactivated( obj2, callback) {deps.add({obj:this, channel:'panes.deactivated' }, obj2, callback);} removeDep_paneDeactivated(obj2) {deps.remove({obj:this, channel:'panes.deactivated' }, obj2);} }
JavaScript
class AtomWorkspaceChannelNode extends ChannelNode { // in this case we made one class that works with all channel of the atom.workspace object so we do not consider channel in the match static matchSource(obj1,channel) {return obj1===atom.workspace} static resolveChannel(channel) { if (channel === deps.fAll) return {channelType:'all', channelAction:'', itemSpec:''}; else { const rematch = AtomWorkspaceChannelNode.channelRegex.exec((channel)?channel.toString():''); if (!rematch) return {}; const { channelType, channelAction='' } = rematch.groups const itemSpec = new RegExp( (rematch.groups.itemRe) ? rematch.groups.itemRe : (rematch.groups.itemStr) ? '^'+rematch.groups.itemStr :'^', rematch.groups.itemFlags ); return {channelType, channelAction, itemSpec} } } constructor(obj, channel) { super(obj, channel); const { channelType, channelAction, itemSpec} = AtomWorkspaceChannelNode.resolveChannel(channel); if (!channelType) { console.assert(false, 'malformed DependentsGraph channel for atom.workspace', {obj,channel}); throw 'malformed DependentsGraph channel for atom.workspace'; } switch (channelType) { case 'uri': switch (channelAction) { case 'opening': this.defaultTargetMethodName = 'onURIOpening'; this.disposables.add(obj.addOpener((uri)=>{ if (itemSpec.test(uri)) { const results = deps.fire({obj,channel}, uri); return results; } })) break; } break; case 'item': this.lastActiveItem = obj.activePaneContainer.getActivePaneItem(); switch (channelAction) { case 'opened': this.defaultTargetMethodName = 'onWorkspaceItemOpened'; this.disposables.add(obj.onDidOpen((event)=>{ if (itemSpec.test(event.uri)) deps.fire({obj,channel}, event.item, event.pane, event.index) })) break; case 'destroyed': this.defaultTargetMethodName = 'onWorkspaceItemDestroyed'; this.disposables.add(obj.onDidDestroyPaneItem((event)=>{ if (itemSpec.test(GetURI(event.item))) deps.fire({obj,channel}, 'destroyed', event.item, event.pane, event.index) })) break; case 'activated': this.defaultTargetMethodName = 'onWorkspaceItemActivated'; this.disposables.add(obj.onDidChangeActivePaneItem((item)=>{ if (item && itemSpec.test(GetURI(item))) deps.fire({obj,channel}, 'activated', item, this.lastActiveItem); this.lastActiveItem = item; })) break; case 'deactivated': this.defaultTargetMethodName = 'onWorkspaceItemDeactivated'; this.disposables.add(obj.onDidChangeActivePaneItem((item)=>{ if (this.lastActiveItem && itemSpec.test(GetURI(this.lastActiveItem))) deps.fire({obj,channel}, 'deactivated', this.lastActiveItem, item); this.lastActiveItem = item; })) break; default: this.defaultTargetMethodName = 'onWorkspaceItemChanged'; this.disposables.add(obj.onDidOpen((event)=>{ if (itemSpec.test(event.uri)) deps.fire({obj,channel}, 'opened', event.item, event.pane, event.index) })) this.disposables.add(obj.onDidDestroyPaneItem((event)=>{ if (itemSpec.test(GetURI(event.item))) deps.fire({obj,channel}, 'destroyed', event.item, event.pane, event.index) })) this.disposables.add(obj.onDidChangeActivePaneItem((item)=>{ if (this.lastActiveItem && itemSpec.test(GetURI(this.lastActiveItem))) deps.fire({obj,channel}, 'deactivated', this.lastActiveItem, item); if (item && itemSpec.test(GetURI(item))) deps.fire({obj,channel}, 'activated', item, this.lastActiveItem); this.lastActiveItem = item; })) } break; case 'textEditor': this.lastActiveEditor = obj.getActiveTextEditor(); switch (channelAction) { case 'opened': this.defaultTargetMethodName = 'onTextEditorOpened'; this.disposables.add(obj.onDidAddTextEditor((event)=>{ if (itemSpec.test(GetURI(event.textEditor))) deps.fire({obj,channel}, event.textEditor, event.pane, event.index) })) break; case 'activated': this.defaultTargetMethodName = 'onTextEditorActivated'; this.disposables.add(obj.onDidChangeActiveTextEditor((editor)=>{ if (itemSpec.test(GetURI(editor))) deps.fire({obj,channel}, editor, this.lastActiveEditor) this.lastActiveEditor = editor; })) break; case 'deactivated': this.defaultTargetMethodName = 'onTextEditorDeactivated'; this.disposables.add(obj.onDidChangeActiveTextEditor((editor)=>{ if (this.lastActiveEditor && itemSpec.test(GetURI(this.lastActiveEditor))) deps.fire({obj,channel}, this.lastActiveEditor, editor) this.lastActiveEditor = editor; })) break; default: this.defaultTargetMethodName = 'onTextEditorChanged'; this.disposables.add(obj.onDidAddTextEditor((event)=>{ if (itemSpec.test(GetURI(event.textEditor))) deps.fire({obj,channel}, 'opened', event.textEditor, event.pane, event.index) })) this.disposables.add(obj.onDidChangeActiveTextEditor((editor)=>{ if (this.lastActiveEditor && itemSpec.test(GetURI(this.lastActiveEditor))) deps.fire({obj,channel}, 'deactivated', this.lastActiveEditor, editor) if (itemSpec.test(GetURI(editor))) deps.fire({obj,channel}, 'activated', editor, this.lastActiveEditor) this.lastActiveEditor = editor; })) } break; case 'pane': this.lastActivePane = obj.activePaneContainer.getActivePane(); switch (channelAction) { case 'opened': this.defaultTargetMethodName = 'onPaneOpened'; this.disposables.add(obj.onDidAddPane((event)=>{ deps.fire({obj,channel}, event.pane) })) break; case 'destroyed': this.defaultTargetMethodName = 'onPaneDestroyed'; this.disposables.add(obj.onDidDestroyPane((event)=>{ deps.fire({obj,channel}, event.pane) })) break; case 'activated': this.defaultTargetMethodName = 'onPaneActivated'; this.disposables.add(obj.onDidChangeActivePane((pane)=>{ deps.fire({obj,channel}, pane, this.lastActivePane); this.lastActivePane = pane; })) break; case 'deactivated': this.defaultTargetMethodName = 'onPaneDeactivated'; this.disposables.add(obj.onDidChangeActivePane((pane)=>{ this.lastActivePane && deps.fire({obj,channel}, this.lastActivePane, pane); this.lastActivePane = pane; })) break; default: this.defaultTargetMethodName = 'onPaneChanged'; this.disposables.add(obj.onDidAddPane((event)=>{ deps.fire({obj,channel}, 'opened', event.pane) })) this.disposables.add(obj.onDidDestroyPane((event)=>{ deps.fire({obj,channel}, 'destroyed', event.pane) })) this.disposables.add(obj.onDidChangeActivePane((pane)=>{ this.lastActivePane && deps.fire({obj,channel}, 'deactivated', this.lastActivePane, pane); deps.fire({obj,channel}, 'activated', pane, this.lastActivePane); this.lastActivePane = pane; })) } break; case 'all': this.defaultTargetMethodName = 'onWorkspaceChanged'; this.lastActiveItem = obj.activePaneContainer.getActivePaneItem(); this.lastActiveEditor = obj.getActiveTextEditor(); this.lastActivePane = obj.activePaneContainer.getActivePane(); this.disposables.add(obj.onDidOpen((event)=>{ deps.fire({obj,channel}, 'item', 'opened', event.item, event.pane, event.index) })) this.disposables.add(obj.onDidDestroyPaneItem((event)=>{ deps.fire({obj,channel}, 'item', 'destroyed', event.item, event.pane, event.index) })) this.disposables.add(obj.onDidChangeActivePaneItem((item)=>{ this.lastActiveItem && deps.fire({obj,channel}, 'item', 'deactivated', this.lastActiveItem, item); item && deps.fire({obj,channel}, 'item', 'activated', item, this.lastActiveItem); this.lastActiveItem = item; })) this.disposables.add(obj.onDidAddTextEditor((event)=>{ deps.fire({obj,channel}, 'textEditor', 'opened', event.textEditor, event.pane, event.index) })) this.disposables.add(obj.onDidChangeActiveTextEditor((editor)=>{ this.lastActiveEditor && deps.fire({obj,channel}, 'textEditor', 'deactivated', this.lastActiveEditor, editor) deps.fire({obj,channel}, 'textEditor', 'activated', editor, this.lastActiveEditor) this.lastActiveEditor = editor; })) this.disposables.add(obj.onDidAddPane((event)=>{ deps.fire({obj,channel}, 'pane', 'opened', event.pane) })) this.disposables.add(obj.onDidDestroyPane((event)=>{ deps.fire({obj,channel}, 'pane', 'destroyed', event.pane) })) this.disposables.add(obj.onDidChangeActivePane((pane)=>{ this.lastActivePane && deps.fire({obj,channel}, 'pane', 'deactivated', this.lastActivePane, pane); deps.fire({obj,channel}, 'pane', 'activated', pane, this.lastActivePane); this.lastActivePane = pane; })) break; default: console.assert(false,'logic error: channelType should have been resolved to one of item|textEditor|pane|all', {channelType}); } } }
JavaScript
class RaddecBalancer { /** * RaddecBalancer constructor * @param {Object} options The options as a JSON object. * @constructor */ constructor(options) { options = options || {}; this.numberOfTargets = options.numberOfTargets || DEFAULT_NUMBER_OF_TARGETS; } /** * Balance the given raddec among the targets. * @param {Raddec} raddec The given Raddec instance. * @param {function} callback The function to call upon completion. */ balanceRaddec(raddec, callback) { // TODO: support strategies other than modulo let targetIndex = parseInt(raddec.transmitterId, 16) % this.numberOfTargets; return callback(raddec, targetIndex); } }
JavaScript
class MemoryBackend { constructor (options = {}) { this._docs = options._docs || {} } /** * Loads the object for a given key. * * @param key {string} * @returns {Promise<object>} Parsed JSON object */ async get (key) { return this._docs[key] } /** * Stores the object at a given key. * @param key {string} * @param value {object} * @returns {Promise<object>} */ async put (key, value) { this._docs[key] = value return value } /** * Deletes an object at a given key. * @param key {string} * @returns {Promise} */ async remove (key) { delete this._docs[key] } /* eslint-disable camelcase */ /** * Returns all the object in this store. * * @param [include_docs=false] {boolean} Include document contents as well * as keys? * @returns {Promise<{offset: number, total_rows: number, rows: Array<object>}>} */ async allDocs ({ include_docs } = {}) { const keys = Object.keys(this._docs) return { offset: 0, total_rows: keys.length, rows: keys.map(key => { const row = { id: key } if (include_docs) { row.doc = this._docs[key] row.doc._id = key } return row }) } } }
JavaScript
class Help$2 { constructor() { this.helpWidth = undefined; this.sortSubcommands = false; this.sortOptions = false; } /** * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one. * * @param {Command} cmd * @returns {Command[]} */ visibleCommands(cmd) { const visibleCommands = cmd.commands.filter(cmd => !cmd._hidden); if (cmd._hasImplicitHelpCommand()) { // Create a command matching the implicit help command. const [, helpName, helpArgs] = cmd._helpCommandnameAndArgs.match(/([^ ]+) *(.*)/); const helpCommand = cmd.createCommand(helpName) .helpOption(false); helpCommand.description(cmd._helpCommandDescription); if (helpArgs) helpCommand.arguments(helpArgs); visibleCommands.push(helpCommand); } if (this.sortSubcommands) { visibleCommands.sort((a, b) => { // @ts-ignore: overloaded return type return a.name().localeCompare(b.name()); }); } return visibleCommands; } /** * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one. * * @param {Command} cmd * @returns {Option[]} */ visibleOptions(cmd) { const visibleOptions = cmd.options.filter((option) => !option.hidden); // Implicit help const showShortHelpFlag = cmd._hasHelpOption && cmd._helpShortFlag && !cmd._findOption(cmd._helpShortFlag); const showLongHelpFlag = cmd._hasHelpOption && !cmd._findOption(cmd._helpLongFlag); if (showShortHelpFlag || showLongHelpFlag) { let helpOption; if (!showShortHelpFlag) { helpOption = cmd.createOption(cmd._helpLongFlag, cmd._helpDescription); } else if (!showLongHelpFlag) { helpOption = cmd.createOption(cmd._helpShortFlag, cmd._helpDescription); } else { helpOption = cmd.createOption(cmd._helpFlags, cmd._helpDescription); } visibleOptions.push(helpOption); } if (this.sortOptions) { const getSortKey = (option) => { // WYSIWYG for order displayed in help with short before long, no special handling for negated. return option.short ? option.short.replace(/^-/, '') : option.long.replace(/^--/, ''); }; visibleOptions.sort((a, b) => { return getSortKey(a).localeCompare(getSortKey(b)); }); } return visibleOptions; } /** * Get an array of the arguments if any have a description. * * @param {Command} cmd * @returns {Argument[]} */ visibleArguments(cmd) { // Side effect! Apply the legacy descriptions before the arguments are displayed. if (cmd._argsDescription) { cmd._args.forEach(argument => { argument.description = argument.description || cmd._argsDescription[argument.name()] || ''; }); } // If there are any arguments with a description then return all the arguments. if (cmd._args.find(argument => argument.description)) { return cmd._args; } return []; } /** * Get the command term to show in the list of subcommands. * * @param {Command} cmd * @returns {string} */ subcommandTerm(cmd) { // Legacy. Ignores custom usage string, and nested commands. const args = cmd._args.map(arg => humanReadableArgName$1(arg)).join(' '); return cmd._name + (cmd._aliases[0] ? '|' + cmd._aliases[0] : '') + (cmd.options.length ? ' [options]' : '') + // simplistic check for non-help option (args ? ' ' + args : ''); } /** * Get the option term to show in the list of options. * * @param {Option} option * @returns {string} */ optionTerm(option) { return option.flags; } /** * Get the argument term to show in the list of arguments. * * @param {Argument} argument * @returns {string} */ argumentTerm(argument) { return argument.name(); } /** * Get the longest command term length. * * @param {Command} cmd * @param {Help} helper * @returns {number} */ longestSubcommandTermLength(cmd, helper) { return helper.visibleCommands(cmd).reduce((max, command) => { return Math.max(max, helper.subcommandTerm(command).length); }, 0); } /** * Get the longest option term length. * * @param {Command} cmd * @param {Help} helper * @returns {number} */ longestOptionTermLength(cmd, helper) { return helper.visibleOptions(cmd).reduce((max, option) => { return Math.max(max, helper.optionTerm(option).length); }, 0); } /** * Get the longest argument term length. * * @param {Command} cmd * @param {Help} helper * @returns {number} */ longestArgumentTermLength(cmd, helper) { return helper.visibleArguments(cmd).reduce((max, argument) => { return Math.max(max, helper.argumentTerm(argument).length); }, 0); } /** * Get the command usage to be displayed at the top of the built-in help. * * @param {Command} cmd * @returns {string} */ commandUsage(cmd) { // Usage let cmdName = cmd._name; if (cmd._aliases[0]) { cmdName = cmdName + '|' + cmd._aliases[0]; } let parentCmdNames = ''; for (let parentCmd = cmd.parent; parentCmd; parentCmd = parentCmd.parent) { parentCmdNames = parentCmd.name() + ' ' + parentCmdNames; } return parentCmdNames + cmdName + ' ' + cmd.usage(); } /** * Get the description for the command. * * @param {Command} cmd * @returns {string} */ commandDescription(cmd) { // @ts-ignore: overloaded return type return cmd.description(); } /** * Get the command description to show in the list of subcommands. * * @param {Command} cmd * @returns {string} */ subcommandDescription(cmd) { // @ts-ignore: overloaded return type return cmd.description(); } /** * Get the option description to show in the list of options. * * @param {Option} option * @return {string} */ optionDescription(option) { const extraInfo = []; if (option.argChoices) { extraInfo.push( // use stringify to match the display of the default value `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`); } if (option.defaultValue !== undefined) { // default for boolean and negated more for programmer than end user, // but show true/false for boolean option as may be for hand-rolled env or config processing. const showDefault = option.required || option.optional || (option.isBoolean() && typeof option.defaultValue === 'boolean'); if (showDefault) { extraInfo.push(`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`); } } // preset for boolean and negated are more for programmer than end user if (option.presetArg !== undefined && option.optional) { extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`); } if (option.envVar !== undefined) { extraInfo.push(`env: ${option.envVar}`); } if (extraInfo.length > 0) { return `${option.description} (${extraInfo.join(', ')})`; } return option.description; } /** * Get the argument description to show in the list of arguments. * * @param {Argument} argument * @return {string} */ argumentDescription(argument) { const extraInfo = []; if (argument.argChoices) { extraInfo.push( // use stringify to match the display of the default value `choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`); } if (argument.defaultValue !== undefined) { extraInfo.push(`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`); } if (extraInfo.length > 0) { const extraDescripton = `(${extraInfo.join(', ')})`; if (argument.description) { return `${argument.description} ${extraDescripton}`; } return extraDescripton; } return argument.description; } /** * Generate the built-in help text. * * @param {Command} cmd * @param {Help} helper * @returns {string} */ formatHelp(cmd, helper) { const termWidth = helper.padWidth(cmd, helper); const helpWidth = helper.helpWidth || 80; const itemIndentWidth = 2; const itemSeparatorWidth = 2; // between term and description function formatItem(term, description) { if (description) { const fullText = `${term.padEnd(termWidth + itemSeparatorWidth)}${description}`; return helper.wrap(fullText, helpWidth - itemIndentWidth, termWidth + itemSeparatorWidth); } return term; } function formatList(textArray) { return textArray.join('\n').replace(/^/gm, ' '.repeat(itemIndentWidth)); } // Usage let output = [`Usage: ${helper.commandUsage(cmd)}`, '']; // Description const commandDescription = helper.commandDescription(cmd); if (commandDescription.length > 0) { output = output.concat([commandDescription, '']); } // Arguments const argumentList = helper.visibleArguments(cmd).map((argument) => { return formatItem(helper.argumentTerm(argument), helper.argumentDescription(argument)); }); if (argumentList.length > 0) { output = output.concat(['Arguments:', formatList(argumentList), '']); } // Options const optionList = helper.visibleOptions(cmd).map((option) => { return formatItem(helper.optionTerm(option), helper.optionDescription(option)); }); if (optionList.length > 0) { output = output.concat(['Options:', formatList(optionList), '']); } // Commands const commandList = helper.visibleCommands(cmd).map((cmd) => { return formatItem(helper.subcommandTerm(cmd), helper.subcommandDescription(cmd)); }); if (commandList.length > 0) { output = output.concat(['Commands:', formatList(commandList), '']); } return output.join('\n'); } /** * Calculate the pad width from the maximum term length. * * @param {Command} cmd * @param {Help} helper * @returns {number} */ padWidth(cmd, helper) { return Math.max( helper.longestOptionTermLength(cmd, helper), helper.longestSubcommandTermLength(cmd, helper), helper.longestArgumentTermLength(cmd, helper) ); } /** * Wrap the given string to width characters per line, with lines after the first indented. * Do not wrap if insufficient room for wrapping (minColumnWidth), or string is manually formatted. * * @param {string} str * @param {number} width * @param {number} indent * @param {number} [minColumnWidth=40] * @return {string} * */ wrap(str, width, indent, minColumnWidth = 40) { // Detect manually wrapped and indented strings by searching for line breaks // followed by multiple spaces/tabs. if (str.match(/[\n]\s+/)) return str; // Do not wrap if not enough room for a wrapped column of text (as could end up with a word per line). const columnWidth = width - indent; if (columnWidth < minColumnWidth) return str; const leadingStr = str.substr(0, indent); const columnText = str.substr(indent); const indentString = ' '.repeat(indent); const regex = new RegExp('.{1,' + (columnWidth - 1) + '}([\\s\u200B]|$)|[^\\s\u200B]+?([\\s\u200B]|$)', 'g'); const lines = columnText.match(regex) || []; return leadingStr + lines.map((line, i) => { if (line.slice(-1) === '\n') { line = line.slice(0, line.length - 1); } return ((i > 0) ? indentString : '') + line.trimRight(); }).join('\n'); } }
JavaScript
class TestServer { constructor(user) { var mockPassport = new passport.Passport() mockPassport.use( new MockStrategy( { user: user, }, function (user, cb) { User.findOrCreate({ where: { email: user.email }, defaults: user, }).then((user) => { cb(null, { uuid: user[0].uuid }) }) } ) ) mockPassport.serializeUser((user, cb) => { cb(null, JSON.stringify(user)) }) mockPassport.deserializeUser((user, cb) => { cb(null, JSON.parse(user)) }) var server = new ExpressServer(config.URL_PORT, config.OPENAPI_YAML) server.setupMiddleware() server.app.use(mockPassport.initialize()) server.app.use(mockPassport.session()) server.app.get( config.OAUTH20_CALLBACK, mockPassport.authenticate('mock', { failureRedirect: '/login/error', successRedirect: '/', }) ) server.setupAPI() this.server = server } launch() { return this.server.launch() } close() { return this.server.close() } }
JavaScript
class MongoModel extends BaseModel { /** * Create model * @param {Postgres|MySQL|Mongo} db Database service * @param {Util} util Util service */ constructor(db, util) { super(db, util); this._addField('_id', 'id'); } /** * Dependencies as constructor arguments * @type {string[]} */ static get requires() { return [ 'mongo', 'util' ]; } /** * ID setter * @type {undefined|number} */ set id(id) { return this._setField('_id', id); } /** * ID getter * @type {undefined|number} */ get id() { return this._getField('_id'); } }
JavaScript
class TodoItem extends Component { removeTodo() { const { todo, todos } = this.props; const idx = todos.indexOf(todo); if (idx !== -1) { todos.remove(idx); } } handleToggleCompleted() { const { todo } = this.props; // toggle the completed flag todo.completed = !todo.completed; } render() { const { todo } = this.props; const { completed, desc } = todo; const descClasses = classnames("todoItem-desc", { "todoItem-descCompleted": completed }); const completedClasses = classnames("todoItem-completed fa", { "fa-check-square-o todoItem-completedChecked": completed, "fa-square-o": !completed, }); return <div className="todoItem"> <i className={ completedClasses } onClick={ () => this.handleToggleCompleted() } /> <input type="text" className={ descClasses } onChange={ event => todo.desc = event.target.value } defaultValue={ desc } /> <i className="todoItem-delete fa fa-times" onClick={ () => this.removeTodo() }/> </div> } }
JavaScript
class Foo { /** * @constructor */ constructor () { // ... bar(); } }
JavaScript
class RequestError extends Error { constructor(message, statusCode, options) { super(message); // Maintains proper stack trace (only available on V8) /* istanbul ignore next */ if (Error.captureStackTrace) { Error.captureStackTrace(this, this.constructor); } this.name = "HttpError"; this.status = statusCode; let headers; if ("headers" in options && typeof options.headers !== "undefined") { headers = options.headers; } if ("response" in options) { this.response = options.response; headers = options.response.headers; } // redact request credentials without mutating original request options const requestCopy = Object.assign({}, options.request); if (options.request.headers.authorization) { requestCopy.headers = Object.assign({}, options.request.headers, { authorization: options.request.headers.authorization.replace(/ .*$/, " [REDACTED]") }); } requestCopy.url = requestCopy.url // client_id & client_secret can be passed as URL query parameters to increase rate limit // see https://developer.github.com/v3/#increasing-the-unauthenticated-rate-limit-for-oauth-applications .replace(/\bclient_secret=\w+/g, "client_secret=[REDACTED]") // OAuth tokens can be passed as URL query parameters, although it is not recommended // see https://developer.github.com/v3/#oauth2-token-sent-in-a-header .replace(/\baccess_token=\w+/g, "access_token=[REDACTED]"); this.request = requestCopy; // deprecations Object.defineProperty(this, "code", { get() { logOnceCode(new deprecation.Deprecation("[@octokit/request-error] `error.code` is deprecated, use `error.status`.")); return statusCode; } }); Object.defineProperty(this, "headers", { get() { logOnceHeaders(new deprecation.Deprecation("[@octokit/request-error] `error.headers` is deprecated, use `error.response.headers`.")); return headers || {}; } }); } }
JavaScript
class IncomingWebhook { constructor(url, defaults = {}) { if (url === undefined) { throw new Error('Incoming webhook URL is required'); } this.url = url; this.defaults = defaults; this.axios = axios_1.default.create({ baseURL: url, httpAgent: defaults.agent, httpsAgent: defaults.agent, maxRedirects: 0, proxy: false, headers: { 'User-Agent': instrument_1.getUserAgent(), }, }); delete this.defaults.agent; } /** * Send a notification to a conversation * @param message - the message (a simple string, or an object describing the message) */ async send(message) { // NOTE: no support for TLS config let payload = Object.assign({}, this.defaults); if (typeof message === 'string') { payload.text = message; } else { payload = Object.assign(payload, message); } try { const response = await this.axios.post(this.url, payload); return this.buildResult(response); } catch (error) { // Wrap errors in this packages own error types (abstract the implementation details' types) if (error.response !== undefined) { throw errors_1.httpErrorWithOriginal(error); } else if (error.request !== undefined) { throw errors_1.requestErrorWithOriginal(error); } else { throw error; } } } /** * Processes an HTTP response into an IncomingWebhookResult. */ buildResult(response) { return { text: response.data, }; } }
JavaScript
class Response { constructor() { let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; Body.call(this, body, opts); const status = opts.status || 200; const headers = new Headers(opts.headers); if (body != null && !headers.has('Content-Type')) { const contentType = extractContentType(body); if (contentType) { headers.append('Content-Type', contentType); } } this[INTERNALS$1] = { url: opts.url, status, statusText: opts.statusText || STATUS_CODES[status], headers, counter: opts.counter }; } get url() { return this[INTERNALS$1].url || ''; } get status() { return this[INTERNALS$1].status; } /** * Convenience property representing if the request ended normally */ get ok() { return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300; } get redirected() { return this[INTERNALS$1].counter > 0; } get statusText() { return this[INTERNALS$1].statusText; } get headers() { return this[INTERNALS$1].headers; } /** * Clone this response * * @return Response */ clone() { return new Response(clone(this), { url: this.url, status: this.status, statusText: this.statusText, headers: this.headers, ok: this.ok, redirected: this.redirected }); } }
JavaScript
class Request { constructor(input) { let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; let parsedURL; // normalize input if (!isRequest(input)) { if (input && input.href) { // in order to support Node.js' Url objects; though WHATWG's URL objects // will fall into this branch also (since their `toString()` will return // `href` property anyway) parsedURL = parse_url(input.href); } else { // coerce input to a string before attempting to parse parsedURL = parse_url(`${input}`); } input = {}; } else { parsedURL = parse_url(input.url); } let method = init.method || input.method || 'GET'; method = method.toUpperCase(); if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) { throw new TypeError('Request with GET/HEAD method cannot have body'); } let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null; Body.call(this, inputBody, { timeout: init.timeout || input.timeout || 0, size: init.size || input.size || 0 }); const headers = new Headers(init.headers || input.headers || {}); if (inputBody != null && !headers.has('Content-Type')) { const contentType = extractContentType(inputBody); if (contentType) { headers.append('Content-Type', contentType); } } let signal = isRequest(input) ? input.signal : null; if ('signal' in init) signal = init.signal; if (signal != null && !isAbortSignal(signal)) { throw new TypeError('Expected signal to be an instanceof AbortSignal'); } this[INTERNALS$2] = { method, redirect: init.redirect || input.redirect || 'follow', headers, parsedURL, signal }; // node-fetch-only options this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20; this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true; this.counter = init.counter || input.counter || 0; this.agent = init.agent || input.agent; } get method() { return this[INTERNALS$2].method; } get url() { return format_url(this[INTERNALS$2].parsedURL); } get headers() { return this[INTERNALS$2].headers; } get redirect() { return this[INTERNALS$2].redirect; } get signal() { return this[INTERNALS$2].signal; } /** * Clone this request * * @return Request */ clone() { return new Request(this); } }
JavaScript
class DataDeletionRequest { /** * Create a DataDeletionRequest. * @member {string} [dataDeletionType] Type of data to delete */ constructor() { } /** * Defines the metadata of DataDeletionRequest * * @returns {object} metadata of DataDeletionRequest * */ mapper() { return { required: false, serializedName: 'DataDeletionRequest', type: { name: 'Composite', className: 'DataDeletionRequest', modelProperties: { dataDeletionType: { required: false, serializedName: 'data_deletion_type', type: { name: 'String' } } } } }; } }
JavaScript
class PipingFactory { constructor(manager, spec) { this._manager = manager; this._spec = spec; } /** * create a new Piping * @param {string} key * @param {*} value * @param {array|object|string} specLine * @param {object} [$this] * @returns {Piping} */ create(key, value, specLine, $this) { var line; if ((typeof specLine === 'object') && (!Array.isArray(specLine))) { line = new Pipe(specLine, this._spec.builtins); return line. on('error', (err, value) => this._manager.error(err, key, value)). on('success', (value) => this._manager.success(key, value)). run(value, function() {}, $this); } line = new Pipeline(key, value, this._spec.get(key), this._spec.builtins, $this); return line. on('error', this._manager.error.bind(this._manager)). on('success', this._manager.success.bind(this._manager)). run(); } }
JavaScript
class MediaObject { /** * Creates an instance of MediaObject. * @param {Object} attributes Object with attributes that will specify the contents. * @param {HTMLElement} rootElement HTMLElement DOM Node that acts as container to this object. * * @memberOf MediaObject */ constructor(rootElement) { /** * Generate a unique id for this MediaObject, currently necessary to handle * multiple MediaObject in the various engines. */ this.id = MediaObject.uid(); this.element = rootElement; this.state = 'idle'; /** * @type {Object} attributesObject Object with attributes that will specify the contents. */ this.attributesObject = new AttributesObject(rootElement); const properties = Parser.parse(this.attributesObject); for (const property of Object.keys(properties)) { this[property] = properties[property]; } /** * @type {HTMLElement} rootElement HTMLElement DOM Node that acts as * container to this object. */ // TODO: rethink about what is the best, explicit bind needed // functions OR saving the element this.hookedFns = { hasChildNodes: rootElement.hasChildNodes.bind(rootElement), removeChild: rootElement.removeChild.bind(rootElement), getLastChild: () => rootElement.lastChild, appendChild: rootElement.appendChild.bind(rootElement), children: () => rootElement.children }; } /** * Sets the properties. Properties are unique, no redefinition otherwise throws error. * * @param {Object} properties The properties */ setProperties(properties) { for (const key in properties) { if (this[key]) { throw new Error('The property ' + key + ' already exists in this MediaObject !'); } this[key] = properties[key]; } } /** * Gets the identifier. * * @return {Number} The identifier. */ getId() { return this.id; } // TODO: define what will be direct method and what will be by getAttribute /** * Returns the value of a given attribute. * * @param {string} attrName Attribute identifier. * @returns any the contents of the attribute. * * @memberOf MediaObject */ getAttribute(attrName) { return this.attributesObject[attrName]; } /** * Sets the attribute. * * @param {String} name The name * @param {*} value The value */ setAttribute(name, value) { this.attributesObject[name] = value; } /** * Removes an attribute. * * @param {String} name The name */ removeAttribute(name) { delete this.attributesObject[name]; } /** * Returns all the attribute identifiers that starts with 'data-attr'. * These attributes are normally passed down to the final element. * * @returns string[] List of attribute identifiers. * * @memberOf MediaObject */ getAllDataAttrKeys() { return Object.keys(this.attributesObject).filter(field => field.startsWith('data-attr')); } /** * Returns the media content extension when available. * * @returns string Extension of media. For example, if the media * source is "image.png" the extension is "png". * * @memberOf MediaObject */ getExtension() { return this.extension; } /** * Returns the media content mime type when available. * * @returns string Media mime type. For example, if the media * source is "image.png" the mime type is "image/png". * * @memberOf MediaObject */ getMimeType() { return this.mime; } /** * Check for existence of a given attribute. * * @param {string} attributeName Attribute identifier to be checked. * @returns Boolean true if attribute exists, false otherwise. * * @memberOf MediaObject */ hasAttribute(attributeName) { return attributeName in this.attributesObject; } /** * Return the data-type attribute value. * * @returns string data-type attribute value. * * @memberOf MediaObject */ getType() { return this.type; } /** * Gets the source. * * @return {string} The source. */ getSource() { return this.src; } /** * Gets the sources. * * @return {Array<Object>} The sources. */ getSources() { return this.sources; } /** * Cleans up the mediaTag element. */ clearContents() { while (this.hookedFns.hasChildNodes()) { this.hookedFns.removeChild(this.hookedFns.getLastChild()); } } /** * Replace the contents of the container, associated to the object, * by the given elements. All previous contents of the container are * erased. * * @param {HTMLElement[]} elements List of HTMLElement elements. * * @memberOf MediaObject */ replaceContents(elements) { /** * Cleans up <media-tag> element. (root) */ this.clearContents(); /** * Adds elements to <media-tag> element. (root) */ elements.forEach(element => this.hookedFns.appendChild(element)); } /** * Sets all data-attr-* to * on the given element. For example, * given a media-tag with data-attr-width="200px", this function * will set element.setAttribute('width', '200px'). Notice that * the attribute set have the prefix 'data-attr-' removed. * * @param {HTMLElement} element Element that will have attributes set. * * @memberOf MediaObject */ utilsSetAllDataAttributes(element) { const dataAttributes = this.getAllDataAttrKeys(); dataAttributes.forEach(dataAttr => element.setAttribute(dataAttr.substr(10), this.getAttribute(dataAttr))); } /** * Pass to the given element all data-attr-* attributes. For * example, given a media-tag with data-attr-width="200px", this * function will set element.setAttribute('data-attr-width','200px'). * Notice that the attribute set has still the prefix 'data-attr-'. * * @param {HTMLElement} element Element that will have attributes set. * * @memberOf MediaObject */ utilsPassAllDataAttributes(element) { const dataAttributes = this.getAllDataAttrKeys(); dataAttributes.forEach(dataAttr => element.setAttribute(dataAttr, this.getAttribute(dataAttr))); } }
JavaScript
class Setting { constructor(defaultValue, type, group) { this.defaultValue = defaultValue; this.type = type; this.group = group; } }
JavaScript
class HybridRunbookWorkerGroup { /** * Create a HybridRunbookWorkerGroup. * @member {string} [id] Gets or sets the id of the resource. * @member {string} [name] Gets or sets the name of the group. * @member {array} [hybridRunbookWorkers] Gets or sets the list of hybrid * runbook workers. * @member {object} [credential] Sets the credential of a worker group. * @member {string} [credential.name] Gets or sets the name of the * credential. */ constructor() { } /** * Defines the metadata of HybridRunbookWorkerGroup * * @returns {object} metadata of HybridRunbookWorkerGroup * */ mapper() { return { required: false, serializedName: 'HybridRunbookWorkerGroup', type: { name: 'Composite', className: 'HybridRunbookWorkerGroup', modelProperties: { id: { required: false, serializedName: 'id', type: { name: 'String' } }, name: { required: false, serializedName: 'name', type: { name: 'String' } }, hybridRunbookWorkers: { required: false, serializedName: 'hybridRunbookWorkers', type: { name: 'Sequence', element: { required: false, serializedName: 'HybridRunbookWorkerElementType', type: { name: 'Composite', className: 'HybridRunbookWorker' } } } }, credential: { required: false, serializedName: 'credential', type: { name: 'Composite', className: 'RunAsCredentialAssociationProperty' } } } } }; } }
JavaScript
class HttpService { /** * Send HTTP GET request * @param {string} method HTTP request method (GET, POST, PUT etc) * @param {string} url URL for GET request * @param {boolean} async Asynchronous request * @param {string} data Data to be sent * @return {Promise} http response wrapped in Promise */ static request(method, url, async = true, data = '') { return new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); xhr.open(method, url, async); // 3d argument true-async, false-sync xhr.onload = (event) => { const resp = xhr.responseText; // request body const result = JSON.parse(resp); resolve(result); }; xhr.onerror = (event) => { const resp = xhr.responseText; // request body const result = JSON.parse(resp); reject({message: result}); }; xhr.send(data); }); } }
JavaScript
class Input extends Base { get [inputDelegate]() { return this.inner; } [render](/** @type {ChangedFlags} */ changed) { super[render](changed); if (this[firstRender]) { // The following jsDoc comment doesn't directly apply to the statement which // follows, but is placed there because the comment has to go somewhere to // be visible to jsDoc, and the statement is at tangentially related. /** * Raised when the user changes the element's text content. * * This is the standard `input` event; the component does not do any work to * raise it. It is documented here to let people know it is available to * detect when the user edits the content. * * @event input */ this[ids].inner.addEventListener("input", () => { this[raiseChangeEvents] = true; // Invoke the value setter to fix up selectionStart/selectionEnd too. this.value = /** @type {any} */ (this.inner).value; this[raiseChangeEvents] = false; }); this.setAttribute("role", "none"); } } get [template]() { const result = super[template]; result.content.append(fragmentFrom.html` <style> [part~="inner"] { font: inherit; outline: none; text-align: inherit; } </style> `); return result; } }
JavaScript
class RequirementsBazaarWidget extends LitElement { render() { return html` <style> .separator { border-top: thin solid #e1e1e1; } .actionButton { color: #1E90FF } .actionButton:hover { color: #3b5fcc; } </style> <div id="main" style="margin-left: 0.5em; margin-right: 0.5em"> <h3 style="margin-top: 0.5em; margin-bottom: 0.5em">Requirements Bazaar</h3> <div id="requirements-list-container"> <p style="margin-top: 0.5em">This widget is connected to <span id="project-link"></span>.</p> <div id="requirements-list" class="col s12"> </div> </div> <div id="not-connected" style="display: none"> <p style="margin-top: 0.5em">This component is not connected to any category in the Requirements Bazaar.</p> </div> </div> `; } static get properties() { return { client: { type: Object }, selectedProjectId: { type: Number }, selectedCategoryId: { type: Number }, localStorageKey: { type: String }, refreshRequirementsIntervalHandle: { type: Object }, currentlyOpenedRequirementId: { type: Number } }; } constructor() { super(); this.localStorageKey = "requirements-bazaar-widget"; const iwcCallback = function (intent) { console.log(intent); }; this.client = new Las2peerWidgetLibrary(Static.ReqBazBackend, iwcCallback, '*'); this.requestUpdate().then(_ => { this.loadConnectedProject(); if (this.selectedProjectId != -1 && this.selectedCategoryId != -1) { this.onProjectConnected(); } else { this.onProjectDisconnected(); } }); } /** * Loads the information about the Requirements Bazaar category which is * connected to the CAE. This information gets stored to localStorage * when the user selects a component in the project-management. */ loadConnectedProject() { const storageEntryString = localStorage.getItem(this.localStorageKey); if (storageEntryString) { let storageEntry = JSON.parse(storageEntryString); storageEntry = storageEntry[localStorage.getItem("versionedModelId")]; this.selectedProjectId = storageEntry.selectedProjectId; this.selectedCategoryId = storageEntry.selectedCategoryId; } } /** * Gets called when the Requirements Bazaar category stored in * localStorage could be loaded successfully. */ onProjectConnected() { this.getRequirementsListContainerElement().style.removeProperty("display"); this.getProjectLinkElement().innerHTML = `<a href="${Static.ReqBazFrontend}/projects/${this.selectedProjectId}/categories/${this.selectedCategoryId}" target="_blank">this category</a>`; this.refreshRequirements(); this.refreshRequirementsIntervalHandle = setInterval(this.refreshRequirements.bind(this), 10000); } onProjectDisconnected() { this.getRequirementsListContainerElement().style.setProperty("display", "none"); this.getProjectLinkElement().innerHTML = ""; clearInterval(this.refreshRequirementsIntervalHandle); this.getNotConnectedElement().style.removeProperty("display"); } /** * Reloads the requirements by sending a request to the * Requirements Bazaar API. */ refreshRequirements() { console.log("refreshRequirements called"); if (this.selectedProjectId && this.selectedCategoryId) { this.client.sendRequest("GET", this.addAccessToken("categories/" + encodeURIComponent(this.selectedCategoryId) + "/requirements"), "", "application/json", {}, false, function (data, type) { this.renderRequirements(data); }.bind(this), function(error) { this.onProjectDisconnected(); }.bind(this)); } } renderRequirements(requirements) { console.log("render requirements called"); const requirementsList = this.getRequirementsListElement(); while(requirementsList.firstChild) requirementsList.removeChild(requirementsList.firstChild); requirements.forEach(function (requirement) { requirementsList.appendChild(this.renderRequirement(requirement)); }.bind(this)); } renderRequirement(requirement) { const requirementHTML = document.createElement("div"); requirementHTML.style.setProperty("margin-bottom", "6px"); const separator = document.createElement("div"); separator.setAttribute("class", "separator"); requirementHTML.appendChild(separator); /* * Name of requirement. */ const requirementName = document.createElement("p"); requirementName.style.setProperty("font-weight", "bold"); requirementName.style.setProperty("margin-bottom", "0"); requirementName.innerText = requirement.name; requirementHTML.appendChild(requirementName); /* * Created by */ const createdBy = document.createElement("p"); createdBy.style.setProperty("margin-top", "2px"); createdBy.style.setProperty("margin-bottom", "0"); createdBy.style.setProperty("color", "#838383"); createdBy.innerText = "Created by " + requirement.creator.userName; requirementHTML.appendChild(createdBy); /* * Requirement description */ const requirementDescription = document.createElement("p"); requirementDescription.style.setProperty("margin-top", "2px"); requirementDescription.style.setProperty("margin-bottom", "4px"); requirementDescription.innerText = requirement.description; requirementHTML.appendChild(requirementDescription); /* * Button "View" */ const viewButton = document.createElement("a"); viewButton.setAttribute("class", "actionButton"); viewButton.innerText = "View"; viewButton.addEventListener("click", function() { const url = Static.ReqBazFrontend + "/projects/" + this.selectedProjectId + "/categories/" + this.selectedCategoryId + "/requirements/" + requirement.id; window.open(url); }.bind(this)); /* * Button "Done/Reopen" */ const actionButton = document.createElement("a"); actionButton.setAttribute("class", "actionButton"); if(this.isAnonymous()) { actionButton.setAttribute("disabled", "true"); } actionButton.setAttribute("data-requirement-id", requirement.id); const requirementId = requirement.id; let method; if (Object.keys(requirement).includes("realized")) { actionButton.innerText = "Reopen"; method = "DELETE"; } else { actionButton.innerText = "Done"; method = "POST"; } // click listener for "done"/"reopen" button actionButton.addEventListener("click", function() { this.client.sendRequest(method, this.addAccessToken("requirements/" + encodeURIComponent(requirementId) + "/realized"), "", "application/json", {}, false, function (data, type) { this.refreshRequirements(); }.bind(this), console.error) }.bind(this)); actionButton.style.setProperty("margin-left", "0.5em"); /* * Div for buttons */ const divButtons = document.createElement("div"); divButtons.style.setProperty("display", "flex"); divButtons.appendChild(viewButton); divButtons.appendChild(actionButton); requirementHTML.appendChild(divButtons); return requirementHTML; /*return `<li data-requirement-id="${requirement.id}" ${this.currentlyOpenedRequirementId == requirement.id ? 'class="active"' : ''}> <div class="collapsible-header" style="font-weight: bold">${requirement.name}</div> <div class="collapsible-body" style="padding-left: 0; padding-right: 0;"> <p style="margin-left: 24px;margin-right: 24px; margin-bottom: 24px">${requirement.description}</p> <div class="" style="margin-bottom: 0; border-top: 1px solid rgba(160,160,160,0.2); padding-top: 16px;"> <a class="waves-effect waves-teal btn-flat teal-text done" target="_blank" href="${Static.ReqBazFrontend}/projects/${this.selectedProjectId}/categories/${this.selectedCategoryId}/requirements/${requirement.id}" >View</a> ${actionButton} </div> </div> </li>`;*/ } isAnonymous() { return !Auth.isAccessTokenAvailable(); } addAccessToken(url) { if (this.isAnonymous()) { return url; } if (url.indexOf("\?") > 0) { url += "&access_token=" + localStorage["access_token"]; } else { url += "?access_token=" + localStorage["access_token"]; } return url; } clearIntervals() { clearInterval(this.refreshRequirementsIntervalHandle); } getNotConnectedElement() { return this.shadowRoot.getElementById("not-connected"); } getProjectLinkElement() { return this.shadowRoot.getElementById("project-link"); } getRequirementsListElement() { return this.shadowRoot.getElementById("requirements-list"); } getRequirementsListContainerElement() { return this.shadowRoot.getElementById("requirements-list-container"); } }
JavaScript
class BookList extends Component { renderList() { return this.props.books.map((book) => { return ( <li key={book.title} onClick={() => this.props.selectBook(book)} className="list-group-item"> {book.title} </li> ); }) } render() { return ( <ul className="list-group col-sm-4"> {this.renderList()} </ul> ); } }
JavaScript
class Annotator { // API: create(fragment), update(fragments), delete(fragment), drop(graph) constructor(app) { this[userId] = app.getUser() this[urn] = app.getUrn() this[anchor] = app.anchor this[model] = app.model; this[applicator] = app.applicator; this[history] = app.history; // todo: this is part of the base module this.modal = $('<div id="edit_modal" class="modal fade in" style="display: none; "><div class="well"><div class="modal-header"><a class="close" data-dismiss="modal">×</a><h3>Annotation Editor</h3></div><div class="modal-body"></div><div class="modal-footer"><button id="btn-apply" type="button" class="btn btn-primary" data-dismiss="modal" disabled title="Apply changes to text.">Apply</button></div></div>') app.anchor.append(this.modal) app.anchor.mouseup((e) => { // Don't use selection inside #global-view if ($(e.target).closest('#global-view').length) return // If selection exists, remove it var pos = $('#popover-selection') if (pos) { pos.popover('destroy') pos.replaceWith(pos.text()) } var selection = document.getSelection(); // replace starter with if (selection && !selection.isCollapsed && this.modal.css('display')==='none') { // add selector to modal or button var selector = OA.create("http://www.w3.org/ns/oa#TextQuoteSelector")(app.anchor,selection); // modal.update({},selector) var span = document.createElement('span') span.setAttribute('id','popover-selection') span.setAttribute('data-annotations','{}') span.setAttribute('data-selector',JSON.stringify(selector)) wrapRangeText(span,selection.getRangeAt(0)) span = $('#popover-selection') span.popover({ container:"body", html:"true", trigger: "manual", placement: "auto top", title: selector.exact, content: "<div class='popover-footer'/>" }) span.popover('show') } }) } /** * DROP: delete entire annotations including metadata * Takes the ids in list.drop and * @param graphs Object where graphs.triples (Array[Object]) is a list of GSPOs to delete and graphs.ids (Array[String]) is the list of annotation ids to be cleared */ drop(graphs) { this[model].defaultDataset = this[model].defaultDataset.filter((ds) => !graphs.indexOf(ds)+1) this[model].namedDataset = this[model].namedDataset.filter((ds) => !graphs.indexOf(ds)+1) return this[model].execute(graphs.map((uri) => `DROP GRAPH <${uri}>`)) } /** * * @param deletions () is the list */ delete (deletions) { return _.flatten(deletions || []).length ? this[model].execute(SPARQL.bindingsToDelete(_.flatten(deletions).map((gspo) => gspo.g.value ? gspo : SPARQL.gspoToBinding(gspo)))) : [] } /** * * @param deletions * @param insertions */ update(deletions, insertions, graph) { // todo: remove old title, add new title return this[model].execute(_.flatten([ SPARQL.bindingsToDelete(_.flatten(deletions).map((gspo) => gspo.g.value ? gspo : SPARQL.gspoToBinding(gspo))), SPARQL.bindingsToInsert(_.flatten(insertions.concat( // filter for graphs, map to graphid, get uniq _.uniq(_.flatten(insertions).map((i) => i.g.value || i.g)).map((annotationId) => _.concat(OA.makeAnnotatedAt(annotationId, graph || defaultGraph), OA.makeAnnotatedBy(annotationId, graph || defaultGraph, this[userId]))) )).map((gspo) => gspo.g.value ? gspo : SPARQL.gspoToBinding(gspo))) ])) } /** * * @param list */ create (annotationId, bindings, graph) { var result = $.Deferred().resolve([]).promise() if (bindings.length) { var selectorId = _.find(bindings, (binding) => binding.p.value === "http://www.w3.org/ns/oa#exact").s.value var targetId = annotationId + "#target-" + Utils.hash(JSON.stringify(selectorId)).slice(0, 4) // planned: make independent of selector type var oa = OA.makeCore(annotationId, graph || defaultGraph) var target = OA.makeTarget(annotationId, graph || defaultGraph, targetId, selectorId, this[urn]) var date = OA.makeAnnotatedAt(annotationId, graph || defaultGraph) var user = OA.makeAnnotatedBy(annotationId, graph || defaultGraph, this[userId]) this[model].defaultDataset.push(annotationId) this[model].namedDataset.push(annotationId) if (!(this[model].defaultDataset.indexOf(graph || defaultGraph)+1)) { this[model].defaultDataset.push(graph || defaultGraph) this[model].namedDataset.push(graph || defaultGraph) } var insert = SPARQL.bindingsToInsert(_.flatten([oa, date, user, target, bindings]).map((gspo) => gspo.g.value ? gspo : SPARQL.gspoToBinding(gspo))) result = this[model].execute(insert) } return result } apply (resolved) { // check if all successful (what about drop?) // if success, map to sparql and add sparql to history // else reset model this[history].add(resolved.map((r) => r.sparql)) // this.history.commit() this[applicator].reset() } }
JavaScript
class MainApp { constructor() { // 主窗口 // this.splashWindow = null; logger.info('App start!'); this.mainWindow = null; // 启动闪屏 this.splashWindow = null; this.settingsWindow = null; this.tray = null; } createSplashWindow() { this.splashWindow = new SplashWindow(); gVars.window.splashWindow = this.splashWindow; logger.info('App created splash window!'); this.splashWindow.show(); // console.log('create splash:'); // console.dir(gVars); } createMainUtilsWindow() { this.mainWindow = new MainWindow(); gVars.window.mainWindow = this.mainWindow; logger.trace('App created main window!'); // console.log('create main:'); // console.dir(gVars); } initApp() { logger.info(`locale:${app.getLocale()}`) logger.info(`name:${app.getName()}`) // Electron 会在初始化后并准备 // 创建浏览器窗口时,调用这个函数。 // 部分 API 在 ready 事件触发后才能使用。 app.on('ready', () => { logger.trace('App ready to create windows!'); this.createSplashWindow(); this.createMainUtilsWindow(); // this.createTray(); }); /** * 当应用被激活时触发,常用于点击应用的 dock 图标的时候。 OS X */ app.on('activate', () => { logger.info('App activate!'); if (this.window == null) { this.createMainUtilsWindow(); } else { this.window.show(); } }); app.on('before-quit', () => { logger.info('before-quit'); }); // // app.on('web-contents-created', () => { // logger.info('web-contents-created'); // }); // app.on('browser-window-created', () => { // logger.info('browser-window-created'); // }); // 当全部窗口关闭时退出。 app.on('window-all-closed', () => { logger.info('App all window closed, App Existed'); // On OS X it is common for applications and their menu bar // to stay active until the user quits explicitly with Cmd + Q // 判断当前操作系统是否是window系统,因为这个事件只作用在window系统中 if (process.platform !== 'darwin') { app.quit(); } }); } initIPC() { ipcMain.on('iamready', (event, args) => { console.dir(event); console.dir(args); }); } init() { this.initApp(); this.initIPC(); } }
JavaScript
class Landing extends Component { render() { return ( <div className="background"> <Container style={containerStyle}> <Row className="justify-content-center" style={padding}> <Col> <Navbar /> </Col> </Row> <Row className="justify-content-center"> <Col md={"auto"}> <Link to="/register"> <button style={buttonStyle} type="submit" className="btn btn-large waves-effect waves-light hoverable blue accent-3 white-text" > Register </button> </Link> </Col> <Col md={"auto"}> <Link to="/login"> <button style={buttonStyle} type="submit" className="btn btn-large waves-effect waves-light hoverable white accent-3 black-text" > Login </button> </Link> </Col> </Row> </Container> </div> ); } }
JavaScript
class AppRootComponent extends React.Component { constructor(props) { super(props); this.state = { isReady: false }; } componentDidMount() { this.props.readyToRender.then(() => { this.setState({ isReady: true }); }); } render() { const props = this.props; const state = this.state; if (!state.isReady) { return <div style={ { position: 'absolute', top: '10%', left: '50%' } }> <div> Initializing ... </div> </div>; } return <Provider store={ props.store }> <Router> <Switch> <Route exact path={ `${routes.login}` } component={ LoginContainer } /> <Route exact path={ `${routes.logout}` } component={ LogoutContainer } /> <ProtectedRouteContainer path={ `${routes.home}` } component={ AppComponent } /> <Redirect from='/' to={ `${routes.home}` } /> <Route path="*" component={ NotFoundComponent } /> </Switch> </Router> </Provider>; } }
JavaScript
class TodoApp extends Component { constructor(props) { super(props); this.state = {}; autoBind(this); } render(){ const { todos, actions } = this.props; return( <div className="todoapp"> <h1>Todos</h1> <Header addTodo={actions.addTodo}/> <Body todos={todos} actions={actions}/> </div> ); } }
JavaScript
class IssueSize { /** * Constructs a new <code>IssueSize</code>. * Issue Size Data Items for a Fixed Income security. * @alias module:model/IssueSize * @param requestId {String} Security identifier used in the request. * @param fsymId {String} FactSet Permanent Security Identifier. */ constructor(requestId, fsymId) { IssueSize.initialize(this, requestId, fsymId); } /** * Initializes the fields of this object. * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). * Only for internal use. */ static initialize(obj, requestId, fsymId) { obj['requestId'] = requestId; obj['fsymId'] = fsymId; } /** * Constructs a <code>IssueSize</code> from a plain JavaScript object, optionally creating a new instance. * Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not. * @param {Object} data The plain JavaScript object bearing properties of interest. * @param {module:model/IssueSize} obj Optional instance to populate. * @return {module:model/IssueSize} The populated <code>IssueSize</code> instance. */ static constructFromObject(data, obj) { if (data) { obj = obj || new IssueSize(); if (data.hasOwnProperty('requestId')) { obj['requestId'] = ApiClient.convertToType(data['requestId'], 'String'); } if (data.hasOwnProperty('fsymId')) { obj['fsymId'] = ApiClient.convertToType(data['fsymId'], 'String'); } if (data.hasOwnProperty('outAmtEffDate')) { obj['outAmtEffDate'] = ApiClient.convertToType(data['outAmtEffDate'], 'Date'); } if (data.hasOwnProperty('outAmtCurrency')) { obj['outAmtCurrency'] = ApiClient.convertToType(data['outAmtCurrency'], 'String'); } if (data.hasOwnProperty('outAmt')) { obj['outAmt'] = ApiClient.convertToType(data['outAmt'], 'Number'); } if (data.hasOwnProperty('outAmtChange')) { obj['outAmtChange'] = ApiClient.convertToType(data['outAmtChange'], 'Number'); } if (data.hasOwnProperty('outAmtChangePrice')) { obj['outAmtChangePrice'] = ApiClient.convertToType(data['outAmtChangePrice'], 'Number'); } if (data.hasOwnProperty('outAmtChangeType')) { obj['outAmtChangeType'] = ApiClient.convertToType(data['outAmtChangeType'], 'String'); } } return obj; } }
JavaScript
class KunlunError extends Error{ constructor(code, message){ super(message); this._name = 'KunlunError'; this._code = code; } get name(){ return this._name; } get code(){ return this._code; } }
JavaScript
class TwitterBot { /** * Constructor. * * @param {App} app The main application */ constructor(app) { this.app = app; app.emitter.on('dbready', () => { this.login(); }); } /** * Log in to the Twitter API. */ login() { if (!this.app.settings.twitter_consumer_key || !this.app.settings.twitter_consumer_secret || !this.app.settings.twitter_access_token_key || !this.app.settings.twitter_access_token_secret) { this.client = undefined; return; } this.client = new Twitter({ consumer_key: this.app.settings.twitter_consumer_key, consumer_secret: this.app.settings.twitter_consumer_secret, access_token_key: this.app.settings.twitter_access_token_key, access_token_secret: this.app.settings.twitter_access_token_secret }); } /** * Set whether the Twitch channel is live. * * @param {boolean} live The channel is live */ setLive(live) { if (!this.client) { return; } this.client.get('account/verify_credentials') .then((res) => { const add = '🔴【LIVE】 '; const name = res.name.replace(add, ''); let description, savedDescription; if (!live && this.app.settings.twitter_bio) { description = this.app.settings.twitter_bio; savedDescription = null; } else if (live && this.app.settings.twitter_live_message) { description = this.app.settings.twitter_live_message.replace(/\${name}/g, this.app.config.users.host).replace(/\${game}/g, this.app.api.game); savedDescription = res.description; } else { return; } this.client.post('account/update_profile', { name: live ? add + name : name, description: description }) .then(() => { console.log('updated Twitter name'); this.app.settings.twitter_bio = savedDescription; this.app.saveSettings(); }) .catch((err) => { console.warn('could not update Twitter profile'); console.log(err); }); }) .catch((err) => { console.warn('failed to get Twitter account'); console.log(err); }); } }
JavaScript
class NgControl extends AbstractControlDirective { constructor() { super(...arguments); /** * @description * The parent form for the control. * * @internal */ this._parent = null; /** * @description * The name for the control */ this.name = null; /** * @description * The value accessor for the control */ this.valueAccessor = null; } }
JavaScript
class StateContainer extends StaticClass { /** * LocalStorage key prefix * @returns {String} - prefix * @constant */ static get prefix () { return 'oauth_state_'; } /** * Generate and store a state that can be checked at a later point * @returns {string} - state */ static generate () { const uuid = Uuid.uuid4(); const key = StateContainer.prefix + uuid; StorageManager.best.set(key, Date.now()); return uuid; } /** * Validate a state * @param {String} state - state to validate * @param {Boolean} purge - remove from state db after validation * @returns {Boolean} - if the state is valid */ static validate (state, purge = true) { const storage = StorageManager.best; const key = StateContainer.prefix + state; const found = typeof storage.get(key) !== 'undefined'; if (purge && found) { storage.remove(key); } return found; } /** * Remove all states from the state db */ static clean () { const tokens = Object.keys(this.list()); for (const token of tokens) { StorageManager.best.remove(StateContainer.prefix + token); } } /** * Get states with their corresponding state db key * @returns {Object<String, String>} - List of stored states */ static list () { const storage = StorageManager.best; return storage .keys() .filter(x => x.startsWith(StateContainer.prefix)) .map(x => x.replace(StateContainer.prefix, '')) .reduce((out, key) => { out[key] = storage.get(key); return out; }, {}); } }
JavaScript
class OptionsDisplay extends Component { render () { // Temporary obect to show the structure of OptionsDisplay const options = this.props.options.map((option) => { return { name: option.name, selected: option.selected, values: option.values } }) const selectedOptions = options.map((option) => { return ( <div className="SelectedOption" key={option.name}> <span className="SelectedOption-name">{option.name}: </span> <span className="SelectedOption-selected">{option.selected}</span> </div> ) }) return ( <div className="OptionsDisplay"> <h4>Options</h4> {selectedOptions} </div> ) } }
JavaScript
class UI { resetForm() { let form = document.querySelector(".needs-validation"); form.classList.remove("was-validated"); form.reset(); document.querySelector("#product").focus(); } addContent() { const name = document.querySelector("#product").value; const price = document.querySelector("#price").value; const description = document.querySelector("#description").value; let newContent = new TextBlock(name, price, description); const tableOfContent = document.querySelector(".table-of-content"); let content = document.createElement("div"); content.classList.add("mw-100"); content.innerHTML = `<div class="container-all-content text-center p-4 mb-2 w-100 border"> <div class="container-button col-md-10 m-md-auto my-md-0 row"> <p class="product-name col-6"> <strong>Product Name = </strong> ${newContent.name} </p> <p class="product-price col-6"> <strong>Product Price = </strong> $ ${newContent.price} </p> <p class="product-description mw-50 col-12 text-start"> ${newContent.description} </p> </div> <input type="button" value="Eliminar" class="btn-remove bg-danger btn" /> </div>`; tableOfContent.appendChild(content); } removeContent() { const button = document.querySelectorAll(".btn-remove"); button.forEach((e) => { e.addEventListener("click", (e) => { e.target.parentElement.parentElement.remove(); }); }); } }
JavaScript
class DB { // Keeping a reference to the connection on the class in case we need it later constructor(connection) { this.connection = connection; } // This is the way to call all the employees from the db with roles and departments to display their roles, salaries, departments, and managers findAllEmp() { return this.connection.query( "SELECT employee.id, employee.first_name, employee.last_name, role.title, department.name AS department, role.salary, CONCAT(manager.first_name, ' ', manager.last_name) AS manager FROM employee LEFT JOIN role on employee.role_id = role.id LEFT JOIN department on role.department_id = department.id LEFT JOIN employee manager on manager.id = employee.manager_id;" ); } // Find all departments, join with employees and roles and sum up utilized department budget findAllDepartments() { return this.connection.query( "SELECT department.id, department.name, SUM(role.salary) AS utilized_budget FROM department LEFT JOIN role ON role.department_id = department.id LEFT JOIN employee ON employee.role_id = role.id GROUP BY department.id, department.name" ); } // Finds all employees from the db, and it joins with roles so that it display role titles findAllEmployeesByDepartment(departmentId) { return this.connection.query( "SELECT employee.id, employee.first_name, employee.last_name, role.title FROM employee LEFT JOIN role on employee.role_id = role.id LEFT JOIN department department on role.department_id = department.id WHERE department.id = ?;", departmentId ); } // This will organize employees by their assigned manager, join with departments and roles so that it can display titles and department names findAllEmpByManager(managerId) { return this.connection.query( "SELECT employee.id, employee.first_name, employee.last_name, department.name AS department, role.title FROM employee LEFT JOIN role on role.id = employee.role_id LEFT JOIN department ON department.id = role.department_id WHERE manager_id = ?;", managerId ); } // adds a new employee addEmployee(employee) { return this.connection.query( "INSERT INTO employee SET ?", employee ); } // This will find all the roles thats in the db, join with departments so that it can display the department name findAllRoles() { return this.connection.query( "SELECT role.id, role.title, department.name AS department, role.salary FROM role LEFT JOIN department on role.department_id = department.id;" ); } // This will remove a employee removeEmp(employeeId) { return this.connection.query( "DELETE FROM employee WHERE id = ?", employeeId ); } // This will update the employee's role updateEmpRole(employeeId, roleId) { return this.connection.query( "UPDATE employee SET role_id = ? WHERE id = ?", [roleId, employeeId] ); } // This change the assigned employee's manager updateEmpManager(employeeId, managerId) { return this.connection.query( "UPDATE employee SET manager_id = ? WHERE id = ?", [managerId, employeeId] ); } // This will find all the managers findAllManagers(employeeId) { return this.connection.query( "SELECT id, first_name, last_name FROM employee WHERE id != ?", employeeId ); } // This will add a new role addNewRole(role) { return this.connection.query("INSERT INTO role SET ?", role); } // This will remove a role rmRole(roleId) { return this.connection.query("DELETE FROM role WHERE id = ?", roleId); } // This will add a new department addDpt(department) { return this.connection.query("INSERT INTO department SET ?", department); } // This will remove a department rmDepartment(departmentId) { return this.connection.query( "DELETE FROM department WHERE id = ?", departmentId ); } }
JavaScript
class Footer extends Component { render () { return ( <footer> <span id="footerCredit">Made by Nicolas Crumrine</span> <div id="footer" className="text-center"> <a className="footerLink" href="http://crumrinecoder.com/" rel="noopener noreferrer"target="_blank" ><i className="fas fa-briefcase"></i></a> <a className="footerLink" href="https://github.com/CrumrineCoder" rel="noopener noreferrer" target="_blank" ><i className="fab fa-github"></i></a> <a className="footerLink" href=" https://www.linkedin.com/in/nicolas-crumrine-50899b120/" rel="noopener noreferrer" target="_blank" ><i className="fab fa-linkedin-in"></i></a> <a className="footerLink" href="mailto:[email protected]" rel="noopener noreferrer" target="_blank" ><i className="fas fa-envelope"></i></a> </div> </footer> ) } }
JavaScript
class OrderRequests extends Component { constructor() { super() this.state = { tab1: "col-12 col-lg-4 col-md-4 text-center order-req-tab-active", tab2: "col-12 col-lg-4 col-md-4 text-center", tab3: "col-12 col-lg-4 col-md-4 text-center", tab1Content: true, tab2Content: false, tab3Content: false, } } async componentDidMount() { this.props.order_request(); // const { user } = await this.props // console.log("Did Mount => ", user) // this.fetchOrderRequests() // if (userDetails.isRestaurant) { // // this.props.history.push('/restaurants') // console.log("Didmount userDetails.isRestaurant => ", userDetails.isRestaurant) // } } static getDerivedStateFromProps(props) { const { user } = props return { userDetails: user, } } handleTabs(e) { if (e === "tab1") { this.setState({ tab1: "col-12 col-lg-4 col-md-4 text-center order-req-tab-active", tab2: "col-12 col-lg-4 col-md-4 text-center", tab3: "col-12 col-lg-4 col-md-4 text-center", tab1Content: true, tab2Content: false, tab3Content: false, }) } else if (e === "tab2") { this.setState({ tab1: "col-12 col-lg-4 col-md-4 text-center", tab2: "col-12 col-lg-4 col-md-4 text-center order-req-tab-active", tab3: "col-12 col-lg-4 col-md-4 text-center", tab1Content: false, tab2Content: true, tab3Content: false, }) } else if (e === "tab3") { this.setState({ tab1: "col-12 col-lg-4 col-md-4 text-center", tab2: "col-12 col-lg-4 col-md-4 text-center", tab3: "col-12 col-lg-4 col-md-4 text-center order-req-tab-active", tab1Content: false, tab2Content: false, tab3Content: true, }) } } handleSendToInProgressBtn(userUid, orderId) { const { userDetails } = this.state; const restaurantUid = userDetails.userUid firebase.firestore().collection('users').doc(restaurantUid).collection('orderRequest').doc(orderId).update({ status: "IN PROGRESS", }).then(() => { // console.log("First Seccussfully send to IN PROGRESS") firebase.firestore().collection('users').doc(userUid).collection('myOrder').doc(orderId).update({ status: "IN PROGRESS", }).then(()=>{ // console.log("Second Seccussfully send to IN PROGRESS") }) }) } handleSendToDeliveredBtn(userUid, orderId) { const { userDetails } = this.state; const restaurantUid = userDetails.userUid firebase.firestore().collection('users').doc(restaurantUid).collection('orderRequest').doc(orderId).update({ status: "DELIVERED", }).then(() => { console.log("First Seccussfully send to IN PROGRESS") firebase.firestore().collection('users').doc(userUid).collection('myOrder').doc(orderId).update({ status: "DELIVERED", }).then(()=>{ console.log("Second Seccussfully send to IN PROGRESS") }) }) } _renderPendingOrderRequest() { const { orderRequest } = this.props; // console.log(orderRequest) if (orderRequest) { return Object.keys(orderRequest).map((val) => { const userUid = orderRequest[val].userUid; const orderId = orderRequest[val].id; if (orderRequest[val].status === "PENDING") { return ( <div className="container border-bottom pb-2 px-lg-0 px-md-0 mb-4" key={orderRequest[val].id}> <div className="row mb-3"> <div className="col-lg-6 col-md-6 col-12"> <h5 className="">{orderRequest[val].userName}</h5> </div> <div className="col-lg-6 col-md-6 col-12 text-lg-right text-md-right text-center "> <span className="text-uppercase text-danger order-req-status">{orderRequest[val].status}</span> </div> </div> { Object.keys(orderRequest[val].itemsList).map((val2) => { // console.log(orderRequest[val].itemsList[val2]) // console.log(val2) return ( <div className="row mb-3" key={val2}> <div className="col-lg-2 col-md-3 col-8 offset-2 offset-lg-0 offset-md-0 px-0 mb-3 text-center"> <img style={{ width: "70px", height: "70px" }} alt="Natural Healthy Food" src={orderRequest[val].itemsList[val2].itemImageUrl} /> </div> <div className="col-lg-7 col-md-6 col-sm-12 px-0"> <h6 className="">{orderRequest[val].itemsList[val2].itemTitle}</h6> <p className="mb-1"><small>{orderRequest[val].itemsList[val2].itemIngredients}</small></p> </div> <div className="col-lg-3 col-md-3 col-sm-12 px-0 text-right"> <span style={{ fontSize: "14px" }} className="mx-3"><b>RS.{orderRequest[val].itemsList[val2].itemPrice}</b></span> </div> </div> ) }) } <div className="row mb-3 mb-md-0 mb-lg-0"> <div className="col-lg-6 col-md-6 col-12 order-lg-first order-md-first order-last "> <button type="button" onClick={() => this.handleSendToInProgressBtn(userUid, orderId)} className="btn btn-warning btn-sm text-uppercase px-3"><b>Send To In Progress</b></button> </div> <div className="col-lg-6 col-md-6 col-12 text-lg-right text-md-right"> <p><b className="mr-4">Total Price:</b><span style={{ fontSize: '1.1rem' }}>RS.{orderRequest[val].totalPrice}</span></p> </div> </div> </div> ) } }) } } _renderInProgressOrderRequest() { const { orderRequest } = this.props; // console.log(orderRequest) if (orderRequest) { return Object.keys(orderRequest).map((val) => { const userUid = orderRequest[val].userUid; const orderId = orderRequest[val].id; // console.log(orderRequest[val].status === "PENDING") if (orderRequest[val].status === "IN PROGRESS") { return ( <div className="container border-bottom pb-2 px-lg-0 px-md-0 mb-4" key={orderRequest[val].id}> <div className="row mb-3"> <div className="col-lg-6 col-md-6 col-12"> <h5 className="">{orderRequest[val].userName}</h5> </div> <div className="col-lg-6 col-md-6 col-12 text-lg-right text-md-right text-center "> <span className="text-uppercase text-danger order-req-status">{orderRequest[val].status}</span> </div> </div> { Object.keys(orderRequest[val].itemsList).map((val2) => { // console.log(orderRequest[val].itemsList[val2]) // console.log(val2) return ( <div className="row mb-3" key={val2}> <div className="col-lg-2 col-md-3 col-8 offset-2 offset-lg-0 offset-md-0 px-0 mb-3 text-center"> <img style={{ width: "70px", height: "70px" }} alt="Natural Healthy Food" src={orderRequest[val].itemsList[val2].itemImageUrl} /> </div> <div className="col-lg-7 col-md-6 col-sm-12 px-0"> <h6 className="">{orderRequest[val].itemsList[val2].itemTitle}</h6> <p className="mb-1"><small>{orderRequest[val].itemsList[val2].itemIngredients}</small></p> </div> <div className="col-lg-3 col-md-3 col-sm-12 px-0 text-right"> <span style={{ fontSize: "14px" }} className="mx-3"><b>RS.{orderRequest[val].itemsList[val2].itemPrice}</b></span> </div> </div> ) }) } <div className="row mb-3 mb-md-0 mb-lg-0"> <div className="col-lg-6 col-md-6 col-12 order-lg-first order-md-first order-last "> <button type="button" onClick={()=>{this.handleSendToDeliveredBtn(userUid, orderId)}} className="btn btn-warning btn-sm text-uppercase px-3"><b>Send To Delivered</b></button> </div> <div className="col-lg-6 col-md-6 col-12 text-lg-right text-md-right"> <p><b className="mr-4">Total Price:</b><span style={{ fontSize: '1.1rem' }}>RS.{orderRequest[val].totalPrice}</span></p> </div> </div> </div> ) } }) } } _renderDeliveredOrderRequest() { const { orderRequest } = this.props; // console.log(orderRequest) if (orderRequest) { return Object.keys(orderRequest).map((val) => { // console.log(orderRequest[val].status === "PENDING") if (orderRequest[val].status === "DELIVERED") { return ( <div className="container border-bottom pb-2 px-lg-0 px-md-0 mb-4" key={orderRequest[val].id}> <div className="row mb-3"> <div className="col-lg-6 col-md-6 col-12"> <h5 className="">{orderRequest[val].userName}</h5> </div> <div className="col-lg-6 col-md-6 col-12 text-lg-right text-md-right text-center "> <span className="text-uppercase text-success order-req-status">{orderRequest[val].status}</span> </div> </div> { Object.keys(orderRequest[val].itemsList).map((val2) => { // console.log(orderRequest[val].itemsList[val2]) // console.log(val2) return ( <div className="row mb-3" key={val2}> <div className="col-lg-2 col-md-3 col-8 offset-2 offset-lg-0 offset-md-0 px-0 mb-3 text-center"> <img style={{ width: "70px", height: "70px" }} alt="Natural Healthy Food" src={orderRequest[val].itemsList[val2].itemImageUrl} /> </div> <div className="col-lg-7 col-md-6 col-sm-12 px-0"> <h6 className="">{orderRequest[val].itemsList[val2].itemTitle}</h6> <p className="mb-1"><small>{orderRequest[val].itemsList[val2].itemIngredients}</small></p> </div> <div className="col-lg-3 col-md-3 col-sm-12 px-0 text-right"> <span style={{ fontSize: "14px" }} className="mx-3"><b>RS.{orderRequest[val].itemsList[val2].itemPrice}</b></span> </div> </div> ) }) } <div className="row mb-3 mb-md-0 mb-lg-0"> <div className="col-lg-6 col-md-6 col-12 order-lg-first order-md-first order-last "> {/* <button type="button" className="btn btn-warning btn-sm text-uppercase px-3"><b>Send To In Progress</b></button> */} <h6 style={{ fontSize: '15px' }} className="text-success">This order is successfully delivered</h6> </div> <div className="col-lg-6 col-md-6 col-12 text-lg-right text-md-right"> <p><b className="mr-4">Total Price:</b><span style={{ fontSize: '1.1rem' }}>RS.{orderRequest[val].totalPrice}</span></p> </div> </div> </div> ) } }) } } render() { const { tab1, tab2, tab3, tab1Content, tab2Content, tab3Content, userDetails } = this.state; return ( <div> <div className="container-fluid res-details-cont1"> <div className=""> {/* <Navbar history={this.props.history} /> */} <Navbar2 history={this.props.history} /> <div className="container px-0 res-details-cont1-text mx-0"> <div className="container"> { userDetails ? <div className="row"> <div className="col-lg-2 col-md-3 col-6 text-lg-center text-md-center pr-0 mb-2"> <img className="p-2 bg-white rounded text-center" alt="Natural Healthy Food" style={{ width: "60%" }} src={userDetails.userProfileImageUrl} /> </div> <div className="col-lg-10 col-md-9 col-12 pl-lg-0 pl-md-0"> <h1 className="restaurant-title">{userDetails.userName}</h1> <p className="restaurant-text">{userDetails.typeOfFood && userDetails.typeOfFood.join(', ')}</p> </div> </div> : null } </div> </div> </div> </div> <div style={{ background: "#EBEDF3" }} className="container-fluid py-5"> <div className="container"> <div className="row"> <div className="col-lg-10 col-md-10 col-sm-12 offset-lg-1 offset-md-1"> <div className="container"> <div className="row"> <div className={tab1} onClick={() => this.handleTabs("tab1")}> {/* <p className="order-req-tab-text"><FontAwesomeIcon icon="spinner" className="mr-3" />Pending</p>*/} </div> <div className={tab2} onClick={() => this.handleTabs("tab2")}> {/* <p className="order-req-tab-text"><FontAwesomeIcon icon="truck" className="mr-3" />In Progress</p>*/} </div> <div className={tab3} onClick={() => this.handleTabs("tab3")}> {/* <p className="order-req-tab-text"><FontAwesomeIcon icon="tasks" className="mr-3" />Delivered</p>*/} </div> </div> {tab1Content && < div className="row pending-order-section"> <div className="col-12 bg-white p-4"> {this._renderPendingOrderRequest()} </div> </div> } {tab2Content && <div className="row inProgress-order-section"> <div className="col-12 bg-white p-4"> {this._renderInProgressOrderRequest()} </div> </div> } {tab3Content && <div className="row delivered-order-section"> <div className="col-12 bg-white p-4"> {this._renderDeliveredOrderRequest()} </div> </div> } </div> </div> </div> </div> </div> <Footer /> </div > ); } }
JavaScript
class AragoniteVBoxPlugin extends RunnerPlugin { /** * Additional options to add to the Aragonite options. * @return {Object} defaults for the additional options. */ static get defaults() { let opts = {}; opts.exec = "VBoxManage"; opts.port = 5720; opts.prefix = "aragonite-"; opts.machines = []; return opts; } /** * Adds additional fields to Aragonite options and calls {@link Plugin#constructor}. * @param {Aragonite} server the parent Aragonite server. * @param {Object} opts the Aragonite options. * @param {string} [opts.vbox.exec=VBoxManage] the command to execute to communicate with "VBoxManage" * @param {integer} [opts.vbox.port=5730] a port that VirtualBox machines will communicate with * @param {string} [opts.prefix="aragonite-"] a prefix to insert before created VirtualBox machines * @param {Object[]} opts.vbox.machines the machine templates that can be used to test projects * @param {string} opts.vbox.machines[].name a human-readable description of the machine. * @param {string} opts.vbox.machines[].vbox the VirtualBox identifier of the machine. * @param {string} opts.vbox.machines[].snap a VirtualBox snapshot of the given machine to clone * @param {string} opts.vbox.machines[].dist the platform the machine is running, e.g. "OSX", "Windows", "Linux" * @param {string} opts.vbox.machines[].version the OS version, e.g. Ubuntu: "14.04", Windows: "XP", OSX: "10.11" * @param {boolean} opts.vbox.machines[].async if `true`, other environments can run at the same time. * @param {number} opts.vbox.machines[].cost the relative cost to run the machine, to prevent over-usage. If the cost * is greater than the machine's total cost, the machine will be converted to be isolated (non-async). */ constructor(server, opts) { opts.vbox = Object.assign({}, AragoniteVBoxPlugin.defaults, opts.vbox); super(server, opts); this.app = express(); this.http = require("http").Server(this.app); this.io = require("socket.io")(this.http); this.io.on("connection", (socket) => { this.sockets.push(socket); }); this.sockets = []; this.runs = {}; this.app.get("/:mac/archive/", (req, res, next) => { let run = this.runs[req.params.mac]; if(!run || !run.conf) { res.status(404); return res.send("MAC address not found."); } if(!run.conf.archive || !run.conf.archive.path) { res.status(204); return res.send("No archive found."); } res.send(fs.readFileSync(run.conf.archive.path)); }); } /** * Determines what VirtualBox machines should be included in a new Aragonite run. * @param {Object} opts See `opts` in {@link Aragonite#run} * @return {Promise<Environment[]>} resolve an array of {@link Environment} items. */ start(opts) { return new Promise((resolve, reject) => { if(this.http.address()) { return resolve(); } this.http.listen(this.opts.vbox.port, function() { resolve(); }); }) .then(() => { return this.opts.vbox.machines.map((machine) => { return new VBoxEnvironment(this, this.server, this.opts, opts, machine); }); }) .catch((e) => { console.error(e); }); } /** * Stop this runner. * TODO: Stop VirtualBox machines. * @return {Promise} resolves when the runner has fully terminated. */ stop() { return new Promise((resolve, reject) => { if(!this.http || !this.http.close) { return resolve(); } this.http.close(() => { resolve(); }); if(this.sockets) { for(const socket of this.sockets) { socket.disconnect(true); } } }); } }
JavaScript
class ArrayList extends Array { constructor(...args) { // new ArrayList(5, i => i * 2) == [0, 2, 4, 6, 8] if (args.length === 2 && typeof args[0] === "number" && typeof args[1] === "function") super(...buildWithTransform(args[0], args[1])); // new ArrayList([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] else if (args.length === 1 && Array.isArray(args[0])) super(...args[0]); else super(...args); } /** * A call to buildWithTransform that does not require using the constructor. * @param {number} size the size of the new array. * @param {Function} transform the transformator function to be applied to each item. * @return {ArrayList} the newly built ArrayList. */ static iterate(size, transform) { return buildWithTransform(size, transform); } /** * A "safer" ArrayList constructor. Takes out the uncertainty of the Array constructor. * @param {Array} args the items of the new ArrayList. * @return {ArrayList} the newly built ArrayList. */ static of(...args) { const list = new ArrayList(); for (const arg of args) list.push(arg); return list; } /** * Mutates the ArrayList by adding an element at the end. * @param {Array} elements the element(s) to add to the array. * @returns {ArrayList} the original ArrayList. */ add(...elements) { this.push(...elements); return this; } /** * Mutates the ArrayList by removing the elements from it. * @param {Array} elements the element(s) to remove from the array. * @returns {ArrayList} the original ArrayList. */ remove(...elements) { this.forEach((value, index) => { if (elements.length && elements.includes(value)) { this.splice(index, 1); elements.splice(elements.indexOf(value), 1); } ; }); return this; } /** * Mutates the ArrayList, removing elements by index. * @param {number} index the index of the element(s) to remove. * @param {number} [amount] the amount of elements to remove. 1 by default. * @returns {ArrayList} the original ArrayList. */ removeFromIndex(index, amount = 1) { this.splice(index, amount); return this; } /** * See ArrayList#add, but append is non-mutating. * @param elements the element(s) to add to the array. * @returns {ArrayList} a copy of the original ArrayList plus the new elements. */ append(...elements) { const _this = this.copyOf(); _this.push(...elements); return _this; } /** * Removes those elements that are common to both arrays. * @param {Array} elements the elements to remove from the array. * @returns {ArrayList} a copy of the original ArrayList minus the common elements. */ difference(elements) { const copy = this.copyOf(); copy.forEach((value, index) => { if (elements.includes(value)) { copy.splice(index, 1); elements.splice(elements.indexOf(value), 1); } ; }); return copy; } /** * If no arguments are given, it checks if there is at least one item in the ArrayList. * With arguments, identical to [Array.some()](https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Global_Objects/Array/some). * @param {Function} [predicate] the condition to be checked for each item. * @returns {boolean} `true` if any element fulfills the condition or if there is at least one element in the array. */ any(predicate = _ => true) { return this.some(predicate); } /** * Returns a map that holds the values of this ArrayList as key and their respective * selected properties as value. * @param prop the property to associate the value with. */ associateWith(prop) { if (typeof prop != "string") throw new SyntaxError(`Prop is not a string`); const _this = new Set(this); const map = new Map(); for (const x of _this) { const aux = x; if (aux[prop]) map.set(x, aux[prop]); else throw new SyntaxError(`Not all elements in array have the ${prop} property`); } return map; } /** * If elements are addable, returns the sum of them divided by their length. * Otherwise, returns NaN. */ average() { return this.sum() / this.length; } /** * Splits an ArrayList into chunks of a custom size. Non-mutating. * @param {number} size must be a positive, non-zero number. * @returns {ArrayList} the new chunked ArrayList. */ chunked(size) { if (size == null || size < 1) return new ArrayList(); const arr = new ArrayList(); for (let i = 0; i < this.length; i += size) arr.push(this.slice(i, i + size)); return arr; } /** * Returns true if the element is found in the array. Alias for Array.prototype.includes if it were to be * used with one argument only. * @param {*} value the element to look for. * @returns {boolean} `true if the element is found, `false` if not. */ contains(value) { return this.includes(value); } /** * Checks if all elements in the specified Array or ArrayList are contained in this ArrayList. * @param {Array} array the Array / ArrayList to compare against. * @returns {boolean} `true` if all elements exist, `false` instead. */ containsAll(array) { return array.every(i => this.includes(i)); } /** * Returns a copy of the original ArrayList. */ copyOf() { return new ArrayList(this); } /** * Returns a copy of a range of the original ArrayList. * @param {number} start inclusive. * @param {number} [end] non-inclusive. */ copyOfRange(start, end = this.length - 1) { return this.slice(start, end); } /** * If no predicate is provided, it returns the real amount of elements in the ArrayList, as opposed to length. * If a predicate is provided, it returns the amount of elements that fulfill it. * @param {Function} [predicate] the condition to be checked for each item. */ count(predicate = _ => true) { return this.filter(predicate).length; } /** * If n is positive, returns a new ArrayList where the first n elements have been removed. * If n is negative, returns a new ArrayList where the all items except the last n have been removed. * @param {number} n the amount of elements to drop. */ drop(n) { return this.slice(n); } /** * Returns a copy of the original ArrayList where the first n elements that fulfilled the * predicate have been removed. * @param {Function} predicate the condition to be checked for each item. */ dropWhile(predicate) { for (const [index, value] of this.entries()) if (!predicate(value)) return this.slice(index); return this; } /** * Groups elements of this ArrayList by key and counts elements in each group. * @returns {Map} Map containing the elements as key and the count as value. */ eachCount() { const count = new Map(); this.forEach(value => { if (!count.has(value)) count.set(value, 1); else count.set(value, count.get(value) + 1); }); return count; } /** * Returns the element at the given index or the result of calling defaultValue * if the index is out of bounds for this array. * @param {number} index the index to look for. * @param {Function} defaultValue a function that will return a default value in case the index is out of bounds. Receives index as a parameter. */ elementAtOrElse(index, defaultValue) { if (index < -this.length || index >= this.length) return defaultValue(index); else return this.at(index); } /** * Compares the elements of two arrays by order, returning true if all elements are in * the same place and are equal. * @param {Array} array the list of which each item will be compared against this ArrayList. * @returns {boolean} `true` if all elements are equal and are in the same place, `false` instead. */ equals(array) { for (const [index, value] of this.entries()) { if (this.length !== array.length) return false; if (this[index] != array[index]) return false; } return true; } /** * Returns a copy of the original ArrayList where all elements that are not instances of * the specified class have been removed. * @param {Class} klass the class to compare each item against. */ filterInstance(klass) { return this.filter(i => i instanceof klass); } /** * Returns a copy of the original ArrayList where all elements that evaluate as falsy have been removed. */ filterNotFalsy() { return this.filter(i => !!i); } /** * Returns a copy of the original ArrayList containing all elements that are not null or undefined. */ filterNotNull() { return this.filter(i => i != null); } /** * Finds the last item of this ArrayList that fulfills a predicate, as opposed to * [Array.find()](https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Global_Objects/Array/find). * @param {Function} predicate the condition to be checked for each item. * @returns {*} the last item fulfilling the predicate. */ findLast(predicate) { return this.reduce((acc, val) => predicate(val) ? val : acc); } /** * Finds the index of the last item of this ArrayList that fulfills a predicate, as opposed to * [Array.findIndex()](https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex). * @param {Function} predicate the condition to be checked for each item. * @returns {number} the index of the last item fulfilling the predicate. */ findLastIndex(predicate) { return this.reduce((acc, val, index) => predicate(val) ? index : acc, 0); } /** * If a predicate is given, returns the first element that fulfills it. * Otherwise, returns the first element of the ArrayList, if it exists. * Aditionally, a defaultValue function can be specified. * @param {Function} [predicate] the condition to check for each item. * @param {Function} [defaultValue] a function that returns a default value, in case no element is found. */ first(predicate, defaultValue) { return predicate ? this.find(predicate) : this[0] ? this[0] : defaultValue ? defaultValue() : undefined; } /** * Creates an object from an array of pairs, where the first element of each * pair is the key and the second is the value. */ fromPairs() { return this.reduce((acc, val) => { if (!isValidObjectPair(val)) throw new TypeError("Array must be exclusively made of Pairs"); acc[val[0]] = val[1]; return acc; }, {}); } /** * Creates an object that relates a group of items to one of their properties. * @param {string | Function} propOrSelector the property to associate the elements with. */ groupBy(propOrSelector) { if (typeof propOrSelector === "string" && this.every((i) => propOrSelector in i)) return this.reduce((acc, val) => { var _a; const value = val[propOrSelector]; acc[value] = (_a = acc[value]) !== null && _a !== void 0 ? _a : new ArrayList(); acc[value].push(val); return acc; }, {}); else if (typeof propOrSelector === "function" && this.every((i) => !!propOrSelector(i))) return this.reduce((acc, val) => { var _a; const value = propOrSelector(val); acc[value] = (_a = acc[value]) !== null && _a !== void 0 ? _a : new ArrayList(); acc[value].push(val); return acc; }, {}); else throw new TypeError("Not all objects in ArrayList share the same property"); } /** * Inserts an element or group of elements at a specific index of the ArrayList. Mutating. * @param {number} index the index where the element(s) will be added. * @param {Array} elements the element(s) to add. * @returns {ArrayList} the modified ArrayList. */ insert(index, ...elements) { this.splice(index, 0, ...elements); return this; } /** * Filters out empty elements and then checks if the array length is zero. Since JS arrays are sparse, * `Array(5)` will create an array of length 5, but no items. * Frameworks like underscore check for the length of the array without doing any kind of filtering, * and so `Array(5)`, which logs as `[ empty x 5 ]` in most JS runtimes, will appear as not empty there. * @returns `true` if there are no elements, `false` instead. */ isEmpty() { return this.filter(_ => true).length === 0; } /** * Uses isEmpty to check if the array has any items. If not, will return the result of calling defaultValue. * @param {Function} defaultValue function providing the default value in case the array is empty. */ ifEmpty(defaultValue) { if (this.isEmpty()) return defaultValue(); } /** * If a predicate is given, returns the last element that fulfills it. * Otherwise, returns the last element of the ArrayList, if it exists. * Aditionally, a defaultValue function can be specified. * @param {Function} [predicate] the condition to check for each item. * @param {Function} [defaultValue] a function that returns a default value, in case no element is found. */ last(predicate, defaultValue) { return predicate ? this.findLast(predicate) : this[this.length - 1] ? this[this.length - 1] : defaultValue ? defaultValue() : undefined; } /** * Returns a copy of the original ArrayList after applying a transformator function on each of the elements. * It filters out falsy values. * @param {Function} transform the transformator function. * @param {*} thisArg the context, in case of needing one. */ mapNotFalsy(transform, thisArg) { return this.map(transform, thisArg).filterNotFalsy(); } /** * Returns a copy of the original ArrayList after applying the transformator function on each of the elements. * It filters out null values. * @param {Function} transform the transformator function. * @param {*} thisArg the context, in case of needing one. */ mapNotNull(transform, thisArg) { return this.map(transform, thisArg).filterNotNull(); } /** * Returns the maximum value using the standard greater than operator. */ max() { return this.reduce((acc, val) => val > acc ? val : acc); } /** * Returns the maximum value using a custom comparator. * @param selector custom comparator. Returns a number. */ maxBy(selector) { return this.reduce((acc, val) => selector(val) > selector(acc) ? val : acc); } /** * Returns the minimum value using the standard less than operator. */ min() { return this.reduce((acc, val) => val < acc ? val : acc); } /** * Returns the minimum value using a custom comparator. * @param selector custom comparator. Returns a number. * @returns */ minBy(selector) { return this.reduce((acc, val) => selector(val) < selector(acc) ? val : acc); } /** * Returns a random element from the array. */ random() { return this[Math.floor(Math.random() * this.length)]; } /** * Returns a reversed copy of the original ArrayList. */ reversed() { return new ArrayList(this).reverse(); } /** * Returns a custom-sized sample of random elements from an ArrayList. * @param {Number} size the size of the sample. * @return {ArrayList} */ sample(size) { const copy = this.copyOf(); const sample = new ArrayList(); for (let i = 0; i < size; i++) { const randomElement = copy.random(); sample.add(randomElement); copy.remove(randomElement); } return sample; } /** * Inserts an element or group of elements at some index of the ArrayList, replacing those values * that were in any of the modified indexes. * @param {number} index the index the element(s) will be added. * @param {Array} elements the element(s) to add. * @returns {ArrayList} the modified ArrayList. */ set(index, ...elements) { this.splice(index, elements.length, ...elements); return this; } /** * Algorithm taken from [this SO question](https://stackoverflow.com/a/2450976/15920951). * It's an implementation of the Fisher-Yates algorithm. * Shuffles the ArrayList and returns it. */ shuffle() { var currentIndex = this.length, temporaryValue, randomIndex; while (0 !== currentIndex) { randomIndex = Math.floor(Math.random() * currentIndex); currentIndex -= 1; temporaryValue = this[currentIndex]; this[currentIndex] = this[randomIndex]; this[randomIndex] = temporaryValue; } return this; } /** * Just like shuffle, the algorithm was taken from [this SO question](https://stackoverflow.com/a/2450976/15920951). * Unlike shuffle, however, shuffled returns a shuffled copy of the original ArrayList, leaving * it untouched. */ shuffled() { const array = new ArrayList(this); var currentIndex = array.length, temporaryValue, randomIndex; while (0 !== currentIndex) { randomIndex = Math.floor(Math.random() * currentIndex); currentIndex -= 1; temporaryValue = array[currentIndex]; array[currentIndex] = array[randomIndex]; array[randomIndex] = temporaryValue; } return array; } /** * Unlike Array.prototype.sort, sorted returns a sorted copy of the original ArrayList. * Optionally, a selector function can be specified. * @param {Function} selector sorting function. If not specified, will use default. */ sorted(selector) { return new ArrayList(this).sort(selector); } /** * Returns the sum of all numbers of the array. If elements are not addable, returns NaN. * @return {number} the sum of all elements in the ArrayList. */ sum() { return this.reduce((acc, val) => acc + Number(val), 0); } /** * If n is positive, returns a copy of the ArrayList that only contains the initial n elements of it. * If n is negative, returns a copy of the ArrayList that only contains the last n elements of it. * @param {number} n the amount of elements. * @returns {ArrayList} a modified copy of the ArrayList. */ take(n) { return this.slice(0, n); } /** * Returns a new ArrayList containing the first n elements that fulfill the predicate. * @param {Function} predicate the condition to be checked for each item. */ takeWhile(predicate) { for (const [i, v] of this.entries()) if (!predicate(v)) return this.slice(0, i); return this; } /** * Returns a Generator object that yields items based on the predicate. Breaks once an item doesn't fulfill it. * @param {Function} predicate the condition to be checked for each item. */ *takeWhileLazy(predicate) { for (let i of this) { if (predicate(i)) yield i; else break; } } /** * Returns an array containing the elements of this ArrayList. */ toArray() { return Array.from(this); } /** * Returns a set containing the elements of this ArrayList. */ toSet() { return new Set(this); } /** * Returns a copy of the original ArrayList that only contains unique elements. */ unique() { return new ArrayList(...new Set(this)); } /** * Returns the result of separating the pairs of an ArrayList into two different ArrayLists. */ unzip() { return this.reduce((acc, val) => { if (!isValidPair(val)) throw new TypeError("Array must be exclusively made of Pairs"); acc[0].push(val[0]); acc[1].push(val[1]); return acc; }, [new ArrayList(), new ArrayList()]); } /** * Returns an ArrayList of pairs result of calling the transformator function on each * of the elements of this ArrayList and another at a given index. * @param {Array} other the Array or ArrayList to be zipped with this ArrayList. * @param {Function} transform the transformator function to be applied on each pair of items. */ zip(other, transform = (a, b) => [a, b]) { return this.map((item, index) => transform(item, other[index])); } /** * Returns an ArrayList of pairs result of calling the transformator function on each * of the elements of this ArrayList and the element at the index that follows it. * @param transform * @returns */ zipWithNext(transform = (a, b) => [a, b]) { const list = new ArrayList(); for (let i = 0; i < this.length; i += 2) list.push(transform(this[i], this[i + 1])); return list; } at(index) { if (index >= 0) return this[index]; else return this[this.length + index]; } }
JavaScript
class PlayerPayRepair extends PlayerPayBank { /** * Takes the repair cost fees to pay for both * houses and hotels that will be charged to the player. * * @param {integer} houseCost The house repair cost. * @param {integer} hotelCost The hotel repair cost. */ constructor(houseCost, hotelCost) { super(null); this.houseCost = houseCost; this.hotelCost = hotelCost; } /** * Withdraws {@link houseCost} if player owns only houses, * withdraws {@link hotelCost} if player owns hotels. * * @override * @param {GameManager} game The game manager instance. * @param {Player} player The player to withdraw cash from. */ do(game, player) { // conditionally update cost super.do(game, player); this.cash = null; } }
JavaScript
class Products extends Component { constructor(props) { super(props); this.state = { list: [], } } // get the product when component did mount getProduct = () => { axios.all([ axios.get(`http://34.94.123.246:5000/product/?getProductbyProductid=${this.props.location.state.productId}`), axios.get(`http://34.94.123.246:5000/user/?getUserbyProductid=${this.props.location.state.productId}`) ]) .then(axios.spread((productRes, userRes) => { this.viewProduct(userRes.data.data, productRes.data.data); })) .catch(err => { console.log(err) }); }; // view the product after getting response viewProduct = (user, product) => { const temp = <> <Row > <Col sm={7}> <img className="main-img img-fluid" src="https://images.unsplash.com/photo-1501618669935-18b6ecb13d6d?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=2664&q=80" alt={product[0].name} /> </Col> <Col sm={5} > <div > <br /> <div className="mb-3"> <Badge pill variant="primary" style={{ size: "150%" }}>{product[0].category}</Badge> </div> <br /> <h1>{product[0].name}</h1> <Button variant="light" onClick={(e) => { this.onSellerProfile(e, product[0].product_creator) }} style={{ textAlign: "left", fontSize: "150%", paddingLeft: 0 }} > {user[0].username} </Button> <p><i>{user[0].email}</i></p> <hr /> <Row id="product-des"> <Col md={2} id="product-des"> <p>Price</p> </Col> <Col md={1}> <p>:</p> </Col> <Col> <p id="price">{product[0].price}USD</p> </Col> </Row> <Row id="product-des"> <Col md={2} id="product-des"> <p>Department</p> </Col> <Col md={1}> <p>:</p> </Col> <Col> <p>{product[0].department}</p> </Col> </Row> <Row id="product-des"> <Col md={2} id="product-des"> <p>Course</p> </Col> <Col md={1}> <p>:</p> </Col> <Col> <p>{product[0].course}</p> </Col> </Row> <Row id="product-des"> <Col md={2} id="product-des"> <p>Quantity</p> </Col> <Col md={1}> <p>:</p> </Col> <Col> <p>{product[0].quantity}</p> </Col> </Row> <Row id="product-des"> <Col md={2} id="product-des"> <p>Description</p> </Col> <Col md={1}> <p>:</p> </Col> <Col> <p>{product[0].description}</p> </Col> </Row> </div> </Col> </Row> <br /> <Row> <div id="btn-buy"> <Button variant="warning" onClick={(e) => { this.onPurchase(e, user[0], product[0]) }}><i className="fas fa-shopping-cart"></i> Buy Now </Button> </div> </Row> </> this.setState({ list: temp }); } // push to transaction to purchase the product when button clicked onPurchase = (e, user, product) => { e.preventDefault(); this.props.history.push({ pathname: "/transaction", state: { user: user, product: product, } }); } // push to seller profile onSellerProfile = (e, sellerid) => { e.preventDefault(); const cookies = new Cookies(); let userid = cookies.get("userid"); this.props.history.push({ pathname: "/profile/seller", state: { userid: userid, sellerid: sellerid, } }); } getTempProduct = () => { let product = { data: [{ "category": "Books", "product_buyer": null, "course": 1, "name": "Final Fantasy VI", "tags": "Game;Video Game;Final Fantasy;FFVI", "price": 60, "product_creator": 1, "pid": 12, "quantity": 6, "description": "This is a FF franchise", }] } let user = { data: [{ "uid": "1", "email": "[email protected]", "username": "John Smith", }] } this.viewProduct(user.data, product.data); } componentDidMount() { this.getProduct(); } render() { return ( <div className="Product page-container"> <div className="page-wrapper"> <div className="push-down"> <Header /> </div> <Container fluid style={{ padding: "2rem 0" }}> <Row> <Col sm={10} className="border-home" style={{ padding: "1rem 0" }}> {this.state.list} </Col> <Col sm={2}> <SidePanel /> </Col> </Row> </Container> </div> <Footer /> </div > ); } }
JavaScript
class Modal extends PureComponent { static propTypes = { /** Most likely the modal header, body, or footer components, though anything is supported */ children: PropTypes.node.isRequired, /** Give the modal a custom class, or list of classes (space-separated) */ className: PropTypes.string, /** If the modal is open or not */ isOpen: PropTypes.bool, /** The CB to change the modal open state */ toggle: PropTypes.func.isRequired, /** Sets the min height to be larger */ large: PropTypes.bool, /** Sets the min height to be smaller */ small: PropTypes.bool, /** Optional styles */ style: PropTypes.shape({}), } static defaultProps = { className: '', isOpen: false, large: false, small: false, style: {}, } constructor(props) { super(props); this.state = { addedToDOM: props.isOpen, }; this.removeFromDOM = this.removeFromDOM.bind(this); } componentWillReceiveProps(nextProps) { if (nextProps.isOpen) { this.setState({ addedToDOM: true, }); } } componentWillUnmount() { document.body.classList.remove('modal-v2-noscroll'); } removeFromDOM() { this.setState({ addedToDOM: false, }); } renderModal() { // eslint-disable-next-line document.body.classList.toggle('modal-v2-noscroll', this.props.isOpen); let modalClasses = `modal v2 ${this.props.className}`; if (this.props.large) { modalClasses = `${modalClasses} large`; } else if (this.props.small) { modalClasses = `${modalClasses} small`; } return ( <Fade in={this.props.isOpen} onExited={this.removeFromDOM} > <div className={modalClasses} style={this.props.style}> <div className="contents"> {this.props.children} <Button className="exit-button" onClick={this.props.toggle}> <i className="fa fa-times" /> </Button> </div> <div className="overlay" onClick={this.props.toggle} /> </div> </Fade> ); } render() { if (this.state.addedToDOM) { return ReactDOM.createPortal( this.renderModal(), document.body, ); } return null; } }
JavaScript
class Manager extends Employee { constructor(name, id, email, officeNumber) { // Uses the employee constructors functions values super(name, id, email) // Creates a new property that holds the officeNumber input value this.officeNumber = officeNumber; } // Creates a new method that returns the Manager role getRole() { return "Manager"; } }
JavaScript
class InterfaceTestcaseHost extends Model { /** * get ViewModel class bind with Model * @return {ViewModel} - ViewModel class */ getViewModel() { return require('../vm/InterfaceTestcaseHost'); } }
JavaScript
class OrderHistory { /** * Constructs a new <code>OrderHistory</code>. * @alias module:models/OrderHistory * @class */ constructor() { /** * * @member {String} code */ this.code = undefined /** * * @member {String} status */ this.status = undefined /** * * @member {String} statusDisplay */ this.statusDisplay = undefined /** * * @member {String} placed */ this.placed = undefined /** * * @member {String} guid */ this.guid = undefined /** * @member {module:models/Price} total */ this.total = undefined } /** * Constructs a <code>OrderHistory</code> from a plain JavaScript * object, optionally creating a new instance. Copies all relevant properties * from <code>data</code> to <code>obj</code> if supplied or a new instance * if not. * @param {Object} data The plain JavaScript object bearing properties of * interest. * @param {module:models/OrderHistory} obj Optional instance to * populate. * @return {module:models/OrderHistory} The populated * <code>OrderHistory</code> instance. */ static constructFromObject(data, obj) { if (data) { obj = obj || new OrderHistory() if (data.hasOwnProperty('code')) { obj.code = ApiClient.convertToType(data.code, 'String') } if (data.hasOwnProperty('status')) { obj.status = ApiClient.convertToType(data.status, 'String') } if (data.hasOwnProperty('statusDisplay')) { obj.statusDisplay = ApiClient.convertToType(data.statusDisplay, 'String') } if (data.hasOwnProperty('placed')) { obj.placed = ApiClient.convertToType(data.placed, 'String') } if (data.hasOwnProperty('guid')) { obj.guid = ApiClient.convertToType(data.guid, 'String') } if (data.hasOwnProperty('total')) { obj.total = Price.constructFromObject(data.total) } } return obj } }
JavaScript
class SimpleDateFormat { /** * * @param format * * yyyy:year * MM,M:month * dd,d:date * HH,H:hours (0-23) * hh,h:hours (1-12) * a:AM,PM * mm,m:minutes * ss,s:seconds * SSS:milliseconds * '[something]':escape string by '' * * @param days */ constructor(format, days) { this.days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; this.months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; this.formatStr = format; } /** * Set names of day of week * * @param days * @returns {SimpleDateFormat} */ setDays(days) { if (!days) { throw Error('days not specified'); } if (!Array.isArray(days)) { throw Error('days must be an array.'); } if (days.length != 7) { throw Error('days array size must be 7.'); } this.days = days; return this; } setMonths(months) { if (!months) { throw Error('months not specified'); } if (!Array.isArray(months)) { throw Error('months must be an array.'); } if (months.length != 12) { throw Error('months array size must be 12.'); } this.months = months; return this; } /** * format date * @param date */ format(date) { return formatWith(this.formatStr, date, { days: this.days, months: this.months }); } /** * format date with formatString * * @param formatStr * yyyy:year * MM,M:month * dd,d:date * HH,H:hours (0-23) * hh,h:hours (1-12) * a:AM,PM * mm,m:minutes * ss,s:seconds * SSS:milliseconds * '[something]':escape string by '' * * @param date */ formatWith(formatStr, date, opt) { if (typeof opt === 'undefined') { return formatWith(formatStr, date, { days: this.days, months: this.months }); } else { return formatWith(formatStr, date, opt); } } }
JavaScript
class OrderContext extends Context { constructor() { super(); // All orders are held in a list of order this.orderList = new OrderList(this); } }
JavaScript
class OrderContract extends Contract { constructor() { // Chaincode id is processcontract, same as file name // Here define smart contract name as 'org.processnet.order' super('org.processnet.order'); this.helper = new Helper(); } /** * Define a custom context for order */ createContext() { return new OrderContext(); } /** * Instantiate to perform any setup of the ledger that might be required. * @param {Context} ctx the transaction context */ async instantiate(ctx) { // No implementation required with this example // It could be where data migration is performed, if necessary console.log('Instantiate the contract'); } async initOrderLedger(ctx) { console.info('============= START : Initialize Ledger ==========='); const orders = [ { class: 'org.processnet.order', createdTime: '1553521600', currentState: "1", orderID: '1', orderer: 'CVS', assuranceObj: {specs: 'N/A', qualifiedOperator: 'N/A', methods: 'N/A', leadTime: 'N/A'}, productObj: {name: 'drugA', price: '1350', productID: '4', weight: '350'}, shippingObj: {address: '160 Pleasant st., Malden, MA', dispatchDate: 'ship in 15 days', orderer: 'CVS', shipMethod: 'sea express', tradeTerm: 'FCA'}, paymentObj: {initPayment: '500', payMethod: 'mastercard', totalAmount: '1350'}, type: '1', receiver: 'MagnetoCorp', }, { class: 'org.processnet.order', createdTime: '1552521600', currentState: '2', orderID: '2', orderer: 'CVS', assuranceObj: {specs: 'some specs...', qualifiedOperator: 'need operator get C license', methods: 'follow our SOP', leadTime: '1 months'}, productObj: {name: 'drugA', price: '1350', productID: '4', weight: '350'}, shippingObj: {address: 'Beacon st., Boston, MA', dispatchDate: 'ship in 2 days', orderer: 'CVS', shipMethod: 'air express', tradeTerm: 'FCA'}, paymentObj: {initPayment: '500', payMethod: 'visa', totalAmount: '1350',}, type: '2', receiver: 'MagnetoCorp', }, { class: 'org.processnet.order', createdTime: '1553521600', currentState: "1", orderID: '3', orderer: 'CVS', assuranceObj: {specs: 'N/A', qualifiedOperator: 'N/A', methods: 'N/A', leadTime: 'N/A'}, productObj: {name: 'drugA', price: '1350', productID: '6', weight: '350'}, shippingObj: {address: '70 Pleasant st., Boston, MA', dispatchDate: 'ship in 30 days', orderer: 'CVS', shipMethod: 'air express', tradeTerm: 'FCA'}, paymentObj: {initPayment: '500', payMethod: 'mastercard', totalAmount: '1350'}, type: '1', receiver: 'MagnetoCorp', }, ]; for (let i = 0; i < orders.length; i++) { orders[i].docType = 'order'; let key = ctx.orderList.name + '"' + orders[i].orderID + '"'; await ctx.stub.putState(key, Buffer.from(JSON.stringify(orders[i]))); console.info('Added <--> ', orders[i]); } console.info('============= END : Initialize Ledger ==========='); } /** * Init order * * @param {Context} ctx the transaction context * @param {Integer} type type of the order * @param {Integer} orderID order unique id * @param {String} name name of the order * @param {String} weight weight of the order * @param {String} price price of the order * @param {Integer} specs specs of the trade assurance * @param {String} qualifiedOperator assign qualified operator in trade assurance * @param {String} methods assign methods in trade assurance * @param {String} leadTime assign lead time in trade assurance * @param {String} address shipping address * @param {String} shipMethod shipping method * @param {String} tradeTerm shipping trade term * @param {String} dispatchDate shipping dispatch date * @param {String} createdTime time of the order created * @param {String} orderer orderer's enrolled username * @param {String} receiver receiver's enrolled username */ async initOrder(ctx, orderID, type, productID, name, weight, price, specs, qualifiedOperator, methods, leadTime, address, shipMethod, tradeTerm, dispatchDate, totalAmount, initPayment, payMethod, createdTime, orderer, receiver) { // create a new order ID console.log(ctx); console.log('----------------------') console.log(ctx.orderList); // create an instance of the order let order = Order.createInstance(orderID, type, productID, name, weight, price, specs, qualifiedOperator, methods, leadTime, address, shipMethod, tradeTerm, dispatchDate, totalAmount, initPayment, payMethod, createdTime, orderer, receiver); // Smart contract, rather than order, moves order into INIT state order.setInit(); // Add the order to the list of all similar orders in the ledger world state let key = await ctx.orderList.addOrder(order); console.log('This is the return key: ' + key); // Must return a serialized order to caller of smart contract return order.toBuffer(); } /** * MOdify order status * * @param {Context} ctx the transaction context * @param {Integer} type type of the order * @param {Integer} orderID order unique id * @param {String} name name of the order * @param {String} weight weight of the order * @param {String} price price of the order * @param {Integer} specs specs of the trade assurance * @param {String} qualifiedOperator assign qualified operator in trade assurance * @param {String} methods assign methods in trade assurance * @param {String} leadTime assign lead time in trade assurance * @param {String} address shipping address * @param {String} shipMethod shipping method * @param {String} tradeTerm shipping trade term * @param {String} dispatchDate shipping dispatch date * @param {String} updatedTime time of the order updated * @param {String} orderer orderer's enrolled username * @param {String} receiver receiver's enrolled username * @param {String} modifier modifier's enrolled username */ async modifyOrder(ctx, orderID, productID, newProductID, newName, newWeight, newPrice, newSpecs, newQualifiedOperator, newMethods, newLeadTime, newAddress, newShipMethod, newTradeTerm, newDispatchDate, newTotalAmount, newInitPayment, newPayMethod, updatedTime, orderer, modifier, newState) { // Retrieve the current order using key fields provided let orderKey = Order.makeKey([orderID]); console.log(orderKey); let order = await ctx.orderList.getOrder(orderKey); // Validate current owner if (order.getOrderer() !== modifier && order.getReceiver() !== modifier) { throw new Error('Order ' + orderKey + ' cannot be modified by ' + modifier); } // Change ownership if (order.currentState != "1" && order.currentState != "4" && order.currentState != "5") { throw new Error('Order contract ' + orderKey + ' is signed by both orgs. Cannot modified!'); } if(order.type == "2") { order.setAssuranceDetails(newSpecs, newQualifiedOperator, newMethods, newLeadTime); } order.setProductDetails(newProductID, newName, newWeight, newPrice); order.setShippingDetails(newAddress, newShipMethod, newTradeTerm, newDispatchDate); order.setPaymentDetails(newTotalAmount, newInitPayment, newPayMethod); // Update state switch (newState) { case "4": order.setPendingCreator(); break; case "5": order.setPendingReceiver(); break; } order.setUpdateTime(updatedTime); // Update the order await ctx.orderList.updateOrder(order); return order.toBuffer(); } /** * MOdify order status * * @param {Context} ctx the transaction context * @param {Integer} type type of the order * @param {Integer} orderID order unique id * @param {String} name name of the order * @param {String} weight weight of the order * @param {String} price price of the order * @param {Integer} specs specs of the trade assurance * @param {String} qualifiedOperator assign qualified operator in trade assurance * @param {String} methods assign methods in trade assurance * @param {String} leadTime assign lead time in trade assurance * @param {String} address shipping address * @param {String} shipMethod shipping method * @param {String} tradeTerm shipping trade term * @param {String} dispatchDate shipping dispatch date * @param {String} updatedTime time of the order updated * @param {String} orderer orderer's enrolled username * @param {String} receiver receiver's enrolled username * @param {String} modifier modifier's enrolled username */ async updateOrder(ctx, orderID, productID, updatedTime, orderer, modifier, newState) { // Retrieve the current order using key fields provided let orderKey = Order.makeKey([orderID]); let order = await ctx.orderList.getOrder(orderKey); // Validate current owner if (order.getOrderer() !== modifier && order.getReceiver() !== modifier) { throw new Error('Order ' + orderKey + ' cannot be modified by ' + modifier); } // Update state switch (newState) { case "2": if(order.getOrderer() == modifier) { order.setAccepted(); break; } case "3": if(order,getOrderer() == modifier) { order.setAbandoned(); break; } case "6": if(order.getReceiver() == modifier) { order.setProcessing(); break; } case "7": if(order.getReceiver() == modifier) { order.setShipOut(); break; } } order.setUpdateTime(updatedTime); // Update the order await ctx.orderList.updateOrder(order); return order.toBuffer(); } async queryAllOrders(ctx, orderID) { let orderKey = Order.makeKey([orderID]); console.log('This is orderKey: ' + orderKey); let endOrderID = toString(parseInt(orderID) + 999); const startKey = ctx.orderList.name + orderKey; const endKey = ctx.orderList.name + Order.makeKey([endOrderID]); const iterator = await ctx.stub.getStateByRange(startKey, endKey); const allResults = []; return this.helper.print(iterator, allResults); } async queryOrder(ctx, orderID) { let orderKey = Order.makeKey([orderID]); console.log('This is orderKey: ' + orderKey); const stateKey = ctx.orderList.name + orderKey; const result = await ctx.stub.getState(stateKey); return result; } async getHistoryByKey(ctx, orderID) { const key = ctx.orderList.name + Order.makeKey([orderID]); const iterator = await ctx.stub.getHistoryForKey(key); const allResults = []; return this.helper.print(iterator, allResults); } }
JavaScript
class FabCar extends Contract { async initLedger(ctx) { console.info('============= START : Initialize Ledger ==========='); const cars = [ { color: 'blue', make: 'Toyota', model: 'Prius', owner: 'Tomoko', }, { color: 'red', make: 'Ford', model: 'Mustang', owner: 'Brad', }, { color: 'green', make: 'Hyundai', model: 'Tucson', owner: 'Jin Soo', }, { color: 'yellow', make: 'Volkswagen', model: 'Passat', owner: 'Max', }, { color: 'black', make: 'Tesla', model: 'S', owner: 'Adriana', }, { color: 'purple', make: 'Peugeot', model: '205', owner: 'Michel', }, { color: 'white', make: 'Chery', model: 'S22L', owner: 'Aarav', }, { color: 'violet', make: 'Fiat', model: 'Punto', owner: 'Pari', }, { color: 'indigo', make: 'Tata', model: 'Nano', owner: 'Valeria', }, { color: 'brown', make: 'Holden', model: 'Barina', owner: 'Shotaro', }, ]; for (let i = 0; i < cars.length; i++) { cars[i].docType = 'car'; await ctx.stub.putState('CAR' + i, Buffer.from(JSON.stringify(cars[i]))); console.info('Added <--> ', cars[i]); } console.info('============= END : Initialize Ledger ==========='); } async queryCar(ctx, carNumber) { const carAsBytes = await ctx.stub.getState(carNumber); // get the car from chaincode state if (!carAsBytes || carAsBytes.length === 0) { throw new Error(`${carNumber} does not exist`); } console.log(carAsBytes.toString()); return carAsBytes.toString(); } async createCar(ctx, carNumber, make, model, color, owner) { console.info('============= START : Create Car ==========='); const car = { color, docType: 'car', make, model, owner, }; await ctx.stub.putState(carNumber, Buffer.from(JSON.stringify(car))); console.info('============= END : Create Car ==========='); } async queryAllCars(ctx) { const startKey = 'CAR0'; const endKey = 'CAR999'; const iterator = await ctx.stub.getStateByRange(startKey, endKey); const allResults = []; while (true) { const res = await iterator.next(); if (res.value && res.value.value.toString()) { console.log(res.value.value.toString('utf8')); const Key = res.value.key; let Record; try { Record = JSON.parse(res.value.value.toString('utf8')); } catch (err) { console.log(err); Record = res.value.value.toString('utf8'); } allResults.push({ Key, Record }); } if (res.done) { console.log('end of data'); await iterator.close(); console.info(allResults); return JSON.stringify(allResults); } } } async changeCarOwner(ctx, carNumber, newOwner) { console.info('============= START : changeCarOwner ==========='); const carAsBytes = await ctx.stub.getState(carNumber); // get the car from chaincode state if (!carAsBytes || carAsBytes.length === 0) { throw new Error(`${carNumber} does not exist`); } const car = JSON.parse(carAsBytes.toString()); car.owner = newOwner; await ctx.stub.putState(carNumber, Buffer.from(JSON.stringify(car))); console.info('============= END : changeCarOwner ==========='); } }
JavaScript
class DevtoolsSpa { path() { return __dirname + '/../../../../semdoc4' } devCommand() { return { command: 'yarn start', } } buildCommand() { return { command: 'yarn build', } } buildOutputPath() { return this.path() + '/dist' } }
JavaScript
class AsmAuthService extends AuthService { constructor(store, userIdService, oAuthLibWrapperService, authStorageService, authRedirectService, globalMessageService, routingService) { super(store, userIdService, oAuthLibWrapperService, authStorageService, authRedirectService, routingService); this.store = store; this.userIdService = userIdService; this.oAuthLibWrapperService = oAuthLibWrapperService; this.authStorageService = authStorageService; this.authRedirectService = authRedirectService; this.globalMessageService = globalMessageService; this.routingService = routingService; } canUserLogin() { let tokenTarget; let token; this.authStorageService .getToken() .subscribe((tok) => (token = tok)) .unsubscribe(); this.authStorageService .getTokenTarget() .subscribe((tokTarget) => (tokenTarget = tokTarget)) .unsubscribe(); return !(Boolean(token === null || token === void 0 ? void 0 : token.access_token) && tokenTarget === TokenTarget.CSAgent); } warnAboutLoggedCSAgent() { this.globalMessageService.add({ key: 'asm.auth.agentLoggedInError', }, GlobalMessageType.MSG_TYPE_ERROR); } /** * Loads a new user token with Resource Owner Password Flow when CS agent is not logged in. * @param userId * @param password */ loginWithCredentials(userId, password) { const _super = Object.create(null, { loginWithCredentials: { get: () => super.loginWithCredentials } }); return __awaiter(this, void 0, void 0, function* () { if (this.canUserLogin()) { yield _super.loginWithCredentials.call(this, userId, password); } else { this.warnAboutLoggedCSAgent(); } }); } /** * Initialize Implicit/Authorization Code flow by redirecting to OAuth server when CS agent is not logged in. */ loginWithRedirect() { if (this.canUserLogin()) { super.loginWithRedirect(); return true; } else { this.warnAboutLoggedCSAgent(); return false; } } /** * Revokes tokens and clears state for logged user (tokens, userId). * To perform logout it is best to use `logout` method. Use this method with caution. */ coreLogout() { return this.userIdService .isEmulated() .pipe(take(1), switchMap((isEmulated) => { if (isEmulated) { this.authStorageService.clearEmulatedUserToken(); this.userIdService.clearUserId(); this.store.dispatch(new AuthActions.Logout()); return of(true); } else { return from(super.coreLogout()); } })) .toPromise(); } /** * Returns `true` if user is logged in or being emulated. */ isUserLoggedIn() { return combineLatest([ this.authStorageService.getToken(), this.userIdService.isEmulated(), this.authStorageService.getTokenTarget(), ]).pipe(map(([token, isEmulated, tokenTarget]) => Boolean(token === null || token === void 0 ? void 0 : token.access_token) && (tokenTarget === TokenTarget.User || (tokenTarget === TokenTarget.CSAgent && isEmulated)))); } }
JavaScript
class Quorum extends BlockchainInterface{ /** * Create a new instance of the {Quorum} class. * @param {string} config_path The path of the Quorum network configuration file. */ constructor(config_path) { super(config_path); let quorum_setup = require(commUtils.resolvePath(config_path)); // An array of obj {'url': <node_endpoint>, 'pub_key': <node_pub_key>} this.nodes_info = quorum_setup.quorum.network; if (quorum_setup.quorum.private === 1) { this.private = true; // Private to every node by default this.privateFor = []; this.nodes_info.forEach(node_info => { this.privateFor.push(node_info.pub_key); }); // console.log("PrivateFor: ", this.privateFor); } else { console.log("Not Private..."); this.private = false; } } /** * Initialize the {Quorum} object. * @return {Promise} The return promise. */ init() { // donothing return Promise.resolve(); } getBlockNumAsync() { const nodeUrl = this.nodes_info[0].url; const web3 = new Web3(new Web3.providers.HttpProvider(nodeUrl)); return web3.eth.getBlockNumber(); } registerBlockProcessing(clientIdx, callback, err_cb) { let idx = clientIdx % this.nodes_info.length; let nodeUrl = this.nodes_info[idx].url; let web3 = new Web3(new Web3.providers.HttpProvider(nodeUrl)); let blk_poll_interval = 50; // poll block for every 50ms let self = this; // console.log("Prepaer registraetion...."); // return web3.eth.getBlock('latest').then((blk)=>{ // self.last_blk_num = parseInt(blk.number, 10); // self.last_blk_hash = blk.hash; // // console.log("At start blk num ", self.last_blk_num, " hash ", self.last_blk_hash); // self.blk_poll_interval = setInterval(() => { // web3.eth.getBlock("latest").then((blk)=>{ // let blk_num = parseInt(blk.number, 10); // let blk_hash = blk.hash; // let parent_hash = blk.parentHash; // let all_txns; // if (blk_num === self.last_blk_num) { // console.log("NO new block..."); // return Promise.resolve([]); // } else { // let txns = blk.transactions; // all_txns = txns.splice(0); // let blk_idxs = []; // for (let blk_idx = blk_num - 1; // blk_idx > self.last_blk_num; blk_idx--) { // blk_idxs.push(blk_idx); // } // return blk_idxs.reduce((prev, item)=>{ // return prev.then((hash)=>{ // return web3.eth.getBlock(hash); // }).then((blk)=>{ // all_txns = all_txns.concat(blk.transactions); // let parent_hash = blk.parentHash; // return Promise.resolve(parent_hash); // }).catch((err)=>{ // commUtils.log("Fail to get block with hash ", err); // return Promise.reject("Fail to get block with number ", item); // }); // }, Promise.resolve(parent_hash)).then((parent_hash)=>{ // if (parent_hash === self.last_blk_hash) { // self.last_blk_num = blk_num; // self.last_blk_hash = blk_hash; // return Promise.resolve(all_txns); // } else { // commUtils.log("Inconsistent Hash!!"); // return Promise.reject("Inconsistent Block Hash..."); // } // }); // } // }).then((all_txns)=>{ // // console.log("On-chain txns: ", all_txns); // }).catch((err)=>{ // commUtils.log("Error in getting the latest block ", err); // return Promise.reject(err); // }) return web3.eth.getBlockNumber().then((blk_num)=>{ self.last_blk_num = blk_num; self.blk_poll_interval = setInterval(() => { web3.eth.getBlockNumber().then((latest_blk_num)=>{ // console.log("Last: ", self.last_blk_num, " Latest: ", latest_blk_num); let poll_blk_promises = []; for (let blk_num = self.last_blk_num + 1; blk_num <= latest_blk_num; blk_num++) { // console.log("Blk Num: ", blk_num); poll_blk_promises.push( web3.eth.getBlock(blk_num).then((blk)=>{ // console.log("Gas Limit in Blk: ", blk.gasLimit); // console.log("Gas used in Blk: ", blk.gasUsed); // console.log("Transaction Count in Blk: ", blk.transactions.length); return Promise.resolve(blk.transactions); }).catch((err)=>{ console.log("Error in getBlock()"); return Promise.reject(err); }) ); } self.last_blk_num = latest_blk_num; return Promise.all(poll_blk_promises); }).then((txns)=>{ //txns is an array of array of txn hashes // We first compile them to a single array let valid_txns = []; let invalid_txns = []; // In Quorum, all in-chain txns are valid. txns.forEach((txn_array)=>{ valid_txns = valid_txns.concat(txn_array); }); // console.log("all on-chain txn: ", valid_txns); callback(valid_txns, invalid_txns); }).catch((err)=>{ commUtils.log("Error in web3.getBlockNumber or getBlock", err); err_cb(err); }); }, blk_poll_interval); return Promise.resolve(); }).catch((err)=>{ console.log("Error in getting the start block number", err); err_cb(err); return Promise.reject(err); }) } unRegisterBlockProcessing() { // do nothing clearInterval(this.poll_interval); return Promise.resolve(); } /** * Deploy the chaincode specified in the network configuration file to all peers. * @return {Promise} The return promise. */ installSmartContract(contracts_config) { let bc = this; let contract_config = contracts_config[0]; let contract_name = contract_config.name; let contract_path = commUtils.resolvePath(contract_config.path); // Use the first node const nodeUrl = this.nodes_info[0].url; const web3 = new Web3(new Web3.providers.HttpProvider(nodeUrl)); // compute the abi, bytecode using solc. const input = fs.readFileSync(contract_path); const output = solc.compile(input.toString(), 1); // convert buffer to string and compile // console.log("Compiled Output: ", output); const bytecode = '0x' + output.contracts[':' + contract_name].bytecode; const abi = JSON.parse(output.contracts[':' + contract_name].interface); // console.log("Generated ABI: ", abi_str); return web3.eth.getAccounts() .then((accounts)=>{ let from_acc = accounts[0]; let contractInstance = new web3.eth.Contract(abi); return new Promise((resolve, reject) => { contractInstance.deploy({ data: bytecode }).send({ from: from_acc, gas: 15000000, privateFor: bc.private? bc.privateFor:undefined }).once('receipt', function(receipt){ let addr = receipt.contractAddress.toString(); console.log("Receive contract addr in txn receipt ", addr); return resolve([addr, abi]); }); }); }); } /** * Return the Quorum context associated with the given callback module name. * @param {string} name The name of the callback module as defined in the configuration files. * @param {object} args Unused. * @return {object} The assembled Quorum context. */ getContext(name, args, clientIdx) { // return Promise.resolve(); let self = this; return new Promise((resolve, reject)=>{ let web3s = []; let my_web3; // endpoint to issue txn self.nodes_info.forEach((node_info, idx)=> { let node_url = node_info.url; const web3 = new Web3(new Web3.providers.HttpProvider(node_url)); if (clientIdx % this.nodes_info.length === idx) { // console.log("Issued URL: ", node_url); my_web3 = web3; } web3s.push(web3); }); resolve({web3s: web3s, my_web3: my_web3}); }); } sendTxn(contractInstance, funcName, args, from_acc) { let self = this; let txStatus = new TxStatus(); return new Promise((resolve, reject) => { // console.log("Issued txn with function ", funcName, " and args ", args) contractInstance.methods[funcName]( ...args ).send({ from: from_acc, gas: 5000000, privateFor: self.private? self.privateFor:undefined /////////////////////////////////////////////////////////////// // Check blocks for txn status }).once('transactionHash', (hash) => { txStatus.SetID(hash); resolve(txStatus); /////////////////////////////////////////////////////////////// // Check txn receipt for status // }).once('receipt', (receipt) => { // txStatus.SetID(receipt.transactionHash); // txStatus.SetStatusSuccess(); // txStatus.SetVerification(true); // resolve(txStatus); /////////////////////////////////////////////////////////////// }); }); } /** * Release the given Quorum context. * @param {object} context The Quorum context to release. * @return {Promise} The return promise. */ releaseContext(context) { return Promise.resolve(); } /** * Invoke the given chaincode according to the specified options. Multiple transactions will be generated according to the length of args. * @param {object} context The Quorum context returned by {getContext}. * @param {string} contractID The name of the chaincode. * @param {string} contractVer The version of the chaincode. * @param {Array} args Array of JSON formatted arguments for transaction(s). Each element containts arguments (including the function name) passing to the chaincode. JSON attribute named transaction_type is used by default to specify the function name. If the attribute does not exist, the first attribute will be used as the function name. * @param {number} timeout The timeout to set for the execution in seconds. * @return {Promise<object>} The promise for the result of the execution. */ invokeSmartContract(context, contractID, contractVer, args, timeout) { const web3 = context.my_web3; // let node_url = this.nodes_info[context.clientIdx % this.nodes_info.length].url; // const web3 = new Web3(new Web3.providers.HttpProvider(node_url)); let address = contractID[0]; let abi = contractID[1]; // let contractInstance = web3.eth.contract(abi).at(address); let contractInstance = new web3.eth.Contract(abi, address); let self = this; return web3.eth.getAccounts() .then((accounts)=>{ let acc_id = Math.floor(context.clientIdx / context.web3s.length) % accounts.length; // console.log("Selected Account and Idx: ", accounts[acc_id], acc_id) let promises = []; let from_acc = accounts[acc_id]; args.forEach((item, index)=>{ // let bef = Date.now(); try { let simpleArgs = []; let func; for(let key in item) { if(key === 'transaction_type') { func = item[key].toString(); } else { simpleArgs.push(item[key]); } } promises.push(self.sendTxn(contractInstance, func, simpleArgs, from_acc)); } catch(err) { let badResult = new TxStatus('artifact'); badResult.SetStatusFail(); badResult.SetVerification(true); promises.push(Promise.resolve(badResult)); } }); return Promise.all(promises); }); } /** * Query the given chaincode according to the specified options. * @param {object} context The Quorum context returned by {getContext}. * @param {string} contractID The name of the chaincode. * @param {string} contractVer The version of the chaincode. * @param {string} key The argument to pass to the chaincode query. * @return {Promise<object>} The promise for the result of the execution. */ queryState(context, contractID, contractVer, key) { let address = contractID[0]; let abi = contractID[1]; let promises = []; let self = this; let func = "query"; // Assume each quorum contract has a function named as 'get' let txStatus = new TxStatus("00000000000"); let all_idx = []; let num_web3s = context.web3s.length; for (var i = 0;i < num_web3s; i++) {all_idx.push(i); } // let selected_idx = commUtils.shuffle(all_idx).slice(0, num_web3s / 2 + 1); let selected_idx = commUtils.shuffle(all_idx).slice(0, 1); context.web3s.forEach((web3, idx)=>{ if (selected_idx.includes(idx)) { let query_promise = web3.eth.getAccounts().then((accounts)=>{ let from_acc = accounts[0]; let contractInstance = new web3.eth.Contract(abi, address); return contractInstance.methods[func](key).call({from: from_acc}); }); // return self.callMethod(contractInstance, func, [key], from_acc, endpoint); }); promises.push(query_promise); } }); // console.log("Promise len: ", promises.length); // Resolve only all nodes reply return Promise.all(promises).then((results)=>{ txStatus.SetStatusSuccess(); txStatus.SetResult(results[0]); // console.log("Query Result: ", results[0]); txStatus.SetVerification(true); return Promise.resolve(txStatus); }).catch( (err) => { commUtils.log("Fail to query on key ", key); return Promise.reject(err); }); } }
JavaScript
class ObjectFactoryProvider { constructor(bridge){ this.created = []; this.bridge = bridge; } /** * newObject - Returns a new instance of an object of the specified type and * version. * For more information, see: * https://developer.gtnexus.com/platform/scripts/built-in-functions/creating-an-object * * @param {String} type The global object type you wish to create an instance * of. * @param {Number} version The API Version of the type. * @return {Object} */ newObject(type, version) { let newObj = {type: type}; this.created.push(newObj); return newObj; } getCreated() { return this.created.slice(); } getNextPoolNumber(poolName, sequenceDepth) { let nextPoolNumber = {}; //TODO - API changes required to support RESTful scenario if (this.bridge.isRest()) { throw new Error(`Unsupported Operation: Restful getNextPoolNumber is not yet implemented. Please use Local`); } //TODO - End if (sequenceDepth) { nextPoolNumber = this.bridge.newFetchRequest('NumberingPool', this.bridge.apiVersion, poolName + '/' + sequenceDepth); } else { nextPoolNumber = this.bridge.newFetchRequest('NumberingPool', this.bridge.apiVersion, poolName); } return nextPoolNumber.execute(); } reset() { this.created = []; } }
JavaScript
class Module extends Base { /** * A log of various guild events and dyno.commands * @param {Object} config The dyno configuration object * @param {Dyno} dyno The Dyno instance */ constructor() { super(); if (new.target === Module) throw new TypeError('Cannot construct Module instances directly.'); this.name = this.constructor.name; this._boundListeners = new Map(); } /** * Validate class requirements */ ensureInterface() { // required properties if (typeof this.module === 'undefined') { throw new Error(`${this.constructor.name} command must define module property.`); } if (typeof this.enabled === 'undefined') { throw new Error(`${this.constructor.name} command must define enabled property.`); } } /** * Register event listener * @param {String} event Event name * @param {Function} listener Event listener */ registerListener(event, listener) { const boundListener = listener.bind(this); this._boundListeners.set(event, boundListener); this.dyno.dispatcher.registerListener(event, boundListener, this); } _isEnabled(guild, module, guildConfig) { if (!guild || !guildConfig) return false; const modules = guildConfig ? guildConfig.modules : null; if (!modules) return false; const name = typeof module === 'string' ? module : module.module || module.name; // check if globally disabled const globalConfig = this.dyno.globalConfig; if (globalConfig && globalConfig.modules.hasOwnProperty(name) && globalConfig.modules[name] === false) return false; // check if module is disabled if (modules.hasOwnProperty(name) && modules[name] === false) { return false; } if (this.config.test) { if (this.config.testGuilds.includes(guild.id) || guildConfig.test) return true; return false; } // premium checks if (!this.config.isPremium && guildConfig.isPremium && guildConfig.premiumInstalled) { return false; } if (this.config.isPremium && (!guildConfig.isPremium || !guildConfig.premiumInstalled)) { return false; } if (!this._config.isPremium && guildConfig.clientID && guildConfig.clientID !== this._config.client.id) { return false; } if (this.config.shared) { return true; } if (guildConfig.beta) { if (!this.config.test && !this.config.beta) { return false; } } else if (this.config.beta) { return false; } return true; } /** * Check if a module is enabled for a server, not async for performance * @param {Object} guild Server object * @param {Module|String} module Module or module name * @returns {Promise.<Boolean>} */ isEnabled(guild, module, guildConfig) { if (!guild || !this.dyno.isReady) { return guildConfig ? false : Promise.resolve(false); } if (this.config.handleRegion && !this.utils.regionEnabled(guild, this.config)) { return guildConfig ? false : Promise.resolve(false); } return guildConfig ? this._isEnabled(guild, module, guildConfig) : new Promise((resolve) => { this.dyno.guilds.getOrFetch(guild.id).then(guildConfig => resolve(this._isEnabled(guild, module, guildConfig))) .catch(() => resolve(false)); }); } schedule(interval, task) { this.jobs = this.jobs || []; this.jobs.push(schedule.scheduleJob(interval, task)); } /** * Start the module */ _start(client, ...args) { this._client = client; if (this.start) { this.start(client, ...args); } } _unload(...args) { logger.info(`Unloading module: ${this.name}`); if (this._boundListeners && this._boundListeners.size > 0) { for (let [event, listener] of this._boundListeners.entries()) { this.dyno.dispatcher.unregisterListener(event, listener); } } if (this.jobs) { for (const job of this.jobs) { job.cancel(); } } try { if (this.unload) this.unload(...args); } catch (err) { logger.error(err); } } }
JavaScript
class Tooltip { constructor(el, opts) { this.el = el; this.tooltipContent = this.el.getAttribute("title"); if ( !this.tooltipContent ) { console.warn(`“${this.el.textContent.trim()}” tooltip has no “title” content`); return false; } // Use Object.assign() to merge “opts” object with default values in this.options this.options = Object.assign( {}, { classes: "", // string, accepts multiple space-separated classes gutter: 0,// gutter space around main content well prepend: "",// HTML to prepend to tooltip append: ""// HTML to append to tooltip }, opts ); // Build tooltip, add attributes this.setup(); // Event listeners this.events(); // Determine tooltip position on load this.updatePosition(); } setup() { this.isOpen = false; // Generate unique ID for each tooltip // https://gist.github.com/gordonbrander/2230317 this.uniqueID = Math.random().toString(36).substr(2, 4); this.parentEl = this.el.parentNode; // this.mediaQueryList = window.matchMedia(`(min-width: ${this.options.breakpoint})`); // Add ARIA attributes this.el.setAttribute("aria-describedby", "tooltip-" + this.uniqueID); this.el.setAttribute("aria-expanded", "false"); this.el.setAttribute("role", "button"); this.el.classList.add("js-init"); // Build tooltip this.tooltipEl = document.createElement('span'); this.tooltipEl.setAttribute("aria-hidden", "true"); this.tooltipEl.setAttribute("data-tooltip-menu","");// for styling purposes this.tooltipEl.setAttribute("id", `tooltip-${this.uniqueID}`); this.tooltipEl.setAttribute("role", "tooltip"); if (this.options.classes) { this.tooltipEl.setAttribute("class", this.options.classes); } this.tooltipEl.innerHTML = this.options.prepend + this.tooltipContent + this.options.append; // We could could also do this, but I thinks it’s a little harder to read: // https://davidwalsh.name/convert-html-stings-dom-nodes // this.tooltipEl = new DOMParser().parseFromString(` // <span id="tooltip-${this.uniqueID}" class="${this.options.classes}" aria-hidden="true" aria-expanded="false" role="alert" // ${this.tooltipContent} // </span> // `, 'text/html').body.firstChild; this.el.appendChild(this.tooltipEl); } events() { let self = this; // Toggle on click this.el.addEventListener("click", function(evt) { // Prevent default on clicks inside of tooltip menu if (self.tooltipEl.isSameNode(evt.target)) { evt.preventDefault(); } else { self.toggle(evt); } }); // Close tooltip if click off of it window.addEventListener("click", function(evt) { if (self.isOpen && !self.el.contains(evt.target)) { self.hideTooltip(); } }); // Update tooltip position once web fonts have loaded document.documentElement.addEventListener("fonts-loaded", function() { self.updatePosition(); }); // Hide on resize, recalc position window.addEventListener( "resize", debounce(function(event) { if ( self.isOpen ) { self.hideTooltip(); } self.updatePosition(); }, 150) ); } updatePosition() { // Reset alignment classes/attributes, centers tooltip over toggle this.el.classList.remove("is-fullwidth"); this.tooltipEl.setAttribute("data-align", ""); // if ( !this.mediaQueryList.matches ) { // return false; // } let bodyWidth = window.innerWidth - (this.options.gutter * 2); let bodyRightCutoff = window.innerWidth - this.options.gutter; let toggleBoundingRect = this.el.getBoundingClientRect(); let toggleRightOffset = toggleBoundingRect.right; let tooltipBoundingRect = this.tooltipEl.getBoundingClientRect(); let tooltipLeftOffset = tooltipBoundingRect.left; let tooltipRightOffset = tooltipBoundingRect.right; let tooltipWidth = tooltipBoundingRect.width; let cutoffRight = tooltipRightOffset > bodyRightCutoff; let cutoffLeft = tooltipLeftOffset < this.options.gutter; // If tooltip fits, do nothing to keep it centered if (!cutoffLeft && !cutoffRight) { return false; } // If right side is cutoff… if (tooltipRightOffset > bodyRightCutoff) { // …check if left side would fit before right aligning if (tooltipWidth <= toggleRightOffset - this.options.gutter) { this.tooltipEl.setAttribute("data-align", "right"); return false; } } // If left side is cutoff… if (tooltipLeftOffset < this.options.gutter) { // …check if right side would fit before left aligning if (bodyWidth - tooltipLeftOffset <= tooltipWidth) { this.tooltipEl.setAttribute("data-align", "left"); return false; } } // Tooltip can’t be aligned to toggle so make it full width this.el.classList.add("is-fullwidth"); this.tooltipEl.setAttribute("data-align", "full"); } showTooltip(evt) { this.isOpen = true; this.el.setAttribute("aria-expanded", "true"); this.tooltipEl.setAttribute("aria-hidden", "false"); } hideTooltip(evt) { this.isOpen = false; this.el.setAttribute("aria-expanded", "false"); this.tooltipEl.setAttribute("aria-hidden", "true"); } // Toggle expandable toggle(evt) { evt.preventDefault(); if (this.isOpen) { this.hideTooltip(); } else { this.showTooltip(); } } }
JavaScript
class MosaicDefinitionTransactionDTO { static getAttributeTypeMap() { return MosaicDefinitionTransactionDTO.attributeTypeMap; } }
JavaScript
class NotImplementedError extends CustomError { /** * Create a NotFoundError instance. * @param {String} [message] Assigns a message to this instance */ constructor (message = DEFAULT_MESSAGE) { super(message); } }
JavaScript
class Z80Reg { constructor() { this.word = 0 } get high() { return this.word >> 8 } get low() { return this.word & 255 } set high(val) { this.word = ((val & 255) << 8) | (this.word & 255) } set low(val) { this.word = (this.word & 0xff00) | (val & 255) } }
JavaScript
class ValueCollection extends Collection { // trackedValues = new Map(); /** * WeakMap to store recorded object references and their `TrackedValue`. */ trackedValues = new WeakMap(); constructor() { super('values'); } _log(...args) { this.logger.log(...args); } registerValueMaybe(hasValue, value, valueHolder, valuesDisabled) { if (valuesDisabled) { valueHolder.valueId = this._addValueDisabled().valueId; // valueHolder.value = undefined; } else if (!hasValue) { valueHolder.valueId = 0; // valueHolder.value = undefined; } else { this.registerValue(value, valueHolder); } } // NOTE: (for now) `valueHolder` is always trace registerValue(value, valueHolder) { const category = determineValueTypeCategory(value); if (category === ValueTypeCategory.Primitive) { valueHolder.valueId = 0; valueHolder.value = value; } else { const valueRef = this._serialize(value, 1, null, category); Verbose && this._log(`value #${valueRef.valueId} for trace #${valueHolder.traceId}: ${ValueTypeCategory.nameFrom(category)} (${valueRef.serialized})`); valueHolder.valueId = valueRef.valueId; valueHolder.value = undefined; } } /** * Keep track of all refs of a value. */ _trackValue(value, valueRef) { let tracked = this.trackedValues.get(value); if (!tracked) { // if (value === undefined) { // this.logger.warn(new Error(`Tried to track value but is undefined`).stack); // } try { this.trackedValues.set(value, tracked = new TrackedValue(value)); } catch (err) { let typeInfo = typeof value; if (isObject(value)) { typeInfo += `(${Object.getPrototypeOf(value)})`; } logError(`could not store value ("${err.message}"): ${typeInfo} ${JSON.stringify(value)}`); } } tracked.addRef(valueRef); return tracked; } _addOmitted() { if (!this._omitted) { this._omitted = this._registerValue(null, null); this._finishValue(this._omitted, null, '(...)', ValuePruneState.Omitted); } return this._omitted; } _addValueDisabled() { if (!this._valueDisabled) { this._valueDisabled = this._registerValue(null, null); this._finishValue(this._valueDisabled, null, '(...)', ValuePruneState.ValueDisabled); } return this._valueDisabled; } _registerValue(value, category) { // create new ref + track object value const valueRef = pools.values.allocate(); const valueId = this._all.length; valueRef.valueId = valueId; valueRef.category = category; if (isTrackableCategory(category)) { const tracked = this._trackValue(value, valueRef, category); valueRef.trackId = tracked.trackId; } // register by id this.push(valueRef); // mark for sending this._send(valueRef); return valueRef; } _finishValue(valueRef, typeName, serialized, pruneState = false) { // store all other props valueRef.typeName = typeName; valueRef.serialized = serialized; valueRef.pruneState = pruneState; return valueRef; } // ########################################################################### // bubblewrap when accessing object properties // ########################################################################### _readErrorCount = 0; _readErrorsByType = new Map(); _getKeysErrorsByType = new Map(); /** * Heuristic to determine whether this (probably) is safe to access, * based on past error observations. */ _canAccess(obj) { // TODO: `Object.getPrototypeOf` can trigger a proxy trap; need to check on that as well. // check if objects of this type have already been floodgated return !this._readErrorsByType.has(Object.getPrototypeOf(obj)); } _canReadKeys(obj) { if (obj.constructor?.prototype === obj) { // NOTE: we cannot read properties of many built-in prototype objects // e.g. `NodeList.prototype` return false; } // TODO: `getPrototypeOf` can trigger a proxy trap return !this._getKeysErrorsByType.has(Object.getPrototypeOf(obj)); } /** * Read a property of an object to copy + track it. * WARNING: This might invoke a getter function, thereby tempering with semantics (something that we genreally never want to do). */ _readProperty(obj, key) { try { this._startAccess(obj); return obj[key]; } catch (err) { this._onAccessError(obj, this._readErrorsByType); const msg = `ERROR: accessing ${Object.getPrototypeOf(obj)}.${key} caused exception`; VerboseErrors && this.logger.debug(msg, err.message); return `(${msg})`; } finally { this._endAccess(obj); } } /** * */ _getProperties(obj) { try { this._startAccess(obj); // NOTE: `for in` gets a lot of enumerable properties that `Object.keys` does not get const keys = []; for (const key in obj) { // if (!isFunction(obj[key])) { keys.push(key); // } } return keys; // // `Object.keys` can also invoke user - defined functions. // // @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/handler/ownKeys*} obj // return Object.keys(obj); } catch (err) { VerboseErrors && this.logger.debug(`accessing object ${Object.getPrototypeOf(obj)} caused exception:`, err.message); this._onAccessError(obj, this._getKeysErrorsByType); return null; } finally { this._endAccess(obj); } } _startAccess(/* obj */) { // eslint-disable-next-line no-undef if (__dbux__._r.disabled) { this.logger.error(`Tried to start accessing object while already accessing another object - ${new Error().stack}`); return; } // NOTE: disable tracing while reading the property // eslint-disable-next-line no-undef __dbux__._r.incDisabled(); } _endAccess() { // eslint-disable-next-line no-undef __dbux__._r.decDisabled(); } _onAccessError(obj, errorsByType) { // TODO: consider adding a timeout for floodgates? ++this._readErrorCount; errorsByType.set(Object.getPrototypeOf(obj), obj); if ((this._readErrorCount % 100) === 0) { // eslint-disable-next-line max-len,no-console console.warn(`[Dbux] When Dbux records object data it blatantly invokes object getters. These object getters caused ${this._readErrorCount} exceptions. If this number is very high, you will likely observe significant slow-down.`); } } // ########################################################################### // serialize // ########################################################################### /** * @param {Map} visited */ _serialize(value, depth = 1, visited = null, category = null) { if (depth > SerializationConfig.maxDepth) { return this._addOmitted(); } category = category || determineValueTypeCategory(value); // let serialized = serialize(category, value, serializationConfig); let serialized; let pruneState = ValuePruneState.Normal; let typeName = ''; // infinite loop prevention if (isObjectCategory(category)) { if (!visited) { visited = new Map(); } else { const existingValueRef = visited.get(value); if (existingValueRef) { return existingValueRef; } } } // register const valueRef = this._registerValue(value, category); // add to visited, if necessary visited && visited.set(value, valueRef); // process by category switch (category) { case ValueTypeCategory.String: if (value.length > SerializationConfig.maxStringLength) { serialized = value.substring(0, SerializationConfig.maxStringLength); pruneState = ValuePruneState.Shortened; } else { serialized = value; } break; case ValueTypeCategory.Function: // TODO: look up staticContext information by function instead // TODO: functions can have custom properties too serialized = 'ƒ ' + value.name; break; case ValueTypeCategory.Array: { let n = value.length; if (n > SerializationConfig.maxObjectSize) { pruneState = ValuePruneState.Shortened; n = SerializationConfig.maxObjectSize; } // build array serialized = []; for (let i = 0; i < n; ++i) { const childValue = value[i]; const childRef = this._serialize(childValue, depth + 1, visited); Verbose && this._log(`${' '.repeat(depth)}#${childRef.valueId} A[${i}] ${ValueTypeCategory.nameFrom(determineValueTypeCategory(childValue))} (${childRef.serialized})`); serialized.push(childRef.valueId); } break; } case ValueTypeCategory.Object: { if (!this._canReadKeys(value)) { pruneState = ValuePruneState.Omitted; } else { // iterate over all object properties let props = this._getProperties(value); if (!props) { // error serialized = `(ERROR: accessing object caused exception)`; category = ValueTypeCategory.String; pruneState = ValuePruneState.Omitted; } else { // NOTE: the name might be mangled. We ideally want to get it from source code when we can. // (NOTE: not all types are instrumented by dbux) typeName = value.constructor?.name || ''; // prune let n = props.length; if (n > SerializationConfig.maxObjectSize) { pruneState = ValuePruneState.Shortened; n = SerializationConfig.maxObjectSize; } // start serializing serialized = []; // TODO: won't work for polyfills :( // TODO: consider thenables const builtInSerializer = value.constructor ? builtInTypeSerializers.get(value.constructor) : null; if (builtInSerializer) { // serialize built-in types - especially: RegExp, Map, Set const entries = builtInSerializer(value); for (const [prop, childValue] of entries) { const childRef = this._serialize(childValue, depth + 1, visited); Verbose && this._log(`${' '.repeat(depth)}#${childRef.valueId} O[${prop}] ` + `${ValueTypeCategory.nameFrom(determineValueTypeCategory(childValue))} (${childRef.serialized})`); serialized.push([prop, childRef.valueId]); } } else { // serialize object (default) for (let i = 0; i < n; ++i) { const prop = props[i]; let childRef; if (!this._canAccess(value)) { childRef = this._addOmitted(); } else { const childValue = this._readProperty(value, prop); childRef = this._serialize(childValue, depth + 1, visited); Verbose && this._log(`${' '.repeat(depth)}#${childRef.valueId} O[${prop}] ` + `${ValueTypeCategory.nameFrom(determineValueTypeCategory(childValue))} (${childRef.serialized})`); } serialized.push([prop, childRef.valueId]); } } } } break; } default: serialized = value; break; } // finish value this._finishValue(valueRef, typeName, serialized, pruneState); return valueRef; } }
JavaScript
class State extends PIXI.Container{ constructor(renderer, stateName) { super(); this.renderer = renderer; this.stateName = stateName; if(this.stateName === undefined) { this.stateName = "State"; } this.isActive = false; this.nextState = undefined; this.update = function(delta) { if(this.debug) { console.log(`Updating ${this.stateName} state. [${delta}]`); } } this.setActive = function(value) { this.isActive = value; } this.setNextState = function(value) { this.nextState = value; } // Calculate the center position. this.center = { x: this.renderer.width * 0.5, y: this.renderer.height * 0.5 } this.debug = true; } makeActive(){ this.setActive(true); } makeInactive() { this.setActive(false); } toggleActiveState() { this.setActive(!this.isActive); } isState(value) { return (this.nextState === value) } switchToMainMenu() { this.setNextState(States.main); } switchToGameOver() { this.setNextState(States.scores); } switchToControls() { this.setNextState(States.controls); } switchToGame() { this.setNextState(States.game); } }
JavaScript
class UsePlanForm extends React.Component { static propTypes = { team: PropTypes.object.isRequired, resourceType: PropTypes.oneOf(['cluster', 'service', 'servicecredential']).isRequired, kind: PropTypes.string.isRequired, plan: PropTypes.string.isRequired, planValues: PropTypes.object, onPlanChange: PropTypes.func, validationErrors: PropTypes.array, mode: PropTypes.oneOf(['create', 'edit', 'view']).isRequired, } static initialState = { dataLoading: true, schema: null, parameterEditable: {}, planValues: {}, } constructor(props) { super(props) // Use passed-in plan values if we have them. const planValues = this.props.planValues ? this.props.planValues : UsePlanForm.initialState.planValues this.state = { ...UsePlanForm.initialState, planValues } } componentDidMountComplete = null componentDidMount() { this.componentDidMountComplete = this.fetchComponentData() } componentDidUpdateComplete = null componentDidUpdate(prevProps) { if (this.props.plan !== prevProps.plan || this.props.team !== prevProps.team) { this.setState({ ...UsePlanForm.initialState }) this.componentDidUpdateComplete = this.fetchComponentData() } if (this.props.planValues !== prevProps.planValues) { this.setState({ planValues: this.props.planValues }) } } async fetchComponentData() { let planDetails, schema, parameterEditable, planValues switch (this.props.resourceType) { case 'cluster': planDetails = await (await KoreApi.client()).GetTeamPlanDetails(this.props.team.metadata.name, this.props.plan); [schema, parameterEditable, planValues] = [planDetails.schema, planDetails.parameterEditable, planDetails.plan.configuration] break case 'service': planDetails = await (await KoreApi.client()).GetTeamServicePlanDetails(this.props.team.metadata.name, this.props.plan); [schema, parameterEditable, planValues] = [planDetails.schema, planDetails.parameterEditable, planDetails.servicePlan.configuration] break case 'servicecredential': schema = await (await KoreApi.client()).GetServiceCredentialSchema(this.props.team.metadata.name, this.props.plan) parameterEditable = { '*': true } planValues = {} break } if (schema && typeof schema === 'string') { schema = JSON.parse(schema) } this.setState({ ...this.state, schema: schema || { properties:[] }, parameterEditable: parameterEditable || {}, // Overwrite plan values only if it's still set to the default value planValues: this.state.planValues === UsePlanForm.initialState.planValues ? copy(planValues || {}) : this.state.planValues, dataLoading: false }) } onValueChange(name, value) { this.setState((state) => { // Texture this back into a state update using the nifty lodash set function: let newPlanValues = set({ ...state.planValues }, name, value) this.props.onPlanChange && this.props.onPlanChange(newPlanValues) return { planValues: set({ ...state.planValues }, name, value) } }) } render() { if (this.state.dataLoading) { return ( <Icon type="loading" /> ) } return ( <> <PlanViewEdit resourceType={this.props.resourceType} mode={this.props.mode} manage={false} team={this.props.team} kind={this.props.kind} plan={this.state.planValues} schema={this.state.schema} parameterEditable={this.state.parameterEditable} onPlanValueChange={(n, v) => this.onValueChange(n, v)} validationErrors={this.props.validationErrors} /> </> ) } }
JavaScript
class Tts extends Command { /** Create the command */ constructor() { super('tts', 'Will say given message out loud.', ' <message>'); } /** * @param {Discord.Message} message The sent command * @param {string[]} args The arguments in the command * @param {Discord.Client} bot The instance of the discord client * @param {sqlite.Database} db The instance of the database */ execute(message, args, bot, db) { if (args.length == 0) { message.channel.sendType(Tsubaki.Style.warn( 'Please tell me what to say!' ) ); } else { message.channel.sendType(args.join(' '), {tts: true} ); } } }
JavaScript
class Parent extends Component { render() { return ( <PageWrapper> <Header /> <Main /> </PageWrapper> ); } }
JavaScript
class ChatMember { /** * * @param {User} user * @param {string} status */ constructor(user, status) { this._user = user this._status = status } /** * Information about the user * @returns {User} */ get user() { return this._user } /** * The member's status in the chat. Can be “creator”, “administrator”, “member”, “left” or “kicked” * @returns {string} */ get status() { return this._status } /** * * @param {Object} raw * @returns {ChatMember} */ static deserialize(raw) { return new ChatMember(raw['user'] ? User.deserialize(raw['user']) : null, raw['status']) } /** * * @returns {Object} */ serialize() { return { user: this.user ? this.user.serialize() : undefined, status: this.status ? this.status : undefined } } /** * * @returns {string} */ toJSON() { return this.serialize() } }
JavaScript
class Dao { constructor(mysqlClient) { this.client = mysqlClient; } }
JavaScript
class Factory { /** * Create sensor model * * @param {string} modelId Model Id * * @return {AbstractSensorModel} Sensor model */ static createSensorModel(modelId) { let SensorModel = null; try { SensorModel = require(`./${modelId}`); } catch (e) { SensorModel = require(`./Unknown`); } return new SensorModel; } }
JavaScript
class CurrencyRateController extends BaseControllerV2_1.BaseController { /** * Creates a CurrencyRateController instance. * * @param options - Constructor options. * @param options.includeUsdRate - Keep track of the USD rate in addition to the current currency rate. * @param options.interval - The polling interval, in milliseconds. * @param options.messenger - A reference to the messaging system. * @param options.state - Initial state to set on this controller. * @param options.fetchExchangeRate - Fetches the exchange rate from an external API. This option is primarily meant for use in unit tests. */ constructor({ includeUsdRate = false, interval = 180000, messenger, state, fetchExchangeRate = crypto_compare_1.fetchExchangeRate, }) { super({ name, metadata, messenger, state: Object.assign(Object.assign({}, defaultState), state), }); this.mutex = new async_mutex_1.Mutex(); this.includeUsdRate = includeUsdRate; this.intervalDelay = interval; this.fetchExchangeRate = fetchExchangeRate; } /** * Start polling for the currency rate. */ start() { return __awaiter(this, void 0, void 0, function* () { yield this.startPolling(); }); } /** * Stop polling for the currency rate. */ stop() { this.stopPolling(); } /** * Prepare to discard this controller. * * This stops any active polling. */ destroy() { super.destroy(); this.stopPolling(); } /** * Sets a currency to track. * * @param currentCurrency - ISO 4217 currency code. */ setCurrentCurrency(currentCurrency) { return __awaiter(this, void 0, void 0, function* () { this.update((state) => { state.pendingCurrentCurrency = currentCurrency; }); yield this.updateExchangeRate(); }); } /** * Sets a new native currency. * * @param symbol - Symbol for the base asset. */ setNativeCurrency(symbol) { return __awaiter(this, void 0, void 0, function* () { this.update((state) => { state.pendingNativeCurrency = symbol; }); yield this.updateExchangeRate(); }); } stopPolling() { if (this.intervalId) { clearInterval(this.intervalId); } } /** * Starts a new polling interval. */ startPolling() { return __awaiter(this, void 0, void 0, function* () { this.stopPolling(); // TODO: Expose polling currency rate update errors yield util_1.safelyExecute(() => this.updateExchangeRate()); this.intervalId = setInterval(() => __awaiter(this, void 0, void 0, function* () { yield util_1.safelyExecute(() => this.updateExchangeRate()); }), this.intervalDelay); }); } /** * Updates exchange rate for the current currency. * * @returns The controller state. */ updateExchangeRate() { return __awaiter(this, void 0, void 0, function* () { const releaseLock = yield this.mutex.acquire(); const { currentCurrency: stateCurrentCurrency, nativeCurrency: stateNativeCurrency, pendingCurrentCurrency, pendingNativeCurrency, } = this.state; const conversionDate = Date.now() / 1000; let conversionRate = null; let usdConversionRate = null; const currentCurrency = pendingCurrentCurrency !== null && pendingCurrentCurrency !== void 0 ? pendingCurrentCurrency : stateCurrentCurrency; const nativeCurrency = pendingNativeCurrency !== null && pendingNativeCurrency !== void 0 ? pendingNativeCurrency : stateNativeCurrency; try { if (currentCurrency && nativeCurrency && // if either currency is an empty string we can skip the comparison // because it will result in an error from the api and ultimately // a null conversionRate either way. currentCurrency !== '' && nativeCurrency !== '') { ({ conversionRate, usdConversionRate } = yield this.fetchExchangeRate(currentCurrency, nativeCurrency, this.includeUsdRate)); } } catch (error) { if (!error.message.includes('market does not exist for this coin pair')) { throw error; } } finally { try { this.update(() => { return { conversionDate, conversionRate, // we currently allow and handle an empty string as a valid nativeCurrency // in cases where a user has not entered a native ticker symbol for a custom network // currentCurrency is not from user input but this protects us from unexpected changes. nativeCurrency, currentCurrency, pendingCurrentCurrency: null, pendingNativeCurrency: null, usdConversionRate, }; }); } finally { releaseLock(); } } return this.state; }); } }
JavaScript
class Genre { constructor(data) { this.data = data } /** * The unique ID of this tag. * @type {number} * @readonly */ get id() { return parseInt(this.data.tid) } /** * The unique ID of the content this tag is connected with. * @type {number} * @readonly */ get contentId() { return parseInt(this.data.id) } /** * The timestamp in this format: * * `YYYY-MM-DD HH:MM:SS` * @type {string} * @readonly */ get timestamp() { return this.data.timestamp } /** * The name of this tag. * @type {string} * @readonly */ get name() { return this.data.tag } /** * A small description about this tag. * @type {string} * @readonly */ get description() { return this.data.description } }
JavaScript
class EditCellHandler { /** * <do> */ execute(context) { let { cell } = context; return cell; } /** * <undo> */ revert(context) { const { cell } = context; return cell; } }
JavaScript
class MongoStore extends Store { /** * Creates an instance of MongoStore. * * @param {any} driver * @param {any} options * * @memberOf MongoStore */ constructor (driver, options = {}) { options.mongo = {} super(driver, options) } /** * * * @param {any} req * @param {any} cb * * @memberOf MongoStore */ create (req, cb) { if (req.data instanceof Array) { this._driver.insertMany(req.data, this.options.mongo, function (err, resp) { if (err) { return cb(err) } const result = { _ids: resp.insertedIds } cb(err, result) }) } else if (req.data instanceof Object) { this._driver.insertOne(req.data, this.options.mongo, function (err, resp) { if (err) { return cb(err) } const result = { _id: resp.insertedId.toString() } cb(err, result) }) } } /** * * * @param {any} req * @param {any} cb * * @memberOf MongoStore */ remove (req, cb) { this._driver.deleteMany(req.query, this.options.mongo, function (err, resp) { if (err) { return cb(err) } const result = { deletedCount: resp.deletedCount } cb(err, result) }) } /** * * * @param {any} req * @param {any} cb * * @memberOf MongoStore */ removeById (req, cb) { this._driver.findOneAndDelete({ _id: this.ObjectID(req.id) }, this.options.mongo, function (err, resp) { if (err) { return cb(err) } const result = resp.value cb(err, result) }) } /** * * * @param {any} req * @param {any} data * @param {any} cb * * @memberOf MongoStore */ update (req, data, cb) { this._driver.findOneAndUpdate(req.query, data, this.options.mongo, function (err, resp) { if (err) { return cb(err) } const result = resp.value cb(err, result) }) } /** * * * @param {any} req * @param {any} data * @param {any} cb * * @memberOf MongoStore */ updateById (req, data, cb) { this._driver.findOneAndUpdate({ _id: this.ObjectID(req.id) }, data, this.options.mongo, function (err, resp) { if (err) { return cb(err) } const result = resp.value cb(err, result) }) } /** * * * @param {any} req * @param {any} cb * * @memberOf MongoStore */ find (req, options, cb) { let cursor = this._driver.find(req.query) const total = cursor.count(); if (options) { if (options.limit) { cursor = cursor.limit(options.limit) } if (options.offset) { cursor = cursor.skip(options.offset) } if (options.fields) { cursor = cursor.project(options.fields) } if (options.orderBy) { cursor = cursor.sort(options.orderBy) } } cursor.toArray(function (err, resp) { if (err) { return cb(err) } const result = Object.assign({ result: resp, total: total }, options) cb(err, result) }) } /** * * * @param {any} req * @param {any} cb * * @memberOf MongoStore */ findById (req, cb) { this._driver.findOne({ _id: this.ObjectID(req.id) }, this.options.mongo, function (err, resp) { cb(err, resp) }) } /** * * * @param {any} req * @param {any} cb * * @memberOf MongoStore */ replace (req, data, cb) { this._driver.updateMany(req.query, data, Object.assign(this.options.mongo, { upsert: true }), function (err, resp) { if (err) { return cb(err) } const result = { matchedCount: resp.matchedCount, modifiedCount: resp.modifiedCount, upsertedCount: resp.upsertedCount, upsertedId: resp.upsertedId } cb(err, result) }) } /** * * * @param {any} req * @param {any} cb * * @memberOf MongoStore */ replaceById (req, data, cb) { this._driver.findOneAndReplace({ _id: this.ObjectID(req.id) }, data, function (err, resp) { if (err) { return cb(err) } const result = resp.value cb(err, result) }) } }
JavaScript
class CalcDateDiff extends Action { constructor() { super(); /** * Node name. Default to `CalcDateDiff`. * * @property name * @type String * @readonly **/ this.title = this.name = 'CalcDateDiff'; /** * Node parameters * @property parameters * @type {Object} * @property {ExpressionString} parameters.dateFrom string reresenting starting date * @property {ExpressionString} parameters.dateTo string reresenting end date *@property {MemoryField} parameters.fieldName number of seconds between dateTo and dateFrom */ this.parameters = _.extend(this.parameters, { 'dateTo': '', 'dateFrom': '', 'fieldName': '' }); } /** * Tick method. * * @private * @param {Tick} tick A tick instance. * @return {any} Always return `b3.SUCCESS`. **/ tick(tick) { var data = this.alldata(tick); var dateTo = _.template(utils.wrapExpression(this.properties.dateTo))(data); let dateToDate = new Date(dateTo); if (dateToDate.toString() == "Invalid Date") { dblogger.error('dateTo has an invalid date format:' + dateTo); } var dateFrom = _.template(utils.wrapExpression(this.properties.dateFrom))(data); let dateFromDate = new Date(dateFrom); if (dateFromDate.toString() == "Invalid Date") { dblogger.error('dateFrom has an invalid date format:' + dateFrom); } let diff = dateToDate - dateFromDate; diff = diff / 1000; this.alldata(tick, this.properties.fieldName, diff.toString()); return b3.SUCCESS(); } /** * defines validation methods to execute at the editor; if one of them fails, a dashed red border is displayed for the node * @return {Array<Validator>} */ validators(node) { function validCompositeField(field) { var bool1 = field && (field.indexOf('message.') === 0 || field.indexOf('context.') === 0 || field.indexOf('global.') === 0 || field.indexOf('volatile.') === 0 || field.indexOf('fsm.') === 0); var bool2 = field && (field.indexOf('\'') === 0 || field.indexOf('"') === 0 || !isNaN(field)); return bool1 || bool2; } return [{ condition: validCompositeField(node.properties.fieldName), text: "fieldName is not a memory field. it should start with \", ', context., global., fsm., volatile. or be a literal number" }, { condition: validCompositeField(node.properties.dateTo), text: "dateTo is not a memory field. it should start with \", ', context., global., fsm., volatile. or be a literal number" }, { condition: validCompositeField(node.properties.dateFrom), text: "dateFrom is not a memory field. it should start with \", ', context., global., fsm., volatile. or be a literal number" }]; } }
JavaScript
class Image extends BaseWidget { /** *@param {ST.Widgets.BaseWidget} parent Widgets parent *@param {Object} [options = Object] See {@link ST.Widgets.BaseWidget} *@param {PIXI.Texture} [options.texture = null] The texture for the Image */ constructor(parent, options = {}) { super(parent, options); // default options const defaults = { texture: null, }; // fill in missing options with defaults options = Object.assign(defaults, options); // Images could be interactive but most will not this.interactive = false; /** * Holds the sprite internally * @member {PIXI.Sprite} * @private */ this._sprite = new PIXI.Sprite(); if(options.texture) { this._sprite.texture = options.texture; } this.addChild(this._sprite); this._sprite.width = this.width; this._sprite.height = this.height; this.sizeProxy = this._sprite; } /** * The PIXI.Sprite used internally * @member {PIXI.Sprite} */ get sprite() { return this._sprite; } set sprite(val) { // eslint-disable-line require-jsdoc if(val instanceof PIXI.Sprite) { this._sprite = val; } } /** *The sprites texture *@member {PIXI.Texture} */ get texture() { return this._sprite.texture; } set texture(val) { // eslint-disable-line require-jsdoc if(val instanceof PIXI.Texture) { this._sprite.texture = val; } } }
JavaScript
class ScreenProjector { /** * Constructs a new `ScreenProjector`. * * @param m_camera - Camera to project against. */ constructor(m_camera) { this.m_camera = m_camera; this.m_width = 0; this.m_height = 0; } /** * Height of the screen. */ get width() { return this.m_width; } /** * Width of the screen. */ get height() { return this.m_height; } /** * Apply current projectionViewMatrix of the camera to project the source vector into * screen coordinates. * * @param {(Vector3Like)} source The source vector to project. * @param {THREE.Vector2} target The target vector. * @returns {THREE.Vector2} The projected vector (the parameter 'target') */ project(source, target = new THREE.Vector2()) { const p = this.projectVector(source, ScreenProjector.tempV3); return this.ndcToScreen(p, target); } /** * Apply current projectionViewMatrix of the camera to project the source vector into * screen coordinates. * * @param {(Vector3Like)} source The source vector to project. * @param {THREE.Vector2} target The target vector. * @returns {THREE.Vector2} The projected vector (the parameter 'target') or undefined if * outside of the near/far plane. The point may be outside the screen. */ projectToScreen(source, target = new THREE.Vector2()) { const p = this.projectVector(source, ScreenProjector.tempV3); if (isInRange(p)) { return this.ndcToScreen(p, target); } return undefined; } /** * Apply current projectionViewMatrix of the camera to project the source vector into * screen coordinates. The z component between -1 and 1 is also returned. * * @param {(Vector3Like)} source The source vector to project. * @param {THREE.Vector3} target The target vector. * @returns {THREE.Vector3} The projected vector (the parameter 'target') or undefined if * outside the near / far plane. */ project3(source, target = new THREE.Vector3()) { const p = this.projectVector(source, ScreenProjector.tempV3); if (p.z > -1 && p.z < 1) { target.set((p.x * this.m_width) / 2, (p.y * this.m_height) / 2, p.z); return target; } return undefined; } /** * Apply current projectionViewMatrix of the camera to project the source vector. Stores * result in NDC in the target vector. * * @param {(Vector3Like)} source The source vector to project. * @param {THREE.Vector3} target The target vector. * @returns {THREE.Vector3} The projected vector (the parameter 'target'). */ projectVector(source, target) { target.set(source.x, source.y, source.z).project(this.m_camera); return target; } /** * Fast test to check if projected point is on screen. * * @returns {boolean} `true` if point is on screen, `false` otherwise. */ onScreen(source) { const p = this.projectVector(source, ScreenProjector.tempV3); return isOnScreen(p); } /** * Update the `ScreenProjector` with the latest values of the screen and the camera. * * @param {THREE.Camera} camera Camera to project against. * @param {number} width Width of screen/canvas. * @param {number} height Height of screen/canvas. */ update(camera, width, height) { this.m_camera = camera; this.m_width = width; this.m_height = height; } ndcToScreen(ndc, screenCoords) { return screenCoords.set((ndc.x * this.m_width) / 2, (ndc.y * this.m_height) / 2); } }
JavaScript
class DistMatrix { /** * Construct a new DistMatrix. * * @param config.coords Coords array. * @param config.distFunc Distance function. */ constructor(config) { const { coords, distFunc } = config; this.n = coords.length; const dists = new Array(this.n * (this.n - 1) / 2); let k = 0; for (let j = 1; j < this.n; ++j) { for (let i = 0; i < j; ++i) { dists[k++] = distFunc(coords[i], coords[j]); } } this.dists = dists; } /** * Return the distance between coord at index i and the coord at index j. i * must be less than or equal to j. * * @param i Index of first coord. * @param j Index of second coord. */ dist(i, j) { if (i === j) { return 0; } return this.dists[i + j * (j - 1) / 2]; } }
JavaScript
class SocketIO { constructor(){ this.socket; this.ip; this.port; } connect(ip, port){ this.ip = ip; this.port = port; this.socket = io.connect(`http://${this.ip}:${this.port}`); this.socket.on('connect' ,() => { gml_Script_gmcallback_sio_on_connect(); }); this.socket.on('disconnect' ,() => { gml_Script_gmcallback_sio_on_disconnect(); }); } disconnect(){ this.socket.close(); } reconnect(){ this.socket.open(); } addEvent(name){ this.socket.on(name, (data) => { window[`gml_Script_gmcallback_sio_on_${name.toLowerCase()}`](-1, -1, data); }); } send(name, data){ this.socket.emit(name.toLowerCase(), data); } getConnectionStatus(){ return this.socket.connected; } }
JavaScript
class SearchViewModel { constructor() { this.title = "Search"; this.searchTerm = ""; this.searchResults = []; this.config = {}; } }
JavaScript
class JRPCClient extends EventEmitter { /** * Initialize a new client instance. * * The transport must: * <ul> * <li>inherit from {@link https://nodejs.org/api/events.html#events_class_eventemitter|EventEmitter}.</li> * <li>have a boolean <b>needsConnection</b> property.</li> * <li>have a <b>send</b> method taking a string parameter and returning a promise.</li> * <li>emit a <b>data</b> event when receiving data. Its first parameter must be the data as an object.</li> * </ul> * * Additionally, if `needsConnection` is true, it must: * <ul> * <li>have a boolean <b>isConnected</b> property.</li> * <li>have a <b>connect</b> method returning a promise.</li> * <li>have a <b>disconnect</b> method returning a promise.</li> * </ul> * * @param {Object} options - Client options. * @param {Object} options.transport - Transport instance to use for communication. * @param {Boolean} [options.autoConnect=true] - Whether to connect the transport automatically when sending data. * @param {Boolean} [options.batchRequests=true] - Turning this off will disable batching. The batching API will still be available but will send requests individually. * @param {Number} [options.timeout=60000] - Time to wait for a server response before returning an error. Minimum `1000`. * * @throws {TypeError} Invalid parameter. * * @emits JRPCClient#connected * @emits JRPCClient#disconnected * @emits JRPCClient#error * * @example * let client = new JRPCClient({ * transport: transport // Your transport instance * }); */ constructor({ transport, autoConnect = true, batchRequests = true, timeout = 60000 }) { super(); checkTransport(transport); check.assert.boolean(autoConnect, 'invalid "autoConnect" option'); check.assert.boolean(batchRequests, 'invalid "batchRequests" option'); check.assert.greaterOrEqual(timeout, 1000, 'invalid "timeout" option'); let transportHandlers = { 'data': onTransportData.bind(this), 'connected': onTransportConnected.bind(this), 'disconnected': onTransportDisconnected.bind(this), 'error': onTransportError.bind(this) }; for (let event in transportHandlers) { transport.on(event, transportHandlers[event]); } let remote = new JRPC({ remoteTimeout: Math.floor(timeout / 1000) }); _data.set(this, { transport, transportHandlers, remote, autoConnect, batchRequests }); } /** * Whether the transport needs to be connected before sending/receiving data. * * @type {Boolean} * @readonly */ get needsConnection() { let { transport } = _data.get(this); return transport.needsConnection; } /** * Whether the transport is currently connected. * * @type {Boolean} * @readonly */ get isConnected() { let { transport } = _data.get(this); return (!transport.needsConnection || transport.isConnected); } /** * Connect the transport. * * @promise {Promise} Resolves once connected. * @reject {Error} Connection error. */ async connect() { let { transport } = _data.get(this); if (transport.needsConnection && !transport.isConnected) { return await transport.connect(); } } /** * Disconnect the transport. * * @promise {Promise} Resolves once disconnected. */ async disconnect() { let { transport } = _data.get(this); if (transport.needsConnection && transport.isConnected) { return await transport.disconnect(); } } /** * Set a handler function for a server notification. It will be invoked with the notification parameters as its first argument. * * The current handler will be replaced by the one specified. * * @param {String} name - Name of the notification. * @param {Function} [handler=null] - New handler for the notification. Invoked with (params). Use `null` to remove the current handler. * * @example * client.notification('notification', (params) => { * console.log(`received notification with ${params}`); * }); */ notification(name, handler) { let { remote } = _data.get(this); if (typeof handler === 'function') { remote.expose(name, (params, next) => { handler.call(null, params); next(true); }); } else if (remote.exposed && remote.exposed.hasOwnProperty(name)) { delete remote.exposed[name]; } } /** * Call a remote method. * * @param {String} method - RPC method to call. * @param {*} params - RPC parameters. * @param {Object} [options={}] - Call options. * @param {Boolean} [options.rejectOnError=true] - Whether to reject when the server responds with an RPC error. * * @promise {Promise} Resolves after the call. * @resolve {*} When `rejectOnError` is `true`, the RPC result. * @resolve {Object https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object} When `rejectOnError` is `false`, {@link JRPCClient~RPCResponse|`RPCResponse`} object. * @reject {Object https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object} When `rejectOnError` is `true`, {@link JRPCClient~RPCError|`RPCError`} object. * @reject {Error https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error} Transport error. * @reject {TypeError https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError} Invalid parameter. * * @connection-required * * @example * let result = await client.call('method', [ 'params' ]); */ call(method, params, { rejectOnError = true } = {}) { return new Promise((resolve, reject) => { if (!check.nonEmptyString(method)) { return reject(new TypeError('missing/invalid "method" parameter')); } let { transport, remote, autoConnect } = _data.get(this); let makeCall = () => { remote.call(method, (params || []), (err, result) => { if (rejectOnError) { if (err) { return reject(err); } return resolve(result); } resolve({ error: (err || null), result: (result || null) }); }); remote.transmit((data, next) => { next(); transport.send(data).catch(reject); }); }; if (!this.isConnected) { if (!autoConnect) { return reject(new Error('Transport not connected')); } return this.connect().then(makeCall).catch(reject); } makeCall(); }); } /** * Prepare a call for {@link JRPCClient#batch|`batch`}. * * @param {String} method - RPC method to call. * @param {*} params - RPC parameters. * * @promise {LazyPromise} Resolves after the call. * @resolve {Object https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object} {@link JRPCClient~RPCResponse|`RPCResponse`} object. * @reject {Error https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error} Transport error. * @reject {TypeError https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError} Invalid parameter. */ prepare(method, params) { return new LazyPromise((resolve, reject) => { if (!check.nonEmptyString(method)) { return reject(new TypeError('missing/invalid "method" parameter')); } let { transport, remote, batchRequests } = _data.get(this); remote.call(method, (params || []), (err, result) => { resolve({ error: (err || null), result: (result || null) }); }); if (!batchRequests) { remote.transmit((data, next) => { next(); transport.send(data).catch(reject); }); } }); } /** * Send a batch of remote calls. * * Calls must be prepared with {@link JRPCClient#prepare|`prepare`}. * * @param {LazyPromise[]|Object} requests - List of calls to make. Can be an array or an object of prepared calls. * * @promise {Promise} Resolves after all the calls. * @resolve {Object[] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object} When `requests` is an array, array of {@link JRPCClient~RPCResponse|`RPCResponse`} objects in the same order. * @resolve {Object https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object} When `requests` is an object, object with the same keys mapped to {@link JRPCClient~RPCResponse|`RPCResponse`} objects. * @reject {Error https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error} Transport error. * @reject {TypeError https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError} Invalid parameter. * * @connection-required * * @example * let requests = [ * client.prepare('method1', [ 'params' ]), * client.prepare('method2', [ 'params' ]) * ]; * * let responses = await client.batch(requests); */ batch(requests) { return new Promise((resolve, reject) => { let array; if (check.array(requests)) { if (check.emptyArray(requests)) { return resolve([]); } if (!check.array.of.instanceStrict(requests, LazyPromise)) { return reject(new TypeError('missing/invalid "requests" parameter')); } array = true; } else if (check.object(requests)) { if (check.emptyObject(requests)) { return resolve({}); } if (!check.object.of.instanceStrict(requests, LazyPromise)) { return reject(new TypeError('missing/invalid "requests" parameter')); } array = false; } else { return reject(new TypeError('missing/invalid "requests" parameter')); } let { transport, remote, autoConnect, batchRequests } = _data.get(this); let makeCalls = () => { if (array) { Promise.all(requests).then(resolve).catch(reject); } else { pProps(requests).then(resolve).catch(reject); } if (batchRequests) { setImmediate(remote.transmit.bind(remote, (data, next) => { next(); transport.send(data).catch(reject); })); } }; if (!this.isConnected) { if (!autoConnect) { return reject(new Error('Transport not connected')); } return this.connect().then(makeCalls).catch(reject); } makeCalls(); }); } /** * Destroy the client instance. Use this if you do not need this instance anymore. * * It will disconnect the transport and try to free up resources. * * @promise {Promise} Resolves once the instance has been destroyed. */ async destroy() { this.removeAllListeners(); let { transport, transportHandlers, remote } = _data.get(this); for (let event in transportHandlers) { transport.removeListener(event, transportHandlers[event]); } remote.shutdown(); await this.disconnect(); _data.delete(this); } }
JavaScript
class UserWidget { constructor(name, age, salary) { this.name = name this.age = age this.salary = salary } render() { return '<div>Name: ' + this.name + ', Age: ' + this.age + ', Salary: ' + this.salary + '</div>' } }
JavaScript
class StudentWidget { constructor() { } render() { } }
JavaScript
class Resident { constructor() { this.name = 'Jim Tenant' this.pets = ['Fluffy', 'Rex'] } listPets() { let str = '' this.pets.forEach((pet) => { str += 'Tenant name: ' + this.name + ' Pet name: ' + pet + '\n' }) return str } }
JavaScript
class Resident { constructor() { this.firstName = 'Charlie' this.lastName = 'Brown' } fullName() { return this.firstName + ' ' + this.lastName } }
JavaScript
class StorageDAO { constructor () { this.createdOn = new Date() this.cellsTemplates = DefaultCellsTemplatesConfig this.users = {} this.gamesByUserId = {} } removeUserGameById (userId, gameId) { logger.debug(`Removing game: ${gameId} of userId ${userId}`) delete this.gamesByUserId[userId][gameId] } removeUserGamesById (userId) { logger.debug(`Removing ALL games for userId ${userId}`) this.gamesByUserId[userId] = {} } saveUser (user) { logger.debug(`Checking user: ${JSON.stringify(user)}`) if (this.getUserByName(user.name)) { throw new AppException( 'error.user.save.alreadyExists.title', 'error.user.save.alreadyExists.body' ) } else { user.id = cuid() } logger.debug(`Saving user: ${JSON.stringify(user)}`) this.users[user.id] = user this.gamesByUserId[user.id] = {} return user } getUserByName (name) { for (let userId in this.users) { if (this.users[userId].name === name) { return this.users[userId] } } return null } getUserById (userId) { return this.users[userId] } saveGame (game) { logger.debug(`Checking game: ${JSON.stringify(game)}`) game.id = game.id || cuid() if (this.getGameWithName(game.name, game.ownerId)) { throw new AppException( 'error.game.save.alreadyExists.title', 'error.game.save.alreadyExists.body' ) } logger.debug(`Saving game: ${JSON.stringify(game)}`) this.gamesByUserId[game.ownerId][game.id] = game return game } getGameWithName (name, userId) { let usersGames = this.gamesByUserId[userId] for (let gameId in usersGames) { if (usersGames[gameId].name === name) { return usersGames[gameId] } } return null } getGameById (gameId) { logger.debug(`Retrieving game with id: ${gameId}`) for (let userId in this.gamesByUserId) { let gameFound = this.gamesByUserId[userId][gameId] if (gameFound) { return gameFound } } return null } getGameForUserId (gameId, userId) { logger.debug(`Retrieving game with id: ${gameId} for owner: ${userId}`) return this.gamesByUserId[userId][gameId] } getGamesForUserId (userId) { let result = [] let usersGames = this.gamesByUserId[userId] for (let gameId in usersGames) { result.push(usersGames[gameId]) } return result } getGamesContainingUserId (userId) { let result = [] this.forEachGame(game => { if (game.containsUserId(userId)) { result.push(game) } }) return result } forEachGame (eachFunction) { let gamesUsersId = Object.keys(this.gamesByUserId) for (let userId in gamesUsersId) { let gamesForUser = this.gamesByUserId[gamesUsersId[userId]] for (let gameId in gamesForUser) { eachFunction.call(eachFunction, gamesForUser[gameId]) } } } forEachGameOfUser (userId, eachFunction) { let gamesForUser = this.gamesByUserId[userId] for (let gameId in gamesForUser) { eachFunction.call(eachFunction, gamesForUser[gameId]) } } getCellsTemplates () { return this.cellsTemplates.slice(0) } }
JavaScript
class SnapshotTimeManager { constructor() { this.times = {}; } /** * Updates / Adds the date of the latest snapshot of a particular blob. * * @param {String} id of the blob * @param {Date} date * * @memberof SnapshotTimeManager */ _update(id, date) { this.times[id] = date; } /** * Returns a timestamp (UTC String) that is at least one second greater than the * last snapshot time of a particular blob. * * @param {String} id of the blob * @param {Date} now reference time for the snapshot to be taken * * @memberof SnapshotTimeManager */ getDate(id, now) { const date = this.times[id]; if (date === undefined || now.getTime() - date.getTime() > 1000) { this._update(id, now); return now; } const updatedDate = new Date(date); updatedDate.setSeconds(date.getSeconds() + 1); this._update(id, updatedDate); return updatedDate; } }
JavaScript
class SDKError extends Error { /** * SDKError constructor. * * @param {object|null} err * @param {string|null} msg */ constructor(err, msg) { let internal = msg || ''; if (err) { internal += err.message ? internal === '' ? err.message : ': ' + err.message : err; } super(internal); this.message = internal; this.name = 'SDKError'; if (err) { this.err = err; } } /** * @return {object|null} */ get internalError() { return this.err; } }
JavaScript
class LoginError extends SDKError { /** * @param {object|null} err * @param {string|null} msg */ constructor(err, msg) { super(err, msg || 'Error during login'); this.name = 'LoginError'; } }
JavaScript
class RefreshTokenError extends SDKError { /** * @param {object|null} err * @param {string|null} msg */ constructor(err, msg) { super(err, msg || 'Error during refresh token'); this.name = 'RefreshTokenError'; } }
JavaScript
class RequestTokenError extends SDKError { /** * @param {object|null} err * @param {string|null} msg */ constructor(err, msg) { super(err, msg || 'Error during request token'); this.name = 'RequestTokenError'; } }
JavaScript
class GraphQLError extends SDKError { /** * @param {object|null} err * @param {string|null} msg */ constructor(err, msg) { super(err, msg || 'Error in GraphQL link'); this.name = 'GraphQLError'; } }
JavaScript
class PowBlockHeader extends value_chain_1.ValueBlockHeader { constructor() { super(); this.m_bits = 0; this.m_nonce = 0; this.m_nonce1 = 0; // this.m_bits = POWUtil.getTarget(prevheader); } get bits() { return this.m_bits; } set bits(bits) { this.m_bits = bits; } get nonce() { return this.m_nonce; } set nonce(_nonce) { assert(_nonce <= consensus.INT32_MAX); this.m_nonce = _nonce; } get nonce1() { return this.m_nonce1; } set nonce1(nonce) { assert(nonce <= consensus.INT32_MAX); this.m_nonce1 = nonce; } _encodeHashContent(writer) { let err = super._encodeHashContent(writer); if (err) { return err; } try { writer.writeU32(this.m_bits); } catch (e) { return error_code_1.ErrorCode.RESULT_INVALID_FORMAT; } return error_code_1.ErrorCode.RESULT_OK; } encode(writer) { let err = super.encode(writer); if (err) { return err; } try { writer.writeU32(this.m_nonce); writer.writeU32(this.m_nonce1); } catch (e) { return error_code_1.ErrorCode.RESULT_INVALID_FORMAT; } return error_code_1.ErrorCode.RESULT_OK; } _decodeHashContent(reader) { let err = super._decodeHashContent(reader); if (err !== error_code_1.ErrorCode.RESULT_OK) { return err; } try { this.m_bits = reader.readU32(); } catch (e) { return error_code_1.ErrorCode.RESULT_INVALID_FORMAT; } return error_code_1.ErrorCode.RESULT_OK; } decode(reader) { let err = super.decode(reader); if (err !== error_code_1.ErrorCode.RESULT_OK) { return err; } try { this.m_nonce = reader.readU32(); this.m_nonce1 = reader.readU32(); } catch (e) { return error_code_1.ErrorCode.RESULT_INVALID_FORMAT; } return error_code_1.ErrorCode.RESULT_OK; } async verify(chain) { let vr = await super.verify(chain); if (vr.err || !vr.valid) { return vr; } // check bits let { err, target } = await consensus.getTarget(this, chain); if (err) { return { err }; } if (this.m_bits !== target) { return { err: error_code_1.ErrorCode.RESULT_OK, valid: false }; } // check POW return { err: error_code_1.ErrorCode.RESULT_OK, valid: this.verifyPOW() }; } verifyPOW() { let writer = new writer_1.BufferWriter(); if (this.encode(writer)) { return false; } let content = writer.render(); return consensus.verifyPOW(digest.hash256(content), this.m_bits); } stringify() { let obj = super.stringify(); obj.difficulty = this.bits; return obj; } }
JavaScript
class InitAfterBindingsWorkaround { static $inject = ['$injector', '$attrs', '$element', '$scope', '$transclude'] constructor($injector, $attrs, $element, $scope, $transclude) { if (!this.initAfterBindings) { throw new Error('When using inheritance you must move the logic in the constructor to the `initAfterBindings` method'); } this.$onInit = () => { $injector.invoke(this.initAfterBindings, this, { $attrs, $element, $scope, $transclude }); }; } }
JavaScript
class Coupons { /** * @param {string} code */ constructor (code) { this.code = code } /** * @return {{coupon: {couponCode: string}}} */ toJSON () { return { coupon: { 'couponCode': this.code } } } }